code
stringlengths
2
1.05M
/* table reflow widget for TableSorter 2/7/2015 (v2.19.0) * Requires tablesorter v2.8+ and jQuery 1.7+ * Also, this widget requires the following default css (modify as desired) / * REQUIRED CSS: change your reflow breakpoint here (35em below) * / @media ( max-width: 35em ) { .ui-table-reflow td, .ui-table-reflow th { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; float: right; / * if not using the stickyHeaders widget (not the css3 version) * the "!important" flag, and "height: auto" can be removed * / width: 100% !important; height: auto !important; } / * reflow widget * / .ui-table-reflow tbody td[data-title]:before { color: #469; font-size: .9em; content: attr(data-title); float: left; width: 50%; white-space: pre-wrap; text-align: bottom; display: inline-block; } / * reflow2 widget * / table.ui-table-reflow .ui-table-cell-label.ui-table-cell-label-top { display: block; padding: .4em 0; margin: .4em 0; text-transform: uppercase; font-size: .9em; font-weight: 400; } table.ui-table-reflow .ui-table-cell-label { padding: .4em; min-width: 30%; display: inline-block; margin: -.4em 1em -.4em -.4em; } } .ui-table-reflow .ui-table-cell-label { display: none; } */ /*jshint browser:true, jquery:true, unused:false */ /*global jQuery: false */ ;(function($){ "use strict"; var ts = $.tablesorter, tablereflow = { // simple reflow // add data-attribute to each cell which shows when media query is active // this widget DOES NOT WORK on a table with multiple thead rows init : function(table, c, wo) { var $this, title = wo.reflow_dataAttrib, header = wo.reflow_headerAttrib, headers = []; c.$table .addClass(wo.reflow_className) .off('refresh.tsreflow updateComplete.tsreflow2') // emulate jQuery Mobile refresh // https://api.jquerymobile.com/table-reflow/#method-refresh .on('refresh.tsreflow updateComplete.tsreflow2', function(){ tablereflow.init(table, c, wo); }); c.$headers.each(function(){ $this = $(this); headers.push( $.trim( $this.attr(header) || $this.text() ) ); }); c.$tbodies.children().each(function(){ $(this).children().each(function(i){ $(this).attr(title, headers[i]); }); }); }, init2: function(table, c, wo) { var $this, $tbody, i, $hdr, txt, len, cols = c.columns, header = wo.reflow2_headerAttrib, headers = []; c.$table .addClass(wo.reflow2_className) .off('refresh.tsreflow2 updateComplete.tsreflow2') // emulate jQuery Mobile refresh // https://api.jquerymobile.com/table-reflow/#method-refresh .on('refresh.tsreflow2 updateComplete.tsreflow2', function(){ tablereflow.init2(table, c, wo); }); // add <b> to every table cell with thead cell contents for (i = 0; i < cols; i++) { $hdr = c.$headers.filter('[data-column="' + i + '"]'); if ($hdr.length > 1) { txt = []; /*jshint loopfunc:true */ $hdr.each(function(){ $this = $(this); if (!$this.hasClass(wo.reflow2_classIgnore)) { txt.push( $this.attr(header) || $this.text() ); } }); } else { txt = [ $hdr.attr(header) || $hdr.text() ]; } headers.push( txt ); } // include "remove-me" class so these additional elements are removed before updating txt = '<b class="' + c.selectorRemove.slice(1) + ' ' + wo.reflow2_labelClass; c.$tbodies.children().each(function(){ $tbody = ts.processTbody(table, $(this), true); $tbody.children().each(function(j){ $this = $(this); len = headers[j].length; i = len - 1; while (i >= 0) { $this.prepend(txt + (i === 0 && len > 1 ? ' ' + wo.reflow2_labelTop : '') + '">' + headers[j][i] + '</b>'); i--; } }); ts.processTbody(table, $tbody, false); }); }, remove : function(table, c, wo) { c.$table.removeClass(wo.reflow_className); }, remove2 : function(table, c, wo) { c.$table.removeClass(wo.reflow2_className); } }; ts.addWidget({ id: "reflow", options: { // class name added to make it responsive (class name within media query) reflow_className : 'ui-table-reflow', // header attribute containing modified header name reflow_headerAttrib : 'data-name', // data attribute added to each tbody cell reflow_dataAttrib : 'data-title' }, init: function(table, thisWidget, c, wo) { tablereflow.init(table, c, wo); }, remove: function(table, c, wo){ tablereflow.remove(table, c, wo); } }); ts.addWidget({ id: "reflow2", options: { // class name added to make it responsive (class name within media query) reflow2_className : 'ui-table-reflow', // ignore header cell content with this class name reflow2_classIgnore : 'ui-table-reflow-ignore', // header attribute containing modified header name reflow2_headerAttrib : 'data-name', // class name applied to thead labels reflow2_labelClass : 'ui-table-cell-label', // class name applied to first row thead label reflow2_labelTop : 'ui-table-cell-label-top' }, init: function(table, thisWidget, c, wo) { tablereflow.init2(table, c, wo); }, remove: function(table, c, wo){ tablereflow.remove2(table, c, wo); } }); })(jQuery);
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > If thisArg is null or undefined, the called function is passed the global object as the this value es5id: 15.3.4.4_A3_T9 description: Checking by using eval, argument at call function is void 0 ---*/ eval( " Function(\"this.feat=1\").call(void 0) " ); //CHECK#1 if (this["feat"] !== 1) { $ERROR('#1: If thisArg is null or undefined, the called function is passed the global object as the this value'); }
'use strict'; /** * This module contains a variety of generic promise wrapped `node.child_process.spawn` commands * @module childProcess */ const R = require('ramda'); const Q = require('q'); /** this is not a constant for unit testing purposes */ let spawn = require('child_process').spawn; const util = require('../util'); module.exports = { output, quiet, stream, inherit, stdin }; /** * @param {string} command * @param {string} args * @returns {string} */ function commandStr(command, args) { return `${command} ${args.join(' ')}`; } /** * @param {string} command * @param {string} args * @param {string|number} code * @returns {string} */ function successString(command, args, code) { return `${commandStr(command, args)} Process Exited: ${code}`; } /** * @param {string} command * @param {string} args * @param {string|number} code * @param {string=} stderr * @returns {string} */ function failString(command, args, code, stderr) { stderr = stderr || ''; return `${commandStr(command, args)} terminated with exit code: ${code} ` + stderr; } /** * @param {string} command * @param {string[]} args * @param {number} code * @param {string=} stderr * @returns {Error} */ function failError(command, args, code, stderr) { util.verbose('Failed: ', command, args, code, stderr); code = parseInt(code, 10); stderr = stderr || ''; const errString = failString(command, args, code, stderr); const e = new Error(errString); e.code = code; return e; } /** * Resolves stdout, rejects with stderr, also streams * @param {string} command * @param {Array.<string>=} args * @param {Object=} opts * @returns {Promise<string>} */ function output(command, args, opts) { args = args || []; const options = R.merge({}, opts); const d = Q.defer(); const child = spawn(command, args, options); let stdout = ''; let stderr = ''; child.stdout.setEncoding('utf8'); child.stderr.setEncoding('utf8'); child.stdout.on('data', (data) => { d.notify({ stdout: data }); stdout += data; }); child.stderr.on('data', (data) => { d.notify({ stderr: data }); stderr += data; }); child.on('close', (code) => { if (+code) { d.reject(failError(command, args, code, stderr)); } else { util.verbose(successString(command, args, code)); d.resolve(stdout.trim()); } }); child.stdin.end(); return d.promise; } /** * Does not resolve stdout, but streams, and resolves stderr * @param {string} command * @param {Array.<string>=} args * @param {Object=} opts * @returns {Promise} */ function quiet(command, args, opts) { args = args || []; const options = R.merge({}, opts); const d = Q.defer(); const child = spawn(command, args, options); let stderr = ''; child.stderr.setEncoding('utf8'); child.stdout.on('data', (data) => { d.notify({ stdout: data }); }); child.stderr.on('data', (data) => { d.notify({ stderr: data }); stderr += data; }); child.on('close', (code) => { if (+code) { d.reject(failError(command, args, code, stderr)); } else { util.verbose(successString(command, args, code)); d.resolve(); } }); child.stdin.end(); return d.promise; } /** * Only streams stdout/stderr, no output on resolve/reject * @param {string} command * @param {Array.<string>=} args * @param {Object=} opts * @returns {Promise} */ function stream(command, args, opts) { args = args || []; const options = R.merge({}, opts); const d = Q.defer(); const child = spawn(command, args, options); child.stdout.setEncoding('utf8'); child.stderr.setEncoding('utf8'); child.stdout.on('data', (data) => { d.notify({ data: data }); }); child.stderr.on('data', (data) => { d.notify({ error: data }); }); child.on('close', (code) => { if (+code) { d.reject(failError(command, args, code)); } else { util.verbose(successString(command, args, code)); d.resolve(); } }); child.stdin.end(); return d.promise; } /** * Stdio inherits, meaning that the given command takes over stdio * @param {string} command * @param {Array.<string>=} args * @param {Object=} opts * @returns {Promise} */ function inherit(command, args, opts) { args = args || []; const options = R.merge({ stdio: 'inherit' }, opts); const d = Q.defer(); const child = spawn(command, args, options); child.on('close', (code) => { if (+code) { d.reject(failError(command, args, code)); } else { util.verbose(successString(command, args, code)); d.resolve(); } }); return d.promise; } /** * like output, but puts stdin in as stdin * @param {string} stdin * @param {string} command * @param {Array.<string>=} args * @param {Object=} opts * @returns {Promise<string>} */ function stdin(stdin, command, args, opts) { stdin = stdin || ''; args = args || []; const options = R.merge({}, opts); const d = Q.defer(); const child = spawn(command, args, options); let stderr = ''; let stdout = ''; child.stdout.on('data', (data) => { d.notify({ stdout: data }); stdout += data; }); child.stderr.on('data', (data) => { d.notify({ stderr: data }); stderr += data; }); child.on('close', (code) => { if (+code) { d.reject(failError(command, args, code, stderr)); } else { d.resolve(stdout); } }); child.stdin.write(stdin); child.stdin.end(); return d.promise; }
"use strict"; const ICollectionBase = require("./ICollectionBase"); const IGuild = require("./IGuild"); const Utils = require("../core/Utils"); const rest = require("../networking/rest"); /** * @interface * @extends ICollectionBase */ class IGuildCollection extends ICollectionBase { constructor(discordie, valuesGetter, valueGetter) { super({ valuesGetter: valuesGetter, valueGetter: valueGetter, itemFactory: (id) => new IGuild(this._discordie, id) }); this._discordie = discordie; Utils.privatify(this); } /** * Makes a request to create a guild. * @param {String} name * @param {String} region * @param {Buffer|null} [icon] * @param {Array<IRole|Object>} [roles] * @param {Array<IChannel|Object>} [channels] * @param {Number} [verificationLevel] * See Discordie.VerificationLevel * @param {Number} [defaultMessageNotifications] * See Discordie.UserNotificationSettings * @returns {Promise<IGuild, Error>} */ create(name, region, icon, roles, channels, verificationLevel, defaultMessageNotifications) { if (icon instanceof Buffer) { icon = Utils.imageToDataURL(icon); } const toRaw = (data, param) => { data = data || []; if (!Array.isArray(data)) throw TypeError("Param '" + param + "' must be an array"); return data.map(v => { return typeof v.getRaw === "function" ? v.getRaw() : null; }).filter(v => v); }; roles = toRaw(roles, "roles"); channels = toRaw(channels, "channels"); return new Promise((rs, rj) => { rest(this._discordie).guilds.createGuild( name, region, icon, roles, channels, verificationLevel, defaultMessageNotifications ) .then(guild => rs(this._discordie.Guilds.get(guild.id))) .catch(rj); }); } /** * Makes a request to get a default list of voice regions. * Use IGuild.fetchRegions for getting guild-specific list. * @returns {Promise<Array<Object>, Error>} */ fetchRegions() { return rest(this._discordie).voice.getRegions(); } } module.exports = IGuildCollection;
const ButtonBackToTop = FocusComponents.common.button.backToTop.component; const ButtonBTSample = React.createClass({ /** * Render the component. * @return {object} React node */ render() { return ( <div className='button-bt-example'> <img src="http://lorempixel.com/800/600/sports/"/> <img src="http://lorempixel.com/800/600/abstract/"/> <img src="http://lorempixel.com/800/600/city/"/> <img src="http://lorempixel.com/800/600/technics/"/> <img src="http://lorempixel.com/800/600/sports/"/> <img src="http://lorempixel.com/800/600/abstract/"/> <img src="http://lorempixel.com/800/600/city/"/> <img src="http://lorempixel.com/800/600/technics/"/> <ButtonBackToTop /> </div> ); } }); return <ButtonBTSample/>;
'use strict'; module.exports = { authCheck: require('./authcheck'), injectScripts: require('./injectscripts'), debounceName: require('./debounce-name') };
/* Script: Language.it.js MooTools Filemanager - Language Strings in English Translation: Moreno Monga */ Filemanager.Language.it = { more: 'Dettagli', width: 'Larghezza:', height: 'Altezza:', ok: 'Ok', open: 'Seleziona file', upload: 'Upload', create: 'Crea cartella', createdir: 'Specifica il nome della cartella:', cancel: 'Annulla', error: 'Errore', information: 'Informazioni', type: 'Tipo:', size: 'Dimensione:', dir: 'Percorso:', modified: 'Ultima modifica:', preview: 'Anteprima', close: 'Chiudi', destroy: 'Cancella', destroyfile: 'Sei sicuro di voler cancellare questo file?', rename: 'Rinomina', renamefile: 'Scrivi un nuovo nome per il file:', rn_mv_cp: 'Rename/Move/Copy', download: 'Download', nopreview: '<i>Non sono disponibili anteprime</i>', title: 'Titolo:', artist: 'Artista:', album: 'Album:', length: 'Lunghezza:', bitrate: 'Bitrate:', deselect: 'Deseleziona', nodestroy: 'La cancellazioni dei file è disabilitata.', toggle_side_boxes: 'Thumbnail view', toggle_side_list: 'List view', show_dir_thumb_gallery: 'Show thumbnails of the files in the preview pane', drag_n_drop: 'Drag & drop has been enabled for this directory', drag_n_drop_disabled: 'Drag & drop has been temporarily disabled for this directory', goto_page: 'Go to page', 'backend.disabled': 'L Upload dei file è disabilitato.', 'backend.authorized': 'Non sei autorizzato a fare l upload dei file.', 'backend.path': 'La cartella degli upload non esiste. Contattare il webmaster.', 'backend.exists': 'La cartella specificata per gli upload esiste già. Contattare il webmaster.', 'backend.mime': 'Il tipo del file specificato non è consentito.', 'backend.extension': 'Il tipo di file che si vuole caricare non è consentito o è sconosciuto.', 'backend.size': 'La dimensione del file è troppo grande per essere processato. Ricarica un file con dimensioni ridotte.', 'backend.partial': 'Il file è stato parzialmente caricato. Per favore, prova a ricaricarlo.', 'backend.nofile': 'Non è stato specificato alcun file da caricare.', 'backend.default': 'Mi spiace, l operazione non è andata a buon fine.', 'backend.path_not_writable': 'You do not have write/upload permissions for this directory.', 'backend.filename_maybe_too_large': 'The filename/path is probably too long for the server filesystem. Please retry with a shorter file name.', 'backend.fmt_not_allowed': 'You are not allowed to upload this file format/name.', 'backend.read_error': 'Cannot read / download the specified file.', 'backend.unidentified_error': 'An unindentified error occurred while communicating with the backend (web server).', 'backend.nonewfile': 'A new name for the file to be moved / copied is missing.', 'backend.corrupt_img': 'This file is a not a image or a corrupt file: ', // path 'backend.resize_inerr': 'This file could not be resized due to an internal error.', 'backend.copy_failed': 'An error occurred while copying the file / directory: ', // oldlocalpath : newlocalpath 'backend.delete_cache_entries_failed': 'An error occurred when attempting to delete the item cache (thumbnails, metadata)', 'backend.mkdir_failed': 'An error occurred when attempting to create the directory: ', // path 'backend.move_failed': 'An error occurred while moving / renaming the file / directory: ', // oldlocalpath : newlocalpath 'backend.path_tampering': 'Path tampering detected.', 'backend.realpath_failed': 'Cannot translate the given file specification to a valid storage location: ', // $path 'backend.unlink_failed': 'An error occurred when attempting to delete the file / directory: ', // path // Image.class.php: 'backend.process_nofile': 'The image processing unit did not receive a valid file location to work on.', 'backend.imagecreatetruecolor_failed': 'The image processing unit failed: GD imagecreatetruecolor() failed.', 'backend.imagealphablending_failed': 'The image processing unit failed: cannot perform the required image alpha blending.', 'backend.imageallocalpha50pctgrey_failed': 'The image processing unit failed: cannot allocate space for the alpha channel and the 50% background.', 'backend.imagecolorallocatealpha_failed': 'The image processing unit failed: cannot allocate space for the alpha channel for this color image.', 'backend.imagerotate_failed': 'The image processing unit failed: GD imagerotate() failed.', 'backend.imagecopyresampled_failed': 'The image processing unit failed: GD imagecopyresampled() failed. Image resolution: ', /* x * y */ 'backend.imagecopy_failed': 'The image processing unit failed: GD imagecopy() failed.', 'backend.imageflip_failed': 'The image processing unit failed: cannot flip the image.', 'backend.imagejpeg_failed': 'The image processing unit failed: GD imagejpeg() failed.', 'backend.imagepng_failed': 'The image processing unit failed: GD imagepng() failed.', 'backend.imagegif_failed': 'The image processing unit failed: GD imagegif() failed.', 'backend.imagecreate_failed': 'The image processing unit failed: GD imagecreate() failed.', 'backend.cvt2truecolor_failed': 'conversion to True Color failed. Image resolution: ', /* x * y */ 'backend.no_imageinfo': 'Corrupt image or not an image file at all.', 'backend.img_will_not_fit': 'Server error: image does not fit in available RAM; minimum required (estimate): ', /* XXX MBytes */ 'backend.unsupported_imgfmt': 'unsupported image format: ', /* jpeg/png/gif/... */ /* FU */ uploader: { unknown: 'Errore sconosciuto', sizeLimitMin: 'Non puoi caricare "<em>${name}</em>" (${size}), la dimensione minima del file è <strong>${size_min}</strong>!', sizeLimitMax: 'Non puoi caricare "<em>${name}</em>" (${size}), la dimensione massima del file è <strong>${size_max}</strong>!', mod_security: 'No response was given from the uploader, this may mean that "mod_security" is active on the server and one of the rules in mod_security has cancelled this request. If you can not disable mod_security, you may need to use the NoFlash Uploader.' }, flash: { hidden: 'To enable the embedded uploader, unblock it in your browser and refresh (see Adblock).', disabled: 'To enable the embedded uploader, enable the blocked Flash movie and refresh (see Flashblock).', flash: 'In order to upload files you need to install <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash">Adobe Flash</a>.' }, resizeImages: 'Ridimensiona immagini grandi', serialize: 'Salva galleria', gallery: { text: 'Titolo immagine', save: 'Salva', remove: 'Rimuovi dalla galleria', drag: 'Sposta gli oggetti qui per creare una galleria...' } };
'use strict'; // Setting up route angular.module('usuarios-mobile').config(['$stateProvider', 'RouteHelpersProvider', function($stateProvider, helper) { // Articles state routing $stateProvider. state('app.listUsuariosMobile', { url: '/usuarios-mobile', title: 'Listar Usuários Mobile', templateUrl: 'modules/usuarios-mobile/views/list-usuarios-mobile.client.view.html', resolve: helper.resolveFor('datatables', 'xeditable') }); } ]);
var searchData= [ ['defaultgaussianmixture',['DefaultGaussianMixture',['../namespaceedda_1_1dist.html#a7ac563ae69a0db2921a59877f32c2846',1,'edda::dist']]], ['devicegmmarray',['DeviceGMMArray',['../namespaceedda.html#adf57cb048134c8ba9b3560698eb45a61',1,'edda']]], ['dword',['DWORD',['../bmp__image_8h.html#af483253b2143078cede883fc3c111ad2',1,'bmp_image.h']]] ];
const config = require('../../../server/config'), Manager = require('./manager'), manager = new Manager(); // Responsible for handling requests for sitemap files module.exports = function handler(siteApp) { const verifyResourceType = function verifyResourceType(req, res, next) { if (!Object.prototype.hasOwnProperty.call(manager, req.params.resource)) { return res.sendStatus(404); } next(); }; siteApp.get('/sitemap.xml', function sitemapXML(req, res) { res.set({ 'Cache-Control': 'public, max-age=' + config.get('caching:sitemap:maxAge'), 'Content-Type': 'text/xml' }); res.send(manager.getIndexXml()); }); siteApp.get('/sitemap-:resource.xml', verifyResourceType, function sitemapResourceXML(req, res) { var type = req.params.resource, page = 1; res.set({ 'Cache-Control': 'public, max-age=' + config.get('caching:sitemap:maxAge'), 'Content-Type': 'text/xml' }); res.send(manager.getSiteMapXml(type, page)); }); };
import Koa from 'koa'; import convert from 'koa-convert'; import webpack from 'webpack'; import webpackConfig from '../build/webpack.config'; import historyApiFallback from 'koa-connect-history-api-fallback'; import serve from 'koa-static'; import _debug from 'debug'; import config from '../config'; import webpackProxyMiddleware from './middleware/webpack-proxy'; import webpackDevMiddleware from './middleware/webpack-dev'; import webpackHMRMiddleware from './middleware/webpack-hmr'; const debug = _debug('app:server'); const paths = config.utils_paths; const app = new Koa(); // This rewrites all routes requests to the root /index.html file // (ignoring file requests). If you want to implement isomorphic // rendering, you'll want to remove this middleware. app.use(convert(historyApiFallback({ verbose: false }))); // ------------------------------------ // Apply Webpack HMR Middleware // ------------------------------------ if (config.env === 'development') { const compiler = webpack(webpackConfig); // Enable webpack-dev and webpack-hot middleware const { publicPath } = webpackConfig.output; if (config.proxy && config.proxy.enabled) { const options = config.proxy.options; app.use(convert(webpackProxyMiddleware(options))); } app.use(webpackDevMiddleware(compiler, publicPath)); app.use(webpackHMRMiddleware(compiler)); // Serve static assets from ~/src/static since Webpack is unaware of // these files. This middleware doesn't need to be enabled outside // of development since this directory will be copied into ~/dist // when the application is compiled. app.use(convert(serve(paths.client('static')))); } else { debug( 'Server is being run outside of live development mode. This starter kit ' + 'does not provide any production-ready server functionality. To learn ' + 'more about deployment strategies, check out the "deployment" section ' + 'in the README.' ); // Serving ~/dist by default. Ideally these files should be served by // the web server and not the app server, but this helps to demo the // server in production. app.use(convert(serve(paths.base(config.dir_dist)))); } export default app;
module.exports = require("core-js/library/fn/string/trim");
import { CRUD_GET_LIST_SUCCESS } from '../../../actions/dataActions'; export default resource => (previousState = 0, { type, payload, meta }) => { if (!meta || meta.resource !== resource) { return previousState; } if (type === CRUD_GET_LIST_SUCCESS) { return payload.total; } return previousState; };
'use strict'; var grunt = require('grunt'); /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ exports.deployments = { setUp: function(done) { // setup here if necessary done(); }, default_options: function(test) { test.expect(1); var actual = grunt.file.read('tmp/default_options'); var expected = grunt.file.read('test/expected/default_options'); test.equal(actual, expected, 'should describe what the default behavior is.'); test.done(); }, custom_options: function(test) { test.expect(1); var actual = grunt.file.read('tmp/custom_options'); var expected = grunt.file.read('test/expected/custom_options'); test.equal(actual, expected, 'should describe what the custom option(s) behavior is.'); test.done(); }, };
var MusicView = React.createClass({ getInitialState: function() { return {album: null} }, render: function() { if (this.state.album){ return ( <div className="musicView" > <h2 className="musicName"> {this.state.album.name} </h2> <h3 className="musicAuthor"> {this.state.album.author} </h3> <img src={this.state.album.thumbnail} width="60"></img> <br/> {this.state.album.summary} <br/> <b>Release date:</b> {this.state.album.rlsdate} <br/> <b>Genre:</b> {this.state.album.genre} <br/> <b>Score:</b> {this.state.album.score} <br/> <b>Link:</b> <a href={this.state.album.url}>{this.state.album.url}</a> <br/> </div> ) }else{ return ( <h2>Click an item to see details</h2> ) } } })
(function($) { $(document).ready(function() { $('.styleswitch').click(function() { switchStylestyle(this.getAttribute("rel")); return false; }); var c = readCookie('style'); if (c) switchStylestyle(c); }); function switchStylestyle(styleName) { $('link[rel*=style][title]').each(function(i) { this.disabled = true; if (this.getAttribute('title') == styleName) this.disabled = false; }); createCookie('style', styleName, 365); } })(jQuery); // Cookie functions function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function eraseCookie(name) { createCookie(name,"",-1); } // Switcher jQuery('.demo_changer .demo-icon').click(function(){ if(jQuery('.demo_changer').hasClass("active")){ jQuery('.demo_changer').animate({"left":"-140px"},function(){ jQuery('.demo_changer').toggleClass("active"); }); }else{ jQuery('.demo_changer').animate({"left":"0px"},function(){ jQuery('.demo_changer').toggleClass("active"); }); } });
const express = require('express') const app = express() const formidable = require('formidable') const path = require('path') const rimraf = require('rimraf') const fs = require('fs') const throttle = require('express-throttle-bandwidth') const port = process.env.PORT || 4444, folder = path.join(__dirname, 'files') if (!fs.existsSync(folder)) { fs.mkdirSync(folder) } else { rimraf.sync(path.join(folder, '*')) } process.on('exit', () => { rimraf.sync(path.join(folder)) }) app.set('port', port) app.use(throttle(1024 * 128)) app.use((_, res, next) => { res.header('Access-Control-Allow-Origin', '*') res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept') next() }) app.post('/upload', (req, res) => { rimraf.sync(path.join(folder, '*')) const form = new formidable.IncomingForm() form.uploadDir = folder form.parse(req, (_, fields, files) => { console.log('\n-----------') console.log('Fields', fields) console.log('Received:', Object.keys(files)) console.log() }) res.send('Thank you') }) app.listen(port, () => { console.log('\nUpload server running on http://localhost:' + port + '/upload') console.log('You can now upload from main dev server using QUploader') })
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > If the argument len is a Number and ToUint32(len) is equal to len, then the length property of the newly constructed object is set to ToUint32(len) es5id: 15.4.2.2_A2.1_T1 description: Array constructor is given one argument ---*/ //CHECK#1 var x = new Array(0); if (x.length !== 0) { $ERROR('#1: var x = new Array(0); x.length === 0. Actual: ' + (x.length)); } //CHECK#2 var x = new Array(1); if (x.length !== 1) { $ERROR('#2: var x = new Array(1); x.length === 1. Actual: ' + (x.length)); } //CHECK#3 var x = new Array(4294967295); if (x.length !== 4294967295) { $ERROR('#3: var x = new Array(4294967295); x.length === 4294967295. Actual: ' + (x.length)); }
/** * 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, { PropTypes } from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Content.css'; function Content({ path, title, content }) { return ( <div className={s.root}> <div className={s.container}> {title && path !== '/' && <h1>{title}</h1>} <div dangerouslySetInnerHTML={{ __html: content }} /> </div> </div> ); } Content.propTypes = { path: PropTypes.string.isRequired, content: PropTypes.string.isRequired, title: PropTypes.string, }; export default withStyles(s)(Content);
/* Template Name: Color Admin - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.5 Version: 1.9.0 Author: Sean Ngu Website: http://www.seantheme.com/color-admin-v1.9/admin/ */ var handleDataTableResponsive = function() { "use strict"; if ($('#data-table').length !== 0) { $('#data-table').DataTable({ responsive: true }); } }; var TableManageResponsive = function () { "use strict"; return { //main function init: function () { handleDataTableResponsive(); } }; }();
// @flow import { createPopper, popperGenerator, detectOverflow } from './createPopper'; export type * from './types'; // eslint-disable-next-line import/no-unused-modules export { createPopper, popperGenerator, detectOverflow };
/** The MIT License (MIT) Copyright (c) 2013-2015, Joe Bain 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(name, context, definition) { if (typeof module !== 'undefined' && module.exports) { module.exports = definition(); } else if (typeof define === 'function' && define.amd) { define(definition); } else { context[name] = definition(); } })('Args', this, function argsDefinition() { "use strict"; if (!Array.isArray) { Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === "[object Array]"; }; } var _extractSchemeEl = function(rawSchemeEl) { var schemeEl = {}; schemeEl.defValue = undefined; schemeEl.typeValue = undefined; schemeEl.customCheck = undefined; for (var name in rawSchemeEl) { if (!rawSchemeEl.hasOwnProperty(name)) continue; if (name === "_default") { schemeEl.defValue = rawSchemeEl[name]; } else if (name === "_type") { schemeEl.typeValue = rawSchemeEl[name]; } else if (name === "_check") { schemeEl.customCheck = rawSchemeEl[name]; } else { schemeEl.sname = name; } } schemeEl.sarg = rawSchemeEl[schemeEl.sname]; if(typeof schemeEl.customCheck === "object" && schemeEl.customCheck instanceof RegExp) { var schemeRegexp = schemeEl.customCheck; schemeEl.customCheck = function(arg) { return !!arg.toString().match(schemeRegexp); }; } return schemeEl; }; var _typeMatches = function(arg, schemeEl) { var ok = false; if ((schemeEl.sarg & Args.ANY) !== 0) { ok = true; } else if ((schemeEl.sarg & Args.STRING) !== 0 && typeof arg === "string") { ok = true; } else if ((schemeEl.sarg & Args.FUNCTION) !== 0 && typeof arg === "function") { ok = true; } else if ((schemeEl.sarg & Args.INT) !== 0 && (typeof arg === "number" && Math.floor(arg) === arg)) { ok = true; } else if ((schemeEl.sarg & Args.FLOAT) !== 0 && typeof arg === "number") { ok = true; } else if ((schemeEl.sarg & Args.ARRAY) !== 0 && (Array.isArray(arg))) { ok = true; } else if (((schemeEl.sarg & Args.OBJECT) !== 0 || schemeEl.typeValue !== undefined) && ( typeof arg === "object" && (schemeEl.typeValue === undefined || (arg instanceof schemeEl.typeValue)) )) { ok = true; } else if ((schemeEl.sarg & Args.ARRAY_BUFFER) !== 0 && arg.toString().match(/ArrayBuffer/)) { ok = true; } else if ((schemeEl.sarg & Args.DATE) !== 0 && arg instanceof Date) { ok = true; } else if ((schemeEl.sarg & Args.BOOL) !== 0 && typeof arg === "boolean") { ok = true; } else if ((schemeEl.sarg & Args.DOM_EL) !== 0 && ( (arg instanceof HTMLElement) || (window.$ !== undefined && arg instanceof window.$) ) ) { ok = true; } if (schemeEl.customCheck !== undefined && typeof schemeEl.customCheck === "function") { if (schemeEl.customCheck(arg)) { ok = true; } else { ok = false; } } return ok; }; var _isTypeSpecified = function(schemeEl) { return (schemeEl.sarg & (Args.ANY | Args.STRING | Args.FUNCTION | Args.INT | Args.FLOAT | Args.OBJECT | Args.ARRAY_BUFFER | Args.DATE | Args.BOOL | Args.DOM_EL | Args.ARRAY)) != 0 || schemeEl.typeValue !== undefined; }; var _getTypeString = function(schemeEl) { var sarg = schemeEl.sarg; var typeValue = schemeEl.typeValue; var customCheck = schemeEl.customCheck; if ((sarg & Args.STRING) !== 0 ) { return "String"; } if ((sarg & Args.FUNCTION) !== 0 ) { return "Function"; } if ((sarg & Args.INT) !== 0 ) { return "Int"; } if ((sarg & Args.FLOAT) !== 0 ) { return "Float"; } if ((sarg & Args.ARRAY) !== 0 ) { return "Array"; } if ((sarg & Args.OBJECT) !== 0) { if (typeValue !== undefined) { return "Object (" + typeValue.toString() + ")"; } else { return "Object"; } } if ((sarg & Args.ARRAY_BUFFER) !== 0 ) { return "Arry Buffer"; } if ((sarg & Args.DATE) !== 0 ) { return "Date"; } if ((sarg & Args.BOOL) !== 0 ) { return "Bool"; } if ((sarg & Args.DOM_EL) !== 0 ) { return "DOM Element"; } if (customCheck !== undefined) { return "[Custom checker]"; } return "unknown"; }; var _checkNamedArgs = function(namedArgs, scheme, returns) { var foundOne = false; for (var s = 0 ; s < scheme.length ; s++) { var found = (function(schemeEl) { var argFound = false; for (var name in namedArgs) { var namedArg = namedArgs[name]; if (name === schemeEl.sname) { if (_typeMatches(namedArg, schemeEl)) { returns[name] = namedArg; argFound = true; break; } } } return argFound; })(_extractSchemeEl(scheme[s])); if (found) { scheme.splice(s--, 1); } foundOne |= found; } return foundOne; }; var _schemesMatch = function(schemeA, schemeB) { if (!schemeA || !schemeB) { return false; } return (schemeA.sarg & ~(Args.Optional | Args.Required)) === (schemeB.sarg & ~(Args.Optional | Args.Required)) && schemeA.typeValue === schemeB.typeValue; }; var _isRequired = function(sarg) { return !_isOptional(sarg); }; var _isOptional = function(sarg) { return (sarg & Args.Optional) !== 0; }; var _reasonForFailure = function(schemeEl, a, arg) { var err = ""; if (_isTypeSpecified(schemeEl)) { err = "Argument " + a + " ("+schemeEl.sname+") should be type "+_getTypeString(schemeEl)+", but it was type " + (typeof arg) + " with value " + arg + "."; } else if (schemeEl.customCheck !== undefined) { var funcString = schemeEl.customCheck.toString(); if (funcString.length > 50) { funcString = funcString.substr(0, 40) + "..." + funcString.substr(funcString.length-10); } err = "Argument " + a + " ("+schemeEl.sname+") does not pass the custom check ("+funcString+")."; } else { err = "Argument " + a + " ("+schemeEl.sname+") has no valid type specified."; } return err; }; /** * Last argument may be a named argument object. This is decided in a non-greedy way, if * there are any unmatched arguments after the normal process and the last argument is an * object it is inspected for matching names. * * If the last argument is a named argument object and it could potentially be matched to * a normal object in the schema the object is first used to try to match any remaining * required args (including the object that it would match against). Only if there are no * remaining required args or none of the remaining required args are matched will the * last object arg match against a normal schema object. * * Runs of objects with the same type are matched greedily but if a required object is * encountered in the schema after all objects of that type have been matched the previous * matches are shifted right to cover the new required arg. Shifts can only happen from * immediately preceding required args or optional args. If a previous required arg is * matched but an optional arg seprates the new required arg from the old one only the * optional arg in between can be shifted. The required arg and any preceding optional * args are not shifted. */ var Args = function(scheme, args) { if (scheme === undefined) throw new Error("The scheme has not been passed."); if (args === undefined) throw new Error("The arguments have not been passed."); args = Array.prototype.slice.call(args,0); var returns = {}; var err = undefined; var runType = undefined; var run = []; var _addToRun = function(schemeEl) { if ( !runType || !_schemesMatch(runType, schemeEl) || (_isRequired(runType.sarg) && _isOptional(schemeEl.sarg)) ) { run = []; } if (run.length > 0 || _isOptional(schemeEl.sarg)) { runType = schemeEl; run.push(schemeEl); } }; var _shiftRun = function(schemeEl, a, r) { if (r === undefined) r = run.length-1; if (r < 0) return; var lastMatch = run[r]; var arg = returns[lastMatch.sname]; if (_typeMatches(arg, schemeEl)) { returns[schemeEl.sname] = arg; returns[lastMatch.sname] = lastMatch.defValue || undefined; if ((lastMatch.sarg & Args.Optional) === 0) { // if the last in the run was not optional _shiftRun(lastMatch, a, r-1); } } else { return _reasonForFailure(schemeEl, a, arg); } }; var a, s; // first let's extract any named args // we need to see if the last arg is an object and if it's constructor was Object (i.e. it is simple) var lastArg = args[args.length-1]; if (lastArg !== null && typeof lastArg === "object" && lastArg.constructor === Object) { // we should also exit if the object arg matches a rule itself // that is more tricky though... if (_checkNamedArgs(args[args.length-1], scheme, returns)) { args.splice(args.length-1,1); } } for (a = 0, s = 0; s < scheme.length ; s++) { a = (function(a,s) { var arg = args[a]; // argument group if (scheme[s] instanceof Array) { var group = scheme[s]; var retName = undefined; var groupIsOptional = false; for (var g = 0 ; g < group.length ; g++) { var groupEl = group[g]; if (groupEl === Args.Optional) { groupIsOptional = true; } else { var schemeEl = _extractSchemeEl(groupEl); if (_typeMatches(arg, schemeEl)) { retName = schemeEl.sname; } } } if (retName === undefined && !groupIsOptional) { if (arg === null || arg === undefined) { err = "Argument " + a + " is null or undefined but it must be not null."; return a; } err = "Argument " + a + " should be one of: "; for (var g = 0 ; g < group.length ; g++) { var schemeEl = _extractSchemeEl(group[g]); err += _getTypeString(schemeEl) + ", "; } err += "but it was type " + (typeof arg) + " with value " + arg + "."; return a; } else if (retName !== undefined) { returns[retName] = arg; return a+1; } } else { var schemeEl = _extractSchemeEl(scheme[s]); // optional arg if ((schemeEl.sarg & Args.Optional) !== 0) { // check if this arg matches the next schema slot if ( arg === null || arg === undefined) { if (schemeEl.defValue !== undefined) { returns[schemeEl.sname] = schemeEl.defValue; } else { returns[schemeEl.sname] = arg; } return a+1; // if the arg is null or undefined it will fill a slot, but may be replace by the default value } else if (_typeMatches(arg, schemeEl)) { returns[schemeEl.sname] = arg; _addToRun(schemeEl); return a+1; } else if (schemeEl.defValue !== undefined) { returns[schemeEl.sname] = schemeEl.defValue; return a; } } // manadatory arg else { //if ((schemeEl.sarg & Args.NotNull) !== 0) { if (arg === null || arg === undefined) { if (_isTypeSpecified(schemeEl) && _schemesMatch(schemeEl, runType)) { err = _shiftRun(schemeEl, a); if (err === "") { _addToRun(schemeEl); } return a; } else { err = "Argument " + a + " ("+schemeEl.sname+") is null or undefined but it must be not null."; return a; } } else if (!_typeMatches(arg, schemeEl)) { if (_isTypeSpecified(schemeEl) && _schemesMatch(schemeEl, runType)) { err = _shiftRun(schemeEl, a); if (err === "") { _addToRun(schemeEl); return a+1; } } else { err = _reasonForFailure(schemeEl, a, arg); } return a; } else { returns[schemeEl.sname] = arg; _addToRun(schemeEl); return a+1; } } } return a; })(a,s); if (err) { break; } } if (err) { throw new Error(err); } return returns; }; Args.ANY = 0x1; Args.STRING = 0x1 << 1; Args.FUNCTION = 0x1 << 2; Args.INT = 0x1 << 3; Args.FLOAT = 0x1 << 4; Args.ARRAY_BUFFER = 0x1 << 5; Args.OBJECT = 0x1 << 6; Args.DATE = 0x1 << 7; Args.BOOL = 0x1 << 8; Args.DOM_EL = 0x1 << 9; Args.ARRAY = 0x1 << 10; Args.Optional = 0x1 << 11; Args.NotNull = Args.Required = 0x1 << 12; return Args; });
import { moduleFor, RenderingTestCase, runTask } from 'internal-test-helpers'; import { Object as EmberObject } from '@ember/-internals/runtime'; import { set, setProperties, computed } from '@ember/-internals/metal'; import { setComponentManager, capabilities } from '@ember/-internals/glimmer'; const BasicComponentManager = EmberObject.extend({ capabilities: capabilities('3.4'), createComponent(factory, args) { return factory.create({ args }); }, updateComponent(component, args) { set(component, 'args', args); }, getContext(component) { return component; }, }); /* eslint-disable */ function createBasicManager(owner) { return BasicComponentManager.create({ owner }); } function createInstrumentedManager(owner) { return InstrumentedComponentManager.create({ owner }); } /* eslint-enable */ let InstrumentedComponentManager; class ComponentManagerTest extends RenderingTestCase { constructor(assert) { super(...arguments); InstrumentedComponentManager = EmberObject.extend({ capabilities: capabilities('3.4', { destructor: true, asyncLifecycleCallbacks: true, }), createComponent(factory, args) { assert.step('createComponent'); return factory.create({ args }); }, updateComponent(component, args) { assert.step('updateComponent'); set(component, 'args', args); }, destroyComponent(component) { assert.step('destroyComponent'); component.destroy(); }, getContext(component) { assert.step('getContext'); return component; }, didCreateComponent(component) { assert.step('didCreateComponent'); component.didRender(); }, didUpdateComponent(component) { assert.step('didUpdateComponent'); component.didUpdate(); }, }); } } moduleFor( 'Component Manager - Curly Invocation', class extends ComponentManagerTest { ['@test the string based version of setComponentManager is deprecated']() { expectDeprecation(() => { setComponentManager( 'basic', EmberObject.extend({ greeting: 'hello', }) ); }, 'Passing the name of the component manager to "setupComponentManager" is deprecated. Please pass a function that produces an instance of the manager.'); } ['@test it can render a basic component with custom component manager']() { let ComponentClass = setComponentManager( createBasicManager, EmberObject.extend({ greeting: 'hello', }) ); this.registerComponent('foo-bar', { template: `<p>{{greeting}} world</p>`, ComponentClass, }); this.render('{{foo-bar}}'); this.assertHTML(`<p>hello world</p>`); } ['@test it can render a basic component with custom component manager with a factory']() { let ComponentClass = setComponentManager( () => BasicComponentManager.create(), EmberObject.extend({ greeting: 'hello', }) ); this.registerComponent('foo-bar', { template: `<p>{{greeting}} world</p>`, ComponentClass, }); this.render('{{foo-bar}}'); this.assertHTML(`<p>hello world</p>`); } ['@test it can have no template context']() { let ComponentClass = setComponentManager(() => { return EmberObject.create({ capabilities: capabilities('3.4'), createComponent() { return null; }, updateComponent() {}, getContext() { return null; }, }); }, {}); this.registerComponent('foo-bar', { template: `<p>{{@greeting}} world</p>`, ComponentClass, }); this.render('{{foo-bar greeting="hello"}}'); this.assertHTML(`<p>hello world</p>`); } ['@test it can discover component manager through inheritance - ES Classes']() { class Base {} setComponentManager(() => { return EmberObject.create({ capabilities: capabilities('3.4'), createComponent(Factory, args) { return new Factory(args); }, updateComponent() {}, getContext(component) { return component; }, }); }, Base); class Child extends Base {} class Grandchild extends Child { constructor() { super(); this.name = 'grandchild'; } } this.registerComponent('foo-bar', { template: `{{this.name}}`, ComponentClass: Grandchild, }); this.render('{{foo-bar}}'); this.assertHTML(`grandchild`); } ['@test it can discover component manager through inheritance - Ember Object']() { let Parent = setComponentManager(createBasicManager, EmberObject.extend()); let Child = Parent.extend(); let Grandchild = Child.extend({ init() { this._super(...arguments); this.name = 'grandchild'; }, }); this.registerComponent('foo-bar', { template: `{{this.name}}`, ComponentClass: Grandchild, }); this.render('{{foo-bar}}'); this.assertHTML(`grandchild`); } ['@test it can customize the template context']() { let customContext = { greeting: 'goodbye', }; let ComponentClass = setComponentManager( () => { return EmberObject.create({ capabilities: capabilities('3.4'), createComponent(factory) { return factory.create(); }, getContext() { return customContext; }, updateComponent() {}, }); }, EmberObject.extend({ greeting: 'hello', count: 1234, }) ); this.registerComponent('foo-bar', { template: `<p>{{greeting}} world {{count}}</p>`, ComponentClass, }); this.render('{{foo-bar}}'); this.assertHTML(`<p>goodbye world </p>`); runTask(() => set(customContext, 'greeting', 'sayonara')); this.assertHTML(`<p>sayonara world </p>`); } ['@test it can set arguments on the component instance']() { let ComponentClass = setComponentManager( createBasicManager, EmberObject.extend({ salutation: computed('args.named.firstName', 'args.named.lastName', function() { return this.args.named.firstName + ' ' + this.args.named.lastName; }), }) ); this.registerComponent('foo-bar', { template: `<p>{{salutation}}</p>`, ComponentClass, }); this.render('{{foo-bar firstName="Yehuda" lastName="Katz"}}'); this.assertHTML(`<p>Yehuda Katz</p>`); } ['@test arguments are updated if they change']() { let ComponentClass = setComponentManager( createBasicManager, EmberObject.extend({ salutation: computed('args.named.firstName', 'args.named.lastName', function() { return this.args.named.firstName + ' ' + this.args.named.lastName; }), }) ); this.registerComponent('foo-bar', { template: `<p>{{salutation}}</p>`, ComponentClass, }); this.render('{{foo-bar firstName=firstName lastName=lastName}}', { firstName: 'Yehuda', lastName: 'Katz', }); this.assertHTML(`<p>Yehuda Katz</p>`); runTask(() => setProperties(this.context, { firstName: 'Chad', lastName: 'Hietala', }) ); this.assertHTML(`<p>Chad Hietala</p>`); } ['@test it can set positional params on the component instance']() { let ComponentClass = setComponentManager( createBasicManager, EmberObject.extend({ salutation: computed('args.positional', function() { return this.args.positional[0] + ' ' + this.args.positional[1]; }), }) ); this.registerComponent('foo-bar', { template: `<p>{{salutation}}</p>`, ComponentClass, }); this.render('{{foo-bar "Yehuda" "Katz"}}'); this.assertHTML(`<p>Yehuda Katz</p>`); } ['@test positional params are updated if they change']() { let ComponentClass = setComponentManager( createBasicManager, EmberObject.extend({ salutation: computed('args.positional', function() { return this.args.positional[0] + ' ' + this.args.positional[1]; }), }) ); this.registerComponent('foo-bar', { template: `<p>{{salutation}}</p>`, ComponentClass, }); this.render('{{foo-bar firstName lastName}}', { firstName: 'Yehuda', lastName: 'Katz', }); this.assertHTML(`<p>Yehuda Katz</p>`); runTask(() => setProperties(this.context, { firstName: 'Chad', lastName: 'Hietala', }) ); this.assertHTML(`<p>Chad Hietala</p>`); } ['@test it can opt-in to running destructor'](assert) { let ComponentClass = setComponentManager( () => { return EmberObject.create({ capabilities: capabilities('3.4', { destructor: true, }), createComponent(factory) { assert.step('createComponent'); return factory.create(); }, getContext(component) { return component; }, updateComponent() {}, destroyComponent(component) { assert.step('destroyComponent'); component.destroy(); }, }); }, EmberObject.extend({ greeting: 'hello', destroy() { assert.step('component.destroy()'); this._super(...arguments); }, }) ); this.registerComponent('foo-bar', { template: `<p>{{greeting}} world</p>`, ComponentClass, }); this.render('{{#if show}}{{foo-bar}}{{/if}}', { show: true }); this.assertHTML(`<p>hello world</p>`); runTask(() => this.context.set('show', false)); this.assertText(''); assert.verifySteps(['createComponent', 'destroyComponent', 'component.destroy()']); } ['@test it can opt-in to running async lifecycle hooks'](assert) { let ComponentClass = setComponentManager( () => { return EmberObject.create({ capabilities: capabilities('3.4', { asyncLifecycleCallbacks: true, }), createComponent(factory, args) { assert.step('createComponent'); return factory.create({ args }); }, updateComponent(component, args) { assert.step('updateComponent'); set(component, 'args', args); }, destroyComponent(component) { assert.step('destroyComponent'); component.destroy(); }, getContext(component) { assert.step('getContext'); return component; }, didCreateComponent() { assert.step('didCreateComponent'); }, didUpdateComponent() { assert.step('didUpdateComponent'); }, }); }, EmberObject.extend({ greeting: 'hello', }) ); this.registerComponent('foo-bar', { template: `<p>{{greeting}} {{@name}}</p>`, ComponentClass, }); this.render('{{foo-bar name=name}}', { name: 'world' }); this.assertHTML(`<p>hello world</p>`); assert.verifySteps(['createComponent', 'getContext', 'didCreateComponent']); runTask(() => this.context.set('name', 'max')); this.assertHTML(`<p>hello max</p>`); assert.verifySteps(['updateComponent', 'didUpdateComponent']); } } ); moduleFor( 'Component Manager - Angle Invocation', class extends ComponentManagerTest { ['@test it can render a basic component with custom component manager']() { let ComponentClass = setComponentManager( createBasicManager, EmberObject.extend({ greeting: 'hello', }) ); this.registerComponent('foo-bar', { template: `<p>{{greeting}} world</p>`, ComponentClass, }); this.render('<FooBar />'); this.assertHTML(`<p>hello world</p>`); } ['@test it can set arguments on the component instance']() { let ComponentClass = setComponentManager( createBasicManager, EmberObject.extend({ salutation: computed('args.named.firstName', 'args.named.lastName', function() { return this.args.named.firstName + ' ' + this.args.named.lastName; }), }) ); this.registerComponent('foo-bar', { template: `<p>{{salutation}}</p>`, ComponentClass, }); this.render('<FooBar @firstName="Yehuda" @lastName="Katz" />'); this.assertHTML(`<p>Yehuda Katz</p>`); } ['@test it can pass attributes']() { let ComponentClass = setComponentManager(createBasicManager, EmberObject.extend()); this.registerComponent('foo-bar', { template: `<p ...attributes>Hello world!</p>`, ComponentClass, }); this.render('<FooBar data-test="foo" />'); this.assertHTML(`<p data-test="foo">Hello world!</p>`); } ['@test arguments are updated if they change']() { let ComponentClass = setComponentManager( createBasicManager, EmberObject.extend({ salutation: computed('args.named.firstName', 'args.named.lastName', function() { return this.args.named.firstName + ' ' + this.args.named.lastName; }), }) ); this.registerComponent('foo-bar', { template: `<p>{{salutation}}</p>`, ComponentClass, }); this.render('<FooBar @firstName={{firstName}} @lastName={{lastName}} />', { firstName: 'Yehuda', lastName: 'Katz', }); this.assertHTML(`<p>Yehuda Katz</p>`); runTask(() => setProperties(this.context, { firstName: 'Chad', lastName: 'Hietala', }) ); this.assertHTML(`<p>Chad Hietala</p>`); } ['@test updating attributes triggers didUpdateComponent'](assert) { let TestManager = EmberObject.extend({ capabilities: capabilities('3.4', { destructor: true, asyncLifecycleCallbacks: true, }), createComponent(factory, args) { assert.step('createComponent'); return factory.create({ args }); }, updateComponent(component, args) { assert.step('updateComponent'); set(component, 'args', args); }, destroyComponent(component) { component.destroy(); }, getContext(component) { assert.step('getContext'); return component; }, didCreateComponent(component) { assert.step('didCreateComponent'); component.didRender(); }, didUpdateComponent(component) { assert.step('didUpdateComponent'); component.didUpdate(); }, }); let ComponentClass = setComponentManager( () => { return TestManager.create(); }, EmberObject.extend({ didRender() {}, didUpdate() {}, }) ); this.registerComponent('foo-bar', { template: `<p ...attributes>Hello world!</p>`, ComponentClass, }); this.render('<FooBar data-test={{value}} />', { value: 'foo' }); this.assertHTML(`<p data-test="foo">Hello world!</p>`); assert.verifySteps(['createComponent', 'getContext', 'didCreateComponent']); runTask(() => this.context.set('value', 'bar')); assert.verifySteps(['didUpdateComponent']); } } );
/* * Planck.js v0.3.0-rc.1 * * Copyright (c) 2016-2018 Ali Shakiba http://shakiba.me/planck.js * Copyright (c) 2006-2013 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ /* * Stage.js * * @copyright 2017 Ali Shakiba http://shakiba.me/stage.js * @license The MIT License */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.planck=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ var planck = require("../lib/"); var Stage = require("stage-js/platform/web"); module.exports = planck; planck.testbed = function(opts, callback) { if (typeof opts === "function") { callback = opts; opts = null; } Stage(function(stage, canvas) { stage.on(Stage.Mouse.START, function() { window.focus(); document.activeElement && document.activeElement.blur(); canvas.focus(); }); stage.MAX_ELAPSE = 1e3 / 30; var Vec2 = planck.Vec2; var testbed = {}; var paused = false; stage.on("resume", function() { paused = false; testbed._resume && testbed._resume(); }); stage.on("pause", function() { paused = true; testbed._pause && testbed._pause(); }); testbed.isPaused = function() { return paused; }; testbed.togglePause = function() { paused ? testbed.resume() : testbed.pause(); }; testbed.pause = function() { stage.pause(); }; testbed.resume = function() { stage.resume(); testbed.focus(); }; testbed.focus = function() { document.activeElement && document.activeElement.blur(); canvas.focus(); }; testbed.debug = false; testbed.width = 80; testbed.height = 60; testbed.x = 0; testbed.y = -10; testbed.ratio = 16; testbed.hz = 60; testbed.speed = 1; testbed.activeKeys = {}; testbed.background = "#222222"; var statusText = ""; var statusMap = {}; function statusSet(name, value) { if (typeof value !== "function" && typeof value !== "object") { statusMap[name] = value; } } function statusMerge(obj) { for (var key in obj) { statusSet(key, obj[key]); } } testbed.status = function(a, b) { if (typeof b !== "undefined") { statusSet(a, b); } else if (a && typeof a === "object") { statusMerge(a); } else if (typeof a === "string") { statusText = a; } testbed._status && testbed._status(statusText, statusMap); }; testbed.info = function(text) { testbed._info && testbed._info(text); }; var lastDrawHash = "", drawHash = ""; (function() { var drawingTexture = new Stage.Texture(); stage.append(Stage.image(drawingTexture)); var buffer = []; stage.tick(function() { buffer.length = 0; }, true); drawingTexture.draw = function(ctx) { ctx.save(); ctx.transform(1, 0, 0, -1, -testbed.x, -testbed.y); ctx.lineWidth = 2 / testbed.ratio; ctx.lineCap = "round"; for (var drawing = buffer.shift(); drawing; drawing = buffer.shift()) { drawing(ctx, testbed.ratio); } ctx.restore(); }; testbed.drawPoint = function(p, r, color) { buffer.push(function(ctx, ratio) { ctx.beginPath(); ctx.arc(p.x, p.y, 5 / ratio, 0, 2 * Math.PI); ctx.strokeStyle = color; ctx.stroke(); }); drawHash += "point" + p.x + "," + p.y + "," + r + "," + color; }; testbed.drawCircle = function(p, r, color) { buffer.push(function(ctx) { ctx.beginPath(); ctx.arc(p.x, p.y, r, 0, 2 * Math.PI); ctx.strokeStyle = color; ctx.stroke(); }); drawHash += "circle" + p.x + "," + p.y + "," + r + "," + color; }; testbed.drawSegment = function(a, b, color) { buffer.push(function(ctx) { ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.strokeStyle = color; ctx.stroke(); }); drawHash += "segment" + a.x + "," + a.y + "," + b.x + "," + b.y + "," + color; }; testbed.drawPolygon = function(points, color) { if (!points || !points.length) { return; } buffer.push(function(ctx) { ctx.beginPath(); ctx.moveTo(points[0].x, points[0].y); for (var i = 1; i < points.length; i++) { ctx.lineTo(points[i].x, points[i].y); } ctx.strokeStyle = color; ctx.closePath(); ctx.stroke(); }); drawHash += "segment"; for (var i = 1; i < points.length; i++) { drawHash += points[i].x + "," + points[i].y + ","; } drawHash += color; }; testbed.drawAABB = function(aabb, color) { buffer.push(function(ctx) { ctx.beginPath(); ctx.moveTo(aabb.lowerBound.x, aabb.lowerBound.y); ctx.lineTo(aabb.upperBound.x, aabb.lowerBound.y); ctx.lineTo(aabb.upperBound.x, aabb.upperBound.y); ctx.lineTo(aabb.lowerBound.x, aabb.upperBound.y); ctx.strokeStyle = color; ctx.closePath(); ctx.stroke(); }); drawHash += "aabb"; drawHash += aabb.lowerBound.x + "," + aabb.lowerBound.y + ","; drawHash += aabb.upperBound.x + "," + aabb.upperBound.y + ","; drawHash += color; }; testbed.color = function(r, g, b) { r = r * 256 | 0; g = g * 256 | 0; b = b * 256 | 0; return "rgb(" + r + ", " + g + ", " + b + ")"; }; })(); var world = callback(testbed); var viewer = new Viewer(world, testbed); var lastX = 0, lastY = 0; stage.tick(function(dt, t) { if (lastX !== testbed.x || lastY !== testbed.y) { viewer.offset(-testbed.x, -testbed.y); lastX = testbed.x, lastY = testbed.y; } }); viewer.tick(function(dt, t) { if (typeof testbed.step === "function") { testbed.step(dt, t); } if (targetBody) { testbed.drawSegment(targetBody.getPosition(), mouseMove, "rgba(255,255,255,0.2)"); } if (lastDrawHash !== drawHash) { lastDrawHash = drawHash; stage.touch(); } drawHash = ""; return true; }); stage.background(testbed.background); stage.viewbox(testbed.width, testbed.height); stage.pin("alignX", -.5); stage.pin("alignY", -.5); stage.prepend(viewer); function findBody(point) { var body; var aabb = planck.AABB(point, point); world.queryAABB(aabb, function(fixture) { if (body) { return; } if (!fixture.getBody().isDynamic() || !fixture.testPoint(point)) { return; } body = fixture.getBody(); return true; }); return body; } var mouseGround = world.createBody(); var mouseJoint; var targetBody; var mouseMove = { x: 0, y: 0 }; viewer.attr("spy", true).on(Stage.Mouse.START, function(point) { point = { x: point.x, y: -point.y }; if (targetBody) { return; } var body = findBody(point); if (!body) { return; } if (testbed.mouseForce) { targetBody = body; } else { mouseJoint = planck.MouseJoint({ maxForce: 1e3 }, mouseGround, body, Vec2(point)); world.createJoint(mouseJoint); } }).on(Stage.Mouse.MOVE, function(point) { point = { x: point.x, y: -point.y }; if (mouseJoint) { mouseJoint.setTarget(point); } mouseMove.x = point.x; mouseMove.y = point.y; }).on(Stage.Mouse.END, function(point) { point = { x: point.x, y: -point.y }; if (mouseJoint) { world.destroyJoint(mouseJoint); mouseJoint = null; } if (targetBody) { var force = Vec2.sub(point, targetBody.getPosition()); targetBody.applyForceToCenter(force.mul(testbed.mouseForce), true); targetBody = null; } }).on(Stage.Mouse.CANCEL, function(point) { point = { x: point.x, y: -point.y }; if (mouseJoint) { world.destroyJoint(mouseJoint); mouseJoint = null; } if (targetBody) { targetBody = null; } }); window.addEventListener("keydown", function(e) { switch (e.keyCode) { case "P".charCodeAt(0): testbed.togglePause(); break; } }, false); var downKeys = {}; window.addEventListener("keydown", function(e) { var keyCode = e.keyCode; downKeys[keyCode] = true; updateActiveKeys(keyCode, true); testbed.keydown && testbed.keydown(keyCode, String.fromCharCode(keyCode)); }); window.addEventListener("keyup", function(e) { var keyCode = e.keyCode; downKeys[keyCode] = false; updateActiveKeys(keyCode, false); testbed.keyup && testbed.keyup(keyCode, String.fromCharCode(keyCode)); }); var activeKeys = testbed.activeKeys; function updateActiveKeys(keyCode, down) { var char = String.fromCharCode(keyCode); if (/\w/.test(char)) { activeKeys[char] = down; } activeKeys.right = downKeys[39] || activeKeys["D"]; activeKeys.left = downKeys[37] || activeKeys["A"]; activeKeys.up = downKeys[38] || activeKeys["W"]; activeKeys.down = downKeys[40] || activeKeys["S"]; activeKeys.fire = downKeys[32] || downKeys[13]; } }); }; Viewer._super = Stage; Viewer.prototype = Stage._create(Viewer._super.prototype); function Viewer(world, opts) { Viewer._super.call(this); this.label("Planck"); opts = opts || {}; var options = this._options = {}; this._options.speed = opts.speed || 1; this._options.hz = opts.hz || 60; if (Math.abs(this._options.hz) < 1) { this._options.hz = 1 / this._options.hz; } this._options.ratio = opts.ratio || 16; this._options.lineWidth = 2 / this._options.ratio; this._world = world; var timeStep = 1 / this._options.hz; var elapsedTime = 0; this.tick(function(dt) { dt = dt * .001 * options.speed; elapsedTime += dt; while (elapsedTime > timeStep) { world.step(timeStep); elapsedTime -= timeStep; } this.renderWorld(); return true; }, true); world.on("remove-fixture", function(obj) { obj.ui && obj.ui.remove(); }); world.on("remove-joint", function(obj) { obj.ui && obj.ui.remove(); }); } Viewer.prototype.renderWorld = function(world) { var world = this._world; var viewer = this; for (var b = world.getBodyList(); b; b = b.getNext()) { for (var f = b.getFixtureList(); f; f = f.getNext()) { if (!f.ui) { if (f.render && f.render.stroke) { this._options.strokeStyle = f.render.stroke; } else if (b.render && b.render.stroke) { this._options.strokeStyle = b.render.stroke; } else if (b.isDynamic()) { this._options.strokeStyle = "rgba(255,255,255,0.9)"; } else if (b.isKinematic()) { this._options.strokeStyle = "rgba(255,255,255,0.7)"; } else if (b.isStatic()) { this._options.strokeStyle = "rgba(255,255,255,0.5)"; } if (f.render && f.render.fill) { this._options.fillStyle = f.render.fill; } else if (b.render && b.render.fill) { this._options.fillStyle = b.render.fill; } else { this._options.fillStyle = ""; } var type = f.getType(); var shape = f.getShape(); if (type == "circle") { f.ui = viewer.drawCircle(shape, this._options); } if (type == "edge") { f.ui = viewer.drawEdge(shape, this._options); } if (type == "polygon") { f.ui = viewer.drawPolygon(shape, this._options); } if (type == "chain") { f.ui = viewer.drawChain(shape, this._options); } if (f.ui) { f.ui.appendTo(viewer); } } if (f.ui) { var p = b.getPosition(), r = b.getAngle(); if (f.ui.__lastX !== p.x || f.ui.__lastY !== p.y || f.ui.__lastR !== r) { f.ui.__lastX = p.x; f.ui.__lastY = p.y; f.ui.__lastR = r; f.ui.offset(p.x, -p.y); f.ui.rotate(-r); } } } } for (var j = world.getJointList(); j; j = j.getNext()) { var type = j.getType(); var a = j.getAnchorA(); var b = j.getAnchorB(); if (!j.ui) { this._options.strokeStyle = "rgba(255,255,255,0.2)"; j.ui = viewer.drawJoint(j, this._options); j.ui.pin("handle", .5); if (j.ui) { j.ui.appendTo(viewer); } } if (j.ui) { var cx = (a.x + b.x) * .5; var cy = (-a.y + -b.y) * .5; var dx = a.x - b.x; var dy = -a.y - -b.y; var d = Math.sqrt(dx * dx + dy * dy); j.ui.width(d); j.ui.rotate(Math.atan2(dy, dx)); j.ui.offset(cx, cy); } } }; Viewer.prototype.drawJoint = function(joint, options) { var lw = options.lineWidth; var ratio = options.ratio; var length = 10; var texture = Stage.canvas(function(ctx) { this.size(length + 2 * lw, 2 * lw, ratio); ctx.scale(ratio, ratio); ctx.beginPath(); ctx.moveTo(lw, lw); ctx.lineTo(lw + length, lw); ctx.lineCap = "round"; ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var image = Stage.image(texture).stretch(); return image; }; Viewer.prototype.drawCircle = function(shape, options) { var lw = options.lineWidth; var ratio = options.ratio; var r = shape.m_radius; var cx = r + lw; var cy = r + lw; var w = r * 2 + lw * 2; var h = r * 2 + lw * 2; var texture = Stage.canvas(function(ctx) { this.size(w, h, ratio); ctx.scale(ratio, ratio); ctx.arc(cx, cy, r, 0, 2 * Math.PI); if (options.fillStyle) { ctx.fillStyle = options.fillStyle; ctx.fill(); } ctx.lineTo(cx, cy); ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var image = Stage.image(texture).offset(shape.m_p.x - cx, -shape.m_p.y - cy); var node = Stage.create().append(image); return node; }; Viewer.prototype.drawEdge = function(edge, options) { var lw = options.lineWidth; var ratio = options.ratio; var v1 = edge.m_vertex1; var v2 = edge.m_vertex2; var dx = v2.x - v1.x; var dy = v2.y - v1.y; var length = Math.sqrt(dx * dx + dy * dy); var texture = Stage.canvas(function(ctx) { this.size(length + 2 * lw, 2 * lw, ratio); ctx.scale(ratio, ratio); ctx.beginPath(); ctx.moveTo(lw, lw); ctx.lineTo(lw + length, lw); ctx.lineCap = "round"; ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var minX = Math.min(v1.x, v2.x); var minY = Math.min(-v1.y, -v2.y); var image = Stage.image(texture); image.rotate(-Math.atan2(dy, dx)); image.offset(minX - lw, minY - lw); var node = Stage.create().append(image); return node; }; Viewer.prototype.drawPolygon = function(shape, options) { var lw = options.lineWidth; var ratio = options.ratio; var vertices = shape.m_vertices; if (!vertices.length) { return; } var minX = Infinity, minY = Infinity; var maxX = -Infinity, maxY = -Infinity; for (var i = 0; i < vertices.length; ++i) { var v = vertices[i]; minX = Math.min(minX, v.x); maxX = Math.max(maxX, v.x); minY = Math.min(minY, -v.y); maxY = Math.max(maxY, -v.y); } var width = maxX - minX; var height = maxY - minY; var texture = Stage.canvas(function(ctx) { this.size(width + 2 * lw, height + 2 * lw, ratio); ctx.scale(ratio, ratio); ctx.beginPath(); for (var i = 0; i < vertices.length; ++i) { var v = vertices[i]; var x = v.x - minX + lw; var y = -v.y - minY + lw; if (i == 0) ctx.moveTo(x, y); else ctx.lineTo(x, y); } if (vertices.length > 2) { ctx.closePath(); } if (options.fillStyle) { ctx.fillStyle = options.fillStyle; ctx.fill(); ctx.closePath(); } ctx.lineCap = "round"; ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var image = Stage.image(texture); image.offset(minX - lw, minY - lw); var node = Stage.create().append(image); return node; }; Viewer.prototype.drawChain = function(shape, options) { var lw = options.lineWidth; var ratio = options.ratio; var vertices = shape.m_vertices; if (!vertices.length) { return; } var minX = Infinity, minY = Infinity; var maxX = -Infinity, maxY = -Infinity; for (var i = 0; i < vertices.length; ++i) { var v = vertices[i]; minX = Math.min(minX, v.x); maxX = Math.max(maxX, v.x); minY = Math.min(minY, -v.y); maxY = Math.max(maxY, -v.y); } var width = maxX - minX; var height = maxY - minY; var texture = Stage.canvas(function(ctx) { this.size(width + 2 * lw, height + 2 * lw, ratio); ctx.scale(ratio, ratio); ctx.beginPath(); for (var i = 0; i < vertices.length; ++i) { var v = vertices[i]; var x = v.x - minX + lw; var y = -v.y - minY + lw; if (i == 0) ctx.moveTo(x, y); else ctx.lineTo(x, y); } if (vertices.length > 2) {} if (options.fillStyle) { ctx.fillStyle = options.fillStyle; ctx.fill(); ctx.closePath(); } ctx.lineCap = "round"; ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var image = Stage.image(texture); image.offset(minX - lw, minY - lw); var node = Stage.create().append(image); return node; }; },{"../lib/":27,"stage-js/platform/web":82}],2:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Body; var common = require("./util/common"); var options = require("./util/options"); var Vec2 = require("./common/Vec2"); var Rot = require("./common/Rot"); var Math = require("./common/Math"); var Sweep = require("./common/Sweep"); var Transform = require("./common/Transform"); var Velocity = require("./common/Velocity"); var Position = require("./common/Position"); var Fixture = require("./Fixture"); var Shape = require("./Shape"); var World = require("./World"); var staticBody = Body.STATIC = "static"; var kinematicBody = Body.KINEMATIC = "kinematic"; var dynamicBody = Body.DYNAMIC = "dynamic"; var BodyDef = { type: staticBody, position: Vec2.zero(), angle: 0, linearVelocity: Vec2.zero(), angularVelocity: 0, linearDamping: 0, angularDamping: 0, fixedRotation: false, bullet: false, gravityScale: 1, allowSleep: true, awake: true, active: true, userData: null }; function Body(world, def) { def = options(def, BodyDef); _ASSERT && common.assert(Vec2.isValid(def.position)); _ASSERT && common.assert(Vec2.isValid(def.linearVelocity)); _ASSERT && common.assert(Math.isFinite(def.angle)); _ASSERT && common.assert(Math.isFinite(def.angularVelocity)); _ASSERT && common.assert(Math.isFinite(def.angularDamping) && def.angularDamping >= 0); _ASSERT && common.assert(Math.isFinite(def.linearDamping) && def.linearDamping >= 0); this.m_world = world; this.m_awakeFlag = def.awake; this.m_autoSleepFlag = def.allowSleep; this.m_bulletFlag = def.bullet; this.m_fixedRotationFlag = def.fixedRotation; this.m_activeFlag = def.active; this.m_islandFlag = false; this.m_toiFlag = false; this.m_userData = def.userData; this.m_type = def.type; if (this.m_type == dynamicBody) { this.m_mass = 1; this.m_invMass = 1; } else { this.m_mass = 0; this.m_invMass = 0; } this.m_I = 0; this.m_invI = 0; this.m_xf = Transform.identity(); this.m_xf.p = Vec2.clone(def.position); this.m_xf.q.setAngle(def.angle); this.m_sweep = new Sweep(); this.m_sweep.setTransform(this.m_xf); this.c_velocity = new Velocity(); this.c_position = new Position(); this.m_force = Vec2.zero(); this.m_torque = 0; this.m_linearVelocity = Vec2.clone(def.linearVelocity); this.m_angularVelocity = def.angularVelocity; this.m_linearDamping = def.linearDamping; this.m_angularDamping = def.angularDamping; this.m_gravityScale = def.gravityScale; this.m_sleepTime = 0; this.m_jointList = null; this.m_contactList = null; this.m_fixtureList = null; this.m_prev = null; this.m_next = null; this.m_destroyed = false; } Body.prototype.isWorldLocked = function() { return this.m_world && this.m_world.isLocked() ? true : false; }; Body.prototype.getWorld = function() { return this.m_world; }; Body.prototype.getNext = function() { return this.m_next; }; Body.prototype.setUserData = function(data) { this.m_userData = data; }; Body.prototype.getUserData = function() { return this.m_userData; }; Body.prototype.getFixtureList = function() { return this.m_fixtureList; }; Body.prototype.getJointList = function() { return this.m_jointList; }; Body.prototype.getContactList = function() { return this.m_contactList; }; Body.prototype.isStatic = function() { return this.m_type == staticBody; }; Body.prototype.isDynamic = function() { return this.m_type == dynamicBody; }; Body.prototype.isKinematic = function() { return this.m_type == kinematicBody; }; Body.prototype.setStatic = function() { this.setType(staticBody); return this; }; Body.prototype.setDynamic = function() { this.setType(dynamicBody); return this; }; Body.prototype.setKinematic = function() { this.setType(kinematicBody); return this; }; Body.prototype.getType = function() { return this.m_type; }; Body.prototype.setType = function(type) { _ASSERT && common.assert(type === staticBody || type === kinematicBody || type === dynamicBody); _ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return; } if (this.m_type == type) { return; } this.m_type = type; this.resetMassData(); if (this.m_type == staticBody) { this.m_linearVelocity.setZero(); this.m_angularVelocity = 0; this.m_sweep.forward(); this.synchronizeFixtures(); } this.setAwake(true); this.m_force.setZero(); this.m_torque = 0; var ce = this.m_contactList; while (ce) { var ce0 = ce; ce = ce.next; this.m_world.destroyContact(ce0.contact); } this.m_contactList = null; var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { var proxyCount = f.m_proxyCount; for (var i = 0; i < proxyCount; ++i) { broadPhase.touchProxy(f.m_proxies[i].proxyId); } } }; Body.prototype.isBullet = function() { return this.m_bulletFlag; }; Body.prototype.setBullet = function(flag) { this.m_bulletFlag = !!flag; }; Body.prototype.isSleepingAllowed = function() { return this.m_autoSleepFlag; }; Body.prototype.setSleepingAllowed = function(flag) { this.m_autoSleepFlag = !!flag; if (this.m_autoSleepFlag == false) { this.setAwake(true); } }; Body.prototype.isAwake = function() { return this.m_awakeFlag; }; Body.prototype.setAwake = function(flag) { if (flag) { if (this.m_awakeFlag == false) { this.m_awakeFlag = true; this.m_sleepTime = 0; } } else { this.m_awakeFlag = false; this.m_sleepTime = 0; this.m_linearVelocity.setZero(); this.m_angularVelocity = 0; this.m_force.setZero(); this.m_torque = 0; } }; Body.prototype.isActive = function() { return this.m_activeFlag; }; Body.prototype.setActive = function(flag) { _ASSERT && common.assert(this.isWorldLocked() == false); if (flag == this.m_activeFlag) { return; } this.m_activeFlag = !!flag; if (this.m_activeFlag) { var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { f.createProxies(broadPhase, this.m_xf); } } else { var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { f.destroyProxies(broadPhase); } var ce = this.m_contactList; while (ce) { var ce0 = ce; ce = ce.next; this.m_world.destroyContact(ce0.contact); } this.m_contactList = null; } }; Body.prototype.isFixedRotation = function() { return this.m_fixedRotationFlag; }; Body.prototype.setFixedRotation = function(flag) { if (this.m_fixedRotationFlag == flag) { return; } this.m_fixedRotationFlag = !!flag; this.m_angularVelocity = 0; this.resetMassData(); }; Body.prototype.getTransform = function() { return this.m_xf; }; Body.prototype.setTransform = function(position, angle) { _ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return; } this.m_xf.set(position, angle); this.m_sweep.setTransform(this.m_xf); var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { f.synchronize(broadPhase, this.m_xf, this.m_xf); } }; Body.prototype.synchronizeTransform = function() { this.m_sweep.getTransform(this.m_xf, 1); }; Body.prototype.synchronizeFixtures = function() { var xf = Transform.identity(); this.m_sweep.getTransform(xf, 0); var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { f.synchronize(broadPhase, xf, this.m_xf); } }; Body.prototype.advance = function(alpha) { this.m_sweep.advance(alpha); this.m_sweep.c.set(this.m_sweep.c0); this.m_sweep.a = this.m_sweep.a0; this.m_sweep.getTransform(this.m_xf, 1); }; Body.prototype.getPosition = function() { return this.m_xf.p; }; Body.prototype.setPosition = function(p) { this.setTransform(p, this.m_sweep.a); }; Body.prototype.getAngle = function() { return this.m_sweep.a; }; Body.prototype.setAngle = function(angle) { this.setTransform(this.m_xf.p, angle); }; Body.prototype.getWorldCenter = function() { return this.m_sweep.c; }; Body.prototype.getLocalCenter = function() { return this.m_sweep.localCenter; }; Body.prototype.getLinearVelocity = function() { return this.m_linearVelocity; }; Body.prototype.getLinearVelocityFromWorldPoint = function(worldPoint) { var localCenter = Vec2.sub(worldPoint, this.m_sweep.c); return Vec2.add(this.m_linearVelocity, Vec2.cross(this.m_angularVelocity, localCenter)); }; Body.prototype.getLinearVelocityFromLocalPoint = function(localPoint) { return this.getLinearVelocityFromWorldPoint(this.getWorldPoint(localPoint)); }; Body.prototype.setLinearVelocity = function(v) { if (this.m_type == staticBody) { return; } if (Vec2.dot(v, v) > 0) { this.setAwake(true); } this.m_linearVelocity.set(v); }; Body.prototype.getAngularVelocity = function() { return this.m_angularVelocity; }; Body.prototype.setAngularVelocity = function(w) { if (this.m_type == staticBody) { return; } if (w * w > 0) { this.setAwake(true); } this.m_angularVelocity = w; }; Body.prototype.getLinearDamping = function() { return this.m_linearDamping; }; Body.prototype.setLinearDamping = function(linearDamping) { this.m_linearDamping = linearDamping; }; Body.prototype.getAngularDamping = function() { return this.m_angularDamping; }; Body.prototype.setAngularDamping = function(angularDamping) { this.m_angularDamping = angularDamping; }; Body.prototype.getGravityScale = function() { return this.m_gravityScale; }; Body.prototype.setGravityScale = function(scale) { this.m_gravityScale = scale; }; Body.prototype.getMass = function() { return this.m_mass; }; Body.prototype.getInertia = function() { return this.m_I + this.m_mass * Vec2.dot(this.m_sweep.localCenter, this.m_sweep.localCenter); }; function MassData() { this.mass = 0; this.center = Vec2.zero(); this.I = 0; } Body.prototype.getMassData = function(data) { data.mass = this.m_mass; data.I = this.getInertia(); data.center.set(this.m_sweep.localCenter); }; Body.prototype.resetMassData = function() { this.m_mass = 0; this.m_invMass = 0; this.m_I = 0; this.m_invI = 0; this.m_sweep.localCenter.setZero(); if (this.isStatic() || this.isKinematic()) { this.m_sweep.c0.set(this.m_xf.p); this.m_sweep.c.set(this.m_xf.p); this.m_sweep.a0 = this.m_sweep.a; return; } _ASSERT && common.assert(this.isDynamic()); var localCenter = Vec2.zero(); for (var f = this.m_fixtureList; f; f = f.m_next) { if (f.m_density == 0) { continue; } var massData = new MassData(); f.getMassData(massData); this.m_mass += massData.mass; localCenter.addMul(massData.mass, massData.center); this.m_I += massData.I; } if (this.m_mass > 0) { this.m_invMass = 1 / this.m_mass; localCenter.mul(this.m_invMass); } else { this.m_mass = 1; this.m_invMass = 1; } if (this.m_I > 0 && this.m_fixedRotationFlag == false) { this.m_I -= this.m_mass * Vec2.dot(localCenter, localCenter); _ASSERT && common.assert(this.m_I > 0); this.m_invI = 1 / this.m_I; } else { this.m_I = 0; this.m_invI = 0; } var oldCenter = Vec2.clone(this.m_sweep.c); this.m_sweep.setLocalCenter(localCenter, this.m_xf); this.m_linearVelocity.add(Vec2.cross(this.m_angularVelocity, Vec2.sub(this.m_sweep.c, oldCenter))); }; Body.prototype.setMassData = function(massData) { _ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return; } if (this.m_type != dynamicBody) { return; } this.m_invMass = 0; this.m_I = 0; this.m_invI = 0; this.m_mass = massData.mass; if (this.m_mass <= 0) { this.m_mass = 1; } this.m_invMass = 1 / this.m_mass; if (massData.I > 0 && this.m_fixedRotationFlag == false) { this.m_I = massData.I - this.m_mass * Vec2.dot(massData.center, massData.center); _ASSERT && common.assert(this.m_I > 0); this.m_invI = 1 / this.m_I; } var oldCenter = Vec2.clone(this.m_sweep.c); this.m_sweep.setLocalCenter(massData.center, this.m_xf); this.m_linearVelocity.add(Vec2.cross(this.m_angularVelocity, Vec2.sub(this.m_sweep.c, oldCenter))); }; Body.prototype.applyForce = function(force, point, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_force.add(force); this.m_torque += Vec2.cross(Vec2.sub(point, this.m_sweep.c), force); } }; Body.prototype.applyForceToCenter = function(force, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_force.add(force); } }; Body.prototype.applyTorque = function(torque, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_torque += torque; } }; Body.prototype.applyLinearImpulse = function(impulse, point, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_linearVelocity.addMul(this.m_invMass, impulse); this.m_angularVelocity += this.m_invI * Vec2.cross(Vec2.sub(point, this.m_sweep.c), impulse); } }; Body.prototype.applyAngularImpulse = function(impulse, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_angularVelocity += this.m_invI * impulse; } }; Body.prototype.shouldCollide = function(that) { if (this.m_type != dynamicBody && that.m_type != dynamicBody) { return false; } for (var jn = this.m_jointList; jn; jn = jn.next) { if (jn.other == that) { if (jn.joint.m_collideConnected == false) { return false; } } } return true; }; Body.prototype.createFixture = function(shape, fixdef) { _ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return null; } var fixture = new Fixture(this, shape, fixdef); if (this.m_activeFlag) { var broadPhase = this.m_world.m_broadPhase; fixture.createProxies(broadPhase, this.m_xf); } fixture.m_next = this.m_fixtureList; this.m_fixtureList = fixture; if (fixture.m_density > 0) { this.resetMassData(); } this.m_world.m_newFixture = true; return fixture; }; Body.prototype.destroyFixture = function(fixture) { _ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return; } _ASSERT && common.assert(fixture.m_body == this); var found = false; if (this.m_fixtureList === fixture) { this.m_fixtureList = fixture.m_next; found = true; } else { var node = this.m_fixtureList; while (node != null) { if (node.m_next === fixture) { node.m_next = fixture.m_next; found = true; break; } node = node.m_next; } } _ASSERT && common.assert(found); var edge = this.m_contactList; while (edge) { var c = edge.contact; edge = edge.next; var fixtureA = c.getFixtureA(); var fixtureB = c.getFixtureB(); if (fixture == fixtureA || fixture == fixtureB) { this.m_world.destroyContact(c); } } if (this.m_activeFlag) { var broadPhase = this.m_world.m_broadPhase; fixture.destroyProxies(broadPhase); } fixture.m_body = null; fixture.m_next = null; this.m_world.publish("remove-fixture", fixture); this.resetMassData(); }; Body.prototype.getWorldPoint = function(localPoint) { return Transform.mulVec2(this.m_xf, localPoint); }; Body.prototype.getWorldVector = function(localVector) { return Rot.mulVec2(this.m_xf.q, localVector); }; Body.prototype.getLocalPoint = function(worldPoint) { return Transform.mulTVec2(this.m_xf, worldPoint); }; Body.prototype.getLocalVector = function(worldVector) { return Rot.mulTVec2(this.m_xf.q, worldVector); }; },{"./Fixture":4,"./Shape":8,"./World":10,"./common/Math":18,"./common/Position":19,"./common/Rot":20,"./common/Sweep":21,"./common/Transform":22,"./common/Vec2":23,"./common/Velocity":25,"./util/common":51,"./util/options":53}],3:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var DEBUG_SOLVER = false; var common = require("./util/common"); var Pool = require("./util/Pool"); var Math = require("./common/Math"); var Vec2 = require("./common/Vec2"); var Transform = require("./common/Transform"); var Mat22 = require("./common/Mat22"); var Rot = require("./common/Rot"); var Settings = require("./Settings"); var Manifold = require("./Manifold"); var Distance = require("./collision/Distance"); module.exports = Contact; function ContactEdge(contact) { this.contact = contact; this.prev = null; this.next = null; this.other = null; } function Contact() { this.m_nodeA = new ContactEdge(this); this.m_nodeB = new ContactEdge(this); this.m_manifold = new Manifold(); this.v_points_cache = [ new VelocityConstraintPoint(), new VelocityConstraintPoint() ]; this.v_points = []; this.v_normal = Vec2.zero(); this.v_normalMass = new Mat22(); this.v_K = new Mat22(); this.p_localPoints_cache = [ Vec2.zero(), Vec2.zero() ]; this.p_localPoints = []; this.p_localNormal = Vec2.zero(); this.p_localPoint = Vec2.zero(); this.p_localCenterA = Vec2.zero(); this.p_localCenterB = Vec2.zero(); } Contact.prototype.init = function(fA, indexA, fB, indexB, evaluateFcn) { this.m_fixtureA = fA; this.m_fixtureB = fB; this.m_indexA = indexA; this.m_indexB = indexB; this.m_evaluateFcn = evaluateFcn; this.m_manifold.init(); this.m_prev = null; this.m_next = null; this.m_toi = 1; this.m_toiCount = 0; this.m_toiFlag = false; this.m_friction = mixFriction(this.m_fixtureA.m_friction, this.m_fixtureB.m_friction); this.m_restitution = mixRestitution(this.m_fixtureA.m_restitution, this.m_fixtureB.m_restitution); this.m_tangentSpeed = 0; this.m_enabledFlag = true; this.m_islandFlag = false; this.m_touchingFlag = false; this.m_filterFlag = false; this.m_bulletHitFlag = false; this.v_points.length = 0; this.v_normal.setZero(); this.v_normalMass.setZero(); this.v_K.setZero(); this.v_pointCount = null; this.v_tangentSpeed = null; this.v_friction = null; this.v_restitution = null; this.v_invMassA = null; this.v_invMassB = null; this.v_invIA = null; this.v_invIB = null; this.p_localPoints.length = 0; this.p_localNormal.setZero(); this.p_localPoint.setZero(); this.p_localCenterA.setZero(); this.p_localCenterB.setZero(); this.p_type = null; this.p_radiusA = null; this.p_radiusB = null; this.p_pointCount = null; this.p_invMassA = null; this.p_invMassB = null; this.p_invIA = null; this.p_invIB = null; }; Contact.prototype.initConstraint = function(step) { var fixtureA = this.m_fixtureA; var fixtureB = this.m_fixtureB; var shapeA = fixtureA.getShape(); var shapeB = fixtureB.getShape(); var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); var manifold = this.m_manifold; var pointCount = manifold.pointCount; _ASSERT && common.assert(pointCount > 0); this.v_invMassA = bodyA.m_invMass; this.v_invMassB = bodyB.m_invMass; this.v_invIA = bodyA.m_invI; this.v_invIB = bodyB.m_invI; this.v_friction = this.m_friction; this.v_restitution = this.m_restitution; this.v_tangentSpeed = this.m_tangentSpeed; this.v_pointCount = pointCount; this.v_K.setZero(); this.v_normalMass.setZero(); this.p_invMassA = bodyA.m_invMass; this.p_invMassB = bodyB.m_invMass; this.p_invIA = bodyA.m_invI; this.p_invIB = bodyB.m_invI; this.p_localCenterA.setVec2(bodyA.m_sweep.localCenter); this.p_localCenterB.setVec2(bodyB.m_sweep.localCenter); this.p_radiusA = shapeA.m_radius; this.p_radiusB = shapeB.m_radius; this.p_type = manifold.type; this.p_localNormal.setVec2(manifold.localNormal); this.p_localPoint.setVec2(manifold.localPoint); this.p_pointCount = pointCount; for (var j = 0; j < pointCount; ++j) { var cp = manifold.points[j]; var vcp = this.v_points[j] = this.v_points_cache[j].init(); if (step.warmStarting) { vcp.normalImpulse = step.dtRatio * cp.normalImpulse; vcp.tangentImpulse = step.dtRatio * cp.tangentImpulse; } else { vcp.normalImpulse = 0; vcp.tangentImpulse = 0; } vcp.rA.setZero(); vcp.rB.setZero(); vcp.normalMass = 0; vcp.tangentMass = 0; vcp.velocityBias = 0; this.p_localPoints[j] = this.p_localPoints_cache[j].setVec2(cp.localPoint); } }; Contact.prototype.getManifold = function() { return this.m_manifold; }; Contact.prototype.getWorldManifold = function(worldManifold) { var bodyA = this.m_fixtureA.getBody(); var bodyB = this.m_fixtureB.getBody(); var shapeA = this.m_fixtureA.getShape(); var shapeB = this.m_fixtureB.getShape(); var manifold = this.m_manifold.getWorldManifold(worldManifold, bodyA.getTransform(), shapeA.m_radius, bodyB.getTransform(), shapeB.m_radius); return manifold; }; Contact.prototype.setEnabled = function(flag) { this.m_enabledFlag = !!flag; }; Contact.prototype.isEnabled = function() { return this.m_enabledFlag; }; Contact.prototype.isTouching = function() { return this.m_touchingFlag; }; Contact.prototype.getNext = function() { return this.m_next; }; Contact.prototype.getFixtureA = function() { return this.m_fixtureA; }; Contact.prototype.getFixtureB = function() { return this.m_fixtureB; }; Contact.prototype.getChildIndexA = function() { return this.m_indexA; }; Contact.prototype.getChildIndexB = function() { return this.m_indexB; }; Contact.prototype.flagForFiltering = function() { this.m_filterFlag = true; }; Contact.prototype.setFriction = function(friction) { this.m_friction = friction; }; Contact.prototype.getFriction = function() { return this.m_friction; }; Contact.prototype.resetFriction = function() { this.m_friction = mixFriction(this.m_fixtureA.m_friction, this.m_fixtureB.m_friction); }; Contact.prototype.setRestitution = function(restitution) { this.m_restitution = restitution; }; Contact.prototype.getRestitution = function() { return this.m_restitution; }; Contact.prototype.resetRestitution = function() { this.m_restitution = mixRestitution(this.m_fixtureA.m_restitution, this.m_fixtureB.m_restitution); }; Contact.prototype.setTangentSpeed = function(speed) { this.m_tangentSpeed = speed; }; Contact.prototype.getTangentSpeed = function() { return this.m_tangentSpeed; }; Contact.prototype.evaluate = function(manifold, xfA, xfB) { this.m_evaluateFcn(manifold, xfA, this.m_fixtureA, this.m_indexA, xfB, this.m_fixtureB, this.m_indexB); }; var cup_manifold = new Manifold(); Contact.prototype.update = function(listener) { this.m_enabledFlag = true; var touching = false; var wasTouching = this.m_touchingFlag; var sensorA = this.m_fixtureA.isSensor(); var sensorB = this.m_fixtureB.isSensor(); var sensor = sensorA || sensorB; var bodyA = this.m_fixtureA.getBody(); var bodyB = this.m_fixtureB.getBody(); var xfA = bodyA.getTransform(); var xfB = bodyB.getTransform(); if (sensor) { var shapeA = this.m_fixtureA.getShape(); var shapeB = this.m_fixtureB.getShape(); touching = Distance.testOverlap(shapeA, this.m_indexA, shapeB, this.m_indexB, xfA, xfB); this.m_manifold.pointCount = 0; } else { var oldManifold = this.m_manifold; this.m_manifold = cup_manifold.init(); cup_manifold = oldManifold; this.evaluate(this.m_manifold, xfA, xfB); touching = this.m_manifold.pointCount > 0; for (var i = 0; i < this.m_manifold.pointCount; ++i) { var nmp = this.m_manifold.points[i]; nmp.normalImpulse = 0; nmp.tangentImpulse = 0; for (var j = 0; j < oldManifold.pointCount; ++j) { var omp = oldManifold.points[j]; if (omp.id.key == nmp.id.key) { nmp.normalImpulse = omp.normalImpulse; nmp.tangentImpulse = omp.tangentImpulse; break; } } } if (touching !== wasTouching) { bodyA.setAwake(true); bodyB.setAwake(true); } } this.m_touchingFlag = touching; if (!wasTouching && touching && listener) { listener.beginContact(this); } if (wasTouching && !touching && listener) { listener.endContact(this); } if (!sensor && touching && listener) { listener.preSolve(this, oldManifold); } }; Contact.prototype.solvePositionConstraint = function(step) { return this._solvePositionConstraint(step, false); }; Contact.prototype.solvePositionConstraintTOI = function(step, toiA, toiB) { return this._solvePositionConstraint(step, true, toiA, toiB); }; var spc_localCenterA = Vec2.zero(); var spc_localCenterB = Vec2.zero(); var spc_cA = Vec2.zero(); var spc_cB = Vec2.zero(); var spc_xfA = Transform.identity(); var spc_xfB = Transform.identity(); var spc_t1 = Vec2.zero(); var spc_t2 = Vec2.zero(); var spc_normal = Vec2.zero(); var spc_point = Vec2.zero(); var spc_pointA = Vec2.zero(); var spc_pointB = Vec2.zero(); var spc_planePoint = Vec2.zero(); var spc_clipPoint = Vec2.zero(); var spc_rA = Vec2.zero(); var spc_rB = Vec2.zero(); var spc_P = Vec2.zero(); Contact.prototype._solvePositionConstraint = function(step, toi, toiA, toiB) { var fixtureA = this.m_fixtureA; var fixtureB = this.m_fixtureB; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); var velocityA = bodyA.c_velocity; var velocityB = bodyB.c_velocity; var positionA = bodyA.c_position; var positionB = bodyB.c_position; var localCenterA = spc_localCenterA.setVec2(this.p_localCenterA); var localCenterB = spc_localCenterB.setVec2(this.p_localCenterB); var mA = 0; var iA = 0; if (!toi || (bodyA === toiA || bodyA === toiB)) { mA = this.p_invMassA; iA = this.p_invIA; } var mB = 0; var iB = 0; if (!toi || (bodyB === toiA || bodyB === toiB)) { mB = this.p_invMassB; iB = this.p_invIB; } var cA = spc_cA.setVec2(positionA.c); var aA = positionA.a; var cB = spc_cB.setVec2(positionB.c); var aB = positionB.a; var minSeparation = 0; for (var j = 0; j < this.p_pointCount; ++j) { var xfA = spc_xfA.setIdentity(); var xfB = spc_xfB.setIdentity(); xfA.q.set(aA); xfB.q.set(aB); xfA.p.setVec2(Vec2.sub_(cA, Rot.mulVec2_(xfA.q, localCenterA, spc_t1), spc_t2)); xfB.p.setVec2(Vec2.sub_(cB, Rot.mulVec2_(xfB.q, localCenterB, spc_t1), spc_t2)); var normal, point, separation; switch (this.p_type) { case Manifold.e_circles: var pointA = Transform.mulVec2_(xfA, this.p_localPoint, spc_pointA); var pointB = Transform.mulVec2_(xfB, this.p_localPoints[0], spc_pointB); normal = Vec2.sub_(pointB, pointA, spc_normal); normal.normalize(); point = Vec2.combine_(.5, pointA, .5, pointB, spc_point); separation = Vec2.dot(Vec2.sub(pointB, pointA), normal) - this.p_radiusA - this.p_radiusB; break; case Manifold.e_faceA: normal = Rot.mulVec2_(xfA.q, this.p_localNormal, spc_normal); var planePoint = Transform.mulVec2_(xfA, this.p_localPoint, spc_planePoint); var clipPoint = Transform.mulVec2_(xfB, this.p_localPoints[j], spc_clipPoint); separation = Vec2.dot(Vec2.sub_(clipPoint, planePoint, spc_t1), normal) - this.p_radiusA - this.p_radiusB; point = spc_point.setVec2(clipPoint); break; case Manifold.e_faceB: normal = Rot.mulVec2_(xfB.q, this.p_localNormal, spc_normal); var planePoint = Transform.mulVec2_(xfB, this.p_localPoint, spc_planePoint); var clipPoint = Transform.mulVec2_(xfA, this.p_localPoints[j], spc_clipPoint); separation = Vec2.dot(Vec2.sub_(clipPoint, planePoint, spc_t1), normal) - this.p_radiusA - this.p_radiusB; point = spc_point.setVec2(clipPoint); normal.mul(-1); break; } var rA = Vec2.sub_(point, cA, spc_rA); var rB = Vec2.sub_(point, cB, spc_rB); minSeparation = Math.min(minSeparation, separation); var baumgarte = toi ? Settings.toiBaugarte : Settings.baumgarte; var linearSlop = Settings.linearSlop; var maxLinearCorrection = Settings.maxLinearCorrection; var C = Math.clamp(baumgarte * (separation + linearSlop), -maxLinearCorrection, 0); var rnA = Vec2.crossVec2Vec2(rA, normal); var rnB = Vec2.crossVec2Vec2(rB, normal); var K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; var impulse = K > 0 ? -C / K : 0; var P = Vec2.mulNumVec2_(impulse, normal, spc_P); cA.subMul(mA, P); aA -= iA * Vec2.crossVec2Vec2(rA, P); cB.addMul(mB, P); aB += iB * Vec2.crossVec2Vec2(rB, P); } positionA.c.setVec2(cA); positionA.a = aA; positionB.c.setVec2(cB); positionB.a = aB; return minSeparation; }; function VelocityConstraintPoint() { this.rA = Vec2.zero(); this.rB = Vec2.zero(); this.normalImpulse = 0; this.tangentImpulse = 0; this.normalMass = 0; this.tangentMass = 0; this.velocityBias = 0; } VelocityConstraintPoint.prototype.init = function() { this.rA.setZero(); this.rB.setZero(); this.normalImpulse = 0; this.tangentImpulse = 0; this.normalMass = 0; this.tangentMass = 0; this.velocityBias = 0; return this; }; var ivc_localCenterA = Vec2.zero(); var ivc_localCenterB = Vec2.zero(); var ivc_normal = Vec2.zero(); var ivc_cA = Vec2.zero(); var ivc_cB = Vec2.zero(); var ivc_vA = Vec2.zero(); var ivc_vB = Vec2.zero(); var ivc_t1 = Vec2.zero(); var ivc_t2 = Vec2.zero(); var ivc_xfA = Transform.identity(); var ivc_xfB = Transform.identity(); Contact.prototype.initVelocityConstraint = function(step) { var fixtureA = this.m_fixtureA; var fixtureB = this.m_fixtureB; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); var velocityA = bodyA.c_velocity; var velocityB = bodyB.c_velocity; var positionA = bodyA.c_position; var positionB = bodyB.c_position; var radiusA = this.p_radiusA; var radiusB = this.p_radiusB; var manifold = this.m_manifold; var mA = this.v_invMassA; var mB = this.v_invMassB; var iA = this.v_invIA; var iB = this.v_invIB; var localCenterA = ivc_localCenterA.setVec2(this.p_localCenterA); var localCenterB = ivc_localCenterB.setVec2(this.p_localCenterB); var cA = ivc_cA.setVec2(positionA.c); var aA = positionA.a; var vA = ivc_vA.setVec2(velocityA.v); var wA = velocityA.w; var cB = ivc_cB.set(positionB.c); var aB = positionB.a; var vB = ivc_vB.set(velocityB.v); var wB = velocityB.w; _ASSERT && common.assert(manifold.pointCount > 0); var xfA = ivc_xfA.setIdentity(); var xfB = ivc_xfB.setIdentity(); xfA.q.set(aA); xfB.q.set(aB); xfA.p.setCombine(1, cA, -1, Rot.mulVec2(xfA.q, localCenterA)); xfB.p.setCombine(1, cB, -1, Rot.mulVec2(xfB.q, localCenterB)); var worldManifold = manifold.getWorldManifold(null, xfA, radiusA, xfB, radiusB); this.v_normal.set(worldManifold.normal); for (var j = 0; j < this.v_pointCount; ++j) { var vcp = this.v_points[j]; vcp.rA.setCombine(1, worldManifold.points[j], -1, cA); vcp.rB.setCombine(1, worldManifold.points[j], -1, cB); var rnA = Vec2.crossVec2Vec2(vcp.rA, this.v_normal); var rnB = Vec2.crossVec2Vec2(vcp.rB, this.v_normal); var kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; vcp.normalMass = kNormal > 0 ? 1 / kNormal : 0; var tangent = Vec2.crossVec2Num_(this.v_normal, 1, ivc_normal); var rtA = Vec2.crossVec2Vec2(vcp.rA, tangent); var rtB = Vec2.crossVec2Vec2(vcp.rB, tangent); var kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; vcp.tangentMass = kTangent > 0 ? 1 / kTangent : 0; vcp.velocityBias = 0; var vRel = Vec2.dot(this.v_normal, vB) + Vec2.dot(this.v_normal, Vec2.crossNumVec2_(wB, vcp.rB, ivc_t1)) - Vec2.dot(this.v_normal, vA) - Vec2.dot(this.v_normal, Vec2.crossNumVec2_(wA, vcp.rA, ivc_t2)); if (vRel < -Settings.velocityThreshold) { vcp.velocityBias = -this.v_restitution * vRel; } } if (this.v_pointCount === 2 && step.blockSolve) { var vcp1 = this.v_points[0]; var vcp2 = this.v_points[1]; var rn1A = Vec2.crossVec2Vec2(vcp1.rA, this.v_normal); var rn1B = Vec2.crossVec2Vec2(vcp1.rB, this.v_normal); var rn2A = Vec2.crossVec2Vec2(vcp2.rA, this.v_normal); var rn2B = Vec2.crossVec2Vec2(vcp2.rB, this.v_normal); var k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B; var k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B; var k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B; var k_maxConditionNumber = 1e3; if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) { this.v_K.ex.set(k11, k12); this.v_K.ey.set(k12, k22); this.v_normalMass.set(this.v_K.getInverse()); } else { this.v_pointCount = 1; } } positionA.c.set(cA); positionA.a = aA; velocityA.v.set(vA); velocityA.w = wA; positionB.c.set(cB); positionB.a = aB; velocityB.v.set(vB); velocityB.w = wB; }; var wsc_vA = Vec2.zero(); var wsc_vB = Vec2.zero(); var wsc_normal = Vec2.zero(); var wsc_P = Vec2.zero(); Contact.prototype.warmStartConstraint = function(step) { var fixtureA = this.m_fixtureA; var fixtureB = this.m_fixtureB; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); var velocityA = bodyA.c_velocity; var velocityB = bodyB.c_velocity; var positionA = bodyA.c_position; var positionB = bodyB.c_position; var mA = this.v_invMassA; var iA = this.v_invIA; var mB = this.v_invMassB; var iB = this.v_invIB; var vA = wsc_vA.set(velocityA.v); var wA = velocityA.w; var vB = wsc_vB.set(velocityB.v); var wB = velocityB.w; var normal = this.v_normal; var tangent = Vec2.crossVec2Num_(normal, 1, wsc_normal); for (var j = 0; j < this.v_pointCount; ++j) { var vcp = this.v_points[j]; var P = wsc_P.setCombine(vcp.normalImpulse, normal, vcp.tangentImpulse, tangent); wA -= iA * Vec2.crossVec2Vec2(vcp.rA, P); vA.subMul(mA, P); wB += iB * Vec2.crossVec2Vec2(vcp.rB, P); vB.addMul(mB, P); } velocityA.v.set(vA); velocityA.w = wA; velocityB.v.set(vB); velocityB.w = wB; }; Contact.prototype.storeConstraintImpulses = function(step) { var manifold = this.m_manifold; for (var j = 0; j < this.v_pointCount; ++j) { manifold.points[j].normalImpulse = this.v_points[j].normalImpulse; manifold.points[j].tangentImpulse = this.v_points[j].tangentImpulse; } }; var svc_vA = Vec2.zero(); var svc_vB = Vec2.zero(); var svc_dv = Vec2.zero(); var svc_P = Vec2.zero(); var svc_tangent = Vec2.zero(); var svc_a = Vec2.zero(); var svc_b = Vec2.zero(); var svc_d = Vec2.zero(); var svc_x = Vec2.zero(); var svc_dv1 = Vec2.zero(); var svc_dv2 = Vec2.zero(); var svc_P1 = Vec2.zero(); var svc_P2 = Vec2.zero(); var svc_t1 = Vec2.zero(); var svc_t2 = Vec2.zero(); Contact.prototype.solveVelocityConstraint = function(step) { var bodyA = this.m_fixtureA.m_body; var bodyB = this.m_fixtureB.m_body; var velocityA = bodyA.c_velocity; var positionA = bodyA.c_position; var velocityB = bodyB.c_velocity; var positionB = bodyB.c_position; var mA = this.v_invMassA; var iA = this.v_invIA; var mB = this.v_invMassB; var iB = this.v_invIB; var vA = svc_vA.setVec2(velocityA.v); var wA = velocityA.w; var vB = svc_vB.setVec2(velocityB.v); var wB = velocityB.w; var normal = this.v_normal; var tangent = Vec2.crossVec2Num_(normal, 1, svc_tangent); var friction = this.v_friction; _ASSERT && common.assert(this.v_pointCount === 1 || this.v_pointCount === 2); for (var j = 0; j < this.v_pointCount; ++j) { var vcp = this.v_points[j]; var dv = svc_dv.setZero(); dv.addCombine(1, vB, 1, Vec2.crossNumVec2_(wB, vcp.rB, svc_t1)); dv.subCombine(1, vA, 1, Vec2.crossNumVec2_(wA, vcp.rA, svc_t1)); var vt = Vec2.dot(dv, tangent) - this.v_tangentSpeed; var lambda = vcp.tangentMass * -vt; var maxFriction = friction * vcp.normalImpulse; var newImpulse = Math.clamp(vcp.tangentImpulse + lambda, -maxFriction, maxFriction); lambda = newImpulse - vcp.tangentImpulse; vcp.tangentImpulse = newImpulse; var P = Vec2.mulNumVec2_(lambda, tangent, svc_P); vA.subMul(mA, P); wA -= iA * Vec2.crossVec2Vec2(vcp.rA, P); vB.addMul(mB, P); wB += iB * Vec2.crossVec2Vec2(vcp.rB, P); } if (this.v_pointCount == 1 || step.blockSolve == false) { for (var i = 0; i < this.v_pointCount; ++i) { var vcp = this.v_points[i]; var dv = svc_dv.setZero(); dv.addCombine(1, vB, 1, Vec2.crossNumVec2_(wB, vcp.rB, svc_t1)); dv.subCombine(1, vA, 1, Vec2.crossNumVec2_(wA, vcp.rA, svc_t1)); var vn = Vec2.dot(dv, normal); var lambda = -vcp.normalMass * (vn - vcp.velocityBias); var newImpulse = Math.max(vcp.normalImpulse + lambda, 0); lambda = newImpulse - vcp.normalImpulse; vcp.normalImpulse = newImpulse; var P = Vec2.mulNumVec2_(lambda, normal, svc_P); vA.subMul(mA, P); wA -= iA * Vec2.crossVec2Vec2(vcp.rA, P); vB.addMul(mB, P); wB += iB * Vec2.crossVec2Vec2(vcp.rB, P); } } else { var vcp1 = this.v_points[0]; var vcp2 = this.v_points[1]; var a = svc_a.set(vcp1.normalImpulse, vcp2.normalImpulse); _ASSERT && common.assert(a.x >= 0 && a.y >= 0); var dv1 = svc_dv1.setZero().add(vB).add(Vec2.crossNumVec2_(wB, vcp1.rB, svc_t1)).sub(vA).sub(Vec2.crossNumVec2_(wA, vcp1.rA, svc_t2)); var dv2 = svc_dv2.setZero().add(vB).add(Vec2.crossNumVec2_(wB, vcp2.rB, svc_t1)).sub(vA).sub(Vec2.crossNumVec2_(wA, vcp2.rA, svc_t2)); var vn1 = Vec2.dot(dv1, normal); var vn2 = Vec2.dot(dv2, normal); var b = svc_b.set(vn1 - vcp1.velocityBias, vn2 - vcp2.velocityBias); b.sub(Mat22.mulVec2_(this.v_K, a, svc_t1)); var k_errorTol = .001; for (;;) { var x = Mat22.mulVec2_(this.v_normalMass, b, svc_x).neg(); if (x.x >= 0 && x.y >= 0) { var d = Vec2.sub_(x, a, svc_d); var P1 = Vec2.mulNumVec2_(d.x, normal, svc_P1); var P2 = Vec2.mulNumVec2_(d.y, normal, svc_P2); vA.subCombine(mA, P1, mA, P2); wA -= iA * (Vec2.crossVec2Vec2(vcp1.rA, P1) + Vec2.crossVec2Vec2(vcp2.rA, P2)); vB.addCombine(mB, P1, mB, P2); wB += iB * (Vec2.crossVec2Vec2(vcp1.rB, P1) + Vec2.crossVec2Vec2(vcp2.rB, P2)); vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; if (DEBUG_SOLVER) { dv1 = vB + Vec2.cross(wB, vcp1.rB) - vA - Vec2.cross(wA, vcp1.rA); dv2 = vB + Vec2.cross(wB, vcp2.rB) - vA - Vec2.cross(wA, vcp2.rA); vn1 = Vec2.dot(dv1, normal); vn2 = Vec2.dot(dv2, normal); _ASSERT && common.assert(Math.abs(vn1 - vcp1.velocityBias) < k_errorTol); _ASSERT && common.assert(Math.abs(vn2 - vcp2.velocityBias) < k_errorTol); } break; } x.x = -vcp1.normalMass * b.x; x.y = 0; vn1 = 0; vn2 = this.v_K.ex.y * x.x + b.y; if (x.x >= 0 && vn2 >= 0) { var d = Vec2.sub_(x, a, svc_d); var P1 = Vec2.mulNumVec2_(d.x, normal, svc_P1); var P2 = Vec2.mulNumVec2_(d.y, normal, svc_P2); vA.subCombine(mA, P1, mA, P2); wA -= iA * (Vec2.crossVec2Vec2(vcp1.rA, P1) + Vec2.crossVec2Vec2(vcp2.rA, P2)); vB.addCombine(mB, P1, mB, P2); wB += iB * (Vec2.crossVec2Vec2(vcp1.rB, P1) + Vec2.crossVec2Vec2(vcp2.rB, P2)); vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; if (DEBUG_SOLVER) { var dv1B = Vec2.add(vB, Vec2.cross(wB, vcp1.rB)); var dv1A = Vec2.add(vA, Vec2.cross(wA, vcp1.rA)); var dv1 = Vec2.sub(dv1B, dv1A); vn1 = Vec2.dot(dv1, normal); _ASSERT && common.assert(Math.abs(vn1 - vcp1.velocityBias) < k_errorTol); } break; } x.x = 0; x.y = -vcp2.normalMass * b.y; vn1 = this.v_K.ey.x * x.y + b.x; vn2 = 0; if (x.y >= 0 && vn1 >= 0) { var d = Vec2.sub_(x, a, svc_d); var P1 = Vec2.mulNumVec2_(d.x, normal, svc_P1); var P2 = Vec2.mulNumVec2_(d.y, normal, svc_P2); vA.subCombine(mA, P1, mA, P2); wA -= iA * (Vec2.crossVec2Vec2(vcp1.rA, P1) + Vec2.crossVec2Vec2(vcp2.rA, P2)); vB.addCombine(mB, P1, mB, P2); wB += iB * (Vec2.crossVec2Vec2(vcp1.rB, P1) + Vec2.crossVec2Vec2(vcp2.rB, P2)); vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; if (DEBUG_SOLVER) { var dv2B = Vec2.add(vB, Vec2.cross(wB, vcp2.rB)); var dv2A = Vec2.add(vA, Vec2.cross(wA, vcp2.rA)); var dv1 = Vec2.sub(dv2B, dv2A); vn2 = Vec2.dot(dv2, normal); _ASSERT && common.assert(Math.abs(vn2 - vcp2.velocityBias) < k_errorTol); } break; } x.x = 0; x.y = 0; vn1 = b.x; vn2 = b.y; if (vn1 >= 0 && vn2 >= 0) { var d = Vec2.sub_(x, a, svc_d); var P1 = Vec2.mulNumVec2_(d.x, normal, svc_P1); var P2 = Vec2.mulNumVec2_(d.y, normal, svc_P2); vA.subCombine(mA, P1, mA, P2); wA -= iA * (Vec2.crossVec2Vec2(vcp1.rA, P1) + Vec2.crossVec2Vec2(vcp2.rA, P2)); vB.addCombine(mB, P1, mB, P2); wB += iB * (Vec2.crossVec2Vec2(vcp1.rB, P1) + Vec2.crossVec2Vec2(vcp2.rB, P2)); vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; break; } break; } } velocityA.v.set(vA); velocityA.w = wA; velocityB.v.set(vB); velocityB.w = wB; }; function mixFriction(friction1, friction2) { return Math.sqrt(friction1 * friction2); } function mixRestitution(restitution1, restitution2) { return restitution1 > restitution2 ? restitution1 : restitution2; } var s_registers = []; var contactPool = new Pool({ create: function() { return new Contact(); } }); Contact.addType = function(type1, type2, callback) { s_registers[type1] = s_registers[type1] || {}; s_registers[type1][type2] = callback; }; Contact.create = function(fixtureA, indexA, fixtureB, indexB) { var typeA = fixtureA.getType(); var typeB = fixtureB.getType(); var contact, evaluateFcn; if (evaluateFcn = s_registers[typeA] && s_registers[typeA][typeB]) { contact = contactPool.allocate(); contact.init(fixtureA, indexA, fixtureB, indexB, evaluateFcn); } else if (evaluateFcn = s_registers[typeB] && s_registers[typeB][typeA]) { contact = contactPool.allocate(); contact.init(fixtureB, indexB, fixtureA, indexA, evaluateFcn); } else { return null; } fixtureA = contact.getFixtureA(); fixtureB = contact.getFixtureB(); indexA = contact.getChildIndexA(); indexB = contact.getChildIndexB(); var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); contact.m_nodeA.contact = contact; contact.m_nodeA.other = bodyB; contact.m_nodeA.prev = null; contact.m_nodeA.next = bodyA.m_contactList; if (bodyA.m_contactList != null) { bodyA.m_contactList.prev = contact.m_nodeA; } bodyA.m_contactList = contact.m_nodeA; contact.m_nodeB.contact = contact; contact.m_nodeB.other = bodyA; contact.m_nodeB.prev = null; contact.m_nodeB.next = bodyB.m_contactList; if (bodyB.m_contactList != null) { bodyB.m_contactList.prev = contact.m_nodeB; } bodyB.m_contactList = contact.m_nodeB; if (!fixtureA.isSensor() && !fixtureB.isSensor()) { bodyA.setAwake(true); bodyB.setAwake(true); } return contact; }; Contact.destroy = function(contact, listener) { var fixtureA = contact.m_fixtureA; var fixtureB = contact.m_fixtureB; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); if (contact.isTouching()) { listener.endContact(contact); } if (contact.m_nodeA.prev) { contact.m_nodeA.prev.next = contact.m_nodeA.next; } if (contact.m_nodeA.next) { contact.m_nodeA.next.prev = contact.m_nodeA.prev; } if (contact.m_nodeA === bodyA.m_contactList) { bodyA.m_contactList = contact.m_nodeA.next; } if (contact.m_nodeB.prev) { contact.m_nodeB.prev.next = contact.m_nodeB.next; } if (contact.m_nodeB.next) { contact.m_nodeB.next.prev = contact.m_nodeB.prev; } if (contact.m_nodeB === bodyB.m_contactList) { bodyB.m_contactList = contact.m_nodeB.next; } if (contact.m_manifold.pointCount > 0 && !fixtureA.isSensor() && !fixtureB.isSensor()) { bodyA.setAwake(true); bodyB.setAwake(true); } var typeA = fixtureA.getType(); var typeB = fixtureB.getType(); var destroyFcn = s_registers[typeA][typeB].destroyFcn; if (typeof destroyFcn === "function") { destroyFcn(contact); } contactPool.release(contact); }; },{"./Manifold":6,"./Settings":7,"./collision/Distance":13,"./common/Mat22":16,"./common/Math":18,"./common/Rot":20,"./common/Transform":22,"./common/Vec2":23,"./util/Pool":49,"./util/common":51}],4:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Fixture; var common = require("./util/common"); var options = require("./util/options"); var Math = require("./common/Math"); var Vec2 = require("./common/Vec2"); var AABB = require("./collision/AABB"); var FixtureDef = { userData: null, friction: .2, restitution: 0, density: 0, isSensor: false, filterGroupIndex: 0, filterCategoryBits: 1, filterMaskBits: 65535 }; function FixtureProxy(fixture, childIndex) { this.aabb = new AABB(); this.fixture = fixture; this.childIndex = childIndex; this.proxyId; } function Fixture(body, shape, def) { if (shape.shape) { def = shape; shape = shape.shape; } else if (typeof def === "number") { def = { density: def }; } def = options(def, FixtureDef); this.m_body = body; this.m_friction = def.friction; this.m_restitution = def.restitution; this.m_density = def.density; this.m_isSensor = def.isSensor; this.m_filterGroupIndex = def.filterGroupIndex; this.m_filterCategoryBits = def.filterCategoryBits; this.m_filterMaskBits = def.filterMaskBits; this.m_shape = shape; this.m_next = null; this.m_proxies = []; this.m_proxyCount = 0; var childCount = this.m_shape.getChildCount(); for (var i = 0; i < childCount; ++i) { this.m_proxies[i] = new FixtureProxy(this, i); } this.m_userData = def.userData; } Fixture.prototype.getType = function() { return this.m_shape.getType(); }; Fixture.prototype.getShape = function() { return this.m_shape; }; Fixture.prototype.isSensor = function() { return this.m_isSensor; }; Fixture.prototype.setSensor = function(sensor) { if (sensor != this.m_isSensor) { this.m_body.setAwake(true); this.m_isSensor = sensor; } }; Fixture.prototype.getUserData = function() { return this.m_userData; }; Fixture.prototype.setUserData = function(data) { this.m_userData = data; }; Fixture.prototype.getBody = function() { return this.m_body; }; Fixture.prototype.getNext = function() { return this.m_next; }; Fixture.prototype.getDensity = function() { return this.m_density; }; Fixture.prototype.setDensity = function(density) { _ASSERT && common.assert(Math.isFinite(density) && density >= 0); this.m_density = density; }; Fixture.prototype.getFriction = function() { return this.m_friction; }; Fixture.prototype.setFriction = function(friction) { this.m_friction = friction; }; Fixture.prototype.getRestitution = function() { return this.m_restitution; }; Fixture.prototype.setRestitution = function(restitution) { this.m_restitution = restitution; }; Fixture.prototype.testPoint = function(p) { return this.m_shape.testPoint(this.m_body.getTransform(), p); }; Fixture.prototype.rayCast = function(output, input, childIndex) { return this.m_shape.rayCast(output, input, this.m_body.getTransform(), childIndex); }; Fixture.prototype.getMassData = function(massData) { this.m_shape.computeMass(massData, this.m_density); }; Fixture.prototype.getAABB = function(childIndex) { _ASSERT && common.assert(0 <= childIndex && childIndex < this.m_proxyCount); return this.m_proxies[childIndex].aabb; }; Fixture.prototype.createProxies = function(broadPhase, xf) { _ASSERT && common.assert(this.m_proxyCount == 0); this.m_proxyCount = this.m_shape.getChildCount(); for (var i = 0; i < this.m_proxyCount; ++i) { var proxy = this.m_proxies[i]; this.m_shape.computeAABB(proxy.aabb, xf, i); proxy.proxyId = broadPhase.createProxy(proxy.aabb, proxy); } }; Fixture.prototype.destroyProxies = function(broadPhase) { for (var i = 0; i < this.m_proxyCount; ++i) { var proxy = this.m_proxies[i]; broadPhase.destroyProxy(proxy.proxyId); proxy.proxyId = null; } this.m_proxyCount = 0; }; Fixture.prototype.synchronize = function(broadPhase, xf1, xf2) { for (var i = 0; i < this.m_proxyCount; ++i) { var proxy = this.m_proxies[i]; var aabb1 = new AABB(); var aabb2 = new AABB(); this.m_shape.computeAABB(aabb1, xf1, proxy.childIndex); this.m_shape.computeAABB(aabb2, xf2, proxy.childIndex); proxy.aabb.combine(aabb1, aabb2); var displacement = Vec2.sub(xf2.p, xf1.p); broadPhase.moveProxy(proxy.proxyId, proxy.aabb, displacement); } }; Fixture.prototype.setFilterData = function(filter) { this.m_filterGroupIndex = filter.groupIndex; this.m_filterCategoryBits = filter.categoryBits; this.m_filterMaskBits = filter.maskBits; this.refilter(); }; Fixture.prototype.getFilterGroupIndex = function() { return this.m_filterGroupIndex; }; Fixture.prototype.getFilterCategoryBits = function() { return this.m_filterCategoryBits; }; Fixture.prototype.getFilterMaskBits = function() { return this.m_filterMaskBits; }; Fixture.prototype.refilter = function() { if (this.m_body == null) { return; } var edge = this.m_body.getContactList(); while (edge) { var contact = edge.contact; var fixtureA = contact.getFixtureA(); var fixtureB = contact.getFixtureB(); if (fixtureA == this || fixtureB == this) { contact.flagForFiltering(); } edge = edge.next; } var world = this.m_body.getWorld(); if (world == null) { return; } var broadPhase = world.m_broadPhase; for (var i = 0; i < this.m_proxyCount; ++i) { broadPhase.touchProxy(this.m_proxies[i].proxyId); } }; Fixture.prototype.shouldCollide = function(that) { if (that.m_filterGroupIndex == this.m_filterGroupIndex && that.m_filterGroupIndex != 0) { return that.m_filterGroupIndex > 0; } var collide = (that.m_filterMaskBits & this.m_filterCategoryBits) != 0 && (that.m_filterCategoryBits & this.m_filterMaskBits) != 0; return collide; }; },{"./collision/AABB":11,"./common/Math":18,"./common/Vec2":23,"./util/common":51,"./util/options":53}],5:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Joint; var common = require("./util/common"); function JointEdge() { this.other = null; this.joint = null; this.prev = null; this.next = null; } var DEFAULTS = { userData: null, collideConnected: false }; function Joint(def, bodyA, bodyB) { bodyA = def.bodyA || bodyA; bodyB = def.bodyB || bodyB; _ASSERT && common.assert(bodyA); _ASSERT && common.assert(bodyB); _ASSERT && common.assert(bodyA != bodyB); this.m_type = "unknown-joint"; this.m_bodyA = bodyA; this.m_bodyB = bodyB; this.m_index = 0; this.m_collideConnected = !!def.collideConnected; this.m_prev = null; this.m_next = null; this.m_edgeA = new JointEdge(); this.m_edgeB = new JointEdge(); this.m_islandFlag = false; this.m_userData = def.userData; } Joint.prototype.isActive = function() { return this.m_bodyA.isActive() && this.m_bodyB.isActive(); }; Joint.prototype.getType = function() { return this.m_type; }; Joint.prototype.getBodyA = function() { return this.m_bodyA; }; Joint.prototype.getBodyB = function() { return this.m_bodyB; }; Joint.prototype.getNext = function() { return this.m_next; }; Joint.prototype.getUserData = function() { return this.m_userData; }; Joint.prototype.setUserData = function(data) { this.m_userData = data; }; Joint.prototype.getCollideConnected = function() { return this.m_collideConnected; }; Joint.prototype.getAnchorA = function() {}; Joint.prototype.getAnchorB = function() {}; Joint.prototype.getReactionForce = function(inv_dt) {}; Joint.prototype.getReactionTorque = function(inv_dt) {}; Joint.prototype.shiftOrigin = function(newOrigin) {}; Joint.prototype.initVelocityConstraints = function(step) {}; Joint.prototype.solveVelocityConstraints = function(step) {}; Joint.prototype.solvePositionConstraints = function(step) {}; },{"./util/common":51}],6:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("./util/common"); var Vec2 = require("./common/Vec2"); var Transform = require("./common/Transform"); var Math = require("./common/Math"); var Rot = require("./common/Rot"); module.exports = Manifold; module.exports.clipSegmentToLine = clipSegmentToLine; module.exports.clipVertex = ClipVertex; module.exports.getPointStates = getPointStates; module.exports.PointState = PointState; Manifold.e_circles = 0; Manifold.e_faceA = 1; Manifold.e_faceB = 2; Manifold.e_vertex = 0; Manifold.e_face = 1; function Manifold() { this.type = -1; this.localNormal = Vec2.zero(); this.localPoint = Vec2.zero(); this.points = [ new ManifoldPoint(), new ManifoldPoint() ]; this.pointCount = 0; } Manifold.prototype.init = function() { this.type = -1; this.localNormal.setZero(); this.localPoint.setZero(); this.points[0].init(); this.points[1].init(); this.pointCount = 0; return this; }; function ManifoldPoint() { this.localPoint = Vec2.zero(); this.normalImpulse = 0; this.tangentImpulse = 0; this.id = new ContactID(); } ManifoldPoint.prototype.init = function() { this.localPoint.setZero(); this.normalImpulse = 0; this.tangentImpulse = 0; this.id.init(); }; function ContactID() { this.cf = new ContactFeature(); } ContactID.prototype.init = function() { this.cf.init(); }; Object.defineProperty(ContactID.prototype, "key", { get: function() { return this.cf.indexA + this.cf.indexB * 4 + this.cf.typeA * 16 + this.cf.typeB * 64; }, enumerable: true, configurable: true }); ContactID.prototype.set = function(o) { this.cf.set(o.cf); }; function ContactFeature() { this.indexA; this.indexB; this.typeA; this.typeB; } ContactFeature.prototype.init = function() { this.indexA = 0; this.indexB = 0; this.typeA = 0; this.typeB = 0; }; ContactFeature.prototype.set = function(o) { this.indexA = o.indexA; this.indexB = o.indexB; this.typeA = o.typeA; this.typeB = o.typeB; }; function WorldManifold() { this.normal; this.points = []; this.separations = []; } Manifold.prototype.getWorldManifold = function(wm, xfA, radiusA, xfB, radiusB) { if (this.pointCount == 0) { return; } wm = wm || new WorldManifold(); var normal = wm.normal; var points = wm.points; var separations = wm.separations; switch (this.type) { case Manifold.e_circles: normal = Vec2.neo(1, 0); var pointA = Transform.mulVec2(xfA, this.localPoint); var pointB = Transform.mulVec2(xfB, this.points[0].localPoint); var dist = Vec2.sub(pointB, pointA); if (Vec2.lengthSquared(dist) > Math.EPSILON * Math.EPSILON) { normal.set(dist); normal.normalize(); } points[0] = Vec2.mid(pointA, pointB); separations[0] = -radiusB - radiusA; points.length = 1; separations.length = 1; break; case Manifold.e_faceA: normal = Rot.mulVec2(xfA.q, this.localNormal); var planePoint = Transform.mulVec2(xfA, this.localPoint); for (var i = 0; i < this.pointCount; ++i) { var clipPoint = Transform.mulVec2(xfB, this.points[i].localPoint); var cA = Vec2.clone(clipPoint).addMul(radiusA - Vec2.dot(Vec2.sub(clipPoint, planePoint), normal), normal); var cB = Vec2.clone(clipPoint).subMul(radiusB, normal); points[i] = Vec2.mid(cA, cB); separations[i] = Vec2.dot(Vec2.sub(cB, cA), normal); } points.length = this.pointCount; separations.length = this.pointCount; break; case Manifold.e_faceB: normal = Rot.mulVec2(xfB.q, this.localNormal); var planePoint = Transform.mulVec2(xfB, this.localPoint); for (var i = 0; i < this.pointCount; ++i) { var clipPoint = Transform.mulVec2(xfA, this.points[i].localPoint); var cB = Vec2.combine(1, clipPoint, radiusB - Vec2.dot(Vec2.sub(clipPoint, planePoint), normal), normal); var cA = Vec2.combine(1, clipPoint, -radiusA, normal); points[i] = Vec2.mid(cA, cB); separations[i] = Vec2.dot(Vec2.sub(cA, cB), normal); } points.length = this.pointCount; separations.length = this.pointCount; normal.mul(-1); break; } wm.normal = normal; wm.points = points; wm.separations = separations; return wm; }; var PointState = { nullState: 0, addState: 1, persistState: 2, removeState: 3 }; function getPointStates(state1, state2, manifold1, manifold2) { for (var i = 0; i < manifold1.pointCount; ++i) { var id = manifold1.points[i].id; state1[i] = PointState.removeState; for (var j = 0; j < manifold2.pointCount; ++j) { if (manifold2.points[j].id.key == id.key) { state1[i] = PointState.persistState; break; } } } for (var i = 0; i < manifold2.pointCount; ++i) { var id = manifold2.points[i].id; state2[i] = PointState.addState; for (var j = 0; j < manifold1.pointCount; ++j) { if (manifold1.points[j].id.key == id.key) { state2[i] = PointState.persistState; break; } } } } function ClipVertex() { this.v = Vec2.zero(); this.id = new ContactID(); } ClipVertex.prototype.set = function(o) { this.v.set(o.v); this.id.set(o.id); }; ClipVertex.prototype.init = function() { this.v.setZero(); this.id.init(); }; function clipSegmentToLine(vOut, vIn, normal, offset, vertexIndexA) { var numOut = 0; var distance0 = Vec2.dot(normal, vIn[0].v) - offset; var distance1 = Vec2.dot(normal, vIn[1].v) - offset; if (distance0 <= 0) vOut[numOut++].set(vIn[0]); if (distance1 <= 0) vOut[numOut++].set(vIn[1]); if (distance0 * distance1 < 0) { var interp = distance0 / (distance0 - distance1); vOut[numOut].v.setCombine(1 - interp, vIn[0].v, interp, vIn[1].v); vOut[numOut].id.cf.indexA = vertexIndexA; vOut[numOut].id.cf.indexB = vIn[0].id.cf.indexB; vOut[numOut].id.cf.typeA = Manifold.e_vertex; vOut[numOut].id.cf.typeB = Manifold.e_face; ++numOut; } return numOut; } },{"./common/Math":18,"./common/Rot":20,"./common/Transform":22,"./common/Vec2":23,"./util/common":51}],7:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = exports; Settings.maxManifoldPoints = 2; Settings.maxPolygonVertices = 12; Settings.aabbExtension = .1; Settings.aabbMultiplier = 2; Settings.linearSlop = .005; Settings.linearSlopSquared = Settings.linearSlop * Settings.linearSlop; Settings.angularSlop = 2 / 180 * Math.PI; Settings.polygonRadius = 2 * Settings.linearSlop; Settings.maxSubSteps = 8; Settings.maxTOIContacts = 32; Settings.maxTOIIterations = 20; Settings.maxDistnceIterations = 20; Settings.velocityThreshold = 1; Settings.maxLinearCorrection = .2; Settings.maxAngularCorrection = 8 / 180 * Math.PI; Settings.maxTranslation = 2; Settings.maxTranslationSquared = Settings.maxTranslation * Settings.maxTranslation; Settings.maxRotation = .5 * Math.PI; Settings.maxRotationSquared = Settings.maxRotation * Settings.maxRotation; Settings.baumgarte = .2; Settings.toiBaugarte = .75; Settings.timeToSleep = .5; Settings.linearSleepTolerance = .01; Settings.linearSleepToleranceSqr = Math.pow(Settings.linearSleepTolerance, 2); Settings.angularSleepTolerance = 2 / 180 * Math.PI; Settings.angularSleepToleranceSqr = Math.pow(Settings.angularSleepTolerance, 2); },{}],8:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Shape; var Math = require("./common/Math"); function Shape() { this.m_type; this.m_radius; } Shape.isValid = function(shape) { return !!shape; }; Shape.prototype.getRadius = function() { return this.m_radius; }; Shape.prototype.getType = function() { return this.m_type; }; Shape.prototype._clone = function() {}; Shape.prototype.getChildCount = function() {}; Shape.prototype.testPoint = function(xf, p) {}; Shape.prototype.rayCast = function(output, input, transform, childIndex) {}; Shape.prototype.computeAABB = function(aabb, xf, childIndex) {}; Shape.prototype.computeMass = function(massData, density) {}; Shape.prototype.computeDistanceProxy = function(proxy) {}; },{"./common/Math":18}],9:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Solver; module.exports.TimeStep = TimeStep; var Settings = require("./Settings"); var common = require("./util/common"); var Vec2 = require("./common/Vec2"); var Math = require("./common/Math"); var Body = require("./Body"); var Contact = require("./Contact"); var Joint = require("./Joint"); var TimeOfImpact = require("./collision/TimeOfImpact"); var TOIInput = TimeOfImpact.Input; var TOIOutput = TimeOfImpact.Output; var Distance = require("./collision/Distance"); var DistanceInput = Distance.Input; var DistanceOutput = Distance.Output; var DistanceProxy = Distance.Proxy; var SimplexCache = Distance.Cache; function TimeStep(dt) { this.dt = 0; this.inv_dt = 0; this.velocityIterations = 0; this.positionIterations = 0; this.warmStarting = false; this.blockSolve = true; this.inv_dt0 = 0; this.dtRatio = 1; } TimeStep.prototype.reset = function(dt) { if (this.dt > 0) { this.inv_dt0 = this.inv_dt; } this.dt = dt; this.inv_dt = dt == 0 ? 0 : 1 / dt; this.dtRatio = dt * this.inv_dt0; }; function Solver(world) { this.m_world = world; this.m_stack = []; this.m_bodies = []; this.m_contacts = []; this.m_joints = []; } Solver.prototype.clear = function() { this.m_stack.length = 0; this.m_bodies.length = 0; this.m_contacts.length = 0; this.m_joints.length = 0; }; Solver.prototype.addBody = function(body) { _ASSERT && common.assert(body instanceof Body, "Not a Body!", body); this.m_bodies.push(body); }; Solver.prototype.addContact = function(contact) { _ASSERT && common.assert(contact instanceof Contact, "Not a Contact!", contact); this.m_contacts.push(contact); }; Solver.prototype.addJoint = function(joint) { _ASSERT && common.assert(joint instanceof Joint, "Not a Joint!", joint); this.m_joints.push(joint); }; Solver.prototype.solveWorld = function(step) { var world = this.m_world; for (var b = world.m_bodyList; b; b = b.m_next) { b.m_islandFlag = false; } for (var c = world.m_contactList; c; c = c.m_next) { c.m_islandFlag = false; } for (var j = world.m_jointList; j; j = j.m_next) { j.m_islandFlag = false; } var stack = this.m_stack; var loop = -1; for (var seed = world.m_bodyList; seed; seed = seed.m_next) { loop++; if (seed.m_islandFlag) { continue; } if (seed.isAwake() == false || seed.isActive() == false) { continue; } if (seed.isStatic()) { continue; } this.clear(); stack.push(seed); seed.m_islandFlag = true; while (stack.length > 0) { var b = stack.pop(); _ASSERT && common.assert(b.isActive() == true); this.addBody(b); b.setAwake(true); if (b.isStatic()) { continue; } for (var ce = b.m_contactList; ce; ce = ce.next) { var contact = ce.contact; if (contact.m_islandFlag) { continue; } if (contact.isEnabled() == false || contact.isTouching() == false) { continue; } var sensorA = contact.m_fixtureA.m_isSensor; var sensorB = contact.m_fixtureB.m_isSensor; if (sensorA || sensorB) { continue; } this.addContact(contact); contact.m_islandFlag = true; var other = ce.other; if (other.m_islandFlag) { continue; } stack.push(other); other.m_islandFlag = true; } for (var je = b.m_jointList; je; je = je.next) { if (je.joint.m_islandFlag == true) { continue; } var other = je.other; if (other.isActive() == false) { continue; } this.addJoint(je.joint); je.joint.m_islandFlag = true; if (other.m_islandFlag) { continue; } stack.push(other); other.m_islandFlag = true; } } this.solveIsland(step); for (var i = 0; i < this.m_bodies.length; ++i) { var b = this.m_bodies[i]; if (b.isStatic()) { b.m_islandFlag = false; } } } }; Solver.prototype.solveIsland = function(step) { var world = this.m_world; var gravity = world.m_gravity; var allowSleep = world.m_allowSleep; var h = step.dt; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; var c = Vec2.clone(body.m_sweep.c); var a = body.m_sweep.a; var v = Vec2.clone(body.m_linearVelocity); var w = body.m_angularVelocity; body.m_sweep.c0.set(body.m_sweep.c); body.m_sweep.a0 = body.m_sweep.a; if (body.isDynamic()) { v.addMul(h * body.m_gravityScale, gravity); v.addMul(h * body.m_invMass, body.m_force); w += h * body.m_invI * body.m_torque; v.mul(1 / (1 + h * body.m_linearDamping)); w *= 1 / (1 + h * body.m_angularDamping); } body.c_position.c = c; body.c_position.a = a; body.c_velocity.v = v; body.c_velocity.w = w; } for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initConstraint(step); } _DEBUG && this.printBodies("M: "); for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initVelocityConstraint(step); } _DEBUG && this.printBodies("R: "); if (step.warmStarting) { for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.warmStartConstraint(step); } } _DEBUG && this.printBodies("Q: "); for (var i = 0; i < this.m_joints.length; ++i) { var joint = this.m_joints[i]; joint.initVelocityConstraints(step); } _DEBUG && this.printBodies("E: "); for (var i = 0; i < step.velocityIterations; ++i) { for (var j = 0; j < this.m_joints.length; ++j) { var joint = this.m_joints[j]; joint.solveVelocityConstraints(step); } for (var j = 0; j < this.m_contacts.length; ++j) { var contact = this.m_contacts[j]; contact.solveVelocityConstraint(step); } } _DEBUG && this.printBodies("D: "); for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.storeConstraintImpulses(step); } _DEBUG && this.printBodies("C: "); for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; var c = Vec2.clone(body.c_position.c); var a = body.c_position.a; var v = Vec2.clone(body.c_velocity.v); var w = body.c_velocity.w; var translation = Vec2.mul(h, v); if (Vec2.lengthSquared(translation) > Settings.maxTranslationSquared) { var ratio = Settings.maxTranslation / translation.length(); v.mul(ratio); } var rotation = h * w; if (rotation * rotation > Settings.maxRotationSquared) { var ratio = Settings.maxRotation / Math.abs(rotation); w *= ratio; } c.addMul(h, v); a += h * w; body.c_position.c.set(c); body.c_position.a = a; body.c_velocity.v.set(v); body.c_velocity.w = w; } _DEBUG && this.printBodies("B: "); var positionSolved = false; for (var i = 0; i < step.positionIterations; ++i) { var minSeparation = 0; for (var j = 0; j < this.m_contacts.length; ++j) { var contact = this.m_contacts[j]; var separation = contact.solvePositionConstraint(step); minSeparation = Math.min(minSeparation, separation); } var contactsOkay = minSeparation >= -3 * Settings.linearSlop; var jointsOkay = true; for (var j = 0; j < this.m_joints.length; ++j) { var joint = this.m_joints[j]; var jointOkay = joint.solvePositionConstraints(step); jointsOkay = jointsOkay && jointOkay; } if (contactsOkay && jointsOkay) { positionSolved = true; break; } } _DEBUG && this.printBodies("L: "); for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; body.m_sweep.c.set(body.c_position.c); body.m_sweep.a = body.c_position.a; body.m_linearVelocity.set(body.c_velocity.v); body.m_angularVelocity = body.c_velocity.w; body.synchronizeTransform(); } this.postSolveIsland(); if (allowSleep) { var minSleepTime = Infinity; var linTolSqr = Settings.linearSleepToleranceSqr; var angTolSqr = Settings.angularSleepToleranceSqr; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; if (body.isStatic()) { continue; } if (body.m_autoSleepFlag == false || body.m_angularVelocity * body.m_angularVelocity > angTolSqr || Vec2.lengthSquared(body.m_linearVelocity) > linTolSqr) { body.m_sleepTime = 0; minSleepTime = 0; } else { body.m_sleepTime += h; minSleepTime = Math.min(minSleepTime, body.m_sleepTime); } } if (minSleepTime >= Settings.timeToSleep && positionSolved) { for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; body.setAwake(false); } } } }; Solver.prototype.printBodies = function(tag) { for (var i = 0; i < this.m_bodies.length; ++i) { var b = this.m_bodies[i]; common.debug(tag, b.c_position.a, b.c_position.c.x, b.c_position.c.y, b.c_velocity.w, b.c_velocity.v.x, b.c_velocity.v.y); } }; var s_subStep = new TimeStep(); Solver.prototype.solveWorldTOI = function(step) { var world = this.m_world; if (world.m_stepComplete) { for (var b = world.m_bodyList; b; b = b.m_next) { b.m_islandFlag = false; b.m_sweep.alpha0 = 0; } for (var c = world.m_contactList; c; c = c.m_next) { c.m_toiFlag = false; c.m_islandFlag = false; c.m_toiCount = 0; c.m_toi = 1; } } for (;;) { var minContact = null; var minAlpha = 1; for (var c = world.m_contactList; c; c = c.m_next) { if (c.isEnabled() == false) { continue; } if (c.m_toiCount > Settings.maxSubSteps) { continue; } var alpha = 1; if (c.m_toiFlag) { alpha = c.m_toi; } else { var fA = c.getFixtureA(); var fB = c.getFixtureB(); if (fA.isSensor() || fB.isSensor()) { continue; } var bA = fA.getBody(); var bB = fB.getBody(); _ASSERT && common.assert(bA.isDynamic() || bB.isDynamic()); var activeA = bA.isAwake() && !bA.isStatic(); var activeB = bB.isAwake() && !bB.isStatic(); if (activeA == false && activeB == false) { continue; } var collideA = bA.isBullet() || !bA.isDynamic(); var collideB = bB.isBullet() || !bB.isDynamic(); if (collideA == false && collideB == false) { continue; } var alpha0 = bA.m_sweep.alpha0; if (bA.m_sweep.alpha0 < bB.m_sweep.alpha0) { alpha0 = bB.m_sweep.alpha0; bA.m_sweep.advance(alpha0); } else if (bB.m_sweep.alpha0 < bA.m_sweep.alpha0) { alpha0 = bA.m_sweep.alpha0; bB.m_sweep.advance(alpha0); } _ASSERT && common.assert(alpha0 < 1); var indexA = c.getChildIndexA(); var indexB = c.getChildIndexB(); var sweepA = bA.m_sweep; var sweepB = bB.m_sweep; var input = new TOIInput(); input.proxyA.set(fA.getShape(), indexA); input.proxyB.set(fB.getShape(), indexB); input.sweepA.set(bA.m_sweep); input.sweepB.set(bB.m_sweep); input.tMax = 1; var output = new TOIOutput(); TimeOfImpact(output, input); var beta = output.t; if (output.state == TOIOutput.e_touching) { alpha = Math.min(alpha0 + (1 - alpha0) * beta, 1); } else { alpha = 1; } c.m_toi = alpha; c.m_toiFlag = true; } if (alpha < minAlpha) { minContact = c; minAlpha = alpha; } } if (minContact == null || 1 - 10 * Math.EPSILON < minAlpha) { world.m_stepComplete = true; break; } var fA = minContact.getFixtureA(); var fB = minContact.getFixtureB(); var bA = fA.getBody(); var bB = fB.getBody(); var backup1 = bA.m_sweep.clone(); var backup2 = bB.m_sweep.clone(); bA.advance(minAlpha); bB.advance(minAlpha); minContact.update(world); minContact.m_toiFlag = false; ++minContact.m_toiCount; if (minContact.isEnabled() == false || minContact.isTouching() == false) { minContact.setEnabled(false); bA.m_sweep.set(backup1); bB.m_sweep.set(backup2); bA.synchronizeTransform(); bB.synchronizeTransform(); continue; } bA.setAwake(true); bB.setAwake(true); this.clear(); this.addBody(bA); this.addBody(bB); this.addContact(minContact); bA.m_islandFlag = true; bB.m_islandFlag = true; minContact.m_islandFlag = true; var bodies = [ bA, bB ]; for (var i = 0; i < bodies.length; ++i) { var body = bodies[i]; if (body.isDynamic()) { for (var ce = body.m_contactList; ce; ce = ce.next) { var contact = ce.contact; if (contact.m_islandFlag) { continue; } var other = ce.other; if (other.isDynamic() && !body.isBullet() && !other.isBullet()) { continue; } var sensorA = contact.m_fixtureA.m_isSensor; var sensorB = contact.m_fixtureB.m_isSensor; if (sensorA || sensorB) { continue; } var backup = other.m_sweep.clone(); if (other.m_islandFlag == false) { other.advance(minAlpha); } contact.update(world); if (contact.isEnabled() == false || contact.isTouching() == false) { other.m_sweep.set(backup); other.synchronizeTransform(); continue; } contact.m_islandFlag = true; this.addContact(contact); if (other.m_islandFlag) { continue; } other.m_islandFlag = true; if (!other.isStatic()) { other.setAwake(true); } this.addBody(other); } } } s_subStep.reset((1 - minAlpha) * step.dt); s_subStep.dtRatio = 1; s_subStep.positionIterations = 20; s_subStep.velocityIterations = step.velocityIterations; s_subStep.warmStarting = false; this.solveIslandTOI(s_subStep, bA, bB); for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; body.m_islandFlag = false; if (!body.isDynamic()) { continue; } body.synchronizeFixtures(); for (var ce = body.m_contactList; ce; ce = ce.next) { ce.contact.m_toiFlag = false; ce.contact.m_islandFlag = false; } } world.findNewContacts(); if (world.m_subStepping) { world.m_stepComplete = false; break; } } if (_DEBUG) for (var b = world.m_bodyList; b; b = b.m_next) { var c = b.m_sweep.c; var a = b.m_sweep.a; var v = b.m_linearVelocity; var w = b.m_angularVelocity; } }; Solver.prototype.solveIslandTOI = function(subStep, toiA, toiB) { var world = this.m_world; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; body.c_position.c.set(body.m_sweep.c); body.c_position.a = body.m_sweep.a; body.c_velocity.v.set(body.m_linearVelocity); body.c_velocity.w = body.m_angularVelocity; } for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initConstraint(subStep); } for (var i = 0; i < subStep.positionIterations; ++i) { var minSeparation = 0; for (var j = 0; j < this.m_contacts.length; ++j) { var contact = this.m_contacts[j]; var separation = contact.solvePositionConstraintTOI(subStep, toiA, toiB); minSeparation = Math.min(minSeparation, separation); } var contactsOkay = minSeparation >= -1.5 * Settings.linearSlop; if (contactsOkay) { break; } } if (false) { for (var i = 0; i < this.m_contacts.length; ++i) { var c = this.m_contacts[i]; var fA = c.getFixtureA(); var fB = c.getFixtureB(); var bA = fA.getBody(); var bB = fB.getBody(); var indexA = c.getChildIndexA(); var indexB = c.getChildIndexB(); var input = new DistanceInput(); input.proxyA.set(fA.getShape(), indexA); input.proxyB.set(fB.getShape(), indexB); input.transformA = bA.getTransform(); input.transformB = bB.getTransform(); input.useRadii = false; var output = new DistanceOutput(); var cache = new SimplexCache(); Distance(output, cache, input); if (output.distance == 0 || cache.count == 3) { cache.count += 0; } } } toiA.m_sweep.c0.set(toiA.c_position.c); toiA.m_sweep.a0 = toiA.c_position.a; toiB.m_sweep.c0.set(toiB.c_position.c); toiB.m_sweep.a0 = toiB.c_position.a; for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initVelocityConstraint(subStep); } for (var i = 0; i < subStep.velocityIterations; ++i) { for (var j = 0; j < this.m_contacts.length; ++j) { var contact = this.m_contacts[j]; contact.solveVelocityConstraint(subStep); } } var h = subStep.dt; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; var c = Vec2.clone(body.c_position.c); var a = body.c_position.a; var v = Vec2.clone(body.c_velocity.v); var w = body.c_velocity.w; var translation = Vec2.mul(h, v); if (Vec2.dot(translation, translation) > Settings.maxTranslationSquared) { var ratio = Settings.maxTranslation / translation.length(); v.mul(ratio); } var rotation = h * w; if (rotation * rotation > Settings.maxRotationSquared) { var ratio = Settings.maxRotation / Math.abs(rotation); w *= ratio; } c.addMul(h, v); a += h * w; body.c_position.c = c; body.c_position.a = a; body.c_velocity.v = v; body.c_velocity.w = w; body.m_sweep.c = c; body.m_sweep.a = a; body.m_linearVelocity = v; body.m_angularVelocity = w; body.synchronizeTransform(); } this.postSolveIsland(); }; function ContactImpulse() { this.normalImpulses = []; this.tangentImpulses = []; } Solver.prototype.postSolveIsland = function() { var impulse = new ContactImpulse(); for (var c = 0; c < this.m_contacts.length; ++c) { var contact = this.m_contacts[c]; for (var p = 0; p < contact.v_points.length; ++p) { impulse.normalImpulses.push(contact.v_points[p].normalImpulse); impulse.tangentImpulses.push(contact.v_points[p].tangentImpulse); } this.m_world.postSolve(contact, impulse); } }; },{"./Body":2,"./Contact":3,"./Joint":5,"./Settings":7,"./collision/Distance":13,"./collision/TimeOfImpact":15,"./common/Math":18,"./common/Vec2":23,"./util/common":51}],10:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = World; var options = require("./util/options"); var common = require("./util/common"); var Vec2 = require("./common/Vec2"); var BroadPhase = require("./collision/BroadPhase"); var Solver = require("./Solver"); var Body = require("./Body"); var Contact = require("./Contact"); var WorldDef = { gravity: Vec2.zero(), allowSleep: true, warmStarting: true, continuousPhysics: true, subStepping: false, blockSolve: true, velocityIterations: 8, positionIterations: 3 }; function World(def) { if (!(this instanceof World)) { return new World(def); } if (def && Vec2.isValid(def)) { def = { gravity: def }; } def = options(def, WorldDef); this.m_solver = new Solver(this); this.m_broadPhase = new BroadPhase(); this.m_contactList = null; this.m_contactCount = 0; this.m_bodyList = null; this.m_bodyCount = 0; this.m_jointList = null; this.m_jointCount = 0; this.m_stepComplete = true; this.m_allowSleep = def.allowSleep; this.m_gravity = Vec2.clone(def.gravity); this.m_clearForces = true; this.m_newFixture = false; this.m_locked = false; this.m_warmStarting = def.warmStarting; this.m_continuousPhysics = def.continuousPhysics; this.m_subStepping = def.subStepping; this.m_blockSolve = def.blockSolve; this.m_velocityIterations = def.velocityIterations; this.m_positionIterations = def.positionIterations; this.m_t = 0; this.m_stepCount = 0; this.addPair = this.createContact.bind(this); } World.prototype.getBodyList = function() { return this.m_bodyList; }; World.prototype.getJointList = function() { return this.m_jointList; }; World.prototype.getContactList = function() { return this.m_contactList; }; World.prototype.getBodyCount = function() { return this.m_bodyCount; }; World.prototype.getJointCount = function() { return this.m_jointCount; }; World.prototype.getContactCount = function() { return this.m_contactCount; }; World.prototype.setGravity = function(gravity) { this.m_gravity = gravity; }; World.prototype.getGravity = function() { return this.m_gravity; }; World.prototype.isLocked = function() { return this.m_locked; }; World.prototype.setAllowSleeping = function(flag) { if (flag == this.m_allowSleep) { return; } this.m_allowSleep = flag; if (this.m_allowSleep == false) { for (var b = this.m_bodyList; b; b = b.m_next) { b.setAwake(true); } } }; World.prototype.getAllowSleeping = function() { return this.m_allowSleep; }; World.prototype.setWarmStarting = function(flag) { this.m_warmStarting = flag; }; World.prototype.getWarmStarting = function() { return this.m_warmStarting; }; World.prototype.setContinuousPhysics = function(flag) { this.m_continuousPhysics = flag; }; World.prototype.getContinuousPhysics = function() { return this.m_continuousPhysics; }; World.prototype.setSubStepping = function(flag) { this.m_subStepping = flag; }; World.prototype.getSubStepping = function() { return this.m_subStepping; }; World.prototype.setAutoClearForces = function(flag) { this.m_clearForces = flag; }; World.prototype.getAutoClearForces = function() { return this.m_clearForces; }; World.prototype.clearForces = function() { for (var body = this.m_bodyList; body; body = body.getNext()) { body.m_force.setZero(); body.m_torque = 0; } }; World.prototype.queryAABB = function(aabb, queryCallback) { _ASSERT && common.assert(typeof queryCallback === "function"); var broadPhase = this.m_broadPhase; this.m_broadPhase.query(aabb, function(proxyId) { var proxy = broadPhase.getUserData(proxyId); return queryCallback(proxy.fixture); }); }; World.prototype.rayCast = function(point1, point2, reportFixtureCallback) { _ASSERT && common.assert(typeof reportFixtureCallback === "function"); var broadPhase = this.m_broadPhase; this.m_broadPhase.rayCast({ maxFraction: 1, p1: point1, p2: point2 }, function(input, proxyId) { var proxy = broadPhase.getUserData(proxyId); var fixture = proxy.fixture; var index = proxy.childIndex; var output = {}; var hit = fixture.rayCast(output, input, index); if (hit) { var fraction = output.fraction; var point = Vec2.add(Vec2.mul(1 - fraction, input.p1), Vec2.mul(fraction, input.p2)); return reportFixtureCallback(fixture, point, output.normal, fraction); } return input.maxFraction; }); }; World.prototype.getProxyCount = function() { return this.m_broadPhase.getProxyCount(); }; World.prototype.getTreeHeight = function() { return this.m_broadPhase.getTreeHeight(); }; World.prototype.getTreeBalance = function() { return this.m_broadPhase.getTreeBalance(); }; World.prototype.getTreeQuality = function() { return this.m_broadPhase.getTreeQuality(); }; World.prototype.shiftOrigin = function(newOrigin) { _ASSERT && common.assert(this.m_locked == false); if (this.m_locked) { return; } for (var b = this.m_bodyList; b; b = b.m_next) { b.m_xf.p.sub(newOrigin); b.m_sweep.c0.sub(newOrigin); b.m_sweep.c.sub(newOrigin); } for (var j = this.m_jointList; j; j = j.m_next) { j.shiftOrigin(newOrigin); } this.m_broadPhase.shiftOrigin(newOrigin); }; World.prototype.createBody = function(def, angle) { _ASSERT && common.assert(this.isLocked() == false); if (this.isLocked()) { return null; } if (def && Vec2.isValid(def)) { def = { position: def, angle: angle }; } var body = new Body(this, def); body.m_prev = null; body.m_next = this.m_bodyList; if (this.m_bodyList) { this.m_bodyList.m_prev = body; } this.m_bodyList = body; ++this.m_bodyCount; return body; }; World.prototype.createDynamicBody = function(def, angle) { if (!def) { def = {}; } else if (Vec2.isValid(def)) { def = { position: def, angle: angle }; } def.type = "dynamic"; return this.createBody(def); }; World.prototype.createKinematicBody = function(def, angle) { if (!def) { def = {}; } else if (Vec2.isValid(def)) { def = { position: def, angle: angle }; } def.type = "kinematic"; return this.createBody(def); }; World.prototype.destroyBody = function(b) { _ASSERT && common.assert(this.m_bodyCount > 0); _ASSERT && common.assert(this.isLocked() == false); if (this.isLocked()) { return; } if (b.m_destroyed) { return false; } var je = b.m_jointList; while (je) { var je0 = je; je = je.next; this.publish("remove-joint", je0.joint); this.destroyJoint(je0.joint); b.m_jointList = je; } b.m_jointList = null; var ce = b.m_contactList; while (ce) { var ce0 = ce; ce = ce.next; this.destroyContact(ce0.contact); b.m_contactList = ce; } b.m_contactList = null; var f = b.m_fixtureList; while (f) { var f0 = f; f = f.m_next; this.publish("remove-fixture", f0); f0.destroyProxies(this.m_broadPhase); b.m_fixtureList = f; } b.m_fixtureList = null; if (b.m_prev) { b.m_prev.m_next = b.m_next; } if (b.m_next) { b.m_next.m_prev = b.m_prev; } if (b == this.m_bodyList) { this.m_bodyList = b.m_next; } b.m_destroyed = true; --this.m_bodyCount; this.publish("remove-body", b); return true; }; World.prototype.createJoint = function(joint) { _ASSERT && common.assert(!!joint.m_bodyA); _ASSERT && common.assert(!!joint.m_bodyB); _ASSERT && common.assert(this.isLocked() == false); if (this.isLocked()) { return null; } joint.m_prev = null; joint.m_next = this.m_jointList; if (this.m_jointList) { this.m_jointList.m_prev = joint; } this.m_jointList = joint; ++this.m_jointCount; joint.m_edgeA.joint = joint; joint.m_edgeA.other = joint.m_bodyB; joint.m_edgeA.prev = null; joint.m_edgeA.next = joint.m_bodyA.m_jointList; if (joint.m_bodyA.m_jointList) joint.m_bodyA.m_jointList.prev = joint.m_edgeA; joint.m_bodyA.m_jointList = joint.m_edgeA; joint.m_edgeB.joint = joint; joint.m_edgeB.other = joint.m_bodyA; joint.m_edgeB.prev = null; joint.m_edgeB.next = joint.m_bodyB.m_jointList; if (joint.m_bodyB.m_jointList) joint.m_bodyB.m_jointList.prev = joint.m_edgeB; joint.m_bodyB.m_jointList = joint.m_edgeB; if (joint.m_collideConnected == false) { for (var edge = joint.m_bodyB.getContactList(); edge; edge = edge.next) { if (edge.other == joint.m_bodyA) { edge.contact.flagForFiltering(); } } } return joint; }; World.prototype.destroyJoint = function(joint) { _ASSERT && common.assert(this.isLocked() == false); if (this.isLocked()) { return; } if (joint.m_prev) { joint.m_prev.m_next = joint.m_next; } if (joint.m_next) { joint.m_next.m_prev = joint.m_prev; } if (joint == this.m_jointList) { this.m_jointList = joint.m_next; } var bodyA = joint.m_bodyA; var bodyB = joint.m_bodyB; bodyA.setAwake(true); bodyB.setAwake(true); if (joint.m_edgeA.prev) { joint.m_edgeA.prev.next = joint.m_edgeA.next; } if (joint.m_edgeA.next) { joint.m_edgeA.next.prev = joint.m_edgeA.prev; } if (joint.m_edgeA == bodyA.m_jointList) { bodyA.m_jointList = joint.m_edgeA.next; } joint.m_edgeA.prev = null; joint.m_edgeA.next = null; if (joint.m_edgeB.prev) { joint.m_edgeB.prev.next = joint.m_edgeB.next; } if (joint.m_edgeB.next) { joint.m_edgeB.next.prev = joint.m_edgeB.prev; } if (joint.m_edgeB == bodyB.m_jointList) { bodyB.m_jointList = joint.m_edgeB.next; } joint.m_edgeB.prev = null; joint.m_edgeB.next = null; _ASSERT && common.assert(this.m_jointCount > 0); --this.m_jointCount; if (joint.m_collideConnected == false) { var edge = bodyB.getContactList(); while (edge) { if (edge.other == bodyA) { edge.contact.flagForFiltering(); } edge = edge.next; } } this.publish("remove-joint", joint); }; var s_step = new Solver.TimeStep(); World.prototype.step = function(timeStep, velocityIterations, positionIterations) { if ((velocityIterations | 0) !== velocityIterations) { velocityIterations = 0; } velocityIterations = velocityIterations || this.m_velocityIterations; positionIterations = positionIterations || this.m_positionIterations; this.m_stepCount++; if (this.m_newFixture) { this.findNewContacts(); this.m_newFixture = false; } this.m_locked = true; s_step.reset(timeStep); s_step.velocityIterations = velocityIterations; s_step.positionIterations = positionIterations; s_step.warmStarting = this.m_warmStarting; s_step.blockSolve = this.m_blockSolve; this.updateContacts(); if (this.m_stepComplete && timeStep > 0) { this.m_solver.solveWorld(s_step); for (var b = this.m_bodyList; b; b = b.getNext()) { if (b.m_islandFlag == false) { continue; } if (b.isStatic()) { continue; } b.synchronizeFixtures(); } this.findNewContacts(); } if (this.m_continuousPhysics && timeStep > 0) { this.m_solver.solveWorldTOI(s_step); } if (this.m_clearForces) { this.clearForces(); } this.m_locked = false; }; World.prototype.findNewContacts = function() { this.m_broadPhase.updatePairs(this.addPair); }; World.prototype.createContact = function(proxyA, proxyB) { var fixtureA = proxyA.fixture; var fixtureB = proxyB.fixture; var indexA = proxyA.childIndex; var indexB = proxyB.childIndex; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); if (bodyA === bodyB) { return; } var edge = bodyB.getContactList(); while (edge) { if (edge.other === bodyA) { var fA = edge.contact.getFixtureA(); var fB = edge.contact.getFixtureB(); var iA = edge.contact.getChildIndexA(); var iB = edge.contact.getChildIndexB(); if (fA === fixtureA && fB === fixtureB && iA === indexA && iB === indexB) { return; } if (fA === fixtureB && fB === fixtureA && iA === indexB && iB === indexA) { return; } } edge = edge.next; } if (bodyB.shouldCollide(bodyA) === false) { return; } if (fixtureB.shouldCollide(fixtureA) === false) { return; } var contact = Contact.create(fixtureA, indexA, fixtureB, indexB); if (contact == null) { return; } contact.m_prev = null; if (this.m_contactList != null) { contact.m_next = this.m_contactList; this.m_contactList.m_prev = contact; } this.m_contactList = contact; ++this.m_contactCount; }; World.prototype.updateContacts = function() { var c, next_c = this.m_contactList; while (c = next_c) { next_c = c.getNext(); var fixtureA = c.getFixtureA(); var fixtureB = c.getFixtureB(); var indexA = c.getChildIndexA(); var indexB = c.getChildIndexB(); var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); if (c.m_filterFlag) { if (bodyB.shouldCollide(bodyA) == false) { this.destroyContact(c); continue; } if (fixtureB.shouldCollide(fixtureA) == false) { this.destroyContact(c); continue; } c.m_filterFlag = false; } var activeA = bodyA.isAwake() && !bodyA.isStatic(); var activeB = bodyB.isAwake() && !bodyB.isStatic(); if (activeA == false && activeB == false) { continue; } var proxyIdA = fixtureA.m_proxies[indexA].proxyId; var proxyIdB = fixtureB.m_proxies[indexB].proxyId; var overlap = this.m_broadPhase.testOverlap(proxyIdA, proxyIdB); if (overlap == false) { this.destroyContact(c); continue; } c.update(this); } }; World.prototype.destroyContact = function(contact) { Contact.destroy(contact, this); if (contact.m_prev) { contact.m_prev.m_next = contact.m_next; } if (contact.m_next) { contact.m_next.m_prev = contact.m_prev; } if (contact == this.m_contactList) { this.m_contactList = contact.m_next; } --this.m_contactCount; }; World.prototype._listeners = null; World.prototype.on = function(name, listener) { if (typeof name !== "string" || typeof listener !== "function") { return this; } if (!this._listeners) { this._listeners = {}; } if (!this._listeners[name]) { this._listeners[name] = []; } this._listeners[name].push(listener); return this; }; World.prototype.off = function(name, listener) { if (typeof name !== "string" || typeof listener !== "function") { return this; } var listeners = this._listeners && this._listeners[name]; if (!listeners || !listeners.length) { return this; } var index = listeners.indexOf(listener); if (index >= 0) { listeners.splice(index, 1); } return this; }; World.prototype.publish = function(name, arg1, arg2, arg3) { var listeners = this._listeners && this._listeners[name]; if (!listeners || !listeners.length) { return 0; } for (var l = 0; l < listeners.length; l++) { listeners[l].call(this, arg1, arg2, arg3); } return listeners.length; }; World.prototype.beginContact = function(contact) { this.publish("begin-contact", contact); }; World.prototype.endContact = function(contact) { this.publish("end-contact", contact); }; World.prototype.preSolve = function(contact, oldManifold) { this.publish("pre-solve", contact, oldManifold); }; World.prototype.postSolve = function(contact, impulse) { this.publish("post-solve", contact, impulse); }; },{"./Body":2,"./Contact":3,"./Solver":9,"./collision/BroadPhase":12,"./common/Vec2":23,"./util/common":51,"./util/options":53}],11:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); module.exports = AABB; function AABB(lower, upper) { if (!(this instanceof AABB)) { return new AABB(lower, upper); } this.lowerBound = Vec2.zero(); this.upperBound = Vec2.zero(); if (typeof lower === "object") { this.lowerBound.set(lower); } if (typeof upper === "object") { this.upperBound.set(upper); } } AABB.prototype.isValid = function() { return AABB.isValid(this); }; AABB.isValid = function(aabb) { var d = Vec2.sub(aabb.upperBound, aabb.lowerBound); var valid = d.x >= 0 && d.y >= 0 && Vec2.isValid(aabb.lowerBound) && Vec2.isValid(aabb.upperBound); return valid; }; AABB.assert = function(o) { if (!_ASSERT) return; if (!AABB.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid AABB!"); } }; AABB.prototype.getCenter = function() { return Vec2.neo((this.lowerBound.x + this.upperBound.x) * .5, (this.lowerBound.y + this.upperBound.y) * .5); }; AABB.prototype.getExtents = function() { return Vec2.neo((this.upperBound.x - this.lowerBound.x) * .5, (this.upperBound.y - this.lowerBound.y) * .5); }; AABB.prototype.getPerimeter = function() { return 2 * (this.upperBound.x - this.lowerBound.x + this.upperBound.y - this.lowerBound.y); }; AABB.prototype.combine = function(a, b) { var lowerA = a.lowerBound; var upperA = a.upperBound; var lowerB = b.lowerBound; var upperB = b.upperBound; var lowerX = Math.min(lowerA.x, lowerB.x); var lowerY = Math.min(lowerA.y, lowerB.y); var upperX = Math.max(upperB.x, upperA.x); var upperY = Math.max(upperB.y, upperA.y); this.lowerBound.set(lowerX, lowerY); this.upperBound.set(upperX, upperY); }; AABB.prototype.combinePoints = function(a, b) { this.lowerBound.set(Math.min(a.x, b.x), Math.min(a.y, b.y)); this.upperBound.set(Math.max(a.x, b.x), Math.max(a.y, b.y)); }; AABB.prototype.set = function(aabb) { this.lowerBound.set(aabb.lowerBound.x, aabb.lowerBound.y); this.upperBound.set(aabb.upperBound.x, aabb.upperBound.y); }; AABB.prototype.contains = function(aabb) { var result = true; result = result && this.lowerBound.x <= aabb.lowerBound.x; result = result && this.lowerBound.y <= aabb.lowerBound.y; result = result && aabb.upperBound.x <= this.upperBound.x; result = result && aabb.upperBound.y <= this.upperBound.y; return result; }; AABB.prototype.extend = function(value) { AABB.extend(this, value); }; AABB.extend = function(aabb, value) { aabb.lowerBound.x -= value; aabb.lowerBound.y -= value; aabb.upperBound.x += value; aabb.upperBound.y += value; }; AABB.testOverlap = function(a, b) { var d1x = b.lowerBound.x - a.upperBound.x; var d2x = a.lowerBound.x - b.upperBound.x; var d1y = b.lowerBound.y - a.upperBound.y; var d2y = a.lowerBound.y - b.upperBound.y; if (d1x > 0 || d1y > 0 || d2x > 0 || d2y > 0) { return false; } return true; }; AABB.areEqual = function(a, b) { return Vec2.areEqual(a.lowerBound, b.lowerBound) && Vec2.areEqual(a.upperBound, b.upperBound); }; AABB.diff = function(a, b) { var wD = Math.max(0, Math.min(a.upperBound.x, b.upperBound.x) - Math.max(b.lowerBound.x, a.lowerBound.x)); var hD = Math.max(0, Math.min(a.upperBound.y, b.upperBound.y) - Math.max(b.lowerBound.y, a.lowerBound.y)); var wA = a.upperBound.x - a.lowerBound.x; var hA = a.upperBound.y - a.lowerBound.y; var wB = b.upperBound.x - b.lowerBound.x; var hB = b.upperBound.y - b.lowerBound.y; return wA * hA + wB * hB - wD * hD; }; AABB.prototype.rayCast = function(output, input) { var tmin = -Infinity; var tmax = Infinity; var p = input.p1; var d = Vec2.sub(input.p2, input.p1); var absD = Vec2.abs(d); var normal = Vec2.zero(); for (var f = "x"; f !== null; f = f === "x" ? "y" : null) { if (absD.x < Math.EPSILON) { if (p[f] < this.lowerBound[f] || this.upperBound[f] < p[f]) { return false; } } else { var inv_d = 1 / d[f]; var t1 = (this.lowerBound[f] - p[f]) * inv_d; var t2 = (this.upperBound[f] - p[f]) * inv_d; var s = -1; if (t1 > t2) { var temp = t1; t1 = t2, t2 = temp; s = 1; } if (t1 > tmin) { normal.setZero(); normal[f] = s; tmin = t1; } tmax = Math.min(tmax, t2); if (tmin > tmax) { return false; } } } if (tmin < 0 || input.maxFraction < tmin) { return false; } output.fraction = tmin; output.normal = normal; return true; }; AABB.prototype.toString = function() { return JSON.stringify(this); }; },{"../Settings":7,"../common/Math":18,"../common/Vec2":23}],12:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = require("../Settings"); var common = require("../util/common"); var Math = require("../common/Math"); var AABB = require("./AABB"); var DynamicTree = require("./DynamicTree"); module.exports = BroadPhase; function BroadPhase() { this.m_tree = new DynamicTree(); this.m_proxyCount = 0; this.m_moveBuffer = []; this.queryCallback = this.queryCallback.bind(this); } BroadPhase.prototype.getUserData = function(proxyId) { return this.m_tree.getUserData(proxyId); }; BroadPhase.prototype.testOverlap = function(proxyIdA, proxyIdB) { var aabbA = this.m_tree.getFatAABB(proxyIdA); var aabbB = this.m_tree.getFatAABB(proxyIdB); return AABB.testOverlap(aabbA, aabbB); }; BroadPhase.prototype.getFatAABB = function(proxyId) { return this.m_tree.getFatAABB(proxyId); }; BroadPhase.prototype.getProxyCount = function() { return this.m_proxyCount; }; BroadPhase.prototype.getTreeHeight = function() { return this.m_tree.getHeight(); }; BroadPhase.prototype.getTreeBalance = function() { return this.m_tree.getMaxBalance(); }; BroadPhase.prototype.getTreeQuality = function() { return this.m_tree.getAreaRatio(); }; BroadPhase.prototype.query = function(aabb, queryCallback) { this.m_tree.query(aabb, queryCallback); }; BroadPhase.prototype.rayCast = function(input, rayCastCallback) { this.m_tree.rayCast(input, rayCastCallback); }; BroadPhase.prototype.shiftOrigin = function(newOrigin) { this.m_tree.shiftOrigin(newOrigin); }; BroadPhase.prototype.createProxy = function(aabb, userData) { _ASSERT && common.assert(AABB.isValid(aabb)); var proxyId = this.m_tree.createProxy(aabb, userData); this.m_proxyCount++; this.bufferMove(proxyId); return proxyId; }; BroadPhase.prototype.destroyProxy = function(proxyId) { this.unbufferMove(proxyId); this.m_proxyCount--; this.m_tree.destroyProxy(proxyId); }; BroadPhase.prototype.moveProxy = function(proxyId, aabb, displacement) { _ASSERT && common.assert(AABB.isValid(aabb)); var changed = this.m_tree.moveProxy(proxyId, aabb, displacement); if (changed) { this.bufferMove(proxyId); } }; BroadPhase.prototype.touchProxy = function(proxyId) { this.bufferMove(proxyId); }; BroadPhase.prototype.bufferMove = function(proxyId) { this.m_moveBuffer.push(proxyId); }; BroadPhase.prototype.unbufferMove = function(proxyId) { for (var i = 0; i < this.m_moveBuffer.length; ++i) { if (this.m_moveBuffer[i] == proxyId) { this.m_moveBuffer[i] = null; } } }; BroadPhase.prototype.updatePairs = function(addPairCallback) { _ASSERT && common.assert(typeof addPairCallback === "function"); this.m_callback = addPairCallback; while (this.m_moveBuffer.length > 0) { this.m_queryProxyId = this.m_moveBuffer.pop(); if (this.m_queryProxyId === null) { continue; } var fatAABB = this.m_tree.getFatAABB(this.m_queryProxyId); this.m_tree.query(fatAABB, this.queryCallback); } }; BroadPhase.prototype.queryCallback = function(proxyId) { if (proxyId == this.m_queryProxyId) { return true; } var proxyIdA = Math.min(proxyId, this.m_queryProxyId); var proxyIdB = Math.max(proxyId, this.m_queryProxyId); var userDataA = this.m_tree.getUserData(proxyIdA); var userDataB = this.m_tree.getUserData(proxyIdB); this.m_callback(userDataA, userDataB); return true; }; },{"../Settings":7,"../common/Math":18,"../util/common":51,"./AABB":11,"./DynamicTree":14}],13:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Distance; module.exports.Input = DistanceInput; module.exports.Output = DistanceOutput; module.exports.Proxy = DistanceProxy; module.exports.Cache = SimplexCache; var Settings = require("../Settings"); var common = require("../util/common"); var stats = require("../common/stats"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); stats.gjkCalls = 0; stats.gjkIters = 0; stats.gjkMaxIters = 0; function DistanceInput() { this.proxyA = new DistanceProxy(); this.proxyB = new DistanceProxy(); this.transformA = null; this.transformB = null; this.useRadii = false; } function DistanceOutput() { this.pointA = Vec2.zero(); this.pointB = Vec2.zero(); this.distance; this.iterations; } function SimplexCache() { this.metric = 0; this.indexA = []; this.indexB = []; this.count = 0; } function Distance(output, cache, input) { ++stats.gjkCalls; var proxyA = input.proxyA; var proxyB = input.proxyB; var xfA = input.transformA; var xfB = input.transformB; var simplex = new Simplex(); simplex.readCache(cache, proxyA, xfA, proxyB, xfB); var vertices = simplex.m_v; var k_maxIters = Settings.maxDistnceIterations; var saveA = []; var saveB = []; var saveCount = 0; var distanceSqr1 = Infinity; var distanceSqr2 = Infinity; var iter = 0; while (iter < k_maxIters) { saveCount = simplex.m_count; for (var i = 0; i < saveCount; ++i) { saveA[i] = vertices[i].indexA; saveB[i] = vertices[i].indexB; } simplex.solve(); if (simplex.m_count == 3) { break; } var p = simplex.getClosestPoint(); distanceSqr2 = p.lengthSquared(); if (distanceSqr2 >= distanceSqr1) {} distanceSqr1 = distanceSqr2; var d = simplex.getSearchDirection(); if (d.lengthSquared() < Math.EPSILON * Math.EPSILON) { break; } var vertex = vertices[simplex.m_count]; vertex.indexA = proxyA.getSupport(Rot.mulTVec2(xfA.q, Vec2.neg(d))); vertex.wA = Transform.mulVec2(xfA, proxyA.getVertex(vertex.indexA)); vertex.indexB = proxyB.getSupport(Rot.mulTVec2(xfB.q, d)); vertex.wB = Transform.mulVec2(xfB, proxyB.getVertex(vertex.indexB)); vertex.w = Vec2.sub(vertex.wB, vertex.wA); ++iter; ++stats.gjkIters; var duplicate = false; for (var i = 0; i < saveCount; ++i) { if (vertex.indexA == saveA[i] && vertex.indexB == saveB[i]) { duplicate = true; break; } } if (duplicate) { break; } ++simplex.m_count; } stats.gjkMaxIters = Math.max(stats.gjkMaxIters, iter); simplex.getWitnessPoints(output.pointA, output.pointB); output.distance = Vec2.distance(output.pointA, output.pointB); output.iterations = iter; simplex.writeCache(cache); if (input.useRadii) { var rA = proxyA.m_radius; var rB = proxyB.m_radius; if (output.distance > rA + rB && output.distance > Math.EPSILON) { output.distance -= rA + rB; var normal = Vec2.sub(output.pointB, output.pointA); normal.normalize(); output.pointA.addMul(rA, normal); output.pointB.subMul(rB, normal); } else { var p = Vec2.mid(output.pointA, output.pointB); output.pointA.set(p); output.pointB.set(p); output.distance = 0; } } } function DistanceProxy() { this.m_buffer = []; this.m_vertices = []; this.m_count = 0; this.m_radius = 0; } DistanceProxy.prototype.getVertexCount = function() { return this.m_count; }; DistanceProxy.prototype.getVertex = function(index) { _ASSERT && common.assert(0 <= index && index < this.m_count); return this.m_vertices[index]; }; DistanceProxy.prototype.getSupport = function(d) { var bestIndex = 0; var bestValue = Vec2.dot(this.m_vertices[0], d); for (var i = 0; i < this.m_count; ++i) { var value = Vec2.dot(this.m_vertices[i], d); if (value > bestValue) { bestIndex = i; bestValue = value; } } return bestIndex; }; DistanceProxy.prototype.getSupportVertex = function(d) { return this.m_vertices[this.getSupport(d)]; }; DistanceProxy.prototype.set = function(shape, index) { _ASSERT && common.assert(typeof shape.computeDistanceProxy === "function"); shape.computeDistanceProxy(this, index); }; function SimplexVertex() { this.indexA; this.indexB; this.wA = Vec2.zero(); this.wB = Vec2.zero(); this.w = Vec2.zero(); this.a; } SimplexVertex.prototype.set = function(v) { this.indexA = v.indexA; this.indexB = v.indexB; this.wA = Vec2.clone(v.wA); this.wB = Vec2.clone(v.wB); this.w = Vec2.clone(v.w); this.a = v.a; }; function Simplex() { this.m_v1 = new SimplexVertex(); this.m_v2 = new SimplexVertex(); this.m_v3 = new SimplexVertex(); this.m_v = [ this.m_v1, this.m_v2, this.m_v3 ]; this.m_count; } Simplex.prototype.print = function() { if (this.m_count == 3) { return [ "+" + this.m_count, this.m_v1.a, this.m_v1.wA.x, this.m_v1.wA.y, this.m_v1.wB.x, this.m_v1.wB.y, this.m_v2.a, this.m_v2.wA.x, this.m_v2.wA.y, this.m_v2.wB.x, this.m_v2.wB.y, this.m_v3.a, this.m_v3.wA.x, this.m_v3.wA.y, this.m_v3.wB.x, this.m_v3.wB.y ].toString(); } else if (this.m_count == 2) { return [ "+" + this.m_count, this.m_v1.a, this.m_v1.wA.x, this.m_v1.wA.y, this.m_v1.wB.x, this.m_v1.wB.y, this.m_v2.a, this.m_v2.wA.x, this.m_v2.wA.y, this.m_v2.wB.x, this.m_v2.wB.y ].toString(); } else if (this.m_count == 1) { return [ "+" + this.m_count, this.m_v1.a, this.m_v1.wA.x, this.m_v1.wA.y, this.m_v1.wB.x, this.m_v1.wB.y ].toString(); } else { return "+" + this.m_count; } }; Simplex.prototype.readCache = function(cache, proxyA, transformA, proxyB, transformB) { _ASSERT && common.assert(cache.count <= 3); this.m_count = cache.count; for (var i = 0; i < this.m_count; ++i) { var v = this.m_v[i]; v.indexA = cache.indexA[i]; v.indexB = cache.indexB[i]; var wALocal = proxyA.getVertex(v.indexA); var wBLocal = proxyB.getVertex(v.indexB); v.wA = Transform.mulVec2(transformA, wALocal); v.wB = Transform.mulVec2(transformB, wBLocal); v.w = Vec2.sub(v.wB, v.wA); v.a = 0; } if (this.m_count > 1) { var metric1 = cache.metric; var metric2 = this.getMetric(); if (metric2 < .5 * metric1 || 2 * metric1 < metric2 || metric2 < Math.EPSILON) { this.m_count = 0; } } if (this.m_count == 0) { var v = this.m_v[0]; v.indexA = 0; v.indexB = 0; var wALocal = proxyA.getVertex(0); var wBLocal = proxyB.getVertex(0); v.wA = Transform.mulVec2(transformA, wALocal); v.wB = Transform.mulVec2(transformB, wBLocal); v.w = Vec2.sub(v.wB, v.wA); v.a = 1; this.m_count = 1; } }; Simplex.prototype.writeCache = function(cache) { cache.metric = this.getMetric(); cache.count = this.m_count; for (var i = 0; i < this.m_count; ++i) { cache.indexA[i] = this.m_v[i].indexA; cache.indexB[i] = this.m_v[i].indexB; } }; Simplex.prototype.getSearchDirection = function() { switch (this.m_count) { case 1: return Vec2.neg(this.m_v1.w); case 2: { var e12 = Vec2.sub(this.m_v2.w, this.m_v1.w); var sgn = Vec2.cross(e12, Vec2.neg(this.m_v1.w)); if (sgn > 0) { return Vec2.cross(1, e12); } else { return Vec2.cross(e12, 1); } } default: _ASSERT && common.assert(false); return Vec2.zero(); } }; Simplex.prototype.getClosestPoint = function() { switch (this.m_count) { case 0: _ASSERT && common.assert(false); return Vec2.zero(); case 1: return Vec2.clone(this.m_v1.w); case 2: return Vec2.combine(this.m_v1.a, this.m_v1.w, this.m_v2.a, this.m_v2.w); case 3: return Vec2.zero(); default: _ASSERT && common.assert(false); return Vec2.zero(); } }; Simplex.prototype.getWitnessPoints = function(pA, pB) { switch (this.m_count) { case 0: _ASSERT && common.assert(false); break; case 1: pA.set(this.m_v1.wA); pB.set(this.m_v1.wB); break; case 2: pA.setCombine(this.m_v1.a, this.m_v1.wA, this.m_v2.a, this.m_v2.wA); pB.setCombine(this.m_v1.a, this.m_v1.wB, this.m_v2.a, this.m_v2.wB); break; case 3: pA.setCombine(this.m_v1.a, this.m_v1.wA, this.m_v2.a, this.m_v2.wA); pA.addMul(this.m_v3.a, this.m_v3.wA); pB.set(pA); break; default: _ASSERT && common.assert(false); break; } }; Simplex.prototype.getMetric = function() { switch (this.m_count) { case 0: _ASSERT && common.assert(false); return 0; case 1: return 0; case 2: return Vec2.distance(this.m_v1.w, this.m_v2.w); case 3: return Vec2.cross(Vec2.sub(this.m_v2.w, this.m_v1.w), Vec2.sub(this.m_v3.w, this.m_v1.w)); default: _ASSERT && common.assert(false); return 0; } }; Simplex.prototype.solve = function() { switch (this.m_count) { case 1: break; case 2: this.solve2(); break; case 3: this.solve3(); break; default: _ASSERT && common.assert(false); } }; Simplex.prototype.solve2 = function() { var w1 = this.m_v1.w; var w2 = this.m_v2.w; var e12 = Vec2.sub(w2, w1); var d12_2 = -Vec2.dot(w1, e12); if (d12_2 <= 0) { this.m_v1.a = 1; this.m_count = 1; return; } var d12_1 = Vec2.dot(w2, e12); if (d12_1 <= 0) { this.m_v2.a = 1; this.m_count = 1; this.m_v1.set(this.m_v2); return; } var inv_d12 = 1 / (d12_1 + d12_2); this.m_v1.a = d12_1 * inv_d12; this.m_v2.a = d12_2 * inv_d12; this.m_count = 2; }; Simplex.prototype.solve3 = function() { var w1 = this.m_v1.w; var w2 = this.m_v2.w; var w3 = this.m_v3.w; var e12 = Vec2.sub(w2, w1); var w1e12 = Vec2.dot(w1, e12); var w2e12 = Vec2.dot(w2, e12); var d12_1 = w2e12; var d12_2 = -w1e12; var e13 = Vec2.sub(w3, w1); var w1e13 = Vec2.dot(w1, e13); var w3e13 = Vec2.dot(w3, e13); var d13_1 = w3e13; var d13_2 = -w1e13; var e23 = Vec2.sub(w3, w2); var w2e23 = Vec2.dot(w2, e23); var w3e23 = Vec2.dot(w3, e23); var d23_1 = w3e23; var d23_2 = -w2e23; var n123 = Vec2.cross(e12, e13); var d123_1 = n123 * Vec2.cross(w2, w3); var d123_2 = n123 * Vec2.cross(w3, w1); var d123_3 = n123 * Vec2.cross(w1, w2); if (d12_2 <= 0 && d13_2 <= 0) { this.m_v1.a = 1; this.m_count = 1; return; } if (d12_1 > 0 && d12_2 > 0 && d123_3 <= 0) { var inv_d12 = 1 / (d12_1 + d12_2); this.m_v1.a = d12_1 * inv_d12; this.m_v2.a = d12_2 * inv_d12; this.m_count = 2; return; } if (d13_1 > 0 && d13_2 > 0 && d123_2 <= 0) { var inv_d13 = 1 / (d13_1 + d13_2); this.m_v1.a = d13_1 * inv_d13; this.m_v3.a = d13_2 * inv_d13; this.m_count = 2; this.m_v2.set(this.m_v3); return; } if (d12_1 <= 0 && d23_2 <= 0) { this.m_v2.a = 1; this.m_count = 1; this.m_v1.set(this.m_v2); return; } if (d13_1 <= 0 && d23_1 <= 0) { this.m_v3.a = 1; this.m_count = 1; this.m_v1.set(this.m_v3); return; } if (d23_1 > 0 && d23_2 > 0 && d123_1 <= 0) { var inv_d23 = 1 / (d23_1 + d23_2); this.m_v2.a = d23_1 * inv_d23; this.m_v3.a = d23_2 * inv_d23; this.m_count = 2; this.m_v1.set(this.m_v3); return; } var inv_d123 = 1 / (d123_1 + d123_2 + d123_3); this.m_v1.a = d123_1 * inv_d123; this.m_v2.a = d123_2 * inv_d123; this.m_v3.a = d123_3 * inv_d123; this.m_count = 3; }; Distance.testOverlap = function(shapeA, indexA, shapeB, indexB, xfA, xfB) { var input = new DistanceInput(); input.proxyA.set(shapeA, indexA); input.proxyB.set(shapeB, indexB); input.transformA = xfA; input.transformB = xfB; input.useRadii = true; var cache = new SimplexCache(); var output = new DistanceOutput(); Distance(output, cache, input); return output.distance < 10 * Math.EPSILON; }; },{"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../common/stats":26,"../util/common":51}],14:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = require("../Settings"); var common = require("../util/common"); var Pool = require("../util/Pool"); var Vec2 = require("../common/Vec2"); var Math = require("../common/Math"); var AABB = require("./AABB"); module.exports = DynamicTree; var aabbPool = new Pool({ create: function() { return new AABB(); }, release: function(aabb) { aabb.lowerBound.setZero(); aabb.upperBound.setZero(); } }); var nodePool = new Pool({ create: function() { return new TreeNode(); } }); function TreeNode(id) { this.id = id; this.aabb = new AABB(); this.userData = null; this.parent = null; this.child1 = null; this.child2 = null; this.height = -1; this.toString = function() { return this.id + ": " + this.userData; }; } TreeNode.prototype.isLeaf = function() { return this.child1 == null; }; function DynamicTree() { this.m_root = null; this.m_nodes = {}; this.m_lastProxyId = 0; } DynamicTree.prototype.getUserData = function(id) { var node = this.m_nodes[id]; _ASSERT && common.assert(!!node); return node.userData; }; DynamicTree.prototype.getFatAABB = function(id) { var node = this.m_nodes[id]; _ASSERT && common.assert(!!node); return node.aabb; }; DynamicTree.prototype.allocateNode = function() { var node = nodePool.allocate(); node.id = ++this.m_lastProxyId; node.userData = null; node.parent = null; node.child1 = null; node.child2 = null; node.height = -1; this.m_nodes[node.id] = node; return node; }; DynamicTree.prototype.freeNode = function(node) { nodePool.release(node); node.height = -1; delete this.m_nodes[node.id]; }; DynamicTree.prototype.createProxy = function(aabb, userData) { _ASSERT && common.assert(AABB.isValid(aabb)); var node = this.allocateNode(); node.aabb.set(aabb); node.aabb.extend(Settings.aabbExtension); node.userData = userData; node.height = 0; this.insertLeaf(node); return node.id; }; DynamicTree.prototype.destroyProxy = function(id) { var node = this.m_nodes[id]; _ASSERT && common.assert(!!node); _ASSERT && common.assert(node.isLeaf()); this.removeLeaf(node); this.freeNode(node); }; DynamicTree.prototype.moveProxy = function(id, aabb, d) { _ASSERT && common.assert(AABB.isValid(aabb)); _ASSERT && common.assert(!d || Vec2.isValid(d)); var node = this.m_nodes[id]; _ASSERT && common.assert(!!node); _ASSERT && common.assert(node.isLeaf()); if (node.aabb.contains(aabb)) { return false; } this.removeLeaf(node); node.aabb.set(aabb); aabb = node.aabb; AABB.extend(aabb, Settings.aabbExtension); if (d.x < 0) { aabb.lowerBound.x += d.x * Settings.aabbMultiplier; } else { aabb.upperBound.x += d.x * Settings.aabbMultiplier; } if (d.y < 0) { aabb.lowerBound.y += d.y * Settings.aabbMultiplier; } else { aabb.upperBound.y += d.y * Settings.aabbMultiplier; } this.insertLeaf(node); return true; }; DynamicTree.prototype.insertLeaf = function(leaf) { _ASSERT && common.assert(AABB.isValid(leaf.aabb)); if (this.m_root == null) { this.m_root = leaf; this.m_root.parent = null; return; } var leafAABB = leaf.aabb; var index = this.m_root; while (index.isLeaf() == false) { var child1 = index.child1; var child2 = index.child2; var area = index.aabb.getPerimeter(); var combinedAABB = aabbPool.allocate(); combinedAABB.combine(index.aabb, leafAABB); var combinedArea = combinedAABB.getPerimeter(); aabbPool.release(combinedAABB); var cost = 2 * combinedArea; var inheritanceCost = 2 * (combinedArea - area); var cost1; if (child1.isLeaf()) { var aabb = aabbPool.allocate(); aabb.combine(leafAABB, child1.aabb); cost1 = aabb.getPerimeter() + inheritanceCost; aabbPool.release(aabb); } else { var aabb = aabbPool.allocate(); aabb.combine(leafAABB, child1.aabb); var oldArea = child1.aabb.getPerimeter(); var newArea = aabb.getPerimeter(); cost1 = newArea - oldArea + inheritanceCost; aabbPool.release(aabb); } var cost2; if (child2.isLeaf()) { var aabb = aabbPool.allocate(); aabb.combine(leafAABB, child2.aabb); cost2 = aabb.getPerimeter() + inheritanceCost; aabbPool.release(aabb); } else { var aabb = aabbPool.allocate(); aabb.combine(leafAABB, child2.aabb); var oldArea = child2.aabb.getPerimeter(); var newArea = aabb.getPerimeter(); cost2 = newArea - oldArea + inheritanceCost; aabbPool.release(aabb); } if (cost < cost1 && cost < cost2) { break; } if (cost1 < cost2) { index = child1; } else { index = child2; } } var sibling = index; var oldParent = sibling.parent; var newParent = this.allocateNode(); newParent.parent = oldParent; newParent.userData = null; newParent.aabb.combine(leafAABB, sibling.aabb); newParent.height = sibling.height + 1; if (oldParent != null) { if (oldParent.child1 == sibling) { oldParent.child1 = newParent; } else { oldParent.child2 = newParent; } newParent.child1 = sibling; newParent.child2 = leaf; sibling.parent = newParent; leaf.parent = newParent; } else { newParent.child1 = sibling; newParent.child2 = leaf; sibling.parent = newParent; leaf.parent = newParent; this.m_root = newParent; } index = leaf.parent; while (index != null) { index = this.balance(index); var child1 = index.child1; var child2 = index.child2; _ASSERT && common.assert(child1 != null); _ASSERT && common.assert(child2 != null); index.height = 1 + Math.max(child1.height, child2.height); index.aabb.combine(child1.aabb, child2.aabb); index = index.parent; } }; DynamicTree.prototype.removeLeaf = function(leaf) { if (leaf == this.m_root) { this.m_root = null; return; } var parent = leaf.parent; var grandParent = parent.parent; var sibling; if (parent.child1 == leaf) { sibling = parent.child2; } else { sibling = parent.child1; } if (grandParent != null) { if (grandParent.child1 == parent) { grandParent.child1 = sibling; } else { grandParent.child2 = sibling; } sibling.parent = grandParent; this.freeNode(parent); var index = grandParent; while (index != null) { index = this.balance(index); var child1 = index.child1; var child2 = index.child2; index.aabb.combine(child1.aabb, child2.aabb); index.height = 1 + Math.max(child1.height, child2.height); index = index.parent; } } else { this.m_root = sibling; sibling.parent = null; this.freeNode(parent); } }; DynamicTree.prototype.balance = function(iA) { _ASSERT && common.assert(iA != null); var A = iA; if (A.isLeaf() || A.height < 2) { return iA; } var B = A.child1; var C = A.child2; var balance = C.height - B.height; if (balance > 1) { var F = C.child1; var G = C.child2; C.child1 = A; C.parent = A.parent; A.parent = C; if (C.parent != null) { if (C.parent.child1 == iA) { C.parent.child1 = C; } else { C.parent.child2 = C; } } else { this.m_root = C; } if (F.height > G.height) { C.child2 = F; A.child2 = G; G.parent = A; A.aabb.combine(B.aabb, G.aabb); C.aabb.combine(A.aabb, F.aabb); A.height = 1 + Math.max(B.height, G.height); C.height = 1 + Math.max(A.height, F.height); } else { C.child2 = G; A.child2 = F; F.parent = A; A.aabb.combine(B.aabb, F.aabb); C.aabb.combine(A.aabb, G.aabb); A.height = 1 + Math.max(B.height, F.height); C.height = 1 + Math.max(A.height, G.height); } return C; } if (balance < -1) { var D = B.child1; var E = B.child2; B.child1 = A; B.parent = A.parent; A.parent = B; if (B.parent != null) { if (B.parent.child1 == A) { B.parent.child1 = B; } else { B.parent.child2 = B; } } else { this.m_root = B; } if (D.height > E.height) { B.child2 = D; A.child1 = E; E.parent = A; A.aabb.combine(C.aabb, E.aabb); B.aabb.combine(A.aabb, D.aabb); A.height = 1 + Math.max(C.height, E.height); B.height = 1 + Math.max(A.height, D.height); } else { B.child2 = E; A.child1 = D; D.parent = A; A.aabb.combine(C.aabb, D.aabb); B.aabb.combine(A.aabb, E.aabb); A.height = 1 + Math.max(C.height, D.height); B.height = 1 + Math.max(A.height, E.height); } return B; } return A; }; DynamicTree.prototype.getHeight = function() { if (this.m_root == null) { return 0; } return this.m_root.height; }; DynamicTree.prototype.getAreaRatio = function() { if (this.m_root == null) { return 0; } var root = this.m_root; var rootArea = root.aabb.getPerimeter(); var totalArea = 0; var node, it = iteratorPool.allocate().preorder(); while (node = it.next()) { if (node.height < 0) { continue; } totalArea += node.aabb.getPerimeter(); } iteratorPool.release(it); return totalArea / rootArea; }; DynamicTree.prototype.computeHeight = function(id) { var node; if (typeof id !== "undefined") { node = this.m_nodes[id]; } else { node = this.m_root; } if (node.isLeaf()) { return 0; } var height1 = ComputeHeight(node.child1); var height2 = ComputeHeight(node.child2); return 1 + Math.max(height1, height2); }; DynamicTree.prototype.validateStructure = function(node) { if (node == null) { return; } if (node == this.m_root) { _ASSERT && common.assert(node.parent == null); } var child1 = node.child1; var child2 = node.child2; if (node.isLeaf()) { _ASSERT && common.assert(child1 == null); _ASSERT && common.assert(child2 == null); _ASSERT && common.assert(node.height == 0); return; } _ASSERT && common.assert(child1.parent == node); _ASSERT && common.assert(child2.parent == node); this.validateStructure(child1); this.validateStructure(child2); }; DynamicTree.prototype.validateMetrics = function(node) { if (node == null) { return; } var child1 = node.child1; var child2 = node.child2; if (node.isLeaf()) { _ASSERT && common.assert(child1 == null); _ASSERT && common.assert(child2 == null); _ASSERT && common.assert(node.height == 0); return; } var height1 = this.m_nodes[child1].height; var height2 = this.m_nodes[child2].height; var height = 1 + Math.max(height1, height2); _ASSERT && common.assert(node.height == height); _ASSERT && common.assert(AABB.areEqual(new AABB().combine(child1.aabb, child2.aabb), node.aabb)); this.validateMetrics(child1); this.validateMetrics(child2); }; DynamicTree.prototype.validate = function() { ValidateStructure(this.m_root); ValidateMetrics(this.m_root); _ASSERT && common.assert(this.getHeight() == this.computeHeight()); }; DynamicTree.prototype.getMaxBalance = function() { var maxBalance = 0; var node, it = iteratorPool.allocate().preorder(); while (node = it.next()) { if (node.height <= 1) { continue; } _ASSERT && common.assert(node.isLeaf() == false); var balance = Math.abs(node.child2.height - node.child1.height); maxBalance = Math.max(maxBalance, balance); } iteratorPool.release(it); return maxBalance; }; DynamicTree.prototype.rebuildBottomUp = function() { var nodes = []; var count = 0; var node, it = iteratorPool.allocate().preorder(); while (node = it.next()) { if (node.height < 0) { continue; } if (node.isLeaf()) { node.parent = null; nodes[count] = node; ++count; } else { this.freeNode(node); } } iteratorPool.release(it); while (count > 1) { var minCost = Infinity; var iMin = -1, jMin = -1; for (var i = 0; i < count; ++i) { var aabbi = nodes[i].aabb; for (var j = i + 1; j < count; ++j) { var aabbj = nodes[j].aabb; var b = aabbPool.allocate(); b.combine(aabbi, aabbj); var cost = b.getPerimeter(); if (cost < minCost) { iMin = i; jMin = j; minCost = cost; } aabbPool.release(b); } } var child1 = nodes[iMin]; var child2 = nodes[jMin]; var parent = this.allocateNode(); parent.child1 = child1; parent.child2 = child2; parent.height = 1 + Math.max(child1.height, child2.height); parent.aabb.combine(child1.aabb, child2.aabb); parent.parent = null; child1.parent = parent; child2.parent = parent; nodes[jMin] = nodes[count - 1]; nodes[iMin] = parent; --count; } this.m_root = nodes[0]; this.validate(); }; DynamicTree.prototype.shiftOrigin = function(newOrigin) { var node, it = iteratorPool.allocate().preorder(); while (node = it.next()) { var aabb = node.aabb; aabb.lowerBound.x -= newOrigin.x; aabb.lowerBound.y -= newOrigin.y; aabb.upperBound.x -= newOrigin.x; aabb.upperBound.y -= newOrigin.y; } iteratorPool.release(it); }; DynamicTree.prototype.query = function(aabb, queryCallback) { _ASSERT && common.assert(typeof queryCallback === "function"); var stack = stackPool.allocate(); stack.push(this.m_root); while (stack.length > 0) { var node = stack.pop(); if (node == null) { continue; } if (AABB.testOverlap(node.aabb, aabb)) { if (node.isLeaf()) { var proceed = queryCallback(node.id); if (proceed == false) { return; } } else { stack.push(node.child1); stack.push(node.child2); } } } stackPool.release(stack); }; DynamicTree.prototype.rayCast = function(input, rayCastCallback) { _ASSERT && common.assert(typeof rayCastCallback === "function"); var p1 = input.p1; var p2 = input.p2; var r = Vec2.sub(p2, p1); _ASSERT && common.assert(r.lengthSquared() > 0); r.normalize(); var v = Vec2.cross(1, r); var abs_v = Vec2.abs(v); var maxFraction = input.maxFraction; var segmentAABB = new AABB(); var t = Vec2.combine(1 - maxFraction, p1, maxFraction, p2); segmentAABB.combinePoints(p1, t); var stack = stackPool.allocate(); var subInput = inputPool.allocate(); stack.push(this.m_root); while (stack.length > 0) { var node = stack.pop(); if (node == null) { continue; } if (AABB.testOverlap(node.aabb, segmentAABB) == false) { continue; } var c = node.aabb.getCenter(); var h = node.aabb.getExtents(); var separation = Math.abs(Vec2.dot(v, Vec2.sub(p1, c))) - Vec2.dot(abs_v, h); if (separation > 0) { continue; } if (node.isLeaf()) { subInput.p1 = Vec2.clone(input.p1); subInput.p2 = Vec2.clone(input.p2); subInput.maxFraction = maxFraction; var value = rayCastCallback(subInput, node.id); if (value == 0) { return; } if (value > 0) { maxFraction = value; t = Vec2.combine(1 - maxFraction, p1, maxFraction, p2); segmentAABB.combinePoints(p1, t); } } else { stack.push(node.child1); stack.push(node.child2); } } stackPool.release(stack); inputPool.release(subInput); }; var inputPool = new Pool({ create: function() { return {}; }, release: function(stack) {} }); var stackPool = new Pool({ create: function() { return []; }, release: function(stack) { stack.length = 0; } }); var iteratorPool = new Pool({ create: function() { return new Iterator(); }, release: function(iterator) { iterator.close(); } }); function Iterator() { var parents = []; var states = []; return { preorder: function(root) { parents.length = 0; parents.push(root); states.length = 0; states.push(0); return this; }, next: function() { while (parents.length > 0) { var i = parents.length - 1; var node = parents[i]; if (states[i] === 0) { states[i] = 1; return node; } if (states[i] === 1) { states[i] = 2; if (node.child1) { parents.push(node.child1); states.push(1); return node.child1; } } if (states[i] === 2) { states[i] = 3; if (node.child2) { parents.push(node.child2); states.push(1); return node.child2; } } parents.pop(); states.pop(); } }, close: function() { parents.length = 0; } }; } },{"../Settings":7,"../common/Math":18,"../common/Vec2":23,"../util/Pool":49,"../util/common":51,"./AABB":11}],15:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = TimeOfImpact; module.exports.Input = TOIInput; module.exports.Output = TOIOutput; var Settings = require("../Settings"); var common = require("../util/common"); var Timer = require("../util/Timer"); var stats = require("../common/stats"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Distance = require("./Distance"); var DistanceInput = Distance.Input; var DistanceOutput = Distance.Output; var DistanceProxy = Distance.Proxy; var SimplexCache = Distance.Cache; function TOIInput() { this.proxyA = new DistanceProxy(); this.proxyB = new DistanceProxy(); this.sweepA = new Sweep(); this.sweepB = new Sweep(); this.tMax; } TOIOutput.e_unknown = 0; TOIOutput.e_failed = 1; TOIOutput.e_overlapped = 2; TOIOutput.e_touching = 3; TOIOutput.e_separated = 4; function TOIOutput() { this.state; this.t; } stats.toiTime = 0; stats.toiMaxTime = 0; stats.toiCalls = 0; stats.toiIters = 0; stats.toiMaxIters = 0; stats.toiRootIters = 0; stats.toiMaxRootIters = 0; function TimeOfImpact(output, input) { var timer = Timer.now(); ++stats.toiCalls; output.state = TOIOutput.e_unknown; output.t = input.tMax; var proxyA = input.proxyA; var proxyB = input.proxyB; var sweepA = input.sweepA; var sweepB = input.sweepB; sweepA.normalize(); sweepB.normalize(); var tMax = input.tMax; var totalRadius = proxyA.m_radius + proxyB.m_radius; var target = Math.max(Settings.linearSlop, totalRadius - 3 * Settings.linearSlop); var tolerance = .25 * Settings.linearSlop; _ASSERT && common.assert(target > tolerance); var t1 = 0; var k_maxIterations = Settings.maxTOIIterations; var iter = 0; var cache = new SimplexCache(); var distanceInput = new DistanceInput(); distanceInput.proxyA = input.proxyA; distanceInput.proxyB = input.proxyB; distanceInput.useRadii = false; for (;;) { var xfA = Transform.identity(); var xfB = Transform.identity(); sweepA.getTransform(xfA, t1); sweepB.getTransform(xfB, t1); distanceInput.transformA = xfA; distanceInput.transformB = xfB; var distanceOutput = new DistanceOutput(); Distance(distanceOutput, cache, distanceInput); if (distanceOutput.distance <= 0) { output.state = TOIOutput.e_overlapped; output.t = 0; break; } if (distanceOutput.distance < target + tolerance) { output.state = TOIOutput.e_touching; output.t = t1; break; } var fcn = new SeparationFunction(); fcn.initialize(cache, proxyA, sweepA, proxyB, sweepB, t1); if (false) { var N = 100; var dx = 1 / N; var xs = []; var fs = []; var x = 0; for (var i = 0; i <= N; ++i) { sweepA.getTransform(xfA, x); sweepB.getTransform(xfB, x); var f = fcn.evaluate(xfA, xfB) - target; printf("%g %g\n", x, f); xs[i] = x; fs[i] = f; x += dx; } } var done = false; var t2 = tMax; var pushBackIter = 0; for (;;) { var s2 = fcn.findMinSeparation(t2); var indexA = fcn.indexA; var indexB = fcn.indexB; if (s2 > target + tolerance) { output.state = TOIOutput.e_separated; output.t = tMax; done = true; break; } if (s2 > target - tolerance) { t1 = t2; break; } var s1 = fcn.evaluate(t1); var indexA = fcn.indexA; var indexB = fcn.indexB; if (s1 < target - tolerance) { output.state = TOIOutput.e_failed; output.t = t1; done = true; break; } if (s1 <= target + tolerance) { output.state = TOIOutput.e_touching; output.t = t1; done = true; break; } var rootIterCount = 0; var a1 = t1, a2 = t2; for (;;) { var t; if (rootIterCount & 1) { t = a1 + (target - s1) * (a2 - a1) / (s2 - s1); } else { t = .5 * (a1 + a2); } ++rootIterCount; ++stats.toiRootIters; var s = fcn.evaluate(t); var indexA = fcn.indexA; var indexB = fcn.indexB; if (Math.abs(s - target) < tolerance) { t2 = t; break; } if (s > target) { a1 = t; s1 = s; } else { a2 = t; s2 = s; } if (rootIterCount == 50) { break; } } stats.toiMaxRootIters = Math.max(stats.toiMaxRootIters, rootIterCount); ++pushBackIter; if (pushBackIter == Settings.maxPolygonVertices) { break; } } ++iter; ++stats.toiIters; if (done) { break; } if (iter == k_maxIterations) { output.state = TOIOutput.e_failed; output.t = t1; break; } } stats.toiMaxIters = Math.max(stats.toiMaxIters, iter); var time = Timer.diff(timer); stats.toiMaxTime = Math.max(stats.toiMaxTime, time); stats.toiTime += time; } var e_points = 1; var e_faceA = 2; var e_faceB = 3; function SeparationFunction() { this.m_proxyA = new DistanceProxy(); this.m_proxyB = new DistanceProxy(); this.m_sweepA; this.m_sweepB; this.m_type; this.m_localPoint = Vec2.zero(); this.m_axis = Vec2.zero(); } SeparationFunction.prototype.initialize = function(cache, proxyA, sweepA, proxyB, sweepB, t1) { this.m_proxyA = proxyA; this.m_proxyB = proxyB; var count = cache.count; _ASSERT && common.assert(0 < count && count < 3); this.m_sweepA = sweepA; this.m_sweepB = sweepB; var xfA = Transform.identity(); var xfB = Transform.identity(); this.m_sweepA.getTransform(xfA, t1); this.m_sweepB.getTransform(xfB, t1); if (count == 1) { this.m_type = e_points; var localPointA = this.m_proxyA.getVertex(cache.indexA[0]); var localPointB = this.m_proxyB.getVertex(cache.indexB[0]); var pointA = Transform.mulVec2(xfA, localPointA); var pointB = Transform.mulVec2(xfB, localPointB); this.m_axis.setCombine(1, pointB, -1, pointA); var s = this.m_axis.normalize(); return s; } else if (cache.indexA[0] == cache.indexA[1]) { this.m_type = e_faceB; var localPointB1 = proxyB.getVertex(cache.indexB[0]); var localPointB2 = proxyB.getVertex(cache.indexB[1]); this.m_axis = Vec2.cross(Vec2.sub(localPointB2, localPointB1), 1); this.m_axis.normalize(); var normal = Rot.mulVec2(xfB.q, this.m_axis); this.m_localPoint = Vec2.mid(localPointB1, localPointB2); var pointB = Transform.mulVec2(xfB, this.m_localPoint); var localPointA = proxyA.getVertex(cache.indexA[0]); var pointA = Transform.mulVec2(xfA, localPointA); var s = Vec2.dot(pointA, normal) - Vec2.dot(pointB, normal); if (s < 0) { this.m_axis = Vec2.neg(this.m_axis); s = -s; } return s; } else { this.m_type = e_faceA; var localPointA1 = this.m_proxyA.getVertex(cache.indexA[0]); var localPointA2 = this.m_proxyA.getVertex(cache.indexA[1]); this.m_axis = Vec2.cross(Vec2.sub(localPointA2, localPointA1), 1); this.m_axis.normalize(); var normal = Rot.mulVec2(xfA.q, this.m_axis); this.m_localPoint = Vec2.mid(localPointA1, localPointA2); var pointA = Transform.mulVec2(xfA, this.m_localPoint); var localPointB = this.m_proxyB.getVertex(cache.indexB[0]); var pointB = Transform.mulVec2(xfB, localPointB); var s = Vec2.dot(pointB, normal) - Vec2.dot(pointA, normal); if (s < 0) { this.m_axis = Vec2.neg(this.m_axis); s = -s; } return s; } }; SeparationFunction.prototype.compute = function(find, t) { var xfA = Transform.identity(); var xfB = Transform.identity(); this.m_sweepA.getTransform(xfA, t); this.m_sweepB.getTransform(xfB, t); switch (this.m_type) { case e_points: { if (find) { var axisA = Rot.mulTVec2(xfA.q, this.m_axis); var axisB = Rot.mulTVec2(xfB.q, Vec2.neg(this.m_axis)); this.indexA = this.m_proxyA.getSupport(axisA); this.indexB = this.m_proxyB.getSupport(axisB); } var localPointA = this.m_proxyA.getVertex(this.indexA); var localPointB = this.m_proxyB.getVertex(this.indexB); var pointA = Transform.mulVec2(xfA, localPointA); var pointB = Transform.mulVec2(xfB, localPointB); var sep = Vec2.dot(pointB, this.m_axis) - Vec2.dot(pointA, this.m_axis); return sep; } case e_faceA: { var normal = Rot.mulVec2(xfA.q, this.m_axis); var pointA = Transform.mulVec2(xfA, this.m_localPoint); if (find) { var axisB = Rot.mulTVec2(xfB.q, Vec2.neg(normal)); this.indexA = -1; this.indexB = this.m_proxyB.getSupport(axisB); } var localPointB = this.m_proxyB.getVertex(this.indexB); var pointB = Transform.mulVec2(xfB, localPointB); var sep = Vec2.dot(pointB, normal) - Vec2.dot(pointA, normal); return sep; } case e_faceB: { var normal = Rot.mulVec2(xfB.q, this.m_axis); var pointB = Transform.mulVec2(xfB, this.m_localPoint); if (find) { var axisA = Rot.mulTVec2(xfA.q, Vec2.neg(normal)); this.indexB = -1; this.indexA = this.m_proxyA.getSupport(axisA); } var localPointA = this.m_proxyA.getVertex(this.indexA); var pointA = Transform.mulVec2(xfA, localPointA); var sep = Vec2.dot(pointA, normal) - Vec2.dot(pointB, normal); return sep; } default: _ASSERT && common.assert(false); if (find) { this.indexA = -1; this.indexB = -1; } return 0; } }; SeparationFunction.prototype.findMinSeparation = function(t) { return this.compute(true, t); }; SeparationFunction.prototype.evaluate = function(t) { return this.compute(false, t); }; },{"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../common/stats":26,"../util/Timer":50,"../util/common":51,"./Distance":13}],16:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Mat22; var common = require("../util/common"); var Math = require("./Math"); var Vec2 = require("./Vec2"); function Mat22(a, b, c, d) { if (typeof a === "object" && a !== null) { this.ex = Vec2.clone(a); this.ey = Vec2.clone(b); } else if (typeof a === "number") { this.ex = Vec2.neo(a, c); this.ey = Vec2.neo(b, d); } else { this.ex = Vec2.zero(); this.ey = Vec2.zero(); } } Mat22.prototype.toString = function() { return JSON.stringify(this); }; Mat22.isValid = function(o) { return o && Vec2.isValid(o.ex) && Vec2.isValid(o.ey); }; Mat22.assert = function(o) { if (!_ASSERT) return; if (!Mat22.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid Mat22!"); } }; Mat22.prototype.set = function(a, b, c, d) { if (typeof a === "number" && typeof b === "number" && typeof c === "number" && typeof d === "number") { this.ex.set(a, c); this.ey.set(b, d); } else if (typeof a === "object" && typeof b === "object") { this.ex.set(a); this.ey.set(b); } else if (typeof a === "object") { _ASSERT && Mat22.assert(a); this.ex.set(a.ex); this.ey.set(a.ey); } else { _ASSERT && common.assert(false); } }; Mat22.prototype.setIdentity = function() { this.ex.x = 1; this.ey.x = 0; this.ex.y = 0; this.ey.y = 1; }; Mat22.prototype.setZero = function() { this.ex.x = 0; this.ey.x = 0; this.ex.y = 0; this.ey.y = 0; }; Mat22.prototype.getInverse = function() { var a = this.ex.x; var b = this.ey.x; var c = this.ex.y; var d = this.ey.y; var det = a * d - b * c; if (det != 0) { det = 1 / det; } var imx = new Mat22(); imx.ex.x = det * d; imx.ey.x = -det * b; imx.ex.y = -det * c; imx.ey.y = det * a; return imx; }; Mat22.prototype.solve = function(v) { _ASSERT && Vec2.assert(v); var a = this.ex.x; var b = this.ey.x; var c = this.ex.y; var d = this.ey.y; var det = a * d - b * c; if (det != 0) { det = 1 / det; } var w = Vec2.zero(); w.x = det * (d * v.x - b * v.y); w.y = det * (a * v.y - c * v.x); return w; }; Mat22.mul = function(mx, v) { if (v && "x" in v && "y" in v) { _ASSERT && Vec2.assert(v); var x = mx.ex.x * v.x + mx.ey.x * v.y; var y = mx.ex.y * v.x + mx.ey.y * v.y; return Vec2.neo(x, y); } else if (v && "ex" in v && "ey" in v) { _ASSERT && Mat22.assert(v); return new Mat22(Vec2.mul(mx, v.ex), Vec2.mul(mx, v.ey)); } _ASSERT && common.assert(false); }; Mat22.mulVec2 = function(mx, v) { _ASSERT && Vec2.assert(v); var x = mx.ex.x * v.x + mx.ey.x * v.y; var y = mx.ex.y * v.x + mx.ey.y * v.y; return Vec2.neo(x, y); }; Mat22.mulVec2_ = function(mx, v, _) { _ASSERT && Vec2.assert(v); var x = mx.ex.x * v.x + mx.ey.x * v.y; var y = mx.ex.y * v.x + mx.ey.y * v.y; return _.set(x, y); }; Mat22.mulMat22 = function(mx, v) { _ASSERT && Mat22.assert(v); return new Mat22(Vec2.mul(mx, v.ex), Vec2.mul(mx, v.ey)); _ASSERT && common.assert(false); }; Mat22.mulT = function(mx, v) { if (v && "x" in v && "y" in v) { _ASSERT && Vec2.assert(v); return Vec2.neo(Vec2.dot(v, mx.ex), Vec2.dot(v, mx.ey)); } else if (v && "ex" in v && "ey" in v) { _ASSERT && Mat22.assert(v); var c1 = Vec2.neo(Vec2.dot(mx.ex, v.ex), Vec2.dot(mx.ey, v.ex)); var c2 = Vec2.neo(Vec2.dot(mx.ex, v.ey), Vec2.dot(mx.ey, v.ey)); return new Mat22(c1, c2); } _ASSERT && common.assert(false); }; Mat22.mulTVec2 = function(mx, v) { _ASSERT && Mat22.assert(mx); _ASSERT && Vec2.assert(v); return Vec2.neo(Vec2.dot(v, mx.ex), Vec2.dot(v, mx.ey)); }; Mat22.mulTMat22 = function(mx, v) { _ASSERT && Mat22.assert(mx); _ASSERT && Mat22.assert(v); var c1 = Vec2.neo(Vec2.dot(mx.ex, v.ex), Vec2.dot(mx.ey, v.ex)); var c2 = Vec2.neo(Vec2.dot(mx.ex, v.ey), Vec2.dot(mx.ey, v.ey)); return new Mat22(c1, c2); }; Mat22.abs = function(mx) { _ASSERT && Mat22.assert(mx); return new Mat22(Vec2.abs(mx.ex), Vec2.abs(mx.ey)); }; Mat22.add = function(mx1, mx2) { _ASSERT && Mat22.assert(mx1); _ASSERT && Mat22.assert(mx2); return new Mat22(Vec2.add(mx1.ex + mx2.ex), Vec2.add(mx1.ey + mx2.ey)); }; },{"../util/common":51,"./Math":18,"./Vec2":23}],17:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Mat33; var common = require("../util/common"); var Math = require("./Math"); var Vec2 = require("./Vec2"); var Vec3 = require("./Vec3"); function Mat33(a, b, c) { if (typeof a === "object" && a !== null) { this.ex = Vec3.clone(a); this.ey = Vec3.clone(b); this.ez = Vec3.clone(c); } else { this.ex = Vec3(); this.ey = Vec3(); this.ez = Vec3(); } } Mat33.prototype.toString = function() { return JSON.stringify(this); }; Mat33.isValid = function(o) { return o && Vec3.isValid(o.ex) && Vec3.isValid(o.ey) && Vec3.isValid(o.ez); }; Mat33.assert = function(o) { if (!_ASSERT) return; if (!Mat33.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid Mat33!"); } }; Mat33.prototype.setZero = function() { this.ex.setZero(); this.ey.setZero(); this.ez.setZero(); return this; }; Mat33.prototype.solve33 = function(v) { var det = Vec3.dot(this.ex, Vec3.cross(this.ey, this.ez)); if (det != 0) { det = 1 / det; } var r = new Vec3(); r.x = det * Vec3.dot(v, Vec3.cross(this.ey, this.ez)); r.y = det * Vec3.dot(this.ex, Vec3.cross(v, this.ez)); r.z = det * Vec3.dot(this.ex, Vec3.cross(this.ey, v)); return r; }; Mat33.prototype.solve22 = function(v) { var a11 = this.ex.x; var a12 = this.ey.x; var a21 = this.ex.y; var a22 = this.ey.y; var det = a11 * a22 - a12 * a21; if (det != 0) { det = 1 / det; } var r = Vec2.zero(); r.x = det * (a22 * v.x - a12 * v.y); r.y = det * (a11 * v.y - a21 * v.x); return r; }; Mat33.prototype.getInverse22 = function(M) { var a = this.ex.x; var b = this.ey.x; var c = this.ex.y; var d = this.ey.y; var det = a * d - b * c; if (det != 0) { det = 1 / det; } M.ex.x = det * d; M.ey.x = -det * b; M.ex.z = 0; M.ex.y = -det * c; M.ey.y = det * a; M.ey.z = 0; M.ez.x = 0; M.ez.y = 0; M.ez.z = 0; }; Mat33.prototype.getSymInverse33 = function(M) { var det = Vec3.dot(this.ex, Vec3.cross(this.ey, this.ez)); if (det != 0) { det = 1 / det; } var a11 = this.ex.x; var a12 = this.ey.x; var a13 = this.ez.x; var a22 = this.ey.y; var a23 = this.ez.y; var a33 = this.ez.z; M.ex.x = det * (a22 * a33 - a23 * a23); M.ex.y = det * (a13 * a23 - a12 * a33); M.ex.z = det * (a12 * a23 - a13 * a22); M.ey.x = M.ex.y; M.ey.y = det * (a11 * a33 - a13 * a13); M.ey.z = det * (a13 * a12 - a11 * a23); M.ez.x = M.ex.z; M.ez.y = M.ey.z; M.ez.z = det * (a11 * a22 - a12 * a12); }; Mat33.mul = function(a, b) { _ASSERT && Mat33.assert(a); if (b && "z" in b && "y" in b && "x" in b) { _ASSERT && Vec3.assert(b); var x = a.ex.x * b.x + a.ey.x * b.y + a.ez.x * b.z; var y = a.ex.y * b.x + a.ey.y * b.y + a.ez.y * b.z; var z = a.ex.z * b.x + a.ey.z * b.y + a.ez.z * b.z; return new Vec3(x, y, z); } else if (b && "y" in b && "x" in b) { _ASSERT && Vec2.assert(b); var x = a.ex.x * b.x + a.ey.x * b.y; var y = a.ex.y * b.x + a.ey.y * b.y; return Vec2.neo(x, y); } _ASSERT && common.assert(false); }; Mat33.mulVec3 = function(a, b) { _ASSERT && Mat33.assert(a); _ASSERT && Vec3.assert(b); var x = a.ex.x * b.x + a.ey.x * b.y + a.ez.x * b.z; var y = a.ex.y * b.x + a.ey.y * b.y + a.ez.y * b.z; var z = a.ex.z * b.x + a.ey.z * b.y + a.ez.z * b.z; return new Vec3(x, y, z); }; Mat33.mulVec2 = function(a, b) { _ASSERT && Mat33.assert(a); _ASSERT && Vec2.assert(b); var x = a.ex.x * b.x + a.ey.x * b.y; var y = a.ex.y * b.x + a.ey.y * b.y; return Vec2.neo(x, y); }; Mat33.add = function(a, b) { _ASSERT && Mat33.assert(a); _ASSERT && Mat33.assert(b); return new Mat33(Vec3.add(a.ex + b.ex), Vec3.add(a.ey + b.ey), Vec3.add(a.ez + b.ez)); }; },{"../util/common":51,"./Math":18,"./Vec2":23,"./Vec3":24}],18:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var native = Math; var math = module.exports = create(native); math.EPSILON = 1e-9; math.isFinite = function(x) { return typeof x === "number" && isFinite(x) && !isNaN(x); }; math.assert = function(x) { if (!_ASSERT) return; if (!math.isFinite(x)) { _DEBUG && common.debug(x); throw new Error("Invalid Number!"); } }; math.invSqrt = function(x) { return 1 / native.sqrt(x); }; math.nextPowerOfTwo = function(x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x + 1; }; math.isPowerOfTwo = function(x) { return x > 0 && (x & x - 1) == 0; }; math.mod = function(num, min, max) { if (typeof min === "undefined") { max = 1, min = 0; } else if (typeof max === "undefined") { max = min, min = 0; } if (max > min) { num = (num - min) % (max - min); return num + (num < 0 ? max : min); } else { num = (num - max) % (min - max); return num + (num <= 0 ? min : max); } }; math.clamp = function(num, min, max) { if (num < min) { return min; } else if (num > max) { return max; } else { return num; } }; math.random = function(min, max) { if (typeof min === "undefined") { max = 1; min = 0; } else if (typeof max === "undefined") { max = min; min = 0; } return min == max ? min : native.random() * (max - min) + min; }; },{"../util/common":51,"../util/create":52}],19:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Position; var Vec2 = require("./Vec2"); var Rot = require("./Rot"); function Position() { this.c = Vec2.zero(); this.a = 0; } Position.prototype.getTransform = function(xf, p) { xf.q.set(this.a); xf.p.set(Vec2.sub(this.c, Rot.mulVec2(xf.q, p))); return xf; }; },{"./Rot":20,"./Vec2":23}],20:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Rot; var common = require("../util/common"); var Vec2 = require("./Vec2"); var Math = require("./Math"); function Rot(angle) { if (!(this instanceof Rot)) { return new Rot(angle); } if (typeof angle === "number") { this.setAngle(angle); } else if (typeof angle === "object") { this.set(angle); } else { this.setIdentity(); } } Rot.neo = function(angle) { var obj = Object.create(Rot.prototype); obj.setAngle(angle); return obj; }; Rot.clone = function(rot) { _ASSERT && Rot.assert(rot); var obj = Object.create(Rot.prototype); obj.s = rot.s; obj.c = rot.c; return obj; }; Rot.identity = function() { var obj = Object.create(Rot.prototype); obj.s = 0; obj.c = 1; return obj; }; Rot.isValid = function(o) { return o && Math.isFinite(o.s) && Math.isFinite(o.c); }; Rot.assert = function(o) { if (!_ASSERT) return; if (!Rot.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid Rot!"); } }; Rot.prototype.setIdentity = function() { this.s = 0; this.c = 1; return this; }; Rot.prototype.set = function(angle) { if (typeof angle === "object") { _ASSERT && Rot.assert(angle); this.s = angle.s; this.c = angle.c; } else { _ASSERT && Math.assert(angle); this.s = Math.sin(angle); this.c = Math.cos(angle); } }; Rot.prototype.setAngle = function(angle) { _ASSERT && Math.assert(angle); this.s = Math.sin(angle); this.c = Math.cos(angle); }; Rot.prototype.getAngle = function() { return Math.atan2(this.s, this.c); }; Rot.prototype.getXAxis = function() { return Vec2.neo(this.c, this.s); }; Rot.prototype.getYAxis = function() { return Vec2.neo(-this.s, this.c); }; Rot.mul = function(rot, m) { _ASSERT && Rot.assert(rot); if ("c" in m && "s" in m) { _ASSERT && Rot.assert(m); var qr = Rot.identity(); qr.s = rot.s * m.c + rot.c * m.s; qr.c = rot.c * m.c - rot.s * m.s; return qr; } else if ("x" in m && "y" in m) { _ASSERT && Vec2.assert(m); return Vec2.neo(rot.c * m.x - rot.s * m.y, rot.s * m.x + rot.c * m.y); } }; Rot.mulRot = function(rot, m) { _ASSERT && Rot.assert(rot); _ASSERT && Rot.assert(m); var qr = Rot.identity(); qr.s = rot.s * m.c + rot.c * m.s; qr.c = rot.c * m.c - rot.s * m.s; return qr; }; Rot.mulVec2 = function(rot, m) { _ASSERT && Rot.assert(rot); _ASSERT && Vec2.assert(m); return Vec2.neo(rot.c * m.x - rot.s * m.y, rot.s * m.x + rot.c * m.y); }; Rot.mulVec2_ = function(rot, m, _) { _ASSERT && Rot.assert(rot); _ASSERT && Vec2.assert(m); return _.set(rot.c * m.x - rot.s * m.y, rot.s * m.x + rot.c * m.y); }; Rot.mulSub = function(rot, v, w) { var x = rot.c * (v.x - w.x) - rot.s * (v.y - w.y); var y = rot.s * (v.x - w.y) + rot.c * (v.y - w.y); return Vec2.neo(x, y); }; Rot.mulT = function(rot, m) { if ("c" in m && "s" in m) { _ASSERT && Rot.assert(m); var qr = Rot.identity(); qr.s = rot.c * m.s - rot.s * m.c; qr.c = rot.c * m.c + rot.s * m.s; return qr; } else if ("x" in m && "y" in m) { _ASSERT && Vec2.assert(m); return Vec2.neo(rot.c * m.x + rot.s * m.y, -rot.s * m.x + rot.c * m.y); } }; Rot.mulTRot = function(rot, m) { _ASSERT && Rot.assert(m); var qr = Rot.identity(); qr.s = rot.c * m.s - rot.s * m.c; qr.c = rot.c * m.c + rot.s * m.s; return qr; }; Rot.mulTRot_ = function(rot, m, _) { _ASSERT && Rot.assert(m); var qr = _.setIdentity(); qr.s = rot.c * m.s - rot.s * m.c; qr.c = rot.c * m.c + rot.s * m.s; return qr; }; Rot.mulTVec2 = function(rot, m) { _ASSERT && Vec2.assert(m); return Vec2.neo(rot.c * m.x + rot.s * m.y, -rot.s * m.x + rot.c * m.y); }; Rot.mulTVec2_ = function(rot, m, _) { _ASSERT && Vec2.assert(m); return _.set(rot.c * m.x + rot.s * m.y, -rot.s * m.x + rot.c * m.y); }; },{"../util/common":51,"./Math":18,"./Vec2":23}],21:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Sweep; var common = require("../util/common"); var Math = require("./Math"); var Vec2 = require("./Vec2"); var Rot = require("./Rot"); var Transform = require("./Transform"); function Sweep(c, a) { _ASSERT && common.assert(typeof c === "undefined"); _ASSERT && common.assert(typeof a === "undefined"); this.localCenter = Vec2.zero(); this.c = Vec2.zero(); this.a = 0; this.alpha0 = 0; this.c0 = Vec2.zero(); this.a0 = 0; } Sweep.prototype.setTransform = function(xf) { var c = Transform.mulVec2(xf, this.localCenter); this.c.set(c); this.c0.set(c); this.a = xf.q.getAngle(); this.a0 = xf.q.getAngle(); }; Sweep.prototype.setLocalCenter = function(localCenter, xf) { this.localCenter.set(localCenter); var c = Transform.mulVec2(xf, this.localCenter); this.c.set(c); this.c0.set(c); }; Sweep.prototype.getTransform = function(xf, beta) { beta = typeof beta === "undefined" ? 0 : beta; xf.q.setAngle((1 - beta) * this.a0 + beta * this.a); xf.p.setCombine(1 - beta, this.c0, beta, this.c); xf.p.sub(Rot.mulVec2(xf.q, this.localCenter)); }; Sweep.prototype.advance = function(alpha) { _ASSERT && common.assert(this.alpha0 < 1); var beta = (alpha - this.alpha0) / (1 - this.alpha0); this.c0.setCombine(beta, this.c, 1 - beta, this.c0); this.a0 = beta * this.a + (1 - beta) * this.a0; this.alpha0 = alpha; }; Sweep.prototype.forward = function() { this.a0 = this.a; this.c0.set(this.c); }; Sweep.prototype.normalize = function() { var a0 = Math.mod(this.a0, -Math.PI, +Math.PI); this.a -= this.a0 - a0; this.a0 = a0; }; Sweep.prototype.clone = function() { var clone = new Sweep(); clone.localCenter.set(this.localCenter); clone.alpha0 = this.alpha0; clone.a0 = this.a0; clone.a = this.a; clone.c0.set(this.c0); clone.c.set(this.c); return clone; }; Sweep.prototype.set = function(that) { this.localCenter.set(that.localCenter); this.alpha0 = that.alpha0; this.a0 = that.a0; this.a = that.a; this.c0.set(that.c0); this.c.set(that.c); }; },{"../util/common":51,"./Math":18,"./Rot":20,"./Transform":22,"./Vec2":23}],22:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Transform; var common = require("../util/common"); var Vec2 = require("./Vec2"); var Rot = require("./Rot"); function Transform(position, rotation) { if (!(this instanceof Transform)) { return new Transform(position, rotation); } this.p = Vec2.zero(); this.q = Rot.identity(); if (typeof position !== "undefined") { this.p.set(position); } if (typeof rotation !== "undefined") { this.q.set(rotation); } } Transform.clone = function(xf) { var obj = Object.create(Transform.prototype); obj.p = Vec2.clone(xf.p); obj.q = Rot.clone(xf.q); return obj; }; Transform.neo = function(position, rotation) { var obj = Object.create(Transform.prototype); obj.p = Vec2.clone(position); obj.q = Rot.clone(rotation); return obj; }; Transform.identity = function() { var obj = Object.create(Transform.prototype); obj.p = Vec2.zero(); obj.q = Rot.identity(); return obj; }; Transform.prototype.setIdentity = function() { this.p.setZero(); this.q.setIdentity(); return this; }; Transform.prototype.set = function(a, b) { if (typeof b === "undefined") { this.p.set(a.p); this.q.set(a.q); } else { this.p.set(a); this.q.set(b); } }; Transform.isValid = function(o) { return o && Vec2.isValid(o.p) && Rot.isValid(o.q); }; Transform.assert = function(o) { if (!_ASSERT) return; if (!Transform.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid Transform!"); } }; Transform.mul = function(a, b) { _ASSERT && Transform.assert(a); if (Array.isArray(b)) { var arr = []; for (var i = 0; i < b.length; i++) { arr[i] = Transform.mul(a, b[i]); } return arr; } else if ("x" in b && "y" in b) { _ASSERT && Vec2.assert(b); var x = a.q.c * b.x - a.q.s * b.y + a.p.x; var y = a.q.s * b.x + a.q.c * b.y + a.p.y; return Vec2.neo(x, y); } else if ("p" in b && "q" in b) { _ASSERT && Transform.assert(b); var xf = Transform.identity(); xf.q = Rot.mulRot(a.q, b.q); xf.p = Vec2.add(Rot.mulVec2(a.q, b.p), a.p); return xf; } }; Transform.mulAll = function(a, b) { _ASSERT && Transform.assert(a); var arr = []; for (var i = 0; i < b.length; i++) { arr[i] = Transform.mul(a, b[i]); } return arr; }; Transform.mulFn = function(a) { _ASSERT && Transform.assert(a); return function(b) { return Transform.mul(a, b); }; }; Transform.mulVec2 = function(a, b) { _ASSERT && Transform.assert(a); _ASSERT && Vec2.assert(b); var x = a.q.c * b.x - a.q.s * b.y + a.p.x; var y = a.q.s * b.x + a.q.c * b.y + a.p.y; return Vec2.neo(x, y); }; Transform.mulVec2_ = function(a, b, _) { _ASSERT && Transform.assert(a); _ASSERT && Vec2.assert(b); var x = a.q.c * b.x - a.q.s * b.y + a.p.x; var y = a.q.s * b.x + a.q.c * b.y + a.p.y; return _.set(x, y); }; Transform.mulXf = function(a, b) { _ASSERT && Transform.assert(a); _ASSERT && Transform.assert(b); var xf = Transform.identity(); xf.q = Rot.mulRot(a.q, b.q); xf.p = Vec2.add(Rot.mulVec2(a.q, b.p), a.p); return xf; }; Transform.mulT = function(a, b) { _ASSERT && Transform.assert(a); if ("x" in b && "y" in b) { _ASSERT && Vec2.assert(b); var px = b.x - a.p.x; var py = b.y - a.p.y; var x = a.q.c * px + a.q.s * py; var y = -a.q.s * px + a.q.c * py; return Vec2.neo(x, y); } else if ("p" in b && "q" in b) { _ASSERT && Transform.assert(b); var xf = Transform.identity(); xf.q.set(Rot.mulTRot(a.q, b.q)); xf.p.set(Rot.mulTVec2(a.q, Vec2.sub(b.p, a.p))); return xf; } }; Transform.mulTVec2 = function(a, b) { _ASSERT && Transform.assert(a); _ASSERT && Vec2.assert(b); var px = b.x - a.p.x; var py = b.y - a.p.y; var x = a.q.c * px + a.q.s * py; var y = -a.q.s * px + a.q.c * py; return Vec2.neo(x, y); }; Transform.mulTVec2_ = function(a, b, _) { _ASSERT && Transform.assert(a); _ASSERT && Vec2.assert(b); var px = b.x - a.p.x; var py = b.y - a.p.y; var x = a.q.c * px + a.q.s * py; var y = -a.q.s * px + a.q.c * py; return _.set(x, y); }; Transform.mulTXf = function(a, b) { _ASSERT && Transform.assert(a); _ASSERT && Transform.assert(b); var xf = Transform.identity(); xf.q.set(Rot.mulTRot(a.q, b.q)); xf.p.set(Rot.mulTVec2(a.q, Vec2.sub(b.p, a.p))); return xf; }; var _vt1 = Vec2.zero(); Transform.mulTXf_ = function(a, b, _) { _ASSERT && Transform.assert(a); _ASSERT && Transform.assert(b); Rot.mulTRot_(a.q, b.q, _.q); Rot.mulTVec2_(a.q, Vec2.sub(b.p, a.p, _vt1), _.p); return _; }; },{"../util/common":51,"./Rot":20,"./Vec2":23}],23:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Vec2; var common = require("../util/common"); var Math = require("./Math"); function Vec2(x, y) { if (!(this instanceof Vec2)) { return new Vec2(x, y); } if (typeof x === "undefined") { this.x = 0; this.y = 0; } else if (typeof x === "object") { this.x = x.x; this.y = x.y; } else { this.x = x; this.y = y; } _ASSERT && Vec2.assert(this); } Vec2.zero = function() { var obj = Object.create(Vec2.prototype); obj.x = 0; obj.y = 0; return obj; }; Vec2.neo = function(x, y) { var obj = Object.create(Vec2.prototype); obj.x = x; obj.y = y; return obj; }; Vec2.clone = function(v) { _ASSERT && Vec2.assert(v); return Vec2.neo(v.x, v.y); }; Vec2.prototype.toString = function() { return JSON.stringify(this); }; Vec2.isValid = function(v) { return v && Math.isFinite(v.x) && Math.isFinite(v.y); }; Vec2.assert = function(o) { if (!_ASSERT) return; if (!Vec2.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid Vec2!"); } }; Vec2.prototype.clone = function() { return Vec2.clone(this); }; Vec2.prototype.setZero = function() { this.x = 0; this.y = 0; return this; }; Vec2.prototype.set = function(x, y) { if (typeof x === "object") { _ASSERT && Vec2.assert(x); this.x = x.x; this.y = x.y; } else { _ASSERT && Math.assert(x); _ASSERT && Math.assert(y); this.x = x; this.y = y; } return this; }; Vec2.prototype.setXY = function(x, y) { this.x = x; this.y = y; return this; }; Vec2.prototype.setVec2 = function(x) { this.x = x.x; this.y = x.y; return this; }; Vec2.prototype.wSet = function(a, v, b, w) { if (typeof b !== "undefined" || typeof w !== "undefined") { return this.setCombine(a, v, b, w); } else { return this.setMul(a, v); } }; Vec2.prototype.setCombine = function(a, v, b, w) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); _ASSERT && Math.assert(b); _ASSERT && Vec2.assert(w); var x = a * v.x + b * w.x; var y = a * v.y + b * w.y; this.x = x; this.y = y; return this; }; Vec2.prototype.setMul = function(a, v) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); var x = a * v.x; var y = a * v.y; this.x = x; this.y = y; return this; }; Vec2.prototype.add = function(w) { _ASSERT && Vec2.assert(w); this.x += w.x; this.y += w.y; return this; }; Vec2.prototype.wAdd = function(a, v, b, w) { if (typeof b !== "undefined" || typeof w !== "undefined") { return this.addCombine(a, v, b, w); } else { return this.addMul(a, v); } }; Vec2.prototype.addCombine = function(a, v, b, w) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); _ASSERT && Math.assert(b); _ASSERT && Vec2.assert(w); var x = a * v.x + b * w.x; var y = a * v.y + b * w.y; this.x += x; this.y += y; return this; }; Vec2.prototype.addMul = function(a, v) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); var x = a * v.x; var y = a * v.y; this.x += x; this.y += y; return this; }; Vec2.prototype.wSub = function(a, v, b, w) { if (typeof b !== "undefined" || typeof w !== "undefined") { return this.subCombine(a, v, b, w); } else { return this.subMul(a, v); } }; Vec2.prototype.subCombine = function(a, v, b, w) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); _ASSERT && Math.assert(b); _ASSERT && Vec2.assert(w); var x = a * v.x + b * w.x; var y = a * v.y + b * w.y; this.x -= x; this.y -= y; return this; }; Vec2.prototype.subMul = function(a, v) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); var x = a * v.x; var y = a * v.y; this.x -= x; this.y -= y; return this; }; Vec2.prototype.sub = function(w) { _ASSERT && Vec2.assert(w); this.x -= w.x; this.y -= w.y; return this; }; Vec2.prototype.mul = function(m) { _ASSERT && Math.assert(m); this.x *= m; this.y *= m; return this; }; Vec2.prototype.length = function() { return Vec2.lengthOf(this); }; Vec2.prototype.lengthSquared = function() { return Vec2.lengthSquared(this); }; Vec2.prototype.normalize = function() { var length = this.length(); if (length < Math.EPSILON) { return 0; } var invLength = 1 / length; this.x *= invLength; this.y *= invLength; return length; }; Vec2.lengthOf = function(v) { _ASSERT && Vec2.assert(v); return Math.sqrt(v.x * v.x + v.y * v.y); }; Vec2.lengthSquared = function(v) { _ASSERT && Vec2.assert(v); return v.x * v.x + v.y * v.y; }; Vec2.distance = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); var dx = v.x - w.x, dy = v.y - w.y; return Math.sqrt(dx * dx + dy * dy); }; Vec2.distanceSquared = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); var dx = v.x - w.x, dy = v.y - w.y; return dx * dx + dy * dy; }; Vec2.areEqual = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return v == w || typeof w === "object" && w !== null && v.x === w.x && v.y === w.y; }; Vec2.skew = function(v) { _ASSERT && Vec2.assert(v); return Vec2.neo(-v.y, v.x); }; Vec2.dot = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return v.x * w.x + v.y * w.y; }; Vec2.cross = function(v, w) { if (typeof w === "number") { _ASSERT && Vec2.assert(v); _ASSERT && Math.assert(w); return Vec2.neo(w * v.y, -w * v.x); } else if (typeof v === "number") { _ASSERT && Math.assert(v); _ASSERT && Vec2.assert(w); return Vec2.neo(-v * w.y, v * w.x); } else { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return v.x * w.y - v.y * w.x; } }; Vec2.crossVec2Vec2 = function(v, w) { return v.x * w.y - v.y * w.x; }; Vec2.crossNumVec2_ = function(v, w, _) { return _.setXY(-v * w.y, v * w.x); }; Vec2.crossVec2Num_ = function(v, w, _) { return _.setXY(w * v.y, -w * v.x); }; Vec2.addCross = function(a, v, w) { if (typeof w === "number") { _ASSERT && Vec2.assert(v); _ASSERT && Math.assert(w); return Vec2.neo(w * v.y + a.x, -w * v.x + a.y); } else if (typeof v === "number") { _ASSERT && Math.assert(v); _ASSERT && Vec2.assert(w); return Vec2.neo(-v * w.y + a.x, v * w.x + a.y); } _ASSERT && common.assert(false); }; Vec2.add = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return Vec2.neo(v.x + w.x, v.y + w.y); }; Vec2.wAdd = function(a, v, b, w) { if (typeof b !== "undefined" || typeof w !== "undefined") { return Vec2.combine(a, v, b, w); } else { return Vec2.mul(a, v); } }; Vec2.combine = function(a, v, b, w) { return Vec2.zero().setCombine(a, v, b, w); }; Vec2.combine_ = function(a, v, b, w, _) { return _.setCombine(a, v, b, w); }; Vec2.sub = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return Vec2.neo(v.x - w.x, v.y - w.y); }; Vec2.sub_ = function(v, w, _) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return _.setXY(v.x - w.x, v.y - w.y); }; Vec2.mul = function(a, b) { if (typeof a === "object") { _ASSERT && Vec2.assert(a); _ASSERT && Math.assert(b); return Vec2.neo(a.x * b, a.y * b); } else if (typeof b === "object") { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(b); return Vec2.neo(a * b.x, a * b.y); } }; Vec2.mulVec2Num_ = function(a, b, _) { return _.setXY(a.x * b, a.y * b); }; Vec2.mulNumVec2_ = function(a, b, _) { return _.setXY(a * b.x, a * b.y); }; Vec2.prototype.neg = function() { this.x = -this.x; this.y = -this.y; return this; }; Vec2.neg = function(v) { _ASSERT && Vec2.assert(v); return Vec2.neo(-v.x, -v.y); }; Vec2.neg_ = function(v, _) { _ASSERT && Vec2.assert(v); return _.setXY(-v.x, -v.y); }; Vec2.abs = function(v) { _ASSERT && Vec2.assert(v); return Vec2.neo(Math.abs(v.x), Math.abs(v.y)); }; Vec2.mid = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return Vec2.neo((v.x + w.x) * .5, (v.y + w.y) * .5); }; Vec2.upper = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return Vec2.neo(Math.max(v.x, w.x), Math.max(v.y, w.y)); }; Vec2.lower = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return Vec2.neo(Math.min(v.x, w.x), Math.min(v.y, w.y)); }; Vec2.prototype.clamp = function(max) { var lengthSqr = this.x * this.x + this.y * this.y; if (lengthSqr > max * max) { var invLength = Math.invSqrt(lengthSqr); this.x *= invLength * max; this.y *= invLength * max; } return this; }; Vec2.clamp = function(v, max) { v = Vec2.neo(v.x, v.y); v.clamp(max); return v; }; Vec2.scaleFn = function(x, y) { return function(v) { return Vec2.neo(v.x * x, v.y * y); }; }; Vec2.translateFn = function(x, y) { return function(v) { return Vec2.neo(v.x + x, v.y + y); }; }; },{"../util/common":51,"./Math":18}],24:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Vec3; var common = require("../util/common"); var Math = require("./Math"); function Vec3(x, y, z) { if (!(this instanceof Vec3)) { return new Vec3(x, y, z); } if (typeof x === "undefined") { this.x = 0, this.y = 0, this.z = 0; } else if (typeof x === "object") { this.x = x.x, this.y = x.y, this.z = x.z; } else { this.x = x, this.y = y, this.z = z; } _ASSERT && Vec3.assert(this); } Vec3.neo = function(x, y, z) { var obj = Object.create(Vec3.prototype); obj.x = x; obj.y = y; obj.z = z; return obj; }; Vec3.clone = function(v) { _ASSERT && Vec3.assert(v); return Vec3.neo(v.x, v.y, v.z); }; Vec3.prototype.toString = function() { return JSON.stringify(this); }; Vec3.isValid = function(v) { return v && Math.isFinite(v.x) && Math.isFinite(v.y) && Math.isFinite(v.z); }; Vec3.assert = function(o) { if (!_ASSERT) return; if (!Vec3.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid Vec3!"); } }; Vec3.prototype.setZero = function() { this.x = 0; this.y = 0; this.z = 0; return this; }; Vec3.prototype.set = function(x, y, z) { this.x = x; this.y = y; this.z = z; return this; }; Vec3.prototype.add = function(w) { this.x += w.x; this.y += w.y; this.z += w.z; return this; }; Vec3.prototype.sub = function(w) { this.x -= w.x; this.y -= w.y; this.z -= w.z; return this; }; Vec3.prototype.mul = function(m) { this.x *= m; this.y *= m; this.z *= m; return this; }; Vec3.areEqual = function(v, w) { _ASSERT && Vec3.assert(v); _ASSERT && Vec3.assert(w); return v == w || typeof v === "object" && v !== null && typeof w === "object" && w !== null && v.x === w.x && v.y === w.y && v.z === w.z; }; Vec3.dot = function(v, w) { return v.x * w.x + v.y * w.y + v.z * w.z; }; Vec3.cross = function(v, w) { return new Vec3(v.y * w.z - v.z * w.y, v.z * w.x - v.x * w.z, v.x * w.y - v.y * w.x); }; Vec3.add = function(v, w) { return new Vec3(v.x + w.x, v.y + w.y, v.z + w.z); }; Vec3.sub = function(v, w) { return new Vec3(v.x - w.x, v.y - w.y, v.z - w.z); }; Vec3.mul = function(v, m) { return new Vec3(m * v.x, m * v.y, m * v.z); }; Vec3.prototype.neg = function() { this.x = -this.x; this.y = -this.y; this.z = -this.z; return this; }; Vec3.neg = function(v) { return new Vec3(-v.x, -v.y, -v.z); }; },{"../util/common":51,"./Math":18}],25:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Velocity; var Vec2 = require("./Vec2"); function Velocity() { this.v = Vec2.zero(); this.w = 0; } },{"./Vec2":23}],26:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; exports.toString = function(newline) { newline = typeof newline === "string" ? newline : "\n"; var string = ""; for (var name in this) { if (typeof this[name] !== "function" && typeof this[name] !== "object") { string += name + ": " + this[name] + newline; } } return string; }; },{}],27:[function(require,module,exports){ exports.internal = {}; exports.Math = require("./common/Math"); exports.Vec2 = require("./common/Vec2"); exports.Vec3 = require("./common/Vec3"); exports.Mat22 = require("./common/Mat22"); exports.Mat33 = require("./common/Mat33"); exports.Transform = require("./common/Transform"); exports.Rot = require("./common/Rot"); exports.AABB = require("./collision/AABB"); exports.Shape = require("./Shape"); exports.Fixture = require("./Fixture"); exports.Body = require("./Body"); exports.Contact = require("./Contact"); exports.Joint = require("./Joint"); exports.World = require("./World"); exports.Circle = require("./shape/CircleShape"); exports.Edge = require("./shape/EdgeShape"); exports.Polygon = require("./shape/PolygonShape"); exports.Chain = require("./shape/ChainShape"); exports.Box = require("./shape/BoxShape"); require("./shape/CollideCircle"); require("./shape/CollideEdgeCircle"); exports.internal.CollidePolygons = require("./shape/CollidePolygon"); require("./shape/CollideCirclePolygone"); require("./shape/CollideEdgePolygon"); exports.DistanceJoint = require("./joint/DistanceJoint"); exports.FrictionJoint = require("./joint/FrictionJoint"); exports.GearJoint = require("./joint/GearJoint"); exports.MotorJoint = require("./joint/MotorJoint"); exports.MouseJoint = require("./joint/MouseJoint"); exports.PrismaticJoint = require("./joint/PrismaticJoint"); exports.PulleyJoint = require("./joint/PulleyJoint"); exports.RevoluteJoint = require("./joint/RevoluteJoint"); exports.RopeJoint = require("./joint/RopeJoint"); exports.WeldJoint = require("./joint/WeldJoint"); exports.WheelJoint = require("./joint/WheelJoint"); exports.internal.Sweep = require("./common/Sweep"); exports.internal.stats = require("./common/stats"); exports.internal.Manifold = require("./Manifold"); exports.internal.Distance = require("./collision/Distance"); exports.internal.TimeOfImpact = require("./collision/TimeOfImpact"); exports.internal.DynamicTree = require("./collision/DynamicTree"); exports.internal.Settings = require("./Settings"); },{"./Body":2,"./Contact":3,"./Fixture":4,"./Joint":5,"./Manifold":6,"./Settings":7,"./Shape":8,"./World":10,"./collision/AABB":11,"./collision/Distance":13,"./collision/DynamicTree":14,"./collision/TimeOfImpact":15,"./common/Mat22":16,"./common/Mat33":17,"./common/Math":18,"./common/Rot":20,"./common/Sweep":21,"./common/Transform":22,"./common/Vec2":23,"./common/Vec3":24,"./common/stats":26,"./joint/DistanceJoint":28,"./joint/FrictionJoint":29,"./joint/GearJoint":30,"./joint/MotorJoint":31,"./joint/MouseJoint":32,"./joint/PrismaticJoint":33,"./joint/PulleyJoint":34,"./joint/RevoluteJoint":35,"./joint/RopeJoint":36,"./joint/WeldJoint":37,"./joint/WheelJoint":38,"./shape/BoxShape":39,"./shape/ChainShape":40,"./shape/CircleShape":41,"./shape/CollideCircle":42,"./shape/CollideCirclePolygone":43,"./shape/CollideEdgeCircle":44,"./shape/CollideEdgePolygon":45,"./shape/CollidePolygon":46,"./shape/EdgeShape":47,"./shape/PolygonShape":48}],28:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = DistanceJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); DistanceJoint.TYPE = "distance-joint"; DistanceJoint._super = Joint; DistanceJoint.prototype = create(DistanceJoint._super.prototype); var DEFAULTS = { frequencyHz: 0, dampingRatio: 0 }; function DistanceJoint(def, bodyA, bodyB, anchorA, anchorB) { if (!(this instanceof DistanceJoint)) { return new DistanceJoint(def, bodyA, bodyB, anchorA, anchorB); } if (bodyB && anchorA && "m_type" in anchorA && "x" in bodyB && "y" in bodyB) { var temp = bodyB; bodyB = anchorA; anchorA = temp; } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = DistanceJoint.TYPE; this.m_localAnchorA = anchorA ? bodyA.getLocalPoint(anchorA) : def.localAnchorA || Vec2.zero(); this.m_localAnchorB = anchorB ? bodyB.getLocalPoint(anchorB) : def.localAnchorB || Vec2.zero(); this.m_length = Math.isFinite(def.length) ? def.length : Vec2.distance(bodyA.getWorldPoint(this.m_localAnchorA), bodyB.getWorldPoint(this.m_localAnchorB)); this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_impulse = 0; this.m_gamma = 0; this.m_bias = 0; this.m_u; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass; } DistanceJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; DistanceJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; DistanceJoint.prototype.setLength = function(length) { this.m_length = length; }; DistanceJoint.prototype.getLength = function() { return this.m_length; }; DistanceJoint.prototype.setFrequency = function(hz) { this.m_frequencyHz = hz; }; DistanceJoint.prototype.getFrequency = function() { return this.m_frequencyHz; }; DistanceJoint.prototype.setDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; DistanceJoint.prototype.getDampingRatio = function() { return this.m_dampingRatio; }; DistanceJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; DistanceJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; DistanceJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(this.m_impulse, this.m_u).mul(inv_dt); }; DistanceJoint.prototype.getReactionTorque = function(inv_dt) { return 0; }; DistanceJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); this.m_u = Vec2.sub(Vec2.add(cB, this.m_rB), Vec2.add(cA, this.m_rA)); var length = this.m_u.length(); if (length > Settings.linearSlop) { this.m_u.mul(1 / length); } else { this.m_u.set(0, 0); } var crAu = Vec2.cross(this.m_rA, this.m_u); var crBu = Vec2.cross(this.m_rB, this.m_u); var invMass = this.m_invMassA + this.m_invIA * crAu * crAu + this.m_invMassB + this.m_invIB * crBu * crBu; this.m_mass = invMass != 0 ? 1 / invMass : 0; if (this.m_frequencyHz > 0) { var C = length - this.m_length; var omega = 2 * Math.PI * this.m_frequencyHz; var d = 2 * this.m_mass * this.m_dampingRatio * omega; var k = this.m_mass * omega * omega; var h = step.dt; this.m_gamma = h * (d + h * k); this.m_gamma = this.m_gamma != 0 ? 1 / this.m_gamma : 0; this.m_bias = C * h * k * this.m_gamma; invMass += this.m_gamma; this.m_mass = invMass != 0 ? 1 / invMass : 0; } else { this.m_gamma = 0; this.m_bias = 0; } if (step.warmStarting) { this.m_impulse *= step.dtRatio; var P = Vec2.mul(this.m_impulse, this.m_u); vA.subMul(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.addMul(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; DistanceJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var vpA = Vec2.add(vA, Vec2.cross(wA, this.m_rA)); var vpB = Vec2.add(vB, Vec2.cross(wB, this.m_rB)); var Cdot = Vec2.dot(this.m_u, vpB) - Vec2.dot(this.m_u, vpA); var impulse = -this.m_mass * (Cdot + this.m_bias + this.m_gamma * this.m_impulse); this.m_impulse += impulse; var P = Vec2.mul(impulse, this.m_u); vA.subMul(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.addMul(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; DistanceJoint.prototype.solvePositionConstraints = function(step) { if (this.m_frequencyHz > 0) { return true; } var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB); var u = Vec2.sub(Vec2.add(cB, rB), Vec2.add(cA, rA)); var length = u.normalize(); var C = length - this.m_length; C = Math.clamp(C, -Settings.maxLinearCorrection, Settings.maxLinearCorrection); var impulse = -this.m_mass * C; var P = Vec2.mul(impulse, u); cA.subMul(this.m_invMassA, P); aA -= this.m_invIA * Vec2.cross(rA, P); cB.addMul(this.m_invMassB, P); aB += this.m_invIB * Vec2.cross(rB, P); this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return Math.abs(C) < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],29:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = FrictionJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); FrictionJoint.TYPE = "friction-joint"; FrictionJoint._super = Joint; FrictionJoint.prototype = create(FrictionJoint._super.prototype); var DEFAULTS = { maxForce: 0, maxTorque: 0 }; function FrictionJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof FrictionJoint)) { return new FrictionJoint(def, bodyA, bodyB, anchor); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = FrictionJoint.TYPE; this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero(); this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero(); this.m_linearImpulse = Vec2.zero(); this.m_angularImpulse = 0; this.m_maxForce = def.maxForce; this.m_maxTorque = def.maxTorque; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_linearMass; this.m_angularMass; } FrictionJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; FrictionJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; FrictionJoint.prototype.setMaxForce = function(force) { _ASSERT && common.assert(Math.isFinite(force) && force >= 0); this.m_maxForce = force; }; FrictionJoint.prototype.getMaxForce = function() { return this.m_maxForce; }; FrictionJoint.prototype.setMaxTorque = function(torque) { _ASSERT && common.assert(Math.isFinite(torque) && torque >= 0); this.m_maxTorque = torque; }; FrictionJoint.prototype.getMaxTorque = function() { return this.m_maxTorque; }; FrictionJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; FrictionJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; FrictionJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(inv_dt, this.m_linearImpulse); }; FrictionJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_angularImpulse; }; FrictionJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA), qB = Rot.neo(aB); this.m_rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var K = new Mat22(); K.ex.x = mA + mB + iA * this.m_rA.y * this.m_rA.y + iB * this.m_rB.y * this.m_rB.y; K.ex.y = -iA * this.m_rA.x * this.m_rA.y - iB * this.m_rB.x * this.m_rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * this.m_rA.x * this.m_rA.x + iB * this.m_rB.x * this.m_rB.x; this.m_linearMass = K.getInverse(); this.m_angularMass = iA + iB; if (this.m_angularMass > 0) { this.m_angularMass = 1 / this.m_angularMass; } if (step.warmStarting) { this.m_linearImpulse.mul(step.dtRatio); this.m_angularImpulse *= step.dtRatio; var P = Vec2.neo(this.m_linearImpulse.x, this.m_linearImpulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_angularImpulse); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_angularImpulse); } else { this.m_linearImpulse.setZero(); this.m_angularImpulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; FrictionJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var h = step.dt; { var Cdot = wB - wA; var impulse = -this.m_angularMass * Cdot; var oldImpulse = this.m_angularImpulse; var maxImpulse = h * this.m_maxTorque; this.m_angularImpulse = Math.clamp(this.m_angularImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_angularImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } { var Cdot = Vec2.sub(Vec2.add(vB, Vec2.cross(wB, this.m_rB)), Vec2.add(vA, Vec2.cross(wA, this.m_rA))); var impulse = Vec2.neg(Mat22.mulVec2(this.m_linearMass, Cdot)); var oldImpulse = this.m_linearImpulse; this.m_linearImpulse.add(impulse); var maxImpulse = h * this.m_maxForce; if (this.m_linearImpulse.lengthSquared() > maxImpulse * maxImpulse) { this.m_linearImpulse.normalize(); this.m_linearImpulse.mul(maxImpulse); } impulse = Vec2.sub(this.m_linearImpulse, oldImpulse); vA.subMul(mA, impulse); wA -= iA * Vec2.cross(this.m_rA, impulse); vB.addMul(mB, impulse); wB += iB * Vec2.cross(this.m_rB, impulse); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; FrictionJoint.prototype.solvePositionConstraints = function(step) { return true; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],30:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = GearJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var RevoluteJoint = require("./RevoluteJoint"); var PrismaticJoint = require("./PrismaticJoint"); GearJoint.TYPE = "gear-joint"; GearJoint._super = Joint; GearJoint.prototype = create(GearJoint._super.prototype); var DEFAULTS = { ratio: 1 }; function GearJoint(def, bodyA, bodyB, joint1, joint2, ratio) { if (!(this instanceof GearJoint)) { return new GearJoint(def, bodyA, bodyB, joint1, joint2, ratio); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = GearJoint.TYPE; _ASSERT && common.assert(joint1.m_type === RevoluteJoint.TYPE || joint1.m_type === PrismaticJoint.TYPE); _ASSERT && common.assert(joint2.m_type === RevoluteJoint.TYPE || joint2.m_type === PrismaticJoint.TYPE); this.m_joint1 = joint1 ? joint1 : def.joint1; this.m_joint2 = joint2 ? joint2 : def.joint2; this.m_ratio = Math.isFinite(ratio) ? ratio : def.ratio; this.m_type1 = this.m_joint1.getType(); this.m_type2 = this.m_joint2.getType(); var coordinateA, coordinateB; this.m_bodyC = this.m_joint1.getBodyA(); this.m_bodyA = this.m_joint1.getBodyB(); var xfA = this.m_bodyA.m_xf; var aA = this.m_bodyA.m_sweep.a; var xfC = this.m_bodyC.m_xf; var aC = this.m_bodyC.m_sweep.a; if (this.m_type1 === RevoluteJoint.TYPE) { var revolute = this.m_joint1; this.m_localAnchorC = revolute.m_localAnchorA; this.m_localAnchorA = revolute.m_localAnchorB; this.m_referenceAngleA = revolute.m_referenceAngle; this.m_localAxisC = Vec2.zero(); coordinateA = aA - aC - this.m_referenceAngleA; } else { var prismatic = this.m_joint1; this.m_localAnchorC = prismatic.m_localAnchorA; this.m_localAnchorA = prismatic.m_localAnchorB; this.m_referenceAngleA = prismatic.m_referenceAngle; this.m_localAxisC = prismatic.m_localXAxisA; var pC = this.m_localAnchorC; var pA = Rot.mulTVec2(xfC.q, Vec2.add(Rot.mul(xfA.q, this.m_localAnchorA), Vec2.sub(xfA.p, xfC.p))); coordinateA = Vec2.dot(pA, this.m_localAxisC) - Vec2.dot(pC, this.m_localAxisC); } this.m_bodyD = this.m_joint2.getBodyA(); this.m_bodyB = this.m_joint2.getBodyB(); var xfB = this.m_bodyB.m_xf; var aB = this.m_bodyB.m_sweep.a; var xfD = this.m_bodyD.m_xf; var aD = this.m_bodyD.m_sweep.a; if (this.m_type2 === RevoluteJoint.TYPE) { var revolute = this.m_joint2; this.m_localAnchorD = revolute.m_localAnchorA; this.m_localAnchorB = revolute.m_localAnchorB; this.m_referenceAngleB = revolute.m_referenceAngle; this.m_localAxisD = Vec2.zero(); coordinateB = aB - aD - this.m_referenceAngleB; } else { var prismatic = this.m_joint2; this.m_localAnchorD = prismatic.m_localAnchorA; this.m_localAnchorB = prismatic.m_localAnchorB; this.m_referenceAngleB = prismatic.m_referenceAngle; this.m_localAxisD = prismatic.m_localXAxisA; var pD = this.m_localAnchorD; var pB = Rot.mulTVec2(xfD.q, Vec2.add(Rot.mul(xfB.q, this.m_localAnchorB), Vec2.sub(xfB.p, xfD.p))); coordinateB = Vec2.dot(pB, this.m_localAxisD) - Vec2.dot(pD, this.m_localAxisD); } this.m_constant = coordinateA + this.m_ratio * coordinateB; this.m_impulse = 0; this.m_lcA, this.m_lcB, this.m_lcC, this.m_lcD; this.m_mA, this.m_mB, this.m_mC, this.m_mD; this.m_iA, this.m_iB, this.m_iC, this.m_iD; this.m_JvAC, this.m_JvBD; this.m_JwA, this.m_JwB, this.m_JwC, this.m_JwD; this.m_mass; } GearJoint.prototype.getJoint1 = function() { return this.m_joint1; }; GearJoint.prototype.getJoint2 = function() { return this.m_joint2; }; GearJoint.prototype.setRatio = function(ratio) { _ASSERT && common.assert(Math.isFinite(ratio)); this.m_ratio = ratio; }; GearJoint.prototype.getRatio = function() { return this.m_ratio; }; GearJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; GearJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; GearJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(this.m_impulse, this.m_JvAC).mul(inv_dt); }; GearJoint.prototype.getReactionTorque = function(inv_dt) { var L = this.m_impulse * this.m_JwA; return inv_dt * L; }; GearJoint.prototype.initVelocityConstraints = function(step) { this.m_lcA = this.m_bodyA.m_sweep.localCenter; this.m_lcB = this.m_bodyB.m_sweep.localCenter; this.m_lcC = this.m_bodyC.m_sweep.localCenter; this.m_lcD = this.m_bodyD.m_sweep.localCenter; this.m_mA = this.m_bodyA.m_invMass; this.m_mB = this.m_bodyB.m_invMass; this.m_mC = this.m_bodyC.m_invMass; this.m_mD = this.m_bodyD.m_invMass; this.m_iA = this.m_bodyA.m_invI; this.m_iB = this.m_bodyB.m_invI; this.m_iC = this.m_bodyC.m_invI; this.m_iD = this.m_bodyD.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var aC = this.m_bodyC.c_position.a; var vC = this.m_bodyC.c_velocity.v; var wC = this.m_bodyC.c_velocity.w; var aD = this.m_bodyD.c_position.a; var vD = this.m_bodyD.c_velocity.v; var wD = this.m_bodyD.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var qC = Rot.neo(aC); var qD = Rot.neo(aD); this.m_mass = 0; if (this.m_type1 == RevoluteJoint.TYPE) { this.m_JvAC = Vec2.zero(); this.m_JwA = 1; this.m_JwC = 1; this.m_mass += this.m_iA + this.m_iC; } else { var u = Rot.mulVec2(qC, this.m_localAxisC); var rC = Rot.mulSub(qC, this.m_localAnchorC, this.m_lcC); var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_lcA); this.m_JvAC = u; this.m_JwC = Vec2.cross(rC, u); this.m_JwA = Vec2.cross(rA, u); this.m_mass += this.m_mC + this.m_mA + this.m_iC * this.m_JwC * this.m_JwC + this.m_iA * this.m_JwA * this.m_JwA; } if (this.m_type2 == RevoluteJoint.TYPE) { this.m_JvBD = Vec2.zero(); this.m_JwB = this.m_ratio; this.m_JwD = this.m_ratio; this.m_mass += this.m_ratio * this.m_ratio * (this.m_iB + this.m_iD); } else { var u = Rot.mulVec2(qD, this.m_localAxisD); var rD = Rot.mulSub(qD, this.m_localAnchorD, this.m_lcD); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_lcB); this.m_JvBD = Vec2.mul(this.m_ratio, u); this.m_JwD = this.m_ratio * Vec2.cross(rD, u); this.m_JwB = this.m_ratio * Vec2.cross(rB, u); this.m_mass += this.m_ratio * this.m_ratio * (this.m_mD + this.m_mB) + this.m_iD * this.m_JwD * this.m_JwD + this.m_iB * this.m_JwB * this.m_JwB; } this.m_mass = this.m_mass > 0 ? 1 / this.m_mass : 0; if (step.warmStarting) { vA.addMul(this.m_mA * this.m_impulse, this.m_JvAC); wA += this.m_iA * this.m_impulse * this.m_JwA; vB.addMul(this.m_mB * this.m_impulse, this.m_JvBD); wB += this.m_iB * this.m_impulse * this.m_JwB; vC.subMul(this.m_mC * this.m_impulse, this.m_JvAC); wC -= this.m_iC * this.m_impulse * this.m_JwC; vD.subMul(this.m_mD * this.m_impulse, this.m_JvBD); wD -= this.m_iD * this.m_impulse * this.m_JwD; } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; this.m_bodyC.c_velocity.v.set(vC); this.m_bodyC.c_velocity.w = wC; this.m_bodyD.c_velocity.v.set(vD); this.m_bodyD.c_velocity.w = wD; }; GearJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var vC = this.m_bodyC.c_velocity.v; var wC = this.m_bodyC.c_velocity.w; var vD = this.m_bodyD.c_velocity.v; var wD = this.m_bodyD.c_velocity.w; var Cdot = Vec2.dot(this.m_JvAC, vA) - Vec2.dot(this.m_JvAC, vC) + Vec2.dot(this.m_JvBD, vB) - Vec2.dot(this.m_JvBD, vD); Cdot += this.m_JwA * wA - this.m_JwC * wC + (this.m_JwB * wB - this.m_JwD * wD); var impulse = -this.m_mass * Cdot; this.m_impulse += impulse; vA.addMul(this.m_mA * impulse, this.m_JvAC); wA += this.m_iA * impulse * this.m_JwA; vB.addMul(this.m_mB * impulse, this.m_JvBD); wB += this.m_iB * impulse * this.m_JwB; vC.subMul(this.m_mC * impulse, this.m_JvAC); wC -= this.m_iC * impulse * this.m_JwC; vD.subMul(this.m_mD * impulse, this.m_JvBD); wD -= this.m_iD * impulse * this.m_JwD; this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; this.m_bodyC.c_velocity.v.set(vC); this.m_bodyC.c_velocity.w = wC; this.m_bodyD.c_velocity.v.set(vD); this.m_bodyD.c_velocity.w = wD; }; GearJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var cC = this.m_bodyC.c_position.c; var aC = this.m_bodyC.c_position.a; var cD = this.m_bodyD.c_position.c; var aD = this.m_bodyD.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var qC = Rot.neo(aC); var qD = Rot.neo(aD); var linearError = 0; var coordinateA, coordinateB; var JvAC, JvBD; var JwA, JwB, JwC, JwD; var mass = 0; if (this.m_type1 == RevoluteJoint.TYPE) { JvAC = Vec2.zero(); JwA = 1; JwC = 1; mass += this.m_iA + this.m_iC; coordinateA = aA - aC - this.m_referenceAngleA; } else { var u = Rot.mulVec2(qC, this.m_localAxisC); var rC = Rot.mulSub(qC, this.m_localAnchorC, this.m_lcC); var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_lcA); JvAC = u; JwC = Vec2.cross(rC, u); JwA = Vec2.cross(rA, u); mass += this.m_mC + this.m_mA + this.m_iC * JwC * JwC + this.m_iA * JwA * JwA; var pC = Vec2.sub(this.m_localAnchorC, this.m_lcC); var pA = Rot.mulTVec2(qC, Vec2.add(rA, Vec2.sub(cA, cC))); coordinateA = Vec2.dot(Vec2.sub(pA, pC), this.m_localAxisC); } if (this.m_type2 == RevoluteJoint.TYPE) { JvBD = Vec2.zero(); JwB = this.m_ratio; JwD = this.m_ratio; mass += this.m_ratio * this.m_ratio * (this.m_iB + this.m_iD); coordinateB = aB - aD - this.m_referenceAngleB; } else { var u = Rot.mulVec2(qD, this.m_localAxisD); var rD = Rot.mulSub(qD, this.m_localAnchorD, this.m_lcD); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_lcB); JvBD = Vec2.mul(this.m_ratio, u); JwD = this.m_ratio * Vec2.cross(rD, u); JwB = this.m_ratio * Vec2.cross(rB, u); mass += this.m_ratio * this.m_ratio * (this.m_mD + this.m_mB) + this.m_iD * JwD * JwD + this.m_iB * JwB * JwB; var pD = Vec2.sub(this.m_localAnchorD, this.m_lcD); var pB = Rot.mulTVec2(qD, Vec2.add(rB, Vec2.sub(cB, cD))); coordinateB = Vec2.dot(pB, this.m_localAxisD) - Vec2.dot(pD, this.m_localAxisD); } var C = coordinateA + this.m_ratio * coordinateB - this.m_constant; var impulse = 0; if (mass > 0) { impulse = -C / mass; } cA.addMul(this.m_mA * impulse, JvAC); aA += this.m_iA * impulse * JwA; cB.addMul(this.m_mB * impulse, JvBD); aB += this.m_iB * impulse * JwB; cC.subMul(this.m_mC * impulse, JvAC); aC -= this.m_iC * impulse * JwC; cD.subMul(this.m_mD * impulse, JvBD); aD -= this.m_iD * impulse * JwD; this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; this.m_bodyC.c_position.c.set(cC); this.m_bodyC.c_position.a = aC; this.m_bodyD.c_position.c.set(cD); this.m_bodyD.c_position.a = aD; return linearError < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53,"./PrismaticJoint":33,"./RevoluteJoint":35}],31:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = MotorJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); MotorJoint.TYPE = "motor-joint"; MotorJoint._super = Joint; MotorJoint.prototype = create(MotorJoint._super.prototype); var DEFAULTS = { maxForce: 1, maxTorque: 1, correctionFactor: .3 }; function MotorJoint(def, bodyA, bodyB) { if (!(this instanceof MotorJoint)) { return new MotorJoint(def, bodyA, bodyB); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = MotorJoint.TYPE; this.m_linearOffset = def.linearOffset ? def.linearOffset : bodyA.getLocalPoint(bodyB.getPosition()); var angleA = bodyA.getAngle(); var angleB = bodyB.getAngle(); this.m_angularOffset = angleB - angleA; this.m_linearImpulse = Vec2.zero(); this.m_angularImpulse = 0; this.m_maxForce = def.maxForce; this.m_maxTorque = def.maxTorque; this.m_correctionFactor = def.correctionFactor; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_linearError; this.m_angularError; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_linearMass; this.m_angularMass; } MotorJoint.prototype.setMaxForce = function(force) { _ASSERT && common.assert(Math.isFinite(force) && force >= 0); this.m_maxForce = force; }; MotorJoint.prototype.getMaxForce = function() { return this.m_maxForce; }; MotorJoint.prototype.setMaxTorque = function(torque) { _ASSERT && common.assert(Math.isFinite(torque) && torque >= 0); this.m_maxTorque = torque; }; MotorJoint.prototype.getMaxTorque = function() { return this.m_maxTorque; }; MotorJoint.prototype.setCorrectionFactor = function(factor) { _ASSERT && common.assert(Math.isFinite(factor) && 0 <= factor && factor <= 1); this.m_correctionFactor = factor; }; MotorJoint.prototype.getCorrectionFactor = function() { return this.m_correctionFactor; }; MotorJoint.prototype.setLinearOffset = function(linearOffset) { if (linearOffset.x != this.m_linearOffset.x || linearOffset.y != this.m_linearOffset.y) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_linearOffset = linearOffset; } }; MotorJoint.prototype.getLinearOffset = function() { return this.m_linearOffset; }; MotorJoint.prototype.setAngularOffset = function(angularOffset) { if (angularOffset != this.m_angularOffset) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_angularOffset = angularOffset; } }; MotorJoint.prototype.getAngularOffset = function() { return this.m_angularOffset; }; MotorJoint.prototype.getAnchorA = function() { return this.m_bodyA.getPosition(); }; MotorJoint.prototype.getAnchorB = function() { return this.m_bodyB.getPosition(); }; MotorJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(inv_dt, this.m_linearImpulse); }; MotorJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_angularImpulse; }; MotorJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA), qB = Rot.neo(aB); this.m_rA = Rot.mulVec2(qA, Vec2.neg(this.m_localCenterA)); this.m_rB = Rot.mulVec2(qB, Vec2.neg(this.m_localCenterB)); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var K = new Mat22(); K.ex.x = mA + mB + iA * this.m_rA.y * this.m_rA.y + iB * this.m_rB.y * this.m_rB.y; K.ex.y = -iA * this.m_rA.x * this.m_rA.y - iB * this.m_rB.x * this.m_rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * this.m_rA.x * this.m_rA.x + iB * this.m_rB.x * this.m_rB.x; this.m_linearMass = K.getInverse(); this.m_angularMass = iA + iB; if (this.m_angularMass > 0) { this.m_angularMass = 1 / this.m_angularMass; } this.m_linearError = Vec2.zero(); this.m_linearError.addCombine(1, cB, 1, this.m_rB); this.m_linearError.subCombine(1, cA, 1, this.m_rA); this.m_linearError.sub(Rot.mulVec2(qA, this.m_linearOffset)); this.m_angularError = aB - aA - this.m_angularOffset; if (step.warmStarting) { this.m_linearImpulse.mul(step.dtRatio); this.m_angularImpulse *= step.dtRatio; var P = Vec2.neo(this.m_linearImpulse.x, this.m_linearImpulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_angularImpulse); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_angularImpulse); } else { this.m_linearImpulse.setZero(); this.m_angularImpulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; MotorJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var h = step.dt; var inv_h = step.inv_dt; { var Cdot = wB - wA + inv_h * this.m_correctionFactor * this.m_angularError; var impulse = -this.m_angularMass * Cdot; var oldImpulse = this.m_angularImpulse; var maxImpulse = h * this.m_maxTorque; this.m_angularImpulse = Math.clamp(this.m_angularImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_angularImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } { var Cdot = Vec2.zero(); Cdot.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA)); Cdot.addMul(inv_h * this.m_correctionFactor, this.m_linearError); var impulse = Vec2.neg(Mat22.mulVec2(this.m_linearMass, Cdot)); var oldImpulse = Vec2.clone(this.m_linearImpulse); this.m_linearImpulse.add(impulse); var maxImpulse = h * this.m_maxForce; this.m_linearImpulse.clamp(maxImpulse); impulse = Vec2.sub(this.m_linearImpulse, oldImpulse); vA.subMul(mA, impulse); wA -= iA * Vec2.cross(this.m_rA, impulse); vB.addMul(mB, impulse); wB += iB * Vec2.cross(this.m_rB, impulse); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; MotorJoint.prototype.solvePositionConstraints = function(step) { return true; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],32:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = MouseJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); MouseJoint.TYPE = "mouse-joint"; MouseJoint._super = Joint; MouseJoint.prototype = create(MouseJoint._super.prototype); var DEFAULTS = { maxForce: 0, frequencyHz: 5, dampingRatio: .7 }; function MouseJoint(def, bodyA, bodyB, target) { if (!(this instanceof MouseJoint)) { return new MouseJoint(def, bodyA, bodyB, target); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = MouseJoint.TYPE; _ASSERT && common.assert(Math.isFinite(def.maxForce) && def.maxForce >= 0); _ASSERT && common.assert(Math.isFinite(def.frequencyHz) && def.frequencyHz >= 0); _ASSERT && common.assert(Math.isFinite(def.dampingRatio) && def.dampingRatio >= 0); this.m_targetA = target ? Vec2.clone(target) : def.target || Vec2.zero(); this.m_localAnchorB = Transform.mulTVec2(bodyB.getTransform(), this.m_targetA); this.m_maxForce = def.maxForce; this.m_impulse = Vec2.zero(); this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_beta = 0; this.m_gamma = 0; this.m_rB = Vec2.zero(); this.m_localCenterB = Vec2.zero(); this.m_invMassB = 0; this.m_invIB = 0; this.mass = new Mat22(); this.m_C = Vec2.zero(); } MouseJoint.prototype.setTarget = function(target) { if (this.m_bodyB.isAwake() == false) { this.m_bodyB.setAwake(true); } this.m_targetA = Vec2.clone(target); }; MouseJoint.prototype.getTarget = function() { return this.m_targetA; }; MouseJoint.prototype.setMaxForce = function(force) { this.m_maxForce = force; }; MouseJoint.getMaxForce = function() { return this.m_maxForce; }; MouseJoint.prototype.setFrequency = function(hz) { this.m_frequencyHz = hz; }; MouseJoint.prototype.getFrequency = function() { return this.m_frequencyHz; }; MouseJoint.prototype.setDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; MouseJoint.prototype.getDampingRatio = function() { return this.m_dampingRatio; }; MouseJoint.prototype.getAnchorA = function() { return Vec2.clone(this.m_targetA); }; MouseJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; MouseJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(inv_dt, this.m_impulse); }; MouseJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * 0; }; MouseJoint.prototype.shiftOrigin = function(newOrigin) { this.m_targetA.sub(newOrigin); }; MouseJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIB = this.m_bodyB.m_invI; var position = this.m_bodyB.c_position; var velocity = this.m_bodyB.c_velocity; var cB = position.c; var aB = position.a; var vB = velocity.v; var wB = velocity.w; var qB = Rot.neo(aB); var mass = this.m_bodyB.getMass(); var omega = 2 * Math.PI * this.m_frequencyHz; var d = 2 * mass * this.m_dampingRatio * omega; var k = mass * (omega * omega); var h = step.dt; _ASSERT && common.assert(d + h * k > Math.EPSILON); this.m_gamma = h * (d + h * k); if (this.m_gamma != 0) { this.m_gamma = 1 / this.m_gamma; } this.m_beta = h * k * this.m_gamma; this.m_rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var K = new Mat22(); K.ex.x = this.m_invMassB + this.m_invIB * this.m_rB.y * this.m_rB.y + this.m_gamma; K.ex.y = -this.m_invIB * this.m_rB.x * this.m_rB.y; K.ey.x = K.ex.y; K.ey.y = this.m_invMassB + this.m_invIB * this.m_rB.x * this.m_rB.x + this.m_gamma; this.m_mass = K.getInverse(); this.m_C.set(cB); this.m_C.addCombine(1, this.m_rB, -1, this.m_targetA); this.m_C.mul(this.m_beta); wB *= .98; if (step.warmStarting) { this.m_impulse.mul(step.dtRatio); vB.addMul(this.m_invMassB, this.m_impulse); wB += this.m_invIB * Vec2.cross(this.m_rB, this.m_impulse); } else { this.m_impulse.setZero(); } velocity.v.set(vB); velocity.w = wB; }; MouseJoint.prototype.solveVelocityConstraints = function(step) { var velocity = this.m_bodyB.c_velocity; var vB = Vec2.clone(velocity.v); var wB = velocity.w; var Cdot = Vec2.cross(wB, this.m_rB); Cdot.add(vB); Cdot.addCombine(1, this.m_C, this.m_gamma, this.m_impulse); Cdot.neg(); var impulse = Mat22.mulVec2(this.m_mass, Cdot); var oldImpulse = Vec2.clone(this.m_impulse); this.m_impulse.add(impulse); var maxImpulse = step.dt * this.m_maxForce; this.m_impulse.clamp(maxImpulse); impulse = Vec2.sub(this.m_impulse, oldImpulse); vB.addMul(this.m_invMassB, impulse); wB += this.m_invIB * Vec2.cross(this.m_rB, impulse); velocity.v.set(vB); velocity.w = wB; }; MouseJoint.prototype.solvePositionConstraints = function(step) { return true; }; },{"../Joint":5,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],33:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = PrismaticJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var inactiveLimit = 0; var atLowerLimit = 1; var atUpperLimit = 2; var equalLimits = 3; PrismaticJoint.TYPE = "prismatic-joint"; PrismaticJoint._super = Joint; PrismaticJoint.prototype = create(PrismaticJoint._super.prototype); var DEFAULTS = { enableLimit: false, lowerTranslation: 0, upperTranslation: 0, enableMotor: false, maxMotorForce: 0, motorSpeed: 0 }; function PrismaticJoint(def, bodyA, bodyB, anchor, axis) { if (!(this instanceof PrismaticJoint)) { return new PrismaticJoint(def, bodyA, bodyB, anchor, axis); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = PrismaticJoint.TYPE; this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero(); this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero(); this.m_localXAxisA = axis ? bodyA.getLocalVector(axis) : def.localAxisA || Vec2.neo(1, 0); this.m_localXAxisA.normalize(); this.m_localYAxisA = Vec2.cross(1, this.m_localXAxisA); this.m_referenceAngle = Math.isFinite(def.referenceAngle) ? def.referenceAngle : bodyB.getAngle() - bodyA.getAngle(); this.m_impulse = Vec3(); this.m_motorMass = 0; this.m_motorImpulse = 0; this.m_lowerTranslation = def.lowerTranslation; this.m_upperTranslation = def.upperTranslation; this.m_maxMotorForce = def.maxMotorForce; this.m_motorSpeed = def.motorSpeed; this.m_enableLimit = def.enableLimit; this.m_enableMotor = def.enableMotor; this.m_limitState = inactiveLimit; this.m_axis = Vec2.zero(); this.m_perp = Vec2.zero(); this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_axis, this.m_perp; this.m_s1, this.m_s2; this.m_a1, this.m_a2; this.m_K = new Mat33(); this.m_motorMass; } PrismaticJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; PrismaticJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; PrismaticJoint.prototype.getLocalAxisA = function() { return this.m_localXAxisA; }; PrismaticJoint.prototype.getReferenceAngle = function() { return this.m_referenceAngle; }; PrismaticJoint.prototype.getJointTranslation = function() { var pA = this.m_bodyA.getWorldPoint(this.m_localAnchorA); var pB = this.m_bodyB.getWorldPoint(this.m_localAnchorB); var d = Vec2.sub(pB, pA); var axis = this.m_bodyA.getWorldVector(this.m_localXAxisA); var translation = Vec2.dot(d, axis); return translation; }; PrismaticJoint.prototype.getJointSpeed = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; var rA = Rot.mulVec2(bA.m_xf.q, Vec2.sub(this.m_localAnchorA, bA.m_sweep.localCenter)); var rB = Rot.mulVec2(bB.m_xf.q, Vec2.sub(this.m_localAnchorB, bB.m_sweep.localCenter)); var p1 = Vec2.add(bA.m_sweep.c, rA); var p2 = Vec2.add(bB.m_sweep.c, rB); var d = Vec2.sub(p2, p1); var axis = Rot.mulVec2(bA.m_xf.q, this.m_localXAxisA); var vA = bA.m_linearVelocity; var vB = bB.m_linearVelocity; var wA = bA.m_angularVelocity; var wB = bB.m_angularVelocity; var speed = Vec2.dot(d, Vec2.cross(wA, axis)) + Vec2.dot(axis, Vec2.sub(Vec2.addCross(vB, wB, rB), Vec2.addCross(vA, wA, rA))); return speed; }; PrismaticJoint.prototype.isLimitEnabled = function() { return this.m_enableLimit; }; PrismaticJoint.prototype.enableLimit = function(flag) { if (flag != this.m_enableLimit) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableLimit = flag; this.m_impulse.z = 0; } }; PrismaticJoint.prototype.getLowerLimit = function() { return this.m_lowerTranslation; }; PrismaticJoint.prototype.getUpperLimit = function() { return this.m_upperTranslation; }; PrismaticJoint.prototype.setLimits = function(lower, upper) { _ASSERT && common.assert(lower <= upper); if (lower != this.m_lowerTranslation || upper != this.m_upperTranslation) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_lowerTranslation = lower; this.m_upperTranslation = upper; this.m_impulse.z = 0; } }; PrismaticJoint.prototype.isMotorEnabled = function() { return this.m_enableMotor; }; PrismaticJoint.prototype.enableMotor = function(flag) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableMotor = flag; }; PrismaticJoint.prototype.setMotorSpeed = function(speed) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_motorSpeed = speed; }; PrismaticJoint.prototype.setMaxMotorForce = function(force) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_maxMotorForce = force; }; PrismaticJoint.prototype.getMotorSpeed = function() { return this.m_motorSpeed; }; PrismaticJoint.prototype.getMotorForce = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; PrismaticJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; PrismaticJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; PrismaticJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.combine(this.m_impulse.x, this.m_perp, this.m_motorImpulse + this.m_impulse.z, this.m_axis).mul(inv_dt); }; PrismaticJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_impulse.y; }; PrismaticJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.zero(); d.addCombine(1, cB, 1, rB); d.subCombine(1, cA, 1, rA); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; { this.m_axis = Rot.mulVec2(qA, this.m_localXAxisA); this.m_a1 = Vec2.cross(Vec2.add(d, rA), this.m_axis); this.m_a2 = Vec2.cross(rB, this.m_axis); this.m_motorMass = mA + mB + iA * this.m_a1 * this.m_a1 + iB * this.m_a2 * this.m_a2; if (this.m_motorMass > 0) { this.m_motorMass = 1 / this.m_motorMass; } } { this.m_perp = Rot.mulVec2(qA, this.m_localYAxisA); this.m_s1 = Vec2.cross(Vec2.add(d, rA), this.m_perp); this.m_s2 = Vec2.cross(rB, this.m_perp); var s1test = Vec2.cross(rA, this.m_perp); var k11 = mA + mB + iA * this.m_s1 * this.m_s1 + iB * this.m_s2 * this.m_s2; var k12 = iA * this.m_s1 + iB * this.m_s2; var k13 = iA * this.m_s1 * this.m_a1 + iB * this.m_s2 * this.m_a2; var k22 = iA + iB; if (k22 == 0) { k22 = 1; } var k23 = iA * this.m_a1 + iB * this.m_a2; var k33 = mA + mB + iA * this.m_a1 * this.m_a1 + iB * this.m_a2 * this.m_a2; this.m_K.ex.set(k11, k12, k13); this.m_K.ey.set(k12, k22, k23); this.m_K.ez.set(k13, k23, k33); } if (this.m_enableLimit) { var jointTranslation = Vec2.dot(this.m_axis, d); if (Math.abs(this.m_upperTranslation - this.m_lowerTranslation) < 2 * Settings.linearSlop) { this.m_limitState = equalLimits; } else if (jointTranslation <= this.m_lowerTranslation) { if (this.m_limitState != atLowerLimit) { this.m_limitState = atLowerLimit; this.m_impulse.z = 0; } } else if (jointTranslation >= this.m_upperTranslation) { if (this.m_limitState != atUpperLimit) { this.m_limitState = atUpperLimit; this.m_impulse.z = 0; } } else { this.m_limitState = inactiveLimit; this.m_impulse.z = 0; } } else { this.m_limitState = inactiveLimit; this.m_impulse.z = 0; } if (this.m_enableMotor == false) { this.m_motorImpulse = 0; } if (step.warmStarting) { this.m_impulse.mul(step.dtRatio); this.m_motorImpulse *= step.dtRatio; var P = Vec2.combine(this.m_impulse.x, this.m_perp, this.m_motorImpulse + this.m_impulse.z, this.m_axis); var LA = this.m_impulse.x * this.m_s1 + this.m_impulse.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_a1; var LB = this.m_impulse.x * this.m_s2 + this.m_impulse.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_a2; vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } else { this.m_impulse.setZero(); this.m_motorImpulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; PrismaticJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; if (this.m_enableMotor && this.m_limitState != equalLimits) { var Cdot = Vec2.dot(this.m_axis, Vec2.sub(vB, vA)) + this.m_a2 * wB - this.m_a1 * wA; var impulse = this.m_motorMass * (this.m_motorSpeed - Cdot); var oldImpulse = this.m_motorImpulse; var maxImpulse = step.dt * this.m_maxMotorForce; this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; var P = Vec2.mul(impulse, this.m_axis); var LA = impulse * this.m_a1; var LB = impulse * this.m_a2; vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } var Cdot1 = Vec2.zero(); Cdot1.x += Vec2.dot(this.m_perp, vB) + this.m_s2 * wB; Cdot1.x -= Vec2.dot(this.m_perp, vA) + this.m_s1 * wA; Cdot1.y = wB - wA; if (this.m_enableLimit && this.m_limitState != inactiveLimit) { var Cdot2 = 0; Cdot2 += Vec2.dot(this.m_axis, vB) + this.m_a2 * wB; Cdot2 -= Vec2.dot(this.m_axis, vA) + this.m_a1 * wA; var Cdot = Vec3(Cdot1.x, Cdot1.y, Cdot2); var f1 = Vec3(this.m_impulse); var df = this.m_K.solve33(Vec3.neg(Cdot)); this.m_impulse.add(df); if (this.m_limitState == atLowerLimit) { this.m_impulse.z = Math.max(this.m_impulse.z, 0); } else if (this.m_limitState == atUpperLimit) { this.m_impulse.z = Math.min(this.m_impulse.z, 0); } var b = Vec2.combine(-1, Cdot1, -(this.m_impulse.z - f1.z), Vec2.neo(this.m_K.ez.x, this.m_K.ez.y)); var f2r = Vec2.add(this.m_K.solve22(b), Vec2.neo(f1.x, f1.y)); this.m_impulse.x = f2r.x; this.m_impulse.y = f2r.y; df = Vec3.sub(this.m_impulse, f1); var P = Vec2.combine(df.x, this.m_perp, df.z, this.m_axis); var LA = df.x * this.m_s1 + df.y + df.z * this.m_a1; var LB = df.x * this.m_s2 + df.y + df.z * this.m_a2; vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } else { var df = this.m_K.solve22(Vec2.neg(Cdot1)); this.m_impulse.x += df.x; this.m_impulse.y += df.y; var P = Vec2.mul(df.x, this.m_perp); var LA = df.x * this.m_s1 + df.y; var LB = df.x * this.m_s2 + df.y; vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; PrismaticJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.sub(Vec2.add(cB, rB), Vec2.add(cA, rA)); var axis = Rot.mulVec2(qA, this.m_localXAxisA); var a1 = Vec2.cross(Vec2.add(d, rA), axis); var a2 = Vec2.cross(rB, axis); var perp = Rot.mulVec2(qA, this.m_localYAxisA); var s1 = Vec2.cross(Vec2.add(d, rA), perp); var s2 = Vec2.cross(rB, perp); var impulse = Vec3(); var C1 = Vec2.zero(); C1.x = Vec2.dot(perp, d); C1.y = aB - aA - this.m_referenceAngle; var linearError = Math.abs(C1.x); var angularError = Math.abs(C1.y); var linearSlop = Settings.linearSlop; var maxLinearCorrection = Settings.maxLinearCorrection; var active = false; var C2 = 0; if (this.m_enableLimit) { var translation = Vec2.dot(axis, d); if (Math.abs(this.m_upperTranslation - this.m_lowerTranslation) < 2 * linearSlop) { C2 = Math.clamp(translation, -maxLinearCorrection, maxLinearCorrection); linearError = Math.max(linearError, Math.abs(translation)); active = true; } else if (translation <= this.m_lowerTranslation) { C2 = Math.clamp(translation - this.m_lowerTranslation + linearSlop, -maxLinearCorrection, 0); linearError = Math.max(linearError, this.m_lowerTranslation - translation); active = true; } else if (translation >= this.m_upperTranslation) { C2 = Math.clamp(translation - this.m_upperTranslation - linearSlop, 0, maxLinearCorrection); linearError = Math.max(linearError, translation - this.m_upperTranslation); active = true; } } if (active) { var k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; var k12 = iA * s1 + iB * s2; var k13 = iA * s1 * a1 + iB * s2 * a2; var k22 = iA + iB; if (k22 == 0) { k22 = 1; } var k23 = iA * a1 + iB * a2; var k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2; var K = new Mat33(); K.ex.set(k11, k12, k13); K.ey.set(k12, k22, k23); K.ez.set(k13, k23, k33); var C = Vec3(); C.x = C1.x; C.y = C1.y; C.z = C2; impulse = K.solve33(Vec3.neg(C)); } else { var k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; var k12 = iA * s1 + iB * s2; var k22 = iA + iB; if (k22 == 0) { k22 = 1; } var K = new Mat22(); K.ex.set(k11, k12); K.ey.set(k12, k22); var impulse1 = K.solve(Vec2.neg(C1)); impulse.x = impulse1.x; impulse.y = impulse1.y; impulse.z = 0; } var P = Vec2.combine(impulse.x, perp, impulse.z, axis); var LA = impulse.x * s1 + impulse.y + impulse.z * a1; var LB = impulse.x * s2 + impulse.y + impulse.z * a2; cA.subMul(mA, P); aA -= iA * LA; cB.addMul(mB, P); aB += iB * LB; this.m_bodyA.c_position.c = cA; this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c = cB; this.m_bodyB.c_position.a = aB; return linearError <= Settings.linearSlop && angularError <= Settings.angularSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],34:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = PulleyJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); PulleyJoint.TYPE = "pulley-joint"; PulleyJoint.MIN_PULLEY_LENGTH = 2; PulleyJoint._super = Joint; PulleyJoint.prototype = create(PulleyJoint._super.prototype); var PulleyJointDef = { collideConnected: true }; function PulleyJoint(def, bodyA, bodyB, groundA, groundB, anchorA, anchorB, ratio) { if (!(this instanceof PulleyJoint)) { return new PulleyJoint(def, bodyA, bodyB, groundA, groundB, anchorA, anchorB, ratio); } def = options(def, PulleyJointDef); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = PulleyJoint.TYPE; this.m_groundAnchorA = groundA ? groundA : def.groundAnchorA || Vec2.neo(-1, 1); this.m_groundAnchorB = groundB ? groundB : def.groundAnchorB || Vec2.neo(1, 1); this.m_localAnchorA = anchorA ? bodyA.getLocalPoint(anchorA) : def.localAnchorA || Vec2.neo(-1, 0); this.m_localAnchorB = anchorB ? bodyB.getLocalPoint(anchorB) : def.localAnchorB || Vec2.neo(1, 0); this.m_lengthA = Math.isFinite(def.lengthA) ? def.lengthA : Vec2.distance(anchorA, groundA); this.m_lengthB = Math.isFinite(def.lengthB) ? def.lengthB : Vec2.distance(anchorB, groundB); this.m_ratio = Math.isFinite(ratio) ? ratio : def.ratio; _ASSERT && common.assert(ratio > Math.EPSILON); this.m_constant = this.m_lengthA + this.m_ratio * this.m_lengthB; this.m_impulse = 0; this.m_uA; this.m_uB; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass; } PulleyJoint.prototype.getGroundAnchorA = function() { return this.m_groundAnchorA; }; PulleyJoint.prototype.getGroundAnchorB = function() { return this.m_groundAnchorB; }; PulleyJoint.prototype.getLengthA = function() { return this.m_lengthA; }; PulleyJoint.prototype.getLengthB = function() { return this.m_lengthB; }; PulleyJoint.prototype.getRatio = function() { return this.m_ratio; }; PulleyJoint.prototype.getCurrentLengthA = function() { var p = this.m_bodyA.getWorldPoint(this.m_localAnchorA); var s = this.m_groundAnchorA; return Vec2.distance(p, s); }; PulleyJoint.prototype.getCurrentLengthB = function() { var p = this.m_bodyB.getWorldPoint(this.m_localAnchorB); var s = this.m_groundAnchorB; return Vec2.distance(p, s); }; PulleyJoint.prototype.shiftOrigin = function(newOrigin) { this.m_groundAnchorA.sub(newOrigin); this.m_groundAnchorB.sub(newOrigin); }; PulleyJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; PulleyJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; PulleyJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(this.m_impulse, this.m_uB).mul(inv_dt); }; PulleyJoint.prototype.getReactionTorque = function(inv_dt) { return 0; }; PulleyJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); this.m_uA = Vec2.sub(Vec2.add(cA, this.m_rA), this.m_groundAnchorA); this.m_uB = Vec2.sub(Vec2.add(cB, this.m_rB), this.m_groundAnchorB); var lengthA = this.m_uA.length(); var lengthB = this.m_uB.length(); if (lengthA > 10 * Settings.linearSlop) { this.m_uA.mul(1 / lengthA); } else { this.m_uA.setZero(); } if (lengthB > 10 * Settings.linearSlop) { this.m_uB.mul(1 / lengthB); } else { this.m_uB.setZero(); } var ruA = Vec2.cross(this.m_rA, this.m_uA); var ruB = Vec2.cross(this.m_rB, this.m_uB); var mA = this.m_invMassA + this.m_invIA * ruA * ruA; var mB = this.m_invMassB + this.m_invIB * ruB * ruB; this.m_mass = mA + this.m_ratio * this.m_ratio * mB; if (this.m_mass > 0) { this.m_mass = 1 / this.m_mass; } if (step.warmStarting) { this.m_impulse *= step.dtRatio; var PA = Vec2.mul(-this.m_impulse, this.m_uA); var PB = Vec2.mul(-this.m_ratio * this.m_impulse, this.m_uB); vA.addMul(this.m_invMassA, PA); wA += this.m_invIA * Vec2.cross(this.m_rA, PA); vB.addMul(this.m_invMassB, PB); wB += this.m_invIB * Vec2.cross(this.m_rB, PB); } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; PulleyJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var vpA = Vec2.add(vA, Vec2.cross(wA, this.m_rA)); var vpB = Vec2.add(vB, Vec2.cross(wB, this.m_rB)); var Cdot = -Vec2.dot(this.m_uA, vpA) - this.m_ratio * Vec2.dot(this.m_uB, vpB); var impulse = -this.m_mass * Cdot; this.m_impulse += impulse; var PA = Vec2.mul(-impulse, this.m_uA); var PB = Vec2.mul(-this.m_ratio * impulse, this.m_uB); vA.addMul(this.m_invMassA, PA); wA += this.m_invIA * Vec2.cross(this.m_rA, PA); vB.addMul(this.m_invMassB, PB); wB += this.m_invIB * Vec2.cross(this.m_rB, PB); this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; PulleyJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA), qB = Rot.neo(aB); var rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var uA = Vec2.sub(Vec2.add(cA, this.m_rA), this.m_groundAnchorA); var uB = Vec2.sub(Vec2.add(cB, this.m_rB), this.m_groundAnchorB); var lengthA = uA.length(); var lengthB = uB.length(); if (lengthA > 10 * Settings.linearSlop) { uA.mul(1 / lengthA); } else { uA.setZero(); } if (lengthB > 10 * Settings.linearSlop) { uB.mul(1 / lengthB); } else { uB.setZero(); } var ruA = Vec2.cross(rA, uA); var ruB = Vec2.cross(rB, uB); var mA = this.m_invMassA + this.m_invIA * ruA * ruA; var mB = this.m_invMassB + this.m_invIB * ruB * ruB; var mass = mA + this.m_ratio * this.m_ratio * mB; if (mass > 0) { mass = 1 / mass; } var C = this.m_constant - lengthA - this.m_ratio * lengthB; var linearError = Math.abs(C); var impulse = -mass * C; var PA = Vec2.mul(-impulse, uA); var PB = Vec2.mul(-this.m_ratio * impulse, uB); cA.addMul(this.m_invMassA, PA); aA += this.m_invIA * Vec2.cross(rA, PA); cB.addMul(this.m_invMassB, PB); aB += this.m_invIB * Vec2.cross(rB, PB); this.m_bodyA.c_position.c = cA; this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c = cB; this.m_bodyB.c_position.a = aB; return linearError < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],35:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = RevoluteJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var inactiveLimit = 0; var atLowerLimit = 1; var atUpperLimit = 2; var equalLimits = 3; RevoluteJoint.TYPE = "revolute-joint"; RevoluteJoint._super = Joint; RevoluteJoint.prototype = create(RevoluteJoint._super.prototype); var DEFAULTS = { lowerAngle: 0, upperAngle: 0, maxMotorTorque: 0, motorSpeed: 0, enableLimit: false, enableMotor: false }; function RevoluteJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof RevoluteJoint)) { return new RevoluteJoint(def, bodyA, bodyB, anchor); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = RevoluteJoint.TYPE; this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero(); this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero(); this.m_referenceAngle = Math.isFinite(def.referenceAngle) ? def.referenceAngle : bodyB.getAngle() - bodyA.getAngle(); this.m_impulse = Vec3(); this.m_motorImpulse = 0; this.m_lowerAngle = def.lowerAngle; this.m_upperAngle = def.upperAngle; this.m_maxMotorTorque = def.maxMotorTorque; this.m_motorSpeed = def.motorSpeed; this.m_enableLimit = def.enableLimit; this.m_enableMotor = def.enableMotor; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass = new Mat33(); this.m_motorMass; this.m_limitState = inactiveLimit; } RevoluteJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; RevoluteJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; RevoluteJoint.prototype.getReferenceAngle = function() { return this.m_referenceAngle; }; RevoluteJoint.prototype.getJointAngle = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; return bB.m_sweep.a - bA.m_sweep.a - this.m_referenceAngle; }; RevoluteJoint.prototype.getJointSpeed = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; return bB.m_angularVelocity - bA.m_angularVelocity; }; RevoluteJoint.prototype.isMotorEnabled = function() { return this.m_enableMotor; }; RevoluteJoint.prototype.enableMotor = function(flag) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableMotor = flag; }; RevoluteJoint.prototype.getMotorTorque = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; RevoluteJoint.prototype.setMotorSpeed = function(speed) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_motorSpeed = speed; }; RevoluteJoint.prototype.getMotorSpeed = function() { return this.m_motorSpeed; }; RevoluteJoint.prototype.setMaxMotorTorque = function(torque) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_maxMotorTorque = torque; }; RevoluteJoint.prototype.isLimitEnabled = function() { return this.m_enableLimit; }; RevoluteJoint.prototype.enableLimit = function(flag) { if (flag != this.m_enableLimit) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableLimit = flag; this.m_impulse.z = 0; } }; RevoluteJoint.prototype.getLowerLimit = function() { return this.m_lowerAngle; }; RevoluteJoint.prototype.getUpperLimit = function() { return this.m_upperAngle; }; RevoluteJoint.prototype.setLimits = function(lower, upper) { _ASSERT && common.assert(lower <= upper); if (lower != this.m_lowerAngle || upper != this.m_upperAngle) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_impulse.z = 0; this.m_lowerAngle = lower; this.m_upperAngle = upper; } }; RevoluteJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; RevoluteJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; RevoluteJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.neo(this.m_impulse.x, this.m_impulse.y).mul(inv_dt); }; RevoluteJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_impulse.z; }; RevoluteJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var fixedRotation = iA + iB === 0; this.m_mass.ex.x = mA + mB + this.m_rA.y * this.m_rA.y * iA + this.m_rB.y * this.m_rB.y * iB; this.m_mass.ey.x = -this.m_rA.y * this.m_rA.x * iA - this.m_rB.y * this.m_rB.x * iB; this.m_mass.ez.x = -this.m_rA.y * iA - this.m_rB.y * iB; this.m_mass.ex.y = this.m_mass.ey.x; this.m_mass.ey.y = mA + mB + this.m_rA.x * this.m_rA.x * iA + this.m_rB.x * this.m_rB.x * iB; this.m_mass.ez.y = this.m_rA.x * iA + this.m_rB.x * iB; this.m_mass.ex.z = this.m_mass.ez.x; this.m_mass.ey.z = this.m_mass.ez.y; this.m_mass.ez.z = iA + iB; this.m_motorMass = iA + iB; if (this.m_motorMass > 0) { this.m_motorMass = 1 / this.m_motorMass; } if (this.m_enableMotor == false || fixedRotation) { this.m_motorImpulse = 0; } if (this.m_enableLimit && fixedRotation == false) { var jointAngle = aB - aA - this.m_referenceAngle; if (Math.abs(this.m_upperAngle - this.m_lowerAngle) < 2 * Settings.angularSlop) { this.m_limitState = equalLimits; } else if (jointAngle <= this.m_lowerAngle) { if (this.m_limitState != atLowerLimit) { this.m_impulse.z = 0; } this.m_limitState = atLowerLimit; } else if (jointAngle >= this.m_upperAngle) { if (this.m_limitState != atUpperLimit) { this.m_impulse.z = 0; } this.m_limitState = atUpperLimit; } else { this.m_limitState = inactiveLimit; this.m_impulse.z = 0; } } else { this.m_limitState = inactiveLimit; } if (step.warmStarting) { this.m_impulse.mul(step.dtRatio); this.m_motorImpulse *= step.dtRatio; var P = Vec2.neo(this.m_impulse.x, this.m_impulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_motorImpulse + this.m_impulse.z); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_motorImpulse + this.m_impulse.z); } else { this.m_impulse.setZero(); this.m_motorImpulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; RevoluteJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var fixedRotation = iA + iB === 0; if (this.m_enableMotor && this.m_limitState != equalLimits && fixedRotation == false) { var Cdot = wB - wA - this.m_motorSpeed; var impulse = -this.m_motorMass * Cdot; var oldImpulse = this.m_motorImpulse; var maxImpulse = step.dt * this.m_maxMotorTorque; this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } if (this.m_enableLimit && this.m_limitState != inactiveLimit && fixedRotation == false) { var Cdot1 = Vec2.zero(); Cdot1.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA)); var Cdot2 = wB - wA; var Cdot = Vec3(Cdot1.x, Cdot1.y, Cdot2); var impulse = Vec3.neg(this.m_mass.solve33(Cdot)); if (this.m_limitState == equalLimits) { this.m_impulse.add(impulse); } else if (this.m_limitState == atLowerLimit) { var newImpulse = this.m_impulse.z + impulse.z; if (newImpulse < 0) { var rhs = Vec2.combine(-1, Cdot1, this.m_impulse.z, Vec2.neo(this.m_mass.ez.x, this.m_mass.ez.y)); var reduced = this.m_mass.solve22(rhs); impulse.x = reduced.x; impulse.y = reduced.y; impulse.z = -this.m_impulse.z; this.m_impulse.x += reduced.x; this.m_impulse.y += reduced.y; this.m_impulse.z = 0; } else { this.m_impulse.add(impulse); } } else if (this.m_limitState == atUpperLimit) { var newImpulse = this.m_impulse.z + impulse.z; if (newImpulse > 0) { var rhs = Vec2.combine(-1, Cdot1, this.m_impulse.z, Vec2.neo(this.m_mass.ez.x, this.m_mass.ez.y)); var reduced = this.m_mass.solve22(rhs); impulse.x = reduced.x; impulse.y = reduced.y; impulse.z = -this.m_impulse.z; this.m_impulse.x += reduced.x; this.m_impulse.y += reduced.y; this.m_impulse.z = 0; } else { this.m_impulse.add(impulse); } } var P = Vec2.neo(impulse.x, impulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + impulse.z); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + impulse.z); } else { var Cdot = Vec2.zero(); Cdot.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA)); var impulse = this.m_mass.solve22(Vec2.neg(Cdot)); this.m_impulse.x += impulse.x; this.m_impulse.y += impulse.y; vA.subMul(mA, impulse); wA -= iA * Vec2.cross(this.m_rA, impulse); vB.addMul(mB, impulse); wB += iB * Vec2.cross(this.m_rB, impulse); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; RevoluteJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var angularError = 0; var positionError = 0; var fixedRotation = this.m_invIA + this.m_invIB == 0; if (this.m_enableLimit && this.m_limitState != inactiveLimit && fixedRotation == false) { var angle = aB - aA - this.m_referenceAngle; var limitImpulse = 0; if (this.m_limitState == equalLimits) { var C = Math.clamp(angle - this.m_lowerAngle, -Settings.maxAngularCorrection, Settings.maxAngularCorrection); limitImpulse = -this.m_motorMass * C; angularError = Math.abs(C); } else if (this.m_limitState == atLowerLimit) { var C = angle - this.m_lowerAngle; angularError = -C; C = Math.clamp(C + Settings.angularSlop, -Settings.maxAngularCorrection, 0); limitImpulse = -this.m_motorMass * C; } else if (this.m_limitState == atUpperLimit) { var C = angle - this.m_upperAngle; angularError = C; C = Math.clamp(C - Settings.angularSlop, 0, Settings.maxAngularCorrection); limitImpulse = -this.m_motorMass * C; } aA -= this.m_invIA * limitImpulse; aB += this.m_invIB * limitImpulse; } { qA.set(aA); qB.set(aB); var rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var C = Vec2.zero(); C.addCombine(1, cB, 1, rB); C.subCombine(1, cA, 1, rA); positionError = C.length(); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var K = new Mat22(); K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; var impulse = Vec2.neg(K.solve(C)); cA.subMul(mA, impulse); aA -= iA * Vec2.cross(rA, impulse); cB.addMul(mB, impulse); aB += iB * Vec2.cross(rB, impulse); } this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return positionError <= Settings.linearSlop && angularError <= Settings.angularSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],36:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = RopeJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var inactiveLimit = 0; var atLowerLimit = 1; var atUpperLimit = 2; var equalLimits = 3; RopeJoint.TYPE = "rope-joint"; RopeJoint._super = Joint; RopeJoint.prototype = create(RopeJoint._super.prototype); var DEFAULTS = { maxLength: 0 }; function RopeJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof RopeJoint)) { return new RopeJoint(def, bodyA, bodyB, anchor); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = RopeJoint.TYPE; this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.neo(-1, 0); this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.neo(1, 0); this.m_maxLength = def.maxLength; this.m_mass = 0; this.m_impulse = 0; this.m_length = 0; this.m_state = inactiveLimit; this.m_u; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass; } RopeJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; RopeJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; RopeJoint.prototype.setMaxLength = function(length) { this.m_maxLength = length; }; RopeJoint.prototype.getMaxLength = function() { return this.m_maxLength; }; RopeJoint.prototype.getLimitState = function() { return this.m_state; }; RopeJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; RopeJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; RopeJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(this.m_impulse, this.m_u).mul(inv_dt); }; RopeJoint.prototype.getReactionTorque = function(inv_dt) { return 0; }; RopeJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA); this.m_rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB); this.m_u = Vec2.zero(); this.m_u.addCombine(1, cB, 1, this.m_rB); this.m_u.subCombine(1, cA, 1, this.m_rA); this.m_length = this.m_u.length(); var C = this.m_length - this.m_maxLength; if (C > 0) { this.m_state = atUpperLimit; } else { this.m_state = inactiveLimit; } if (this.m_length > Settings.linearSlop) { this.m_u.mul(1 / this.m_length); } else { this.m_u.setZero(); this.m_mass = 0; this.m_impulse = 0; return; } var crA = Vec2.cross(this.m_rA, this.m_u); var crB = Vec2.cross(this.m_rB, this.m_u); var invMass = this.m_invMassA + this.m_invIA * crA * crA + this.m_invMassB + this.m_invIB * crB * crB; this.m_mass = invMass != 0 ? 1 / invMass : 0; if (step.warmStarting) { this.m_impulse *= step.dtRatio; var P = Vec2.mul(this.m_impulse, this.m_u); vA.subMul(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.addMul(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; RopeJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var vpA = Vec2.addCross(vA, wA, this.m_rA); var vpB = Vec2.addCross(vB, wB, this.m_rB); var C = this.m_length - this.m_maxLength; var Cdot = Vec2.dot(this.m_u, Vec2.sub(vpB, vpA)); if (C < 0) { Cdot += step.inv_dt * C; } var impulse = -this.m_mass * Cdot; var oldImpulse = this.m_impulse; this.m_impulse = Math.min(0, this.m_impulse + impulse); impulse = this.m_impulse - oldImpulse; var P = Vec2.mul(impulse, this.m_u); vA.subMul(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.addMul(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; RopeJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB); var u = Vec2.zero(); u.addCombine(1, cB, 1, rB); u.subCombine(1, cA, 1, rA); var length = u.normalize(); var C = length - this.m_maxLength; C = Math.clamp(C, 0, Settings.maxLinearCorrection); var impulse = -this.m_mass * C; var P = Vec2.mul(impulse, u); cA.subMul(this.m_invMassA, P); aA -= this.m_invIA * Vec2.cross(rA, P); cB.addMul(this.m_invMassB, P); aB += this.m_invIB * Vec2.cross(rB, P); this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return length - this.m_maxLength < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],37:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = WeldJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); WeldJoint.TYPE = "weld-joint"; WeldJoint._super = Joint; WeldJoint.prototype = create(WeldJoint._super.prototype); var DEFAULTS = { frequencyHz: 0, dampingRatio: 0 }; function WeldJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof WeldJoint)) { return new WeldJoint(def, bodyA, bodyB, anchor); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = WeldJoint.TYPE; this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero(); this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero(); this.m_referenceAngle = Math.isFinite(def.referenceAngle) ? def.referenceAngle : bodyB.getAngle() - bodyA.getAngle(); this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_impulse = Vec3(); this.m_bias = 0; this.m_gamma = 0; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass = new Mat33(); } WeldJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; WeldJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; WeldJoint.prototype.getReferenceAngle = function() { return this.m_referenceAngle; }; WeldJoint.prototype.setFrequency = function(hz) { this.m_frequencyHz = hz; }; WeldJoint.prototype.getFrequency = function() { return this.m_frequencyHz; }; WeldJoint.prototype.setDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; WeldJoint.prototype.getDampingRatio = function() { return this.m_dampingRatio; }; WeldJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; WeldJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; WeldJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.neo(this.m_impulse.x, this.m_impulse.y).mul(inv_dt); }; WeldJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_impulse.z; }; WeldJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA), qB = Rot.neo(aB); this.m_rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var K = new Mat33(); K.ex.x = mA + mB + this.m_rA.y * this.m_rA.y * iA + this.m_rB.y * this.m_rB.y * iB; K.ey.x = -this.m_rA.y * this.m_rA.x * iA - this.m_rB.y * this.m_rB.x * iB; K.ez.x = -this.m_rA.y * iA - this.m_rB.y * iB; K.ex.y = K.ey.x; K.ey.y = mA + mB + this.m_rA.x * this.m_rA.x * iA + this.m_rB.x * this.m_rB.x * iB; K.ez.y = this.m_rA.x * iA + this.m_rB.x * iB; K.ex.z = K.ez.x; K.ey.z = K.ez.y; K.ez.z = iA + iB; if (this.m_frequencyHz > 0) { K.getInverse22(this.m_mass); var invM = iA + iB; var m = invM > 0 ? 1 / invM : 0; var C = aB - aA - this.m_referenceAngle; var omega = 2 * Math.PI * this.m_frequencyHz; var d = 2 * m * this.m_dampingRatio * omega; var k = m * omega * omega; var h = step.dt; this.m_gamma = h * (d + h * k); this.m_gamma = this.m_gamma != 0 ? 1 / this.m_gamma : 0; this.m_bias = C * h * k * this.m_gamma; invM += this.m_gamma; this.m_mass.ez.z = invM != 0 ? 1 / invM : 0; } else if (K.ez.z == 0) { K.getInverse22(this.m_mass); this.m_gamma = 0; this.m_bias = 0; } else { K.getSymInverse33(this.m_mass); this.m_gamma = 0; this.m_bias = 0; } if (step.warmStarting) { this.m_impulse.mul(step.dtRatio); var P = Vec2.neo(this.m_impulse.x, this.m_impulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_impulse.z); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_impulse.z); } else { this.m_impulse.setZero(); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; WeldJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; if (this.m_frequencyHz > 0) { var Cdot2 = wB - wA; var impulse2 = -this.m_mass.ez.z * (Cdot2 + this.m_bias + this.m_gamma * this.m_impulse.z); this.m_impulse.z += impulse2; wA -= iA * impulse2; wB += iB * impulse2; var Cdot1 = Vec2.zero(); Cdot1.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA)); var impulse1 = Vec2.neg(Mat33.mulVec2(this.m_mass, Cdot1)); this.m_impulse.x += impulse1.x; this.m_impulse.y += impulse1.y; var P = Vec2.clone(impulse1); vA.subMul(mA, P); wA -= iA * Vec2.cross(this.m_rA, P); vB.addMul(mB, P); wB += iB * Vec2.cross(this.m_rB, P); } else { var Cdot1 = Vec2.zero(); Cdot1.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA)); var Cdot2 = wB - wA; var Cdot = Vec3(Cdot1.x, Cdot1.y, Cdot2); var impulse = Vec3.neg(Mat33.mulVec3(this.m_mass, Cdot)); this.m_impulse.add(impulse); var P = Vec2.neo(impulse.x, impulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + impulse.z); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + impulse.z); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; WeldJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA), qB = Rot.neo(aB); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var positionError, angularError; var K = new Mat33(); K.ex.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; K.ey.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; K.ez.x = -rA.y * iA - rB.y * iB; K.ex.y = K.ey.x; K.ey.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; K.ez.y = rA.x * iA + rB.x * iB; K.ex.z = K.ez.x; K.ey.z = K.ez.y; K.ez.z = iA + iB; if (this.m_frequencyHz > 0) { var C1 = Vec2.zero(); C1.addCombine(1, cB, 1, rB); C1.subCombine(1, cA, 1, rA); positionError = C1.length(); angularError = 0; var P = Vec2.neg(K.solve22(C1)); cA.subMul(mA, P); aA -= iA * Vec2.cross(rA, P); cB.addMul(mB, P); aB += iB * Vec2.cross(rB, P); } else { var C1 = Vec2.zero(); C1.addCombine(1, cB, 1, rB); C1.subCombine(1, cA, 1, rA); var C2 = aB - aA - this.m_referenceAngle; positionError = C1.length(); angularError = Math.abs(C2); var C = Vec3(C1.x, C1.y, C2); var impulse = Vec3(); if (K.ez.z > 0) { impulse = Vec3.neg(K.solve33(C)); } else { var impulse2 = Vec2.neg(K.solve22(C1)); impulse.set(impulse2.x, impulse2.y, 0); } var P = Vec2.neo(impulse.x, impulse.y); cA.subMul(mA, P); aA -= iA * (Vec2.cross(rA, P) + impulse.z); cB.addMul(mB, P); aB += iB * (Vec2.cross(rB, P) + impulse.z); } this.m_bodyA.c_position.c = cA; this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c = cB; this.m_bodyB.c_position.a = aB; return positionError <= Settings.linearSlop && angularError <= Settings.angularSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],38:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = WheelJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); WheelJoint.TYPE = "wheel-joint"; WheelJoint._super = Joint; WheelJoint.prototype = create(WheelJoint._super.prototype); var DEFAULTS = { enableMotor: false, maxMotorTorque: 0, motorSpeed: 0, frequencyHz: 2, dampingRatio: .7 }; function WheelJoint(def, bodyA, bodyB, anchor, axis) { if (!(this instanceof WheelJoint)) { return new WheelJoint(def, bodyA, bodyB, anchor, axis); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = WheelJoint.TYPE; this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero(); this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero(); this.m_localAxis = axis ? bodyA.getLocalVector(axis) : def.localAxisA || Vec2.neo(1, 0); this.m_localXAxisA = this.m_localAxis; this.m_localYAxisA = Vec2.cross(1, this.m_localXAxisA); this.m_mass = 0; this.m_impulse = 0; this.m_motorMass = 0; this.m_motorImpulse = 0; this.m_springMass = 0; this.m_springImpulse = 0; this.m_maxMotorTorque = def.maxMotorTorque; this.m_motorSpeed = def.motorSpeed; this.m_enableMotor = def.enableMotor; this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_bias = 0; this.m_gamma = 0; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_ax = Vec2.zero(); this.m_ay = Vec2.zero(); this.m_sAx; this.m_sBx; this.m_sAy; this.m_sBy; } WheelJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; WheelJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; WheelJoint.prototype.getLocalAxisA = function() { return this.m_localXAxisA; }; WheelJoint.prototype.getJointTranslation = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; var pA = bA.getWorldPoint(this.m_localAnchorA); var pB = bB.getWorldPoint(this.m_localAnchorB); var d = Vec2.sub(pB, pA); var axis = bA.getWorldVector(this.m_localXAxisA); var translation = Vec2.dot(d, axis); return translation; }; WheelJoint.prototype.getJointSpeed = function() { var wA = this.m_bodyA.m_angularVelocity; var wB = this.m_bodyB.m_angularVelocity; return wB - wA; }; WheelJoint.prototype.isMotorEnabled = function() { return this.m_enableMotor; }; WheelJoint.prototype.enableMotor = function(flag) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableMotor = flag; }; WheelJoint.prototype.setMotorSpeed = function(speed) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_motorSpeed = speed; }; WheelJoint.prototype.getMotorSpeed = function() { return this.m_motorSpeed; }; WheelJoint.prototype.setMaxMotorTorque = function(torque) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_maxMotorTorque = torque; }; WheelJoint.prototype.getMaxMotorTorque = function() { return this.m_maxMotorTorque; }; WheelJoint.prototype.getMotorTorque = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; WheelJoint.prototype.setSpringFrequencyHz = function(hz) { this.m_frequencyHz = hz; }; WheelJoint.prototype.getSpringFrequencyHz = function() { return this.m_frequencyHz; }; WheelJoint.prototype.setSpringDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; WheelJoint.prototype.getSpringDampingRatio = function() { return this.m_dampingRatio; }; WheelJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; WheelJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; WheelJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.combine(this.m_impulse, this.m_ay, this.m_springImpulse, this.m_ax).mul(inv_dt); }; WheelJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; WheelJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.zero(); d.addCombine(1, cB, 1, rB); d.subCombine(1, cA, 1, rA); { this.m_ay = Rot.mulVec2(qA, this.m_localYAxisA); this.m_sAy = Vec2.cross(Vec2.add(d, rA), this.m_ay); this.m_sBy = Vec2.cross(rB, this.m_ay); this.m_mass = mA + mB + iA * this.m_sAy * this.m_sAy + iB * this.m_sBy * this.m_sBy; if (this.m_mass > 0) { this.m_mass = 1 / this.m_mass; } } this.m_springMass = 0; this.m_bias = 0; this.m_gamma = 0; if (this.m_frequencyHz > 0) { this.m_ax = Rot.mulVec2(qA, this.m_localXAxisA); this.m_sAx = Vec2.cross(Vec2.add(d, rA), this.m_ax); this.m_sBx = Vec2.cross(rB, this.m_ax); var invMass = mA + mB + iA * this.m_sAx * this.m_sAx + iB * this.m_sBx * this.m_sBx; if (invMass > 0) { this.m_springMass = 1 / invMass; var C = Vec2.dot(d, this.m_ax); var omega = 2 * Math.PI * this.m_frequencyHz; var d = 2 * this.m_springMass * this.m_dampingRatio * omega; var k = this.m_springMass * omega * omega; var h = step.dt; this.m_gamma = h * (d + h * k); if (this.m_gamma > 0) { this.m_gamma = 1 / this.m_gamma; } this.m_bias = C * h * k * this.m_gamma; this.m_springMass = invMass + this.m_gamma; if (this.m_springMass > 0) { this.m_springMass = 1 / this.m_springMass; } } } else { this.m_springImpulse = 0; } if (this.m_enableMotor) { this.m_motorMass = iA + iB; if (this.m_motorMass > 0) { this.m_motorMass = 1 / this.m_motorMass; } } else { this.m_motorMass = 0; this.m_motorImpulse = 0; } if (step.warmStarting) { this.m_impulse *= step.dtRatio; this.m_springImpulse *= step.dtRatio; this.m_motorImpulse *= step.dtRatio; var P = Vec2.combine(this.m_impulse, this.m_ay, this.m_springImpulse, this.m_ax); var LA = this.m_impulse * this.m_sAy + this.m_springImpulse * this.m_sAx + this.m_motorImpulse; var LB = this.m_impulse * this.m_sBy + this.m_springImpulse * this.m_sBx + this.m_motorImpulse; vA.subMul(this.m_invMassA, P); wA -= this.m_invIA * LA; vB.addMul(this.m_invMassB, P); wB += this.m_invIB * LB; } else { this.m_impulse = 0; this.m_springImpulse = 0; this.m_motorImpulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; WheelJoint.prototype.solveVelocityConstraints = function(step) { var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; { var Cdot = Vec2.dot(this.m_ax, vB) - Vec2.dot(this.m_ax, vA) + this.m_sBx * wB - this.m_sAx * wA; var impulse = -this.m_springMass * (Cdot + this.m_bias + this.m_gamma * this.m_springImpulse); this.m_springImpulse += impulse; var P = Vec2.mul(impulse, this.m_ax); var LA = impulse * this.m_sAx; var LB = impulse * this.m_sBx; vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } { var Cdot = wB - wA - this.m_motorSpeed; var impulse = -this.m_motorMass * Cdot; var oldImpulse = this.m_motorImpulse; var maxImpulse = step.dt * this.m_maxMotorTorque; this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } { var Cdot = Vec2.dot(this.m_ay, vB) - Vec2.dot(this.m_ay, vA) + this.m_sBy * wB - this.m_sAy * wA; var impulse = -this.m_mass * Cdot; this.m_impulse += impulse; var P = Vec2.mul(impulse, this.m_ay); var LA = impulse * this.m_sAy; var LB = impulse * this.m_sBy; vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; WheelJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.zero(); d.addCombine(1, cB, 1, rB); d.subCombine(1, cA, 1, rA); var ay = Rot.mulVec2(qA, this.m_localYAxisA); var sAy = Vec2.cross(Vec2.add(d, rA), ay); var sBy = Vec2.cross(rB, ay); var C = Vec2.dot(d, ay); var k = this.m_invMassA + this.m_invMassB + this.m_invIA * this.m_sAy * this.m_sAy + this.m_invIB * this.m_sBy * this.m_sBy; var impulse; if (k != 0) { impulse = -C / k; } else { impulse = 0; } var P = Vec2.mul(impulse, ay); var LA = impulse * sAy; var LB = impulse * sBy; cA.subMul(this.m_invMassA, P); aA -= this.m_invIA * LA; cB.addMul(this.m_invMassB, P); aB += this.m_invIB * LB; this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return Math.abs(C) <= Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],39:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = BoxShape; var common = require("../util/common"); var create = require("../util/create"); var PolygonShape = require("./PolygonShape"); BoxShape._super = PolygonShape; BoxShape.prototype = create(BoxShape._super.prototype); BoxShape.TYPE = "polygon"; function BoxShape(hx, hy, center, angle) { if (!(this instanceof BoxShape)) { return new BoxShape(hx, hy, center, angle); } BoxShape._super.call(this); this._setAsBox(hx, hy, center, angle); } },{"../util/common":51,"../util/create":52,"./PolygonShape":48}],40:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = ChainShape; var common = require("../util/common"); var create = require("../util/create"); var options = require("../util/options"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Shape = require("../Shape"); var EdgeShape = require("./EdgeShape"); ChainShape._super = Shape; ChainShape.prototype = create(ChainShape._super.prototype); ChainShape.TYPE = "chain"; function ChainShape(vertices, loop) { if (!(this instanceof ChainShape)) { return new ChainShape(vertices, loop); } ChainShape._super.call(this); this.m_type = ChainShape.TYPE; this.m_radius = Settings.polygonRadius; this.m_vertices = []; this.m_count = 0; this.m_prevVertex = null; this.m_nextVertex = null; this.m_hasPrevVertex = false; this.m_hasNextVertex = false; if (vertices && vertices.length) { if (loop) { this._createLoop(vertices); } else { this._createChain(vertices); } } } ChainShape.prototype._createLoop = function(vertices) { _ASSERT && common.assert(this.m_vertices.length == 0 && this.m_count == 0); _ASSERT && common.assert(vertices.length >= 3); for (var i = 1; i < vertices.length; ++i) { var v1 = vertices[i - 1]; var v2 = vertices[i]; _ASSERT && common.assert(Vec2.distanceSquared(v1, v2) > Settings.linearSlopSquared); } this.m_vertices.length = 0; this.m_count = vertices.length + 1; for (var i = 0; i < vertices.length; ++i) { this.m_vertices[i] = vertices[i].clone(); } this.m_vertices[vertices.length] = vertices[0].clone(); this.m_prevVertex = this.m_vertices[this.m_count - 2]; this.m_nextVertex = this.m_vertices[1]; this.m_hasPrevVertex = true; this.m_hasNextVertex = true; return this; }; ChainShape.prototype._createChain = function(vertices) { _ASSERT && common.assert(this.m_vertices.length == 0 && this.m_count == 0); _ASSERT && common.assert(vertices.length >= 2); for (var i = 1; i < vertices.length; ++i) { var v1 = vertices[i - 1]; var v2 = vertices[i]; _ASSERT && common.assert(Vec2.distanceSquared(v1, v2) > Settings.linearSlopSquared); } this.m_count = vertices.length; for (var i = 0; i < vertices.length; ++i) { this.m_vertices[i] = vertices[i].clone(); } this.m_hasPrevVertex = false; this.m_hasNextVertex = false; this.m_prevVertex = null; this.m_nextVertex = null; return this; }; ChainShape.prototype._setPrevVertex = function(prevVertex) { this.m_prevVertex = prevVertex; this.m_hasPrevVertex = true; }; ChainShape.prototype._setNextVertex = function(nextVertex) { this.m_nextVertex = nextVertex; this.m_hasNextVertex = true; }; ChainShape.prototype._clone = function() { var clone = new ChainShape(); clone.createChain(this.m_vertices); clone.m_type = this.m_type; clone.m_radius = this.m_radius; clone.m_prevVertex = this.m_prevVertex; clone.m_nextVertex = this.m_nextVertex; clone.m_hasPrevVertex = this.m_hasPrevVertex; clone.m_hasNextVertex = this.m_hasNextVertex; return clone; }; ChainShape.prototype.getChildCount = function() { return this.m_count - 1; }; ChainShape.prototype.getChildEdge = function(edge, childIndex) { _ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count - 1); edge.m_type = EdgeShape.TYPE; edge.m_radius = this.m_radius; edge.m_vertex1 = this.m_vertices[childIndex]; edge.m_vertex2 = this.m_vertices[childIndex + 1]; if (childIndex > 0) { edge.m_vertex0 = this.m_vertices[childIndex - 1]; edge.m_hasVertex0 = true; } else { edge.m_vertex0 = this.m_prevVertex; edge.m_hasVertex0 = this.m_hasPrevVertex; } if (childIndex < this.m_count - 2) { edge.m_vertex3 = this.m_vertices[childIndex + 2]; edge.m_hasVertex3 = true; } else { edge.m_vertex3 = this.m_nextVertex; edge.m_hasVertex3 = this.m_hasNextVertex; } }; ChainShape.prototype.getVertex = function(index) { _ASSERT && common.assert(0 <= index && index <= this.m_count); if (index < this.m_count) { return this.m_vertices[index]; } else { return this.m_vertices[0]; } }; ChainShape.prototype.testPoint = function(xf, p) { return false; }; ChainShape.prototype.rayCast = function(output, input, xf, childIndex) { _ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count); var edgeShape = new EdgeShape(this.getVertex(childIndex), this.getVertex(childIndex + 1)); return edgeShape.rayCast(output, input, xf, 0); }; ChainShape.prototype.computeAABB = function(aabb, xf, childIndex) { _ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count); var v1 = Transform.mulVec2(xf, this.getVertex(childIndex)); var v2 = Transform.mulVec2(xf, this.getVertex(childIndex + 1)); aabb.combinePoints(v1, v2); }; ChainShape.prototype.computeMass = function(massData, density) { massData.mass = 0; massData.center = Vec2.neo(); massData.I = 0; }; ChainShape.prototype.computeDistanceProxy = function(proxy, childIndex) { _ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count); proxy.m_buffer[0] = this.getVertex(childIndex); proxy.m_buffer[1] = this.getVertex(childIndex + 1); proxy.m_vertices = proxy.m_buffer; proxy.m_count = 2; proxy.m_radius = this.m_radius; }; },{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"../util/options":53,"./EdgeShape":47}],41:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = CircleShape; var common = require("../util/common"); var create = require("../util/create"); var options = require("../util/options"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Shape = require("../Shape"); CircleShape._super = Shape; CircleShape.prototype = create(CircleShape._super.prototype); CircleShape.TYPE = "circle"; function CircleShape(a, b) { if (!(this instanceof CircleShape)) { return new CircleShape(a, b); } CircleShape._super.call(this); this.m_type = CircleShape.TYPE; this.m_p = Vec2.zero(); this.m_radius = 1; if (typeof a === "object" && Vec2.isValid(a)) { this.m_p.set(a); if (typeof b === "number") { this.m_radius = b; } } else if (typeof a === "number") { this.m_radius = a; } } CircleShape.prototype.getRadius = function() { return this.m_radius; }; CircleShape.prototype.getCenter = function() { return this.m_p; }; CircleShape.prototype.getVertex = function(index) { _ASSERT && common.assert(index == 0); return this.m_p; }; CircleShape.prototype.getVertexCount = function(index) { return 1; }; CircleShape.prototype._clone = function() { var clone = new CircleShape(); clone.m_type = this.m_type; clone.m_radius = this.m_radius; clone.m_p = this.m_p.clone(); return clone; }; CircleShape.prototype.getChildCount = function() { return 1; }; CircleShape.prototype.testPoint = function(xf, p) { var center = Vec2.add(xf.p, Rot.mulVec2(xf.q, this.m_p)); var d = Vec2.sub(p, center); return Vec2.dot(d, d) <= this.m_radius * this.m_radius; }; CircleShape.prototype.rayCast = function(output, input, xf, childIndex) { var position = Vec2.add(xf.p, Rot.mulVec2(xf.q, this.m_p)); var s = Vec2.sub(input.p1, position); var b = Vec2.dot(s, s) - this.m_radius * this.m_radius; var r = Vec2.sub(input.p2, input.p1); var c = Vec2.dot(s, r); var rr = Vec2.dot(r, r); var sigma = c * c - rr * b; if (sigma < 0 || rr < Math.EPSILON) { return false; } var a = -(c + Math.sqrt(sigma)); if (0 <= a && a <= input.maxFraction * rr) { a /= rr; output.fraction = a; output.normal = Vec2.add(s, Vec2.mul(a, r)); output.normal.normalize(); return true; } return false; }; CircleShape.prototype.computeAABB = function(aabb, xf, childIndex) { var p = Vec2.add(xf.p, Rot.mulVec2(xf.q, this.m_p)); aabb.lowerBound.set(p.x - this.m_radius, p.y - this.m_radius); aabb.upperBound.set(p.x + this.m_radius, p.y + this.m_radius); }; CircleShape.prototype.computeMass = function(massData, density) { massData.mass = density * Math.PI * this.m_radius * this.m_radius; massData.center = this.m_p; massData.I = massData.mass * (.5 * this.m_radius * this.m_radius + Vec2.dot(this.m_p, this.m_p)); }; CircleShape.prototype.computeDistanceProxy = function(proxy) { proxy.m_vertices.push(this.m_p); proxy.m_count = 1; proxy.m_radius = this.m_radius; }; },{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"../util/options":53}],42:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Vec2 = require("../common/Vec2"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Contact = require("../Contact"); var Manifold = require("../Manifold"); var CircleShape = require("./CircleShape"); Contact.addType(CircleShape.TYPE, CircleShape.TYPE, CircleCircleContact); function CircleCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { _ASSERT && common.assert(fixtureA.getType() == CircleShape.TYPE); _ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE); CollideCircles(manifold, fixtureA.getShape(), xfA, fixtureB.getShape(), xfB); } function CollideCircles(manifold, circleA, xfA, circleB, xfB) { manifold.pointCount = 0; var pA = Transform.mulVec2(xfA, circleA.m_p); var pB = Transform.mulVec2(xfB, circleB.m_p); var distSqr = Vec2.distanceSquared(pB, pA); var rA = circleA.m_radius; var rB = circleB.m_radius; var radius = rA + rB; if (distSqr > radius * radius) { return; } manifold.type = Manifold.e_circles; manifold.localPoint.set(circleA.m_p); manifold.localNormal.setZero(); manifold.pointCount = 1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.cf.indexA = 0; manifold.points[0].id.cf.typeA = Manifold.e_vertex; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; } exports.CollideCircles = CollideCircles; },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../common/Math":18,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"./CircleShape":41}],43:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Manifold = require("../Manifold"); var Contact = require("../Contact"); var Shape = require("../Shape"); var CircleShape = require("./CircleShape"); var PolygonShape = require("./PolygonShape"); Contact.addType(PolygonShape.TYPE, CircleShape.TYPE, PolygonCircleContact); function PolygonCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { _ASSERT && common.assert(fixtureA.getType() == PolygonShape.TYPE); _ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE); CollidePolygonCircle(manifold, fixtureA.getShape(), xfA, fixtureB.getShape(), xfB); } function CollidePolygonCircle(manifold, polygonA, xfA, circleB, xfB) { manifold.pointCount = 0; var c = Transform.mulVec2(xfB, circleB.m_p); var cLocal = Transform.mulTVec2(xfA, c); var normalIndex = 0; var separation = -Infinity; var radius = polygonA.m_radius + circleB.m_radius; var vertexCount = polygonA.m_count; var vertices = polygonA.m_vertices; var normals = polygonA.m_normals; for (var i = 0; i < vertexCount; ++i) { var s = Vec2.dot(normals[i], Vec2.sub(cLocal, vertices[i])); if (s > radius) { return; } if (s > separation) { separation = s; normalIndex = i; } } var vertIndex1 = normalIndex; var vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0; var v1 = vertices[vertIndex1]; var v2 = vertices[vertIndex2]; if (separation < Math.EPSILON) { manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.set(normals[normalIndex]); manifold.localPoint.setCombine(.5, v1, .5, v2); manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.cf.indexA = 0; manifold.points[0].id.cf.typeA = Manifold.e_vertex; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; return; } var u1 = Vec2.dot(Vec2.sub(cLocal, v1), Vec2.sub(v2, v1)); var u2 = Vec2.dot(Vec2.sub(cLocal, v2), Vec2.sub(v1, v2)); if (u1 <= 0) { if (Vec2.distanceSquared(cLocal, v1) > radius * radius) { return; } manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.setCombine(1, cLocal, -1, v1); manifold.localNormal.normalize(); manifold.localPoint.set(v1); manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.cf.indexA = 0; manifold.points[0].id.cf.typeA = Manifold.e_vertex; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; } else if (u2 <= 0) { if (Vec2.distanceSquared(cLocal, v2) > radius * radius) { return; } manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.setCombine(1, cLocal, -1, v2); manifold.localNormal.normalize(); manifold.localPoint.set(v2); manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.cf.indexA = 0; manifold.points[0].id.cf.typeA = Manifold.e_vertex; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; } else { var faceCenter = Vec2.mid(v1, v2); var separation = Vec2.dot(cLocal, normals[vertIndex1]) - Vec2.dot(faceCenter, normals[vertIndex1]); if (separation > radius) { return; } manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.set(normals[vertIndex1]); manifold.localPoint.set(faceCenter); manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.cf.indexA = 0; manifold.points[0].id.cf.typeA = Manifold.e_vertex; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; } } },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"./CircleShape":41,"./PolygonShape":48}],44:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Vec2 = require("../common/Vec2"); var Rot = require("../common/Rot"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Contact = require("../Contact"); var Manifold = require("../Manifold"); var EdgeShape = require("./EdgeShape"); var ChainShape = require("./ChainShape"); var CircleShape = require("./CircleShape"); Contact.addType(EdgeShape.TYPE, CircleShape.TYPE, EdgeCircleContact); Contact.addType(ChainShape.TYPE, CircleShape.TYPE, ChainCircleContact); function EdgeCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { _ASSERT && common.assert(fixtureA.getType() == EdgeShape.TYPE); _ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE); var shapeA = fixtureA.getShape(); var shapeB = fixtureB.getShape(); CollideEdgeCircle(manifold, shapeA, xfA, shapeB, xfB); } function ChainCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { _ASSERT && common.assert(fixtureA.getType() == ChainShape.TYPE); _ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE); var chain = fixtureA.getShape(); var edge = new EdgeShape(); chain.getChildEdge(edge, indexA); var shapeA = edge; var shapeB = fixtureB.getShape(); CollideEdgeCircle(manifold, shapeA, xfA, shapeB, xfB); } function CollideEdgeCircle(manifold, edgeA, xfA, circleB, xfB) { manifold.pointCount = 0; var Q = Transform.mulTVec2(xfA, Transform.mulVec2(xfB, circleB.m_p)); var A = edgeA.m_vertex1; var B = edgeA.m_vertex2; var e = Vec2.sub(B, A); var u = Vec2.dot(e, Vec2.sub(B, Q)); var v = Vec2.dot(e, Vec2.sub(Q, A)); var radius = edgeA.m_radius + circleB.m_radius; if (v <= 0) { var P = Vec2.clone(A); var d = Vec2.sub(Q, P); var dd = Vec2.dot(d, d); if (dd > radius * radius) { return; } if (edgeA.m_hasVertex0) { var A1 = edgeA.m_vertex0; var B1 = A; var e1 = Vec2.sub(B1, A1); var u1 = Vec2.dot(e1, Vec2.sub(B1, Q)); if (u1 > 0) { return; } } manifold.type = Manifold.e_circles; manifold.localNormal.setZero(); manifold.localPoint.set(P); manifold.pointCount = 1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.cf.indexA = 0; manifold.points[0].id.cf.typeA = Manifold.e_vertex; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; return; } if (u <= 0) { var P = Vec2.clone(B); var d = Vec2.sub(Q, P); var dd = Vec2.dot(d, d); if (dd > radius * radius) { return; } if (edgeA.m_hasVertex3) { var B2 = edgeA.m_vertex3; var A2 = B; var e2 = Vec2.sub(B2, A2); var v2 = Vec2.dot(e2, Vec2.sub(Q, A2)); if (v2 > 0) { return; } } manifold.type = Manifold.e_circles; manifold.localNormal.setZero(); manifold.localPoint.set(P); manifold.pointCount = 1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.cf.indexA = 1; manifold.points[0].id.cf.typeA = Manifold.e_vertex; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; return; } var den = Vec2.dot(e, e); _ASSERT && common.assert(den > 0); var P = Vec2.combine(u / den, A, v / den, B); var d = Vec2.sub(Q, P); var dd = Vec2.dot(d, d); if (dd > radius * radius) { return; } var n = Vec2.neo(-e.y, e.x); if (Vec2.dot(n, Vec2.sub(Q, A)) < 0) { n.set(-n.x, -n.y); } n.normalize(); manifold.type = Manifold.e_faceA; manifold.localNormal.set(n); manifold.localPoint.set(A); manifold.pointCount = 1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.cf.indexA = 0; manifold.points[0].id.cf.typeA = Manifold.e_face; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; } },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"./ChainShape":40,"./CircleShape":41,"./EdgeShape":47}],45:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Vec2 = require("../common/Vec2"); var Rot = require("../common/Rot"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Contact = require("../Contact"); var Manifold = require("../Manifold"); var EdgeShape = require("./EdgeShape"); var ChainShape = require("./ChainShape"); var PolygonShape = require("./PolygonShape"); Contact.addType(EdgeShape.TYPE, PolygonShape.TYPE, EdgePolygonContact); Contact.addType(ChainShape.TYPE, PolygonShape.TYPE, ChainPolygonContact); function EdgePolygonContact(manifold, xfA, fA, indexA, xfB, fB, indexB) { _ASSERT && common.assert(fA.getType() == EdgeShape.TYPE); _ASSERT && common.assert(fB.getType() == PolygonShape.TYPE); CollideEdgePolygon(manifold, fA.getShape(), xfA, fB.getShape(), xfB); } function ChainPolygonContact(manifold, xfA, fA, indexA, xfB, fB, indexB) { _ASSERT && common.assert(fA.getType() == ChainShape.TYPE); _ASSERT && common.assert(fB.getType() == PolygonShape.TYPE); var chain = fA.getShape(); var edge = new EdgeShape(); chain.getChildEdge(edge, indexA); CollideEdgePolygon(manifold, edge, xfA, fB.getShape(), xfB); } var e_unknown = -1; var e_edgeA = 1; var e_edgeB = 2; var e_isolated = 0; var e_concave = 1; var e_convex = 2; function EPAxis() { this.type; this.index; this.separation; } function TempPolygon() { this.vertices = []; this.normals = []; this.count = 0; } function ReferenceFace() { this.i1, this.i2; this.v1, this.v2; this.normal = Vec2.zero(); this.sideNormal1 = Vec2.zero(); this.sideOffset1; this.sideNormal2 = Vec2.zero(); this.sideOffset2; } var edgeAxis = new EPAxis(); var polygonAxis = new EPAxis(); var polygonBA = new TempPolygon(); var rf = new ReferenceFace(); function CollideEdgePolygon(manifold, edgeA, xfA, polygonB, xfB) { var m_type1, m_type2; var xf = Transform.mulTXf(xfA, xfB); var centroidB = Transform.mulVec2(xf, polygonB.m_centroid); var v0 = edgeA.m_vertex0; var v1 = edgeA.m_vertex1; var v2 = edgeA.m_vertex2; var v3 = edgeA.m_vertex3; var hasVertex0 = edgeA.m_hasVertex0; var hasVertex3 = edgeA.m_hasVertex3; var edge1 = Vec2.sub(v2, v1); edge1.normalize(); var normal1 = Vec2.neo(edge1.y, -edge1.x); var offset1 = Vec2.dot(normal1, Vec2.sub(centroidB, v1)); var offset0 = 0; var offset2 = 0; var convex1 = false; var convex2 = false; if (hasVertex0) { var edge0 = Vec2.sub(v1, v0); edge0.normalize(); var normal0 = Vec2.neo(edge0.y, -edge0.x); convex1 = Vec2.cross(edge0, edge1) >= 0; offset0 = Vec2.dot(normal0, centroidB) - Vec2.dot(normal0, v0); } if (hasVertex3) { var edge2 = Vec2.sub(v3, v2); edge2.normalize(); var normal2 = Vec2.neo(edge2.y, -edge2.x); convex2 = Vec2.cross(edge1, edge2) > 0; offset2 = Vec2.dot(normal2, centroidB) - Vec2.dot(normal2, v2); } var front; var normal = Vec2.zero(); var lowerLimit = Vec2.zero(); var upperLimit = Vec2.zero(); if (hasVertex0 && hasVertex3) { if (convex1 && convex2) { front = offset0 >= 0 || offset1 >= 0 || offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal0); upperLimit.set(normal2); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal1); upperLimit.setMul(-1, normal1); } } else if (convex1) { front = offset0 >= 0 || offset1 >= 0 && offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal0); upperLimit.set(normal1); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal2); upperLimit.setMul(-1, normal1); } } else if (convex2) { front = offset2 >= 0 || offset0 >= 0 && offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal1); upperLimit.set(normal2); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal1); upperLimit.setMul(-1, normal0); } } else { front = offset0 >= 0 && offset1 >= 0 && offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal1); upperLimit.set(normal1); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal2); upperLimit.setMul(-1, normal0); } } } else if (hasVertex0) { if (convex1) { front = offset0 >= 0 || offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal0); upperLimit.setMul(-1, normal1); } else { normal.setMul(-1, normal1); lowerLimit.set(normal1); upperLimit.setMul(-1, normal1); } } else { front = offset0 >= 0 && offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal1); upperLimit.setMul(-1, normal1); } else { normal.setMul(-1, normal1); lowerLimit.set(normal1); upperLimit.setMul(-1, normal0); } } } else if (hasVertex3) { if (convex2) { front = offset1 >= 0 || offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.setMul(-1, normal1); upperLimit.set(normal2); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal1); upperLimit.set(normal1); } } else { front = offset1 >= 0 && offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.setMul(-1, normal1); upperLimit.set(normal1); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal2); upperLimit.set(normal1); } } } else { front = offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.setMul(-1, normal1); upperLimit.setMul(-1, normal1); } else { normal.setMul(-1, normal1); lowerLimit.set(normal1); upperLimit.set(normal1); } } polygonBA.count = polygonB.m_count; for (var i = 0; i < polygonB.m_count; ++i) { polygonBA.vertices[i] = Transform.mulVec2(xf, polygonB.m_vertices[i]); polygonBA.normals[i] = Rot.mulVec2(xf.q, polygonB.m_normals[i]); } var radius = 2 * Settings.polygonRadius; manifold.pointCount = 0; { edgeAxis.type = e_edgeA; edgeAxis.index = front ? 0 : 1; edgeAxis.separation = Infinity; for (var i = 0; i < polygonBA.count; ++i) { var s = Vec2.dot(normal, Vec2.sub(polygonBA.vertices[i], v1)); if (s < edgeAxis.separation) { edgeAxis.separation = s; } } } if (edgeAxis.type == e_unknown) { return; } if (edgeAxis.separation > radius) { return; } { polygonAxis.type = e_unknown; polygonAxis.index = -1; polygonAxis.separation = -Infinity; var perp = Vec2.neo(-normal.y, normal.x); for (var i = 0; i < polygonBA.count; ++i) { var n = Vec2.neg(polygonBA.normals[i]); var s1 = Vec2.dot(n, Vec2.sub(polygonBA.vertices[i], v1)); var s2 = Vec2.dot(n, Vec2.sub(polygonBA.vertices[i], v2)); var s = Math.min(s1, s2); if (s > radius) { polygonAxis.type = e_edgeB; polygonAxis.index = i; polygonAxis.separation = s; break; } if (Vec2.dot(n, perp) >= 0) { if (Vec2.dot(Vec2.sub(n, upperLimit), normal) < -Settings.angularSlop) { continue; } } else { if (Vec2.dot(Vec2.sub(n, lowerLimit), normal) < -Settings.angularSlop) { continue; } } if (s > polygonAxis.separation) { polygonAxis.type = e_edgeB; polygonAxis.index = i; polygonAxis.separation = s; } } } if (polygonAxis.type != e_unknown && polygonAxis.separation > radius) { return; } var k_relativeTol = .98; var k_absoluteTol = .001; var primaryAxis; if (polygonAxis.type == e_unknown) { primaryAxis = edgeAxis; } else if (polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol) { primaryAxis = polygonAxis; } else { primaryAxis = edgeAxis; } var ie = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; if (primaryAxis.type == e_edgeA) { manifold.type = Manifold.e_faceA; var bestIndex = 0; var bestValue = Vec2.dot(normal, polygonBA.normals[0]); for (var i = 1; i < polygonBA.count; ++i) { var value = Vec2.dot(normal, polygonBA.normals[i]); if (value < bestValue) { bestValue = value; bestIndex = i; } } var i1 = bestIndex; var i2 = i1 + 1 < polygonBA.count ? i1 + 1 : 0; ie[0].v = polygonBA.vertices[i1]; ie[0].id.cf.indexA = 0; ie[0].id.cf.indexB = i1; ie[0].id.cf.typeA = Manifold.e_face; ie[0].id.cf.typeB = Manifold.e_vertex; ie[1].v = polygonBA.vertices[i2]; ie[1].id.cf.indexA = 0; ie[1].id.cf.indexB = i2; ie[1].id.cf.typeA = Manifold.e_face; ie[1].id.cf.typeB = Manifold.e_vertex; if (front) { rf.i1 = 0; rf.i2 = 1; rf.v1 = v1; rf.v2 = v2; rf.normal.set(normal1); } else { rf.i1 = 1; rf.i2 = 0; rf.v1 = v2; rf.v2 = v1; rf.normal.setMul(-1, normal1); } } else { manifold.type = Manifold.e_faceB; ie[0].v = v1; ie[0].id.cf.indexA = 0; ie[0].id.cf.indexB = primaryAxis.index; ie[0].id.cf.typeA = Manifold.e_vertex; ie[0].id.cf.typeB = Manifold.e_face; ie[1].v = v2; ie[1].id.cf.indexA = 0; ie[1].id.cf.indexB = primaryAxis.index; ie[1].id.cf.typeA = Manifold.e_vertex; ie[1].id.cf.typeB = Manifold.e_face; rf.i1 = primaryAxis.index; rf.i2 = rf.i1 + 1 < polygonBA.count ? rf.i1 + 1 : 0; rf.v1 = polygonBA.vertices[rf.i1]; rf.v2 = polygonBA.vertices[rf.i2]; rf.normal.set(polygonBA.normals[rf.i1]); } rf.sideNormal1.set(rf.normal.y, -rf.normal.x); rf.sideNormal2.setMul(-1, rf.sideNormal1); rf.sideOffset1 = Vec2.dot(rf.sideNormal1, rf.v1); rf.sideOffset2 = Vec2.dot(rf.sideNormal2, rf.v2); var clipPoints1 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var clipPoints2 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var np; np = Manifold.clipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1); if (np < Settings.maxManifoldPoints) { return; } np = Manifold.clipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2); if (np < Settings.maxManifoldPoints) { return; } if (primaryAxis.type == e_edgeA) { manifold.localNormal = Vec2.clone(rf.normal); manifold.localPoint = Vec2.clone(rf.v1); } else { manifold.localNormal = Vec2.clone(polygonB.m_normals[rf.i1]); manifold.localPoint = Vec2.clone(polygonB.m_vertices[rf.i1]); } var pointCount = 0; for (var i = 0; i < Settings.maxManifoldPoints; ++i) { var separation = Vec2.dot(rf.normal, Vec2.sub(clipPoints2[i].v, rf.v1)); if (separation <= radius) { var cp = manifold.points[pointCount]; if (primaryAxis.type == e_edgeA) { cp.localPoint = Transform.mulT(xf, clipPoints2[i].v); cp.id = clipPoints2[i].id; } else { cp.localPoint = clipPoints2[i].v; cp.id.cf.typeA = clipPoints2[i].id.cf.typeB; cp.id.cf.typeB = clipPoints2[i].id.cf.typeA; cp.id.cf.indexA = clipPoints2[i].id.cf.indexB; cp.id.cf.indexB = clipPoints2[i].id.cf.indexA; } ++pointCount; } } manifold.pointCount = pointCount; } },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"./ChainShape":40,"./EdgeShape":47,"./PolygonShape":48}],46:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Manifold = require("../Manifold"); var Contact = require("../Contact"); var Shape = require("../Shape"); var PolygonShape = require("./PolygonShape"); module.exports = CollidePolygons; Contact.addType(PolygonShape.TYPE, PolygonShape.TYPE, PolygonContact); function PolygonContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { _ASSERT && common.assert(fixtureA.getType() == PolygonShape.TYPE); _ASSERT && common.assert(fixtureB.getType() == PolygonShape.TYPE); CollidePolygons(manifold, fixtureA.getShape(), xfA, fixtureB.getShape(), xfB); } var fms_v1 = Vec2.zero(); var fms_n = Vec2.zero(); var fms_xf = Transform.identity(); var fms_maxSeparation; var fms_bestIndex; function FindMaxSeparation(poly1, xf1, poly2, xf2) { var count1 = poly1.m_count; var count2 = poly2.m_count; var n1s = poly1.m_normals; var v1s = poly1.m_vertices; var v2s = poly2.m_vertices; var xf = Transform.mulTXf_(xf2, xf1, fms_xf); var bestIndex = 0; var maxSeparation = -Infinity; for (var i = 0; i < count1; ++i) { var n = Rot.mulVec2_(xf.q, n1s[i], fms_n); var v1 = Transform.mulVec2_(xf, v1s[i], fms_v1); var si = Infinity; for (var j = 0; j < count2; ++j) { var sij = Vec2.dot(n, v2s[j]) - Vec2.dot(n, v1); if (sij < si) { si = sij; } } if (si > maxSeparation) { maxSeparation = si; bestIndex = i; } } fms_maxSeparation = maxSeparation; fms_bestIndex = bestIndex; } var fie_t1 = Vec2.zero(); var fie_normal1 = Vec2.zero(); function FindIncidentEdge(c, poly1, xf1, edge1, poly2, xf2) { var normals1 = poly1.m_normals; var count2 = poly2.m_count; var vertices2 = poly2.m_vertices; var normals2 = poly2.m_normals; _ASSERT && common.assert(0 <= edge1 && edge1 < poly1.m_count); var normal1 = Rot.mulTVec2_(xf2.q, Rot.mulVec2_(xf1.q, normals1[edge1], fie_t1), fie_normal1); var index = 0; var minDot = Infinity; for (var i = 0; i < count2; ++i) { var dot = Vec2.dot(normal1, normals2[i]); if (dot < minDot) { minDot = dot; index = i; } } var i1 = index; var i2 = i1 + 1 < count2 ? i1 + 1 : 0; c[0].v = Transform.mulVec2(xf2, vertices2[i1]); c[0].id.cf.indexA = edge1; c[0].id.cf.indexB = i1; c[0].id.cf.typeA = Manifold.e_face; c[0].id.cf.typeB = Manifold.e_vertex; c[1].v = Transform.mulVec2(xf2, vertices2[i2]); c[1].id.cf.indexA = edge1; c[1].id.cf.indexB = i2; c[1].id.cf.typeA = Manifold.e_face; c[1].id.cf.typeB = Manifold.e_vertex; } var cpg_planePoint = Vec2.zero(); var cpg_tangent = Vec2.zero(); var cpg_normal = Vec2.zero(); var cpg_localTangent = Vec2.zero(); var cpg_localNormal = Vec2.zero(); var cpg_v11 = Vec2.zero(); var cpg_v12 = Vec2.zero(); var cpg_t1 = Vec2.zero(); var cpg_clipPoints1 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var cpg_clipPoints2 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var cpg_incidentEdge = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; function CollidePolygons(manifold, polyA, xfA, polyB, xfB) { manifold.pointCount = 0; var totalRadius = polyA.m_radius + polyB.m_radius; FindMaxSeparation(polyA, xfA, polyB, xfB); var edgeA = fms_bestIndex; var separationA = fms_maxSeparation; if (separationA > totalRadius) return; FindMaxSeparation(polyB, xfB, polyA, xfA); var edgeB = fms_bestIndex; var separationB = fms_maxSeparation; if (separationB > totalRadius) return; var poly1; var poly2; var xf1; var xf2; var edge1; var flip; var k_tol = .1 * Settings.linearSlop; if (separationB > separationA + k_tol) { poly1 = polyB; poly2 = polyA; xf1 = xfB; xf2 = xfA; edge1 = edgeB; manifold.type = Manifold.e_faceB; flip = 1; } else { poly1 = polyA; poly2 = polyB; xf1 = xfA; xf2 = xfB; edge1 = edgeA; manifold.type = Manifold.e_faceA; flip = 0; } var incidentEdge = cpg_incidentEdge; cpg_incidentEdge[0].init(); cpg_incidentEdge[1].init(); FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2); var count1 = poly1.m_count; var vertices1 = poly1.m_vertices; var iv1 = edge1; var iv2 = edge1 + 1 < count1 ? edge1 + 1 : 0; var v11 = cpg_v11.set(vertices1[iv1]); var v12 = cpg_v12.set(vertices1[iv2]); var localTangent = Vec2.sub_(v12, v11, cpg_localTangent); localTangent.normalize(); var localNormal = Vec2.crossVec2Num_(localTangent, 1, cpg_localNormal); var planePoint = Vec2.combine_(.5, v11, .5, v12, cpg_planePoint); var tangent = Rot.mulVec2_(xf1.q, localTangent, cpg_tangent); var normal = Vec2.crossVec2Num_(tangent, 1, cpg_normal); v11 = Transform.mulVec2_(xf1, v11, v11); v12 = Transform.mulVec2_(xf1, v12, v12); var frontOffset = Vec2.dot(normal, v11); var sideOffset1 = -Vec2.dot(tangent, v11) + totalRadius; var sideOffset2 = Vec2.dot(tangent, v12) + totalRadius; cpg_clipPoints1[0].init(); cpg_clipPoints1[1].init(); cpg_clipPoints2[0].init(); cpg_clipPoints2[1].init(); var clipPoints1 = cpg_clipPoints1; var clipPoints2 = cpg_clipPoints2; var np; np = Manifold.clipSegmentToLine(clipPoints1, incidentEdge, Vec2.neg_(tangent, cpg_t1), sideOffset1, iv1); if (np < Settings.maxManifoldPoints) { return; } np = Manifold.clipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2, iv2); if (np < Settings.maxManifoldPoints) { return; } manifold.localNormal.set(localNormal); manifold.localPoint.set(planePoint); var pointCount = 0; for (var i = 0; i < Settings.maxManifoldPoints; ++i) { var separation = Vec2.dot(normal, clipPoints2[i].v) - frontOffset; if (separation <= totalRadius) { var cp = manifold.points[i]; cp.init(); cp.localPoint.set(Transform.mulTVec2(xf2, clipPoints2[i].v, cpg_t1)); cp.id = clipPoints2[i].id; if (flip) { var cf = cp.id.cf; var indexA = cf.indexA; var indexB = cf.indexB; var typeA = cf.typeA; var typeB = cf.typeB; cf.indexA = indexB; cf.indexB = indexA; cf.typeA = typeB; cf.typeB = typeA; } ++pointCount; } } manifold.pointCount = pointCount; } },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"./PolygonShape":48}],47:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = EdgeShape; var create = require("../util/create"); var options = require("../util/options"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); EdgeShape._super = Shape; EdgeShape.prototype = create(EdgeShape._super.prototype); EdgeShape.TYPE = "edge"; function EdgeShape(v1, v2) { if (!(this instanceof EdgeShape)) { return new EdgeShape(v1, v2); } EdgeShape._super.call(this); this.m_type = EdgeShape.TYPE; this.m_radius = Settings.polygonRadius; this.m_vertex1 = v1 ? Vec2.clone(v1) : Vec2.zero(); this.m_vertex2 = v2 ? Vec2.clone(v2) : Vec2.zero(); this.m_vertex0 = Vec2.zero(); this.m_vertex3 = Vec2.zero(); this.m_hasVertex0 = false; this.m_hasVertex3 = false; } EdgeShape.prototype.setNext = function(v3) { if (v3) { this.m_vertex3.set(v3); this.m_hasVertex3 = true; } else { this.m_vertex3.setZero(); this.m_hasVertex3 = false; } return this; }; EdgeShape.prototype.setPrev = function(v0) { if (v0) { this.m_vertex0.set(v0); this.m_hasVertex0 = true; } else { this.m_vertex0.setZero(); this.m_hasVertex0 = false; } return this; }; EdgeShape.prototype._set = function(v1, v2) { this.m_vertex1.set(v1); this.m_vertex2.set(v2); this.m_hasVertex0 = false; this.m_hasVertex3 = false; return this; }; EdgeShape.prototype._clone = function() { var clone = new EdgeShape(); clone.m_type = this.m_type; clone.m_radius = this.m_radius; clone.m_vertex1.set(this.m_vertex1); clone.m_vertex2.set(this.m_vertex2); clone.m_vertex0.set(this.m_vertex0); clone.m_vertex3.set(this.m_vertex3); clone.m_hasVertex0 = this.m_hasVertex0; clone.m_hasVertex3 = this.m_hasVertex3; return clone; }; EdgeShape.prototype.getChildCount = function() { return 1; }; EdgeShape.prototype.testPoint = function(xf, p) { return false; }; EdgeShape.prototype.rayCast = function(output, input, xf, childIndex) { var p1 = Rot.mulTVec2(xf.q, Vec2.sub(input.p1, xf.p)); var p2 = Rot.mulTVec2(xf.q, Vec2.sub(input.p2, xf.p)); var d = Vec2.sub(p2, p1); var v1 = this.m_vertex1; var v2 = this.m_vertex2; var e = Vec2.sub(v2, v1); var normal = Vec2.neo(e.y, -e.x); normal.normalize(); var numerator = Vec2.dot(normal, Vec2.sub(v1, p1)); var denominator = Vec2.dot(normal, d); if (denominator == 0) { return false; } var t = numerator / denominator; if (t < 0 || input.maxFraction < t) { return false; } var q = Vec2.add(p1, Vec2.mul(t, d)); var r = Vec2.sub(v2, v1); var rr = Vec2.dot(r, r); if (rr == 0) { return false; } var s = Vec2.dot(Vec2.sub(q, v1), r) / rr; if (s < 0 || 1 < s) { return false; } output.fraction = t; if (numerator > 0) { output.normal = Rot.mulVec2(xf.q, normal).neg(); } else { output.normal = Rot.mulVec2(xf.q, normal); } return true; }; EdgeShape.prototype.computeAABB = function(aabb, xf, childIndex) { var v1 = Transform.mulVec2(xf, this.m_vertex1); var v2 = Transform.mulVec2(xf, this.m_vertex2); aabb.combinePoints(v1, v2); aabb.extend(this.m_radius); }; EdgeShape.prototype.computeMass = function(massData, density) { massData.mass = 0; massData.center.setCombine(.5, this.m_vertex1, .5, this.m_vertex2); massData.I = 0; }; EdgeShape.prototype.computeDistanceProxy = function(proxy) { proxy.m_vertices.push(this.m_vertex1); proxy.m_vertices.push(this.m_vertex2); proxy.m_count = 2; proxy.m_radius = this.m_radius; }; },{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/create":52,"../util/options":53}],48:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = PolygonShape; var common = require("../util/common"); var create = require("../util/create"); var options = require("../util/options"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Shape = require("../Shape"); PolygonShape._super = Shape; PolygonShape.prototype = create(PolygonShape._super.prototype); PolygonShape.TYPE = "polygon"; function PolygonShape(vertices) { if (!(this instanceof PolygonShape)) { return new PolygonShape(vertices); } PolygonShape._super.call(this); this.m_type = PolygonShape.TYPE; this.m_radius = Settings.polygonRadius; this.m_centroid = Vec2.zero(); this.m_vertices = []; this.m_normals = []; this.m_count = 0; if (vertices && vertices.length) { this._set(vertices); } } PolygonShape.prototype.getVertex = function(index) { _ASSERT && common.assert(0 <= index && index < this.m_count); return this.m_vertices[index]; }; PolygonShape.prototype._clone = function() { var clone = new PolygonShape(); clone.m_type = this.m_type; clone.m_radius = this.m_radius; clone.m_count = this.m_count; clone.m_centroid.set(this.m_centroid); for (var i = 0; i < this.m_count; i++) { clone.m_vertices.push(this.m_vertices[i].clone()); } for (var i = 0; i < this.m_normals.length; i++) { clone.m_normals.push(this.m_normals[i].clone()); } return clone; }; PolygonShape.prototype.getChildCount = function() { return 1; }; function ComputeCentroid(vs, count) { _ASSERT && common.assert(count >= 3); var c = Vec2.zero(); var area = 0; var pRef = Vec2.zero(); if (false) { for (var i = 0; i < count; ++i) { pRef.add(vs[i]); } pRef.mul(1 / count); } var inv3 = 1 / 3; for (var i = 0; i < count; ++i) { var p1 = pRef; var p2 = vs[i]; var p3 = i + 1 < count ? vs[i + 1] : vs[0]; var e1 = Vec2.sub(p2, p1); var e2 = Vec2.sub(p3, p1); var D = Vec2.cross(e1, e2); var triangleArea = .5 * D; area += triangleArea; c.addMul(triangleArea * inv3, p1); c.addMul(triangleArea * inv3, p2); c.addMul(triangleArea * inv3, p3); } _ASSERT && common.assert(area > Math.EPSILON); c.mul(1 / area); return c; } PolygonShape.prototype._set = function(vertices) { _ASSERT && common.assert(3 <= vertices.length && vertices.length <= Settings.maxPolygonVertices); if (vertices.length < 3) { this._setAsBox(1, 1); return; } var n = Math.min(vertices.length, Settings.maxPolygonVertices); var ps = []; var tempCount = 0; for (var i = 0; i < n; ++i) { var v = vertices[i]; var unique = true; for (var j = 0; j < tempCount; ++j) { if (Vec2.distanceSquared(v, ps[j]) < .25 * Settings.linearSlopSquared) { unique = false; break; } } if (unique) { ps[tempCount++] = v; } } n = tempCount; if (n < 3) { _ASSERT && common.assert(false); this._setAsBox(1, 1); return; } var i0 = 0; var x0 = ps[0].x; for (var i = 1; i < n; ++i) { var x = ps[i].x; if (x > x0 || x == x0 && ps[i].y < ps[i0].y) { i0 = i; x0 = x; } } var hull = []; var m = 0; var ih = i0; for (;;) { hull[m] = ih; var ie = 0; for (var j = 1; j < n; ++j) { if (ie == ih) { ie = j; continue; } var r = Vec2.sub(ps[ie], ps[hull[m]]); var v = Vec2.sub(ps[j], ps[hull[m]]); var c = Vec2.cross(r, v); if (c < 0) { ie = j; } if (c == 0 && v.lengthSquared() > r.lengthSquared()) { ie = j; } } ++m; ih = ie; if (ie == i0) { break; } } if (m < 3) { _ASSERT && common.assert(false); this._setAsBox(1, 1); return; } this.m_count = m; for (var i = 0; i < m; ++i) { this.m_vertices[i] = ps[hull[i]]; } for (var i = 0; i < m; ++i) { var i1 = i; var i2 = i + 1 < m ? i + 1 : 0; var edge = Vec2.sub(this.m_vertices[i2], this.m_vertices[i1]); _ASSERT && common.assert(edge.lengthSquared() > Math.EPSILON * Math.EPSILON); this.m_normals[i] = Vec2.cross(edge, 1); this.m_normals[i].normalize(); } this.m_centroid = ComputeCentroid(this.m_vertices, m); }; PolygonShape.prototype._setAsBox = function(hx, hy, center, angle) { this.m_vertices[0] = Vec2.neo(-hx, -hy); this.m_vertices[1] = Vec2.neo(hx, -hy); this.m_vertices[2] = Vec2.neo(hx, hy); this.m_vertices[3] = Vec2.neo(-hx, hy); this.m_normals[0] = Vec2.neo(0, -1); this.m_normals[1] = Vec2.neo(1, 0); this.m_normals[2] = Vec2.neo(0, 1); this.m_normals[3] = Vec2.neo(-1, 0); this.m_count = 4; if (Vec2.isValid(center)) { angle = angle || 0; this.m_centroid.set(center); var xf = Transform.identity(); xf.p.set(center); xf.q.set(angle); for (var i = 0; i < this.m_count; ++i) { this.m_vertices[i] = Transform.mulVec2(xf, this.m_vertices[i]); this.m_normals[i] = Rot.mulVec2(xf.q, this.m_normals[i]); } } }; PolygonShape.prototype.testPoint = function(xf, p) { var pLocal = Rot.mulTVec2(xf.q, Vec2.sub(p, xf.p)); for (var i = 0; i < this.m_count; ++i) { var dot = Vec2.dot(this.m_normals[i], Vec2.sub(pLocal, this.m_vertices[i])); if (dot > 0) { return false; } } return true; }; PolygonShape.prototype.rayCast = function(output, input, xf, childIndex) { var p1 = Rot.mulTVec2(xf.q, Vec2.sub(input.p1, xf.p)); var p2 = Rot.mulTVec2(xf.q, Vec2.sub(input.p2, xf.p)); var d = Vec2.sub(p2, p1); var lower = 0; var upper = input.maxFraction; var index = -1; for (var i = 0; i < this.m_count; ++i) { var numerator = Vec2.dot(this.m_normals[i], Vec2.sub(this.m_vertices[i], p1)); var denominator = Vec2.dot(this.m_normals[i], d); if (denominator == 0) { if (numerator < 0) { return false; } } else { if (denominator < 0 && numerator < lower * denominator) { lower = numerator / denominator; index = i; } else if (denominator > 0 && numerator < upper * denominator) { upper = numerator / denominator; } } if (upper < lower) { return false; } } _ASSERT && common.assert(0 <= lower && lower <= input.maxFraction); if (index >= 0) { output.fraction = lower; output.normal = Rot.mulVec2(xf.q, this.m_normals[index]); return true; } return false; }; PolygonShape.prototype.computeAABB = function(aabb, xf, childIndex) { var minX = Infinity, minY = Infinity; var maxX = -Infinity, maxY = -Infinity; for (var i = 0; i < this.m_count; ++i) { var v = Transform.mulVec2(xf, this.m_vertices[i]); minX = Math.min(minX, v.x); maxX = Math.max(maxX, v.x); minY = Math.min(minY, v.y); maxY = Math.max(maxY, v.y); } aabb.lowerBound.set(minX, minY); aabb.upperBound.set(maxX, maxY); aabb.extend(this.m_radius); }; PolygonShape.prototype.computeMass = function(massData, density) { _ASSERT && common.assert(this.m_count >= 3); var center = Vec2.zero(); var area = 0; var I = 0; var s = Vec2.zero(); for (var i = 0; i < this.m_count; ++i) { s.add(this.m_vertices[i]); } s.mul(1 / this.m_count); var k_inv3 = 1 / 3; for (var i = 0; i < this.m_count; ++i) { var e1 = Vec2.sub(this.m_vertices[i], s); var e2 = i + 1 < this.m_count ? Vec2.sub(this.m_vertices[i + 1], s) : Vec2.sub(this.m_vertices[0], s); var D = Vec2.cross(e1, e2); var triangleArea = .5 * D; area += triangleArea; center.addCombine(triangleArea * k_inv3, e1, triangleArea * k_inv3, e2); var ex1 = e1.x; var ey1 = e1.y; var ex2 = e2.x; var ey2 = e2.y; var intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2; var inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2; I += .25 * k_inv3 * D * (intx2 + inty2); } massData.mass = density * area; _ASSERT && common.assert(area > Math.EPSILON); center.mul(1 / area); massData.center.setCombine(1, center, 1, s); massData.I = density * I; massData.I += massData.mass * (Vec2.dot(massData.center, massData.center) - Vec2.dot(center, center)); }; PolygonShape.prototype.validate = function() { for (var i = 0; i < this.m_count; ++i) { var i1 = i; var i2 = i < this.m_count - 1 ? i1 + 1 : 0; var p = this.m_vertices[i1]; var e = Vec2.sub(this.m_vertices[i2], p); for (var j = 0; j < this.m_count; ++j) { if (j == i1 || j == i2) { continue; } var v = Vec2.sub(this.m_vertices[j], p); var c = Vec2.cross(e, v); if (c < 0) { return false; } } } return true; }; PolygonShape.prototype.computeDistanceProxy = function(proxy) { proxy.m_vertices = this.m_vertices; proxy.m_count = this.m_count; proxy.m_radius = this.m_radius; }; },{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"../util/options":53}],49:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Pool; function Pool(opts) { var _queue = []; var _max = opts.max || Infinity; var _createFn = opts.create || function() { return {}; }; var _outFn = opts.allocate || function() {}; var _inFn = opts.release || function() {}; var _discardFn = opts.discard || function() {}; var _createCount = 0; var _outCount = 0; var _inCount = 0; var _discardCount = 0; this.max = function(n) { if (typeof n === "number") { _max = n; return this; } return _max; }; this.size = function() { return _queue.length; }; this.allocate = function() { var obj; if (_queue.length > 0) { obj = _queue.shift(); } else { _createCount++; obj = _createFn(); } _outCount++; _outFn(obj); return obj; }; this.release = function(obj) { if (_queue.length < _max) { _inCount++; _inFn(obj); _queue.push(obj); } else { _discardCount++; _discardFn(obj); } }; this.toString = function() { return " +" + _createCount + " >" + _outCount + " <" + _inCount + " -" + _discardCount + " =" + _queue.length + "/" + _max; }; } },{}],50:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports.now = function() { return Date.now(); }; module.exports.diff = function(time) { return Date.now() - time; }; },{}],51:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; exports.debug = function() { if (!_DEBUG) return; console.log.apply(console, arguments); }; exports.assert = function(statement, err, log) { if (!_ASSERT) return; if (statement) return; log && console.log(log); throw new Error(err); }; },{}],52:[function(require,module,exports){ if (typeof Object.create == "function") { module.exports = function(proto, props) { return Object.create.call(Object, proto, props); }; } else { module.exports = function(proto, props) { if (props) throw Error("Second argument is not supported!"); if (typeof proto !== "object" || proto === null) throw Error("Invalid prototype!"); noop.prototype = proto; return new noop(); }; function noop() {} } },{}],53:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var propIsEnumerable = Object.prototype.propertyIsEnumerable; module.exports = function(to, from) { if (to === null || typeof to === "undefined") { to = {}; } for (var key in from) { if (from.hasOwnProperty(key) && typeof to[key] === "undefined") { to[key] = from[key]; } } if (typeof Object.getOwnPropertySymbols === "function") { var symbols = Object.getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { var symbol = symbols[i]; if (from.propertyIsEnumerable(symbol) && typeof to[key] === "undefined") { to[symbol] = from[symbol]; } } } return to; }; },{}],54:[function(require,module,exports){ function _identity(x) { return x; }; var _cache = {}; var _modes = {}; var _easings = {}; function Easing(token) { if (typeof token === 'function') { return token; } if (typeof token !== 'string') { return _identity; } var fn = _cache[token]; if (fn) { return fn; } var match = /^(\w+)(-(in|out|in-out|out-in))?(\((.*)\))?$/i.exec(token); if (!match || !match.length) { return _identity; } var easing = _easings[match[1]]; var mode = _modes[match[3]]; var params = match[5]; if (easing && easing.fn) { fn = easing.fn; } else if (easing && easing.fc) { fn = easing.fc.apply(easing.fc, params && params.replace(/\s+/, '').split(',')); } else { fn = _identity; } if (mode) { fn = mode.fn(fn); } // TODO: It can be a memory leak with different `params`. _cache[token] = fn; return fn; }; Easing.add = function(data) { // TODO: create a map of all { name-mode : data } var names = (data.name || data.mode).split(/\s+/); for (var i = 0; i < names.length; i++) { var name = names[i]; if (name) { (data.name ? _easings : _modes)[name] = data; } } }; Easing.add({ mode : 'in', fn : function(f) { return f; } }); Easing.add({ mode : 'out', fn : function(f) { return function(t) { return 1 - f(1 - t); }; } }); Easing.add({ mode : 'in-out', fn : function(f) { return function(t) { return (t < 0.5) ? (f(2 * t) / 2) : (1 - f(2 * (1 - t)) / 2); }; } }); Easing.add({ mode : 'out-in', fn : function(f) { return function(t) { return (t < 0.5) ? (1 - f(2 * (1 - t)) / 2) : (f(2 * t) / 2); }; } }); Easing.add({ name : 'linear', fn : function(t) { return t; } }); Easing.add({ name : 'quad', fn : function(t) { return t * t; } }); Easing.add({ name : 'cubic', fn : function(t) { return t * t * t; } }); Easing.add({ name : 'quart', fn : function(t) { return t * t * t * t; } }); Easing.add({ name : 'quint', fn : function(t) { return t * t * t * t * t; } }); Easing.add({ name : 'sin sine', fn : function(t) { return 1 - Math.cos(t * Math.PI / 2); } }); Easing.add({ name : 'exp expo', fn : function(t) { return t == 0 ? 0 : Math.pow(2, 10 * (t - 1)); } }); Easing.add({ name : 'circle circ', fn : function(t) { return 1 - Math.sqrt(1 - t * t); } }); Easing.add({ name : 'bounce', fn : function(t) { return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375; } }); Easing.add({ name : 'poly', fc : function(e) { return function(t) { return Math.pow(t, e); }; } }); Easing.add({ name : 'elastic', fc : function(a, p) { p = p || 0.45; a = a || 1; var s = p / (2 * Math.PI) * Math.asin(1 / a); return function(t) { return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p); }; } }); Easing.add({ name : 'back', fc : function(s) { s = typeof s !== 'undefined' ? s : 1.70158; return function(t) { return t * t * ((s + 1) * t - s); }; } }); module.exports = Easing; },{}],55:[function(require,module,exports){ if (typeof DEBUG === 'undefined') DEBUG = true; require('../core')._load(function(stage, elem) { Mouse.subscribe(stage, elem); }); // TODO: capture mouse Mouse.CLICK = 'click'; Mouse.START = 'touchstart mousedown'; Mouse.MOVE = 'touchmove mousemove'; Mouse.END = 'touchend mouseup'; Mouse.CANCEL = 'touchcancel mousecancel'; Mouse.subscribe = function(stage, elem) { if (stage.mouse) { return; } stage.mouse = new Mouse(stage, elem); // `click` events are synthesized from start/end events on same nodes // `mousecancel` events are synthesized on blur or mouseup outside element elem.addEventListener('touchstart', handleStart); elem.addEventListener('touchend', handleEnd); elem.addEventListener('touchmove', handleMove); elem.addEventListener('touchcancel', handleCancel); elem.addEventListener('mousedown', handleStart); elem.addEventListener('mouseup', handleEnd); elem.addEventListener('mousemove', handleMove); document.addEventListener('mouseup', handleCancel); window.addEventListener("blur", handleCancel); var clicklist = [], cancellist = []; function handleStart(event) { event.preventDefault(); stage.mouse.locate(event); // DEBUG && console.log('Mouse Start: ' + event.type + ' ' + mouse); stage.mouse.publish(event.type, event); stage.mouse.lookup('click', clicklist); stage.mouse.lookup('mousecancel', cancellist); } function handleMove(event) { event.preventDefault(); stage.mouse.locate(event); stage.mouse.publish(event.type, event); } function handleEnd(event) { event.preventDefault(); // up/end location is not available, last one is used instead // DEBUG && console.log('Mouse End: ' + event.type + ' ' + mouse); stage.mouse.publish(event.type, event); if (clicklist.length) { // DEBUG && console.log('Mouse Click: ' + clicklist.length); stage.mouse.publish('click', event, clicklist); } cancellist.length = 0; } function handleCancel(event) { if (cancellist.length) { // DEBUG && console.log('Mouse Cancel: ' + event.type); stage.mouse.publish('mousecancel', event, cancellist); } clicklist.length = 0; } }; function Mouse(stage, elem) { if (!(this instanceof Mouse)) { // old-style mouse subscription return; } var ratio = stage.viewport().ratio || 1; stage.on('viewport', function(size) { ratio = size.ratio || ratio; }); this.x = 0; this.y = 0; this.toString = function() { return (this.x | 0) + 'x' + (this.y | 0); }; this.locate = function(event) { locateElevent(elem, event, this); this.x *= ratio; this.y *= ratio; }; this.lookup = function(type, collect) { this.type = type; this.root = stage; this.event = null; collect.length = 0; this.collect = collect; this.root.visit(this.visitor, this); }; this.publish = function(type, event, targets) { this.type = type; this.root = stage; this.event = event; this.collect = false; this.timeStamp = Date.now(); if (type !== 'mousemove' && type !== 'touchmove') { DEBUG && console.log(this.type + ' ' + this); } if (targets) { while (targets.length) if (this.visitor.end(targets.shift(), this)) break; targets.length = 0; } else { this.root.visit(this.visitor, this); } }; this.visitor = { reverse : true, visible : true, start : function(node, mouse) { return !node._flag(mouse.type); }, end : function(node, mouse) { // mouse: event/collect, type, root rel.raw = mouse.event; rel.type = mouse.type; rel.timeStamp = mouse.timeStamp; rel.abs.x = mouse.x; rel.abs.y = mouse.y; var listeners = node.listeners(mouse.type); if (!listeners) { return; } node.matrix().inverse().map(mouse, rel); if (!(node === mouse.root || node.hitTest(rel))) { return; } if (mouse.collect) { mouse.collect.push(node); } if (mouse.event) { var cancel = false; for (var l = 0; l < listeners.length; l++) { cancel = listeners[l].call(node, rel) ? true : cancel; } return cancel; } } }; }; // TODO: define per mouse object with get-only x and y var rel = {}, abs = {}; defineValue(rel, 'clone', function(obj) { obj = obj || {}, obj.x = this.x, obj.y = this.y; return obj; }); defineValue(rel, 'toString', function() { return (this.x | 0) + 'x' + (this.y | 0) + ' (' + this.abs + ')'; }); defineValue(rel, 'abs', abs); defineValue(abs, 'clone', function(obj) { obj = obj || {}, obj.x = this.x, obj.y = this.y; return obj; }); defineValue(abs, 'toString', function() { return (this.x | 0) + 'x' + (this.y | 0); }); function defineValue(obj, name, value) { Object.defineProperty(obj, name, { value : value }); } function locateElevent(el, ev, loc) { // pageX/Y if available? if (ev.touches && ev.touches.length) { loc.x = ev.touches[0].clientX; loc.y = ev.touches[0].clientY; } else { loc.x = ev.clientX; loc.y = ev.clientY; } var rect = el.getBoundingClientRect(); loc.x -= rect.left; loc.y -= rect.top; loc.x -= el.clientLeft | 0; loc.y -= el.clientTop | 0; return loc; }; module.exports = Mouse; },{"../core":60}],56:[function(require,module,exports){ var Easing = require('./easing'); var Class = require('../core'); var Pin = require('../pin'); Class.prototype.tween = function(duration, delay, append) { if (typeof duration !== 'number') { append = duration, delay = 0, duration = 0; } else if (typeof delay !== 'number') { append = delay, delay = 0; } if (!this._tweens) { this._tweens = []; var ticktime = 0; this.tick(function(elapsed, now, last) { if (!this._tweens.length) { return; } // ignore old elapsed var ignore = ticktime != last; ticktime = now; if (ignore) { return true; } var head = this._tweens[0]; var next = head.tick(this, elapsed, now, last); if (next && head === this._tweens[0]) { this._tweens.shift(); } if (typeof next === 'function') { try { next.call(this); } catch (e) { console.log(e); } } if (typeof next === 'object') { this._tweens.unshift(next); } return true; }, true); } this.touch(); if (!append) { this._tweens.length = 0; } var tween = new Tween(this, duration, delay); this._tweens.push(tween); return tween; }; function Tween(owner, duration, delay) { this._end = {}; this._duration = duration || 400; this._delay = delay || 0; this._owner = owner; this._time = 0; }; Tween.prototype.tick = function(node, elapsed, now, last) { this._time += elapsed; if (this._time < this._delay) { return; } var time = this._time - this._delay; if (!this._start) { this._start = {}; for ( var key in this._end) { this._start[key] = this._owner.pin(key); } } var p, over; if (time < this._duration) { p = time / this._duration; over = false; } else { p = 1; over = true; } if (typeof this._easing == 'function') { p = this._easing(p); } var q = 1 - p; for ( var key in this._end) { this._owner.pin(key, this._start[key] * q + this._end[key] * p); } if (over) { return this._next || this._done || true; } }; Tween.prototype.tween = function(duration, delay) { return this._next = new Tween(this._owner, duration, delay); }; Tween.prototype.duration = function(duration) { this._duration = duration; return this; }; Tween.prototype.delay = function(delay) { this._delay = delay; return this; }; Tween.prototype.ease = function(easing) { this._easing = Easing(easing); return this; }; Tween.prototype.done = function(fn) { this._done = fn; return this; }; Tween.prototype.hide = function() { this.done(function() { this.hide(); }); return this; }; Tween.prototype.remove = function() { this.done(function() { this.remove(); }); return this; }; Tween.prototype.pin = function(a, b) { if (typeof a === 'object') { for ( var attr in a) { pinning(this._owner, this._end, attr, a[attr]); } } else if (typeof b !== 'undefined') { pinning(this._owner, this._end, a, b); } return this; }; function pinning(node, map, key, value) { if (typeof node.pin(key) === 'number') { map[key] = value; } else if (typeof node.pin(key + 'X') === 'number' && typeof node.pin(key + 'Y') === 'number') { map[key + 'X'] = value; map[key + 'Y'] = value; } } Pin._add_shortcuts(Tween); /** * @deprecated Use .done(fn) instead. */ Tween.prototype.then = function(fn) { this.done(fn); return this; }; /** * @deprecated NOOP */ Tween.prototype.clear = function(forward) { return this; }; module.exports = Tween; },{"../core":60,"../pin":68,"./easing":54}],57:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var create = require('./util/create'); var math = require('./util/math'); Class.anim = function(frames, fps) { var anim = new Anim(); anim.frames(frames).gotoFrame(0); fps && anim.fps(fps); return anim; }; Anim._super = Class; Anim.prototype = create(Anim._super.prototype); // TODO: replace with atlas fps or texture time Class.Anim = { FPS : 15 }; function Anim() { Anim._super.call(this); this.label('Anim'); this._textures = []; this._fps = Class.Anim.FPS; this._ft = 1000 / this._fps; this._time = -1; this._repeat = 0; this._index = 0; this._frames = []; var lastTime = 0; this.tick(function(t, now, last) { if (this._time < 0 || this._frames.length <= 1) { return; } // ignore old elapsed var ignore = lastTime != last; lastTime = now; if (ignore) { return true; } this._time += t; if (this._time < this._ft) { return true; } var n = this._time / this._ft | 0; this._time -= n * this._ft; this.moveFrame(n); if (this._repeat > 0 && (this._repeat -= n) <= 0) { this.stop(); this._callback && this._callback(); return false; } return true; }, false); }; Anim.prototype.fps = function(fps) { if (typeof fps === 'undefined') { return this._fps; } this._fps = fps > 0 ? fps : Class.Anim.FPS; this._ft = 1000 / this._fps; return this; }; /** * @deprecated Use frames */ Anim.prototype.setFrames = function(a, b, c) { return this.frames(a, b, c); }; Anim.prototype.frames = function(frames) { this._index = 0; this._frames = Class.texture(frames).array(); this.touch(); return this; }; Anim.prototype.length = function() { return this._frames ? this._frames.length : 0; }; Anim.prototype.gotoFrame = function(frame, resize) { this._index = math.rotate(frame, this._frames.length) | 0; resize = resize || !this._textures[0]; this._textures[0] = this._frames[this._index]; if (resize) { this.pin('width', this._textures[0].width); this.pin('height', this._textures[0].height); } this.touch(); return this; }; Anim.prototype.moveFrame = function(move) { return this.gotoFrame(this._index + move); }; Anim.prototype.repeat = function(repeat, callback) { this._repeat = repeat * this._frames.length - 1; this._callback = callback; this.play(); return this; }; Anim.prototype.play = function(frame) { if (typeof frame !== 'undefined') { this.gotoFrame(frame); this._time = 0; } else if (this._time < 0) { this._time = 0; } this.touch(); return this; }; Anim.prototype.stop = function(frame) { this._time = -1; if (typeof frame !== 'undefined') { this.gotoFrame(frame); } return this; }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/math":78}],58:[function(require,module,exports){ if (typeof DEBUG === 'undefined') DEBUG = true; var Class = require('./core'); var Texture = require('./texture'); var extend = require('./util/extend'); var create = require('./util/create'); var is = require('./util/is'); var string = require('./util/string'); // name : atlas var _atlases_map = {}; // [atlas] var _atlases_arr = []; // TODO: print subquery not found error // TODO: index textures Class.atlas = function(def) { var atlas = is.fn(def.draw) ? def : new Atlas(def); if (def.name) { _atlases_map[def.name] = atlas; } _atlases_arr.push(atlas); deprecated(def, 'imagePath'); deprecated(def, 'imageRatio'); var url = def.imagePath; var ratio = def.imageRatio || 1; if (is.string(def.image)) { url = def.image; } else if (is.hash(def.image)) { url = def.image.src || def.image.url; ratio = def.image.ratio || ratio; } url && Class.preload(function(done) { url = Class.resolve(url); DEBUG && console.log('Loading atlas: ' + url); var imageloader = Class.config('image-loader'); imageloader(url, function(image) { DEBUG && console.log('Image loaded: ' + url); atlas.src(image, ratio); done(); }, function(err) { DEBUG && console.log('Error loading atlas: ' + url, err); done(); }); }); return atlas; }; Atlas._super = Texture; Atlas.prototype = create(Atlas._super.prototype); function Atlas(def) { Atlas._super.call(this); var atlas = this; deprecated(def, 'filter'); deprecated(def, 'cutouts'); deprecated(def, 'sprites'); deprecated(def, 'factory'); var map = def.map || def.filter; var ppu = def.ppu || def.ratio || 1; var trim = def.trim || 0; var textures = def.textures; var factory = def.factory; var cutouts = def.cutouts || def.sprites; function make(def) { if (!def || is.fn(def.draw)) { return def; } def = extend({}, def); if (is.fn(map)) { def = map(def); } if (ppu != 1) { def.x *= ppu, def.y *= ppu; def.width *= ppu, def.height *= ppu; def.top *= ppu, def.bottom *= ppu; def.left *= ppu, def.right *= ppu; } if (trim != 0) { def.x += trim, def.y += trim; def.width -= 2 * trim, def.height -= 2 * trim; def.top -= trim, def.bottom -= trim; def.left -= trim, def.right -= trim; } var texture = atlas.pipe(); texture.top = def.top, texture.bottom = def.bottom; texture.left = def.left, texture.right = def.right; texture.src(def.x, def.y, def.width, def.height); return texture; } function find(query) { if (textures) { if (is.fn(textures)) { return textures(query); } else if (is.hash(textures)) { return textures[query]; } } if (cutouts) { // deprecated var result = null, n = 0; for (var i = 0; i < cutouts.length; i++) { if (string.startsWith(cutouts[i].name, query)) { if (n === 0) { result = cutouts[i]; } else if (n === 1) { result = [ result, cutouts[i] ]; } else { result.push(cutouts[i]); } n++; } } if (n === 0 && is.fn(factory)) { result = function(subquery) { return factory(query + (subquery ? subquery : '')); }; } return result; } } this.select = function(query) { if (!query) { // TODO: if `textures` is texture def, map or fn? return new Selection(this.pipe()); } var found = find(query); if (found) { return new Selection(found, find, make); } }; }; var nfTexture = new Texture(); nfTexture.x = nfTexture.y = nfTexture.width = nfTexture.height = 0; nfTexture.pipe = nfTexture.src = nfTexture.dest = function() { return this; }; nfTexture.draw = function() { }; var nfSelection = new Selection(nfTexture); function Selection(result, find, make) { function link(result, subquery) { if (!result) { return nfTexture; } else if (is.fn(result.draw)) { return result; } else if (is.hash(result) && is.number(result.width) && is.number(result.height) && is.fn(make)) { return make(result); } else if (is.hash(result) && is.defined(subquery)) { return link(result[subquery]); } else if (is.fn(result)) { return link(result(subquery)); } else if (is.array(result)) { return link(result[0]); } else if (is.string(result) && is.fn(find)) { return link(find(result)); } } this.one = function(subquery) { return link(result, subquery); }; this.array = function(arr) { var array = is.array(arr) ? arr : []; if (is.array(result)) { for (var i = 0; i < result.length; i++) { array[i] = link(result[i]); } } else { array[0] = link(result); } return array; }; } Class.texture = function(query) { if (!is.string(query)) { return new Selection(query); } var result = null, atlas, i; if ((i = query.indexOf(':')) > 0 && query.length > i + 1) { atlas = _atlases_map[query.slice(0, i)]; result = atlas && atlas.select(query.slice(i + 1)); } if (!result && (atlas = _atlases_map[query])) { result = atlas.select(); } for (i = 0; !result && i < _atlases_arr.length; i++) { result = _atlases_arr[i].select(query); } if (!result) { console.error('Texture not found: ' + query); result = nfSelection; } return result; }; function deprecated(hash, name, msg) { if (name in hash) console.log(msg ? msg.replace('%name', name) : '\'' + name + '\' field of texture atlas is deprecated.'); }; module.exports = Atlas; },{"./core":60,"./texture":71,"./util/create":74,"./util/extend":76,"./util/is":77,"./util/string":81}],59:[function(require,module,exports){ var Class = require('./core'); var Texture = require('./texture'); Class.canvas = function(type, attributes, callback) { if (typeof type === 'string') { if (typeof attributes === 'object') { } else { if (typeof attributes === 'function') { callback = attributes; } attributes = {}; } } else { if (typeof type === 'function') { callback = type; } attributes = {}; type = '2d'; } var canvas = document.createElement('canvas'); var context = canvas.getContext(type, attributes); var texture = new Texture(canvas); texture.context = function() { return context; }; texture.size = function(width, height, ratio) { ratio = ratio || 1; canvas.width = width * ratio; canvas.height = height * ratio; this.src(canvas, ratio); return this; }; texture.canvas = function(fn) { if (typeof fn === 'function') { fn.call(this, context); } else if (typeof fn === 'undefined' && typeof callback === 'function') { callback.call(this, context); } return this; }; if (typeof callback === 'function') { callback.call(texture, context); } return texture; }; },{"./core":60,"./texture":71}],60:[function(require,module,exports){ if (typeof DEBUG === 'undefined') DEBUG = true; var stats = require('./util/stats'); var extend = require('./util/extend'); var is = require('./util/is'); var _await = require('./util/await'); stats.create = 0; function Class(arg) { if (!(this instanceof Class)) { if (is.fn(arg)) { return Class.app.apply(Class, arguments); } else if (is.object(arg)) { return Class.atlas.apply(Class, arguments); } else { return arg; } } stats.create++; for (var i = 0; i < _init.length; i++) { _init[i].call(this); } } var _init = []; Class._init = function(fn) { _init.push(fn); }; var _load = []; Class._load = function(fn) { _load.push(fn); }; var _config = {}; Class.config = function() { if (arguments.length === 1 && is.string(arguments[0])) { return _config[arguments[0]]; } if (arguments.length === 1 && is.object(arguments[0])) { extend(_config, arguments[0]); } if (arguments.length === 2 && is.string(arguments[0])) { _config[arguments[0], arguments[1]]; } }; var _app_queue = []; var _preload_queue = []; var _stages = []; var _loaded = false; var _paused = false; Class.app = function(app, opts) { if (!_loaded) { _app_queue.push(arguments); return; } DEBUG && console.log('Creating app...'); var loader = Class.config('app-loader'); loader(function(stage, canvas) { DEBUG && console.log('Initing app...'); for (var i = 0; i < _load.length; i++) { _load[i].call(this, stage, canvas); } app(stage, canvas); _stages.push(stage); DEBUG && console.log('Starting app...'); stage.start(); }, opts); }; var loading = _await(); Class.preload = function(load) { if (typeof load === 'string') { var url = Class.resolve(load); if (/\.js($|\?|\#)/.test(url)) { DEBUG && console.log('Loading script: ' + url); load = function(callback) { loadScript(url, callback); }; } } if (typeof load !== 'function') { return; } // if (!_started) { // _preload_queue.push(load); // return; // } load(loading()); }; Class.start = function(config) { DEBUG && console.log('Starting...'); Class.config(config); // DEBUG && console.log('Preloading...'); // _started = true; // while (_preload_queue.length) { // var load = _preload_queue.shift(); // load(loading()); // } loading.then(function() { DEBUG && console.log('Loading apps...'); _loaded = true; while (_app_queue.length) { var args = _app_queue.shift(); Class.app.apply(Class, args); } }); }; Class.pause = function() { if (!_paused) { _paused = true; for (var i = _stages.length - 1; i >= 0; i--) { _stages[i].pause(); } } }; Class.resume = function() { if (_paused) { _paused = false; for (var i = _stages.length - 1; i >= 0; i--) { _stages[i].resume(); } } }; Class.create = function() { return new Class(); }; Class.resolve = (function() { if (typeof window === 'undefined' || typeof document === 'undefined') { return function(url) { return url; }; } var scripts = document.getElementsByTagName('script'); function getScriptSrc() { // HTML5 if (document.currentScript) { return document.currentScript.src; } // IE>=10 var stack; try { var err = new Error(); if (err.stack) { stack = err.stack; } else { throw err; } } catch (err) { stack = err.stack; } if (typeof stack === 'string') { stack = stack.split('\n'); // Uses the last line, where the call started for (var i = stack.length; i--;) { var url = stack[i].match(/(\w+\:\/\/[^/]*?\/.+?)(:\d+)(:\d+)?/); if (url) { return url[1]; } } } // IE<11 if (scripts.length && 'readyState' in scripts[0]) { for (var i = scripts.length; i--;) { if (scripts[i].readyState === 'interactive') { return scripts[i].src; } } } return location.href; } return function(url) { if (/^\.\//.test(url)) { var src = getScriptSrc(); var base = src.substring(0, src.lastIndexOf('/') + 1); url = base + url.substring(2); // } else if (/^\.\.\//.test(url)) { // url = base + url; } return url; }; })(); module.exports = Class; function loadScript(src, callback) { var el = document.createElement('script'); el.addEventListener('load', function() { callback(); }); el.addEventListener('error', function(err) { callback(err || 'Error loading script: ' + src); }); el.src = src; el.id = 'preload-' + Date.now(); document.body.appendChild(el); }; },{"./util/await":73,"./util/extend":76,"./util/is":77,"./util/stats":80}],61:[function(require,module,exports){ require('./util/event')(require('./core').prototype, function(obj, name, on) { obj._flag(name, on); }); },{"./core":60,"./util/event":75}],62:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var repeat = require('./util/repeat'); var create = require('./util/create'); module.exports = Image; Class.image = function(image) { var img = new Image(); image && img.image(image); return img; }; Image._super = Class; Image.prototype = create(Image._super.prototype); function Image() { Image._super.call(this); this.label('Image'); this._textures = []; this._image = null; }; /** * @deprecated Use image */ Image.prototype.setImage = function(a, b, c) { return this.image(a, b, c); }; Image.prototype.image = function(image) { this._image = Class.texture(image).one(); this.pin('width', this._image ? this._image.width : 0); this.pin('height', this._image ? this._image.height : 0); this._textures[0] = this._image.pipe(); this._textures.length = 1; return this; }; Image.prototype.tile = function(inner) { this._repeat(false, inner); return this; }; Image.prototype.stretch = function(inner) { this._repeat(true, inner); return this; }; Image.prototype._repeat = function(stretch, inner) { var self = this; this.untick(this._repeatTicker); this.tick(this._repeatTicker = function() { if (this._mo_stretch == this._pin._ts_transform) { return; } this._mo_stretch = this._pin._ts_transform; var width = this.pin('width'); var height = this.pin('height'); this._textures.length = repeat(this._image, width, height, stretch, inner, insert); }); function insert(i, sx, sy, sw, sh, dx, dy, dw, dh) { var repeat = self._textures.length > i ? self._textures[i] : self._textures[i] = self._image.pipe(); repeat.src(sx, sy, sw, sh); repeat.dest(dx, dy, dw, dh); } }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/repeat":79}],63:[function(require,module,exports){ module.exports = require('./core'); module.exports.Matrix = require('./matrix'); module.exports.Texture = require('./texture'); require('./atlas'); require('./tree'); require('./event'); require('./pin'); require('./loop'); require('./root'); },{"./atlas":58,"./core":60,"./event":61,"./loop":66,"./matrix":67,"./pin":68,"./root":69,"./texture":71,"./tree":72}],64:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var create = require('./util/create'); Class.row = function(align) { return Class.create().row(align).label('Row'); }; Class.prototype.row = function(align) { this.sequence('row', align); return this; }; Class.column = function(align) { return Class.create().column(align).label('Row'); }; Class.prototype.column = function(align) { this.sequence('column', align); return this; }; Class.sequence = function(type, align) { return Class.create().sequence(type, align).label('Sequence'); }; Class.prototype.sequence = function(type, align) { this._padding = this._padding || 0; this._spacing = this._spacing || 0; this.untick(this._layoutTiker); this.tick(this._layoutTiker = function() { if (this._mo_seq == this._ts_touch) { return; } this._mo_seq = this._ts_touch; var alignChildren = (this._mo_seqAlign != this._ts_children); this._mo_seqAlign = this._ts_children; var width = 0, height = 0; var child, next = this.first(true); var first = true; while (child = next) { next = child.next(true); child.matrix(true); var w = child.pin('boxWidth'); var h = child.pin('boxHeight'); if (type == 'column') { !first && (height += this._spacing); child.pin('offsetY') != height && child.pin('offsetY', height); width = Math.max(width, w); height = height + h; alignChildren && child.pin('alignX', align); } else if (type == 'row') { !first && (width += this._spacing); child.pin('offsetX') != width && child.pin('offsetX', width); width = width + w; height = Math.max(height, h); alignChildren && child.pin('alignY', align); } first = false; } width += 2 * this._padding; height += 2 * this._padding; this.pin('width') != width && this.pin('width', width); this.pin('height') != height && this.pin('height', height); }); return this; }; Class.box = function() { return Class.create().box().label('Box'); }; Class.prototype.box = function() { this._padding = this._padding || 0; this.untick(this._layoutTiker); this.tick(this._layoutTiker = function() { if (this._mo_box == this._ts_touch) { return; } this._mo_box = this._ts_touch; var width = 0, height = 0; var child, next = this.first(true); while (child = next) { next = child.next(true); child.matrix(true); var w = child.pin('boxWidth'); var h = child.pin('boxHeight'); width = Math.max(width, w); height = Math.max(height, h); } width += 2 * this._padding; height += 2 * this._padding; this.pin('width') != width && this.pin('width', width); this.pin('height') != height && this.pin('height', height); }); return this; }; Class.layer = function() { return Class.create().layer().label('Layer'); }; Class.prototype.layer = function() { this.untick(this._layoutTiker); this.tick(this._layoutTiker = function() { var parent = this.parent(); if (parent) { var width = parent.pin('width'); if (this.pin('width') != width) { this.pin('width', width); } var height = parent.pin('height'); if (this.pin('height') != height) { this.pin('height', height); } } }, true); return this; }; // TODO: move padding to pin Class.prototype.padding = function(pad) { this._padding = pad; return this; }; Class.prototype.spacing = function(space) { this._spacing = space; return this; }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74}],65:[function(require,module,exports){ /** * Default loader for web. */ if (typeof DEBUG === 'undefined') DEBUG = true; var Class = require('../core'); Class._supported = (function() { var elem = document.createElement('canvas'); return (elem.getContext && elem.getContext('2d')) ? true : false; })(); window.addEventListener('load', function() { DEBUG && console.log('On load.'); if (Class._supported) { Class.start(); } // TODO if not supported }, false); Class.config({ 'app-loader' : AppLoader, 'image-loader' : ImageLoader }); function AppLoader(app, configs) { configs = configs || {}; var canvas = configs.canvas, context = null, full = false; var width = 0, height = 0, ratio = 1; if (typeof canvas === 'string') { canvas = document.getElementById(canvas); } if (!canvas) { canvas = document.getElementById('cutjs') || document.getElementById('stage'); } if (!canvas) { full = true; DEBUG && console.log('Creating Canvas...'); canvas = document.createElement('canvas'); canvas.style.position = 'absolute'; canvas.style.top = '0'; canvas.style.left = '0'; var body = document.body; body.insertBefore(canvas, body.firstChild); } context = canvas.getContext('2d'); var devicePixelRatio = window.devicePixelRatio || 1; var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; ratio = devicePixelRatio / backingStoreRatio; var requestAnimationFrame = window.requestAnimationFrame || window.msRequestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.oRequestAnimationFrame || function(callback) { return window.setTimeout(callback, 1000 / 60); }; DEBUG && console.log('Creating stage...'); var root = Class.root(requestAnimationFrame, render); function render() { context.setTransform(1, 0, 0, 1, 0, 0); context.clearRect(0, 0, width, height); root.render(context); } root.background = function(color) { canvas.style.backgroundColor = color; return this; }; app(root, canvas); resize(); window.addEventListener('resize', resize, false); window.addEventListener('orientationchange', resize, false); function resize() { if (full) { // screen.availWidth/Height? width = (window.innerWidth > 0 ? window.innerWidth : screen.width); height = (window.innerHeight > 0 ? window.innerHeight : screen.height); canvas.style.width = width + 'px'; canvas.style.height = height + 'px'; } else { width = canvas.clientWidth; height = canvas.clientHeight; } width *= ratio; height *= ratio; if (canvas.width === width && canvas.height === height) { return; } canvas.width = width; canvas.height = height; DEBUG && console.log('Resize: ' + width + ' x ' + height + ' / ' + ratio); root.viewport(width, height, ratio); render(); } } function ImageLoader(src, success, error) { DEBUG && console.log('Loading image: ' + src); var image = new Image(); image.onload = function() { success(image); }; image.onerror = error; image.src = src; } },{"../core":60}],66:[function(require,module,exports){ var Class = require('./core'); require('./pin'); var stats = require('./util/stats'); Class.prototype._textures = null; Class.prototype._alpha = 1; Class.prototype.render = function(context) { if (!this._visible) { return; } stats.node++; var m = this.matrix(); context.setTransform(m.a, m.b, m.c, m.d, m.e, m.f); // move this elsewhere! this._alpha = this._pin._alpha * (this._parent ? this._parent._alpha : 1); var alpha = this._pin._textureAlpha * this._alpha; if (context.globalAlpha != alpha) { context.globalAlpha = alpha; } if (this._textures !== null) { for (var i = 0, n = this._textures.length; i < n; i++) { this._textures[i].draw(context); } } if (context.globalAlpha != this._alpha) { context.globalAlpha = this._alpha; } var child, next = this._first; while (child = next) { next = child._next; child.render(context); } }; Class.prototype._tickBefore = null; Class.prototype._tickAfter = null; Class.prototype.MAX_ELAPSE = Infinity; Class.prototype._tick = function(elapsed, now, last) { if (!this._visible) { return; } if (elapsed > this.MAX_ELAPSE) { elapsed = this.MAX_ELAPSE; } var ticked = false; if (this._tickBefore !== null) { for (var i = 0; i < this._tickBefore.length; i++) { stats.tick++; var tickFn = this._tickBefore[i]; ticked = tickFn.call(this, elapsed, now, last) === true || ticked; } } var child, next = this._first; while (child = next) { next = child._next; if (child._flag('_tick')) { ticked = child._tick(elapsed, now, last) === true ? true : ticked; } } if (this._tickAfter !== null) { for (var i = 0; i < this._tickAfter.length; i++) { stats.tick++; var tickFn = this._tickAfter[i]; ticked = tickFn.call(this, elapsed, now, last) === true || ticked; } } return ticked; }; Class.prototype.tick = function(ticker, before) { if (typeof ticker !== 'function') { return; } if (before) { if (this._tickBefore === null) { this._tickBefore = []; } this._tickBefore.push(ticker); } else { if (this._tickAfter === null) { this._tickAfter = []; } this._tickAfter.push(ticker); } this._flag('_tick', this._tickAfter !== null && this._tickAfter.length > 0 || this._tickBefore !== null && this._tickBefore.length > 0); }; Class.prototype.untick = function(ticker) { if (typeof ticker !== 'function') { return; } var i; if (this._tickBefore !== null && (i = this._tickBefore.indexOf(ticker)) >= 0) { this._tickBefore.splice(i, 1); } if (this._tickAfter !== null && (i = this._tickAfter.indexOf(ticker)) >= 0) { this._tickAfter.splice(i, 1); } }; Class.prototype.timeout = function(fn, time) { this.setTimeout(fn, time); }; Class.prototype.setTimeout = function(fn, time) { function timer(t) { if ((time -= t) < 0) { this.untick(timer); fn.call(this); } else { return true; } } this.tick(timer); return timer; }; Class.prototype.clearTimeout = function(timer) { this.untick(timer); }; },{"./core":60,"./pin":68,"./util/stats":80}],67:[function(require,module,exports){ function Matrix(a, b, c, d, e, f) { this.reset(a, b, c, d, e, f); }; Matrix.prototype.toString = function() { return '[' + this.a + ', ' + this.b + ', ' + this.c + ', ' + this.d + ', ' + this.e + ', ' + this.f + ']'; }; Matrix.prototype.clone = function() { return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f); }; Matrix.prototype.reset = function(a, b, c, d, e, f) { this._dirty = true; if (typeof a === 'object') { this.a = a.a, this.d = a.d; this.b = a.b, this.c = a.c; this.e = a.e, this.f = a.f; } else { this.a = a || 1, this.d = d || 1; this.b = b || 0, this.c = c || 0; this.e = e || 0, this.f = f || 0; } return this; }; Matrix.prototype.identity = function() { this._dirty = true; this.a = 1; this.b = 0; this.c = 0; this.d = 1; this.e = 0; this.f = 0; return this; }; Matrix.prototype.rotate = function(angle) { if (!angle) { return this; } this._dirty = true; var u = angle ? Math.cos(angle) : 1; // android bug may give bad 0 values var v = angle ? Math.sin(angle) : 0; var a = u * this.a - v * this.b; var b = u * this.b + v * this.a; var c = u * this.c - v * this.d; var d = u * this.d + v * this.c; var e = u * this.e - v * this.f; var f = u * this.f + v * this.e; this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; this.f = f; return this; }; Matrix.prototype.translate = function(x, y) { if (!x && !y) { return this; } this._dirty = true; this.e += x; this.f += y; return this; }; Matrix.prototype.scale = function(x, y) { if (!(x - 1) && !(y - 1)) { return this; } this._dirty = true; this.a *= x; this.b *= y; this.c *= x; this.d *= y; this.e *= x; this.f *= y; return this; }; Matrix.prototype.skew = function(x, y) { if (!x && !y) { return this; } this._dirty = true; var a = this.a + this.b * x; var b = this.b + this.a * y; var c = this.c + this.d * x; var d = this.d + this.c * y; var e = this.e + this.f * x; var f = this.f + this.e * y; this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; this.f = f; return this; }; Matrix.prototype.concat = function(m) { this._dirty = true; var n = this; var a = n.a * m.a + n.b * m.c; var b = n.b * m.d + n.a * m.b; var c = n.c * m.a + n.d * m.c; var d = n.d * m.d + n.c * m.b; var e = n.e * m.a + m.e + n.f * m.c; var f = n.f * m.d + m.f + n.e * m.b; this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; this.f = f; return this; }; Matrix.prototype.inverse = Matrix.prototype.reverse = function() { if (this._dirty) { this._dirty = false; this.inversed = this.inversed || new Matrix(); var z = this.a * this.d - this.b * this.c; this.inversed.a = this.d / z; this.inversed.b = -this.b / z; this.inversed.c = -this.c / z; this.inversed.d = this.a / z; this.inversed.e = (this.c * this.f - this.e * this.d) / z; this.inversed.f = (this.e * this.b - this.a * this.f) / z; } return this.inversed; }; Matrix.prototype.map = function(p, q) { q = q || {}; q.x = this.a * p.x + this.c * p.y + this.e; q.y = this.b * p.x + this.d * p.y + this.f; return q; }; Matrix.prototype.mapX = function(x, y) { if (typeof x === 'object') y = x.y, x = x.x; return this.a * x + this.c * y + this.e; }; Matrix.prototype.mapY = function(x, y) { if (typeof x === 'object') y = x.y, x = x.x; return this.b * x + this.d * y + this.f; }; module.exports = Matrix; },{}],68:[function(require,module,exports){ var Class = require('./core'); var Matrix = require('./matrix'); var iid = 0; Class._init(function() { this._pin = new Pin(this); }); Class.prototype.matrix = function(relative) { if (relative === true) { return this._pin.relativeMatrix(); } return this._pin.absoluteMatrix(); }; Class.prototype.pin = function(a, b) { if (typeof a === 'object') { this._pin.set(a); return this; } else if (typeof a === 'string') { if (typeof b === 'undefined') { return this._pin.get(a); } else { this._pin.set(a, b); return this; } } else if (typeof a === 'undefined') { return this._pin; } }; function Pin(owner) { this._owner = owner; this._parent = null; // relative to parent this._relativeMatrix = new Matrix(); // relative to stage this._absoluteMatrix = new Matrix(); this.reset(); }; Pin.prototype.reset = function() { this._textureAlpha = 1; this._alpha = 1; this._width = 0; this._height = 0; this._scaleX = 1; this._scaleY = 1; this._skewX = 0; this._skewY = 0; this._rotation = 0; // scale/skew/rotate center this._pivoted = false; this._pivotX = null; this._pivotY = null; // self pin point this._handled = false; this._handleX = 0; this._handleY = 0; // parent pin point this._aligned = false; this._alignX = 0; this._alignY = 0; // as seen by parent px this._offsetX = 0; this._offsetY = 0; this._boxX = 0; this._boxY = 0; this._boxWidth = this._width; this._boxHeight = this._height; // TODO: also set for owner this._ts_translate = ++iid; this._ts_transform = ++iid; this._ts_matrix = ++iid; }; Pin.prototype._update = function() { this._parent = this._owner._parent && this._owner._parent._pin; // if handled and transformed then be translated if (this._handled && this._mo_handle != this._ts_transform) { this._mo_handle = this._ts_transform; this._ts_translate = ++iid; } if (this._aligned && this._parent && this._mo_align != this._parent._ts_transform) { this._mo_align = this._parent._ts_transform; this._ts_translate = ++iid; } return this; }; Pin.prototype.toString = function() { return this._owner + ' (' + (this._parent ? this._parent._owner : null) + ')'; }; // TODO: ts fields require refactoring Pin.prototype.absoluteMatrix = function() { this._update(); var ts = Math.max(this._ts_transform, this._ts_translate, this._parent ? this._parent._ts_matrix : 0); if (this._mo_abs == ts) { return this._absoluteMatrix; } this._mo_abs = ts; var abs = this._absoluteMatrix; abs.reset(this.relativeMatrix()); this._parent && abs.concat(this._parent._absoluteMatrix); this._ts_matrix = ++iid; return abs; }; Pin.prototype.relativeMatrix = function() { this._update(); var ts = Math.max(this._ts_transform, this._ts_translate, this._parent ? this._parent._ts_transform : 0); if (this._mo_rel == ts) { return this._relativeMatrix; } this._mo_rel = ts; var rel = this._relativeMatrix; rel.identity(); if (this._pivoted) { rel.translate(-this._pivotX * this._width, -this._pivotY * this._height); } rel.scale(this._scaleX, this._scaleY); rel.skew(this._skewX, this._skewY); rel.rotate(this._rotation); if (this._pivoted) { rel.translate(this._pivotX * this._width, this._pivotY * this._height); } // calculate effective box if (this._pivoted) { // origin this._boxX = 0; this._boxY = 0; this._boxWidth = this._width; this._boxHeight = this._height; } else { // aabb var p, q; if (rel.a > 0 && rel.c > 0 || rel.a < 0 && rel.c < 0) { p = 0, q = rel.a * this._width + rel.c * this._height; } else { p = rel.a * this._width, q = rel.c * this._height; } if (p > q) { this._boxX = q; this._boxWidth = p - q; } else { this._boxX = p; this._boxWidth = q - p; } if (rel.b > 0 && rel.d > 0 || rel.b < 0 && rel.d < 0) { p = 0, q = rel.b * this._width + rel.d * this._height; } else { p = rel.b * this._width, q = rel.d * this._height; } if (p > q) { this._boxY = q; this._boxHeight = p - q; } else { this._boxY = p; this._boxHeight = q - p; } } this._x = this._offsetX; this._y = this._offsetY; this._x -= this._boxX + this._handleX * this._boxWidth; this._y -= this._boxY + this._handleY * this._boxHeight; if (this._aligned && this._parent) { this._parent.relativeMatrix(); this._x += this._alignX * this._parent._width; this._y += this._alignY * this._parent._height; } rel.translate(this._x, this._y); return this._relativeMatrix; }; Pin.prototype.get = function(key) { if (typeof getters[key] === 'function') { return getters[key](this); } }; // TODO: Use defineProperty instead? What about multi-field pinning? Pin.prototype.set = function(a, b) { if (typeof a === 'string') { if (typeof setters[a] === 'function' && typeof b !== 'undefined') { setters[a](this, b); } } else if (typeof a === 'object') { for (b in a) { if (typeof setters[b] === 'function' && typeof a[b] !== 'undefined') { setters[b](this, a[b], a); } } } if (this._owner) { this._owner._ts_pin = ++iid; this._owner.touch(); } return this; }; var getters = { alpha : function(pin) { return pin._alpha; }, textureAlpha : function(pin) { return pin._textureAlpha; }, width : function(pin) { return pin._width; }, height : function(pin) { return pin._height; }, boxWidth : function(pin) { return pin._boxWidth; }, boxHeight : function(pin) { return pin._boxHeight; }, // scale : function(pin) { // }, scaleX : function(pin) { return pin._scaleX; }, scaleY : function(pin) { return pin._scaleY; }, // skew : function(pin) { // }, skewX : function(pin) { return pin._skewX; }, skewY : function(pin) { return pin._skewY; }, rotation : function(pin) { return pin._rotation; }, // pivot : function(pin) { // }, pivotX : function(pin) { return pin._pivotX; }, pivotY : function(pin) { return pin._pivotY; }, // offset : function(pin) { // }, offsetX : function(pin) { return pin._offsetX; }, offsetY : function(pin) { return pin._offsetY; }, // align : function(pin) { // }, alignX : function(pin) { return pin._alignX; }, alignY : function(pin) { return pin._alignY; }, // handle : function(pin) { // }, handleX : function(pin) { return pin._handleX; }, handleY : function(pin) { return pin._handleY; } }; var setters = { alpha : function(pin, value) { pin._alpha = value; }, textureAlpha : function(pin, value) { pin._textureAlpha = value; }, width : function(pin, value) { pin._width_ = value; pin._width = value; pin._ts_transform = ++iid; }, height : function(pin, value) { pin._height_ = value; pin._height = value; pin._ts_transform = ++iid; }, scale : function(pin, value) { pin._scaleX = value; pin._scaleY = value; pin._ts_transform = ++iid; }, scaleX : function(pin, value) { pin._scaleX = value; pin._ts_transform = ++iid; }, scaleY : function(pin, value) { pin._scaleY = value; pin._ts_transform = ++iid; }, skew : function(pin, value) { pin._skewX = value; pin._skewY = value; pin._ts_transform = ++iid; }, skewX : function(pin, value) { pin._skewX = value; pin._ts_transform = ++iid; }, skewY : function(pin, value) { pin._skewY = value; pin._ts_transform = ++iid; }, rotation : function(pin, value) { pin._rotation = value; pin._ts_transform = ++iid; }, pivot : function(pin, value) { pin._pivotX = value; pin._pivotY = value; pin._pivoted = true; pin._ts_transform = ++iid; }, pivotX : function(pin, value) { pin._pivotX = value; pin._pivoted = true; pin._ts_transform = ++iid; }, pivotY : function(pin, value) { pin._pivotY = value; pin._pivoted = true; pin._ts_transform = ++iid; }, offset : function(pin, value) { pin._offsetX = value; pin._offsetY = value; pin._ts_translate = ++iid; }, offsetX : function(pin, value) { pin._offsetX = value; pin._ts_translate = ++iid; }, offsetY : function(pin, value) { pin._offsetY = value; pin._ts_translate = ++iid; }, align : function(pin, value) { this.alignX(pin, value); this.alignY(pin, value); }, alignX : function(pin, value) { pin._alignX = value; pin._aligned = true; pin._ts_translate = ++iid; this.handleX(pin, value); }, alignY : function(pin, value) { pin._alignY = value; pin._aligned = true; pin._ts_translate = ++iid; this.handleY(pin, value); }, handle : function(pin, value) { this.handleX(pin, value); this.handleY(pin, value); }, handleX : function(pin, value) { pin._handleX = value; pin._handled = true; pin._ts_translate = ++iid; }, handleY : function(pin, value) { pin._handleY = value; pin._handled = true; pin._ts_translate = ++iid; }, resizeMode : function(pin, value, all) { if (all) { if (value == 'in') { value = 'in-pad'; } else if (value == 'out') { value = 'out-crop'; } scaleTo(pin, all.resizeWidth, all.resizeHeight, value); } }, resizeWidth : function(pin, value, all) { if (!all || !all.resizeMode) { scaleTo(pin, value, null); } }, resizeHeight : function(pin, value, all) { if (!all || !all.resizeMode) { scaleTo(pin, null, value); } }, scaleMode : function(pin, value, all) { if (all) { scaleTo(pin, all.scaleWidth, all.scaleHeight, value); } }, scaleWidth : function(pin, value, all) { if (!all || !all.scaleMode) { scaleTo(pin, value, null); } }, scaleHeight : function(pin, value, all) { if (!all || !all.scaleMode) { scaleTo(pin, null, value); } }, matrix : function(pin, value) { this.scaleX(pin, value.a); this.skewX(pin, value.c / value.d); this.skewY(pin, value.b / value.a); this.scaleY(pin, value.d); this.offsetX(pin, value.e); this.offsetY(pin, value.f); this.rotation(pin, 0); } }; function scaleTo(pin, width, height, mode) { var w = typeof width === 'number'; var h = typeof height === 'number'; var m = typeof mode === 'string'; pin._ts_transform = ++iid; if (w) { pin._scaleX = width / pin._width_; pin._width = pin._width_; } if (h) { pin._scaleY = height / pin._height_; pin._height = pin._height_; } if (w && h && m) { if (mode == 'out' || mode == 'out-crop') { pin._scaleX = pin._scaleY = Math.max(pin._scaleX, pin._scaleY); } else if (mode == 'in' || mode == 'in-pad') { pin._scaleX = pin._scaleY = Math.min(pin._scaleX, pin._scaleY); } if (mode == 'out-crop' || mode == 'in-pad') { pin._width = width / pin._scaleX; pin._height = height / pin._scaleY; } } }; Class.prototype.scaleTo = function(a, b, c) { if (typeof a === 'object') c = b, b = a.y, a = a.x; scaleTo(this._pin, a, b, c); return this; }; // Used by Tween class Pin._add_shortcuts = function(Class) { Class.prototype.size = function(w, h) { this.pin('width', w); this.pin('height', h); return this; }; Class.prototype.width = function(w) { if (typeof w === 'undefined') { return this.pin('width'); } this.pin('width', w); return this; }; Class.prototype.height = function(h) { if (typeof h === 'undefined') { return this.pin('height'); } this.pin('height', h); return this; }; Class.prototype.offset = function(a, b) { if (typeof a === 'object') b = a.y, a = a.x; this.pin('offsetX', a); this.pin('offsetY', b); return this; }; Class.prototype.rotate = function(a) { this.pin('rotation', a); return this; }; Class.prototype.skew = function(a, b) { if (typeof a === 'object') b = a.y, a = a.x; else if (typeof b === 'undefined') b = a; this.pin('skewX', a); this.pin('skewY', b); return this; }; Class.prototype.scale = function(a, b) { if (typeof a === 'object') b = a.y, a = a.x; else if (typeof b === 'undefined') b = a; this.pin('scaleX', a); this.pin('scaleY', b); return this; }; Class.prototype.alpha = function(a, ta) { this.pin('alpha', a); if (typeof ta !== 'undefined') { this.pin('textureAlpha', ta); } return this; }; }; Pin._add_shortcuts(Class); module.exports = Pin; },{"./core":60,"./matrix":67}],69:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var stats = require('./util/stats'); var create = require('./util/create'); var extend = require('./util/extend'); Root._super = Class; Root.prototype = create(Root._super.prototype); Class.root = function(request, render) { return new Root(request, render); }; function Root(request, render) { Root._super.call(this); this.label('Root'); var paused = true; var self = this; var lastTime = 0; var loop = function(now) { if (paused === true) { return; } stats.tick = stats.node = stats.draw = 0; var last = lastTime || now; var elapsed = now - last; lastTime = now; var ticked = self._tick(elapsed, now, last); if (self._mo_touch != self._ts_touch) { self._mo_touch = self._ts_touch; render(self); request(loop); } else if (ticked) { request(loop); } else { paused = true; } stats.fps = elapsed ? 1000 / elapsed : 0; }; this.start = function() { return this.resume(); }; this.resume = function() { if (paused) { this.publish('resume'); paused = false; request(loop); } return this; }; this.pause = function() { if (!paused) { this.publish('pause'); } paused = true; return this; }; this.touch_root = this.touch; this.touch = function() { this.resume(); return this.touch_root(); }; }; Root.prototype.background = function(color) { // to be implemented by loaders return this; }; Root.prototype.viewport = function(width, height, ratio) { if (typeof width === 'undefined') { return extend({}, this._viewport); } this._viewport = { width : width, height : height, ratio : ratio || 1 }; this.viewbox(); var data = extend({}, this._viewport); this.visit({ start : function(node) { if (!node._flag('viewport')) { return true; } node.publish('viewport', [ data ]); } }); return this; }; // TODO: static/fixed viewbox Root.prototype.viewbox = function(width, height, mode) { if (typeof width === 'number' && typeof height === 'number') { this._viewbox = { width : width, height : height, mode : /^(in|out|in-pad|out-crop)$/.test(mode) ? mode : 'in-pad' }; } var box = this._viewbox; var size = this._viewport; if (size && box) { this.pin({ width : box.width, height : box.height }); this.scaleTo(size.width, size.height, box.mode); } else if (size) { this.pin({ width : size.width, height : size.height }); } return this; }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/extend":76,"./util/stats":80}],70:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var create = require('./util/create'); var is = require('./util/is'); Class.string = function(frames) { return new Str().frames(frames); }; Str._super = Class; Str.prototype = create(Str._super.prototype); function Str() { Str._super.call(this); this.label('String'); this._textures = []; }; /** * @deprecated Use frames */ Str.prototype.setFont = function(a, b, c) { return this.frames(a, b, c); }; Str.prototype.frames = function(frames) { this._textures = []; if (typeof frames == 'string') { frames = Class.texture(frames); this._item = function(value) { return frames.one(value); }; } else if (typeof frames === 'object') { this._item = function(value) { return frames[value]; }; } else if (typeof frames === 'function') { this._item = frames; } return this; }; /** * @deprecated Use value */ Str.prototype.setValue = function(a, b, c) { return this.value(a, b, c); }; Str.prototype.value = function(value) { if (typeof value === 'undefined') { return this._value; } if (this._value === value) { return this; } this._value = value; if (value === null) { value = ''; } else if (typeof value !== 'string' && !is.array(value)) { value = value.toString(); } this._spacing = this._spacing || 0; var width = 0, height = 0; for (var i = 0; i < value.length; i++) { var image = this._textures[i] = this._item(value[i]); width += i > 0 ? this._spacing : 0; image.dest(width, 0); width = width + image.width; height = Math.max(height, image.height); } this.pin('width', width); this.pin('height', height); this._textures.length = value.length; return this; }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/is":77}],71:[function(require,module,exports){ var stats = require('./util/stats'); var math = require('./util/math'); function Texture(image, ratio) { if (typeof image === 'object') { this.src(image, ratio); } } Texture.prototype.pipe = function() { return new Texture(this); }; /** * Signatures: (image), (x, y, w, h), (w, h) */ Texture.prototype.src = function(x, y, w, h) { if (typeof x === 'object') { var image = x, ratio = y || 1; this._image = image; this._sx = this._dx = 0; this._sy = this._dy = 0; this._sw = this._dw = image.width / ratio; this._sh = this._dh = image.height / ratio; this.width = image.width / ratio; this.height = image.height / ratio; this.ratio = ratio; } else { if (typeof w === 'undefined') { w = x, h = y; } else { this._sx = x, this._sy = y; } this._sw = this._dw = w; this._sh = this._dh = h; this.width = w; this.height = h; } return this; }; /** * Signatures: (x, y, w, h), (x, y) */ Texture.prototype.dest = function(x, y, w, h) { this._dx = x, this._dy = y; this._dx = x, this._dy = y; if (typeof w !== 'undefined') { this._dw = w, this._dh = h; this.width = w, this.height = h; } return this; }; Texture.prototype.draw = function(context, x1, y1, x2, y2, x3, y3, x4, y4) { var image = this._image; if (image === null || typeof image !== 'object') { return; } var sx = this._sx, sy = this._sy; var sw = this._sw, sh = this._sh; var dx = this._dx, dy = this._dy; var dw = this._dw, dh = this._dh; if (typeof x3 !== 'undefined') { x1 = math.limit(x1, 0, this._sw), x2 = math.limit(x2, 0, this._sw - x1); y1 = math.limit(y1, 0, this._sh), y2 = math.limit(y2, 0, this._sh - y1); sx += x1, sy += y1, sw = x2, sh = y2; dx = x3, dy = y3, dw = x4, dh = y4; } else if (typeof x2 !== 'undefined') { dx = x1, dy = y1, dw = x2, dh = y2; } else if (typeof x1 !== 'undefined') { dw = x1, dh = y1; } var ratio = this.ratio || 1; sx *= ratio, sy *= ratio, sw *= ratio, sh *= ratio; try { if (typeof image.draw === 'function') { image.draw(context, sx, sy, sw, sh, dx, dy, dw, dh); } else { stats.draw++; context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh); } } catch (ex) { if (!image._draw_failed) { console.log('Unable to draw: ', image); console.log(ex); image._draw_failed = true; } } }; module.exports = Texture; },{"./util/math":78,"./util/stats":80}],72:[function(require,module,exports){ var Class = require('./core'); var is = require('./util/is'); var iid = 0; // TODO: do not clear next/prev/parent on remove Class.prototype._label = ''; Class.prototype._visible = true; Class.prototype._parent = null; Class.prototype._next = null; Class.prototype._prev = null; Class.prototype._first = null; Class.prototype._last = null; Class.prototype._attrs = null; Class.prototype._flags = null; Class.prototype.toString = function() { return '[' + this._label + ']'; }; /** * @deprecated Use label() */ Class.prototype.id = function(id) { return this.label(id); }; Class.prototype.label = function(label) { if (typeof label === 'undefined') { return this._label; } this._label = label; return this; }; Class.prototype.attr = function(name, value) { if (typeof value === 'undefined') { return this._attrs !== null ? this._attrs[name] : undefined; } (this._attrs !== null ? this._attrs : this._attrs = {})[name] = value; return this; }; Class.prototype.visible = function(visible) { if (typeof visible === 'undefined') { return this._visible; } this._visible = visible; this._parent && (this._parent._ts_children = ++iid); this._ts_pin = ++iid; this.touch(); return this; }; Class.prototype.hide = function() { return this.visible(false); }; Class.prototype.show = function() { return this.visible(true); }; Class.prototype.parent = function() { return this._parent; }; Class.prototype.next = function(visible) { var next = this._next; while (next && visible && !next._visible) { next = next._next; } return next; }; Class.prototype.prev = function(visible) { var prev = this._prev; while (prev && visible && !prev._visible) { prev = prev._prev; } return prev; }; Class.prototype.first = function(visible) { var next = this._first; while (next && visible && !next._visible) { next = next._next; } return next; }; Class.prototype.last = function(visible) { var prev = this._last; while (prev && visible && !prev._visible) { prev = prev._prev; } return prev; }; Class.prototype.visit = function(visitor, data) { var reverse = visitor.reverse; var visible = visitor.visible; if (visitor.start && visitor.start(this, data)) { return; } var child, next = reverse ? this.last(visible) : this.first(visible); while (child = next) { next = reverse ? child.prev(visible) : child.next(visible); if (child.visit(visitor, data)) { return true; } } return visitor.end && visitor.end(this, data); }; Class.prototype.append = function(child, more) { if (is.array(child)) for (var i = 0; i < child.length; i++) append(this, child[i]); else if (typeof more !== 'undefined') // deprecated for (var i = 0; i < arguments.length; i++) append(this, arguments[i]); else if (typeof child !== 'undefined') append(this, child); return this; }; Class.prototype.prepend = function(child, more) { if (is.array(child)) for (var i = child.length - 1; i >= 0; i--) prepend(this, child[i]); else if (typeof more !== 'undefined') // deprecated for (var i = arguments.length - 1; i >= 0; i--) prepend(this, arguments[i]); else if (typeof child !== 'undefined') prepend(this, child); return this; }; Class.prototype.appendTo = function(parent) { append(parent, this); return this; }; Class.prototype.prependTo = function(parent) { prepend(parent, this); return this; }; Class.prototype.insertNext = function(sibling, more) { if (is.array(sibling)) for (var i = 0; i < sibling.length; i++) insertAfter(sibling[i], this); else if (typeof more !== 'undefined') // deprecated for (var i = 0; i < arguments.length; i++) insertAfter(arguments[i], this); else if (typeof sibling !== 'undefined') insertAfter(sibling, this); return this; }; Class.prototype.insertPrev = function(sibling, more) { if (is.array(sibling)) for (var i = sibling.length - 1; i >= 0; i--) insertBefore(sibling[i], this); else if (typeof more !== 'undefined') // deprecated for (var i = arguments.length - 1; i >= 0; i--) insertBefore(arguments[i], this); else if (typeof sibling !== 'undefined') insertBefore(sibling, this); return this; }; Class.prototype.insertAfter = function(prev) { insertAfter(this, prev); return this; }; Class.prototype.insertBefore = function(next) { insertBefore(this, next); return this; }; function append(parent, child) { _ensure(child); _ensure(parent); child.remove(); if (parent._last) { parent._last._next = child; child._prev = parent._last; } child._parent = parent; parent._last = child; if (!parent._first) { parent._first = child; } child._parent._flag(child, true); child._ts_parent = ++iid; parent._ts_children = ++iid; parent.touch(); } function prepend(parent, child) { _ensure(child); _ensure(parent); child.remove(); if (parent._first) { parent._first._prev = child; child._next = parent._first; } child._parent = parent; parent._first = child; if (!parent._last) { parent._last = child; } child._parent._flag(child, true); child._ts_parent = ++iid; parent._ts_children = ++iid; parent.touch(); }; function insertBefore(self, next) { _ensure(self); _ensure(next); self.remove(); var parent = next._parent; var prev = next._prev; next._prev = self; prev && (prev._next = self) || parent && (parent._first = self); self._parent = parent; self._prev = prev; self._next = next; self._parent._flag(self, true); self._ts_parent = ++iid; self.touch(); }; function insertAfter(self, prev) { _ensure(self); _ensure(prev); self.remove(); var parent = prev._parent; var next = prev._next; prev._next = self; next && (next._prev = self) || parent && (parent._last = self); self._parent = parent; self._prev = prev; self._next = next; self._parent._flag(self, true); self._ts_parent = ++iid; self.touch(); }; Class.prototype.remove = function(child, more) { if (typeof child !== 'undefined') { if (is.array(child)) { for (var i = 0; i < child.length; i++) _ensure(child[i]).remove(); } else if (typeof more !== 'undefined') { for (var i = 0; i < arguments.length; i++) _ensure(arguments[i]).remove(); } else { _ensure(child).remove(); } return this; } if (this._prev) { this._prev._next = this._next; } if (this._next) { this._next._prev = this._prev; } if (this._parent) { if (this._parent._first === this) { this._parent._first = this._next; } if (this._parent._last === this) { this._parent._last = this._prev; } this._parent._flag(this, false); this._parent._ts_children = ++iid; this._parent.touch(); } this._prev = this._next = this._parent = null; this._ts_parent = ++iid; // this._parent.touch(); return this; }; Class.prototype.empty = function() { var child, next = this._first; while (child = next) { next = child._next; child._prev = child._next = child._parent = null; this._flag(child, false); } this._first = this._last = null; this._ts_children = ++iid; this.touch(); return this; }; Class.prototype.touch = function() { this._ts_touch = ++iid; this._parent && this._parent.touch(); return this; }; /** * Deep flags used for optimizing event distribution. */ Class.prototype._flag = function(obj, name) { if (typeof name === 'undefined') { return this._flags !== null && this._flags[obj] || 0; } if (typeof obj === 'string') { if (name) { this._flags = this._flags || {}; if (!this._flags[obj] && this._parent) { this._parent._flag(obj, true); } this._flags[obj] = (this._flags[obj] || 0) + 1; } else if (this._flags && this._flags[obj] > 0) { if (this._flags[obj] == 1 && this._parent) { this._parent._flag(obj, false); } this._flags[obj] = this._flags[obj] - 1; } } if (typeof obj === 'object') { if (obj._flags) { for ( var type in obj._flags) { if (obj._flags[type] > 0) { this._flag(type, name); } } } } return this; }; /** * @private */ Class.prototype.hitTest = function(hit) { if (this.attr('spy')) { return true; } return hit.x >= 0 && hit.x <= this._pin._width && hit.y >= 0 && hit.y <= this._pin._height; }; function _ensure(obj) { if (obj && obj instanceof Class) { return obj; } throw 'Invalid node: ' + obj; }; module.exports = Class; },{"./core":60,"./util/is":77}],73:[function(require,module,exports){ module.exports = function() { var count = 0; function fork(fn, n) { count += n = (typeof n === 'number' && n >= 1 ? n : 1); return function() { fn && fn.apply(this, arguments); if (n > 0) { n--, count--, call(); } }; } var then = []; function call() { if (count === 0) { while (then.length) { setTimeout(then.shift(), 0); } } } fork.then = function(fn) { if (count === 0) { setTimeout(fn, 0); } else { then.push(fn); } }; return fork; }; },{}],74:[function(require,module,exports){ if (typeof Object.create == 'function') { module.exports = function(proto, props) { return Object.create.call(Object, proto, props); }; } else { module.exports = function(proto, props) { if (props) throw Error('Second argument is not supported!'); if (typeof proto !== 'object' || proto === null) throw Error('Invalid prototype!'); noop.prototype = proto; return new noop; }; function noop() { } } },{}],75:[function(require,module,exports){ module.exports = function(prototype, callback) { prototype._listeners = null; prototype.on = prototype.listen = function(types, listener) { if (!types || !types.length || typeof listener !== 'function') { return this; } if (this._listeners === null) { this._listeners = {}; } var isarray = typeof types !== 'string' && typeof types.join === 'function'; if (types = (isarray ? types.join(' ') : types).match(/\S+/g)) { for (var i = 0; i < types.length; i++) { var type = types[i]; this._listeners[type] = this._listeners[type] || []; this._listeners[type].push(listener); if (typeof callback === 'function') { callback(this, type, true); } } } return this; }; prototype.off = function(types, listener) { if (!types || !types.length || typeof listener !== 'function') { return this; } if (this._listeners === null) { return this; } var isarray = typeof types !== 'string' && typeof types.join === 'function'; if (types = (isarray ? types.join(' ') : types).match(/\S+/g)) { for (var i = 0; i < types.length; i++) { var type = types[i], all = this._listeners[type], index; if (all && (index = all.indexOf(listener)) >= 0) { all.splice(index, 1); if (!all.length) { delete this._listeners[type]; } if (typeof callback === 'function') { callback(this, type, false); } } } } return this; }; prototype.listeners = function(type) { return this._listeners && this._listeners[type]; }; prototype.publish = function(name, args) { var listeners = this.listeners(name); if (!listeners || !listeners.length) { return 0; } for (var l = 0; l < listeners.length; l++) { listeners[l].apply(this, args); } return listeners.length; }; prototype.trigger = function(name, args) { this.publish(name, args); return this; }; }; },{}],76:[function(require,module,exports){ module.exports = function(base) { for (var i = 1; i < arguments.length; i++) { var obj = arguments[i]; for ( var key in obj) { if (obj.hasOwnProperty(key)) { base[key] = obj[key]; } } } return base; }; },{}],77:[function(require,module,exports){ /** * ! is the definitive JavaScript type testing library * * @copyright 2013-2014 Enrico Marino / Jordan Harband * @license MIT */ var objProto = Object.prototype; var owns = objProto.hasOwnProperty; var toStr = objProto.toString; var NON_HOST_TYPES = { 'boolean' : 1, 'number' : 1, 'string' : 1, 'undefined' : 1 }; var hexRegex = /^[A-Fa-f0-9]+$/; var is = module.exports = {}; is.a = is.an = is.type = function(value, type) { return typeof value === type; }; is.defined = function(value) { return typeof value !== 'undefined'; }; is.empty = function(value) { var type = toStr.call(value); var key; if ('[object Array]' === type || '[object Arguments]' === type || '[object String]' === type) { return value.length === 0; } if ('[object Object]' === type) { for (key in value) { if (owns.call(value, key)) { return false; } } return true; } return !value; }; is.equal = function(value, other) { if (value === other) { return true; } var type = toStr.call(value); var key; if (type !== toStr.call(other)) { return false; } if ('[object Object]' === type) { for (key in value) { if (!is.equal(value[key], other[key]) || !(key in other)) { return false; } } for (key in other) { if (!is.equal(value[key], other[key]) || !(key in value)) { return false; } } return true; } if ('[object Array]' === type) { key = value.length; if (key !== other.length) { return false; } while (--key) { if (!is.equal(value[key], other[key])) { return false; } } return true; } if ('[object Function]' === type) { return value.prototype === other.prototype; } if ('[object Date]' === type) { return value.getTime() === other.getTime(); } return false; }; is.instance = function(value, constructor) { return value instanceof constructor; }; is.nil = function(value) { return value === null; }; is.undef = function(value) { return typeof value === 'undefined'; }; is.array = function(value) { return '[object Array]' === toStr.call(value); }; is.emptyarray = function(value) { return is.array(value) && value.length === 0; }; is.arraylike = function(value) { return !!value && !is.boolean(value) && owns.call(value, 'length') && isFinite(value.length) && is.number(value.length) && value.length >= 0; }; is.boolean = function(value) { return '[object Boolean]' === toStr.call(value); }; is.element = function(value) { return value !== undefined && typeof HTMLElement !== 'undefined' && value instanceof HTMLElement && value.nodeType === 1; }; is.fn = function(value) { return '[object Function]' === toStr.call(value); }; is.number = function(value) { return '[object Number]' === toStr.call(value); }; is.nan = function(value) { return !is.number(value) || value !== value; }; is.object = function(value) { return '[object Object]' === toStr.call(value); }; is.hash = function(value) { return is.object(value) && value.constructor === Object && !value.nodeType && !value.setInterval; }; is.regexp = function(value) { return '[object RegExp]' === toStr.call(value); }; is.string = function(value) { return '[object String]' === toStr.call(value); }; is.hex = function(value) { return is.string(value) && (!value.length || hexRegex.test(value)); }; },{}],78:[function(require,module,exports){ var create = require('./create'); var native = Math; module.exports = create(Math); module.exports.random = function(min, max) { if (typeof min === 'undefined') { max = 1, min = 0; } else if (typeof max === 'undefined') { max = min, min = 0; } return min == max ? min : native.random() * (max - min) + min; }; module.exports.rotate = function(num, min, max) { if (typeof min === 'undefined') { max = 1, min = 0; } else if (typeof max === 'undefined') { max = min, min = 0; } if (max > min) { num = (num - min) % (max - min); return num + (num < 0 ? max : min); } else { num = (num - max) % (min - max); return num + (num <= 0 ? min : max); } }; module.exports.limit = function(num, min, max) { if (num < min) { return min; } else if (num > max) { return max; } else { return num; } }; module.exports.length = function(x, y) { return native.sqrt(x * x + y * y); }; },{"./create":74}],79:[function(require,module,exports){ module.exports = function(img, owidth, oheight, stretch, inner, insert) { var width = img.width; var height = img.height; var left = img.left; var right = img.right; var top = img.top; var bottom = img.bottom; left = typeof left === 'number' && left === left ? left : 0; right = typeof right === 'number' && right === right ? right : 0; top = typeof top === 'number' && top === top ? top : 0; bottom = typeof bottom === 'number' && bottom === bottom ? bottom : 0; width = width - left - right; height = height - top - bottom; if (!inner) { owidth = Math.max(owidth - left - right, 0); oheight = Math.max(oheight - top - bottom, 0); } var i = 0; if (top > 0 && left > 0) insert(i++, 0, 0, left, top, 0, 0, left, top); if (bottom > 0 && left > 0) insert(i++, 0, height + top, left, bottom, 0, oheight + top, left, bottom); if (top > 0 && right > 0) insert(i++, width + left, 0, right, top, owidth + left, 0, right, top); if (bottom > 0 && right > 0) insert(i++, width + left, height + top, right, bottom, owidth + left, oheight + top, right, bottom); if (stretch) { if (top > 0) insert(i++, left, 0, width, top, left, 0, owidth, top); if (bottom > 0) insert(i++, left, height + top, width, bottom, left, oheight + top, owidth, bottom); if (left > 0) insert(i++, 0, top, left, height, 0, top, left, oheight); if (right > 0) insert(i++, width + left, top, right, height, owidth + left, top, right, oheight); // center insert(i++, left, top, width, height, left, top, owidth, oheight); } else { // tile var l = left, r = owidth, w; while (r > 0) { w = Math.min(width, r), r -= width; var t = top, b = oheight, h; while (b > 0) { h = Math.min(height, b), b -= height; insert(i++, left, top, w, h, l, t, w, h); if (r <= 0) { if (left) insert(i++, 0, top, left, h, 0, t, left, h); if (right) insert(i++, width + left, top, right, h, l + w, t, right, h); } t += h; } if (top) insert(i++, left, 0, w, top, l, 0, w, top); if (bottom) insert(i++, left, height + top, w, bottom, l, t, w, bottom); l += w; } } return i; }; },{}],80:[function(require,module,exports){ module.exports = {}; },{}],81:[function(require,module,exports){ module.exports.startsWith = function(str, sub) { return typeof str === 'string' && typeof sub === 'string' && str.substring(0, sub.length) == sub; }; },{}],82:[function(require,module,exports){ module.exports = require('../lib/'); module.exports.internal = {}; require('../lib/canvas'); module.exports.internal.Image = require('../lib/image'); require('../lib/anim'); require('../lib/str'); require('../lib/layout'); require('../lib/addon/tween'); module.exports.Mouse = require('../lib/addon/mouse'); module.exports.Math = require('../lib/util/math'); module.exports._extend = require('../lib/util/extend'); module.exports._create = require('../lib/util/create'); require('../lib/loader/web'); },{"../lib/":63,"../lib/addon/mouse":55,"../lib/addon/tween":56,"../lib/anim":57,"../lib/canvas":59,"../lib/image":62,"../lib/layout":64,"../lib/loader/web":65,"../lib/str":70,"../lib/util/create":74,"../lib/util/extend":76,"../lib/util/math":78}]},{},[1])(1) });
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), meta: { banner : '/*!\n' + ' * <%= pkg.title %> v<%= pkg.version %> - <%= pkg.description %>\n' + ' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %> - <%= pkg.homepage %>\n' + ' * License: <%= pkg.license %>\n' + ' */\n\n' }, uglify: { options : { banner : '<%= meta.banner %>', report: 'gzip' }, dist: { files: { 'jquery.timepicker.min.js': ['jquery.timepicker.js'] } } }, cssmin: { minify: { files: { 'jquery.timepicker.min.css': ['jquery.timepicker.css'] } } } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.registerTask('default', ['uglify', 'cssmin']); };
var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.ASSUME_ES5=!1;$jscomp.ASSUME_NO_NATIVE_MAP=!1;$jscomp.ASSUME_NO_NATIVE_SET=!1;$jscomp.defineProperty=$jscomp.ASSUME_ES5||"function"==typeof Object.defineProperties?Object.defineProperty:function(b,d,a){b!=Array.prototype&&b!=Object.prototype&&(b[d]=a.value)};$jscomp.getGlobal=function(b){return"undefined"!=typeof window&&window===b?b:"undefined"!=typeof global&&null!=global?global:b};$jscomp.global=$jscomp.getGlobal(this);$jscomp.SYMBOL_PREFIX="jscomp_symbol_"; $jscomp.initSymbol=function(){$jscomp.initSymbol=function(){};$jscomp.global.Symbol||($jscomp.global.Symbol=$jscomp.Symbol)};$jscomp.symbolCounter_=0;$jscomp.Symbol=function(b){return $jscomp.SYMBOL_PREFIX+(b||"")+$jscomp.symbolCounter_++}; $jscomp.initSymbolIterator=function(){$jscomp.initSymbol();var b=$jscomp.global.Symbol.iterator;b||(b=$jscomp.global.Symbol.iterator=$jscomp.global.Symbol("iterator"));"function"!=typeof Array.prototype[b]&&$jscomp.defineProperty(Array.prototype,b,{configurable:!0,writable:!0,value:function(){return $jscomp.arrayIterator(this)}});$jscomp.initSymbolIterator=function(){}};$jscomp.arrayIterator=function(b){var d=0;return $jscomp.iteratorPrototype(function(){return d<b.length?{done:!1,value:b[d++]}:{done:!0}})}; $jscomp.iteratorPrototype=function(b){$jscomp.initSymbolIterator();b={next:b};b[$jscomp.global.Symbol.iterator]=function(){return this};return b};$jscomp.iteratorFromArray=function(b,d){$jscomp.initSymbolIterator();b instanceof String&&(b+="");var a=0,h={next:function(){if(a<b.length){var l=a++;return{value:d(l,b[l]),done:!1}}h.next=function(){return{done:!0,value:void 0}};return h.next()}};h[Symbol.iterator]=function(){return h};return h}; $jscomp.polyfill=function(b,d,a,h){if(d){a=$jscomp.global;b=b.split(".");for(h=0;h<b.length-1;h++){var l=b[h];l in a||(a[l]={});a=a[l]}b=b[b.length-1];h=a[b];d=d(h);d!=h&&null!=d&&$jscomp.defineProperty(a,b,{configurable:!0,writable:!0,value:d})}};$jscomp.polyfill("Array.prototype.keys",function(b){return b?b:function(){return $jscomp.iteratorFromArray(this,function(b){return b})}},"es6","es3");$jscomp.polyfill("Object.getOwnPropertySymbols",function(b){return b?b:function(){return[]}},"es6","es5"); $jscomp.owns=function(b,d){return Object.prototype.hasOwnProperty.call(b,d)};$jscomp.polyfill("Object.assign",function(b){return b?b:function(b,a){for(var d=1;d<arguments.length;d++){var l=arguments[d];if(l)for(var g in l)$jscomp.owns(l,g)&&(b[g]=l[g])}return b}},"es6","es3");$jscomp.findInternal=function(b,d,a){b instanceof String&&(b=String(b));for(var h=b.length,l=0;l<h;l++){var g=b[l];if(d.call(a,g,l,b))return{i:l,v:g}}return{i:-1,v:void 0}}; $jscomp.polyfill("Array.prototype.find",function(b){return b?b:function(b,a){return $jscomp.findInternal(this,b,a).v}},"es6","es3");$jscomp.polyfill("Array.prototype.values",function(b){return b?b:function(){return $jscomp.iteratorFromArray(this,function(b,a){return a})}},"es6","es3"); (function(b,d){"object"===typeof exports&&"object"===typeof module?module.exports=d():"function"===typeof define&&define.amd?define([],d):"object"===typeof exports?exports.RxPlayer=d():b.RxPlayer=d()})(this,function(){return function(b){function d(h){if(a[h])return a[h].exports;var l=a[h]={i:h,l:!1,exports:{}};b[h].call(l.exports,l,l.exports,d);l.l=!0;return l.exports}var a={};d.m=b;d.c=a;d.i=function(a){return a};d.d=function(a,b,g){d.o(a,b)||Object.defineProperty(a,b,{configurable:!1,enumerable:!0, get:g})};d.n=function(a){var b=a&&a.__esModule?function(){return a["default"]}:function(){return a};d.d(b,"a",b);return b};d.o=function(a,b){return Object.prototype.hasOwnProperty.call(a,b)};d.p="";return d(d.s=138)}([function(b,d,a){var h=a(12),l=a(263),g=a(48);b=function(){function a(a){this._isScalar=!1;a&&(this._subscribe=a)}a.prototype.lift=function(f){var c=new a;c.source=this;c.operator=f;return c};a.prototype.subscribe=function(a,c,e){var f=this.operator;a=l.toSubscriber(a,c,e);f?f.call(a, this.source):a.add(this.source?this._subscribe(a):this._trySubscribe(a));if(a.syncErrorThrowable&&(a.syncErrorThrowable=!1,a.syncErrorThrown))throw a.syncErrorValue;return a};a.prototype._trySubscribe=function(a){try{return this._subscribe(a)}catch(c){a.syncErrorThrown=!0,a.syncErrorValue=c,a.error(c)}};a.prototype.forEach=function(a,c){var e=this;c||(h.root.Rx&&h.root.Rx.config&&h.root.Rx.config.Promise?c=h.root.Rx.config.Promise:h.root.Promise&&(c=h.root.Promise));if(!c)throw Error("no Promise impl found"); return new c(function(c,f){var k=e.subscribe(function(c){if(k)try{a(c)}catch(p){f(p),k.unsubscribe()}else a(c)},f,c)})};a.prototype._subscribe=function(a){return this.source.subscribe(a)};a.prototype[g.observable]=function(){return this};a.create=function(f){return new a(f)};return a}();d.Observable=b},function(b,d,a){function h(){}var l={NONE:0,ERROR:1,WARNING:2,INFO:3,DEBUG:4},g=function(){};h.error=g;h.warn=g;h.info=g;h.debug=g;h.setLevel=function(a){"string"==typeof a&&(a=l[a]);h.error=a>=l.ERROR? console.error.bind(console):g;h.warn=a>=l.WARNING?console.warn.bind(console):g;h.info=a>=l.INFO?console.info.bind(console):g;h.debug=a>=l.DEBUG?console.log.bind(console):g};d.a=h},function(b,d,a){function h(a){this.name="AssertionError";this.message=a;Error.captureStackTrace&&Error.captureStackTrace(this,h)}function l(a,f){if(!a)throw new h(f);}var g="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor=== Symbol&&a!==Symbol.prototype?"symbol":typeof a};h.prototype=Error();l.equal=function(a,f,c){return l(a===f,c)};l.iface=function(a,f,c){l(a,f+" should be an object");for(var e in c)l.equal(g(a[e]),c[e],f+" should have property "+e+" as a "+c[e])};d.a=l},function(b,d,a){var h=this&&this.__extends||function(a,e){function c(){this.constructor=a}for(var f in e)e.hasOwnProperty(f)&&(a[f]=e[f]);a.prototype=null===e?Object.create(e):(c.prototype=e.prototype,new c)},l=a(51);b=a(11);var g=a(71),k=a(49);a=function(a){function c(e, k,b){a.call(this);this.syncErrorValue=null;this.isStopped=this.syncErrorThrowable=this.syncErrorThrown=!1;switch(arguments.length){case 0:this.destination=g.empty;break;case 1:if(!e){this.destination=g.empty;break}if("object"===typeof e){e instanceof c?(this.destination=e,this.destination.add(this)):(this.syncErrorThrowable=!0,this.destination=new f(this,e));break}default:this.syncErrorThrowable=!0,this.destination=new f(this,e,k,b)}}h(c,a);c.prototype[k.rxSubscriber]=function(){return this};c.create= function(a,e,f){a=new c(a,e,f);a.syncErrorThrowable=!1;return a};c.prototype.next=function(a){this.isStopped||this._next(a)};c.prototype.error=function(a){this.isStopped||(this.isStopped=!0,this._error(a))};c.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())};c.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,a.prototype.unsubscribe.call(this))};c.prototype._next=function(a){this.destination.next(a)};c.prototype._error=function(a){this.destination.error(a); this.unsubscribe()};c.prototype._complete=function(){this.destination.complete();this.unsubscribe()};c.prototype._unsubscribeAndRecycle=function(){var a=this._parent,c=this._parents;this._parents=this._parent=null;this.unsubscribe();this.isStopped=this.closed=!1;this._parent=a;this._parents=c;return this};return c}(b.Subscription);d.Subscriber=a;var f=function(a){function c(c,e,f,k){a.call(this);this._parentSubscriber=c;c=this;if(l.isFunction(e))var m=e;else e&&(m=e.next,f=e.error,k=e.complete,e!== g.empty&&(c=Object.create(e),l.isFunction(c.unsubscribe)&&this.add(c.unsubscribe.bind(c)),c.unsubscribe=this.unsubscribe.bind(this)));this._context=c;this._next=m;this._error=f;this._complete=k}h(c,a);c.prototype.next=function(a){if(!this.isStopped&&this._next){var c=this._parentSubscriber;c.syncErrorThrowable?this.__tryOrSetError(c,this._next,a)&&this.unsubscribe():this.__tryOrUnsub(this._next,a)}};c.prototype.error=function(a){if(!this.isStopped){var c=this._parentSubscriber;if(this._error)c.syncErrorThrowable? this.__tryOrSetError(c,this._error,a):this.__tryOrUnsub(this._error,a),this.unsubscribe();else if(c.syncErrorThrowable)c.syncErrorValue=a,c.syncErrorThrown=!0,this.unsubscribe();else throw this.unsubscribe(),a;}};c.prototype.complete=function(){var a=this;if(!this.isStopped){var c=this._parentSubscriber;if(this._complete){var e=function(){return a._complete.call(a._context)};c.syncErrorThrowable?this.__tryOrSetError(c,e):this.__tryOrUnsub(e)}this.unsubscribe()}};c.prototype.__tryOrUnsub=function(a, c){try{a.call(this._context,c)}catch(q){throw this.unsubscribe(),q;}};c.prototype.__tryOrSetError=function(a,c,e){try{c.call(this._context,e)}catch(r){return a.syncErrorValue=r,a.syncErrorThrown=!0}return!1};c.prototype._unsubscribe=function(){var a=this._parentSubscriber;this._parentSubscriber=this._context=null;a.unsubscribe()};return c}(a)},function(b,d,a){d.a={DEFAULT_UNMUTED_VOLUME:.1,DEFAULT_AUDIO_TRACK:{language:"fra",audioDescription:!1},DEFAULT_TEXT_TRACK:null,DEFAULT_AUTO_PLAY:!1,DEFAULT_SHOW_SUBTITLE:!0, DEFAULT_WANTED_BUFFER_AHEAD:30,DEFAULT_MAX_BUFFER_AHEAD:Infinity,DEFAULT_MAX_BUFFER_BEHIND:Infinity,DEFAULT_INITIAL_BITRATES:{audio:0,video:0,other:0},DEFAULT_MAX_BITRATES:{audio:Infinity,video:Infinity,other:Infinity},DEFAULT_ADAPTIVE_BUFFER_THRESHOLD:.3,INACTIVITY_DELAY:6E4,DEFAULT_THROTTLE_WHEN_HIDDEN:!1,DEFAULT_LIMIT_VIDEO_WIDTH:!1,DEFAULT_LIVE_GAP:10,DEFAULT_SUGGESTED_PRESENTATION_DELAY:{SMOOTH:10,DASH:10},DISCONTINUITY_THRESHOLD:1,END_OF_PLAY:.5,BITRATE_REBUFFERING_RATIO:1.5,BUFFER_GC_GAPS:{CALM:240, BEEFY:30},DEFAULT_MAX_PIPELINES_RETRY_ON_ERROR:4,DEFAULT_MAX_PIPELINES_RETRY_ON_OFFLINE:Infinity,INITIAL_BACKOFF_DELAY_BASE:200,MAX_BACKOFF_DELAY_BASE:3E3,SAMPLING_INTERVAL_MEDIASOURCE:1E3,SAMPLING_INTERVAL_NO_MEDIASOURCE:500,ABR_MINIMUM_TOTAL_BYTES:128E3,ABR_MINIMUM_CHUNK_SIZE:16E3,ABR_STARVATION_GAP:5,OUT_OF_STARVATION_GAP:7,RESUME_AFTER_SEEKING_GAP:.5,RESUME_AFTER_BUFFERING_GAP:5,STALL_GAP:.5,MAX_MISSING_FROM_COMPLETE_SEGMENT:.12,MAX_BUFFERED_DISTANCE:.1,MINIMUM_SEGMENT_SIZE:.3,EME_DEFAULT_WIDEVINE_ROBUSTNESSES:["HW_SECURE_ALL", "HW_SECURE_DECODE","HW_SECURE_CRYPTO","SW_SECURE_DECODE","SW_SECURE_CRYPTO"],EME_KEY_SYSTEMS:{clearkey:["webkit-org.w3.clearkey","org.w3.clearkey"],widevine:["com.widevine.alpha"],playready:["com.microsoft.playready","com.chromecast.playready","com.youtube.playready"]}}},function(b,d,a){var h=this&&this.__extends||function(a,c){function e(){this.constructor=a}for(var f in c)c.hasOwnProperty(f)&&(a[f]=c[f]);a.prototype=null===c?Object.create(c):(e.prototype=c.prototype,new e)},l=a(0);b=a(3);var g= a(11),k=a(50),f=a(72),c=a(49),e=function(a){function c(c){a.call(this,c);this.destination=c}h(c,a);return c}(b.Subscriber);d.SubjectSubscriber=e;a=function(a){function b(){a.call(this);this.observers=[];this.hasError=this.isStopped=this.closed=!1;this.thrownError=null}h(b,a);b.prototype[c.rxSubscriber]=function(){return new e(this)};b.prototype.lift=function(a){var c=new m(this,this);c.operator=a;return c};b.prototype.next=function(a){if(this.closed)throw new k.ObjectUnsubscribedError;if(!this.isStopped){var c= this.observers,e=c.length;c=c.slice();for(var f=0;f<e;f++)c[f].next(a)}};b.prototype.error=function(a){if(this.closed)throw new k.ObjectUnsubscribedError;this.hasError=!0;this.thrownError=a;this.isStopped=!0;var c=this.observers,e=c.length;c=c.slice();for(var f=0;f<e;f++)c[f].error(a);this.observers.length=0};b.prototype.complete=function(){if(this.closed)throw new k.ObjectUnsubscribedError;this.isStopped=!0;var a=this.observers,c=a.length;a=a.slice();for(var e=0;e<c;e++)a[e].complete();this.observers.length= 0};b.prototype.unsubscribe=function(){this.closed=this.isStopped=!0;this.observers=null};b.prototype._trySubscribe=function(c){if(this.closed)throw new k.ObjectUnsubscribedError;return a.prototype._trySubscribe.call(this,c)};b.prototype._subscribe=function(a){if(this.closed)throw new k.ObjectUnsubscribedError;if(this.hasError)return a.error(this.thrownError),g.Subscription.EMPTY;if(this.isStopped)return a.complete(),g.Subscription.EMPTY;this.observers.push(a);return new f.SubjectSubscription(this, a)};b.prototype.asObservable=function(){var a=new l.Observable;a.source=this;return a};b.create=function(a,c){return new m(a,c)};return b}(l.Observable);d.Subject=a;var m=function(a){function c(c,e){a.call(this);this.destination=c;this.source=e}h(c,a);c.prototype.next=function(a){var c=this.destination;c&&c.next&&c.next(a)};c.prototype.error=function(a){var c=this.destination;c&&c.error&&this.destination.error(a)};c.prototype.complete=function(){var a=this.destination;a&&a.complete&&this.destination.complete()}; c.prototype._subscribe=function(a){return this.source?this.source.subscribe(a):g.Subscription.EMPTY};return c}(a);d.AnonymousSubject=m},function(b,d,a){function h(a){return!!a&&!!a.type&&0<=l.a.keys.indexOf(a.type)}a.d(d,"d",function(){return h});var l=a(18),g=a(132),k=a(133),f=a(134),c=a(135),e=a(136),m=a(137);a.d(d,"b",function(){return l.b});a.d(d,"a",function(){return l.a});a.d(d,"j",function(){return l.c});a.d(d,"c",function(){return g.a});a.d(d,"g",function(){return k.a});a.d(d,"f",function(){return f.a}); a.d(d,"i",function(){return c.a});a.d(d,"e",function(){return e.a});a.d(d,"h",function(){return m.a})},function(b,d,a){function h(a){return!!p.a&&p.a.isTypeSupported(a)}function l(){return p.b}function g(a){return a.readyState>=p.c.HAVE_METADATA?q.Observable.of(null):t.f(a).take(1)}function k(c){return c.readyState>=p.c.HAVE_ENOUGH_DATA?q.Observable.of(null):a.i(r.a)(c,"canplay").take(1)}function f(a,c){var e=void 0;if(p.b){var f=a.textTracks.length;a=0<f?a.textTracks[f-1]:a.addTextTrack("subtitles"); a.mode=c?a.HIDDEN:a.SHOWING}else e=document.createElement("track"),a.appendChild(e),a=e.track,e.kind="subtitles",a.mode=c?"hidden":"showing";return{track:a,trackElement:e}}function c(){return!p.b}function e(a){return p.d&&a.stalled&&"timeupdate"===a.state&&a.range&&10<a.range.end-a.currentTime}function m(a){a.src="";a.removeAttribute("src")}function n(){return!1===navigator.onLine}a.d(d,"n",function(){return f});a.d(d,"j",function(){return k});a.d(d,"i",function(){return g});a.d(d,"k",function(){return m}); a.d(d,"p",function(){return h});a.d(d,"q",function(){return n});a.d(d,"m",function(){return e});a.d(d,"o",function(){return c});a.d(d,"e",function(){return l});var q=a(0);a.n(q);var r=a(31);b=a(29);var p=a(34),t=a(17),u=a(90),w=a(88);a.d(d,"a",function(){return p.e});a.d(d,"f",function(){return w.a});a.d(d,"l",function(){return p.a});a.d(d,"c",function(){return u.a});a.d(d,"b",function(){return u.b});a.d(d,"r",function(){return p.b});a.d(d,"d",function(){return u.c});a.d(d,"g",function(){return w.b}); a.d(d,"h",function(){return w.c});if(window.WebKitSourceBuffer&&!window.WebKitSourceBuffer.prototype.addEventListener){d=window.WebKitSourceBuffer.prototype;for(var x in b.a.prototype)d[x]=b.a.prototype[x];d.__listeners=[];d.appendBuffer=function(a){if(this.updating)throw Error("updating");this.trigger("updatestart");this.updating=!0;try{this.append(a)}catch(y){this.__emitUpdate("error",y);return}this.__emitUpdate("update")};d.__emitUpdate=function(a,c){var e=this;setTimeout(function(){e.trigger(a, c);e.updating=!1;e.trigger("updateend")},0)}}},function(b,d,a){var h=Object.getOwnPropertySymbols,l=Object.prototype.hasOwnProperty,g=Object.prototype.propertyIsEnumerable;b.exports=function(){try{if(!Object.assign)return!1;var a=new String("abc");a[5]="de";if("5"===Object.getOwnPropertyNames(a)[0])return!1;var f={};for(a=0;10>a;a++)f["_"+String.fromCharCode(a)]=a;if("0123456789"!==Object.getOwnPropertyNames(f).map(function(a){return f[a]}).join(""))return!1;var c={};"abcdefghijklmnopqrst".split("").forEach(function(a){c[a]= a});return"abcdefghijklmnopqrst"!==Object.keys(Object.assign({},c)).join("")?!1:!0}catch(e){return!1}}()?Object.assign:function(a,f){if(null===a||void 0===a)throw new TypeError("Object.assign cannot be called with null or undefined");var c=Object(a);for(var e,k=1;k<arguments.length;k++){var b=Object(arguments[k]);for(var d in b)l.call(b,d)&&(c[d]=b[d]);if(h){e=h(b);for(var r=0;r<e.length;r++)g.call(b,e[r])&&(c[e[r]]=b[e[r]])}}return c}},function(b,d,a){d.a=function(a){return a instanceof h.Observable? a:a&&"function"==typeof a.subscribe?new h.Observable(function(g){var k=a.subscribe(function(a){return g.next(a)},function(a){return g.error(a)},function(){return g.complete()});return function(){k&&k.dispose?k.dispose():k&&k.unsubscribe&&k.unsubscribe()}}):a&&"function"==typeof a.then?h.Observable.fromPromise(a):h.Observable.of(a)};var h=a(0);a.n(h)},function(b,d,a){function h(a,c){return{start:Math.min(a.start,c.start),end:Math.max(a.end,c.end)}}function l(a,c){var e=a.end;return a.start<=c&&c<e} function g(a,c){return l(a,c.start)||a.start<c.end&&c.end<a.end||l(c,a.start)}function k(a){for(var c=[],e=0;e<a.length;e++)c.push({start:a.start(e),end:a.end(e)});return c}function f(a,c){for(var e=a.length-1;0<=e;e--){var f=a.start(e);if(c>=f){var k=a.end(e);if(c<k)return{start:f,end:k}}}return null}function c(a,c){for(var e=a.length,f=0;f<e;f++){var k=a.start(f);if(c<k)return k-c}return Infinity}function e(a,c){for(var e=null,f=[],k=a.length-1;0<=k;k--){var g=a.start(k),b=a.end(k);c<g||c>=b?f.push({start:g, end:b}):e={start:g,end:b}}return{outerRanges:f,innerRange:e}}function m(a,c){return(a=f(a,c))?a.end-a.start:0}function n(a,c){return(a=f(a,c))?c-a.start:0}function q(a,c){return(a=f(a,c))?a.end-c:Infinity}function r(a,c){if(c.start===c.end)return a;for(var e=0;e<a.length;e++){var f=a[e],k=g(c,f),b=Math.abs(f.start-c.end)<t||Math.abs(f.end-c.start)<t;if(k||b)c=h(c,f),a.splice(e--,1);else if(0===e){if(c.end<=a[0].start)break}else if(a[e-1].end<=c.start&&c.end<=f.start)break}a.splice(e,0,c);for(c=0;c< a.length;c++)e=a[c],e.start===e.end&&a.splice(c++,1);for(c=1;c<a.length;c++)if(e=a[c-1],f=a[c],Math.abs(f.start-e.end)<t||Math.abs(f.end-e.start)<t)e=h(e,f),a.splice(--c,2,e);return a}function p(a,c){for(var e=0;e<a.length;e++){var f=a[e];a:{var k=f;for(var b=c,m=0;m<b.length;m++)if(g(k,b[m])){k=b[m];break a}k=null}k?k.start>f.start?f.start=k.start:k.end<f.end&&(f.end=k.end):a.splice(e--,1)}return a}a.d(d,"h",function(){return k});a.d(d,"g",function(){return e});a.d(d,"a",function(){return q});a.d(d, "d",function(){return c});a.d(d,"c",function(){return n});a.d(d,"i",function(){return f});a.d(d,"b",function(){return m});a.d(d,"e",function(){return r});a.d(d,"f",function(){return p});var t=1/60},function(b,d,a){function h(a){return a.reduce(function(a,c){return a.concat(c instanceof e.UnsubscriptionError?c.errors:c)},[])}var l=a(26),g=a(84),k=a(51),f=a(52),c=a(33),e=a(262);b=function(){function a(a){this.closed=!1;this._subscriptions=this._parents=this._parent=null;a&&(this._unsubscribe=a)}a.prototype.unsubscribe= function(){var a=!1;if(!this.closed){var b=this._parent;var m=this._parents,d=this._unsubscribe,t=this._subscriptions;this.closed=!0;this._subscriptions=this._parents=this._parent=null;for(var u=-1,w=m?m.length:0;b;)b.remove(this),b=++u<w&&m[u]||null;if(k.isFunction(d)&&(b=f.tryCatch(d).call(this),b===c.errorObject)){a=!0;var x=x||(c.errorObject.e instanceof e.UnsubscriptionError?h(c.errorObject.e.errors):[c.errorObject.e])}if(l.isArray(t))for(u=-1,w=t.length;++u<w;)b=t[u],g.isObject(b)&&(b=f.tryCatch(b.unsubscribe).call(b), b===c.errorObject&&(a=!0,x=x||[],b=c.errorObject.e,b instanceof e.UnsubscriptionError?x=x.concat(h(b.errors)):x.push(b)));if(a)throw new e.UnsubscriptionError(x);}};a.prototype.add=function(c){if(!c||c===a.EMPTY)return a.EMPTY;if(c===this)return this;var e=c;switch(typeof c){case "function":e=new a(c);case "object":if(e.closed||"function"!==typeof e.unsubscribe)return e;if(this.closed)return e.unsubscribe(),e;"function"!==typeof e._addParent&&(c=e,e=new a,e._subscriptions=[c]);break;default:throw Error("unrecognized teardown "+ c+" added to Subscription.");}(this._subscriptions||(this._subscriptions=[])).push(e);e._addParent(this);return e};a.prototype.remove=function(a){var c=this._subscriptions;c&&(a=c.indexOf(a),-1!==a&&c.splice(a,1))};a.prototype._addParent=function(a){var c=this._parent,e=this._parents;c&&c!==a?e?-1===e.indexOf(a)&&e.push(a):this._parents=[a]:this._parent=a};a.EMPTY=function(a){a.closed=!0;return a}(new a);return a}();d.Subscription=b},function(b,d,a){b=a(264);a="undefined"!==typeof self&&"undefined"!== typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&self;b="undefined"!==typeof window&&window||"undefined"!==typeof b&&b||a;d.root=b;if(!b)throw Error("RxJS could not find any global context (window, self, global)");},function(b,d,a){function h(a){for(var c=a.length,e=new Uint8Array(c),f=0;f<c;f++)e[f]=a.charCodeAt(f)&255;return e}function l(a){return String.fromCharCode.apply(null,a)}function g(a){for(var c="",e=a.length,f=0;f<e;f+=2)c+=String.fromCharCode(a[f]);return c}function k(a){for(var c= a.length,e=new Uint8Array(c/2),f=0,k=0;f<c;f+=2,k++)e[k]=parseInt(a.substr(f,2),16)&255;return e}function f(a,c){c||(c="");for(var e="",f=0;f<a.byteLength;f++)e+=(a[f]>>>4).toString(16),e+=(a[f]&15).toString(16),c.length&&f<a.byteLength-1&&(e+=c);return e}function c(){for(var a=arguments.length,c=-1,e=0,f;++c<a;)f=arguments[c],e+="number"===typeof f?f:f.length;e=new Uint8Array(e);var k=0;for(c=-1;++c<a;)f=arguments[c],"number"===typeof f?k+=f:0<f.length&&(e.set(f,k),k+=f.length);return e}function e(a, c){return(a[0+c]<<8)+(a[1+c]<<0)}function m(a,c){return 65536*a[0+c]+256*a[1+c]+a[2+c]}function n(a,c){return 16777216*a[0+c]+65536*a[1+c]+256*a[2+c]+a[3+c]}function q(a,c){return 4294967296*(16777216*a[0+c]+65536*a[1+c]+256*a[2+c]+a[3+c])+16777216*a[4+c]+65536*a[5+c]+256*a[6+c]+a[7+c]}function r(a){return new Uint8Array([a>>>8&255,a&255])}function p(a){return new Uint8Array([a>>>24&255,a>>>16&255,a>>>8&255,a&255])}function t(a){var c=a%4294967296;a=(a-c)/4294967296;return new Uint8Array([a>>>24& 255,a>>>16&255,a>>>8&255,a&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255])}function u(a,c){return(a[0+c]<<0)+(a[1+c]<<8)}function w(a,c){return a[0+c]+256*a[1+c]+65536*a[2+c]+16777216*a[3+c]}function x(a){v.a.equal(a.length,16,"UUID length should be 16");var c=h(a);a=c[0];var e=c[1],k=c[2],b=c[3],g=c[4],m=c[5],n=c[6],l=c[7],d=c.subarray(8,10);c=c.subarray(10,16);var q=new Uint8Array(16);q[0]=b;q[1]=k;q[2]=e;q[3]=a;q[4]=m;q[5]=g;q[6]=l;q[7]=n;q.set(d,8);q.set(c,10);return f(q)}a.d(d,"b",function(){return h}); a.d(d,"a",function(){return l});a.d(d,"l",function(){return g});a.d(d,"k",function(){return k});a.d(d,"p",function(){return f});a.d(d,"i",function(){return c});a.d(d,"g",function(){return e});a.d(d,"h",function(){return m});a.d(d,"e",function(){return n});a.d(d,"f",function(){return q});a.d(d,"d",function(){return u});a.d(d,"c",function(){return w});a.d(d,"n",function(){return r});a.d(d,"j",function(){return p});a.d(d,"o",function(){return t});a.d(d,"m",function(){return x});var v=a(2)},function(b, d,a){var h=this&&this.__extends||function(a,b){function k(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(k.prototype=b.prototype,new k)};b=function(a){function b(){a.apply(this,arguments)}h(b,a);b.prototype.notifyNext=function(a,f,c,e,b){this.destination.next(f)};b.prototype.notifyError=function(a,f){this.destination.error(a)};b.prototype.notifyComplete=function(a){this.destination.complete()};return b}(a(3).Subscriber);d.OuterSubscriber= b},function(b,d,a){var h=this&&this.__extends||function(a,c){function e(){this.constructor=a}for(var f in c)c.hasOwnProperty(f)&&(a[f]=c[f]);a.prototype=null===c?Object.create(c):(e.prototype=c.prototype,new e)};b=a(0);var l=a(44),g=a(25),k=a(20);a=function(a){function c(c,f){a.call(this);this.array=c;this.scheduler=f;f||1!==c.length||(this._isScalar=!0,this.value=c[0])}h(c,a);c.create=function(a,f){return new c(a,f)};c.of=function(){for(var a=[],f=0;f<arguments.length;f++)a[f-0]=arguments[f];f=a[a.length- 1];k.isScheduler(f)?a.pop():f=null;var b=a.length;return 1<b?new c(a,f):1===b?new l.ScalarObservable(a[0],f):new g.EmptyObservable(f)};c.dispatch=function(a){var c=a.array,e=a.index,f=a.subscriber;e>=a.count?f.complete():(f.next(c[e]),f.closed||(a.index=e+1,this.schedule(a)))};c.prototype._subscribe=function(a){var e=this.array,f=e.length,k=this.scheduler;if(k)return k.schedule(c.dispatch,0,{array:e,index:0,count:f,subscriber:a});for(k=0;k<f&&!a.closed;k++)a.next(e[k]);a.complete()};return c}(b.Observable); d.ArrayObservable=a},function(b,d,a){var h=a(12),l=a(81),g=a(85),k=a(84),f=a(0),c=a(47),e=a(172),m=a(48);d.subscribeToResult=function(a,b,d,p){var n=new e.InnerSubscriber(a,d,p);if(n.closed)return null;if(b instanceof f.Observable)if(b._isScalar)n.next(b.value),n.complete();else return b.subscribe(n);else if(l.isArrayLike(b)){a=0;for(d=b.length;a<d&&!n.closed;a++)n.next(b[a]);n.closed||n.complete()}else{if(g.isPromise(b))return b.then(function(a){n.closed||(n.next(a),n.complete())},function(a){return n.error(a)}).then(null, function(a){h.root.setTimeout(function(){throw a;})}),n;if(b&&"function"===typeof b[c.iterator]){b=b[c.iterator]();do{a=b.next();if(a.done){n.complete();break}n.next(a.value);if(n.closed)break}while(1)}else if(b&&"function"===typeof b[m.observable])if(b=b[m.observable](),"function"!==typeof b.subscribe)n.error(new TypeError("Provided object does not correctly implement Symbol.observable"));else return b.subscribe(new e.InnerSubscriber(a,d,p));else b=k.isObject(b)?"an invalid object":"'"+b+"'",n.error(new TypeError("You provided "+ b+" where a stream was expected. You can provide an Observable, Promise, Array, or Iterable."))}return null}},function(b,d,a){function h(a,c){return c.filter(function(c){var e=document.createElement(a.tagName);c="on"+c;c in e?e=!0:(e.setAttribute(c,"return;"),e="function"==typeof e[c]);return e})[0]}function l(a,e){return a.reduce(function(a,f){return a.concat((e||c.g).map(function(a){return a+f}))},[])}function g(e,b){var g=void 0;e=l(e,b);return function(b){return b instanceof c.h?("undefined"== typeof g&&(g=h(b,e)||null),g?k.Observable.fromEvent(b,g):k.Observable.never()):a.i(f.a)(b,e)}}a.d(d,"b",function(){return q});a.d(d,"c",function(){return r});a.d(d,"f",function(){return p});a.d(d,"a",function(){return t});a.d(d,"e",function(){return u});a.d(d,"d",function(){return w});a.d(d,"i",function(){return x});a.d(d,"g",function(){return v});a.d(d,"h",function(){return y});a.d(d,"j",function(){return z});var k=a(0);a.n(k);b=a(4);a(1);var f=a(31),c=a(34);b=b.a.INACTIVITY_DELAY;var e=window.devicePixelRatio|| 1;d=function(){var c=void 0;null!=document.hidden?c="":null!=document.mozHidden?c="moz":null!=document.msHidden?c="ms":null!=document.webkitHidden&&(c="webkit");var e=c?c+"Hidden":"hidden";c+="visibilitychange";return a.i(f.a)(document,c).map(function(){return document[e]})};var m=d().filter(function(a){return!1===a}),n=d().debounceTime(b).filter(function(a){return!0===a}),q=function(){return k.Observable.merge(m,n).startWith(!1)},r=function(c){return k.Observable.merge(k.Observable.interval(2E4), a.i(f.a)(window,"resize").debounceTime(500)).startWith("init").map(function(){return c.clientWidth*e}).distinctUntilChanged()},p=g(["loadedmetadata"]),t=g(["fullscreenchange","FullscreenChange"],c.g.concat("MS")),u=g(["sourceopen","webkitsourceopen"]),w=g(["encrypted","needkey"]),x=g(["keymessage","message"]),v=g(["keyadded","ready"]),y=g(["keyerror","error"]),z=g(["keystatuseschange"])},function(b,d,a){a.d(d,"a",function(){return h});a.d(d,"c",function(){return l});a.d(d,"b",function(){return g}); b=a(165);var h=a.i(b.a)(["NETWORK_ERROR","MEDIA_ERROR","ENCRYPTED_MEDIA_ERROR","INDEX_ERROR","OTHER_ERROR"]),l=a.i(b.a)(["TIMEOUT","ERROR_EVENT","ERROR_HTTP_CODE","PARSE_ERROR"]),g=a.i(b.a)("PIPELINE_RESOLVE_ERROR PIPELINE_LOAD_ERROR PIPELINE_PARSING_ERROR MANIFEST_PARSE_ERROR MANIFEST_INCOMPATIBLE_CODECS_ERROR MEDIA_IS_ENCRYPTED_ERROR KEY_ERROR KEY_STATUS_CHANGE_ERROR KEY_UPDATE_ERROR KEY_LOAD_ERROR KEY_LOAD_TIMEOUT KEY_GENERATE_REQUEST_ERROR INCOMPATIBLE_KEYSYSTEMS LICENSE_SERVER_CERTIFICATE_ERROR BUFFER_APPEND_ERROR BUFFER_FULL_ERROR BUFFER_TYPE_UNKNOWN MEDIA_ERR_ABORTED MEDIA_ERR_NETWORK MEDIA_ERR_DECODE MEDIA_ERR_SRC_NOT_SUPPORTED MEDIA_SOURCE_NOT_SUPPORTED MEDIA_KEYS_NOT_SUPPORTED OUT_OF_INDEX_ERROR UNKNOWN_INDEX".split(" "))}, function(b,d,a){d.a=function(a,b,g){if("function"===typeof Array.prototype.includes)return a.includes(b,g);var k=a.length>>>0;if(0===k)return!1;g|=0;for(g=Math.max(0<=g?g:k-Math.abs(g),0);g<k;){var f=a[g],c=b;if(f===c||"number"===typeof f&&"number"===typeof c&&isNaN(f)&&isNaN(c))return!0;g++}return!1}},function(b,d,a){d.isScheduler=function(a){return a&&"function"===typeof a.schedule}},function(b,d,a){b.exports=function(a,b,g){if("function"===typeof Array.prototype.find)return a.find(b,g);g=g||this; var k=a.length,f;if("function"!==typeof b)throw new TypeError(b+" is not a function");for(f=0;f<k;f++)if(b.call(g,a[f],f,a))return a[f]}},function(b,d,a){d.a=function(a,b,g){return a+"("+b+")"+(g?": "+g.message:"")}},function(b,d,a){a.d(d,"d",function(){return l});a.d(d,"e",function(){return g});a.d(d,"a",function(){return k});a.d(d,"b",function(){return f});a.d(d,"c",function(){return c});a(2);var h=a(27),l=function(a,c,f){var e=a.presentationTimeOffset||0;a=a.timescale||1;return{up:c*a-e,to:(c+ f)*a-e}},g=function(a){var c=a.ts,e=a.d;a=a.r;return-1===e?c:c+(a+1)*e},k=function(a,c){var e=c.initialization;e=void 0===e?{}:e;return new h.a({id:""+a+"_init",init:!0,range:e.range||null,indexRange:c.indexRange||null,media:e.media,timescale:c.timescale})},f=function(a,c){a.timescale!==c&&(a.timescale=c);return a},c=function(a,c){return c/a.timescale}},function(b,d,a){function h(){for(var a=arguments.length,c=Array(a),e=0;e<a;e++)c[e]=arguments[e];a=c.length;if(0===a)return"";e="";for(var b=0;b< a;b++){var n=c[b];"string"===typeof n&&""!==n&&(g.test(n)?e=n:("/"===n[0]&&(n=n.substr(1)),"/"===e[e.length-1]&&(e=e.substr(0,e.length-1)),e=e+"/"+n))}a=e;if(k.test(a)){c=[];a=a.split("/");e=0;for(b=a.length;e<b;e++)".."==a[e]?c.pop():"."!=a[e]&&c.push(a[e]);c=c.join("/")}else c=a;return c}function l(a){var c=a.lastIndexOf("/");return 0<=c?a.substring(0,c+1):a}a.d(d,"b",function(){return h});a.d(d,"a",function(){return l});var g=/^(?:[a-z]+:)?\/\//i,k=/\/\.{1,2}\//},function(b,d,a){var h=this&&this.__extends|| function(a,b){function k(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(k.prototype=b.prototype,new k)};b=function(a){function b(b){a.call(this);this.scheduler=b}h(b,a);b.create=function(a){return new b(a)};b.dispatch=function(a){a.subscriber.complete()};b.prototype._subscribe=function(a){var f=this.scheduler;if(f)return f.schedule(b.dispatch,0,{subscriber:a});a.complete()};return b}(a(0).Observable);d.EmptyObservable=b},function(b,d,a){d.isArray= Array.isArray||function(a){return a&&"number"===typeof a.length}},function(b,d,a){d.a=function l(){var a=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};if(!(this instanceof l))throw new TypeError("Cannot call a class as a function");this.id=a.id;this.duration=a.duration;this.isInit=!!a.init;this.range=a.range;this.time=a.time;this.indexRange=a.indexRange;this.number=a.number;this.timescale=null==a.timescale?1:a.timescale;this.media=a.media}},function(b,d,a){function h(a,e){return new Date(1E3* (a+e.availabilityStartTime))}function l(a,e){var c=e.suggestedPresentationDelay,f=e.presentationLiveGap,b=e.timeShiftBufferDepth;"number"!=typeof a&&(a=a.getTime());var k=Date.now();return Math.max(Math.min(a,k-1E3*(f+c)),k-1E3*b)/1E3-e.availabilityStartTime}function g(a){return f(a)[0]}function k(a){if(!a.isLive)return a.getDuration();var c=a.availabilityStartTime;a=a.presentationLiveGap;return Date.now()/1E3-c-a}function f(a){if(!a.isLive)return[0,a.getDuration()];var c=a.availabilityStartTime, f=a.presentationLiveGap;a=a.timeShiftBufferDepth;c=Date.now()/1E3-c-f;return[Math.min(c,c-a+5),c]}a.d(d,"a",function(){return h});a.d(d,"b",function(){return l});a.d(d,"c",function(){return g});a.d(d,"d",function(){return k});a.d(d,"e",function(){return f})},function(b,d,a){function h(){this.__listeners={}}var l=a(1),g=a(2);h.prototype.addEventListener=function(b,f){a.i(g.a)("function"==typeof f,"eventemitter: second argument should be a function");this.__listeners[b]||(this.__listeners[b]=[]);this.__listeners[b].push(f)}; h.prototype.removeEventListener=function(a,f){if(0===arguments.length)this.__listeners={};else if(this.__listeners.hasOwnProperty(a))if(1===arguments.length)delete this.__listeners[a];else{var c=this.__listeners[a],e=c.indexOf(f);~e&&c.splice(e,1);c.length||delete this.__listeners[a]}};h.prototype.trigger=function(a,f){this.__listeners.hasOwnProperty(a)&&this.__listeners[a].slice().forEach(function(a){try{a(f)}catch(e){l.a.error(e,e.stack)}})};h.prototype.on=h.prototype.addEventListener;h.prototype.off= h.prototype.removeEventListener;d.a=h},function(b,d,a){function h(a){if(null!=a){if("string"===typeof a){var c=a;a=!1}else c=a.language,a=!!a.closedCaption;return{language:c,closedCaption:a,normalized:g(c)}}return a}function l(a){if(null!=a){if("string"===typeof a){var c=a;a=!1}else c=a.language,a=!!a.audioDescription;return{language:c,audioDescription:a,normalized:g(c)}}return a}function g(a){if(null==a||""===a)return"";a=(""+a).toLowerCase().split("-");var c=a[0],b=void 0;2===c.length?b=k.a[c]: 3===c.length&&(b=f.a[c]);(c=b||c)&&(a[0]=c);return a.join("-")}a.d(d,"a",function(){return g});a.d(d,"b",function(){return l});a.d(d,"c",function(){return h});var k=a(163),f=a(164)},function(b,d,a){d.a=function(a,b){return Array.isArray(b)?h.Observable.merge.apply(null,b.map(function(b){return h.Observable.fromEvent(a,b)})):h.Observable.fromEvent(a,b)};var h=a(0);a.n(h)},function(b,d,a){b=a(78);a=a(79);d.async=new a.AsyncScheduler(b.AsyncAction)},function(b,d,a){d.errorObject={e:{}}},function(b,d, a){a.d(d,"g",function(){return h});a.d(d,"h",function(){return l});a.d(d,"e",function(){return g});a.d(d,"a",function(){return k});a.d(d,"f",function(){return f});a.d(d,"b",function(){return c});a.d(d,"d",function(){return e});a.d(d,"c",function(){return m});b=window;var h=["","webkit","moz","ms"],l=b.HTMLElement,g=b.HTMLVideoElement,k=b.MediaSource||b.MozMediaSource||b.WebKitMediaSource||b.MSMediaSource,f=b.MediaKeys||b.MozMediaKeys||b.WebKitMediaKeys||b.MSMediaKeys;f||(b=function(){throw new MediaError("MEDIA_KEYS_NOT_SUPPORTED", null,!0);},f={create:b,isTypeSupported:b});var c="Microsoft Internet Explorer"==navigator.appName||"Netscape"==navigator.appName&&/(Trident|Edge)\//.test(navigator.userAgent),e=-1!==navigator.userAgent.toLowerCase().indexOf("firefox"),m={HAVE_NOTHING:0,HAVE_METADATA:1,HAVE_CURRENT_DATA:2,HAVE_FUTURE_DATA:3,HAVE_ENOUGH_DATA:4}},function(b,d,a){a.d(d,"a",function(){return h});var h={STOPPED:"STOPPED",LOADED:"LOADED",LOADING:"LOADING",PLAYING:"PLAYING",PAUSED:"PAUSED",ENDED:"ENDED",BUFFERING:"BUFFERING", SEEKING:"SEEKING"}},function(b,d,a){a.d(d,"a",function(){return h});a.d(d,"b",function(){return l});b=a(113);var h=new b.a({load:function(){return[]},save:function(){}}),l=new b.b},function(b,d,a){Object.defineProperty(d,"__esModule",{value:!0});var h=a(27),l=a(23),g=function(a,f){a=a.timeline;for(var c=0,e=a.length;c<e;){var b=c+e>>>1;a[b].ts<f?c=b+1:e=b}return 0<c?c-1:c};d["default"]={getInitSegment:l.a,setTimescale:l.b,scale:l.c,getSegments:function(b,f,c,e){e=a.i(l.d)(f,c,e);c=e.up;e=e.to;var k= f.timeline,n=f.timescale,d=f.media,r=[],p=k.length;f=g(f,c)-1;var t=k.length&&k[0].d||0;a:for(;!(++f>=p);){var u=k[f],w=u.d,x=u.ts,v=u.range;t=Math.max(t,w);if(0>w){x+t<e&&r.push(new h.a({id:""+b+"_"+x,time:x,init:!1,range:v,duration:void 0,indexRange:null,timescale:n,media:d}));break}var y=k[f+1],z=u.r||0;0>z&&(z=Math.ceil(((y?y.t:Infinity)-u.ts)/u.d)-1);u=z;y=c-x;y=0<y?Math.floor(y/w):0;for(;(z=x+y*w)<e;)if(y++<=u)r.push(new h.a({id:""+b+"_"+z,time:z,init:!1,range:v,duration:w,indexRange:null,timescale:n, media:d}));else continue a;break}return r},shouldRefresh:function(b,f,c,e){c=b.timeline;f=b.timescale;b=b.presentationTimeOffset;c=c[c.length-1];if(!c)return!1;0>c.d&&(c={ts:c.ts,d:0,r:c.r});return!(e*f-(void 0===b?0:b)<=a.i(l.e)(c))},getFirstPosition:function(a){if(a.timeline.length)return a.timeline[0].ts/a.timescale},getLastPosition:function(b){if(b.timeline.length){var f=b.timeline[b.timeline.length-1];return a.i(l.e)(f)/b.timescale}},checkDiscontinuity:function(b,f){var c=b.timeline,e=b.timescale; e=void 0===e?1:e;f*=e;if(0>=f)return-1;var k=g(b,f);if(0>k||k>=c.length-1)return-1;var n=c[k];if(-1===n.d)return-1;b=n.ts;n=a.i(l.e)(n);c=c[k+1];return n!==c.ts&&f>=b&&f<=n&&n-f<e?c.ts/e:-1},_addSegmentInfos:function(b,f,c){var e=b.timeline,k=b.timescale,g=e.length,d=e[g-1];f=f.timescale===k?{time:f.time,duration:f.duration}:{time:f.time/f.timescale*k,duration:f.duration/f.timescale*k};var h=void 0;c&&(h=c.timescale===k?c.time:c.time/c.timescale*k);if(null!=h&&f.time===h){c=f.time+f.duration;k=c- (d.ts+d.d*d.r);if(0>=k)return!1;-1===d.d&&((g=e[g-2])&&g.d===k?(g.r++,e.pop()):d.d=k);b.timeline.push({d:-1,ts:c,r:0});return!0}return f.time>=a.i(l.e)(d)?(d.d===f.duration?d.r++:b.timeline.push({d:f.duration,ts:f.time,r:0}),!0):!1}}},function(b,d,a){function h(c,e){for(var f=c.length,b=0,k,g=void 0;b+8<f&&(g=a.i(r.e)(c,b),k=a.i(r.e)(c,b+4),a.i(q.a)(0<g,"out of range size"),k!==e);)b+=g;if(b>=f)return-1;a.i(q.a)(b+g<=f,"atom out of range");return b}function l(c,e){var f=h(c,1936286840);if(-1==f)return null; var b=a.i(r.e)(c,f);f=f+4+4;var k=c[f];f+=8;var g=a.i(r.e)(c,f);f+=4;if(0===k)k=a.i(r.e)(c,f),f+=4,e+=a.i(r.e)(c,f)+b,f+=4;else if(1===k)k=a.i(r.f)(c,f),f+=8,e+=a.i(r.f)(c,f)+b,f+=8;else return null;b=[];f+=2;var m=a.i(r.g)(c,f);for(f+=2;0<=--m;){var n=a.i(r.e)(c,f);f+=4;var d=n&2147483647;if(1==(n&2147483648)>>>31)throw Error("not implemented");n=a.i(r.e)(c,f);f+=4;f+=4;b.push({time:k,duration:n,count:0,timescale:g,range:[e,e+d-1]});k+=n;e+=d}return b}function g(e){e=c(e,1836019558);if(!e)return-1; e=c(e,1953653094);if(!e)return-1;var f=h(e,1952867444);if(-1==f)return-1;f=f+4+4;var b=e[f];f+=4;return 1<b?-1:b?a.i(r.f)(e,f):a.i(r.e)(e,f)}function k(e){e=c(e,1836019558);if(!e)return-1;e=c(e,1953653094);if(!e)return-1;var f=h(e,1953658222);if(-1==f)return-1;f=f+4+4;var b=e[f];f+=1;if(1<b)return-1;var k=a.i(r.h)(e,f);f+=3;b=k&256;var g=0;if(!b)return f=h(e,1952868452),-1==f?g=-1:(f=f+4+4+1,b=a.i(r.h)(e,f),b&8?(f+=4,b&1&&(f+=8),b&2&&(f+=4),g=a.i(r.e)(e,f)):g=-1),0<=g?g:-1;var m=k&1,n=k&4,d=k&512, l=k&1024;k&=2048;var q=a.i(r.e)(e,f);f+=4;m&&(f+=4);n&&(f+=4);m=q;for(n=0;m--;)b?(n+=a.i(r.e)(e,f),f+=4):n+=g,d&&(f+=4),l&&(f+=4),k&&(f+=4);return n}function f(e){e=c(e,1836019574);if(!e)return-1;e=c(e,1953653099);if(-1==f)return-1;e=c(e,1835297121);if(-1==f)return-1;var f=h(e,1835296868);if(f/-1)return-1;f=f+4+4;var b=e[f];f+=4;return 1===b?(f+=16,a.i(r.e)(e,f)):0==b?(f+=8,a.i(r.e)(e,f)):-1}function c(c,e){for(var f=c.length,b=0,k,g=void 0;b+8<f&&(g=a.i(r.e)(c,b),k=a.i(r.e)(c,b+4),a.i(q.a)(0<g,"out of range size"), k!==e);)b+=g;return b<f?c.subarray(b+8,b+g):null}function e(a){return c(a,1835295092)}function m(c){var e=c.systemId;c=c.privateData;e=e.replace(/-/g,"");a.i(q.a)(32===e.length);e=a.i(r.i)(4,a.i(r.k)(e),a.i(r.j)(c.length),c);c=e.length+8;return a.i(r.i)(a.i(r.j)(c),a.i(r.b)("pssh"),e)}function n(c,e){if(!e||!e.length)return c;var f=h(c,1836019574);if(-1==f)return c;for(var b=a.i(r.e)(c,f),k=[c.subarray(f,f+b)],g=0;g<e.length;g++)k.push(m(e[g]));k=r.i.apply(null,k);k.set(a.i(r.j)(k.length),0);return a.i(r.i)(c.subarray(0, f),k,c.subarray(f+b))}a.d(d,"b",function(){return f});a.d(d,"e",function(){return g});a.d(d,"f",function(){return k});a.d(d,"a",function(){return l});a.d(d,"d",function(){return e});a.d(d,"c",function(){return n});var q=a(2),r=a(13)},function(b,d,a){function h(c,e){var f=e.length+8,b=a.i(n.i);f=a.i(n.j)(f);if(r[c])c=r[c];else{var k=a.i(n.b)(c);c=r[c]=k}return b(f,c,e)}function l(c,e,f,b,k){for(var g=c.length,m=0,d;m<g;){d=a.i(n.e)(c,m);if(1970628964===a.i(n.e)(c,m+4)&&a.i(n.e)(c,m+8)===e&&a.i(n.e)(c, m+12)===f&&a.i(n.e)(c,m+16)===b&&a.i(n.e)(c,m+20)===k)return c.subarray(m+24,m+d);m+=d}}function g(c,f){for(var b=c.length,k=0,g,m=void 0;k+8<b&&(m=a.i(n.e)(c,k),g=a.i(n.e)(c,k+4),a.i(e.a)(0<m,"smooth: out of range size"),g!==f);)k+=m;return k<b?c.subarray(k+8,k+m):null}function k(a,c,e,f){var b=[a,c,e];f.forEach(function(a){a=p.pssh(a.systemId,a.privateData,a.keyIds);b.push(a)});return b}function f(c,e,f,b){var k=c.length,g=e.length;f=f.length;c=c.subarray(f,k);k=new Uint8Array(g+(k-f));k.set(e, 0);k.set(c,g);e=e.length+8;k.set(a.i(n.j)(e),b+16);return k}function c(c,e,f,b,g,m,d){f=p.mult("stbl",[f,h("stts",new Uint8Array(8)),h("stsc",new Uint8Array(8)),h("stsz",new Uint8Array(12)),h("stco",new Uint8Array(8))]);var l=h("url ",new Uint8Array([0,0,0,1]));l=p.dref(l);l=p.mult("dinf",[l]);b=p.mult("minf",[b,l,f]);e=p.hdlr(e);f=p.mdhd(c);e=p.mult("mdia",[f,e,b]);g=p.tkhd(g,m,1);g=p.mult("trak",[g,e]);m=p.trex(1);m=p.mult("mvex",[m]);c=p.mvhd(c,1);d=p.mult("moov",k(c,m,g,d));c=p.ftyp("isom",["isom", "iso2","iso6","avc1","dash"]);return a.i(n.i)(c,d)}var e=a(2),m=a(7),n=a(13),q=[96E3,88200,64E3,48E3,44100,32E3,24E3,22050,16E3,12E3,11025,8E3,7350],r={},p={mult:function(a,c){return h(a,n.i.apply(null,c))},avc1encv:function(c,e,f,b,k,g,m,d,l,q){return h(c,a.i(n.i)(6,a.i(n.n)(e),16,a.i(n.n)(f),a.i(n.n)(b),a.i(n.n)(k),2,a.i(n.n)(g),6,[0,1,m.length],a.i(n.b)(m),31-m.length,a.i(n.n)(d),[255,255],l,"encv"===c?q:[]))},avcc:function(c,e,f){f=2===f?1:4===f?3:0;var b=c[1],k=c[2],g=c[3];return h("avcC",a.i(n.i)([1, b,k,g,252|f,225],a.i(n.n)(c.length),c,[1],a.i(n.n)(e.length),e))},dref:function(c){return h("dref",a.i(n.i)(7,[1],c))},esds:function(c,e){return h("esds",a.i(n.i)(4,[3,25],a.i(n.n)(c),[0,4,17,64,21],11,[5,2],a.i(n.k)(e),[6,1,2]))},frma:function(c){return h("frma",a.i(n.b)(c))},free:function(a){return h("free",new Uint8Array(a-8))},ftyp:function(c,e){return h("ftyp",n.i.apply(null,[a.i(n.b)(c),[0,0,0,1]].concat(e.map(n.b))))},hdlr:function(c){switch(c){case "video":c="vide";var e="VideoHandler";break; case "audio":c="soun";e="SoundHandler";break;default:c="hint",e=""}return h("hdlr",a.i(n.i)(8,a.i(n.b)(c),12,a.i(n.b)(e),1))},mdhd:function(c){return h("mdhd",a.i(n.i)(12,a.i(n.j)(c),8))},moof:function(a,c){return p.mult("moof",[a,c])},mp4aenca:function(c,e,f,b,k,g,m,d){return h(c,a.i(n.i)(6,a.i(n.n)(e),8,a.i(n.n)(f),a.i(n.n)(b),2,a.i(n.n)(k),a.i(n.n)(g),2,m,"enca"===c?d:[]))},mvhd:function(c,e){return h("mvhd",a.i(n.i)(12,a.i(n.j)(c),4,[0,1],2,[1,0],10,[0,1],14,[0,1],14,[64,0,0,0],26,a.i(n.n)(e+ 1)))},pssh:function(c){var f=1<arguments.length&&void 0!==arguments[1]?arguments[1]:[],b=2<arguments.length&&void 0!==arguments[2]?arguments[2]:[];c=c.replace(/-/g,"");a.i(e.a)(32===c.length,"wrong system id length");var k=b.length;if(0<k){var g=1;b=n.i.apply(null,[a.i(n.j)(k)].concat(b))}else g=0,b=[];return h("pssh",a.i(n.i)([g,0,0,0],a.i(n.k)(c),b,a.i(n.j)(f.length),f))},saio:function(c,e,f,b){return h("saio",a.i(n.i)(4,[0,0,0,1],a.i(n.j)(c.length+e.length+f.length+b.length+8+8+8+8)))},saiz:function(c){if(0=== c.length)return h("saiz",new Uint8Array);var e=a.i(n.e)(c,0),f=a.i(n.e)(c,4),b=new Uint8Array(9+f);b.set(a.i(n.j)(f),5);f=9;for(var k=8,g,m;k<c.length;)k+=8,2===(e&2)?(m=2,g=a.i(n.g)(c,k),k+=2+6*g):m=g=0,b[f]=6*g+8+m,f++;return h("saiz",b)},schm:function(c,e){return h("schm",a.i(n.i)(4,a.i(n.b)(c),a.i(n.j)(e)))},senc:function(a){return h("senc",a)},smhd:function(){return h("smhd",new Uint8Array(8))},stsd:function(a){return h("stsd",n.i.apply(null,[7,[a.length]].concat(a)))},tkhd:function(c,e,f){return h("tkhd", a.i(n.i)(a.i(n.j)(7),8,a.i(n.j)(f),20,[1,0,0,0],[0,1,0,0],12,[0,1,0,0],12,[64,0,0,0],a.i(n.n)(c),2,a.i(n.n)(e),2))},trex:function(c){return h("trex",a.i(n.i)(4,a.i(n.j)(c),[0,0,0,1],12))},tfdt:function(c){return h("tfdt",a.i(n.i)([1,0,0,0],a.i(n.o)(c)))},tenc:function(c,e,f){return h("tenc",a.i(n.i)(6,[c,e],a.i(n.k)(f)))},traf:function(a,c,e,f,b){var k=[a,c,e];f&&k.push(p.senc(f),p.saiz(f),p.saio(b,a,c,e));return p.mult("traf",k)},trun:function(c){if(c[11]&1)return c;var e=new Uint8Array(c.length+ 4);e.set(a.i(n.j)(c.length+4),0);e.set(c.subarray(4,16),4);e[11]|=1;e.set([0,0,0,0],16);e.set(c.subarray(16,c.length),20);return e},vmhd:function(){var a=new Uint8Array(12);a[3]=1;return h("vmhd",a)}},t={traf:function(a){return(a=g(a,1836019558))?g(a,1953653094):null},senc:function(a){return l(a,2721664850,1520127764,2722393154,2086964724)},tfxd:function(a){return l(a,1830656773,1121273062,2162299933,2952222642)},tfrf:function(a){return l(a,3565190898,3392751253,2387879627,2655430559)},mdat:function(a){return g(a, 1835295092)}};d.a={getMdat:t.mdat,getTraf:t.traf,parseTfrf:function(c){c=t.tfrf(c);if(!c)return[];for(var e=[],f=c[0],b=c[4],k=0;k<b;k++){if(1==f){var g=a.i(n.f)(c,16*k+5);var m=a.i(n.f)(c,16*k+13)}else g=a.i(n.e)(c,8*k+5),m=a.i(n.e)(c,8*k+9);e.push({time:g,duration:m})}return e},parseTfxd:function(c){if(c=t.tfxd(c))return{duration:a.i(n.f)(c,12),time:a.i(n.f)(c,4)}},createVideoInitSegment:function(e,f,b,k,g,m,d,l,h){h||(h=[]);var q=d.split("00000001");d=q[1];q=q[2];d=a.i(n.k)(d);q=a.i(n.k)(q);m= p.avcc(d,q,m);h.length?(l=p.tenc(1,8,l),l=p.mult("schi",[l]),d=p.schm("cenc",65536),q=p.frma("avc1"),l=p.mult("sinf",[q,d,l]),k=p.avc1encv("encv",1,f,b,k,g,"AVC Coding",24,m,l)):k=p.avc1encv("avc1",1,f,b,k,g,"AVC Coding",24,m);k=p.stsd([k]);return c(e,"video",k,p.vmhd(),f,b,h)},createAudioInitSegment:function(e,f,b,k,g,m,d,l){l||(l=[]);m||(m=(32|q.indexOf(g)&31)<<4,m=(m|f&31)<<3,m=a.i(n.p)(a.i(n.n)(m)));m=p.esds(1,m);if(l.length){d=p.tenc(1,8,d);d=p.mult("schi",[d]);var h=p.schm("cenc",65536),r=p.frma("mp4a"); d=p.mult("sinf",[r,h,d]);f=p.mp4aenca("enca",1,f,b,k,g,m,d)}else f=p.mp4aenca("mp4a",1,f,b,k,g,m);f=p.stsd([f]);return c(e,"audio",f,p.smhd(),0,0,l)},patchSegment:function(c,e){var b=c.subarray(0,a.i(n.e)(c,0)),k=p.tfdt(e);e=k.length;var g=a.i(n.e)(b,8),d=a.i(n.e)(b,8+g),l=a.i(n.e)(b,8+g+8),h=a.i(n.e)(b,8+g+8+l),q=b.subarray(8,8+g),r=b.subarray(8+g+8,8+g+8+d-8);d=r.subarray(0,l);h=r.subarray(l,l+h);d.set([0,0,0,1],12);r=t.senc(r);h=p.trun(h);k=p.traf(d,k,h,r,q);q=p.moof(q,k);e=8+g+8+l+e;return m.r? f(c,q,b,e):8<=b.length-q.length?(b=b.length-q.length,c.set(q,0),c.set(p.free(b),q.length),b=q.length+8+b,c.set(a.i(n.j)(b),e+16),c):f(c,q,b,e)}}},function(b,d,a){var h=0;d.a=function(){var a=0;h<Number.MAX_VALUE&&(a=h+1);h=a;return""+a}},function(b,d,a){var h=a(0);a.n(h);var l=a(6);d.a=function(a){var b={url:"",headers:null,method:"GET",responseType:"json",timeout:3E4,body:void 0},f;for(f in b)a.hasOwnProperty(f)&&(b[f]=a[f]);return h.Observable.create(function(c){var e=b.url,f=b.headers,k=b.responseType, g=b.timeout,d=b.body,h=new XMLHttpRequest;h.open(b.method,e,!0);0<=g&&(h.timeout=g);h.responseType=k;"document"===h.responseType&&h.overrideMimeType("text/xml");if(f)for(var t in f)h.setRequestHeader(t,f[t]);var u=Date.now();h.onerror=function(){c.error(new l.h(h,e,l.j.ERROR_EVENT))};h.ontimeout=function(){c.error(new l.h(h,e,l.j.TIMEOUT))};a.ignoreProgressEvents||(h.onprogress=function(a){c.next({type:"progress",value:{url:e,sentTime:u,currentTime:Date.now(),loadedSize:a.loaded,totalSize:a.total}})}); h.onload=function(a){if(4===h.readyState)if(200<=h.status&&300>h.status){var f=Date.now();a=a.total;var b=h.status,k=h.responseType,g=h.responseURL||e,m=void 0;if("json"===k)if("string"!=typeof h.response)m=h.response;else try{m=JSON.parse(h.responseText)}catch(C){m=null}else m=h.response;null==m?c.error(new l.h(h,g,l.j.PARSE_ERROR)):(c.next({type:"response",value:{status:b,url:g,responseType:k,sentTime:u,receivedTime:f,size:a,responseData:m}}),c.complete())}else c.error(new l.h(h,e,l.j.ERROR_HTTP_CODE))}; void 0!==d?h.send(d):h.send();return function(){h&&4!==h.readyState&&h.abort()}})}},function(b,d,a){d.a=function(a,b){try{return a(b)}catch(k){return h.Observable.throw(k)}};var h=a(0);a.n(h)},function(b,d,a){var h=this&&this.__extends||function(a,b){function f(){this.constructor=a}for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);a.prototype=null===b?Object.create(b):(f.prototype=b.prototype,new f)};b=a(5);var l=a(50);a=function(a){function b(f){a.call(this);this._value=f}h(b,a);Object.defineProperty(b.prototype, "value",{get:function(){return this.getValue()},enumerable:!0,configurable:!0});b.prototype._subscribe=function(f){var c=a.prototype._subscribe.call(this,f);c&&!c.closed&&f.next(this._value);return c};b.prototype.getValue=function(){if(this.hasError)throw this.thrownError;if(this.closed)throw new l.ObjectUnsubscribedError;return this._value};b.prototype.next=function(f){a.prototype.next.call(this,this._value=f)};return b}(b.Subject);d.BehaviorSubject=a},function(b,d,a){var h=this&&this.__extends|| function(a,b){function k(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(k.prototype=b.prototype,new k)};b=function(a){function b(b,f){a.call(this);this.value=b;this.scheduler=f;this._isScalar=!0;f&&(this._isScalar=!1)}h(b,a);b.create=function(a,f){return new b(a,f)};b.dispatch=function(a){var f=a.value,c=a.subscriber;a.done?c.complete():(c.next(f),c.closed||(a.done=!0,this.schedule(a)))};b.prototype._subscribe=function(a){var f=this.value, c=this.scheduler;if(c)return c.schedule(b.dispatch,0,{done:!1,value:f,subscriber:a});a.next(f);a.closed||a.complete()};return b}(a(0).Observable);d.ScalarObservable=b},function(b,d,a){var h=this&&this.__extends||function(a,c){function e(){this.constructor=a}for(var f in c)c.hasOwnProperty(f)&&(a[f]=c[f]);a.prototype=null===c?Object.create(c):(e.prototype=c.prototype,new e)};b=a(14);var l=a(16);d.mergeAll=function(a){void 0===a&&(a=Number.POSITIVE_INFINITY);return this.lift(new g(a))};var g=function(){function a(a){this.concurrent= a}a.prototype.call=function(a,e){return e.subscribe(new k(a,this.concurrent))};return a}();d.MergeAllOperator=g;var k=function(a){function c(c,f){a.call(this,c);this.concurrent=f;this.hasCompleted=!1;this.buffer=[];this.active=0}h(c,a);c.prototype._next=function(a){this.active<this.concurrent?(this.active++,this.add(l.subscribeToResult(this,a))):this.buffer.push(a)};c.prototype._complete=function(){this.hasCompleted=!0;0===this.active&&0===this.buffer.length&&this.destination.complete()};c.prototype.notifyComplete= function(a){var c=this.buffer;this.remove(a);this.active--;0<c.length?this._next(c.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()};return c}(b.OuterSubscriber);d.MergeAllSubscriber=k},function(b,d,a){var h=a(214);d.multicast=function(a,b){var f="function"===typeof a?a:function(){return a};if("function"===typeof b)return this.lift(new l(f,b));b=Object.create(this,h.connectableObservableDescriptor);b.source=this;b.subjectFactory=f;return b};var l=function(){function a(a,f){this.subjectFactory= a;this.selector=f}a.prototype.call=function(a,f){var c=this.selector,e=this.subjectFactory();a=c(e).subscribe(a);a.add(f.subscribe(e));return a};return a}();d.MulticastOperator=l},function(b,d,a){function h(a){var b=a.Symbol;if("function"===typeof b)return b.iterator||(b.iterator=b("iterator polyfill")),b.iterator;if((b=a.Set)&&"function"===typeof(new b)["@@iterator"])return"@@iterator";if(a=a.Map){b=Object.getOwnPropertyNames(a.prototype);for(var k=0;k<b.length;++k){var f=b[k];if("entries"!==f&& "size"!==f&&a.prototype[f]===a.prototype.entries)return f}}return"@@iterator"}b=a(12);d.symbolIteratorPonyfill=h;d.iterator=h(b.root);d.$$iterator=d.iterator},function(b,d,a){function h(a){var b=a.Symbol;"function"===typeof b?b.observable?a=b.observable:(a=b("observable"),b.observable=a):a="@@observable";return a}b=a(12);d.getSymbolObservable=h;d.observable=h(b.root);d.$$observable=d.observable},function(b,d,a){b=a(12).root.Symbol;d.rxSubscriber="function"===typeof b&&"function"===typeof b.for?b.for("rxSubscriber"): "@@rxSubscriber";d.$$rxSubscriber=d.rxSubscriber},function(b,d,a){var h=this&&this.__extends||function(a,b){function k(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(k.prototype=b.prototype,new k)};b=function(a){function b(){var b=a.call(this,"object unsubscribed");this.name=b.name="ObjectUnsubscribedError";this.stack=b.stack;this.message=b.message}h(b,a);return b}(Error);d.ObjectUnsubscribedError=b},function(b,d,a){d.isFunction=function(a){return"function"=== typeof a}},function(b,d,a){function h(){try{return g.apply(this,arguments)}catch(k){return l.errorObject.e=k,l.errorObject}}var l=a(33),g;d.tryCatch=function(a){g=a;return h}},function(b,d,a){b.exports=function(a,b,g){if("function"===typeof Array.prototype.findIndex)return a.findIndex(b,g);if("function"!==typeof b)throw new TypeError("predicate must be a function");a=Object(a);var k=a.length;if(0===k)return-1;for(var f=0;f<k;f++)if(b.call(g,a[f],f,a))return f;return-1}},function(b,d,a){function h(a, c){function e(){var a=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};a.errorCode&&(a={systemCode:a.systemCode,code:a.errorCode.code});this.name="KeySessionError";this.mediaKeyError=a;this.message="MediaKeyError code:"+a.code+" and systemCode:"+a.systemCode}e.prototype=Error();return function(f,b){var k="function"==typeof c?c.call(this):this,g=m.g(k),d=m.h(k).map(function(a){throw new e(k.error||a);});try{return a.call(this,f,b),l.Observable.merge(g,d).take(1)}catch(H){return l.Observable.throw(H)}}} a.d(d,"b",function(){return r});a.d(d,"a",function(){return q});b=a(8);b=a.n(b);var l=a(0);a.n(l);var g=a(29),k=a(13),f=a(2),c=a(9),e=a(34),m=a(17),n=a(55),q=void 0;navigator.requestMediaKeySystemAccess&&(q=function(e,f){return a.i(c.a)(navigator.requestMediaKeySystemAccess(e,f))});var r=function(){};if(!q&&e.e.prototype.webkitGenerateKeyRequest){var p=function(a,c){var e=this;g.a.call(this);this.sessionId="";this._vid=a;this._key=c;this._con=l.Observable.merge(m.i(a),m.g(a),m.h(a)).subscribe(function(a){return e.trigger(a.type, a)})};p.prototype=b()({generateRequest:function(a,c){this._vid.webkitGenerateKeyRequest(this._key,c)},update:h(function(c,e){if(0<=this._key.indexOf("clearkey")){var f=JSON.parse(a.i(k.a)(c));c=a.i(k.b)(atob(f.keys[0].k));f=a.i(k.b)(atob(f.keys[0].kid));this._vid.webkitAddKey(this._key,c,f,e)}else this._vid.webkitAddKey(this._key,c,null,e);this.sessionId=e}),close:function(){this._con&&this._con.unsubscribe();this._vid=this._con=null}},g.a.prototype);r=function(a){this.ks_=a};r.prototype={_setVideo:function(a){this._vid= a},createSession:function(){return new p(this._vid,this.ks_)}};var t=function(a){var c=document.querySelector("video")||document.createElement("video");return c&&c.canPlayType?!!c.canPlayType("video/mp4",a):!1};q=function(a,c){if(!t(a))return l.Observable.throw();for(var e=0;e<c.length;e++){var f=c[e],b=f.videoCapabilities,k=f.audioCapabilities,g=f.initDataTypes,m=f.sessionTypes,d=f.distinctiveIdentifier;f=f.persistentState;var h=!0;if(h=(h=(h=(h=h&&(!g||!!g.filter(function(a){return"cenc"===a})[0]))&& (!m||m.filter(function(a){return"temporary"===a}).length===m.length))&&"required"!==d)&&"required"!==f)return c={videoCapabilities:b,audioCapabilities:k,initDataTypes:["cenc"],distinctiveIdentifier:"not-allowed",persistentState:"not-allowed",sessionTypes:["temporary"]},l.Observable.of(new n.a(a,new r(a),c))}return l.Observable.throw()}}else if(e.f&&!q){var u=function(a){g.a.call(this);this.sessionId="";this._mk=a};u.prototype=b()({generateRequest:function(a,c){var e=this;this._ss=this._mk.memCreateSession("video/mp4", c);this._con=l.Observable.merge(m.i(this._ss),m.g(this._ss),m.h(this._ss)).subscribe(function(a){return e.trigger(a.type,a)})},update:h(function(c,e){a.i(f.a)(this._ss);this._ss.update(c,e);this.sessionId=e},function(){return this._ss}),close:function(){this._ss&&(this._ss.close(),this._ss=null);this._con&&(this._con.unsubscribe(),this._con=null)}},g.a.prototype);e.f.prototype.alwaysRenew=!0;e.f.prototype.memCreateSession=e.f.prototype.createSession;e.f.prototype.createSession=function(){return new u(this)}; q=function(a,c){if(!e.f.isTypeSupported(a))return l.Observable.throw();for(var f=0;f<c.length;f++){var b=c[f],k=b.videoCapabilities,g=b.audioCapabilities,m=b.initDataTypes;b=b.distinctiveIdentifier;var d=!0;if(d=(d=d&&(!m||!!m.filter(function(a){return"cenc"===a})[0]))&&"required"!==b)return c={videoCapabilities:k,audioCapabilities:g,initDataTypes:["cenc"],distinctiveIdentifier:"not-allowed",persistentState:"required",sessionTypes:["temporary","persistent-license"]},l.Observable.of(new n.a(a,new e.f(a), c))}return l.Observable.throw()}}},function(b,d,a){var h=a(0);a.n(h);var l=function(){function a(a,f){for(var c=0;c<f.length;c++){var e=f[c];e.enumerable=e.enumerable||!1;e.configurable=!0;"value"in e&&(e.writable=!0);Object.defineProperty(a,e.key,e)}}return function(b,f,c){f&&a(b.prototype,f);c&&a(b,c);return b}}();b=function(){function a(b,f,c){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this._keyType=b;this._mediaKeys=f;this._configuration=c}a.prototype.createMediaKeys= function(){return h.Observable.of(this._mediaKeys)};a.prototype.getConfiguration=function(){return this._configuration};l(a,[{key:"keySystem",get:function(){return this._keyType}}]);return a}();d.a=b},function(b,d,a){b=function(){function a(b){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this._alpha=Math.exp(Math.log(.5)/b);this._totalWeight=this._lastEstimate=0}a.prototype.addSample=function(a,b){var k=Math.pow(this._alpha,a);b=b*(1-k)+k*this._lastEstimate;isNaN(b)|| (this._lastEstimate=b,this._totalWeight+=a)};a.prototype.getEstimate=function(){return this._lastEstimate/(1-Math.pow(this._alpha,this._totalWeight))};return a}();d.a=b},function(b,d,a){function h(b,g,d){function l(e){return a.i(c.a)(e.createMediaKeys())}function h(c,e){var g=e.keySystem,h=e.keySystemAccess;g.persistentLicense&&m.a.setStorage(g.licenseStorage);f.a.info("eme: encrypted event",c);return l(h).mergeMap(function(e){var f=g.serverCertificate;f=f&&"function"===typeof e.setServerCertificate? a.i(n.a)(e,f,d):k.Observable.empty();var m=h.getConfiguration();return f.concat(k.Observable.merge(a.i(q.a)(e,m,b,g,t),a.i(r.a)(e,m,g,c.initDataType,new Uint8Array(c.initData),d)))})}return k.Observable.combineLatest(a.i(e.d)(b),a.i(p.a)(g,t)).take(1).mergeMap(function(a){return h(a[0],a[1])})}function l(){a.i(q.b)(t.$videoElement).subscribe(function(){});t.$mediaKeys=null;t.$keySystem=null;t.$videoElement=null;t.$mediaKeySystemConfiguration=null;m.b.dispose()}function g(){return a.i(p.b)(t)}a.d(d, "c",function(){return h});a.d(d,"b",function(){return g});a.d(d,"a",function(){return l});var k=a(0);a.n(k);var f=a(1),c=a(9);a(2);var e=a(17),m=a(36),n=a(110),q=a(115),r=a(111),p=a(109);a.d(d,"d",function(){return e.d});var t={$mediaKeys:null,$mediaKeySystemConfiguration:null,$keySystem:null,$videoElement:null}},function(b,d,a){b=function(){function a(){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this._entries=[]}a.prototype.find=function(a){for(var b=0;b<this._entries.length;b++)if(!0=== a(this._entries[b]))return this._entries[b];return null};return a}();d.a=b},function(b,d,a){d.a=function(a){if("number"==typeof a)return a;for(var b=0,g,k=0;k<a.length;k++)g=a[k],b=(b<<5)-b+g,b&=b;return b}},function(b,d,a){function h(a,c){if("function"!==typeof c&&null!==c)throw new TypeError("Super expression must either be null or a function, not "+typeof c);a.prototype=Object.create(c&&c.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});c&&(Object.setPrototypeOf?Object.setPrototypeOf(a, c):a.__proto__=c)}a.d(d,"a",function(){return c});b=a(29);var l=a(2),g=a(42),k=a(9),f=a(128),c=function(c){function e(a){if(!(this instanceof e))throw new TypeError("Cannot call a class as a function");var b=c.call(this);if(!this)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");b=!b||"object"!==typeof b&&"function"!==typeof b?this:b;b.codec=a;b.updating=!1;b.readyState="opened";b.buffered=new f.a;return b}h(e,c);e.prototype.appendBuffer=function(a){var c=this; this._lock(function(){return c._append(a)})};e.prototype.remove=function(a,c){var e=this;this._lock(function(){return e._remove(a,c)})};e.prototype.abort=function(){this.remove(0,Infinity);this.updating=!1;this.readyState="closed";this._abort()};e.prototype._append=function(){};e.prototype._remove=function(){};e.prototype._abort=function(){};e.prototype._lock=function(c){var e=this;a.i(l.a)(!this.updating,"updating");this.updating=!0;this.trigger("updatestart");a.i(g.a)(function(){return a.i(k.a)(c())}).subscribe(function(){return setTimeout(function(){return e._unlock("update")}, 0)},function(a){return setTimeout(function(){return e._unlock("error",a)},0)})};e.prototype._unlock=function(a,c){this.updating=!1;this.trigger(a,c);this.trigger("updateend")};return e}(b.a)},function(b,d,a){function h(b){var k=0,f=b.length,c=a.i(l.a)(b.subarray(k,k+8));k+=8;var e=b[k];k+=1;var g=b[k];k+=1;var d=b[k];k+=1;var h=b[k];k+=1;e=[e,g,d,h].join(".");g=b[k]+a.i(l.c)(b,k+1);k+=4;d=a.i(l.c)(b,k);k+=4;h=a.i(l.a)(b.subarray(k,k+4));k+=4;var r=a.i(l.d)(b,k);k+=2;var p=a.i(l.d)(b,k);k+=2;var t= [b[k],b[k+1]].join(":"),u=1===b[k+2];k=64;var w=[],x=void 0,v=0;if(!g)throw Error("bif: no images to parse");for(;k<f;){var y=a.i(l.c)(b,k);k+=4;var z=a.i(l.c)(b,k);k+=4;if(x){var B=x.index,C=d,A=v;x=b.subarray(x.offset,z);w.push({index:B,duration:C,ts:A,data:x});v+=d}if(4294967295===y)break;x={index:y,offset:z}}return{fileFormat:c,version:e,imageCount:g,timescale:d,format:h,width:r,height:p,aspectRatio:t,isVod:u,thumbs:w}}a.d(d,"a",function(){return h});var l=a(13)},function(b,d,a){function h(a){return a.replace(f, "\n").replace(k,function(a,c){return String.fromCharCode(c)})}function l(f,b){var k=/<sync[ >]/ig,d=/<sync[ >]|<\/body>/ig,n=[],l=f.match(c)[1];d.exec(f);var q=/\.(\S+)\s*{([^}]*)}/gi;for(var x={},v;v=q.exec(l);){var y=v[1];v=v[2].match(/\s*lang:\s*(\S+);/i)[1];y&&v&&(x[v]=y)}l=x[b];for(a.i(g.a)(l,"sami: could not find lang "+b+" in CSS");;){b=k.exec(f);q=d.exec(f);if(!b&&!q)break;if(!b||!q||b.index>=q.index)throw Error("parse error");q=f.slice(b.index,q.index);b=q.match(m);if(!b)throw Error("parse error (sync time attribute)"); x=+b[1];if(isNaN(x))throw Error("parse error (sync time attribute NaN)");b=n;q=q.split("\n");x/=1E3;for(y=q.length;0<=--y;)if(v=q[y].match(e)){var z=v[2];l===v[1]&&("&nbsp;"===z?b[b.length-1].end=x:b.push({text:h(z),start:x}))}}return n}a.d(d,"a",function(){return l});var g=a(2),k=/&#([0-9]+);/g,f=/<br>/gi,c=/<style[^>]*>([\s\S]*?)<\/style[^>]*>/i,e=/\s*<p class=([^>]+)>(.*)/i,m=/<sync[^>]+?start="?([0-9]*)"?[^0-9]/i},function(b,d,a){function h(a,c,e){a="string"==typeof a?(new DOMParser).parseFromString(a, "text/xml"):a;if(!(a instanceof window.Document||a instanceof window.HTMLElement))throw Error("ttml needs a Document to parse");a=a.querySelector("tt");if(!a)throw Error("ttml could not find <tt> tag");a=l(a.querySelector("body"),0);for(c=0;c<a.length;c++){var f=a[c];f.start+=e;f.end+=e}return a}function l(a,c){var e=0;a=a.firstChild;for(var b=[],m;a;){if(1===a.nodeType)switch(a.tagName.toUpperCase()){case "P":m=a;var d=c,n=e;e=g(m.getAttribute("begin"),d);var h=g(m.getAttribute("end"),d),q=g(m.getAttribute("dur"), 0);if("number"==!("undefined"===typeof e||k(e))&&"number"==!("undefined"===typeof h||k(h))&&"number"==!("undefined"===typeof q||k(q)))throw Error("ttml unsupported timestamp format");0<q?(null==e&&(e=n||d),null==h&&(h=e+q)):null==h&&(h=g(m.getAttribute("duration"),0),h=0<=h?h+e:Number.MAX_VALUE);d=m.innerHTML;null==d&&(d=(new XMLSerializer).serializeToString(m),d=(new DOMParser).parseFromString(d,"text/html").body.firstChild.innerHTML);d=window.escape(d.replace(f,"\r\n"));d=d.replace(/%C3%26nbsp%3B/gm, "%C3%A0");m={id:m.getAttribute("xml:id")||m.getAttribute("id"),text:window.decodeURIComponent(d),start:e,end:h};e=m.end;b.push(m);break;case "DIV":m=g(a.getAttribute("begin"),0),null==m&&(m=c),b.push.apply(b,l(a,m))}a=a.nextSibling}return b}function g(a,f){if(!a)return null;var b;if(b=a.match(c)){f=b;a=f[3];b=f[4];var k=f[6];return 3600*parseInt(f[2]||0,10)+60*parseInt(a,10)+parseInt(b,10)+parseFloat("0."+k)}return(b=a.match(e))?(a=b,b=a[4],parseFloat(a[1])*m[b]+f):null}a.d(d,"a",function(){return h}); var k="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},f=/<br( )*\/* *>/gm,c=/^(([0-9]+):)?([0-9]+):([0-9]+)(\.([0-9]+))?$/,e=/(([0-9]+)(\.[0-9]+)?)(ms|h|m|s)/,m={h:3600,m:60,s:1,ms:.001}},function(b,d,a){function h(a){if("timeline"===a.indexType){var c=a.timeline[a.timeline.length-1],e=c.d;return(c.ts+(c.r+1)*e)/a.timescale-Math.min(Math.max(e/ a.timescale,5),10)}return Date.now()/1E3-5}function l(a){return a}function g(a){return"true"==a}function k(a){return"true"==a?!0:"false"==a?!1:parseInt(a)}function f(a){return new Date(Date.parse(a))}function c(c){if(!c)return 0;var e=x.exec(c);a.i(w.a)(e,c+" is not a valid ISO8601 duration");return 31536E3*parseFloat(e[2]||0)+2592E3*parseFloat(e[4]||0)+86400*parseFloat(e[6]||0)+3600*parseFloat(e[8]||0)+60*parseFloat(e[10]||0)+parseFloat(e[12]||0)}function e(a){var c=y.exec(a);if(!c)return-1;a=parseInt(c[1])|| 0;c=parseInt(c[2])||0;return 0<c?a/c:a}function m(a){return a}function n(a){return(a=v.exec(a))?[+a[1],+a[2]]:null}function q(a,c,e){for(a=a.firstElementChild;a;)e=c(e,a.nodeName,a),a=a.nextElementSibling;return e}function r(a){return a?"urn:tva:metadata:cs:AudioPurposeCS:2007"===a.schemeIdUri&&1===a.value:!1}function p(c){var e=c.mimeType;e=void 0===e?"":e;var f=e.split("/")[0];if(a.i(u.a)(z,f))return f;if("application/bif"===e)return"image";if("application/ttml+xml"===e)return"text";if("application/mp4"=== e)return(c=c.role)&&"urn:mpeg:dash:role:2011"===c.schemeIdUri&&"subtitle"===c.value?"text":"metadata";c=c.representations;c=void 0===c?[]:c;return c.length&&(c=c[0].mimeType.split("/")[0],a.i(u.a)(z,c))?c:"unknown"}function t(a){return a?"urn:tva:metadata:cs:AudioPurposeCS:2007"===a.schemeIdUri&&2===a.value:!1}a.d(d,"g",function(){return l});a.d(d,"h",function(){return e});a.d(d,"f",function(){return n});a.d(d,"i",function(){return g});a.d(d,"m",function(){return f});a.d(d,"j",function(){return c}); a.d(d,"l",function(){return k});a.d(d,"k",function(){return m});a.d(d,"a",function(){return q});a.d(d,"b",function(){return B});a.d(d,"d",function(){return t});a.d(d,"e",function(){return r});a.d(d,"c",function(){return p});var u=a(19),w=a(2),x=/^P(([\d.]*)Y)?(([\d.]*)M)?(([\d.]*)D)?T?(([\d.]*)H)?(([\d.]*)M)?(([\d.]*)S)?/,v=/([0-9]+)-([0-9]+)/,y=/([0-9]+)(\/([0-9]+))?/,z=["audio","video","text","image"],B=function(a){if(a){var c=a.representations||[],e=c.filter(function(a){return a&&a.index});if(!c.length)return h(a.index); var f=Math.min.apply(Math,e.map(function(a){return h(a.index)}));if(!isNaN(f)){if(c.length===e.length)return f;if(a.index)return a=h(a.index),Math.min(f,a)}}}},function(b,d,a){function h(a){var b=a.value;return"response"===a.type?{type:"response",value:{responseData:b.responseData,size:b.size,duration:b.receivedTime-b.sentTime,url:b.url}}:{type:"progress",value:{size:b.loadedSize,totalSize:b.totalSize,duration:b.currentTime-b.sentTime,url:b.url}}}var l=a(41);d.a=function(b){return a.i(l.a)(b).map(h)}}, function(b,d,a){function h(a){return function(c,e,b){c=b?parseInt(b,10):1;e=""+a;e=e.toString();c=e.length>=c?e:(Array(c+1).join("0")+e).slice(-c);return c}}function l(a,c,e){return-1===a.indexOf("$")?a:a.replace(/\$\$/g,"$").replace(/\$RepresentationID\$/g,e.id).replace(/\$Bandwidth(|\%0(\d+)d)\$/g,h(e.bitrate)).replace(/\$Number(|\%0(\d+)d)\$/g,h(c.number)).replace(/\$Time(|\%0(\d+)d)\$/g,h(c.time))}function g(a){return"application/mp4"===a.mimeType}function k(a){var c=a[0];return(a=a[1])&&Infinity!== a?"bytes="+ +c+"-"+ +a:"bytes="+ +c+"-"}a.d(d,"b",function(){return l});a.d(d,"a",function(){return g});a.d(d,"c",function(){return k})},function(b,d,a){function h(a){var b=a.value;return"response"===a.type?{type:"response",value:{responseData:b.responseData,size:b.size,duration:b.receivedTime-b.sentTime,url:b.url}}:{type:"progress",value:{size:b.loadedSize,totalSize:b.totalSize,duration:b.currentTime-b.sentTime,url:b.url}}}var l=a(41);d.a=function(b){return a.i(l.a)(b).map(h)}},function(b,d,a){function h(a){var c= a[0];return(a=a[1])&&Infinity!==a?"bytes="+ +c+"-"+ +a:"bytes="+ +c+"-"}function l(a){return a.responseData.getElementsByTagName("media")[0].getAttribute("src")}function g(a){return(a=a.match(m))&&a[1]||""}function k(a,c){return c?a.replace(m,"?token="+c):a.replace(m,"")}function f(a){var c=a.match(e);return c?a.replace(c[1],c[1]+"/manifest"):a}function c(a,c,e){return a.replace(/\{bitrate\}/g,c.bitrate).replace(/\{start time\}/g,e.time)}a.d(d,"f",function(){return h});a.d(d,"c",function(){return l}); a.d(d,"a",function(){return g});a.d(d,"b",function(){return k});a.d(d,"d",function(){return f});a.d(d,"e",function(){return c});var e=/\.(isml?)(\?token=\S+)?$/,m=/\?token=(\S+)/},function(b,d,a){function h(a){return a*(1+(2*Math.random()-1)*g)}function l(a){return h(a*Math.pow(2,(1<arguments.length&&void 0!==arguments[1]?arguments[1]:1)-1))}a.d(d,"b",function(){return h});a.d(d,"a",function(){return l});var g=.3},function(b,d,a){function h(a,e){var c=0;return function(){c&&clearTimeout(c);c=setTimeout(a, e)}}function l(c,e){var b=e.retryDelay,g=e.totalRetry,d=e.shouldRetry,l=e.resetDelay,p=e.errorSelector,t=e.onRetry,u=0,w=void 0;0<l&&(w=h(function(){return u=0},l));return c.catch(function(c,e){if(d&&!d(c)||u++>=g){if(p)throw p(c,u);throw c;}t&&t(c,u);c=a.i(f.a)(b,u);return k.Observable.timer(c).mergeMap(function(){w&&w();return e})})}function g(c,e){var b=e.retryDelay,g=e.totalRetry,d=e.shouldRetry,l=e.resetDelay,p=e.errorSelector,t=e.onRetry,u=0,w=void 0;0<l&&(w=h(function(){return u=0},l));return function v(){for(var e= arguments.length,m=Array(e),l=0;l<e;l++)m[l]=arguments[l];return c.apply(void 0,m).catch(function(c){if(d&&!d(c)||u++>=g){if(p)throw p(c,u);throw c;}t&&t(c,u);c=a.i(f.a)(b,u);return k.Observable.timer(c).mergeMap(function(){w&&w();return v.apply(void 0,m)})})}}a.d(d,"a",function(){return l});a.d(d,"b",function(){return g});var k=a(0);a.n(k);var f=a(69)},function(b,d,a){d.empty={closed:!0,next:function(a){},error:function(a){throw a;},complete:function(){}}},function(b,d,a){var h=this&&this.__extends|| function(a,b){function k(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(k.prototype=b.prototype,new k)};b=function(a){function b(b,f){a.call(this);this.subject=b;this.subscriber=f;this.closed=!1}h(b,a);b.prototype.unsubscribe=function(){if(!this.closed){this.closed=!0;var a=this.subject,b=a.observers;this.subject=null;!b||0===b.length||a.isStopped||a.closed||(a=b.indexOf(this.subscriber),-1!==a&&b.splice(a,1))}};return b}(a(11).Subscription); d.SubjectSubscription=b},function(b,d,a){function h(a){var c=a.value;a=a.subscriber;a.closed||(a.next(c),a.complete())}function l(a){var c=a.err;a=a.subscriber;a.closed||a.error(c)}var g=this&&this.__extends||function(a,c){function e(){this.constructor=a}for(var b in c)c.hasOwnProperty(b)&&(a[b]=c[b]);a.prototype=null===c?Object.create(c):(e.prototype=c.prototype,new e)},k=a(12);b=function(a){function c(c,b){a.call(this);this.promise=c;this.scheduler=b}g(c,a);c.create=function(a,b){return new c(a, b)};c.prototype._subscribe=function(a){var c=this,e=this.promise,b=this.scheduler;if(null==b)this._isScalar?a.closed||(a.next(this.value),a.complete()):e.then(function(e){c.value=e;c._isScalar=!0;a.closed||(a.next(e),a.complete())},function(c){a.closed||a.error(c)}).then(null,function(a){k.root.setTimeout(function(){throw a;})});else if(this._isScalar){if(!a.closed)return b.schedule(h,0,{value:this.value,subscriber:a})}else e.then(function(e){c.value=e;c._isScalar=!0;a.closed||a.add(b.schedule(h, 0,{value:e,subscriber:a}))},function(c){a.closed||a.add(b.schedule(l,0,{err:c,subscriber:a}))}).then(null,function(a){k.root.setTimeout(function(){throw a;})})};return c}(a(0).Observable);d.PromiseObservable=b},function(b,d,a){function h(){for(var a=[],e=0;e<arguments.length;e++)a[e-0]=arguments[e];e=null;g.isScheduler(a[a.length-1])&&(e=a.pop());return null===e&&1===a.length&&a[0]instanceof l.Observable?a[0]:(new k.ArrayObservable(a,e)).lift(new f.MergeAllOperator(1))}var l=a(0),g=a(20),k=a(15), f=a(45);d.concat=function(){for(var a=[],e=0;e<arguments.length;e++)a[e-0]=arguments[e];return this.lift.call(h.apply(void 0,[this].concat(a)))};d.concatStatic=h},function(b,d,a){function h(){for(var a=[],e=0;e<arguments.length;e++)a[e-0]=arguments[e];e=Number.POSITIVE_INFINITY;var b=null,d=a[a.length-1];f.isScheduler(d)?(b=a.pop(),1<a.length&&"number"===typeof a[a.length-1]&&(e=a.pop())):"number"===typeof d&&(e=a.pop());return null===b&&1===a.length&&a[0]instanceof l.Observable?a[0]:(new g.ArrayObservable(a, b)).lift(new k.MergeAllOperator(e))}var l=a(0),g=a(15),k=a(45),f=a(20);d.merge=function(){for(var a=[],e=0;e<arguments.length;e++)a[e-0]=arguments[e];return this.lift.call(h.apply(void 0,[this].concat(a)))};d.mergeStatic=h},function(b,d,a){var h=this&&this.__extends||function(a,c){function e(){this.constructor=a}for(var b in c)c.hasOwnProperty(b)&&(a[b]=c[b]);a.prototype=null===c?Object.create(c):(e.prototype=c.prototype,new e)},l=a(16);b=a(14);d.mergeMap=function(a,c,e){void 0===e&&(e=Number.POSITIVE_INFINITY); "number"===typeof c&&(e=c,c=null);return this.lift(new g(a,c,e))};var g=function(){function a(a,e,b){void 0===b&&(b=Number.POSITIVE_INFINITY);this.project=a;this.resultSelector=e;this.concurrent=b}a.prototype.call=function(a,e){return e.subscribe(new k(a,this.project,this.resultSelector,this.concurrent))};return a}();d.MergeMapOperator=g;var k=function(a){function c(c,b,f,k){void 0===k&&(k=Number.POSITIVE_INFINITY);a.call(this,c);this.project=b;this.resultSelector=f;this.concurrent=k;this.hasCompleted= !1;this.buffer=[];this.index=this.active=0}h(c,a);c.prototype._next=function(a){this.active<this.concurrent?this._tryNext(a):this.buffer.push(a)};c.prototype._tryNext=function(a){var c=this.index++;try{var e=this.project(a,c)}catch(q){this.destination.error(q);return}this.active++;this._innerSub(e,a,c)};c.prototype._innerSub=function(a,c,b){this.add(l.subscribeToResult(this,a,c,b))};c.prototype._complete=function(){this.hasCompleted=!0;0===this.active&&0===this.buffer.length&&this.destination.complete()}; c.prototype.notifyNext=function(a,c,b,f,k){this.resultSelector?this._notifyResultSelector(a,c,b,f):this.destination.next(c)};c.prototype._notifyResultSelector=function(a,c,b,f){try{var e=this.resultSelector(a,c,b,f)}catch(p){this.destination.error(p);return}this.destination.next(e)};c.prototype.notifyComplete=function(a){var c=this.buffer;this.remove(a);this.active--;0<c.length?this._next(c.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()};return c}(b.OuterSubscriber);d.MergeMapSubscriber= k},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(3);var l=a(173);d.observeOn=function(a,b){void 0===b&&(b=0);return this.lift(new g(a,b))};var g=function(){function a(a,c){void 0===c&&(c=0);this.scheduler=a;this.delay=c}a.prototype.call=function(a,c){return c.subscribe(new k(a,this.scheduler,this.delay))};return a}();d.ObserveOnOperator= g;var k=function(a){function c(c,b,e){void 0===e&&(e=0);a.call(this,c);this.scheduler=b;this.delay=e}h(c,a);c.dispatch=function(a){a.notification.observe(a.destination);this.unsubscribe()};c.prototype.scheduleMessage=function(a){this.add(this.scheduler.schedule(c.dispatch,this.delay,new f(a,this.destination)))};c.prototype._next=function(a){this.scheduleMessage(l.Notification.createNext(a))};c.prototype._error=function(a){this.scheduleMessage(l.Notification.createError(a))};c.prototype._complete= function(){this.scheduleMessage(l.Notification.createComplete())};return c}(b.Subscriber);d.ObserveOnSubscriber=k;var f=function(){return function(a,b){this.notification=a;this.destination=b}}();d.ObserveOnMessage=f},function(b,d,a){var h=this&&this.__extends||function(a,b){function f(){this.constructor=a}for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);a.prototype=null===b?Object.create(b):(f.prototype=b.prototype,new f)},l=a(12);b=function(a){function b(b,c){a.call(this,b,c);this.scheduler=b;this.work= c;this.pending=!1}h(b,a);b.prototype.schedule=function(a,c){void 0===c&&(c=0);if(this.closed)return this;this.state=a;this.pending=!0;a=this.id;var b=this.scheduler;null!=a&&(this.id=this.recycleAsyncId(b,a,c));this.delay=c;this.id=this.id||this.requestAsyncId(b,this.id,c);return this};b.prototype.requestAsyncId=function(a,c,b){void 0===b&&(b=0);return l.root.setInterval(a.flush.bind(a,this),b)};b.prototype.recycleAsyncId=function(a,c,b){void 0===b&&(b=0);return null!==b&&this.delay===b&&!1===this.pending? c:(l.root.clearInterval(c),void 0)};b.prototype.execute=function(a,c){if(this.closed)return Error("executing a cancelled action");this.pending=!1;if(a=this._execute(a,c))return a;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))};b.prototype._execute=function(a,c){c=!1;var b=void 0;try{this.work(a)}catch(m){c=!0,b=!!m&&m||Error(m)}if(c)return this.unsubscribe(),b};b.prototype._unsubscribe=function(){var a=this.id,c=this.scheduler,b=c.actions,k=b.indexOf(this); this.state=this.work=null;this.pending=!1;this.scheduler=null;-1!==k&&b.splice(k,1);null!=a&&(this.id=this.recycleAsyncId(c,a,null));this.delay=null};return b}(a(257).Action);d.AsyncAction=b},function(b,d,a){var h=this&&this.__extends||function(a,b){function k(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(k.prototype=b.prototype,new k)};b=function(a){function b(){a.apply(this,arguments);this.actions=[];this.active=!1;this.scheduled=void 0} h(b,a);b.prototype.flush=function(a){var b=this.actions;if(this.active)b.push(a);else{var c;this.active=!0;do if(c=a.execute(a.state,a.delay))break;while(a=b.shift());this.active=!1;if(c){for(;a=b.shift();)a.unsubscribe();throw c;}}};return b}(a(175).Scheduler);d.AsyncScheduler=b},function(b,d,a){var h=this&&this.__extends||function(a,b){function k(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(k.prototype=b.prototype,new k)};b=function(a){function b(){var b= a.call(this,"Timeout has occurred");this.name=b.name="TimeoutError";this.stack=b.stack;this.message=b.message}h(b,a);return b}(Error);d.TimeoutError=b},function(b,d,a){d.isArrayLike=function(a){return a&&"number"===typeof a.length}},function(b,d,a){d.isDate=function(a){return a instanceof Date&&!isNaN(+a)}},function(b,d,a){var h=a(26);d.isNumeric=function(a){return!h.isArray(a)&&0<=a-parseFloat(a)+1}},function(b,d,a){d.isObject=function(a){return null!=a&&"object"===typeof a}},function(b,d,a){d.isPromise= function(a){return a&&"function"!==typeof a.subscribe&&"function"===typeof a.then}},function(b,d,a){d.noop=function(){}},function(b,d,a){Object.defineProperty(d,"__esModule",{value:!0});b=a(176);a.n(b);b=a(177);a.n(b);b=a(178);a.n(b);b=a(179);a.n(b);b=a(180);a.n(b);b=a(181);a.n(b);b=a(182);a.n(b);b=a(183);a.n(b);b=a(184);a.n(b);b=a(185);a.n(b);b=a(186);a.n(b);b=a(187);a.n(b);b=a(188);a.n(b);b=a(189);a.n(b);b=a(190);a.n(b);b=a(191);a.n(b);b=a(192);a.n(b);b=a(193);a.n(b);b=a(194);a.n(b);b=a(195);a.n(b); b=a(196);a.n(b);b=a(197);a.n(b);b=a(198);a.n(b);b=a(199);a.n(b);b=a(200);a.n(b);b=a(201);a.n(b);b=a(202);a.n(b);b=a(203);a.n(b);b=a(204);a.n(b);b=a(205);a.n(b);b=a(206);a.n(b);b=a(207);a.n(b);b=a(208);a.n(b);b=a(209);a.n(b);b=a(210);a.n(b);b=a(211);a.n(b);b=a(212);a.n(b);a(1);a=a(98);d["default"]=a.a},function(b,d,a){var h=a(54),l=a(89),g=a(55);a.d(d,"b",function(){return h.a});a.d(d,"c",function(){return l.a});a.d(d,"a",function(){return g.a})},function(b,d,a){function h(a,c){if(c instanceof k.b)return c._setVideo(a); if(a.setMediaKeys)return a.setMediaKeys(c);if(null!==c){if(a.WebkitSetMediaKeys)return a.WebkitSetMediaKeys(c);if(a.mozSetMediaKeys)return a.mozSetMediaKeys(c);if(a.msSetMediaKeys)return a.msSetMediaKeys(c)}}var l=a(0);a.n(l);var g=a(9),k=a(54);d.a=function(b,c){return l.Observable.defer(function(){return a.i(g.a)(h(b,c))})}},function(b,d,a){function h(a){g()||(a.requestFullscreen?a.requestFullscreen():a.msRequestFullscreen?a.msRequestFullscreen():a.mozRequestFullScreen?a.mozRequestFullScreen():a.webkitRequestFullscreen&& a.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT))}function l(){g()&&(document.exitFullscreen?document.exitFullscreen():document.msExitFullscreen?document.msExitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen())}function g(){return!!(document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement)}a.d(d,"c",function(){return h});a.d(d,"a",function(){return l}); a.d(d,"b",function(){return g})},function(b,d,a){var h=a(56);b=a(4);var l=b.a.ABR_MINIMUM_TOTAL_BYTES,g=b.a.ABR_MINIMUM_CHUNK_SIZE;b=function(){function a(){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this._fast=new h.a(2);this._slow=new h.a(10);this._bytesSampled=0}a.prototype.addSample=function(a,c){if(!(c<g)){var b=8E3*c/a;a/=1E3;this._bytesSampled+=c;this._fast.addSample(a,b);this._slow.addSample(a,b)}};a.prototype.getEstimate=function(){if(!(this._bytesSampled< l))return Math.min(this._fast.getEstimate(),this._slow.getEstimate())};a.prototype.reset=function(){this._fast=new h.a(2);this._slow=new h.a(10);this._bytesSampled=0};return a}();d.a=b},function(b,d,a){d.a=function(a,b){var k=h()(a,function(a){return a.bitrate>b});return-1===k?a:a.slice(0,k)};b=a(53);var h=a.n(b)},function(b,d,a){d.a=function(a,b){var k=a.sort(function(a,b){return a.width-b.width});if(k=h()(k,function(a){return a.width>=b})){var f=k.width;return a.filter(function(a){return a.width<= f})}return a};b=a(21);var h=a.n(b)},function(b,d,a){d.a=function(a,b){var k=h()(a,function(a){return a.bitrate>b});return-1===k?a[a.length-1]:a[k-1]};b=a(53);var h=a.n(b)},function(b,d,a){var h=a(5);a.n(h);a(19);a(2);var l=a(96),g=function(a,b){if(!a._choosers[b]){var c=a._choosers;a=a._chooserInstanceOptions;a=new l.a({limitWidth$:a.limitWidth[b],throttle$:a.throttle[b],initialBitrate:a.initialBitrates[b],manualBitrate:a.manualBitrates[b],maxAutoBitrate:a.maxAutoBitrates[b]});c[b]=a}};b=function(){function a(b, c){var e=this,f=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{};if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this._dispose$=new h.Subject;this._choosers={};this._chooserInstanceOptions={initialBitrates:f.initialBitrates||{},manualBitrates:f.manualBitrates||{},maxAutoBitrates:f.maxAutoBitrates||{},throttle:f.throttle||{},limitWidth:f.limitWidth||{}};c.takeUntil(this._dispose$).subscribe(function(a){var c=a.type;a=a.value;g(e,c);e._choosers[c].addEstimate(a.duration, a.size)});b.mergeMap(function(a){return a}).takeUntil(this._dispose$).subscribe(function(a){var c=a.type,b=a.event;a=a.value;g(e,c);switch(b){case "requestBegin":e._choosers[c].addPendingRequest(a.id,a);break;case "requestEnd":e._choosers[c].removePendingRequest(a.id);break;case "progress":e._choosers[c].addRequestProgress(a.id,a)}})}a.prototype.get$=function(a,c){var b=2<arguments.length&&void 0!==arguments[2]?arguments[2]:[];g(this,a);return this._choosers[a].get$(c,b)};a.prototype.setManualBitrate= function(a,c){var b=this._choosers[a];b?b.manualBitrate$.next(c):this._chooserInstanceOptions.initialBitrates[a]=c};a.prototype.setMaxAutoBitrate=function(a,c){var b=this._choosers[a];b?b.maxAutoBitrate$.next(c):this._chooserInstanceOptions.maxAutoBitrates[a]=c};a.prototype.getManualBitrate=function(a){var c=this._choosers[a];return c?c.manualBitrate$.getValue():this._chooserInstanceOptions.manualBitrates[a]};a.prototype.getMaxAutoBitrate=function(a){var c=this._choosers[a];return c?c.maxAutoBitrate$.getValue(): this._chooserInstanceOptions.maxAutoBitrates[a]};a.prototype.dispose=function(){var a=this;Object.keys(this._choosers).forEach(function(c){a._choosers[c].dispose()});this._choosers=this._chooserInstanceOptions=null;this._dispose$.next();this._dispose$.complete()};return a}();d.a=b},function(b,d,a){b=a(8);var h=a.n(b),l=a(43);a.n(l);var g=a(5);a.n(g);var k=a(0);a.n(k);b=a(4);a(2);var f=a(91),c=a(93),e=a(92),m=a(94),n=a(56),q=b.a.ABR_STARVATION_GAP,r=b.a.OUT_OF_STARVATION_GAP,p=function(c,b){c=a.i(m.a)(c, b)||c[0];return k.Observable.of(c).concat(k.Observable.never())};b=function(){function b(){var a=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};if(!(this instanceof b))throw new TypeError("Cannot call a class as a function");this._dispose$=new g.Subject;this.manualBitrate$=(new l.BehaviorSubject(null!=a.manualBitrate?a.manualBitrate:-1)).takeUntil(this._dispose$);this.maxAutoBitrate$=(new l.BehaviorSubject(null!=a.maxAutoBitrate?a.maxAutoBitrate:Infinity)).takeUntil(this._dispose$);this.estimator= new f.a;this._currentRequests={};this.initialBitrate=a.initialBitrate||0;this._limitWidth$=a.limitWidth$;this._throttle$=a.throttle$}b.prototype.get$=function(b,f){var d=this;if(2>f.length)return k.Observable.of({bitrate:void 0,representation:f.length?f[0]:null}).concat(k.Observable.never()).takeUntil(this._dispose$);var g=this.initialBitrate,l=this.manualBitrate$,w=this.maxAutoBitrate$,t=[];this._limitWidth$&&t.push(this._limitWidth$.map(function(a){return{width:a}}));this._throttle$&&t.push(this._throttle$.map(function(a){return{bitrate:a}})); var u=t.length?k.Observable.combineLatest.apply(k.Observable,t).map(function(a){return h.a.apply(void 0,[{}].concat(a))}):k.Observable.of({});return l.switchMap(function(h){if(0<=h)return p(f,h);var l=!1;return k.Observable.combineLatest(b,w,u).map(function(b){var k=b[0],h=b[1];b=b[2];var p=void 0,w=k.bufferGap;w<=q?l=!0:l&&w>=r&&(l=!1);if(l){var y=k.bitrate;a:{var t=d._currentRequests;w+=k.position;for(var v=Object.keys(t),u=v.length,A=0;A<u-1;A++){var x=t[v[A]];if(Math.abs(w-x.time)<x.duration){w= x;break a}}w=void 0}if(w&&(v=w.duration,t=w.requestTimestamp,t=(Date.now()-t)/1E3,v&&t>1+1.2*v)){u=w;v=void 0;w=u.duration;if(2<=u.progress.length){v=new n.a(2);u=u.progress;for(A=1;A<u.length;A++)x=u[A].timestamp-u[A-1].timestamp,v.addSample(x/1E3,8*(u[A].size-u[A-1].size)/(x/1E3));v=v.getEstimate()}v||(v=w*y/(5*t/4));if(t=v)d.resetEstimate(),p=Math.min(t,y,h)}}null==p&&(p=d.estimator.getEstimate(),p=null!=p&&k.bufferGap<=l?.95*p:p,p=Math.min(null==p?g:p,h));1<k.speed&&(p/=k.speed);k=f;b.hasOwnProperty("bitrate")&& (k=a.i(e.a)(k,b.bitrate));b.hasOwnProperty("width")&&(k=a.i(c.a)(k,b.width));return{bitrate:p,representation:a.i(m.a)(k,p)||f[0]}}).do(function(a){a=a.bitrate;null!=a&&(g=a)}).share()})};b.prototype.addEstimate=function(a,c){null!=a&&null!=c&&this.estimator.addSample(a,c)};b.prototype.resetEstimate=function(){this.estimator.reset()};b.prototype.addPendingRequest=function(a,c){this._currentRequests[a]=c;this._currentRequests[a].progress=[]};b.prototype.addRequestProgress=function(a,c){this._currentRequests[a].progress.push(c)}; b.prototype.removePendingRequest=function(a){delete this._currentRequests[a]};b.prototype.resetRequests=function(){this._currentRequests={}};b.prototype.dispose=function(){this._dispose$.next()};return b}();d.a=b},function(b,d,a){function h(c,b){var e=c.currentTime,f=c.paused,d=c.playbackRate,g=c.readyState,m=c.buffered;return{currentTime:e,buffered:m,duration:c.duration,bufferGap:a.i(k.a)(m,e),state:b,playbackRate:d,currentRange:a.i(k.i)(m,e),readyState:g,paused:f}}var l=a(0);a.n(l);var g=a(43); a.n(g);b=a(4);var k=a(10),f=b.a.SAMPLING_INTERVAL_MEDIASOURCE,c=b.a.SAMPLING_INTERVAL_NO_MEDIASOURCE,e=b.a.RESUME_AFTER_SEEKING_GAP,m=b.a.RESUME_AFTER_BUFFERING_GAP,n=b.a.STALL_GAP,q="canplay play progress seeking seeked loadedmetadata".split(" ");d.a=function(a,b){var k=b.withMediaSource;return l.Observable.create(function(b){function d(c){c=h(a,c&&c.type||"timeupdate");var f=c.state;var d=c.currentTime,l=c.bufferGap,q=c.paused,r=c.readyState,p=g.stalled,v=g.state,t=g.currentTime;var w=(w=c.currentRange)&& c.duration-(l+w.end)<=n;var y=1<=r&&"loadedmetadata"!=f&&!p&&!w,u=void 0,x=void 0;k?y&&(l<=n||Infinity===l||1===r)?u=!0:p&&1<r&&Infinity>l&&(l>("seeking"==p.state?e:m)||w)&&(x=!0):y&&(!q&&"timeupdate"==f&&"timeupdate"==v&&d===t||"seeking"==f&&Infinity===l)?u=!0:p&&("seeking"!=f&&d!==t||"canplay"==f||Infinity>l&&(l>("seeking"==p.state?e:m)||w))&&(x=!0);f=u?{state:f,timestamp:Date.now()}:x?null:p;c.stalled=f;g=c;b.next(g)}var g=h(a,"init");g.stalled=null;var l=setInterval(d,k?f:c);q.forEach(function(c){return a.addEventListener(c, d)});b.next(g);return function(){clearInterval(l);q.forEach(function(c){return a.removeEventListener(c,d)})}}).multicast(function(){return new g.BehaviorSubject({})}).refCount()}},function(b,d,a){function h(a,c){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!c||"object"!==typeof c&&"function"!==typeof c?a:c}function l(a,c){if("function"!==typeof c&&null!==c)throw new TypeError("Super expression must either be null or a function, not "+typeof c); a.prototype=Object.create(c&&c.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});c&&(Object.setPrototypeOf?Object.setPrototypeOf(a,c):a.__proto__=c)}function g(a,c){return a.filter(function(a){return a.type==c}).map(function(a){return a.value})}var k=a(0);a.n(k);var f=a(5);a.n(f);var c=a(43);a.n(c);b=a(4);var e=a(1),m=a(31),n=a(29),q=a(2),r=a(10),p=a(7),t=a(17),u=a(148),w=a(28),x=a(6),v=a(121),y=a(57),z=a(35),B=a(97),C=a(102),A=a(99),H=a(101),E="function"===typeof Symbol&& "symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},I=function(){function a(a,c){for(var b=0;b<c.length;b++){var e=c[b];e.enumerable=e.enumerable||!1;e.configurable=!0;"value"in e&&(e.writable=!0);Object.defineProperty(a,e.key,e)}}return function(c,b,e){b&&a(c.prototype,b);e&&a(c,e);return c}}(),J=b.a.DEFAULT_UNMUTED_VOLUME;b=function(b){function d(k){if(!(this instanceof d))throw new TypeError("Cannot call a class as a function"); var g=h(this,b.call(this)),m=a.i(H.a)(k);k=m.defaultAudioTrack;var l=m.defaultTextTrack,n=m.initialAudioBitrate,r=m.initialVideoBitrate,w=m.limitVideoWidth,v=m.maxAudioBitrate,u=m.maxBufferAhead,y=m.maxBufferBehind,A=m.maxVideoBitrate,x=m.throttleWhenHidden,B=m.transport,Q=m.transportOptions,D=m.videoElement;m=m.wantedBufferAhead;a.i(q.a)(D instanceof p.a,"videoElement needs to be an HTMLVideoElement");D.preload="auto";g.version="3.0.0-rc4";g.log=e.a;g.state=void 0;g.defaultTransport=B;g.defaultTransportOptions= Q;g.videoElement=D;g._priv=a.i(C.a)(g);g._priv.destroy$=new f.Subject;g._priv.fullScreenSubscription=a.i(t.a)(D).takeUntil(g._priv.destroy$).subscribe(function(){return g.trigger("fullscreenChange",g.isFullscreen())});g._priv.errorStream$=(new f.Subject).takeUntil(g._priv.destroy$);g._priv.playing$=new c.BehaviorSubject;g._priv.speed$=new c.BehaviorSubject(D.playbackRate);g._priv.unsubscribeLoadedVideo$=(new f.Subject).takeUntil(g._priv.destroy$);g._priv.wantedBufferAhead$=new c.BehaviorSubject(m); g._priv.maxBufferAhead$=new c.BehaviorSubject(u);g._priv.maxBufferBehind$=new c.BehaviorSubject(y);g._priv.lastAudioTrack=k;g._priv.lastTextTrack=l;g._priv.lastBitrates={audio:n,video:r};g._priv.initialMaxAutoBitrates={audio:v,video:A};g._priv.manualBitrates={audio:-1,video:-1};g._priv.throttleWhenHidden=x;g._priv.limitVideoWidth=w;g._priv.mutedMemory=J;"abrManager currentAdaptations currentImagePlaylist currentRepresentations fatalError initialAudioTrack initialTextTrack languageManager manifest recordedEvents".split(" ").forEach(function(a){g._priv[a]= void 0});g._priv.resetContentState();g._priv.setPlayerState(z.a.STOPPED);return g}l(d,b);I(d,null,[{key:"ErrorTypes",get:function(){return x.a}},{key:"ErrorCodes",get:function(){return x.b}}]);d.prototype.stop=function(){this.state!==z.a.STOPPED&&(this._priv.resetContentState(),this._priv.unsubscribeLoadedVideo$.next(),this._priv.setPlayerState(z.a.STOPPED))};d.prototype.dispose=function(){this.stop();a.i(y.a)();var c=this._priv;c.destroy$.next();c.destroy$.complete();c.playing$.complete();c.speed$.complete(); c.wantedBufferAhead$.complete();c.maxBufferAhead$.complete();c.maxBufferBehind$.complete();c.playing$=null;c.speed$=null;c.wantedBufferAhead$=null;c.maxBufferAhead$=null;c.maxBufferBehind$=null;c.unsubscribeLoadedVideo$=null;c.fullScreenSubscription=null;c.errorStream$=null;c.lastBitrates=null;c.manualBitrates=null;this.videoElement=c.initialMaxAutoBitrates=null};d.prototype.loadVideo=function(){var c=this,b=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};b=a.i(H.b)(b,this);e.a.info("loadvideo", b);var f=b,d=f.autoPlay;b=f.defaultAudioTrack;var l=f.defaultTextTrack,h=f.hideNativeSubtitle,n=f.keySystems,r=f.startAt,p=f.supplementaryImageTracks,w=f.supplementaryTextTracks,y=f.transport,x=f.transportOptions;f=f.url;a.i(q.a)(f,"you have to give an url");a.i(q.a)(y,"you have to set the transport type");var C=u.a[y];a.i(q.a)(C,'transport "'+y+'" not supported');C=C(x);this.stop();this._priv.initialAudioTrack=b;this._priv.initialTextTrack=l;this._priv.playing$.next(d);x=this.videoElement;var D= this._priv;b=D.errorStream$;l=D.unsubscribeLoadedVideo$;var E=D.wantedBufferAhead$,I=D.maxBufferAhead$;D=D.maxBufferBehind$;var G=!y.directFile;y=a.i(B.a)(x,{withMediaSource:G});var J={initialBitrates:this._priv.lastBitrates,manualBitrates:this._priv.manualBitrates,maxAutoBitrates:this._priv.initialMaxAutoBitrates,throttle:this._priv.throttleWhenHidden&&{video:a.i(t.b)().map(function(a){return a?0:Infinity}).takeUntil(l)},limitWidth:this._priv.limitVideoWidth&&{video:a.i(t.c)(x).takeUntil(l)}};E= {wantedBufferAhead$:E,maxBufferAhead$:I,maxBufferBehind$:D};d=a.i(v.a)({adaptiveOptions:J,autoPlay:d,bufferOptions:E,errorStream:b,hideNativeSubtitle:h,keySystems:n,speed$:this._priv.speed$,startAt:r,timings$:y,transport:C,url:f,videoElement:x,withMediaSource:G,supplementaryImageTracks:p,supplementaryTextTracks:w}).takeUntil(l).publish();h=g(d,"stalled").startWith(null);h=g(d,"loaded").take(1).share().mapTo(z.a.LOADED).concat(k.Observable.combineLatest(this._priv.playing$,h,A.a)).distinctUntilChanged().startWith(z.a.LOADING); n=a.i(m.a)(x,["play","pause"]);r=a.i(m.a)(x.textTracks,["addtrack"]);var K=void 0;l.take(1).subscribe(function(){K&&K.unsubscribe()});p=function(){};n.takeUntil(l).subscribe(function(a){return c._priv.onPlayPauseNext(a)},p);r.takeUntil(l).subscribe(function(a){return c._priv.onNativeTextTrackNext(a)},p);y.takeUntil(l).subscribe(function(a){return c._priv.triggerTimeChange(a)},p);h.takeUntil(l).subscribe(function(a){return c._priv.setPlayerState(a)},p);d.subscribe(function(a){return c._priv.onStreamNext(a)}, function(a){return c._priv.onStreamError(a)},function(){return c._priv.onStreamComplete()});b.takeUntil(l).subscribe(function(a){return c._priv.onErrorStreamNext(a)});K=d.connect()};d.prototype.getError=function(){return this._priv.fatalError};d.prototype.getManifest=function(){return this._priv.manifest||null};d.prototype.getCurrentAdaptations=function(){return this._priv.manifest?this._priv.currentAdaptations:null};d.prototype.getCurrentRepresentations=function(){return this._priv.manifest?this._priv.currentRepresentations: null};d.prototype.getVideoElement=function(){return this.videoElement};d.prototype.getNativeTextTrack=function(){return 0<this.videoElement.textTracks.length?this.videoElement.textTracks[0]:null};d.prototype.getPlayerState=function(){return this.state};d.prototype.isLive=function(){return this._priv.manifest?this._priv.manifest.isLive:!1};d.prototype.getUrl=function(){if(this._priv.manifest)return this._priv.manifest.getUrl()};d.prototype.getVideoDuration=function(){return this.videoElement.duration}; d.prototype.getVideoBufferGap=function(){return a.i(r.a)(this.videoElement.buffered,this.videoElement.currentTime)};d.prototype.getVideoLoadedTime=function(){return a.i(r.b)(this.videoElement.buffered,this.videoElement.currentTime)};d.prototype.getVideoPlayedTime=function(){return a.i(r.c)(this.videoElement.buffered,this.videoElement.currentTime)};d.prototype.getWallClockTime=function(){if(!this._priv.manifest)return 0;var c=this.videoElement.currentTime;return this.isLive()?+a.i(w.a)(c,this._priv.manifest)/ 1E3:c};d.prototype.getPosition=function(){return this.videoElement.currentTime};d.prototype.getPlaybackRate=function(){return this._priv.speed$.getValue()};d.prototype.getVolume=function(){return this.videoElement.volume};d.prototype.isFullscreen=function(){return a.i(p.b)()};d.prototype.getAvailableVideoBitrates=function(){var a=this._priv.currentAdaptations.video;return a?a.representations.map(function(a){return a.bitrate}):[]};d.prototype.getAvailableAudioBitrates=function(){var a=this._priv.currentAdaptations.audio; return a?a.representations.map(function(a){return a.bitrate}):[]};d.prototype.getManualAudioBitrate=function(){return this._priv.manualBitrates.audio};d.prototype.getManualVideoBitrate=function(){return this._priv.manualBitrates.video};d.prototype.getVideoBitrate=function(){return this._priv.recordedEvents.videoBitrate};d.prototype.getAudioBitrate=function(){return this._priv.recordedEvents.audioBitrate};d.prototype.getMaxVideoBitrate=function(){return this._priv.abrManager?this._priv.abrManager.getMaxAutoBitrate("video"): this._priv.initialMaxAutoBitrates.video};d.prototype.getMaxAudioBitrate=function(){return this._priv.abrManager?this._priv.abrManager.getMaxAutoBitrate("audio"):this._priv.initialMaxAutoBitrates.audio};d.prototype.play=function(){this.videoElement.play()};d.prototype.pause=function(){this.videoElement.pause()};d.prototype.setPlaybackRate=function(a){this._priv.speed$.next(a)};d.prototype.seekTo=function(c){a.i(q.a)(this._priv.manifest,"player: no manifest loaded");var b=void 0,e="undefined"===typeof c? "undefined":E(c);if("number"===e)b=c;else if("object"===e)if(b=this.videoElement.currentTime,null!=c.relative)b+=c.relative;else if(null!=c.position)b=c.position;else if(c.wallClockTime)b=a.i(w.b)(1E3*c.wallClockTime,this._priv.manifest);else throw Error('invalid time object. You must set one of the following properties: "relative", "position" or "wallClockTime"');if(void 0===b)throw Error("invalid time given");return this.videoElement.currentTime=b};d.prototype.exitFullscreen=function(){a.i(p.c)()}; d.prototype.setFullscreen=function(){(0<arguments.length&&void 0!==arguments[0]?arguments[0]:1)?a.i(p.d)(this.videoElement):a.i(p.c)()};d.prototype.setVolume=function(a){a!==this.videoElement.volume&&(this.videoElement.volume=a,this.trigger("volumeChange",a))};d.prototype.isMute=function(){return!this.getVolume()};d.prototype.mute=function(){this._priv.mutedMemory=this.getVolume();this.setVolume(0)};d.prototype.unMute=function(){0===this.getVolume()&&this.setVolume(this._priv.mutedMemory||J)};d.prototype.setVideoBitrate= function(a){this._priv.manualBitrates.video=a;this._priv.abrManager&&this._priv.abrManager.setManualBitrate("video",a)};d.prototype.setAudioBitrate=function(a){this._priv.manualBitrates.audio=a;this._priv.abrManager&&this._priv.abrManager.setManualBitrate("audio",a)};d.prototype.setMaxVideoBitrate=function(a){this._priv.initialMaxAutoBitrates.video=a;this._priv.abrManager&&this._priv.abrManager.setMaxAutoBitrate("video",a)};d.prototype.setMaxAudioBitrate=function(a){this._priv.initialMaxAutoBitrates.audio= a;this._priv.abrManager&&this._priv.abrManager.setMaxAutoBitrate("audio",a)};d.prototype.setMaxBufferBehind=function(a){this._priv.maxBufferBehind$.next(a)};d.prototype.setMaxBufferAhead=function(a){this._priv.maxBufferAhead$.next(a)};d.prototype.setWantedBufferAhead=function(a){this._priv.wantedBufferAhead$.next(a)};d.prototype.getMaxBufferBehind=function(){return this._priv.maxBufferBehind$.getValue()};d.prototype.getMaxBufferAhead=function(){return this._priv.maxBufferAhead$.getValue()};d.prototype.getWantedBufferAhead= function(){return this._priv.wantedBufferAhead$.getValue()};d.prototype.getCurrentKeySystem=function(){return a.i(y.b)()};d.prototype.getAvailableAudioTracks=function(){return this._priv.languageManager?this._priv.languageManager.getAvailableAudioTracks():null};d.prototype.getAvailableTextTracks=function(){return this._priv.languageManager?this._priv.languageManager.getAvailableTextTracks():null};d.prototype.getAudioTrack=function(){if(this._priv.languageManager)return this._priv.languageManager.getCurrentAudioTrack()}; d.prototype.getTextTrack=function(){if(this._priv.languageManager)return this._priv.languageManager.getCurrentTextTrack()};d.prototype.setAudioTrack=function(c){a.i(q.a)(this._priv.languageManager,"No compatible content launched.");try{this._priv.languageManager.setAudioTrack(c)}catch(L){throw Error("player: unknown audio track");}};d.prototype.setTextTrack=function(c){a.i(q.a)(this._priv.languageManager,"No compatible content launched.");try{this._priv.languageManager.setTextTrack(c)}catch(L){throw Error("player: unknown text track"); }};d.prototype.disableTextTrack=function(){if(this._priv.languageManager)return this._priv.languageManager.disableTextTrack()};d.prototype.getImageTrackData=function(){return this._priv.manifest?this._priv.currentImagePlaylist:null};d.prototype.getMinimumPosition=function(){return this._priv.manifest?a.i(w.c)(this._priv.manifest):null};d.prototype.getMaximumPosition=function(){return this._priv.manifest?a.i(w.d)(this._priv.manifest):null};return d}(n.a);d.a=b},function(b,d,a){d.a=function(a,b){return b? "seeking"==b.state?h.a.SEEKING:h.a.BUFFERING:a?h.a.PLAYING:h.a.PAUSED};var h=a(35)},function(b,d,a){b=a(21);var h=a.n(b),l=function(a,b){if(!b)return null;if(a.length)return h()(a,function(a){return b.normalized===a.normalizedLanguage&&b.closedCaption===a.isClosedCaption})},g=function(a,b){if(a.length&&b)return h()(a,function(a){return b.normalized===a.normalizedLanguage&&b.audioDescription===a.isAudioDescription})};a=function(){function a(b,c){var e=b.text,f=b.audio,d=c.text$,k=c.audio$,h=2<arguments.length&& void 0!==arguments[2]?arguments[2]:{};if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");var p=h.defaultAudioTrack;h=h.defaultTextTrack;e=e||[];f=f||[];this._currentTextAdaptation=this._currentAudioAdaptation=null;this._textAdaptations=e;this._audioAdaptations=f;this._text$=d;if(this._audio$=k)this._currentAudioAdaptation=p?g(f,p)||f[0]:f[0],k.next(this._currentAudioAdaptation);d&&(this._currentTextAdaptation=h?l(e,h)||null:null,d.next(this._currentTextAdaptation))}a.prototype.updateAdaptations= function(a){var c=a.audio;a=a.text;this._audioAdaptations=c||[];this._textAdaptations=a||[];var b=this._currentAudioAdaptation,f=b&&b.id,d=void 0;null!=f&&(d=h()(c,function(a){return a.id===f}));d||(this._currentAudioAdaptation=g(c,{language:b.language,audioDescription:!!b.isAudioDescription})||c[0],this._audio$.next(this._currentAudioAdaptation));var k=(c=this._currentTextAdaptation)&&c.id;b=void 0;null!=k&&(b=h()(a,function(a){return a.id===k}));null===k||b||(this._currentTextAdaptation=l(a,{language:c.language, closedCaption:!!c.isClosedCaption})||a[0],this._text$.next(this._currentTextAdaptation))};a.prototype.setAudioTrack=function(a){var c=h()(this._audioAdaptations,function(c){return c.id===a});if(void 0===c)throw Error("Audio Track not found.");this._currentAudioAdaptation=c;this._audio$.next(this._currentAudioAdaptation)};a.prototype.setTextTrack=function(a){var c=h()(this._textAdaptations,function(c){return c.id===a});if(void 0===c)throw Error("Text Track not found.");this._currentTextAdaptation= c;this._text$.next(this._currentTextAdaptation)};a.prototype.disableTextTrack=function(){this._currentTextAdaptation=null;this._text$.next(this._currentTextAdaptation)};a.prototype.getCurrentAudioTrack=function(){var a=this._currentAudioAdaptation;return a?{language:a.language,normalized:a.normalizedLanguage,audioDescription:a.isAudioDescription,id:a.id}:null};a.prototype.getCurrentTextTrack=function(){var a=this._currentTextAdaptation;return a?{language:a.language,normalized:a.normalizedLanguage, closedCaption:a.isClosedCaption,id:a.id}:null};a.prototype.getAvailableAudioTracks=function(){var a=this._currentAudioAdaptation,c=a&&a.id;return this._audioAdaptations.map(function(a){return{language:a.language,normalized:a.normalizedLanguage,audioDescription:a.isAudioDescription,id:a.id,active:null==c?!1:c===a.id}})};a.prototype.getAvailableTextTracks=function(){var a=this._currentTextAdaptation,c=a&&a.id;return this._textAdaptations.map(function(a){return{language:a.language,normalized:a.normalizedLanguage, closedCaption:a.isClosedCaption,id:a.id,active:null==c?!1:c===a.id}})};return a}();d.a=a},function(b,d,a){function h(){var c=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},b={transport:c.transport,transportOptions:v(c.transportOptions,{}),maxBufferAhead:v(c.maxBufferAhead,r),maxBufferBehind:v(c.maxBufferBehind,p),limitVideoWidth:v(c.limitVideoWidth,x),defaultAudioTrack:a.i(f.b)(v(c.defaultAudioTrack,m)),defaultTextTrack:a.i(f.c)(v(c.defaultTextTrack,n)),wantedBufferAhead:v(c.wantedBufferAhead, q),throttleWhenHidden:v(c.throttleWhenHidden,w),videoElement:c.videoElement?c.videoElement:document.createElement("video")},e=t||{},d=u||{};b.initialAudioBitrate=v(c.initialAudioBitrate,e.audio,e.other);b.initialVideoBitrate=v(c.initialVideoBitrate,e.video,e.other);b.maxAudioBitrate=v(c.maxAudioBitrate,d.audio,d.other);b.maxVideoBitrate=v(c.maxVideoBitrate,d.video,d.other);return b}function l(){var b=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},d=arguments[1],g=d.defaultTransportOptions, m=d._priv,l=m.lastTextTrack;m=m.lastAudioTrack;d={url:b.url,transport:v(b.transport,d.defaultTransport),autoPlay:v(b.autoPlay,c),keySystems:v(b.keySystems,[]),transportOptions:v(b.transportOptions,g),hideNativeSubtitle:v(b.hideNativeSubtitle,!e),supplementaryTextTracks:v(b.supplementaryTextTracks,[]),supplementaryImageTracks:v(b.supplementaryImageTracks,[]),defaultAudioTrack:a.i(f.b)(v(b.defaultAudioTrack,m)),defaultTextTrack:a.i(f.c)(v(b.defaultTextTrack,l))};d.startAt=b.startAt&&b.startAt.wallClockTime instanceof Date?k()({},b.startAt,{wallClockTime:b.startAt.wallClockTime/1E3}):b.startAt;b.directFile&&(d.transport="directfile");return d}a.d(d,"a",function(){return h});a.d(d,"b",function(){return l});b=a(4);d=a(167);var g=a(8),k=a.n(g),f=a(30),c=b.a.DEFAULT_AUTO_PLAY,e=b.a.DEFAULT_SHOW_SUBTITLE,m=b.a.DEFAULT_AUDIO_TRACK,n=b.a.DEFAULT_TEXT_TRACK,q=b.a.DEFAULT_WANTED_BUFFER_AHEAD,r=b.a.DEFAULT_MAX_BUFFER_AHEAD,p=b.a.DEFAULT_MAX_BUFFER_BEHIND,t=b.a.DEFAULT_INITIAL_BITRATES,u=b.a.DEFAULT_MAX_BITRATES,w=b.a.DEFAULT_THROTTLE_WHEN_HIDDEN, x=b.a.DEFAULT_LIMIT_VIDEO_WIDTH,v=d.a},function(b,d,a){b=a(169);var h=a.n(b),l=a(1);a(2);var g=a(28),k=a(35),f=a(100);d.a=function(c){return{resetContentState:function(){c._priv.initialAudioTrack=void 0;c._priv.initialTextTrack=void 0;c._priv.languageManager=null;c._priv.abrManager=null;c._priv.manifest=null;c._priv.currentRepresentations={};c._priv.currentAdaptations={};c._priv.recordedEvents={};c._priv.fatalError=null;c._priv.currentImagePlaylist=null},recordState:function(a,b){var e=c._priv.recordedEvents[a]; h()(e,b)||(c._priv.recordedEvents[a]=b,c.trigger(a+"Change",b))},onStreamNext:function(a){var b=a.value;switch(a.type){case "representationChange":c._priv.onRepresentationChange(b);break;case "manifestUpdate":c._priv.onManifestUpdate(b);break;case "adaptationChange":c._priv.onAdaptationChange(b);break;case "bitrateEstimationChange":c._priv.onBitrateEstimationChange(b);break;case "manifestChange":c._priv.onManifestChange(b);break;case "pipeline":a=b.parsed,"image"===b.bufferType&&(c._priv.currentImagePlaylist= a.segmentData,c.trigger("imageTrackUpdate",{data:c._priv.currentImagePlaylist}))}},onErrorStreamNext:function(a){c.trigger("warning",a)},onStreamError:function(a){c._priv.resetContentState();c._priv.fatalError=a;c._priv.unsubscribeLoadedVideo$.next();c._priv.setPlayerState(k.a.STOPPED);c._priv.fatalError===a&&c.trigger("error",a)},onStreamComplete:function(){c._priv.resetContentState();c._priv.unsubscribeLoadedVideo$.next();c._priv.setPlayerState(k.a.ENDED)},onManifestChange:function(a){var b=a.manifest, e=a.adaptations$,d=void 0===e?{}:e;c._priv.manifest=b;c._priv.languageManager=new f.a(b.adaptations,{audio$:d.audio,text$:d.text},{defaultAudioTrack:c._priv.initialAudioTrack,defaultTextTrack:c._priv.initialTextTrack});Object.keys(d).forEach(function(a){"audio"!==a&&"text"!==a&&d[a].next((b.adaptations[a]||[])[0]||null)});c._priv.abrManager=a.abrManager;c.trigger("manifestChange",b)},onManifestUpdate:function(a){a=a.manifest;c._priv.manifest=a;c._priv.languageManager.updateAdaptations(a.adaptations); c.trigger("manifestUpdate",a)},onAdaptationChange:function(a){var b=a.type;c._priv.currentAdaptations[b]=a.adaptation;c._priv.languageManager&&("audio"===b?(a=c._priv.languageManager.getCurrentAudioTrack(),c._priv.lastAudioTrack=a,c._priv.recordState("audioTrack",a)):"text"===b&&(a=c._priv.languageManager.getCurrentTextTrack(),c._priv.lastTextTrack=a,c._priv.recordState("textTrack",a)))},onRepresentationChange:function(a){var b=a.type;a=a.representation;a=(c._priv.currentRepresentations[b]=a)&&a.bitrate; null!=a&&(c._priv.lastBitrates[b]=a);"video"==b?c._priv.recordState("videoBitrate",null!=a?a:-1):"audio"==b&&c._priv.recordState("audioBitrate",null!=a?a:-1)},onBitrateEstimationChange:function(a){c._priv.recordState("bitrateEstimation",{type:a.type,bitrate:a.bitrate})},onPlayPauseNext:function(a){!0!==c.videoElement.ended&&c._priv.playing$.next("play"==a.type)},onNativeTextTrackNext:function(a){(a=a.target[0])&&c.trigger("nativeTextTrackChange",a)},setPlayerState:function(a){c.state!==a&&(c.state= a,l.a.info("playerStateChange",a),c.trigger("playerStateChange",a))},triggerTimeChange:function(b){if(c._priv.manifest&&b){var e={position:b.currentTime,duration:b.duration,playbackRate:b.playbackRate,bufferGap:isFinite(b.bufferGap)?b.bufferGap:0};c._priv.manifest.isLive&&0<b.currentTime&&(e.wallClockTime=a.i(g.a)(b.currentTime,c._priv.manifest).getTime()/1E3,e.liveGap=a.i(g.d)(c._priv.manifest)-b.currentTime);c.trigger("positionUpdate",e)}}}}},function(b,d,a){d.a=function(b,d,f,c){if(!isFinite(f)&& !isFinite(c))return h.Observable.empty();var e=[],k=a.i(l.g)(b.getBuffered(),d),g=k.innerRange,q=k.outerRanges;(function(){if(isFinite(f)){for(var a=0;a<q.length;a++){var c=q[a];d-f>=c.end?e.push(c):d>=c.end&&d-f>c.start&&d-f<c.end&&e.push({start:c.start,end:d-f})}g&&d-f>g.start&&e.push({start:g.start,end:d-f})}})();(function(){if(isFinite(c)){for(var a=0;a<q.length;a++){var b=q[a];d+c<=b.start?e.push(b):d<=b.start&&d+c<b.end&&d+c>b.start&&e.push({start:d+c,end:b.end})}g&&d+c<g.end&&e.push({start:d+ c,end:g.end})}})();return h.Observable.from(e.map(function(a){return b.removeBuffer(a)})).concatAll().ignoreElements()};var h=a(0);a.n(h);var l=a(10)},function(b,d,a){function h(c,b,f){var e=a.i(k.g)(b,c);b=e.innerRange;e=e.outerRanges;for(var d=[],m=0;m<e.length;m++){var l=e[m];c-f<l.end?d.push(l):c+f>l.start&&d.push(l)}b&&(g.a.debug("buffer: gc removing part of inner range",d),c-f>b.start&&d.push({start:b.start,end:c-f}),c+f<b.end&&d.push({start:c+f,end:b.end}));return d}d.a=function(a,b){g.a.warn("buffer: running garbage collector"); return a.take(1).mergeMap(function(a){var e=b.getBuffered(),d=h(a.currentTime,e,f);0===d.length&&(d=h(a.currentTime,e,c));g.a.debug("buffer: gc cleaning",d);return l.Observable.from(d.map(function(a){return b.removeBuffer(a)})).concatAll()})};var l=a(0);a.n(l);b=a(4);var g=a(1),k=a(10),f=b.a.BUFFER_GC_GAPS.CALM,c=b.a.BUFFER_GC_GAPS.BEEFY},function(b,d,a){function h(b){function d(b){function k(a){if(l.test(a.id))return!1;if(a.isInit||0>a.time)return!0;a=L.hasCompleteSegment(a.time,a.duration,a.timescale); return!a||a.bitrate*u<b.bitrate}c.a.info("bitrate",E,b.bitrate);var l=new e.a,q=function(a){return h({segment:a,representation:b,init:J}).map(function(c){return f()({segment:a},c)})},r=g.Observable.combineLatest(B,C,A,H).mergeMap(function(e,f){var d=e[0],h=e[2],r=e[3];var p=Math.min(e[1],r);var v=M.getBuffered();L.addBufferedInfos(v);d.stalled&&I&&(e=b.index.checkDiscontinuity(d.currentTime),0<e&&D.next({type:"index-discontinuity",value:{ts:e+1}}));e=null;0===f&&(c.a.debug("add init segment",E),e= b.index.getInitSegment());if(0===d.readyState)e=e?[e]:[];else{f=G;var w=Q,u=w;w=d.currentTime+d.timeOffset;var A=(d.duration||Infinity)-w;p=Math.max(0,null==d.liveGap?Math.min(p,A):Math.min(p,d.liveGap,A));v=a.i(m.a)(v,w);v=w+(v>f&&Infinity>v?Math.min(v,u):0);f=p=w+p;p=f-v;b.index.shouldRefresh(d.currentTime+d.timeOffset,v,f)&&(f=new n.g("OUT_OF_INDEX_ERROR",b.index.getType(),!1),D.next({type:"out-of-index",value:f}));v=b.index.getSegments(v,p);e&&v.unshift(e);e=v}e=e.filter(k);for(v=0;v<e.length;v++)l.add(e[v].id); e=g.Observable.of.apply(g.Observable,e).concatMap(q);d=a.i(t.a)(M,d.currentTime,h,r);return g.Observable.merge(e,d)}).concatMap(function(c){var e=c.segment,d=c.parsed,k=d.segmentData,g=d.nextSegments,m=d.segmentInfos;e.isInit&&(J=m);var h=g?b.index._addSegments(g,m):[],q=function(){l.remove(e.id);if(!e.isInit){var a=m?m:e,c=a.time,f=a.timescale;L.insert(e,c/f,(c+a.duration)/f,b.bitrate)}},r=function(){return M.appendBuffer(k).do(q)};return r().catch(function(c){if("QuotaExceededError"!=c.name)throw l.remove(e.id), new n.f("BUFFER_APPEND_ERROR",c,!0);return a.i(p.a)(B,M).mergeMap(r).catch(function(a){l.remove(e.id);throw new n.f("BUFFER_FULL_ERROR",a,!0);})}).map(function(){return{type:"pipeline",value:f()({bufferType:E,addedSegments:h},c)}})});return g.Observable.merge(r,D).catch(function(a){if(!I||a.type!=n.a.NETWORK_ERROR||!a.isHttpError(412))throw a;return g.Observable.of({type:"precondition-failed",value:a}).concat(g.Observable.timer(2E3)).concat(d(b))}).startWith({type:"representationChange",value:{type:E, representation:b}})}var l=b.sourceBuffer,h=b.downloader,w=b.switch$,B=b.clock$,C=b.wantedBufferAhead,A=b.maxBufferBehind,H=b.maxBufferAhead,E=b.bufferType,I=b.isLive,J=null,D=new k.Subject,G="video"==E?4:1,Q="video"==E?6:1,L=new q.a,M=new r.a(l);return w.switchMap(d).finally(function(){return M.dispose()})}function l(a){return g.Observable.of({type:"representationChange",value:{type:a.bufferType,representation:null}})}a.d(d,"b",function(){return h});a.d(d,"a",function(){return l});var g=a(0);a.n(g); var k=a(5);a.n(k);b=a(8);var f=a.n(b);b=a(4);var c=a(1),e=a(161),m=a(10),n=a(6),q=a(107),r=a(106),p=a(104),t=a(103),u=b.a.BITRATE_REBUFFERING_RATIO},function(b,d,a){var h=a(5);a.n(h);b=function(){function a(b){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this.buffer=b;this.queue=[];this.flushing=null;this.__onUpdate=this._onUpdate.bind(this);this.__onError=this._onError.bind(this);this.__flush=this._flush.bind(this);this.buffer.addEventListener("update",this.__onUpdate); this.buffer.addEventListener("error",this.__onError);this.buffer.addEventListener("updateend",this.__flush)}a.prototype.appendBuffer=function(a){return this._queueAction("append",a)};a.prototype.removeBuffer=function(a){return this._queueAction("remove",{start:a.start,end:a.end})};a.prototype.getBuffered=function(){return this.buffer.buffered};a.prototype.dispose=function(){this.buffer.removeEventListener("update",this.__onUpdate);this.buffer.removeEventListener("error",this.__onError);this.buffer.removeEventListener("updateend", this.__flush);this.buffer=null;this.queue.length=0;this.flushing=null};a.prototype._onUpdate=function(a){this.flushing&&(this.flushing.next(a),this.flushing.complete(),this.flushing=null)};a.prototype._onError=function(a){this.flushing&&(this.flushing.error(a),this.flushing=null)};a.prototype._queueAction=function(a,b){var f=new h.Subject;1===this.queue.unshift({type:a,args:b,subj:f})&&this._flush();return f};a.prototype._flush=function(){if(!this.flushing&&0!==this.queue.length&&!this.buffer.updating){var a= this.queue.pop(),b=a.type,f=a.args;this.flushing=a.subj;try{switch(b){case "append":this.buffer.appendBuffer(f);break;case "remove":this.buffer.remove(f.start,f.end)}}catch(c){this._onError(c)}}};return a}();d.a=b},function(b,d,a){b=a(4);a(2);var h=a(168),l=a(10),g=b.a.MAX_MISSING_FROM_COMPLETE_SEGMENT,k=b.a.MAX_BUFFERED_DISTANCE,f=b.a.MINIMUM_SEGMENT_SIZE;b=function(){function c(){if(!(this instanceof c))throw new TypeError("Cannot call a class as a function");this._inventory=[]}c.prototype.addBufferedInfos= function(c){c=a.i(l.h)(c);for(var b=c.length-1,e=this._inventory,d=0,g=e[0],p=0;p<=b;p++){if(!g)return;var t=c[p],u=t.start;t=t.end;if(!(t-u<f)){for(var w=d;g&&a.i(h.a)(g.bufferedEnd,g.end)-u<f;)g=e[++d];var x=-1,v=d-w;v&&(d=e[w+v-1],x=a.i(h.a)(d.bufferedEnd,d.end),e.splice(w,v),d=w);if(!g)return;t-a.i(h.a)(g.bufferedStart,g.start)>=f&&(null!=g.bufferedStart&&g.bufferedStart<u?g.bufferedStart=u:null==g.bufferedStart&&(-1!==x&&x>u?g.bufferedStart-x<=k&&(g.bufferedStart=x):g.bufferedStart=g.start-u<= k?u:g.start),g=e[++d]);for(;g&&t-a.i(h.a)(g.bufferedStart,g.start)>=f;)u=e[d-1],null==u.bufferedEnd&&(u.bufferedEnd=u.end),g.bufferedStart=u.bufferedEnd,g=e[++d];if(u=e[d-1])null!=u.bufferedEnd&&u.bufferedEnd>t?u.bufferedEnd=t:null==u.bufferedEnd&&(u.bufferedEnd=t-u.end<=k?t:u.end)}}g&&e.splice(d,e.length-d)};c.prototype.insert=function(a,c,b,f){if(null!=b){var e=this._inventory;b={bitrate:f,start:c,end:b,bufferedStart:void 0,bufferedEnd:void 0,segment:a};for(f=e.length-1;0<=f;f--){var d=e[f];if(d.start<= c){d.end<=c?this._inventory.splice(f+1,0,b):d.start>=c?this._inventory.splice(f,1,b):(null!=d.end&&(d.end=c),this._inventory.splice(f+1,0,b));return}}(e=this._inventory[0])?null==a.end?e.start===c?this._inventory.splice(0,1,b):this._inventory.splice(0,0,b):e.start>=a.end?this._inventory.splice(0,0,b):e.end<=a.end?this._inventory.splice(0,1,b):(e.start=a.end,this._inventory.splice(0,0,b)):this._inventory.push(b)}};c.prototype.hasCompleteSegment=function(a,c,b){for(var e=this._inventory,f=e.length- 1;0<=f;f--){var d=e[f],k=d.segment,m=a,l=c;k.timescale!==b&&(m=a*k.timescale/b,l=c*k.timescale/b);if(k.time===m&&k.duration===l){if((a=e[f-1])&&null==a.bufferedEnd||null==d.bufferedStart)break;if((!a||a.bufferedEnd<d.bufferedStart)&&d.bufferedStart-d.start>g)break;if((e=e[f+1])&&null==e.bufferedStart||null==d.bufferedEnd)break;if(null!=d.end&&(!e||e.bufferedStart>d.bufferedEnd)&&d.end-d.bufferedEnd>g)break;return d}}return null};return c}();d.a=b},function(b,d,a){a.d(d,"a",function(){return h});var h= {expired:!0,"internal-error":!0}},function(b,d,a){function h(b){var e=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},f=e.$keySystem,d=e.$mediaKeys,k=e.$mediaKeySystemConfiguration;return f&&d&&!a.i(c.e)()?(e=b.filter(function(a){return a.type!==f.type||a.persistentLicense&&"required"!=k.persistentState||a.distinctiveIdentifierRequired&&"required"!=k.distinctiveIdentifier?!1:!0})[0])?{keySystem:e,keySystemAccess:new c.f(f,d,k)}:null:null}function l(a){var c=["temporary"],b="optional",e= "optional";a.persistentLicense&&(b="required",c.push("persistent-license"));a.persistentStateRequired&&(b="required");a.distinctiveIdentifierRequired&&(e="required");var f=a.audioRobustnesses||m;a=(a.videoRobustnesses||m).map(function(a){return{contentType:'video/mp4;codecs="avc1.4d401e"',robustness:a}});f=f.map(function(a){return{contentType:'audio/mp4;codecs="mp4a.40.2"',robustness:a}});return[{initDataTypes:["cenc"],videoCapabilities:a,audioCapabilities:f,distinctiveIdentifier:e,persistentState:b, sessionTypes:c},{initDataTypes:["cenc"],videoCapabilities:void 0,audioCapabilities:void 0,distinctiveIdentifier:e,persistentState:b,sessionTypes:c}]}function g(){var a=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};return a.$keySystem&&a.$keySystem.type}a.d(d,"b",function(){return g});var k=a(0);a.n(k);b=a(4);var f=a(1),c=a(7),e=a(6),m=b.a.EME_DEFAULT_WIDEVINE_ROBUSTNESSES,n=b.a.EME_KEY_SYSTEMS;d.a=function(b,d){if(d=h(b,d))return f.a.debug("eme: found compatible keySystem quickly",d), k.Observable.of(d);var g=b.reduce(function(a,c){return a.concat((n[c.type]||[]).map(function(a){return{keyType:a,keySystem:c}}))},[]);return k.Observable.create(function(b){function d(h){if(!k)if(h>=g.length)b.error(new e.c("INCOMPATIBLE_KEYSYSTEMS",null,!0));else{var n=g[h],q=n.keyType,r=n.keySystem,p=l(r);f.a.debug("eme: request keysystem access "+q+","+(h+1+" of "+g.length),p);m=a.i(c.g)(q,p).subscribe(function(a){f.a.info("eme: found compatible keysystem",q,p);b.next({keySystem:r,keySystemAccess:a}); b.complete()},function(){f.a.debug("eme: rejected access to keysystem",q,p);m=null;d(h+1)})}}var k=!1,m=null;d(0);return function(){k=!0;m&&m.unsubscribe()}})}},function(b,d,a){function h(c,b){return g.Observable.defer(function(){return a.i(k.a)(c.setServerCertificate(b)).ignoreElements().catch(function(a){throw new f.c("LICENSE_SERVER_CERTIFICATE_ERROR",a,!0);})})}function l(a,b,f){return h(a,b).catch(function(a){a.fatal=!1;f.next(a);return g.Observable.empty()})}a.d(d,"a",function(){return l}); var g=a(0);a.n(g);var k=a(9),f=a(6)},function(b,d,a){function h(a,c,b){return{type:"eme",value:e()({name:a,session:c},b)}}function l(c,b,e){function f(a,c){return a.type===u.a.ENCRYPTED_MEDIA_ERROR?(a.fatal=c,a):new u.c("KEY_LOAD_ERROR",a,c)}x.a.debug("eme: handle message events",c);var d=void 0,k={totalRetry:2,retryDelay:200,errorSelector:function(a){return f(a,!0)},onRetry:function(a){return e.next(f(a,!1))}},g=a.i(t.h)(c).map(function(a){throw new u.c("KEY_ERROR",a,!0);}),l=a.i(t.j)(c).mergeMap(function(e){d= e.sessionId;x.a.debug("eme: keystatuseschange event",d,c,e);c.keyStatuses.forEach(function(a,c){if(w.a[c]||w.a[a])throw new u.c("KEY_STATUS_CHANGE_ERROR",c,!0);});return b.onKeyStatusesChange?a.i(q.a)(function(){return a.i(r.a)(b.onKeyStatusesChange(e,c))}).catch(function(a){throw new u.c("KEY_STATUS_CHANGE_ERROR",a,!0);}):(x.a.info("eme: keystatuseschange event not handled"),m.Observable.empty())}),v=a.i(t.i)(c).mergeMap(function(e){d=e.sessionId;var f=new Uint8Array(e.message),g=e.messageType|| "license-request";x.a.debug("eme: event message type "+g,c,e);e=m.Observable.defer(function(){return a.i(r.a)(b.getLicense(f,g)).timeout(1E4).catch(function(a){if(a instanceof n.TimeoutError)throw new u.c("KEY_LOAD_TIMEOUT",null,!1);throw a;})});return a.i(p.a)(e,k)});l=m.Observable.merge(v,l).concatMap(function(b){x.a.debug("eme: update session",d,b);return a.i(r.a)(c.update(b,d)).catch(function(a){throw new u.c("KEY_UPDATE_ERROR",a,!0);}).mapTo(h("session-update",c,{updatedWith:b}))});g=m.Observable.merge(l, g);return c.closed?g.takeUntil(a.i(r.a)(c.closed)):g}function g(a,c,b,e,f){x.a.debug("eme: create a new "+c+" session");var d=a.createSession(c);a=l(d,b,f).finally(function(){v.b.deleteAndClose(d);v.a.delete(e)}).publish();return{session:d,sessionEvents:a}}function k(c,b,e,f,d,k){c=g(c,e,b,d,k);var l=c.session;c=c.sessionEvents;v.b.add(d,l,c);x.a.debug("eme: generate request",f,d);f=a.i(r.a)(l.generateRequest(f,d)).catch(function(a){throw new u.c("KEY_GENERATE_REQUEST_ERROR",a,!1);}).do(function(){"persistent-license"== e&&v.a.add(d,l)}).mapTo(h("generated-request",l,{initData:d,initDataType:f}));return m.Observable.merge(c,f)}function f(a,c,b,e,f,d){return k(a,c,b,e,f,d).catch(function(g){if(g.code!==u.b.KEY_GENERATE_REQUEST_ERROR)throw g;var l=v.b.getFirst();if(!l)throw g;x.a.warn("eme: could not create a new session, retry after closing a currently loaded session",g);return v.b.deleteAndClose(l).mergeMap(function(){return k(a,c,b,e,f,d)})})}function c(c,b,e,d,k,l){x.a.debug("eme: load persisted session",e);var n= g(c,"persistent-license",b,k,l),q=n.session,p=n.sessionEvents;return a.i(r.a)(q.load(e)).catch(function(){return m.Observable.of(!1)}).mergeMap(function(a){if(a)return v.b.add(k,q,p),v.a.add(k,q),p.startWith(h("loaded-session",q,{storedSessionId:e}));x.a.warn("eme: no data stored for the loaded session, do fallback",e);v.b.deleteById(e);v.a.delete(k);q.sessionId&&q.remove();return f(c,b,"persistent-license",d,k,l).startWith(h("loaded-session-failed",q,{storedSessionId:e}))})}b=a(8);var e=a.n(b),m= a(0);a.n(m);var n=a(80);a.n(n);var q=a(42),r=a(9),p=a(70),t=a(17),u=a(6),w=a(108),x=a(1),v=a(36);d.a=function(a,b,e,d,k,g){return m.Observable.defer(function(){var l=v.b.get(k);if(l&&l.sessionId)return x.a.debug("eme: reuse loaded session",l.sessionId),m.Observable.of(h("reuse-session",l));var n=(l=b.sessionTypes)&&0<=l.indexOf("persistent-license");l=n&&e.persistentLicense?"persistent-license":"temporary";return n&&e.persistentLicense&&(n=v.a.get(k))?c(a,e,n.sessionId,d,k,g):f(a,e,l,d,k,g)})}},function(b, d,a){function h(a,b){if("function"!==typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}var l=a(0);a.n(l);var g=a(1),k=a(9);b=a(58);var f=a(59);b=function(c){function b(){if(!(this instanceof b))throw new TypeError("Cannot call a class as a function");var a=c.apply(this, arguments);if(!this)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!a||"object"!==typeof a&&"function"!==typeof a?this:a}h(b,c);b.prototype.getFirst=function(){if(0<this._entries.length)return this._entries[0].session};b.prototype.find=function(a){for(var c=0;c<this._entries.length;c++)if(!0===a(this._entries[c]))return this._entries[c];return null};b.prototype.get=function(c){c=a.i(f.a)(c);var b=this.find(function(a){return a.initData===c});return b?b.session: null};b.prototype.add=function(c,b,e){c=a.i(f.a)(c);var d=this.get(c);d&&this.deleteAndClose(d);e=e.connect();c={session:b,initData:c,eventSubscription:e};g.a.debug("eme-mem-store: add session",c);this._entries.push(c)};b.prototype.deleteById=function(a){var c=this.find(function(c){return c.session.sessionId===a});return c?this.delete(c.session):null};b.prototype.delete=function(a){var c=this.find(function(c){return c.session===a});if(!c)return null;var b=c.session,e=c.eventSubscription;g.a.debug("eme-mem-store: delete session", c);c=this._entries.indexOf(c);this._entries.splice(c,1);e.unsubscribe();return b};b.prototype.deleteAndClose=function(c){return(c=this.delete(c))?(g.a.debug("eme-mem-store: close session",c),a.i(k.a)(c.close()).catch(function(){return l.Observable.of(null)})):l.Observable.of(null)};b.prototype.dispose=function(){var a=this,c=this._entries.map(function(c){return a.deleteAndClose(c.session)});this._entries=[];return l.Observable.merge.apply(null,c)};return b}(b.a);d.a=b},function(b,d,a){var h=a(112), l=a(114);a.d(d,"b",function(){return h.a});a.d(d,"a",function(){return l.a})},function(b,d,a){function h(a,c){if("function"!==typeof c&&null!==c)throw new TypeError("Super expression must either be null or a function, not "+typeof c);a.prototype=Object.create(c&&c.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});c&&(Object.setPrototypeOf?Object.setPrototypeOf(a,c):a.__proto__=c)}var l=a(1),g=a(2);b=a(58);var k=a(59);b=function(b){function c(a){if(!(this instanceof c))throw new TypeError("Cannot call a class as a function"); var e=b.call(this);if(!this)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");e=!e||"object"!==typeof e&&"function"!==typeof e?this:e;e.setStorage(a);return e}h(c,b);c.prototype.setStorage=function(c){if(this._storage!==c){a.i(g.a)(c,"no licenseStorage given for keySystem with persistentLicense");g.a.iface(c,"licenseStorage",{save:"function",load:"function"});this._storage=c;try{this._entries=this._storage.load(),a.i(g.a)(Array.isArray(this._entries))}catch(m){l.a.warn("eme-persitent-store: could not get entries from license storage", m),this.dispose()}}};c.prototype.get=function(c){c=a.i(k.a)(c);return this.find(function(a){return a.initData===c})||null};c.prototype.add=function(c,b){var e=b&&b.sessionId;if(e){c=a.i(k.a)(c);var f=this.get(c);f&&f.sessionId===e||(f&&this.delete(c),l.a.info("eme-persitent-store: add new session",e,b),this._entries.push({sessionId:e,initData:c}),this._save())}};c.prototype.delete=function(c){c=a.i(k.a)(c);var b=this.find(function(a){return a.initData===c});b&&(l.a.warn("eme-persitent-store: delete session from store", b),b=this._entries.indexOf(b),this._entries.splice(b,1),this._save())};c.prototype.dispose=function(){this._entries=[];this._save()};c.prototype._save=function(){try{this._storage.save(this._entries)}catch(e){l.a.warn("eme-persitent-store: could not save licenses in localStorage")}};return c}(b.a);d.a=b},function(b,d,a){function h(c){return c?a.i(k.h)(c,null):l.Observable.empty()}a.d(d,"b",function(){return h});var l=a(0);a.n(l);var g=a(1),k=a(7),f=a(36);d.a=function(c,b,d,h,q){return l.Observable.defer(function(){var e= q.$videoElement,m=q.$mediaKeys;q.$mediaKeys=c;q.$mediaKeySystemConfiguration=b;q.$keySystem=h;q.$videoElement=d;if(d.mediaKeys===c)return l.Observable.of(c);m&&m!==c&&f.b.dispose();e&&e!==d?(g.a.debug("eme: unlink old video element and set mediakeys"),e=a.i(k.h)(e,null).concat(a.i(k.h)(d,c))):(g.a.debug("eme: set mediakeys"),e=a.i(k.h)(d,c));return e.mapTo(c)})}},function(b,d,a){function h(c){var b=a.i(t.a)(c.locations[0]);return(c=c.periods[0])&&c.baseURL?a.i(t.b)(b,c.baseURL):b}function l(a,c,b, f){if(!c.transportType)throw new w.f("MANIFEST_PARSE_ERROR",null,!0);c.id=c.id||"gen-manifest-"+B++;c.type=c.type||"static";c.isLive="dynamic"==c.type;var d=c.locations;d&&d.length||(c.locations=[a]);var k={rootURL:h(c),baseURL:c.baseURL,isLive:c.isLive};a=c.periods.map(function(a){return g(a,k,b,f)});c=e(c,a[0]);c.periods=null;c.duration||(c.duration=Infinity);c.isLive&&(c.suggestedPresentationDelay=c.suggestedPresentationDelay||0,c.availabilityStartTime=c.availabilityStartTime||0);return new v.a(c)} function g(a,b,e,d){"undefined"==typeof a.id&&(a.id="gen-period-"+B++);var g=a.adaptations.map(function(a){return k(a,b)});e&&g.push.apply(g,f(e).map(function(a){return k(a,b)}));d&&g.push.apply(g,c(d).map(function(a){return k(a,b)}));e=g.filter(function(a){return 0>C.indexOf(a.type)?(p.a.info("not supported adaptation type",a.type),!1):!0});if(0===e.length)throw new w.f("MANIFEST_PARSE_ERROR",null,!0);d={};for(g=0;g<e.length;g++){var l=e[g],h=l.representations,m=l.type;d[m]||(d[m]=[]);0<h.length&& d[m].push(l)}for(var n in d)if(0===d[n].length)throw new w.f("MANIFEST_INCOMPATIBLE_CODECS_ERROR",null,!0);a.adaptations=d;return a}function k(c,b){if("undefined"==typeof c.id)throw new w.f("MANIFEST_PARSE_ERROR",null,!0);var f=e(b,c),d={};z.forEach(function(a){a in f&&(d[a]=f[a])});c=f.representations.map(function(c){var b=f.rootURL,g=f.baseURL;if("undefined"==typeof c.id)throw new w.f("MANIFEST_PARSE_ERROR",null,!0);c=e(d,c);c.index=c.index||{};c.index.timescale||(c.index.timescale=1);c.bitrate|| (c.bitrate=1);"mp4a.40.02"==c.codecs&&(c.codecs="mp4a.40.2");c.baseURL=a.i(t.b)(b,g,c.baseURL);c.codec=c.codecs;return c}).sort(function(a,c){return a.bitrate-c.bitrate});b=f.type;var g=f.accessibility;g=void 0===g?[]:g;if(!b)throw new w.f("MANIFEST_PARSE_ERROR",null,!0);"video"==b||"audio"==b?(c=c.filter(function(c){return a.i(u.p)(n(c))}),"audio"===b&&(b=a.i(r.a)(g,"visuallyImpaired"),f.audioDescription=b)):"text"===b&&(b=a.i(r.a)(g,"hardOfHearing"),f.closedCaption=b);f.representations=c;f.bitrates= c.map(function(a){return a.bitrate});return f}function f(c){return(Array.isArray(c)?c:[c]).reduce(function(c,b){var e=b.mimeType,f=b.codecs,d=b.url,g=b.language,k=b.languages,l=b.closedCaption;g&&(k=[g]);return c.concat(k.map(function(c){return{id:"gen-text-ada-"+B++,type:"text",language:c,normalizedLanguage:a.i(x.a)(c),accessibility:l?["hardOfHearing"]:[],baseURL:d,representations:[{id:"gen-text-rep-"+B++,mimeType:e,codecs:f,index:{indexType:"template",duration:Number.MAX_VALUE,timescale:1,startNumber:0}}]}}))}, [])}function c(a){return(Array.isArray(a)?a:[a]).map(function(a){var c=a.mimeType;a=a.url;return{id:"gen-image-ada-"+B++,type:"image",baseURL:a,representations:[{id:"gen-image-rep-"+B++,mimeType:c,index:{indexType:"template",duration:Number.MAX_VALUE,timescale:1,startNumber:0}}]}})}function e(){for(var a={},c=arguments.length,b=Array(c),f=0;f<c;f++)b[f]=arguments[f];for(c=b.length-1;0<=c;c--){f=b[c];for(var d in f)if(!a.hasOwnProperty(d)){var g=f[d];g&&"object"===("undefined"===typeof g?"undefined": y(g))?g instanceof Date?a[d]=new Date(g.getTime()):Array.isArray(g)?a[d]=g.slice(0):a[d]=e(g):a[d]=g}}return a}function m(a,c){var b=function(a,c){return q()(c,function(c){return c.id===a})},e=a.getAdaptations();c=c.getAdaptations();for(var f=0;f<e.length;f++){var d=b(e[f].id,c);if(d){var g=e[f].representations;d=d.representations;for(var k=0;k<g.length;k++){var l=b(g[k].id,d);l?g[k].index.update(l.index):p.a.warn('manifest: representation "'+g[k].id+'" not found when merging.')}}else p.a.warn('manifest: adaptation "'+ e[f].id+'" not found when merging.')}return a}function n(a){return a.mimeType+';codecs="'+a.codec+'"'}a.d(d,"a",function(){return l});a.d(d,"c",function(){return n});a.d(d,"b",function(){return m});b=a(21);var q=a.n(b),r=a(19),p=a(1),t=a(24),u=a(7),w=a(6),x=a(30),v=a(140),y="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},z="audioSamplingRate codecs codingDependency frameRate height index maxPlayoutRate maximumSAPPeriod mimeType profiles segmentProfiles width".split(" "), B=0,C=["audio","video","text","image"]},function(b,d,a){var h=a(0);a.n(h);var l=a(6),g=a(7),k=a(69);d.a=function(b,c){var e=c.baseDelay,f=c.maxDelay,d=c.maxRetryRegular,q=c.maxRetryOffline,r=c.onRetry,p=0,t=0;return b.catch(function(c,b){var m=c instanceof l.h?c.type===l.j.ERROR_HTTP_CODE?500<=c.status||404==c.status:c.type===l.j.TIMEOUT||c.type===l.j.ERROR_EVENT:!1;if(!m)throw c;m=c.type===l.j.ERROR_EVENT&&a.i(g.q)()?2:1;var n=2===m?q:d;m!==t&&(p=0,t=m);if(++p>n)throw c;r&&r(c,p);c=Math.min(e*Math.pow(2, p-1),f);c=a.i(k.b)(c);return h.Observable.timer(c).mergeMap(function(){return b})})}},function(b,d,a){function h(c,b){var e=2<arguments.length&&void 0!==arguments[2]?arguments[2]:!0;a.i(f.d)(b)||(b=new (b instanceof f.h?f.i:f.e)(c,b,e));return b}d.a=function(b){var f=b.resolver,d=b.loader,v=b.parser,u=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},z=u.maxRetry,B=u.cache,C=new k.Subject;f||(f=g.Observable.of);d||(d=g.Observable.of);v||(v=g.Observable.of);var A={baseDelay:t,maxDelay:p,maxRetryRegular:"number"=== typeof z?z:q,maxRetryOffline:r,onRetry:function(a){C.next(h("PIPELINE_LOAD_ERROR",a,!1))}},H=function(c){return a.i(e.a)(f,c).catch(function(a){throw h("PIPELINE_RESOLVE_ERROR",a);})},E=function(c,b){var f=function(c){return a.i(n.a)(a.i(e.a)(d,c),A).catch(function(a){throw h("PIPELINE_LOAD_ERROR",a);}).do(function(a){var b=a.value;"response"===a.type&&B&&B.add(c,b)}).startWith({type:"request",value:b})},g=B?B.get(c):null;return null===g?f(c):a.i(m.a)(g).map(function(a){return{type:"cache",value:a}}).catch(function(){return f(c)})}, I=function(c){return a.i(e.a)(v,c).catch(function(a){throw h("PIPELINE_PARSING_ERROR",a);})};return function(b){var e=H(b).mergeMap(function(e){return E(e,b).mergeMap(function(b){var f=b.type;b=b.value;if(a.i(c.a)(["cache","data","response"],f)){var d=l()({response:b},e);return("response"===f?g.Observable.of({type:"metrics",value:{size:b.size,duration:b.duration}}):g.Observable.empty()).concat(I(d).map(function(a){return{type:"data",value:l()({parsed:a},d)}}))}return g.Observable.of({type:f,value:b})})}).do(null, null,function(){f.complete()}),f=C.map(function(a){return{type:"error",value:a}});return g.Observable.merge(e,f)}};b=a(8);var l=a.n(b),g=a(0);a.n(g);var k=a(5);a.n(k);b=a(4);var f=a(6),c=a(19),e=a(42),m=a(9),n=a(117),q=b.a.DEFAULT_MAX_PIPELINES_RETRY_ON_ERROR,r=b.a.DEFAULT_MAX_PIPELINES_RETRY_ON_OFFLINE,p=b.a.MAX_BACKOFF_DELAY_BASE,t=b.a.INITIAL_BACKOFF_DELAY_BASE},function(b,d,a){var h=a(6),l=a(1),g=a(57);d.a=function(b,f,c){return f&&f.length?a.i(g.c)(b,f,c):a.i(g.d)(b).map(function(){l.a.error("eme: ciphered media and no keySystem passed"); throw new h.c("MEDIA_IS_ENCRYPTED_ERROR",null,!0);})}},function(b,d,a){d.a=function(b){return a.i(l.a)(b,"error").mergeMap(function(){var a=void 0;switch(b.error.code){case 1:a="MEDIA_ERR_ABORTED";break;case 2:a="MEDIA_ERR_NETWORK";break;case 3:a="MEDIA_ERR_DECODE";break;case 4:a="MEDIA_ERR_SRC_NOT_SUPPORTED"}h.a.error("stream: video element MEDIA_ERR("+a+")");throw new MediaError(a,null,!0);})};var h=a(1),l=a(31)},function(b,d,a){d.a=function(b){function f(b,e,f,d,g,k,l,m){var n=D(e);return l.switchMap(function(l){if(!l)return a.i(y.a)(F, b,e,P,S),a.i(u.a)({bufferType:e}).startWith({type:"adaptationChange",value:{type:e,adaptation:l}});var q=null,r=R.map(function(a){var c=void 0,b=void 0;q&&(c=q.bitrate,q.index&&(b=q.index.getLastPosition()));return{bitrate:c,bufferGap:a.bufferGap,duration:a.duration,isLive:k.isLive,lastIndexPosition:b,position:a.currentTime,speed:U.getValue()}});r=m.get$(e,r,l.representations);var p=r.map(function(a){return a.representation}).distinctUntilChanged(function(a,c){return(a&&a.bitrate)===(c&&c.bitrate)&& (a&&a.id)===(c&&c.id)}).do(function(a){return q=a}),v=a.i(y.b)(F,b,e,f,P,S,{hideNativeSubtitle:ha});p=h.Observable.combineLatest(p,g).map(function(a){return a[0]});v=a.i(u.b)({sourceBuffer:v,downloader:function(c){var b=c.segment,f=c.representation;c=c.init;b=a.i(w.a)(V[e],n)({segment:b,representation:f,adaptation:l,manifest:k,init:c});return a.i(A.a)(e,b,X,Y,O)},switch$:p,clock$:d,wantedBufferAhead:ia,maxBufferBehind:ja,maxBufferAhead:ka,bufferType:e,isLive:k.isLive}).startWith({type:"adaptationChange", value:{type:e,adaptation:l}}).catch(function(b){c.a.error("buffer",e,"has crashed",b);if(!a.i(y.c)(e))return O.next(b),h.Observable.empty();throw b;});r=r.filter(function(a){return null!=a.bitrate}).map(function(a){return{type:"bitrateEstimationChange",value:{type:e,bitrate:a.bitrate}}});return h.Observable.merge(v,r)})}function d(b,e){var f=a.i(v.a)(b,ca),d=f;b=a.i(r.i)(F).do(function(){c.a.info("set initial time",f);F.playbackRate=1;F.currentTime=f;d=0});var g=a.i(r.j)(F).do(function(){c.a.info("canplay event"); T&&F.play();T=!0});return{clock$:e.map(function(a){return k()({timeOffset:d},a)}),loaded$:h.Observable.combineLatest(b,g).take(1).mapTo({type:"loaded",value:!0})}}function n(c){return Z(c.getUrl()).map(function(b){return{type:"manifestUpdate",value:{manifest:a.i(t.b)(c,b)}}})}function G(b,e){b&&a.i(z.a)(b,e.getDuration());var k=a.i(B.a)(e,R),l=k.timings,m=k.seekings,q=d(e,l);k=q.loaded$;var r=q.clock$,p=new x.a(Y,X,aa),v={};q=Object.keys(e.adaptations).map(function(c){v[c]=new g.ReplaySubject(1); var d=a.i(t.c)(e.adaptations[c][0].representations[0]);a.i(y.c)(c)&&a.i(y.d)(b,c,d,P);return f(b,c,d,r,m,e,v[c],p)});q=e.isLive?h.Observable.merge.apply(h.Observable,q).mergeMap(function(a){a:{switch(a.type){case "index-discontinuity":c.a.warn("explicit discontinuity seek",a.value.ts);F.currentTime=a.value.ts;break;case "precondition-failed":e.updateLiveGap(1);c.a.warn("precondition failed",e.presentationLiveGap);break;case "out-of-index":c.a.info("out of index");a=n(e);break a}a=h.Observable.of(a)}return a}): h.Observable.merge.apply(h.Observable,q);var w=h.Observable.of({type:"manifestChange",value:{manifest:e,adaptations$:v,abrManager:p}}),u=a.i(I.a)(F,ba,O),A=a.i(H.a)(F,U,l,{changePlaybackRate:K}).map(function(a){return{type:"speed",value:a}});l=a.i(E.a)(F,e,l).map(function(a){return{type:"stalled",value:a}});var D=a.i(C.a)(F);return h.Observable.merge(q,u,k,w,D,A,l).finally(function(){return p.dispose()})}var aa=b.adaptiveOptions,T=b.autoPlay,N=b.bufferOptions,ba=b.keySystems,ca=b.startAt,da=b.url, F=b.videoElement,U=b.speed$,ea=b.supplementaryTextTracks,fa=b.supplementaryImageTracks,R=b.timings$,ha=b.hideNativeSubtitle,O=b.errorStream,W=b.withMediaSource,K=void 0===W?!0:W,V=b.transport,ia=N.wantedBufferAhead$,ka=N.maxBufferAhead$,ja=N.maxBufferBehind$,X=new l.Subject,Y=new l.Subject,la=a.i(w.a)(V.manifest),Z=a.i(m.a)(function(c){c=la({url:c});var b=new l.Subject;return a.i(A.a)("manifest",c,b,b,O).map(function(c){c=c.parsed;return a.i(t.a)(c.url,c.manifest,ea,fa)})}),P={},S={};b=R.filter(function(a){var c= a.currentTime;a=a.duration;return 0<a&&a-c<J});N=a.i(e.b)(function(c){var b=c.url,e=c.mediaSource;c=e?a.i(p.e)(e):h.Observable.of(null);return h.Observable.combineLatest(Z(b),c).mergeMap(function(a){return G(e,a[0])})},{totalRetry:3,retryDelay:250,resetDelay:6E4,shouldRetry:function(a){return!0!==a.fatal},errorSelector:function(c){a.i(q.d)(c)||(c=new q.e("NONE",c,!0));c.fatal=!0;return c},onRetry:function(a,b){c.a.warn("stream retry",a,b);O.next(a)}});return a.i(z.b)(da,F,K,S,P).mergeMap(N).takeUntil(b)}; var h=a(0);a.n(h);var l=a(5);a.n(l);var g=a(174);a.n(g);b=a(8);var k=a.n(b);b=a(4);var f=a(19),c=a(1);a(2);var e=a(70),m=a(166),n=a(162),q=a(6),r=a(7),p=a(17),t=a(116),u=a(105),w=a(118),x=a(95),v=a(122),y=a(126),z=a(123),B=a(131),C=a(120),A=a(124),H=a(129),E=a(130),I=a(119),J=b.a.END_OF_PLAY,D=function(c){var b={};a.i(f.a)(["audio","video"],c)?b.cache=new n.a:"image"===c&&(b.maxRetry=0);return b}},function(b,d,a){d.a=function(b,d){if(d){var f=a.i(h.e)(b),c=f[0];f=f[1];if(null!=d.position)return Math.max(Math.min(d.position, f),c);if(null!=d.wallClockTime)return Math.max(Math.min(b.isLive?d.wallClockTime-b.availabilityStartTime:d.wallClockTime,f),c);if(null!=d.fromFirstPosition)return b=d.fromFirstPosition,0>=b?c:Math.min(c+b,f);if(null!=d.fromLastPosition)return b=d.fromLastPosition,0<=b?f:Math.max(c,f+b)}return b.isLive?(c=b.suggestedPresentationDelay,a.i(h.d)(b)-(null==c?l:c)):0};b=a(4);var h=a(28),l=b.a.DEFAULT_LIVE_GAP},function(b,d,a){a.d(d,"b",function(){return f});a.d(d,"a",function(){return k});var h=a(0);a.n(h); var l=a(1),g=a(7),k=function(a,b){b=Infinity===b?Number.MAX_VALUE:b;a.duration!==b&&(a.duration=b,l.a.info("set duration",a.duration))},f=function(c,b,f,d,k){return h.Observable.create(function(e){function h(){if(m&&"closed"!=m.readyState){var c=m,e=c.readyState;c=c.sourceBuffers;for(var f=0;f<c.length;f++){var h=c[f];try{"open"==e&&h.abort(),m.removeSourceBuffer(h)}catch(z){l.a.warn("error while disposing souceBuffer",z)}}}Object.keys(k).forEach(function(a){delete k[a]});Object.keys(d).forEach(function(a){var c= d[a];try{c.abort()}catch(C){l.a.warn("error while disposing souceBuffer",C)}delete d[a]});a.i(g.k)(b);if(n)try{URL.revokeObjectURL(n)}catch(z){l.a.warn("error while revoking ObjectURL",z)}n=m=null}var m=void 0,n=void 0;h();if(f){if(!g.l)throw new MediaError("MEDIA_SOURCE_NOT_SUPPORTED",null,!0);m=new g.l;n=URL.createObjectURL(m)}else m=null,n=c;b.src=n;e.next({url:c,mediaSource:m});l.a.info("create mediasource object",n);return h})}},function(b,d,a){d.a=function(a,b,d,f,c){var e=void 0,g=void 0;return b.filter(function(b){var k= b.type;b=b.value;if("data"===k)return!0;if("error"===k)b.pipelineType=a,c.next(b);else if("manifest"!==a)if("metrics"===k)d.next({type:a,value:b});else if("request"===k){if(k=b&&b.segment,null!=k){b=k.duration/k.timescale;var l=k.time/k.timescale;g=k.id;k={duration:isNaN(b)?void 0:b,time:isNaN(l)?void 0:l,requestTimestamp:Date.now(),id:g};e=new h.Subject;f.next(e);e.next({type:a,event:"requestBegin",value:k})}}else"progress"===k&&b.size!==b.totalSize&&(k={duration:b.duration,size:b.size,totalSize:b.totalSize, timestamp:Date.now(),id:g},e.next({type:a,event:"progress",value:k}))}).map(function(a){return a.value}).finally(function(){e&&(null!=g&&e.next({type:a,event:"requestEnd",value:{id:g}}),e.complete())}).share()};var h=a(5);a.n(h)},function(b,d,a){function h(a,b){if("function"!==typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});b&&(Object.setPrototypeOf? Object.setPrototypeOf(a,b):a.__proto__=b)}b=function(a){function b(){if(!(this instanceof b))throw new TypeError("Cannot call a class as a function");var d=a.apply(this,arguments);if(!this)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!d||"object"!==typeof d&&"function"!==typeof d?this:d}h(b,a);b.prototype._append=function(){this.buffered.insert(0,Number.MAX_VALUE)};return b}(a(60).a);d.a=b},function(b,d,a){a.d(d,"c",function(){return k});a.d(d,"d",function(){return f}); a.d(d,"b",function(){return c});a.d(d,"a",function(){return e});var h=a(1),l=a(127),g=a(125),k=function(a){return"audio"==a||"video"==a},f=function(a,c,b,e){e[c]||(h.a.info("add sourcebuffer",b),e[c]=a.addSourceBuffer(b));return e[c]},c=function(a,c,b,e,d,t){var m=6<arguments.length&&void 0!==arguments[6]?arguments[6]:{};if(k(b))m=f(c,b,e,d);else{var n=t[b];if(n)try{n.abort()}catch(x){h.a.warn(x)}finally{delete t[b]}if("text"==b)h.a.info("add text sourcebuffer",e),m=new l.a(a,e,m.hideNativeSubtitle); else if("image"==b)h.a.info("add image sourcebuffer",e),m=new g.a(e);else throw h.a.error("unknown buffer type "+b),new MediaError("BUFFER_TYPE_UNKNOWN",null,!0);t[b]=m}return m},e=function(a,c,b,e,f){var d=k(b);d?(a=e[b],delete e[b]):(a=f[b],delete f[b]);if(a)try{a.abort(),d&&c.removeSourceBuffer(a)}catch(u){h.a.warn(u)}}},function(b,d,a){function h(a,b){if("function"!==typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&& b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function l(a){for(var c=[],b=0;b<a.length;b++){var d=a[b],g=d.start,k=d.end;(d=d.text)&&c.push(new f(g,k,d))}return c}b=a(60);var g=a(7),k=a(1),f=window.VTTCue||window.TextTrackCue;b=function(c){function b(e,f,d){if(!(this instanceof b))throw new TypeError("Cannot call a class as a function");var k=c.call(this,f);if(!this)throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); k=!k||"object"!==typeof k&&"function"!==typeof k?this:k;var l=a.i(g.n)(e,d);d=l.track;l=l.trackElement;k._videoElement=e;k._isVtt=/^text\/vtt/.test(f);k._track=d;k._trackElement=l;return k}h(b,c);b.prototype._append=function(c){var b=this,e=c.timescale,f=c.start,d=c.end;c=c.data;if(!(0>=d-f))if(f/=e,e=null!=d?d/e:void 0,this._isVtt)a.i(g.o)()&&this._trackElement?(d=new Blob([c],{type:"text/vtt"}),d=URL.createObjectURL(d),this._trackElement.src=d,this.buffered.insert(f,null!=e?e:Number.MAX_VALUE)): k.a.warn("vtt subtitles not supported");else if(d=l(c),0<d.length){c=d[0];var h=this._track.cues;0<h.length&&c.startTime<h[h.length-1].startTime&&this._remove(c.startTime,Infinity);d.forEach(function(a){return b._track.addCue(a)});this.buffered.insert(f,null!=e?e:d[d.length-1].endTime)}};b.prototype._remove=function(a,c){for(var b=this._track,e=b.cues,f=e.length-1;0<=f;f--){var d=e[f],k=d.startTime,g=d.endTime;k>=a&&k<=c&&g<=c&&b.removeCue(d)}this.buffered.remove(a,c)};b.prototype._abort=function(){var a= this._trackElement,c=this._videoElement;a&&c&&c.hasChildNodes(a)&&c.removeChild(a);this._track.mode="disabled";this.size=0;this._videoElement=this._track=this._trackElement=null};return b}(b.a);d.a=b},function(b,d,a){a(2);var h=a(10);b=function(){function b(){if(!(this instanceof b))throw new TypeError("Cannot call a class as a function");this._ranges=[];this.length=0}b.prototype.insert=function(b,d){a.i(h.e)(this._ranges,{start:b,end:d});this.length=this._ranges.length};b.prototype.remove=function(b, d){var f=[];0<b&&f.push({start:0,end:b});Infinity>d&&f.push({start:d,end:Infinity});a.i(h.f)(this._ranges,f);this.length=this._ranges.length};b.prototype.start=function(a){if(a>=this._ranges.length)throw Error("INDEX_SIZE_ERROR");return this._ranges[a].start};b.prototype.end=function(a){if(a>=this._ranges.length)throw Error("INDEX_SIZE_ERROR");return this._ranges[a].end};return b}();d.a=b},function(b,d,a){var h=a(0);a.n(h);var l=a(1);d.a=function(a,b,f,c){c=c.pauseWhenStalled;var e=void 0;e=void 0=== c||c?f.pairwise().map(function(a){var c=a[1].stalled;a=a[0].stalled;if(!a!==!c||a&&c&&a.state!==c.state)return!a}).filter(function(a){return null!=a}).startWith(!1):h.Observable.of(!1).concat(h.Observable.never());return e.switchMap(function(c){return c?h.Observable.defer(function(){l.a.info("pause playback to build buffer");a.playbackRate=0;return h.Observable.of(0)}):b.do(function(c){l.a.info("resume playback speed",c);a.playbackRate=c})})}},function(b,d,a){b=a(4);var h=a(1),l=a(10),g=a(7),k=b.a.DISCONTINUITY_THRESHOLD; d.a=function(b,c,e){return e.do(function(c){if(c.stalled){var e=c.buffered,f=c.currentTime;e=a.i(l.d)(e,f);a.i(g.m)(c)?(h.a.warn("after freeze seek",f,c.range),b.currentTime=f):e<k&&(c=f+e+1/60,h.a.warn("discontinuity seek",f,e,c),b.currentTime=c)}}).share().map(function(a){return a.stalled}).distinctUntilChanged(function(a,c){return!a&&!c||a&&c&&a.state===c.state})}},function(b,d,a){function h(a){return a.filter(function(a){return"seeking"==a.state&&(Infinity===a.bufferGap||-2>a.bufferGap)}).skip(1).startWith(!0)} b=a(8);var l=a.n(b),g=a(28);d.a=function(b,f){f=f.map(function(c){var e=l()({},c);e.liveGap=b.isLive?a.i(g.d)(b)-c.currentTime:Infinity;return e});var c=h(f);return{timings:f,seekings:c}}},function(b,d,a){function h(b,f,c){this.name="EncryptedMediaError";this.type=l.a.ENCRYPTED_MEDIA_ERROR;this.reason=f;this.code=l.b[b];this.fatal=c;this.message=a.i(g.a)(this.name,this.code,this.reason)}var l=a(18),g=a(22);h.prototype=Error();d.a=h},function(b,d,a){function h(b,f,c){this.name="IndexError";this.type= l.a.INDEX_ERROR;this.indexType=f;this.reason=null;this.code=l.b[b];this.fatal=c;this.message=a.i(g.a)(this.name,this.code,null)}var l=a(18),g=a(22);h.prototype=Error();d.a=h},function(b,d,a){function h(b,f,c){this.name="MediaError";this.type=l.a.MEDIA_ERROR;this.reason=f;this.code=l.b[b];this.fatal=c;this.message=a.i(g.a)(this.name,this.code,this.reason)}var l=a(18),g=a(22);h.prototype=Error();d.a=h},function(b,d,a){function h(b,f,c){this.name="NetworkError";this.type=l.a.NETWORK_ERROR;this.xhr=f.xhr; this.url=f.url;this.status=f.status;this.reqType=f.type;this.reason=f;this.code=l.b[b];this.fatal=c;this.reason?this.message=a.i(g.a)(this.name,this.code,this.reason):(b=""+this.reqType+(0<this.status?"("+this.status+")":"")+" on "+this.url,this.message=a.i(g.a)(this.name,this.code,{message:b}))}var l=a(18),g=a(22);h.prototype=Error();h.prototype.isHttpError=function(a){return this.reqType==l.c.ERROR_HTTP_CODE&&this.status==a};d.a=h},function(b,d,a){function h(b,f,c){this.name="OtherError";this.type= l.a.OTHER_ERROR;this.reason=f;this.code=l.b[b];this.fatal=c;this.message=a.i(g.a)(this.name,this.code,this.reason)}var l=a(18),g=a(22);h.prototype=Error();d.a=h},function(b,d,a){function h(a,b,d){this.name="RequestError";this.url=b;this.xhr=a;this.status=a.status;this.message=this.type=d}h.prototype=Error();d.a=h},function(b,d,a){b.exports=a(87).default},function(b,d,a){b=a(8);var h=a.n(b);b=a(21);var l=a.n(b),g=a(146),k=a(40);b=function(){function b(){var c=this,e=0<arguments.length&&void 0!==arguments[0]? arguments[0]:{};if(!(this instanceof b))throw new TypeError("Cannot call a class as a function");var f=a.i(k.a)();this.id=null==e.id?f:""+e.id;this.type=e.type||"";this.representations=Array.isArray(e.representations)?e.representations.map(function(a){return new g.a(h()({rootId:c.id},a))}).sort(function(a,c){return a.bitrate-c.bitrate}):[];null!=e.language&&(this.language=e.language);null!=e.normalizedLanguage&&(this.normalizedLanguage=e.normalizedLanguage);null!=e.closedCaption&&(this.isClosedCaption= e.closedCaption);null!=e.audioDescription&&(this.isAudioDescription=e.audioDescription);null!=e.contentProtection&&(this.contentProtection=e.contentProtection);null!=e.smoothProtection&&(this._smoothProtection=e.smoothProtection);this.manual=e.manual}b.prototype.getAvailableBitrates=function(){return this.representations.map(function(a){return a.bitrate})};b.prototype.getRepresentation=function(a){return l()(this.representations,function(c){return a===c.id})};b.prototype.getRepresentationsForBitrate= function(a){return this.representations.filter(function(c){return c.bitrate===a})||null};return b}();d.a=b},function(b,d,a){b=a(21);var h=a.n(b),l=a(139),g=a(40);b=function(){function b(){var f=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};if(!(this instanceof b))throw new TypeError("Cannot call a class as a function");var c=a.i(g.a)();this.id=null==f.id?c:""+f.id;this.transport=f.transportType||"";this.adaptations=f.adaptations?Object.keys(f.adaptations).reduce(function(a,c){a[c]=f.adaptations[c].map(function(a){return new l.a(a)}); return a},{}):[];this.periods=[{adaptations:this.adaptations}];this.isLive="dynamic"===f.type;this.uris=f.locations||[];this._duration=f.duration;this.suggestedPresentationDelay=f.suggestedPresentationDelay;this.availabilityStartTime=f.availabilityStartTime;this.presentationLiveGap=f.presentationLiveGap;this.timeShiftBufferDepth=f.timeShiftBufferDepth}b.prototype.getDuration=function(){return this._duration};b.prototype.getUrl=function(){return this.uris[0]};b.prototype.getAdaptations=function(){var a= this.adaptations;if(!a)return[];var c=[],b;for(b in a)c.push.apply(c,a[b]);return c};b.prototype.getAdaptation=function(a){return h()(this.getAdaptations(),function(c){return a===c.id})};b.prototype.updateLiveGap=function(a){this.isLive&&(this.presentationLiveGap+=a)};return b}();d.a=b},function(b,d,a){Object.defineProperty(d,"__esModule",{value:!0});b=a(8);b=a.n(b);var h=a(37);a=a(23);d["default"]=b()({},h["default"],{getInitSegment:a.a,setTimescale:a.b,scale:a.c,_addSegmentInfos:function(a,b){if(b.timescale!== a.timescale){var d=a.timescale;a.timeline.push({ts:b.time/b.timescale*d,d:b.duration/b.timescale*d,r:b.count,range:b.range})}else a.timeline.push({ts:b.time,d:b.duration,r:b.count,range:b.range});return!0},shouldRefresh:function(){return!1}})},function(b,d,a){var h={};h.smooth=a(144).default;h.timeline=a(37).default;h.template=a(145).default;h.list=a(143).default;h.base=a(141).default;d.a=function(a){return h[a.indexType]}},function(b,d,a){Object.defineProperty(d,"__esModule",{value:!0});var h=a(27), l=a(23);d["default"]={getInitSegment:l.a,setTimescale:l.b,scale:l.c,getSegments:function(b,d,f,c){var e=a.i(l.d)(d,f,c);f=d.duration;c=d.list;d=d.timescale;var g=Math.min(c.length-1,Math.floor(e.to/f)),k=[];for(e=Math.floor(e.up/f);e<=g;)k.push(new h.a({id:""+b+"_"+e,time:e*f,init:!1,range:c[e].range,duration:f,indexRange:null,timescale:d,media:c[e].media})),e++;return k},getFirstPosition:function(){return 0},getLastPosition:function(a){return a.list.length*a.duration/a.timescale},shouldRefresh:function(a, b,f,c){b=a.list;f=a.presentationTimeOffset;a=Math.floor((c*a.timescale-(void 0===f?0:f))/a.duration);return!(0<=a&&a<b.length)},_addSegmentInfos:function(){return!1},checkDiscontinuity:function(){return-1}}},function(b,d,a){Object.defineProperty(d,"__esModule",{value:!0});b=a(37);var h=a(23);d["default"]={getSegments:b["default"].getSegments,getInitSegment:h.a,checkDiscontinuity:b["default"].checkDiscontinuity,_addSegmentInfos:b["default"]._addSegmentInfos,setTimescale:h.b,scale:h.c,shouldRefresh:function(b, d,k,f){var c=b.timeline;k=b.timescale;b=b.presentationTimeOffset;b=void 0===b?0:b;d=d*k-b;c=c[c.length-1];if(!c)return!1;0>c.d&&(c={ts:c.ts,d:0,r:c.r});c=a.i(h.e)(c);return 1>=(c-d)/k&&f*k-b>c},getFirstPosition:function(a){if(a.timeline.length)return a.timeline[0].ts/a.timescale},getLastPosition:function(b){if(b.timeline.length){var d=b.timeline[b.timeline.length-1];return a.i(h.e)(d)/b.timescale}}}},function(b,d,a){Object.defineProperty(d,"__esModule",{value:!0});var h=a(27),l=a(23);d["default"]= {getInitSegment:l.a,setTimescale:l.b,scale:l.c,getSegments:function(b,d,f,c){var e=a.i(l.d)(d,f,c);f=e.to;c=d.duration;var k=d.startNumber,g=d.timescale;d=d.media;var q=[];for(e=e.up;e<=f;e+=c){var r=Math.floor(e/c)+(null==k?1:k);q.push(new h.a({id:""+b+"_"+r,number:r,time:r*c,init:!1,duration:c,range:null,indexRange:null,timescale:g,media:d}))}return q},getFirstPosition:function(){},getLastPosition:function(){},shouldRefresh:function(){return!1},checkDiscontinuity:function(){return-1},_addSegmentInfos:function(){return!1}}}, function(b,d,a){var h=a(40),l=a(147);d.a=function k(){var b=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};if(!(this instanceof k))throw new TypeError("Cannot call a class as a function");var c=a.i(h.a)();this.id=null==b.id?c:b.id;this.bitrate=b.bitrate;this.codec=b.codecs;null!=b.height&&(this.height=b.height);null!=b.width&&(this.width=b.width);null!=b.mimeType&&(this.mimeType=b.mimeType);this.index=new l.a({index:b.index,rootId:this.id});this.baseURL=b.baseURL;null!=b.codecPrivateData&& (this._codecPrivateData=b.codecPrivateData);null!=b.channels&&(this._channels=b.channels);null!=b.bitsPerSample&&(this._bitsPerSample=b.bitsPerSample);null!=b.packetSize&&(this._packetSize=b.packetSize);null!=b.samplingRate&&(this._samplingRate=b.samplingRate)}},function(b,d,a){var h=a(142);b=function(){function b(d){if(!(this instanceof b))throw new TypeError("Cannot call a class as a function");this._index=d.index;this._rootId=d.rootId;this._indexHelpers=a.i(h.a)(this._index)}b.prototype.getInitSegment= function(){return this._indexHelpers.getInitSegment(this._rootId,this._index)};b.prototype.getSegments=function(a,b){return this._indexHelpers.getSegments(this._rootId,this._index,a,b)};b.prototype.shouldRefresh=function(a,b,f){return this._indexHelpers.shouldRefresh(this._index,a,b,f)};b.prototype.getFirstPosition=function(){return this._indexHelpers.getFirstPosition(this._index)};b.prototype.getLastPosition=function(){return this._indexHelpers.getLastPosition(this._index)};b.prototype.checkDiscontinuity= function(a){return this._indexHelpers.checkDiscontinuity(this._index,a)};b.prototype.scale=function(a){return this._indexHelpers.scale(this._index,a)};b.prototype.setTimescale=function(a){return this._indexHelpers.setTimescale(this._index,a)};b.prototype._addSegments=function(a,b){for(var f=[],c=0;c<a.length;c++)this._indexHelpers._addSegmentInfos(this._index,a[c],b)&&f.push(a[c]);return f};b.prototype.update=function(a){this._index=a._index};b.prototype.getType=function(){return this._index.indexType|| ""};return b}();d.a=b},function(b,d,a){b={};b.smooth=a(157).default;b.dash=a(149).default;b.directfile=a(156).default;d.a=b},function(b,d,a){Object.defineProperty(d,"__esModule",{value:!0});var h=a(0);a.n(h);var l=a(1),g=a(24),k=a(13),f=a(38),c=a(62),e=a(63),m=a(61),n=a(153),q=a(150),r=a(65),p=a(66),t=a(155);d["default"]=function(){var b=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},d=a.i(t.a)(b.segmentLoader),x=b.contentProtectionParser;x||(x=function(){});b={loader:function(a){return d({segment:a.segment, representation:a.representation,adaptation:a.adaptation,manifest:a.manifest})},parser:function(c){var b=c.segment,e=c.adaptation,d=c.init;c=new Uint8Array(c.response.responseData);var k=void 0,g=c,l=b.indexRange;(l=a.i(f.a)(c,l?l[0]:0))&&(k=l);b.isInit?(b={time:-1,duration:0},d=a.i(f.b)(c),0<d&&(b.timescale=d),e.contentProtection&&(g=a.i(f.c)(c,e.contentProtection))):b=a.i(q.a)(b,c,l,d);return h.Observable.of({segmentData:g,segmentInfos:b,nextSegments:k})}};return{directFile:!1,manifest:{loader:function(c){c= c.url;return a.i(r.a)({url:c,responseType:"document"})},parser:function(c){c=c.response;var b=c.responseData;return h.Observable.of({manifest:a.i(n.a)(b,x),url:c.url})}},audio:b,video:b,text:{loader:function(c){var b=c.segment,e=c.representation,f=b.media,d=b.range;c=b.indexRange;var k=b.isInit,l=a.i(p.a)(e)?"arraybuffer":"text";if(k&&!(f||d||c))return h.Observable.empty();b=f?a.i(p.b)(f,b,e):"";b=a.i(g.b)(e.baseURL,b);if(d&&c&&d[1]===c[0]-1)return a.i(r.a)({url:b,responseType:l,headers:{Range:a.i(p.c)([d[0], c[1]])}});d=a.i(r.a)({url:b,responseType:l,headers:d?{Range:a.i(p.c)(d)}:null});return c?(c=a.i(r.a)({url:b,responseType:l,headers:{Range:a.i(p.c)(c)}}),h.Observable.merge(d,c)):d},parser:function(b){var d=b.response,g=b.segment,m=b.representation,n=b.init,r=b.adaptation.language,v=g.isInit,w=g.indexRange,t=b=void 0,u=void 0,x=a.i(p.a)(m);if(x){var G=new Uint8Array(d.responseData);d=a.i(k.a)(a.i(f.d)(G));(w=a.i(f.a)(G,w?w[0]:0))&&(b=w);v||(t=a.i(q.a)(g,G,w,n))}else G=d=d.responseData,t={time:g.time, duration:g.duration,timescale:g.timescale};if(v)t={time:-1,duration:0},x&&(g=a.i(f.b)(G),0<g&&(t.timescale=g)),u={start:0,end:0,timescale:t.timescale||0,data:[]};else if(x)switch(g=m.codec,(void 0===g?"":g).toLowerCase()){case "stpp":u={start:t.time,end:t.time+t.duration,timescale:t.timescale,data:a.i(e.a)(d,r,0)};break;default:l.a.warn("The codec used for the subtitle is not managed yet.")}else switch(m.mimeType){case "application/ttml+xml":u={start:t.time,end:t.time+t.duration,timescale:t.timescale, data:a.i(e.a)(d,r,0)};break;case "application/x-sami":case "application/smil":u={start:t.time,end:t.time+t.duration,timescale:t.timescale,data:a.i(c.a)(d,r,0)};break;case "text/vtt":u={start:t.time,end:t.time+t.duration,timescale:t.timescale,data:d};break;default:l.a.warn("The codec used for the subtitle is not managed yet.")}return h.Observable.of({segmentData:u,segmentInfos:t,nextSegments:b})}},image:{loader:function(c){var b=c.segment;c=c.representation;if(b.isInit)return h.Observable.empty(); var e=b.media;b=e?a.i(p.b)(e,b,c):"";b=a.i(g.b)(c.baseURL,b);return a.i(r.a)({url:b,responseType:"arraybuffer"})},parser:function(c){var b=new Uint8Array(c.response.responseData);c={time:0,duration:Number.MAX_VALUE};var e=void 0;b&&(b=a.i(m.a)(b),e=b.thumbs,c.timescale=b.timescale);return h.Observable.of({segmentData:e,segmentInfos:c})}}}}},function(b,d,a){a(2);var h=a(38);d.a=function(b,d,k,f){k||(k=[]);var c=void 0,e=void 0,g=a.i(h.e)(d),l=a.i(h.f)(d);f=f&&0<f.timescale?f.timescale:b.timescale; if(f===b.timescale){d=Math.min(.9*f,b.duration/4);var q=b.time;b=b.duration}else d=Math.min(.9*f,b.duration/b.timescale*f/4),q=b.time/b.timescale*f,b=b.duration/b.timescale*f;0<=g&&(null==q||Math.abs(g-q)<=d)&&(c=g);0<=l&&(null==b||Math.abs(l-b)<=d)&&(e=l);null==c&&(1===k.length?(c=k[0].time,0<=c&&(null==q||Math.abs(q-c)<=d)?(g=k[0].timescale,c=null!=g&&g!==f?c/g*f:c):c=q):c=q);null==e&&(1===k.length?(e=k[0].duration,0<=e&&(null==b||Math.abs(b-e)<=d)?(k=k[0].timescale,e=null!=k&&k!==f?e/k*f:e):e= b):e=b);return{timescale:f,time:c||0,duration:e||0}}},function(b,d,a){b=a(4);var h=a(2),l=a(30),g=a(64),k=[{k:"profiles",fn:g.g},{k:"width",fn:parseInt},{k:"height",fn:parseInt},{k:"frameRate",fn:g.h},{k:"audioSamplingRate",fn:g.g},{k:"mimeType",fn:g.g},{k:"segmentProfiles",fn:g.g},{k:"codecs",fn:g.g},{k:"maximumSAPPeriod",fn:parseFloat},{k:"maxPlayoutRate",fn:parseFloat},{k:"codingDependency",fn:g.i}],f=[{k:"timescale",fn:parseInt,def:1},{k:"timeShiftBufferDepth",fn:g.j},{k:"presentationTimeOffset", fn:parseFloat,def:0},{k:"indexRange",fn:g.f},{k:"indexRangeExact",fn:g.i,def:!1},{k:"availabilityTimeOffset",fn:parseFloat},{k:"availabilityTimeComplete",fn:g.i,def:!0}],c=f.concat([{k:"duration",fn:parseInt},{k:"startNumber",fn:parseInt}]),e={ContentProtection:[{k:"schemeIdUri",fn:g.g},{k:"value",fn:g.g}],SegmentURL:[{k:"media",fn:g.g},{k:"mediaRange",fn:g.f},{k:"index",fn:g.g},{k:"indexRange",fn:g.f}],S:[{k:"t",fn:parseInt,n:"ts"},{k:"d",fn:parseInt},{k:"r",fn:parseInt}],SegmentTimeline:[],SegmentBase:f, SegmentTemplate:c.concat([{k:"initialization",fn:function(a){return{media:a,range:void 0}}},{k:"index",fn:g.g},{k:"media",fn:g.g},{k:"bitstreamSwitching",fn:g.g}]),SegmentList:c,ContentComponent:[{k:"id",fn:g.g},{k:"lang",fn:g.g,n:"language"},{k:"lang",fn:l.a,n:"normalizedLanguage"},{k:"contentType",fn:g.g},{k:"par",fn:g.k}],Representation:k.concat([{k:"id",fn:g.g},{k:"bandwidth",fn:parseInt,n:"bitrate"},{k:"qualityRanking",fn:parseInt}]),AdaptationSet:k.concat([{k:"id",fn:g.g},{k:"group",fn:parseInt}, {k:"lang",fn:g.g,n:"language"},{k:"lang",fn:l.a,n:"normalizedLanguage"},{k:"contentType",fn:g.g},{k:"par",fn:g.k},{k:"minBandwidth",fn:parseInt,n:"minBitrate"},{k:"maxBandwidth",fn:parseInt,n:"maxBitrate"},{k:"minWidth",fn:parseInt},{k:"maxWidth",fn:parseInt},{k:"minHeight",fn:parseInt},{k:"maxHeight",fn:parseInt},{k:"minFrameRate",fn:g.h},{k:"maxFrameRate",fn:g.h},{k:"segmentAlignment",fn:g.l},{k:"subsegmentAlignment",fn:g.l},{k:"bitstreamSwitching",fn:g.i}]),Period:[{k:"id",fn:g.g},{k:"start",fn:g.j}, {k:"duration",fn:g.j},{k:"bitstreamSwitching",fn:g.i}],MPD:[{k:"id",fn:g.g},{k:"profiles",fn:g.g},{k:"type",fn:g.g,def:"static"},{k:"availabilityStartTime",fn:g.m},{k:"availabilityEndTime",fn:g.m},{k:"publishTime",fn:g.m},{k:"mediaPresentationDuration",fn:g.j,n:"duration"},{k:"minimumUpdatePeriod",fn:g.j},{k:"minBufferTime",fn:g.j},{k:"timeShiftBufferDepth",fn:g.j},{k:"suggestedPresentationDelay",fn:g.j,def:b.a.DEFAULT_SUGGESTED_PRESENTATION_DELAY.DASH},{k:"maxSegmentDuration",fn:g.j},{k:"maxSubsegmentDuration", fn:g.j}],Role:[{k:"schemeIdUri",fn:g.g},{k:"value",fn:g.g}],Accessibility:[{k:"schemeIdUri",fn:g.g},{k:"value",fn:parseInt}]};d.a=function(c,b){var f=e[c.nodeName];a.i(h.a)(f,"no attributes for "+c.nodeName);b=b||{};for(var d=0;d<f.length;d++){var k=f[d],g=k.k,l=k.fn,m=k.n;k=k.def;c.hasAttribute(g)?b[m||g]=l(c.getAttribute(g)):null!=k&&(b[m||g]=k)}return b}},function(b,d,a){a.d(d,"a",function(){return h});a.d(d,"b",function(){return l});a.d(d,"c",function(){return g});a.d(d,"d",function(){return k}); b=function(a){return function(b){return a.reduce(function(a,c){b.hasOwnProperty(c)&&(a[c]=b[c]);return a},{})}};var h=b("availabilityStartTime baseURL duration id locations periods presentationLiveGap suggestedPresentationDelay timeShiftBufferDepth transportType type".split(" ")),l=b(["adaptations","baseURL","duration","id","start"]),g=b("contentProtection accessibility baseURL contentProtection id language normalizedLanguage representations type".split(" ")),k=b("bitrate baseURL codecs height id index mimeType width".split(" "))}, function(b,d,a){function h(a,b){return"string"==typeof a?h.parseFromString(a,b):h.parseFromDocument(a,b)}var l=a(2),g=a(154);h.parseFromString=function(a,b){return h.parseFromDocument((new DOMParser).parseFromString(a,"application/xml"),b)};h.parseFromDocument=function(b,f){b=b.documentElement;l.a.equal(b.nodeName,"MPD","document root should be MPD");return a.i(g.a)(b,f)};d.a=h},function(b,d,a){function h(b,c){var e=a.i(r.a)(b,function(a,b,e){switch(b){case "BaseURL":a.baseURL=e.textContent;break; case "Location":a.locations.push(e.textContent);break;case "Period":a.periods.push(l(e,c))}return a},{transportType:"dash",periods:[],locations:[]});b=a.i(t.a)(b,e);/dynamic/.test(b.type)&&(e=b.periods[0].adaptations.filter(function(a){return"video"==a.type})[0],e=a.i(r.b)(e),e||(q.a.warn("Live edge not deduced from manifest, setting a default one"),e=Date.now()/1E3-60),b.availabilityStartTime=b.availabilityStartTime.getTime()/1E3,b.presentationLiveGap=Date.now()/1E3-(e+b.availabilityStartTime)); return a.i(p.a)(b)}function l(b,c){b=a.i(t.a)(b,a.i(r.a)(b,function(a,b,e){switch(b){case "BaseURL":a.baseURL=e.textContent;break;case "AdaptationSet":b=g(e,c),null==b.id&&(b.id=a.adaptations.length),a.adaptations.push(b)}return a},{adaptations:[]}));return a.i(p.b)(b)}function g(b,d){var g=void 0,h=a.i(r.a)(b,function(b,h,l){switch(h){case "Accessibility":g=a.i(t.a)(l);break;case "BaseURL":b.baseURL=l.textContent;break;case "ContentComponent":h=a.i(t.a)(l);b.contentComponent=h;break;case "ContentProtection":h= d(a.i(t.a)(l),l);b.contentProtection=h;break;case "Representation":h=k(l);null==h.id&&(h.id=b.representations.length);b.representations.push(h);break;case "Role":h=a.i(t.a)(l);b.role=h;break;case "SegmentBase":b.index=e(l);break;case "SegmentList":b.index=c(l);break;case "SegmentTemplate":b.index=f(l)}return b},{representations:[]}),l=a.i(t.a)(b,h);l.type=a.i(r.c)(l);l.accessibility=[];a.i(r.d)(g)&&l.accessibility.push("hardOfHearing");a.i(r.e)(g)&&l.accessibility.push("visuallyImpaired");l.representations= l.representations.map(function(a){u.forEach(function(b){!a.hasOwnProperty(b)&&l.hasOwnProperty(b)&&(a[b]=l[b])});return a});return a.i(p.c)(l)}function k(b){var d=a.i(r.a)(b,function(a,b,d){switch(b){case "BaseURL":a.baseURL=d.textContent;break;case "SegmentBase":a.index=e(d);break;case "SegmentList":a.index=c(d);break;case "SegmentTemplate":a.index=f(d)}return a},{});b=a.i(t.a)(b,d);return a.i(p.d)(b)}function f(a){a=m(a);a.indexType||(a.indexType="template");return a}function c(b){var c=m(b);c.list= [];c.indexType="list";return a.i(r.a)(b,function(b,c,e){"SegmentURL"==c&&b.list.push(a.i(t.a)(e));return b},c)}function e(b){var c=a.i(r.a)(b,function(b,c,e){if("Initialization"==c){var f=c=void 0;e.hasAttribute("range")&&(c=a.i(r.f)(e.getAttribute("range")));e.hasAttribute("sourceURL")&&(f=e.getAttribute("sourceURL"));b.initialization={range:c,media:f}}return b},a.i(t.a)(b));"SegmentBase"==b.nodeName&&(c.indexType="base",c.timeline=[]);return c}function m(b){return a.i(r.a)(b,function(a,b,c){"SegmentTimeline"== b&&(a.indexType="timeline",a.timeline=n(c));return a},e(b))}function n(b){return a.i(r.a)(b,function(b,c,e){c=b.length;e=a.i(t.a)(e);null==e.ts&&(c=0<c&&b[c-1],e.ts=c?c.ts+c.d*(c.r+1):0);null==e.r&&(e.r=0);b.push(e);return b},[])}a.d(d,"a",function(){return h});var q=a(1);a(2);var r=a(64),p=a(152),t=a(151),u=["codecs","height","index","mimeType","width"]},function(b,d,a){function h(b){var c=b.url;b=b.segment;var d=b.range;b=b.indexRange;if(d&&b&&d[1]===b[0]-1)return a.i(k.a)({url:c,responseType:"arraybuffer", headers:{Range:a.i(f.c)([d[0],b[1]])}});d=d?{Range:a.i(f.c)(d)}:null;d=a.i(k.a)({url:c,responseType:"arraybuffer",headers:d});return b?(c=a.i(k.a)({url:c,responseType:"arraybuffer",headers:{Range:a.i(f.c)(b)}}),l.Observable.merge(d,c)):d}var l=a(0);a.n(l);var g=a(24),k=a(65),f=a(66);d.a=function(b){return function(c){var e=c.segment,d=c.adaptation,k=c.representation;c=c.manifest;var r=e.media,p=e.range,t=e.indexRange;if(e.isInit&&!(r||p||t))return l.Observable.empty();r=r?a.i(f.b)(r,e,k):"";r=a.i(g.b)(k.baseURL, r);var u={adaptation:d,representation:k,manifest:c,segment:e,transport:"dash",url:r};return b?l.Observable.create(function(a){var c=!1,e=!1,f=b(u,{reject:function(){var b=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};e||(c=!0,a.error(b))},resolve:function(){var b=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};e||(c=!0,a.next({responseData:b.data,size:b.size||0,duration:b.duration||0}),a.complete())},fallback:function(){e=!0;h(u).subscribe(a)}});return function(){c||e||"function"!== typeof f||f()}}):h(u)}}},function(b,d,a){Object.defineProperty(d,"__esModule",{value:!0});var h=a(0);a.n(h);d["default"]={directFile:!0,manifest:{parser:function(a){a=a.url;return h.Observable.of({manifest:{transportType:"directfile",locations:[a],periods:[],isLive:!1,duration:Infinity,adaptations:null},url:a})}}}},function(b,d,a){Object.defineProperty(d,"__esModule",{value:!0});var h=a(0);a.n(h);var l=a(13),g=a(24),k=a(41),f=a(159),c=a(61);b=a(62);var e=a(63),m=a(39),n=a(67),q=a(68),r=a(158),p=a(160), t=m.a.patchSegment,u=m.a.getMdat,w={"application/x-sami":b.a,"application/smil":b.a,"application/ttml+xml":e.a,"application/ttml+xml+mp4":e.a,"text/vtt":function(a){return a}},x=/\.wsx?(\?token=\S+)?/;d["default"]=function(){var b=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},e=a.i(f.a)(b),d=a.i(p.a)(b.segmentLoader);b={loader:function(a){return d({segment:a.segment,representation:a.representation,adaptation:a.adaptation,manifest:a.manifest})},parser:function(b){var c=b.segment,e=b.manifest; b=b.response.responseData;if(c.isInit)return h.Observable.of({segmentData:b,segmentInfos:{timescale:c.timescale,time:-1,duration:0}});b=new Uint8Array(b);e=a.i(r.a)(b,c,e.isLive);c=e.nextSegments;e=e.segmentInfos;b=t(b,e.time);return h.Observable.of({segmentData:b,segmentInfos:e,nextSegments:c})}};return{directFile:!1,manifest:{resolver:function(b){b=b.url;var c=void 0,e=a.i(q.a)(b);c=x.test(b)?a.i(k.a)({url:a.i(q.b)(b,""),responseType:"document",ignoreProgressEvents:!0}).map(function(a){return a.value}).map(q.c): h.Observable.of(b);return c.map(function(b){return{url:a.i(q.b)(a.i(q.d)(b),e)}})},loader:function(b){b=b.url;return a.i(n.a)({url:b,responseType:"document"})},parser:function(a){a=a.response;var b=e(a.responseData);return h.Observable.of({manifest:b,url:a.url})}},audio:b,video:b,text:{loader:function(b){var c=b.segment,e=b.representation;if(c.isInit)return h.Observable.empty();b=e.mimeType;var f=a.i(g.b)(e.baseURL);c=a.i(q.e)(f,e,c);return 0<=b.indexOf("mp4")?a.i(n.a)({url:c,responseType:"arraybuffer"}): a.i(n.a)({url:c,responseType:"text"})},parser:function(b){var c=b.response,e=b.segment,f=b.manifest,d=b.adaptation.language,k=b.representation.mimeType;b=w[k];if(!b)throw Error("could not find a text-track parser for the type "+k);var g=c.responseData,m=c=void 0,n={};0<=k.indexOf("mp4")?(g=new Uint8Array(g),k=a.i(l.a)(u(g)),f=a.i(r.a)(g,e,f.isLive),c=f.nextSegments,m=f.segmentInfos,n.start=m.start,n.end=null!=m.duration?m.start+m.duration:void 0,n.timescale=m.timescale):(k=g,n.start=e.time,n.end= null!=e.duration?e.time+e.duration:void 0,n.timescale=e.timescale);n.data=b(k,d,e.time/e.timescale);return h.Observable.of({segmentData:n,segmentInfos:m,nextSegments:c})}},image:{loader:function(b){var c=b.segment;b=b.representation;if(c.isInit)return h.Observable.empty();var e=a.i(g.b)(b.baseURL);c=a.i(q.e)(e,b,c);return a.i(n.a)({url:c,responseType:"arraybuffer"})},parser:function(b){var e=new Uint8Array(b.response.responseData);b={time:0,duration:Number.MAX_VALUE};var f=void 0;e&&(e=a.i(c.a)(e), f=e.thumbs,b.timescale=e.timescale);return h.Observable.of({segmentData:f,segmentInfos:b})}}}}},function(b,d,a){var h=a(1),l=a(38);b=a(39);var g=b.a.getTraf,k=b.a.parseTfrf,f=b.a.parseTfxd;d.a=function(b,e,d){var c=void 0,m=void 0;d?(d=g(b))?(c=k(d),m=f(d)):h.a.warn("smooth: could not find traf atom"):c=null;m||(m=Math.min(.9*e.timescale,e.duration/4),b=a.i(l.f)(b),m=0<=b&&Math.abs(b-e.duration)<=m?{time:e.time,duration:b}:{time:e.time,duration:e.duration});if(c)for(b=c.length-1;0<=b;b--)c[b].timescale= e.timescale;m&&(m.timescale=e.timescale);return{nextSegments:c,segmentInfos:m}}},function(b,d,a){function h(a){return"boolean"==typeof a?a:"string"==typeof a?"TRUE"===a.toUpperCase():!1}function l(a){if(!a)return Infinity;a=a.index;var b=a.timeline[a.timeline.length-1];return(b.ts+(b.r+1)*b.d)/a.timescale}function g(b){return[{systemId:"edef8ba9-79d6-4ace-a3c8-27dcd51d21ed",privateData:a.i(c.i)([8,1,18,16],b)}]}var k=a(19),f=a(4),c=a(13),e=a(2),m=a(30),n={audio:"audio/mp4",video:"video/mp4",text:"application/ttml+xml"}, q={audio:"mp4a.40.2",video:"avc1.4D401E"};b={AACL:"audio/mp4",AVC1:"video/mp4",H264:"video/mp4",TTML:"application/ttml+xml+mp4"};var r={audio:[["Bitrate","bitrate",parseInt],["AudioTag","audiotag",parseInt],["FourCC","mimeType",b],["Channels","channels",parseInt],["SamplingRate","samplingRate",parseInt],["BitsPerSample","bitsPerSample",parseInt],["PacketSize","packetSize",parseInt],["CodecPrivateData","codecPrivateData",String]],video:[["Bitrate","bitrate",parseInt],["FourCC","mimeType",b],["CodecPrivateData", "codecs",function(a){return(a=(/00000001\d7([0-9a-fA-F]{6})/.exec(a)||[])[1])?"avc1."+a:""}],["MaxWidth","width",parseInt],["MaxHeight","height",parseInt],["CodecPrivateData","codecPrivateData",String]],text:[["Bitrate","bitrate",parseInt],["FourCC","mimeType",b]]};d.a=function(){function b(a,b,c){for(a=a.firstElementChild;a;)c=b(c,a.nodeName,a),a=a.nextElementSibling;return c}function d(c,f){c.hasAttribute("Timescale")&&(f=+c.getAttribute("Timescale"));var d=c.getAttribute("Type"),k=c.getAttribute("Subtype"), g=c.getAttribute("Name"),h=c.getAttribute("Language"),l=a.i(m.a)(h),p=c.getAttribute("Url"),t=r[d],u=[];a.i(e.a)(t,"unrecognized QualityLevel type "+d);var w=0;f=b(c,function(a,b,c){switch(b){case "QualityLevel":b={};for(var e=0;e<t.length;e++){var f=t[e],k=f[0],g=f[2];b[f[1]]="function"==typeof g?g(c.getAttribute(k)):g[c.getAttribute(k)]}"audio"==d&&(c=c.getAttribute("FourCC")||"",e=b.codecPrivateData,c="AACH"==c?5:e?(parseInt(e.substr(0,2),16)&248)>>3:2,b.codecs=c?"mp4a.40."+c:"");if("video"!=d|| b.bitrate>B)b.id=w++,a.representations.push(b);break;case "c":b=a.index;e=a.index.timeline;f=e.length;k=0<f?e[f-1]:{d:0,ts:0,r:0};g=+c.getAttribute("d");var h=c.getAttribute("t");(c=+c.getAttribute("r"))&&c--;0<f&&!k.d&&(k.d=h-k.ts,e[f-1]=k);0<f&&g==k.d&&null==h?k.r+=(c||0)+1:e.push({d:g,ts:null==h?k.ts+k.d*(k.r+1):+h,r:c});b.timeline=e}return a},{representations:[],index:{timeline:[],indexType:"smooth",timescale:f,initialization:{}}});c=f.representations;f=f.index;a.i(e.a)(c.length,"adaptation should have at least one representation"); c.forEach(function(a){return a.codecs=a.codecs||q[d]});c.forEach(function(a){return a.mimeType=a.mimeType||n[d]});if("ADVT"==k)return null;"text"===d&&"DESC"===k&&u.push("hardOfHearing");return{type:d,accessibility:u,index:f,representations:c,name:g,language:h,normalizedLanguage:l,baseURL:p}}function u(a){return w((new DOMParser).parseFromString(a,"application/xml"))}function w(f){f=f.documentElement;e.a.equal(f.nodeName,"SmoothStreamingMedia","document root should be SmoothStreamingMedia");a.i(e.a)(/^[2]-[0-2]$/.test(f.getAttribute("MajorVersion")+ "-"+f.getAttribute("MinorVersion")),"Version should be 2.0, 2.1 or 2.2");var g=+f.getAttribute("Timescale")||1E7,m=[],n=b(f,function(b,f,h){switch(f){case "Protection":h=h.firstElementChild;e.a.equal(h.nodeName,"ProtectionHeader","Protection should have ProtectionHeader child");f=a.i(c.b)(atob(h.textContent));var l=a.i(c.d)(f,8);l=a.i(c.l)(f.subarray(10,10+l));l=(new DOMParser).parseFromString(l,"application/xml").querySelector("KID").textContent;l=a.i(c.m)(atob(l)).toLowerCase();var n=a.i(c.k)(l); h=h.getAttribute("SystemID").toLowerCase().replace(/\{|\}/g,"");f={keyId:l,keySystems:[{systemId:h,privateData:f}].concat(C(n))};b.protection=f;break;case "StreamIndex":if(f=d(h,g)){h=0;do l=f.type+"_"+(f.language?f.language+"_":"")+h++;while(a.i(k.a)(m,l));f.id=l;m.push(l);b.adaptations.push(f)}}return b},{protection:null,adaptations:[]}),q=n.protection;n=n.adaptations;n.forEach(function(a){return a.smoothProtection=q});var r=void 0,p=void 0,t=void 0,u=void 0,w=h(f.getAttribute("IsLive"));if(w){r= y;t=+f.getAttribute("DVRWindowLength")/g;u=z;p=n.filter(function(a){return"video"==a.type})[0];var v=n.filter(function(a){return"audio"==a.type})[0];p=Math.min(l(p),l(v));p=Date.now()/1E3-(p+u)}return{transportType:"smooth",profiles:"",type:w?"dynamic":"static",suggestedPresentationDelay:r,timeShiftBufferDepth:t,presentationLiveGap:p,availabilityStartTime:u,periods:[{duration:(+f.getAttribute("Duration")||Infinity)/g,adaptations:n,laFragCount:+f.getAttribute("LookAheadFragmentCount")}]}}function x(a){return"string"== typeof a?u(a):w(a)}var v=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},y=null==v.suggestedPresentationDelay?f.a.DEFAULT_SUGGESTED_PRESENTATION_DELAY.SMOOTH:v.suggestedPresentationDelay,z=v.referenceDateTime||Date.UTC(1970,0,1,0,0,0,0)/1E3,B=v.minRepresentationBitrate||19E4,C=v.keySystems||g;x.parseFromString=u;x.parseFromDocument=w;return x}},function(b,d,a){function h(b){var c=b.url,e=void 0;(b=b.segment.range)&&(e={Range:a.i(f.f)(b)});return a.i(k.a)({url:c,responseType:"arraybuffer", headers:e})}var l=a(0);a.n(l);var g=a(24);b=a(39);var k=a(67),f=a(68),c=b.a.createVideoInitSegment,e=b.a.createAudioInitSegment;d.a=function n(b){return function(d){var k=d.segment,q=d.representation,r=d.adaptation;d=d.manifest;if(k.isInit){d={};var w=r._smoothProtection||{};switch(r.type){case "video":d=c(k.timescale,q.width,q.height,72,72,4,q._codecPrivateData,w.keyId,w.keySystems);break;case "audio":d=e(k.timescale,q._channels,q._bitsPerSample,q._packetSize,q._samplingRate,q._codecPrivateData, w.keyId,w.keySystems)}return l.Observable.of({type:"data",value:{responseData:d}})}w=a.i(f.e)(a.i(g.b)(q.baseURL),q,k);var x={adaptation:r,representation:q,segment:k,transport:"smooth",url:w,manifest:d};return b?l.Observable.create(function(a){var c=!1,e=!1,f=b(x,{reject:function(){var b=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};e||(c=!0,a.error(b))},resolve:function(){var b=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};e||(c=!0,a.next({type:"response",value:{responseData:b.data, size:b.size||0,duration:b.duration||0}}),a.complete())},fallback:function(){e=!0;n(x).subscribe(a)}});return function(){c||e||"function"!==typeof f||f()}}):h(x)}}},function(b,d,a){a.d(d,"a",function(){return h});var h=function(){function a(){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this.hash={}}a.prototype.add=function(a){this.hash[a]=!0};a.prototype.remove=function(a){delete this.hash[a]};a.prototype.test=function(a){return!0===this.hash[a]};return a}()},function(b, d,a){b=function(){function a(){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this.cache={}}a.prototype.add=function(a,b){a=a.segment;a.isInit&&(this.cache[a.id]=b)};a.prototype.get=function(a){a=a.segment;return a.isInit&&(a=this.cache[a.id],null!=a)?a:null};return a}();d.a=b},function(b,d,a){d.a={aa:"aar",ab:"abk",ae:"ave",af:"afr",ak:"aka",am:"amh",an:"arg",ar:"ara",as:"asm",av:"ava",ay:"aym",az:"aze",ba:"bak",be:"bel",bg:"bul",bi:"bis",bm:"bam",bn:"ben",bo:"bod", br:"bre",bs:"bos",ca:"cat",ce:"che",ch:"cha",co:"cos",cr:"cre",cs:"ces",cu:"chu",cv:"chv",cy:"cym",da:"dan",de:"deu",dv:"div",dz:"dzo",ee:"ewe",el:"ell",en:"eng",eo:"epo",es:"spa",et:"est",eu:"eus",fa:"fas",ff:"ful",fi:"fin",fj:"fij",fo:"fao",fr:"fra",fy:"fry",ga:"gle",gd:"gla",gl:"glg",gn:"grn",gu:"guj",gv:"glv",ha:"hau",he:"heb",hi:"hin",ho:"hmo",hr:"hrv",ht:"hat",hu:"hun",hy:"hye",hz:"her",ia:"ina",id:"ind",ie:"ile",ig:"ibo",ii:"iii",ik:"ipk",io:"ido",is:"isl",it:"ita",iu:"iku",ja:"jpn",jv:"jav", ka:"kat",kg:"kon",ki:"kik",kj:"kua",kk:"kaz",kl:"kal",km:"khm",kn:"kan",ko:"kor",kr:"kau",ks:"kas",ku:"kur",kv:"kom",kw:"cor",ky:"kir",la:"lat",lb:"ltz",lg:"lug",li:"lim",ln:"lin",lo:"lao",lt:"lit",lu:"lub",lv:"lav",mg:"mlg",mh:"mah",mi:"mri",mk:"mkd",ml:"mal",mn:"mon",mr:"mar",ms:"msa",mt:"mlt",my:"mya",na:"nau",nb:"nob",nd:"nde",ne:"nep",ng:"ndo",nl:"nld",nn:"nno",no:"nor",nr:"nbl",nv:"nav",ny:"nya",oc:"oci",oj:"oji",om:"orm",or:"ori",os:"oss",pa:"pan",pi:"pli",pl:"pol",ps:"pus",pt:"por",qu:"que", rm:"roh",rn:"run",ro:"ron",ru:"rus",rw:"kin",sa:"san",sc:"srd",sd:"snd",se:"sme",sg:"sag",si:"sin",sk:"slk",sl:"slv",sm:"smo",sn:"sna",so:"som",sq:"sqi",sr:"srp",ss:"ssw",st:"sot",su:"sun",sv:"swe",sw:"swa",ta:"tam",te:"tel",tg:"tgk",th:"tha",ti:"tir",tk:"tuk",tl:"tgl",tn:"tsn",to:"ton",tr:"tur",ts:"tso",tt:"tat",tw:"twi",ty:"tah",ug:"uig",uk:"ukr",ur:"urd",uz:"uzb",ve:"ven",vi:"vie",vo:"vol",wa:"wln",wo:"wol",xh:"xho",yi:"yid",yo:"yor",za:"zha",zh:"zho",zu:"zul"}},function(b,d,a){d.a={alb:"sqi", arm:"hye",baq:"eus",bur:"mya",chi:"zho",cze:"ces",dut:"nld",fre:"fra",geo:"kat",ger:"deu",gre:"ell",ice:"isl",mac:"mkd",mao:"mri",may:"msa",per:"fas",slo:"slk",rum:"ron",tib:"bod",wel:"cym"}},function(b,d,a){d.a=function(a){var b=a.reduce(function(a,b){a[b]=b;return a},{});b.keys=a;return b}},function(b,d,a){d.a=function(b){var d=!1;return function(){if(d)return h.Observable.empty();d=!0;return a.i(l.a)(b.apply(void 0,arguments)).do(null,function(){return d=!1},function(){return d=!1})}};var h=a(0); a.n(h);var l=a(9)},function(b,d,a){d.a=function(){for(var a=0,b=arguments.length;a<b;){if(void 0!==(arguments.length<=a?void 0:arguments[a]))return arguments.length<=a?void 0:arguments[a];a++}}},function(b,d,a){d.a=function(){for(var a=0,b=arguments.length;a<b;){if(null!=(arguments.length<=a?void 0:arguments[a]))return arguments.length<=a?void 0:arguments[a];a++}}},function(b,d,a){function h(a){return!a||"object"!==typeof a||"number"!==typeof a.length||"function"!==typeof a.copy||"function"!==typeof a.slice|| 0<a.length&&"number"!==typeof a[0]?!1:!0}function l(a,b,d){var e;if(null===a||void 0===a||null===b||void 0===b||a.prototype!==b.prototype)return!1;if(f(a)){if(!f(b))return!1;a=g.call(a);b=g.call(b);return c(a,b,d)}if(h(a)){if(!h(b)||a.length!==b.length)return!1;for(e=0;e<a.length;e++)if(a[e]!==b[e])return!1;return!0}try{var l=k(a);var m=k(b)}catch(t){return!1}if(l.length!=m.length)return!1;l.sort();m.sort();for(e=l.length-1;0<=e;e--)if(l[e]!=m[e])return!1;for(e=l.length-1;0<=e;e--)if(m=l[e],!c(a[m], b[m],d))return!1;return typeof a===typeof b}var g=Array.prototype.slice,k=a(171),f=a(170),c=b.exports=function(a,b,c){c||(c={});return a===b?!0:a instanceof Date&&b instanceof Date?a.getTime()===b.getTime():!a||!b||"object"!=typeof a&&"object"!=typeof b?c.strict?a===b:a==b:l(a,b,c)}},function(b,d){function a(a){return"[object Arguments]"==Object.prototype.toString.call(a)}function h(a){return a&&"object"==typeof a&&"number"==typeof a.length&&Object.prototype.hasOwnProperty.call(a,"callee")&&!Object.prototype.propertyIsEnumerable.call(a, "callee")||!1}d="[object Arguments]"==function(){return Object.prototype.toString.call(arguments)}();d=b.exports=d?a:h;d.supported=a;d.unsupported=h},function(b,d){function a(a){var b=[],d;for(d in a)b.push(d);return b}d=b.exports="function"===typeof Object.keys?Object.keys:a;d.shim=a},function(b,d,a){var h=this&&this.__extends||function(a,b){function d(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(d.prototype=b.prototype,new d)};b=function(a){function b(b, f,c){a.call(this);this.parent=b;this.outerValue=f;this.outerIndex=c;this.index=0}h(b,a);b.prototype._next=function(a){this.parent.notifyNext(this.outerValue,a,this.outerIndex,this.index++,this)};b.prototype._error=function(a){this.parent.notifyError(a,this);this.unsubscribe()};b.prototype._complete=function(){this.parent.notifyComplete(this);this.unsubscribe()};return b}(a(3).Subscriber);d.InnerSubscriber=b},function(b,d,a){var h=a(0);b=function(){function a(a,b,f){this.kind=a;this.value=b;this.error= f;this.hasValue="N"===a}a.prototype.observe=function(a){switch(this.kind){case "N":return a.next&&a.next(this.value);case "E":return a.error&&a.error(this.error);case "C":return a.complete&&a.complete()}};a.prototype.do=function(a,b,f){switch(this.kind){case "N":return a&&a(this.value);case "E":return b&&b(this.error);case "C":return f&&f()}};a.prototype.accept=function(a,b,f){return a&&"function"===typeof a.next?this.observe(a):this.do(a,b,f)};a.prototype.toObservable=function(){switch(this.kind){case "N":return h.Observable.of(this.value); case "E":return h.Observable.throw(this.error);case "C":return h.Observable.empty()}throw Error("unexpected notification kind value");};a.createNext=function(b){return"undefined"!==typeof b?new a("N",b):a.undefinedValueNotification};a.createError=function(b){return new a("E",void 0,b)};a.createComplete=function(){return a.completeNotification};a.completeNotification=new a("C");a.undefinedValueNotification=new a("N",void 0);return a}();d.Notification=b},function(b,d,a){var h=this&&this.__extends|| function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(5);var l=a(260),g=a(11),k=a(77),f=a(50),c=a(72);a=function(a){function b(b,c,e){void 0===b&&(b=Number.POSITIVE_INFINITY);void 0===c&&(c=Number.POSITIVE_INFINITY);a.call(this);this.scheduler=e;this._events=[];this._bufferSize=1>b?1:b;this._windowTime=1>c?1:c}h(b,a);b.prototype.next=function(b){var c=this._getNow();this._events.push(new e(c, b));this._trimBufferThenGetEvents();a.prototype.next.call(this,b)};b.prototype._subscribe=function(a){var b=this._trimBufferThenGetEvents(),e=this.scheduler;if(this.closed)throw new f.ObjectUnsubscribedError;if(this.hasError)var d=g.Subscription.EMPTY;else this.isStopped?d=g.Subscription.EMPTY:(this.observers.push(a),d=new c.SubjectSubscription(this,a));e&&a.add(a=new k.ObserveOnSubscriber(a,e));e=b.length;for(var h=0;h<e&&!a.closed;h++)a.next(b[h].value);this.hasError?a.error(this.thrownError):this.isStopped&& a.complete();return d};b.prototype._getNow=function(){return(this.scheduler||l.queue).now()};b.prototype._trimBufferThenGetEvents=function(){for(var a=this._getNow(),b=this._bufferSize,c=this._windowTime,e=this._events,f=e.length,d=0;d<f&&!(a-e[d].time<c);)d++;f>b&&(d=Math.max(d,f-b));0<d&&e.splice(0,d);return e};return b}(b.Subject);d.ReplaySubject=a;var e=function(){return function(a,b){this.time=a;this.value=b}}()},function(b,d,a){b=function(){function a(b,d){void 0===d&&(d=a.now);this.SchedulerAction= b;this.now=d}a.prototype.schedule=function(a,b,d){void 0===b&&(b=0);return(new this.SchedulerAction(this,a)).schedule(d,b)};a.now=Date.now?Date.now:function(){return+new Date};return a}();d.Scheduler=b},function(b,d,a){b=a(0);a=a(223);b.Observable.combineLatest=a.combineLatest},function(b,d,a){b=a(0);a=a(224);b.Observable.defer=a.defer},function(b,d,a){b=a(0);a=a(225);b.Observable.empty=a.empty},function(b,d,a){b=a(0);a=a(226);b.Observable.from=a.from},function(b,d,a){b=a(0);a=a(227);b.Observable.fromEvent= a.fromEvent},function(b,d,a){b=a(0);a=a(228);b.Observable.fromPromise=a.fromPromise},function(b,d,a){b=a(0);a=a(229);b.Observable.interval=a.interval},function(b,d,a){b=a(0);a=a(230);b.Observable.merge=a.merge},function(b,d,a){b=a(0);a=a(231);b.Observable.never=a.never},function(b,d,a){b=a(0);a=a(232);b.Observable.of=a.of},function(b,d,a){b=a(0);a=a(233);b.Observable.throw=a._throw},function(b,d,a){b=a(0);a=a(234);b.Observable.timer=a.timer},function(b,d,a){b=a(0);a=a(235);b.Observable.prototype.catch= a._catch;b.Observable.prototype._catch=a._catch},function(b,d,a){b=a(0);a=a(74);b.Observable.prototype.concat=a.concat},function(b,d,a){b=a(0);a=a(237);b.Observable.prototype.concatAll=a.concatAll},function(b,d,a){b=a(0);a=a(238);b.Observable.prototype.concatMap=a.concatMap},function(b,d,a){b=a(0);a=a(239);b.Observable.prototype.debounceTime=a.debounceTime},function(b,d,a){b=a(0);a=a(240);b.Observable.prototype.distinctUntilChanged=a.distinctUntilChanged},function(b,d,a){b=a(0);a=a(241);b.Observable.prototype.do= a._do;b.Observable.prototype._do=a._do},function(b,d,a){b=a(0);a=a(242);b.Observable.prototype.filter=a.filter},function(b,d,a){b=a(0);a=a(243);b.Observable.prototype.finally=a._finally;b.Observable.prototype._finally=a._finally},function(b,d,a){b=a(0);a=a(244);b.Observable.prototype.ignoreElements=a.ignoreElements},function(b,d,a){b=a(0);a=a(245);b.Observable.prototype.map=a.map},function(b,d,a){b=a(0);a=a(246);b.Observable.prototype.mapTo=a.mapTo},function(b,d,a){b=a(0);a=a(75);b.Observable.prototype.merge= a.merge},function(b,d,a){b=a(0);a=a(76);b.Observable.prototype.mergeMap=a.mergeMap;b.Observable.prototype.flatMap=a.mergeMap},function(b,d,a){b=a(0);a=a(46);b.Observable.prototype.multicast=a.multicast},function(b,d,a){b=a(0);a=a(247);b.Observable.prototype.pairwise=a.pairwise},function(b,d,a){b=a(0);a=a(248);b.Observable.prototype.publish=a.publish},function(b,d,a){b=a(0);a=a(249);b.Observable.prototype.scan=a.scan},function(b,d,a){b=a(0);a=a(250);b.Observable.prototype.share=a.share},function(b, d,a){b=a(0);a=a(251);b.Observable.prototype.skip=a.skip},function(b,d,a){b=a(0);a=a(252);b.Observable.prototype.startWith=a.startWith},function(b,d,a){b=a(0);a=a(253);b.Observable.prototype.switchMap=a.switchMap},function(b,d,a){b=a(0);a=a(254);b.Observable.prototype.take=a.take},function(b,d,a){b=a(0);a=a(255);b.Observable.prototype.takeUntil=a.takeUntil},function(b,d,a){b=a(0);a=a(256);b.Observable.prototype.timeout=a.timeout},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor= a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(0);var l=a(44),g=a(25);a=function(a){function b(b,e){a.call(this);this.arrayLike=b;this.scheduler=e;e||1!==b.length||(this._isScalar=!0,this.value=b[0])}h(b,a);b.create=function(a,e){var c=a.length;return 0===c?new g.EmptyObservable:1===c?new l.ScalarObservable(a[0],e):new b(a,e)};b.dispatch=function(a){var b=a.arrayLike,c=a.index,f=a.subscriber;f.closed||(c>=a.length?f.complete(): (f.next(b[c]),a.index=c+1,this.schedule(a)))};b.prototype._subscribe=function(a){var c=this.arrayLike,f=this.scheduler,d=c.length;if(f)return f.schedule(b.dispatch,0,{arrayLike:c,index:0,length:d,subscriber:a});for(f=0;f<d&&!a.closed;f++)a.next(c[f]);a.complete()};return b}(b.Observable);d.ArrayLikeObservable=a},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype= b.prototype,new c)};b=a(5);var l=a(0),g=a(3),k=a(11);a=function(a){function b(b,c){a.call(this);this.source=b;this.subjectFactory=c;this._refCount=0;this._isComplete=!1}h(b,a);b.prototype._subscribe=function(a){return this.getSubject().subscribe(a)};b.prototype.getSubject=function(){var a=this._subject;if(!a||a.isStopped)this._subject=this.subjectFactory();return this._subject};b.prototype.connect=function(){var a=this._connection;a||(this._isComplete=!1,a=this._connection=new k.Subscription,a.add(this.source.subscribe(new f(this.getSubject(), this))),a.closed?(this._connection=null,a=k.Subscription.EMPTY):this._connection=a);return a};b.prototype.refCount=function(){return this.lift(new c(this))};return b}(l.Observable);d.ConnectableObservable=a;a=a.prototype;d.connectableObservableDescriptor={operator:{value:null},_refCount:{value:0,writable:!0},_subject:{value:null,writable:!0},_connection:{value:null,writable:!0},_subscribe:{value:a._subscribe},_isComplete:{value:a._isComplete,writable:!0},getSubject:{value:a.getSubject},connect:{value:a.connect}, refCount:{value:a.refCount}};var f=function(a){function b(b,c){a.call(this,b);this.connectable=c}h(b,a);b.prototype._error=function(b){this._unsubscribe();a.prototype._error.call(this,b)};b.prototype._complete=function(){this.connectable._isComplete=!0;this._unsubscribe();a.prototype._complete.call(this)};b.prototype._unsubscribe=function(){var a=this.connectable;if(a){this.connectable=null;var b=a._connection;a._refCount=0;a._subject=null;a._connection=null;b&&b.unsubscribe()}};return b}(b.SubjectSubscriber), c=function(){function a(a){this.connectable=a}a.prototype.call=function(a,b){var c=this.connectable;c._refCount++;a=new e(a,c);b=b.subscribe(a);a.closed||(a.connection=c.connect());return b};return a}(),e=function(a){function b(b,c){a.call(this,b);this.connectable=c}h(b,a);b.prototype._unsubscribe=function(){var a=this.connectable;if(a){this.connectable=null;var b=a._refCount;0>=b?this.connection=null:(a._refCount=b-1,1<b?this.connection=null:(b=this.connection,a=a._connection,this.connection=null, !a||b&&a!==b||a.unsubscribe()))}else this.connection=null};return b}(g.Subscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(0);var l=a(16);a=a(14);b=function(a){function b(b){a.call(this);this.observableFactory=b}h(b,a);b.create=function(a){return new b(a)};b.prototype._subscribe=function(a){return new g(a,this.observableFactory)}; return b}(b.Observable);d.DeferObservable=b;var g=function(a){function b(b,e){a.call(this,b);this.factory=e;this.tryDefer()}h(b,a);b.prototype.tryDefer=function(){try{this._callFactory()}catch(c){this._error(c)}};b.prototype._callFactory=function(){var a=this.factory();a&&this.add(l.subscribeToResult(this,a))};return b}(a.OuterSubscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function d(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b? Object.create(b):(d.prototype=b.prototype,new d)};b=function(a){function b(b,f){a.call(this);this.error=b;this.scheduler=f}h(b,a);b.create=function(a,f){return new b(a,f)};b.dispatch=function(a){a.subscriber.error(a.error)};b.prototype._subscribe=function(a){var f=this.error,c=this.scheduler;a.syncErrorThrowable=!0;if(c)return c.schedule(b.dispatch,0,{error:f,subscriber:a});a.error(f)};return b}(a(0).Observable);d.ErrorObservable=b},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor= a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(0);var l=a(52),g=a(51),k=a(33),f=a(11),c=Object.prototype.toString;a=function(a){function b(b,c,e,f){a.call(this);this.sourceObj=b;this.eventName=c;this.selector=e;this.options=f}h(b,a);b.create=function(a,c,e,f){g.isFunction(e)&&(f=e,e=void 0);return new b(a,c,f,e)};b.setupSubscription=function(a,e,d,k,g){if(a&&"[object NodeList]"===c.call(a)||a&&"[object HTMLCollection]"=== c.call(a))for(var h=0,l=a.length;h<l;h++)b.setupSubscription(a[h],e,d,k,g);else if(a&&"function"===typeof a.addEventListener&&"function"===typeof a.removeEventListener){a.addEventListener(e,d,g);var m=function(){return a.removeEventListener(e,d)}}else if(a&&"function"===typeof a.on&&"function"===typeof a.off)a.on(e,d),m=function(){return a.off(e,d)};else if(a&&"function"===typeof a.addListener&&"function"===typeof a.removeListener)a.addListener(e,d),m=function(){return a.removeListener(e,d)};else throw new TypeError("Invalid event target"); k.add(new f.Subscription(m))};b.prototype._subscribe=function(a){var c=this.selector;b.setupSubscription(this.sourceObj,this.eventName,c?function(){for(var b=[],e=0;e<arguments.length;e++)b[e-0]=arguments[e];b=l.tryCatch(c).apply(void 0,b);b===k.errorObject?a.error(k.errorObject.e):a.next(b)}:function(b){return a.next(b)},a,this.options)};return b}(b.Observable);d.FromEventObservable=a},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&& (a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},l=a(26),g=a(81),k=a(85),f=a(73),c=a(220),e=a(15),m=a(213),n=a(47),q=a(0),r=a(77),p=a(48);b=function(a){function b(b,c){a.call(this,null);this.ish=b;this.scheduler=c}h(b,a);b.create=function(a,d){if(null!=a){if("function"===typeof a[p.observable])return a instanceof q.Observable&&!d?a:new b(a,d);if(l.isArray(a))return new e.ArrayObservable(a,d);if(k.isPromise(a))return new f.PromiseObservable(a,d);if("function"===typeof a[n.iterator]|| "string"===typeof a)return new c.IteratorObservable(a,d);if(g.isArrayLike(a))return new m.ArrayLikeObservable(a,d)}throw new TypeError((null!==a&&typeof a||a)+" is not observable");};b.prototype._subscribe=function(a){var b=this.ish,c=this.scheduler;return null==c?b[p.observable]().subscribe(a):b[p.observable]().subscribe(new r.ObserveOnSubscriber(a,c,0))};return b}(q.Observable);d.FromObservable=b},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&& (a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},l=a(83);b=a(0);var g=a(32);a=function(a){function b(b,e){void 0===b&&(b=0);void 0===e&&(e=g.async);a.call(this);this.period=b;this.scheduler=e;if(!l.isNumeric(b)||0>b)this.period=0;e&&"function"===typeof e.schedule||(this.scheduler=g.async)}h(b,a);b.create=function(a,e){void 0===a&&(a=0);void 0===e&&(e=g.async);return new b(a,e)};b.dispatch=function(a){var b=a.subscriber,c=a.period;b.next(a.index);b.closed||(a.index+= 1,this.schedule(a,c))};b.prototype._subscribe=function(a){var c=this.period;a.add(this.scheduler.schedule(b.dispatch,c,{index:0,subscriber:a,period:c}))};return b}(b.Observable);d.IntervalObservable=a},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},l=a(12);b=a(0);var g=a(47);a=function(a){function b(b,c){a.call(this);this.scheduler=c;if(null== b)throw Error("iterator cannot be null.");if((c=b[g.iterator])||"string"!==typeof b)if(c||void 0===b.length){if(!c)throw new TypeError("object is not iterable");b=b[g.iterator]()}else b=new f(b);else b=new k(b);this.iterator=b}h(b,a);b.create=function(a,c){return new b(a,c)};b.dispatch=function(a){var b=a.index,c=a.iterator,e=a.subscriber;if(a.hasError)e.error(a.error);else{var f=c.next();f.done?e.complete():(e.next(f.value),a.index=b+1,e.closed?"function"===typeof c.return&&c.return():this.schedule(a))}}; b.prototype._subscribe=function(a){var c=this.iterator,e=this.scheduler;if(e)return e.schedule(b.dispatch,0,{index:0,iterator:c,subscriber:a});do{e=c.next();if(e.done){a.complete();break}else a.next(e.value);if(a.closed){"function"===typeof c.return&&c.return();break}}while(1)};return b}(b.Observable);d.IteratorObservable=a;var k=function(){function a(a,b,c){void 0===b&&(b=0);void 0===c&&(c=a.length);this.str=a;this.idx=b;this.len=c}a.prototype[g.iterator]=function(){return this};a.prototype.next= function(){return this.idx<this.len?{done:!1,value:this.str.charAt(this.idx++)}:{done:!0,value:void 0}};return a}(),f=function(){function a(a,b,e){void 0===b&&(b=0);if(void 0===e)if(e=+a.length,isNaN(e))e=0;else if(0!==e&&"number"===typeof e&&l.root.isFinite(e)){var f=+e;f=0===f?f:isNaN(f)?f:0>f?-1:1;e=f*Math.floor(Math.abs(e));e=0>=e?0:e>c?c:e}this.arr=a;this.idx=b;this.len=e}a.prototype[g.iterator]=function(){return this};a.prototype.next=function(){return this.idx<this.len?{done:!1,value:this.arr[this.idx++]}: {done:!0,value:void 0}};return a}(),c=Math.pow(2,53)-1},function(b,d,a){var h=this&&this.__extends||function(a,b){function f(){this.constructor=a}for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);a.prototype=null===b?Object.create(b):(f.prototype=b.prototype,new f)};b=a(0);var l=a(86);a=function(a){function b(){a.call(this)}h(b,a);b.create=function(){return new b};b.prototype._subscribe=function(a){l.noop()};return b}(b.Observable);d.NeverObservable=a},function(b,d,a){var h=this&&this.__extends||function(a, b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},l=a(83);b=a(0);var g=a(32),k=a(20),f=a(82);a=function(a){function b(b,c,e){void 0===b&&(b=0);a.call(this);this.period=-1;this.dueTime=0;l.isNumeric(c)?this.period=1>Number(c)&&1||Number(c):k.isScheduler(c)&&(e=c);k.isScheduler(e)||(e=g.async);this.scheduler=e;this.dueTime=f.isDate(b)?+b-this.scheduler.now():b}h(b,a);b.create=function(a,c,e){void 0=== a&&(a=0);return new b(a,c,e)};b.dispatch=function(a){var b=a.index,c=a.period,e=a.subscriber;e.next(b);if(!e.closed){if(-1===c)return e.complete();a.index=b+1;this.schedule(a,c)}};b.prototype._subscribe=function(a){return this.scheduler.schedule(b.dispatch,this.dueTime,{index:0,period:this.period,subscriber:a})};return b}(b.Observable);d.TimerObservable=a},function(b,d,a){var h=a(20),l=a(26),g=a(15),k=a(236);d.combineLatest=function(){for(var a=[],b=0;b<arguments.length;b++)a[b-0]=arguments[b];var e= b=null;h.isScheduler(a[a.length-1])&&(e=a.pop());"function"===typeof a[a.length-1]&&(b=a.pop());1===a.length&&l.isArray(a[0])&&(a=a[0]);return(new g.ArrayObservable(a,e)).lift(new k.CombineLatestOperator(b))}},function(b,d,a){b=a(215);d.defer=b.DeferObservable.create},function(b,d,a){b=a(25);d.empty=b.EmptyObservable.create},function(b,d,a){b=a(218);d.from=b.FromObservable.create},function(b,d,a){b=a(217);d.fromEvent=b.FromEventObservable.create},function(b,d,a){b=a(73);d.fromPromise=b.PromiseObservable.create}, function(b,d,a){b=a(219);d.interval=b.IntervalObservable.create},function(b,d,a){b=a(75);d.merge=b.mergeStatic},function(b,d,a){b=a(221);d.never=b.NeverObservable.create},function(b,d,a){b=a(15);d.of=b.ArrayObservable.of},function(b,d,a){b=a(216);d._throw=b.ErrorObservable.create},function(b,d,a){b=a(222);d.timer=b.TimerObservable.create},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b): (c.prototype=b.prototype,new c)};b=a(14);var l=a(16);d._catch=function(a){a=new g(a);var b=this.lift(a);return a.caught=b};var g=function(){function a(a){this.selector=a}a.prototype.call=function(a,b){return b.subscribe(new k(a,this.selector,this.caught))};return a}(),k=function(a){function b(b,c,d){a.call(this,b);this.selector=c;this.caught=d}h(b,a);b.prototype.error=function(b){if(!this.isStopped){var c=void 0;try{c=this.selector(b,this.caught)}catch(n){a.prototype.error.call(this,n);return}this._unsubscribeAndRecycle(); this.add(l.subscribeToResult(this,c))}};return b}(b.OuterSubscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},l=a(15),g=a(26);b=a(14);var k=a(16),f={};d.combineLatest=function(){for(var a=[],b=0;b<arguments.length;b++)a[b-0]=arguments[b];b=null;"function"===typeof a[a.length-1]&&(b=a.pop());1===a.length&&g.isArray(a[0])&&(a=a[0].slice()); a.unshift(this);return this.lift.call(new l.ArrayObservable(a),new c(b))};var c=function(){function a(a){this.project=a}a.prototype.call=function(a,b){return b.subscribe(new e(a,this.project))};return a}();d.CombineLatestOperator=c;var e=function(a){function b(b,c){a.call(this,b);this.project=c;this.active=0;this.values=[];this.observables=[]}h(b,a);b.prototype._next=function(a){this.values.push(f);this.observables.push(a)};b.prototype._complete=function(){var a=this.observables,b=a.length;if(0=== b)this.destination.complete();else{this.toRespond=this.active=b;for(var c=0;c<b;c++){var e=a[c];this.add(k.subscribeToResult(this,e,e,c))}}};b.prototype.notifyComplete=function(a){0===--this.active&&this.destination.complete()};b.prototype.notifyNext=function(a,b,c,e,d){a=this.values;e=a[c];e=this.toRespond?e===f?--this.toRespond:this.toRespond:0;a[c]=b;0===e&&(this.project?this._tryProject(a):this.destination.next(a.slice()))};b.prototype._tryProject=function(a){try{var b=this.project.apply(this, a)}catch(p){this.destination.error(p);return}this.destination.next(b)};return b}(b.OuterSubscriber);d.CombineLatestSubscriber=e},function(b,d,a){var h=a(45);d.concatAll=function(){return this.lift(new h.MergeAllOperator(1))}},function(b,d,a){var h=a(76);d.concatMap=function(a,b){return this.lift(new h.MergeMapOperator(a,b,1))}},function(b,d,a){function h(a){a.debouncedNext()}var l=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype= null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(3);var g=a(32);d.debounceTime=function(a,b){void 0===b&&(b=g.async);return this.lift(new k(a,b))};var k=function(){function a(a,b){this.dueTime=a;this.scheduler=b}a.prototype.call=function(a,b){return b.subscribe(new f(a,this.dueTime,this.scheduler))};return a}(),f=function(a){function b(b,c,e){a.call(this,b);this.dueTime=c;this.scheduler=e;this.lastValue=this.debouncedSubscription=null;this.hasValue=!1}l(b,a);b.prototype._next=function(a){this.clearDebounce(); this.lastValue=a;this.hasValue=!0;this.add(this.debouncedSubscription=this.scheduler.schedule(h,this.dueTime,this))};b.prototype._complete=function(){this.debouncedNext();this.destination.complete()};b.prototype.debouncedNext=function(){this.clearDebounce();this.hasValue&&(this.destination.next(this.lastValue),this.lastValue=null,this.hasValue=!1)};b.prototype.clearDebounce=function(){var a=this.debouncedSubscription;null!==a&&(this.remove(a),a.unsubscribe(),this.debouncedSubscription=null)};return b}(b.Subscriber)}, function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(3);var l=a(52),g=a(33);d.distinctUntilChanged=function(a,b){return this.lift(new k(a,b))};var k=function(){function a(a,b){this.compare=a;this.keySelector=b}a.prototype.call=function(a,b){return b.subscribe(new f(a,this.compare,this.keySelector))};return a}(),f=function(a){function b(b,c, e){a.call(this,b);this.keySelector=e;this.hasKey=!1;"function"===typeof c&&(this.compare=c)}h(b,a);b.prototype.compare=function(a,b){return a===b};b.prototype._next=function(a){var b=a;if(this.keySelector&&(b=l.tryCatch(this.keySelector)(a),b===g.errorObject))return this.destination.error(g.errorObject.e);var c=!1;if(this.hasKey){if(c=l.tryCatch(this.compare)(this.key,b),c===g.errorObject)return this.destination.error(g.errorObject.e)}else this.hasKey=!0;!1===!!c&&(this.key=b,this.destination.next(a))}; return b}(b.Subscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},l=a(3);d._do=function(a,b,e){return this.lift(new g(a,b,e))};var g=function(){function a(a,b,d){this.nextOrObserver=a;this.error=b;this.complete=d}a.prototype.call=function(a,b){return b.subscribe(new k(a,this.nextOrObserver,this.error,this.complete))};return a}(),k= function(a){function b(b,c,d,f){a.call(this,b);b=new l.Subscriber(c,d,f);b.syncErrorThrowable=!0;this.add(b);this.safeSubscriber=b}h(b,a);b.prototype._next=function(a){var b=this.safeSubscriber;b.next(a);b.syncErrorThrown?this.destination.error(b.syncErrorValue):this.destination.next(a)};b.prototype._error=function(a){var b=this.safeSubscriber;b.error(a);b.syncErrorThrown?this.destination.error(b.syncErrorValue):this.destination.error(a)};b.prototype._complete=function(){var a=this.safeSubscriber; a.complete();a.syncErrorThrown?this.destination.error(a.syncErrorValue):this.destination.complete()};return b}(l.Subscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(3);d.filter=function(a,b){return this.lift(new l(a,b))};var l=function(){function a(a,b){this.predicate=a;this.thisArg=b}a.prototype.call=function(a,b){return b.subscribe(new g(a, this.predicate,this.thisArg))};return a}(),g=function(a){function b(b,e,d){a.call(this,b);this.predicate=e;this.thisArg=d;this.count=0}h(b,a);b.prototype._next=function(a){try{var b=this.predicate.call(this.thisArg,a,this.count++)}catch(m){this.destination.error(m);return}b&&this.destination.next(a)};return b}(b.Subscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b): (c.prototype=b.prototype,new c)};b=a(3);var l=a(11);d._finally=function(a){return this.lift(new g(a))};var g=function(){function a(a){this.callback=a}a.prototype.call=function(a,b){return b.subscribe(new k(a,this.callback))};return a}(),k=function(a){function b(b,c){a.call(this,b);this.add(new l.Subscription(c))}h(b,a);return b}(b.Subscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null=== b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(3);var l=a(86);d.ignoreElements=function(){return this.lift(new g)};var g=function(){function a(){}a.prototype.call=function(a,b){return b.subscribe(new k(a))};return a}(),k=function(a){function b(){a.apply(this,arguments)}h(b,a);b.prototype._next=function(a){l.noop()};return b}(b.Subscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype= null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(3);d.map=function(a,b){if("function"!==typeof a)throw new TypeError("argument is not a function. Are you looking for `mapTo()`?");return this.lift(new l(a,b))};var l=function(){function a(a,b){this.project=a;this.thisArg=b}a.prototype.call=function(a,b){return b.subscribe(new g(a,this.project,this.thisArg))};return a}();d.MapOperator=l;var g=function(a){function b(b,e,d){a.call(this,b);this.project=e;this.count=0;this.thisArg=d||this} h(b,a);b.prototype._next=function(a){try{var b=this.project.call(this.thisArg,a,this.count++)}catch(m){this.destination.error(m);return}this.destination.next(b)};return b}(b.Subscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(3);d.mapTo=function(a){return this.lift(new l(a))};var l=function(){function a(a){this.value=a}a.prototype.call= function(a,b){return b.subscribe(new g(a,this.value))};return a}(),g=function(a){function b(b,e){a.call(this,b);this.value=e}h(b,a);b.prototype._next=function(a){this.destination.next(this.value)};return b}(b.Subscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(3);d.pairwise=function(){return this.lift(new l)};var l=function(){function a(){} a.prototype.call=function(a,b){return b.subscribe(new g(a))};return a}(),g=function(a){function b(b){a.call(this,b);this.hasPrev=!1}h(b,a);b.prototype._next=function(a){this.hasPrev?this.destination.next([this.prev,a]):this.hasPrev=!0;this.prev=a};return b}(b.Subscriber)},function(b,d,a){var h=a(5),l=a(46);d.publish=function(a){return a?l.multicast.call(this,function(){return new h.Subject},a):l.multicast.call(this,new h.Subject)}},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor= a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(3);d.scan=function(a,b){var c=!1;2<=arguments.length&&(c=!0);return this.lift(new l(a,b,c))};var l=function(){function a(a,b,e){void 0===e&&(e=!1);this.accumulator=a;this.seed=b;this.hasSeed=e}a.prototype.call=function(a,b){return b.subscribe(new g(a,this.accumulator,this.seed,this.hasSeed))};return a}(),g=function(a){function b(b,e,d,f){a.call(this,b);this.accumulator=e;this._seed= d;this.hasSeed=f;this.index=0}h(b,a);Object.defineProperty(b.prototype,"seed",{get:function(){return this._seed},set:function(a){this.hasSeed=!0;this._seed=a},enumerable:!0,configurable:!0});b.prototype._next=function(a){if(this.hasSeed)return this._tryNext(a);this.seed=a;this.destination.next(a)};b.prototype._tryNext=function(a){var b=this.index++;try{var c=this.accumulator(this.seed,a,b)}catch(n){this.destination.error(n)}this.seed=c;this.destination.next(c)};return b}(b.Subscriber)},function(b, d,a){function h(){return new g.Subject}var l=a(46),g=a(5);d.share=function(){return l.multicast.call(this,h).refCount()}},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(3);d.skip=function(a){return this.lift(new l(a))};var l=function(){function a(a){this.total=a}a.prototype.call=function(a,b){return b.subscribe(new g(a,this.total))}; return a}(),g=function(a){function b(b,e){a.call(this,b);this.total=e;this.count=0}h(b,a);b.prototype._next=function(a){++this.count>this.total&&this.destination.next(a)};return b}(b.Subscriber)},function(b,d,a){var h=a(15),l=a(44),g=a(25),k=a(74),f=a(20);d.startWith=function(){for(var a=[],b=0;b<arguments.length;b++)a[b-0]=arguments[b];b=a[a.length-1];f.isScheduler(b)?a.pop():b=null;var d=a.length;return 1===d?k.concatStatic(new l.ScalarObservable(a[0],b),this):1<d?k.concatStatic(new h.ArrayObservable(a, b),this):k.concatStatic(new g.EmptyObservable(b),this)}},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(14);var l=a(16);d.switchMap=function(a,b){return this.lift(new g(a,b))};var g=function(){function a(a,b){this.project=a;this.resultSelector=b}a.prototype.call=function(a,b){return b.subscribe(new k(a,this.project,this.resultSelector))}; return a}(),k=function(a){function b(b,c,d){a.call(this,b);this.project=c;this.resultSelector=d;this.index=0}h(b,a);b.prototype._next=function(a){var b=this.index++;try{var c=this.project(a,b)}catch(q){this.destination.error(q);return}this._innerSub(c,a,b)};b.prototype._innerSub=function(a,b,c){var e=this.innerSubscription;e&&e.unsubscribe();this.add(this.innerSubscription=l.subscribeToResult(this,a,b,c))};b.prototype._complete=function(){var b=this.innerSubscription;b&&!b.closed||a.prototype._complete.call(this)}; b.prototype._unsubscribe=function(){this.innerSubscription=null};b.prototype.notifyComplete=function(b){this.remove(b);this.innerSubscription=null;this.isStopped&&a.prototype._complete.call(this)};b.prototype.notifyNext=function(a,b,c,d,f){this.resultSelector?this._tryNotifyNext(a,b,c,d):this.destination.next(b)};b.prototype._tryNotifyNext=function(a,b,c,d){try{var e=this.resultSelector(a,b,c,d)}catch(p){this.destination.error(p);return}this.destination.next(e)};return b}(b.OuterSubscriber)},function(b, d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(3);var l=a(261),g=a(25);d.take=function(a){return 0===a?new g.EmptyObservable:this.lift(new k(a))};var k=function(){function a(a){this.total=a;if(0>this.total)throw new l.ArgumentOutOfRangeError;}a.prototype.call=function(a,b){return b.subscribe(new f(a,this.total))};return a}(),f=function(a){function b(b, c){a.call(this,b);this.total=c;this.count=0}h(b,a);b.prototype._next=function(a){var b=this.total,c=++this.count;c<=b&&(this.destination.next(a),c===b&&(this.destination.complete(),this.unsubscribe()))};return b}(b.Subscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};b=a(14);var l=a(16);d.takeUntil=function(a){return this.lift(new g(a))}; var g=function(){function a(a){this.notifier=a}a.prototype.call=function(a,b){return b.subscribe(new k(a,this.notifier))};return a}(),k=function(a){function b(b,c){a.call(this,b);this.notifier=c;this.add(l.subscribeToResult(this,c))}h(b,a);b.prototype.notifyNext=function(a,b,c,d,f){this.complete()};b.prototype.notifyComplete=function(){};return b}(b.OuterSubscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var e in b)b.hasOwnProperty(e)&&(a[e]= b[e]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},l=a(32),g=a(82);b=a(3);var k=a(80);d.timeout=function(a,b){void 0===b&&(b=l.async);var c=g.isDate(a);a=c?+a-b.now():Math.abs(a);return this.lift(new f(a,c,b,new k.TimeoutError))};var f=function(){function a(a,b,c,e){this.waitFor=a;this.absoluteTimeout=b;this.scheduler=c;this.errorInstance=e}a.prototype.call=function(a,b){return b.subscribe(new c(a,this.absoluteTimeout,this.waitFor,this.scheduler,this.errorInstance))};return a}(), c=function(a){function b(b,c,d,e,f){a.call(this,b);this.absoluteTimeout=c;this.waitFor=d;this.scheduler=e;this.errorInstance=f;this.action=null;this.scheduleTimeout()}h(b,a);b.dispatchTimeout=function(a){a.error(a.errorInstance)};b.prototype.scheduleTimeout=function(){var a=this.action;a?this.action=a.schedule(this,this.waitFor):this.add(this.action=this.scheduler.schedule(b.dispatchTimeout,this.waitFor,this))};b.prototype._next=function(b){this.absoluteTimeout||this.scheduleTimeout();a.prototype._next.call(this, b)};b.prototype._unsubscribe=function(){this.errorInstance=this.scheduler=this.action=null};return b}(b.Subscriber)},function(b,d,a){var h=this&&this.__extends||function(a,b){function d(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(d.prototype=b.prototype,new d)};b=function(a){function b(b,d){a.call(this)}h(b,a);b.prototype.schedule=function(a,b){return this};return b}(a(11).Subscription);d.Action=b},function(b,d,a){var h=this&&this.__extends|| function(a,b){function d(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(d.prototype=b.prototype,new d)};b=function(a){function b(b,d){a.call(this,b,d);this.scheduler=b;this.work=d}h(b,a);b.prototype.schedule=function(b,d){void 0===d&&(d=0);if(0<d)return a.prototype.schedule.call(this,b,d);this.delay=d;this.state=b;this.scheduler.flush(this);return this};b.prototype.execute=function(b,d){return 0<d||this.closed?a.prototype.execute.call(this, b,d):this._execute(b,d)};b.prototype.requestAsyncId=function(b,d,c){void 0===c&&(c=0);return null!==c&&0<c||null===c&&0<this.delay?a.prototype.requestAsyncId.call(this,b,d,c):b.flush(this)};return b}(a(78).AsyncAction);d.QueueAction=b},function(b,d,a){var h=this&&this.__extends||function(a,b){function d(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(d.prototype=b.prototype,new d)};b=function(a){function b(){a.apply(this,arguments)}h(b,a); return b}(a(79).AsyncScheduler);d.QueueScheduler=b},function(b,d,a){b=a(258);a=a(259);d.queue=new a.QueueScheduler(b.QueueAction)},function(b,d,a){var h=this&&this.__extends||function(a,b){function d(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(d.prototype=b.prototype,new d)};b=function(a){function b(){var b=a.call(this,"argument out of range");this.name=b.name="ArgumentOutOfRangeError";this.stack=b.stack;this.message=b.message}h(b,a); return b}(Error);d.ArgumentOutOfRangeError=b},function(b,d,a){var h=this&&this.__extends||function(a,b){function d(){this.constructor=a}for(var f in b)b.hasOwnProperty(f)&&(a[f]=b[f]);a.prototype=null===b?Object.create(b):(d.prototype=b.prototype,new d)};b=function(a){function b(b){a.call(this);this.errors=b;b=Error.call(this,b?b.length+" errors occurred during unsubscription:\n "+b.map(function(a,b){return b+1+") "+a.toString()}).join("\n "):"");this.name=b.name="UnsubscriptionError";this.stack= b.stack;this.message=b.message}h(b,a);return b}(Error);d.UnsubscriptionError=b},function(b,d,a){var h=a(3),l=a(49),g=a(71);d.toSubscriber=function(a,b,c){if(a){if(a instanceof h.Subscriber)return a;if(a[l.rxSubscriber])return a[l.rxSubscriber]()}return a||b||c?new h.Subscriber(a,b,c):new h.Subscriber(g.empty)}},function(b,d){d=function(){return this}();try{d=d||Function("return this")()||(0,eval)("this")}catch(a){"object"===typeof window&&(d=window)}b.exports=d}])});
/* Highcharts JS v7.1.0 (2019-04-01) (c) 2010-2019 Highsoft AS Author: Sebastian Domas License: www.highcharts.com/license */ (function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/modules/histogram-bellcurve",["highcharts"],function(c){a(c);a.Highcharts=c;return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){function c(b,a,g,m){b.hasOwnProperty(a)||(b[a]=m.apply(null,g))}a=a?a._modules:{};c(a,"mixins/derived-series.js",[a["parts/Globals.js"]],function(a){var b=a.Series,g=a.addEvent;return{hasDerivedData:!0, init:function(){b.prototype.init.apply(this,arguments);this.initialised=!1;this.baseSeries=null;this.eventRemovers=[];this.addEvents()},setDerivedData:a.noop,setBaseSeries:function(){var a=this.chart,b=this.options.baseSeries;this.baseSeries=b&&(a.series[b]||a.get(b))||null},addEvents:function(){var a=this,b;b=g(this.chart,"afterLinkSeries",function(){a.setBaseSeries();a.baseSeries&&!a.initialised&&(a.setDerivedData(),a.addBaseSeriesEvents(),a.initialised=!0)});this.eventRemovers.push(b)},addBaseSeriesEvents:function(){var a= this,b,e;b=g(a.baseSeries,"updatedData",function(){a.setDerivedData()});e=g(a.baseSeries,"destroy",function(){a.baseSeries=null;a.initialised=!1});a.eventRemovers.push(b,e)},destroy:function(){this.eventRemovers.forEach(function(a){a()});b.prototype.destroy.apply(this,arguments)}}});c(a,"modules/histogram.src.js",[a["parts/Globals.js"],a["mixins/derived-series.js"]],function(a,c){function b(a){return function(f){for(var b=1;a[b]<=f;)b++;return a[--b]}}var m=a.objectEach,k=a.seriesType,e=a.correctFloat, n=a.isNumber,q=a.arrayMax,r=a.arrayMin;a=a.merge;var d={"square-root":function(a){return Math.ceil(Math.sqrt(a.options.data.length))},sturges:function(a){return Math.ceil(Math.log(a.options.data.length)*Math.LOG2E)},rice:function(a){return Math.ceil(2*Math.pow(a.options.data.length,1/3))}};k("histogram","column",{binsNumber:"square-root",binWidth:void 0,pointPadding:0,groupPadding:0,grouping:!1,pointPlacement:"between",tooltip:{headerFormat:"",pointFormat:'\x3cspan style\x3d"font-size: 10px"\x3e{point.x} - {point.x2}\x3c/span\x3e\x3cbr/\x3e\x3cspan style\x3d"color:{point.color}"\x3e\u25cf\x3c/span\x3e {series.name} \x3cb\x3e{point.y}\x3c/b\x3e\x3cbr/\x3e'}}, a(c,{setDerivedData:function(){var a=this.derivedData(this.baseSeries.yData,this.binsNumber(),this.options.binWidth);this.setData(a,!1)},derivedData:function(a,h,d){var f=q(a),l=e(r(a)),c=[],g={},p=[],k;d=this.binWidth=this.options.pointRange=e(n(d)?d||1:(f-l)/h);for(h=l;h<f&&(this.userOptions.binWidth||e(f-h)>=d||0>=e(l+c.length*d-h));h=e(h+d))c.push(h),g[h]=0;0!==g[l]&&(c.push(e(l)),g[e(l)]=0);k=b(c.map(function(a){return parseFloat(a)}));a.forEach(function(a){a=e(k(a));g[a]++});m(g,function(a, b){p.push({x:Number(b),y:a,x2:e(Number(b)+d)})});p.sort(function(a,b){return a.x-b.x});return p},binsNumber:function(){var a=this.options.binsNumber,b=d[a]||"function"===typeof a&&a;return Math.ceil(b&&b(this.baseSeries)||(n(a)?a:d["square-root"](this.baseSeries)))}}))});c(a,"modules/bellcurve.src.js",[a["parts/Globals.js"],a["mixins/derived-series.js"]],function(a,c){function b(a){var b=a.length;a=a.reduce(function(a,b){return a+b},0);return 0<b&&a/b}function m(a,d){var f=a.length;d=q(d)?d:b(a); a=a.reduce(function(a,b){b-=d;return a+b*b},0);return 1<f&&Math.sqrt(a/(f-1))}function k(a,b,f){a-=b;return Math.exp(-(a*a)/(2*f*f))/(f*Math.sqrt(2*Math.PI))}var e=a.seriesType,n=a.correctFloat,q=a.isNumber;a=a.merge;e("bellcurve","areaspline",{intervals:3,pointsInInterval:3,marker:{enabled:!1}},a(c,{setMean:function(){this.mean=n(b(this.baseSeries.yData))},setStandardDeviation:function(){this.standardDeviation=n(m(this.baseSeries.yData,this.mean))},setDerivedData:function(){1<this.baseSeries.yData.length&& (this.setMean(),this.setStandardDeviation(),this.setData(this.derivedData(this.mean,this.standardDeviation),!1))},derivedData:function(a,b){var f=this.options.intervals,c=this.options.pointsInInterval,d=a-f*b,f=f*c*2+1,c=b/c,e=[],g;for(g=0;g<f;g++)e.push([d,k(d,a,b)]),d+=c;return e}}))});c(a,"masters/modules/histogram-bellcurve.src.js",[],function(){})}); //# sourceMappingURL=histogram-bellcurve.js.map
var vows = require('vows'), _ = require('underscore')._, RawTests = require('./selenium.vows'); // makeSuite takes a configuration and makes a batch of tests, splitting // up tests according to 'conf.processes' exports.makeSuite = function(conf) { var getCapText = function(conf, cap) { return " (" + cap.browserName+"_"+cap.version+"_"+cap.platform+"_"+conf.serviceName+")"; }; // gets a version of the testbase relativized to a particular config // and capability request var getTestsForCap = function(cap) { var capText = getCapText(conf, cap); var allTests = RawTests.allTests(conf, cap, capText); var capTests = {}; // Replace the name of each test with a relativized name showing // which conf and caps we are using _.each(allTests, function(test, testName) { capTests[testName+capText] = test; }); return capTests; }; // Gather tests for all capabilities requests into one big dict var allTests = {}; _.each(conf.caps, function(cap) { var tests = getTestsForCap(cap); _.each(tests, function(test, testName) { allTests[testName] = test; }); }); // Split tests into batches according to how parallelized we want to be var numTests = _.size(allTests); if (conf.maxTests && conf.maxTests < numTests) { numTests = conf.maxTests; } var numBatches = Math.ceil(numTests / conf.processes); if (numBatches >= 1) { var batches = {}; var testsPerBatch = numBatches * conf.processes; var i = 0; var total = 0; _.each(allTests, function(test, testName) { if (!conf.maxTests || total < conf.maxTests) { if (typeof batches[i] === 'undefined') { batches[i] = {}; } batches[i][testName] = test; if (i < numBatches - 1) { i++; } else { i = 0; } total++; } }); return batches; } };
var path = require('path'); var Supervisor = require(path.join(__dirname,'/../processes/supervisor')); /** * @function stopGateway * @description Halts all pocesses. */ function stopGateway() { return new Supervisor().stop(); } module.exports = stopGateway;
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { Injector, NgModule, NgZone, OpaqueToken } from '@angular/core'; import { AsyncTestCompleter } from './async_test_completer'; import { ComponentFixture } from './component_fixture'; import { stringify } from './facade/lang'; import { TestingCompilerFactory } from './test_compiler'; var UNDEFINED = new Object(); /** * An abstract class for inserting the root test component element in a platform independent way. * * @experimental */ export var TestComponentRenderer = (function () { function TestComponentRenderer() { } TestComponentRenderer.prototype.insertRootElement = function (rootElementId) { }; return TestComponentRenderer; }()); var _nextRootElementId = 0; /** * @experimental */ export var ComponentFixtureAutoDetect = new OpaqueToken('ComponentFixtureAutoDetect'); /** * @experimental */ export var ComponentFixtureNoNgZone = new OpaqueToken('ComponentFixtureNoNgZone'); /** * @whatItDoes Configures and initializes environment for unit testing and provides methods for * creating components and services in unit tests. * @description * * TestBed is the primary api for writing unit tests for Angular applications and libraries. * * @stable */ export var TestBed = (function () { function TestBed() { this._instantiated = false; this._compiler = null; this._moduleRef = null; this._moduleWithComponentFactories = null; this._compilerOptions = []; this._moduleOverrides = []; this._componentOverrides = []; this._directiveOverrides = []; this._pipeOverrides = []; this._providers = []; this._declarations = []; this._imports = []; this._schemas = []; this._activeFixtures = []; this.platform = null; this.ngModule = null; } /** * Initialize the environment for testing with a compiler factory, a PlatformRef, and an * angular module. These are common to every test in the suite. * * This may only be called once, to set up the common providers for the current test * suite on the current platform. If you absolutely need to change the providers, * first use `resetTestEnvironment`. * * Test modules and platforms for individual platforms are available from * '@angular/<platform_name>/testing'. * * @experimental */ TestBed.initTestEnvironment = function (ngModule, platform) { var testBed = getTestBed(); testBed.initTestEnvironment(ngModule, platform); return testBed; }; /** * Reset the providers for the test injector. * * @experimental */ TestBed.resetTestEnvironment = function () { getTestBed().resetTestEnvironment(); }; TestBed.resetTestingModule = function () { getTestBed().resetTestingModule(); return TestBed; }; /** * Allows overriding default compiler providers and settings * which are defined in test_injector.js */ TestBed.configureCompiler = function (config) { getTestBed().configureCompiler(config); return TestBed; }; /** * Allows overriding default providers, directives, pipes, modules of the test injector, * which are defined in test_injector.js */ TestBed.configureTestingModule = function (moduleDef) { getTestBed().configureTestingModule(moduleDef); return TestBed; }; /** * Compile components with a `templateUrl` for the test's NgModule. * It is necessary to call this function * as fetching urls is asynchronous. */ TestBed.compileComponents = function () { return getTestBed().compileComponents(); }; TestBed.overrideModule = function (ngModule, override) { getTestBed().overrideModule(ngModule, override); return TestBed; }; TestBed.overrideComponent = function (component, override) { getTestBed().overrideComponent(component, override); return TestBed; }; TestBed.overrideDirective = function (directive, override) { getTestBed().overrideDirective(directive, override); return TestBed; }; TestBed.overridePipe = function (pipe, override) { getTestBed().overridePipe(pipe, override); return TestBed; }; TestBed.get = function (token, notFoundValue) { if (notFoundValue === void 0) { notFoundValue = Injector.THROW_IF_NOT_FOUND; } return getTestBed().get(token, notFoundValue); }; TestBed.createComponent = function (component) { return getTestBed().createComponent(component); }; /** * Initialize the environment for testing with a compiler factory, a PlatformRef, and an * angular module. These are common to every test in the suite. * * This may only be called once, to set up the common providers for the current test * suite on the current platform. If you absolutely need to change the providers, * first use `resetTestEnvironment`. * * Test modules and platforms for individual platforms are available from * '@angular/<platform_name>/testing'. * * @experimental */ TestBed.prototype.initTestEnvironment = function (ngModule, platform) { if (this.platform || this.ngModule) { throw new Error('Cannot set base providers because it has already been called'); } this.platform = platform; this.ngModule = ngModule; }; /** * Reset the providers for the test injector. * * @experimental */ TestBed.prototype.resetTestEnvironment = function () { this.resetTestingModule(); this.platform = null; this.ngModule = null; }; TestBed.prototype.resetTestingModule = function () { this._compiler = null; this._moduleOverrides = []; this._componentOverrides = []; this._directiveOverrides = []; this._pipeOverrides = []; this._moduleRef = null; this._moduleWithComponentFactories = null; this._compilerOptions = []; this._providers = []; this._declarations = []; this._imports = []; this._schemas = []; this._instantiated = false; this._activeFixtures.forEach(function (fixture) { return fixture.destroy(); }); this._activeFixtures = []; }; TestBed.prototype.configureCompiler = function (config) { this._assertNotInstantiated('TestBed.configureCompiler', 'configure the compiler'); this._compilerOptions.push(config); }; TestBed.prototype.configureTestingModule = function (moduleDef) { this._assertNotInstantiated('TestBed.configureTestingModule', 'configure the test module'); if (moduleDef.providers) { (_a = this._providers).push.apply(_a, moduleDef.providers); } if (moduleDef.declarations) { (_b = this._declarations).push.apply(_b, moduleDef.declarations); } if (moduleDef.imports) { (_c = this._imports).push.apply(_c, moduleDef.imports); } if (moduleDef.schemas) { (_d = this._schemas).push.apply(_d, moduleDef.schemas); } var _a, _b, _c, _d; }; TestBed.prototype.compileComponents = function () { var _this = this; if (this._moduleWithComponentFactories || this._instantiated) { return Promise.resolve(null); } var moduleType = this._createCompilerAndModule(); return this._compiler.compileModuleAndAllComponentsAsync(moduleType) .then(function (moduleAndComponentFactories) { _this._moduleWithComponentFactories = moduleAndComponentFactories; }); }; TestBed.prototype._initIfNeeded = function () { if (this._instantiated) { return; } if (!this._moduleWithComponentFactories) { try { var moduleType = this._createCompilerAndModule(); this._moduleWithComponentFactories = this._compiler.compileModuleAndAllComponentsSync(moduleType); } catch (e) { if (e.compType) { throw new Error(("This test module uses the component " + stringify(e.compType) + " which is using a \"templateUrl\", but they were never compiled. ") + "Please call \"TestBed.compileComponents\" before your test."); } else { throw e; } } } this._moduleRef = this._moduleWithComponentFactories.ngModuleFactory.create(this.platform.injector); this._instantiated = true; }; TestBed.prototype._createCompilerAndModule = function () { var _this = this; var providers = this._providers.concat([{ provide: TestBed, useValue: this }]); var declarations = this._declarations; var imports = [this.ngModule, this._imports]; var schemas = this._schemas; var DynamicTestModule = (function () { function DynamicTestModule() { } DynamicTestModule.decorators = [ { type: NgModule, args: [{ providers: providers, declarations: declarations, imports: imports, schemas: schemas },] }, ]; /** @nocollapse */ DynamicTestModule.ctorParameters = function () { return []; }; return DynamicTestModule; }()); var compilerFactory = this.platform.injector.get(TestingCompilerFactory); this._compiler = compilerFactory.createTestingCompiler(this._compilerOptions.concat([{ useDebug: true }])); this._moduleOverrides.forEach(function (entry) { return _this._compiler.overrideModule(entry[0], entry[1]); }); this._componentOverrides.forEach(function (entry) { return _this._compiler.overrideComponent(entry[0], entry[1]); }); this._directiveOverrides.forEach(function (entry) { return _this._compiler.overrideDirective(entry[0], entry[1]); }); this._pipeOverrides.forEach(function (entry) { return _this._compiler.overridePipe(entry[0], entry[1]); }); return DynamicTestModule; }; TestBed.prototype._assertNotInstantiated = function (methodName, methodDescription) { if (this._instantiated) { throw new Error(("Cannot " + methodDescription + " when the test module has already been instantiated. ") + ("Make sure you are not using `inject` before `" + methodName + "`.")); } }; TestBed.prototype.get = function (token, notFoundValue) { if (notFoundValue === void 0) { notFoundValue = Injector.THROW_IF_NOT_FOUND; } this._initIfNeeded(); if (token === TestBed) { return this; } // Tests can inject things from the ng module and from the compiler, // but the ng module can't inject things from the compiler and vice versa. var result = this._moduleRef.injector.get(token, UNDEFINED); return result === UNDEFINED ? this._compiler.injector.get(token, notFoundValue) : result; }; TestBed.prototype.execute = function (tokens, fn) { var _this = this; this._initIfNeeded(); var params = tokens.map(function (t) { return _this.get(t); }); return fn.apply(void 0, params); }; TestBed.prototype.overrideModule = function (ngModule, override) { this._assertNotInstantiated('overrideModule', 'override module metadata'); this._moduleOverrides.push([ngModule, override]); }; TestBed.prototype.overrideComponent = function (component, override) { this._assertNotInstantiated('overrideComponent', 'override component metadata'); this._componentOverrides.push([component, override]); }; TestBed.prototype.overrideDirective = function (directive, override) { this._assertNotInstantiated('overrideDirective', 'override directive metadata'); this._directiveOverrides.push([directive, override]); }; TestBed.prototype.overridePipe = function (pipe, override) { this._assertNotInstantiated('overridePipe', 'override pipe metadata'); this._pipeOverrides.push([pipe, override]); }; TestBed.prototype.createComponent = function (component) { var _this = this; this._initIfNeeded(); var componentFactory = this._moduleWithComponentFactories.componentFactories.find(function (compFactory) { return compFactory.componentType === component; }); if (!componentFactory) { throw new Error("Cannot create the component " + stringify(component) + " as it was not imported into the testing module!"); } var noNgZone = this.get(ComponentFixtureNoNgZone, false); var autoDetect = this.get(ComponentFixtureAutoDetect, false); var ngZone = noNgZone ? null : this.get(NgZone, null); var testComponentRenderer = this.get(TestComponentRenderer); var rootElId = "root" + _nextRootElementId++; testComponentRenderer.insertRootElement(rootElId); var initComponent = function () { var componentRef = componentFactory.create(_this, [], "#" + rootElId); return new ComponentFixture(componentRef, ngZone, autoDetect); }; var fixture = !ngZone ? initComponent() : ngZone.run(initComponent); this._activeFixtures.push(fixture); return fixture; }; return TestBed; }()); var _testBed = null; /** * @experimental */ export function getTestBed() { return _testBed = _testBed || new TestBed(); } /** * Allows injecting dependencies in `beforeEach()` and `it()`. * * Example: * * ``` * beforeEach(inject([Dependency, AClass], (dep, object) => { * // some code that uses `dep` and `object` * // ... * })); * * it('...', inject([AClass], (object) => { * object.doSomething(); * expect(...); * }) * ``` * * Notes: * - inject is currently a function because of some Traceur limitation the syntax should * eventually * becomes `it('...', @Inject (object: AClass, async: AsyncTestCompleter) => { ... });` * * @stable */ export function inject(tokens, fn) { var testBed = getTestBed(); if (tokens.indexOf(AsyncTestCompleter) >= 0) { return function () { // Return an async test method that returns a Promise if AsyncTestCompleter is one of // the // injected tokens. return testBed.compileComponents().then(function () { var completer = testBed.get(AsyncTestCompleter); testBed.execute(tokens, fn); return completer.promise; }); }; } else { return function () { return testBed.execute(tokens, fn); }; } } /** * @experimental */ export var InjectSetupWrapper = (function () { function InjectSetupWrapper(_moduleDef) { this._moduleDef = _moduleDef; } InjectSetupWrapper.prototype._addModule = function () { var moduleDef = this._moduleDef(); if (moduleDef) { getTestBed().configureTestingModule(moduleDef); } }; InjectSetupWrapper.prototype.inject = function (tokens, fn) { var _this = this; return function () { _this._addModule(); return inject(tokens, fn)(); }; }; return InjectSetupWrapper; }()); export function withModule(moduleDef, fn) { if (fn === void 0) { fn = null; } if (fn) { return function () { var testBed = getTestBed(); if (moduleDef) { testBed.configureTestingModule(moduleDef); } return fn(); }; } return new InjectSetupWrapper(function () { return moduleDef; }); } //# sourceMappingURL=test_bed.js.map
'use strict'; (function(window, document, $, undefined) { window.kunstmaan = window.kunstmaan || {}; window.kunstmaan.leadGeneration = window.kunstmaan.leadGeneration || {}; window.kunstmaan.leadGeneration.Popup = function(name, htmlId) { var instance = { 'name': name }; var _rules = [], _$popup = $('#' + htmlId), _$close = $('.' + htmlId + '--close'), _$noThanks = $('.' + htmlId + '--no-thanks'), _$submit = $('.' + htmlId + '--submit'); var _listenToHtmlClicks, _listenToEvents, _conditionsMet, _forEachRule, _doConditionsMetLogic, _htmlNoThanks, _noThanks, _htmlClose, _close, _conversion, _htmlSubmit, _submit, _onSubmitSuccess, _getData, _setData; instance.addRule = function(rule) { rule.setPopup(instance); _rules.push(rule); }; instance.activate = function() { _listenToHtmlClicks(); _listenToEvents(); window.kunstmaan.leadGeneration.log(instance.name + ": activating all rules"); // listening to all rules document.addEventListener(window.kunstmaan.leadGeneration.events.CONDITIONS_MET, _conditionsMet, true); var data = _getData(); // if not converted && not clicked "no thanks", activate & listen to rules if (data === null || (!data.already_converted && !data.no_thanks)) { if (_rules.length === 0) { // when there are nu rules, directly show the popup _doConditionsMetLogic(); } else { _forEachRule(function(rule) { rule.activate(); }); } } }; instance.show = function() { window.kunstmaan.leadGeneration.log(instance.name + ": show popup"); document.dispatchEvent(new window.CustomEvent(window.kunstmaan.leadGeneration.events.BEFORE_SHOWING, { detail: {popup: instance.name} })); $('#' + htmlId).removeClass('popup--hide').addClass('popup--show'); var data = _getData(); data.last_shown = new window.Date().getTime(); _setData(data); document.dispatchEvent(new window.CustomEvent(window.kunstmaan.leadGeneration.events.IS_SHOWING, { detail: {popup: instance.name} })); }; instance.setRuleProperty = function(ruleId, id, value) { var data = _getData(); if (!data.rule) { data.rule = {}; } if (!data.rule[ruleId]) { data.rule[ruleId] = {}; } // adjust timestamp data.rule[ruleId][id] = value; // store in browser storage _setData(data); }; instance.getRuleProperty = function(ruleId, id) { var data = _getData(); if (!data.rule || !data.rule[ruleId] || !data.rule[ruleId][id]) { return false; } return data.rule[ruleId][id]; }; _listenToHtmlClicks = function() { _$close.click(_htmlClose); _$noThanks.click(_htmlNoThanks); _$submit.click(_htmlSubmit); }; _listenToEvents = function() { document.addEventListener(window.kunstmaan.leadGeneration.events.DO_CLOSE, _close, true); document.addEventListener(window.kunstmaan.leadGeneration.events.DO_NO_THANKS, _noThanks, true); document.addEventListener(window.kunstmaan.leadGeneration.events.DO_SUBMIT_FORM, _submit, true); document.addEventListener(window.kunstmaan.leadGeneration.events.DO_CONVERSION, _conversion, true); }; _conditionsMet = function(event) { if (event.detail.popup === instance.name) { window.kunstmaan.leadGeneration.log(instance.name + ": checking all conditions"); _doConditionsMetLogic(); } }; _forEachRule = function(cb) { var i = 0; for (; i < _rules.length; i++) { cb(_rules[i]); } }; _doConditionsMetLogic = function() { var areMet = true; _forEachRule(function(rule) { if (!rule.isMet) { areMet = false; } }); var data = _getData(); // if all conditions are met notify that the popup is ready to be shown if (areMet && (data === null || (!data.already_converted && !data.no_thanks))) { window.kunstmaan.leadGeneration.log(instance.name + ": firing ready event"); document.dispatchEvent(new window.CustomEvent(window.kunstmaan.leadGeneration.events.READY_TO_SHOW, { detail: {popup: instance.name} })); } }; _htmlNoThanks = function(event) { window.kunstmaan.leadGeneration.log(instance.name + ": no thanks"); event.preventDefault(); document.dispatchEvent(new window.CustomEvent(window.kunstmaan.leadGeneration.events.DO_NO_THANKS, { detail: {popup: instance.name} })); }; _noThanks = function(event) { if (event.detail.popup === instance.name) { window.kunstmaan.leadGeneration.log(instance.name + ": no thanks event catched"); var data = _getData(); data.no_thanks = true; _setData(data); document.dispatchEvent(new window.CustomEvent(window.kunstmaan.leadGeneration.events.NO_THANKS, { detail: {popup: instance.name} })); _close(event); } }; _htmlClose = function(event) { event.preventDefault(); window.kunstmaan.leadGeneration.log(instance.name + ": html close click"); document.dispatchEvent(new window.CustomEvent(window.kunstmaan.leadGeneration.events.DO_CLOSE, { detail: {popup: instance.name} })); }; _close = function(event) { if (event.detail.popup === instance.name) { document.dispatchEvent(new window.CustomEvent(window.kunstmaan.leadGeneration.events.BEFORE_CLOSING, {detail: {popup: instance.name}})); window.kunstmaan.leadGeneration.log(instance.name + ": close event catched"); _$popup.removeClass('popup--show').addClass('popup--hide'); document.dispatchEvent(new window.CustomEvent(window.kunstmaan.leadGeneration.events.IS_CLOSING, {detail: {popup: instance.name}})); } }; _conversion = function(event) { if (event.detail.popup === instance.name) { window.kunstmaan.leadGeneration.log(instance.name + ': mark as converted'); var data = _getData(); data.already_converted = true; _setData(data); } }; _htmlSubmit = function(event) { event.preventDefault(); window.kunstmaan.leadGeneration.log(instance.name + ': html submit form'); var $form = _$submit.parents('form'); document.dispatchEvent(new window.CustomEvent(window.kunstmaan.leadGeneration.events.DO_SUBMIT_FORM, {detail: {popup: instance.name, form: $form}})); }; _submit = function(event) { if (event.detail.popup === instance.name) { window.kunstmaan.leadGeneration.log(instance.name + ': submit form'); var url = $(event.detail.form).attr('action'); var data = $(event.detail.form).serialize(); $.post(url, data, _onSubmitSuccess); } }; _onSubmitSuccess = function(data) { window.kunstmaan.leadGeneration.log(instance.name + ': onSubmitSuccess'); $('#' + htmlId + '--content').html(data); _listenToHtmlClicks(); }; _getData = function() { if (window.localStorage) { var data = window.localStorage.getItem('popup_' + instance.name); if (data != null) { return window.JSON.parse(data); } else { data = {'last_shown': null, 'already_converted': false, 'no_thanks': false}; _setData(data); } return data; } }; _setData = function(data) { if (window.localStorage) { window.localStorage.setItem('popup_' + instance.name, window.JSON.stringify(data)); } }; return instance; }; })(window, document, $);
var fs = require('fs'); var execSync = require('child_process').execSync; var exec = function (cmd) { execSync(cmd, {stdio: 'inherit'}); }; /* global jake, task, desc, publishTask */ task('build', ['lint', 'clean', 'browserify', 'minify'], function () { console.log('Build completed.'); }); desc('Cleans browerified/minified files and package files'); task('clean', ['clobber'], function () { jake.rmRf('./ejs.js'); jake.rmRf('./ejs.min.js'); console.log('Cleaned up compiled files.'); }); desc('Lints the source code'); task('lint', ['clean'], function () { exec('./node_modules/.bin/eslint "**/*.js"'); console.log('Linting completed.'); }); task('browserify', function () { exec('./node_modules/browserify/bin/cmd.js --standalone ejs lib/ejs.js > ejs.js'); console.log('Browserification completed.'); }); task('minify', function () { exec('./node_modules/uglify-js/bin/uglifyjs ejs.js > ejs.min.js'); console.log('Minification completed.'); }); desc('Generates the EJS API docs'); task('doc', function (dev) { jake.rmRf('out'); var p = dev ? '-p' : ''; exec('./node_modules/.bin/jsdoc ' + p + ' -c jsdoc.json lib/* docs/jsdoc/*'); console.log('Documentation generated.'); }); desc('Publishes the EJS API docs'); task('docPublish', ['doc'], function () { fs.writeFileSync('out/CNAME', 'api.ejs.co'); console.log('Pushing docs to gh-pages...'); exec('./node_modules/.bin/git-directory-deploy --directory out/'); console.log('Docs published to gh-pages.'); }); desc('Runs the EJS test suite'); task('test', ['lint'], function () { exec('./node_modules/.bin/mocha'); }); publishTask('ejs', ['build'], function () { this.packageFiles.include([ 'jakefile.js', 'README.md', 'LICENSE', 'package.json', 'postinstall.js', 'ejs.js', 'ejs.min.js', 'lib/**' ]); }); jake.Task.publish.on('complete', function () { console.log('Updating hosted docs...'); console.log('If this fails, run jake docPublish to re-try.'); jake.Task.docPublish.invoke(); });
define(["npm:aurelia-loader-default@1.0.0-beta.1.0.1/aurelia-loader-default"], function(main) { return main; });
version https://git-lfs.github.com/spec/v1 oid sha256:908993a1b52e182ff79479fca7e10537d646cd9285dde32433ffc66265343ed3 size 1819
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- function write(v) { WScript.Echo(v + ""); } // Win OOB Bug 1150770 Error.x = 10; write(RangeError.x === 10);
angular .module('material.components.icon') .directive('mdIcon', ['$mdIcon', '$mdTheming', '$mdAria', '$sce', mdIconDirective]); /** * @ngdoc directive * @name mdIcon * @module material.components.icon * * @restrict E * * @description * The `md-icon` directive makes it easier to use vector-based icons in your app (as opposed to * raster-based icons types like PNG). The directive supports both icon fonts and SVG icons. * * Icons should be considered view-only elements that should not be used directly as buttons; instead nest a `<md-icon>` * inside a `md-button` to add hover and click features. * * ### Icon fonts * Icon fonts are a technique in which you use a font where the glyphs in the font are * your icons instead of text. Benefits include a straightforward way to bundle everything into a * single HTTP request, simple scaling, easy color changing, and more. * * `md-icon` lets you consume an icon font by letting you reference specific icons in that font * by name rather than character code. * * ### SVG * For SVGs, the problem with using `<img>` or a CSS `background-image` is that you can't take * advantage of some SVG features, such as styling specific parts of the icon with CSS or SVG * animation. * * `md-icon` makes it easier to use SVG icons by *inlining* the SVG into an `<svg>` element in the * document. The most straightforward way of referencing an SVG icon is via URL, just like a * traditional `<img>`. `$mdIconProvider`, as a convenience, lets you _name_ an icon so you can * reference it by name instead of URL throughout your templates. * * Additionally, you may not want to make separate HTTP requests for every icon, so you can bundle * your SVG icons together and pre-load them with $mdIconProvider as an icon set. An icon set can * also be given a name, which acts as a namespace for individual icons, so you can reference them * like `"social:cake"`. * * When using SVGs, both external SVGs (via URLs) or sets of SVGs [from icon sets] can be * easily loaded and used. When using font-icons, developers must follow three (3) simple steps: * * <ol> * <li>Load the font library. e.g.<br/> * `<link href="https://fonts.googleapis.com/icon?family=Material+Icons" * rel="stylesheet">` * </li> * <li> * Use either (a) font-icon class names or (b) a fontset and a font ligature to render the font glyph by * using its textual name _or_ numerical character reference. Note that `material-icons` is the default fontset when * none is specified. * </li> * <li> Use any of the following templates: <br/> * <ul> * <li>`<md-icon md-font-icon="classname"></md-icon>`</li> * <li>`<md-icon md-font-set="font library classname or alias">textual_name</md-icon>`</li> * <li>`<md-icon> numerical_character_reference </md-icon>`</li> * <li>`<md-icon ng_bind="'textual_name'"></md-icon>`</li> * <li>`<md-icon ng-bind="scopeVariable"></md-icon>`</li> * </ul> * </li> * </ol> * * Full details for these steps can be found: * * <ul> * <li>http://google.github.io/material-design-icons/</li> * <li>http://google.github.io/material-design-icons/#icon-font-for-the-web</li> * </ul> * * The Material Design icon style <code>.material-icons</code> and the icon font references are published in * Material Design Icons: * * <ul> * <li>https://design.google.com/icons/</li> * <li>https://design.google.com/icons/#ic_accessibility</li> * </ul> * * ### Localization * * Because an `md-icon` element's text content is not intended to translated, it is recommended to declare the text * content for an `md-icon` element in its start tag. Instead of using the HTML text content, consider using `ng-bind` * with a scope variable or literal string. * * Examples: * * <ul> * <li>`<md-icon ng-bind="myIconVariable"></md-icon>`</li> * <li>`<md-icon ng-bind="'menu'"></md-icon>` * </ul> * * <h2 id="material_design_icons">Material Design Icons</h2> * Using the Material Design Icon-Selector, developers can easily and quickly search for a Material Design font-icon and * determine its textual name and character reference code. Click on any icon to see the slide-up information * panel with details regarding a SVG download or information on the font-icon usage. * * <a href="https://www.google.com/design/icons/#ic_accessibility" target="_blank" style="border-bottom:none;"> * <img src="https://cloud.githubusercontent.com/assets/210413/7902490/fe8dd14c-0780-11e5-98fb-c821cc6475e6.png" * aria-label="Material Design Icon-Selector" style="max-width:75%;padding-left:10%"> * </a> * * <span class="image_caption"> * Click on the image above to link to the * <a href="https://design.google.com/icons/#ic_accessibility" target="_blank">Material Design Icon-Selector</a>. * </span> * * @param {string} md-font-icon String name of CSS icon associated with the font-face will be used * to render the icon. Requires the fonts and the named CSS styles to be preloaded. * @param {string} md-font-set CSS style name associated with the font library; which will be assigned as * the class for the font-icon ligature. This value may also be an alias that is used to lookup the classname; * internally use `$mdIconProvider.fontSet(<alias>)` to determine the style name. * @param {string} md-svg-src String URL (or expression) used to load, cache, and display an * external SVG. * @param {string} md-svg-icon md-svg-icon String name used for lookup of the icon from the internal cache; * interpolated strings or expressions may also be used. Specific set names can be used with * the syntax `<set name>:<icon name>`.<br/><br/> * To use icon sets, developers are required to pre-register the sets using the `$mdIconProvider` service. * @param {string=} aria-label Labels icon for accessibility. If an empty string is provided, icon * will be hidden from accessibility layer with `aria-hidden="true"`. If there's no aria-label on the icon * nor a label on the parent element, a warning will be logged to the console. * @param {string=} alt Labels icon for accessibility. If an empty string is provided, icon * will be hidden from accessibility layer with `aria-hidden="true"`. If there's no alt on the icon * nor a label on the parent element, a warning will be logged to the console. * * @usage * When using SVGs: * <hljs lang="html"> * * <!-- Icon ID; may contain optional icon set prefix; icons must registered using $mdIconProvider --> * <md-icon md-svg-icon="social:android" aria-label="android " ></md-icon> * * <!-- Icon urls; may be preloaded in templateCache --> * <md-icon md-svg-src="/android.svg" aria-label="android " ></md-icon> * <md-icon md-svg-src="{{ getAndroid() }}" aria-label="android " ></md-icon> * * </hljs> * * Use the <code>$mdIconProvider</code> to configure your application with * svg iconsets. * * <hljs lang="js"> * angular.module('appSvgIconSets', ['ngMaterial']) * .controller('DemoCtrl', function($scope) {}) * .config(function($mdIconProvider) { * $mdIconProvider * .iconSet('social', 'img/icons/sets/social-icons.svg', 24) * .defaultIconSet('img/icons/sets/core-icons.svg', 24); * }); * </hljs> * * * When using Font Icons with classnames: * <hljs lang="html"> * * <md-icon md-font-icon="android" aria-label="android" ></md-icon> * <md-icon class="icon_home" aria-label="Home" ></md-icon> * * </hljs> * * When using Material Font Icons with ligatures: * <hljs lang="html"> * <!-- * For Material Design Icons * The class '.material-icons' is auto-added if a style has NOT been specified * since `material-icons` is the default fontset. So your markup: * --> * <md-icon> face </md-icon> * <!-- becomes this at runtime: --> * <md-icon md-font-set="material-icons"> face </md-icon> * <!-- If the fontset does not support ligature names, then we need to use the ligature unicode.--> * <md-icon> &#xE87C; </md-icon> * <!-- The class '.material-icons' must be manually added if other styles are also specified--> * <md-icon class="material-icons md-light md-48"> face </md-icon> * </hljs> * * When using other Font-Icon libraries: * * <hljs lang="js"> * // Specify a font-icon style alias * angular.config(function($mdIconProvider) { * $mdIconProvider.fontSet('md', 'material-icons'); * }); * </hljs> * * <hljs lang="html"> * <md-icon md-font-set="md">favorite</md-icon> * </hljs> * */ function mdIconDirective($mdIcon, $mdTheming, $mdAria, $sce) { return { restrict: 'E', link : postLink }; /** * Directive postLink * Supports embedded SVGs, font-icons, & external SVGs */ function postLink(scope, element, attr) { $mdTheming(element); var lastFontIcon = attr.mdFontIcon; var lastFontSet = $mdIcon.fontSet(attr.mdFontSet); prepareForFontIcon(); attr.$observe('mdFontIcon', fontIconChanged); attr.$observe('mdFontSet', fontIconChanged); // Keep track of the content of the svg src so we can compare against it later to see if the // attribute is static (and thus safe). var originalSvgSrc = element[0].getAttribute(attr.$attr.mdSvgSrc); // If using a font-icon, then the textual name of the icon itself // provides the aria-label. var label = attr.alt || attr.mdFontIcon || attr.mdSvgIcon || element.text(); var attrName = attr.$normalize(attr.$attr.mdSvgIcon || attr.$attr.mdSvgSrc || ''); if ( !attr['aria-label'] ) { if (label !== '' && !parentsHaveText() ) { $mdAria.expect(element, 'aria-label', label); $mdAria.expect(element, 'role', 'img'); } else if ( !element.text() ) { // If not a font-icon with ligature, then // hide from the accessibility layer. $mdAria.expect(element, 'aria-hidden', 'true'); } } if (attrName) { // Use either pre-configured SVG or URL source, respectively. attr.$observe(attrName, function(attrVal) { element.empty(); if (attrVal) { $mdIcon(attrVal) .then(function(svg) { element.empty(); element.append(svg); }); } }); } function parentsHaveText() { var parent = element.parent(); if (parent.attr('aria-label') || parent.text()) { return true; } else if(parent.parent().attr('aria-label') || parent.parent().text()) { return true; } return false; } function prepareForFontIcon() { if (!attr.mdSvgIcon && !attr.mdSvgSrc) { if (attr.mdFontIcon) { element.addClass('md-font ' + attr.mdFontIcon); } element.addClass(lastFontSet); } } function fontIconChanged() { if (!attr.mdSvgIcon && !attr.mdSvgSrc) { if (attr.mdFontIcon) { element.removeClass(lastFontIcon); element.addClass(attr.mdFontIcon); lastFontIcon = attr.mdFontIcon; } var fontSet = $mdIcon.fontSet(attr.mdFontSet); if (lastFontSet !== fontSet) { element.removeClass(lastFontSet); element.addClass(fontSet); lastFontSet = fontSet; } } } } }
version https://git-lfs.github.com/spec/v1 oid sha256:b1828b45943f19da0e26be3154d3d51fd17dc7940a670c52379f02d4ff678d46 size 591
var test = require('tape'); var AmpersandModel = require('ampersand-model'); var AmpersandCollection = require('ampersand-rest-collection'); var AmpersandView = require('../ampersand-view'); var Model = AmpersandModel.extend({ props: { id: 'number', name: ['string', true], html: 'string', url: 'string', something: 'string', fireDanger: 'string' }, session: { active: 'boolean' }, derived: { classes: { deps: ['something', 'fireDanger', 'active'], fn: function () { return this.something + this.active; } } } }); var Collection = AmpersandCollection.extend({ model: Model }); var ItemView = AmpersandView.extend({ template: '<li><a href=""></a><span></span><input/></li>', initialize: function () { // register a misc handler so we can test release this.listenTo(this.model, 'change:something', function () {}); }, render: function () { this.renderWithTemplate(); this.el.id = '_' + this.model.id; return this; } }); var MainView = AmpersandView.extend({ initialize: function () { this.el = document.createElement('div'); this.el.id = 'container'; this.collection = new Collection(getModelData()); }, render: function (opts) { this.el.innerHTML = '<ul></ul>'; this.collectionView = this.renderCollection(this.collection, ItemView, this.query('ul'), opts); return this; }, numberRendered: function () { return this.queryAll('li').length; } }); var MainViewUl = MainView.extend({ initialize: function () { this.el = document.createElement('ul'); this.collection = new Collection(getModelData()); }, render: function (opts) { this.collectionView = this.renderCollection(this.collection, ItemView); return this; } }); function getModelData() { return [ 'Henrik Joreteg', 'Bugs Bunny', 'Scrooge McDuck', 'Crazy Dave', 'Arty Cee' ].map(function (name, count) { return { id: ++count, avatar: 'http://robohash.org/' + name.charAt(1), randomHtml: '<p>yo</p>', name: name, active: count === 2 }; }); } test('test initial render', function (t) { var view = new MainView(); view.render(); t.equal(view.collection.length, 5); t.equal(view.numberRendered(), view.collection.length); t.end(); }); test('collection view is returned', function (t) { var view = new MainView(); view.render(); t.equal(typeof view.collectionView, 'object'); t.equal(view.collectionView.collection.length, 5); t.end(); }); test('this.el is default', function (t) { var view = new MainViewUl(); view.render(); t.equal(view.collection.length, 5); t.equal(view.numberRendered(), view.collection.length); t.end(); }); test('add', function (t) { var view = new MainView(); view.render(); view.collection.add({id: 6}); t.equal(view.numberRendered(), view.collection.length); t.end(); }); test('remove', function (t) { var view = new MainView(); view.render(); view.collection.remove(view.collection.last()); t.equal(view.numberRendered(), view.collection.length); t.end(); }); test('reset', function (t) { var view = new MainView(); view.render(); view.collection.reset(); t.equal(view.numberRendered(), view.collection.length); t.equal(view.numberRendered(), 0); t.end(); }); test('sort', function (t) { var view = new MainView(); view.render(); view.collection.comparator = function (model) { return model.get('name'); }; view.collection.sort(); t.equal(view.numberRendered(), view.collection.length); var domIds = []; view.queryAll('li').forEach(function (el) { domIds.push(Number(el.id.slice(1))); }); t.deepEqual(domIds, [5, 2, 4, 1, 3]); t.end(); }); test('animateRemove', function (t) { var view = new MainView(); view.render(); var prevAnimateRemove = ItemView.prototype.animateRemove; ItemView.prototype.animateRemove = function () { var self = this; this.el.className = 'fadeOut'; setTimeout(function () { self.remove(); }, 100); t.ok('animateRemove called'); }; view.collection.remove(view.collection.last()); setTimeout(function () { t.equal(view.numberRendered(), view.collection.length); // set it back ItemView.prototype.animateRemove = prevAnimateRemove; t.end(); }, 150); }); test('filtered', function (t) { var view = new MainView(); view.render({ filter: function (model) { return model.get('name').length > 10; } }); t.equal(view.numberRendered(), 2); t.end(); }); test('reversed', function (t) { var view = new MainView(); view.render({ reverse: true }); var domIds = []; view.queryAll('li').forEach(function (el) { domIds.push(Number(el.id.slice(1))); }); t.deepEqual(domIds, [5, 4, 3, 2, 1]); t.end(); }); test('cleanup', function (t) { var view = new MainView(); view.render(); t.equal(view.numberRendered(), view.collection.length); t.equal(view.collection.first()._events['change:something'].length, 1); view.remove(); // when main view is removed so should registered event handler // from subview t.notOk(view.collection.first()._events['change:something']); t.end(); }); test('child view can choose to insert self', function (t) { var view = new MainView(); ItemView.prototype.insertSelf = true; ItemView.prototype.render = function (extraInfo) { t.ok(extraInfo.containerEl); this.renderWithTemplate(); }; view.render(); t.equal(view.numberRendered(), 0, 'Parent should not have rendered anything'); view.remove(); t.end(); }); test('child view `parent` should be parent view not collection view, when using `renderCollection()`', function (t) { var Child = AmpersandView.extend({ template: '<li></li>', initialize: function () { t.equal(this.parent, view); t.end(); } }); var View = AmpersandView.extend({ initialize: function () { this.el = document.createElement('div'); this.collection = new Collection([{id: 9}]); }, render: function (opts) { this.el.innerHTML = '<ul></ul>'; this.collectionView = this.renderCollection(this.collection, Child, this.query('ul'), {parent: this}); } }); var view = new View(); view.render(); });
// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file relies on the fact that the following declarations have been made // in runtime.js: // var $Object = global.Object; // var $Boolean = global.Boolean; // var $Number = global.Number; // var $Function = global.Function; // var $Array = global.Array; // // in math.js: // var $floor = MathFloor var $isNaN = GlobalIsNaN; var $isFinite = GlobalIsFinite; // ---------------------------------------------------------------------------- // Helper function used to install functions on objects. function InstallFunctions(object, attributes, functions) { if (functions.length >= 8) { %OptimizeObjectForAddingMultipleProperties(object, functions.length >> 1); } for (var i = 0; i < functions.length; i += 2) { var key = functions[i]; var f = functions[i + 1]; %FunctionSetName(f, key); %FunctionRemovePrototype(f); %AddNamedProperty(object, key, f, attributes); %SetNativeFlag(f); } %ToFastProperties(object); } // Helper function to install a getter-only accessor property. function InstallGetter(object, name, getter) { %FunctionSetName(getter, name); %FunctionRemovePrototype(getter); %DefineAccessorPropertyUnchecked(object, name, getter, null, DONT_ENUM); %SetNativeFlag(getter); } // Helper function to install a getter/setter accessor property. function InstallGetterSetter(object, name, getter, setter) { %FunctionSetName(getter, name); %FunctionSetName(setter, name); %FunctionRemovePrototype(getter); %FunctionRemovePrototype(setter); %DefineAccessorPropertyUnchecked(object, name, getter, setter, DONT_ENUM); %SetNativeFlag(getter); %SetNativeFlag(setter); } // Helper function for installing constant properties on objects. function InstallConstants(object, constants) { if (constants.length >= 4) { %OptimizeObjectForAddingMultipleProperties(object, constants.length >> 1); } var attributes = DONT_ENUM | DONT_DELETE | READ_ONLY; for (var i = 0; i < constants.length; i += 2) { var name = constants[i]; var k = constants[i + 1]; %AddNamedProperty(object, name, k, attributes); } %ToFastProperties(object); } // Prevents changes to the prototype of a built-in function. // The "prototype" property of the function object is made non-configurable, // and the prototype object is made non-extensible. The latter prevents // changing the __proto__ property. function SetUpLockedPrototype(constructor, fields, methods) { %CheckIsBootstrapping(); var prototype = constructor.prototype; // Install functions first, because this function is used to initialize // PropertyDescriptor itself. var property_count = (methods.length >> 1) + (fields ? fields.length : 0); if (property_count >= 4) { %OptimizeObjectForAddingMultipleProperties(prototype, property_count); } if (fields) { for (var i = 0; i < fields.length; i++) { %AddNamedProperty(prototype, fields[i], UNDEFINED, DONT_ENUM | DONT_DELETE); } } for (var i = 0; i < methods.length; i += 2) { var key = methods[i]; var f = methods[i + 1]; %AddNamedProperty(prototype, key, f, DONT_ENUM | DONT_DELETE | READ_ONLY); %SetNativeFlag(f); } %InternalSetPrototype(prototype, null); %ToFastProperties(prototype); } // ---------------------------------------------------------------------------- // ECMA 262 - 15.1.4 function GlobalIsNaN(number) { if (!IS_NUMBER(number)) number = NonNumberToNumber(number); return NUMBER_IS_NAN(number); } // ECMA 262 - 15.1.5 function GlobalIsFinite(number) { if (!IS_NUMBER(number)) number = NonNumberToNumber(number); return NUMBER_IS_FINITE(number); } // ECMA-262 - 15.1.2.2 function GlobalParseInt(string, radix) { if (IS_UNDEFINED(radix) || radix === 10 || radix === 0) { // Some people use parseInt instead of Math.floor. This // optimization makes parseInt on a Smi 12 times faster (60ns // vs 800ns). The following optimization makes parseInt on a // non-Smi number 9 times faster (230ns vs 2070ns). Together // they make parseInt on a string 1.4% slower (274ns vs 270ns). if (%_IsSmi(string)) return string; if (IS_NUMBER(string) && ((0.01 < string && string < 1e9) || (-1e9 < string && string < -0.01))) { // Truncate number. return string | 0; } string = TO_STRING_INLINE(string); radix = radix | 0; } else { // The spec says ToString should be evaluated before ToInt32. string = TO_STRING_INLINE(string); radix = TO_INT32(radix); if (!(radix == 0 || (2 <= radix && radix <= 36))) { return NAN; } } if (%_HasCachedArrayIndex(string) && (radix == 0 || radix == 10)) { return %_GetCachedArrayIndex(string); } return %StringParseInt(string, radix); } // ECMA-262 - 15.1.2.3 function GlobalParseFloat(string) { string = TO_STRING_INLINE(string); if (%_HasCachedArrayIndex(string)) return %_GetCachedArrayIndex(string); return %StringParseFloat(string); } function GlobalEval(x) { if (!IS_STRING(x)) return x; // For consistency with JSC we require the global object passed to // eval to be the global object from which 'eval' originated. This // is not mandated by the spec. // We only throw if the global has been detached, since we need the // receiver as this-value for the call. if (!%IsAttachedGlobal(global)) { throw new $EvalError('The "this" value passed to eval must ' + 'be the global object from which eval originated'); } var global_proxy = %GlobalProxy(global); var f = %CompileString(x, false); if (!IS_FUNCTION(f)) return f; return %_CallFunction(global_proxy, f); } // ---------------------------------------------------------------------------- // Set up global object. function SetUpGlobal() { %CheckIsBootstrapping(); var attributes = DONT_ENUM | DONT_DELETE | READ_ONLY; // ECMA 262 - 15.1.1.1. %AddNamedProperty(global, "NaN", NAN, attributes); // ECMA-262 - 15.1.1.2. %AddNamedProperty(global, "Infinity", INFINITY, attributes); // ECMA-262 - 15.1.1.3. %AddNamedProperty(global, "undefined", UNDEFINED, attributes); // Set up non-enumerable function on the global object. InstallFunctions(global, DONT_ENUM, $Array( "isNaN", GlobalIsNaN, "isFinite", GlobalIsFinite, "parseInt", GlobalParseInt, "parseFloat", GlobalParseFloat, "eval", GlobalEval )); } SetUpGlobal(); // ---------------------------------------------------------------------------- // Object // ECMA-262 - 15.2.4.2 function ObjectToString() { if (IS_UNDEFINED(this) && !IS_UNDETECTABLE(this)) return "[object Undefined]"; if (IS_NULL(this)) return "[object Null]"; return "[object " + %_ClassOf(ToObject(this)) + "]"; } // ECMA-262 - 15.2.4.3 function ObjectToLocaleString() { CHECK_OBJECT_COERCIBLE(this, "Object.prototype.toLocaleString"); return this.toString(); } // ECMA-262 - 15.2.4.4 function ObjectValueOf() { return ToObject(this); } // ECMA-262 - 15.2.4.5 function ObjectHasOwnProperty(V) { if (%IsJSProxy(this)) { // TODO(rossberg): adjust once there is a story for symbols vs proxies. if (IS_SYMBOL(V)) return false; var handler = %GetHandler(this); return CallTrap1(handler, "hasOwn", DerivedHasOwnTrap, ToName(V)); } return %HasOwnProperty(TO_OBJECT_INLINE(this), ToName(V)); } // ECMA-262 - 15.2.4.6 function ObjectIsPrototypeOf(V) { CHECK_OBJECT_COERCIBLE(this, "Object.prototype.isPrototypeOf"); if (!IS_SPEC_OBJECT(V)) return false; return %IsInPrototypeChain(this, V); } // ECMA-262 - 15.2.4.6 function ObjectPropertyIsEnumerable(V) { var P = ToName(V); if (%IsJSProxy(this)) { // TODO(rossberg): adjust once there is a story for symbols vs proxies. if (IS_SYMBOL(V)) return false; var desc = GetOwnPropertyJS(this, P); return IS_UNDEFINED(desc) ? false : desc.isEnumerable(); } return %IsPropertyEnumerable(ToObject(this), P); } // Extensions for providing property getters and setters. function ObjectDefineGetter(name, fun) { var receiver = this; if (receiver == null && !IS_UNDETECTABLE(receiver)) { receiver = %GlobalProxy(global); } if (!IS_SPEC_FUNCTION(fun)) { throw new $TypeError( 'Object.prototype.__defineGetter__: Expecting function'); } var desc = new PropertyDescriptor(); desc.setGet(fun); desc.setEnumerable(true); desc.setConfigurable(true); DefineOwnProperty(ToObject(receiver), ToName(name), desc, false); } function ObjectLookupGetter(name) { var receiver = this; if (receiver == null && !IS_UNDETECTABLE(receiver)) { receiver = %GlobalProxy(global); } return %LookupAccessor(ToObject(receiver), ToName(name), GETTER); } function ObjectDefineSetter(name, fun) { var receiver = this; if (receiver == null && !IS_UNDETECTABLE(receiver)) { receiver = %GlobalProxy(global); } if (!IS_SPEC_FUNCTION(fun)) { throw new $TypeError( 'Object.prototype.__defineSetter__: Expecting function'); } var desc = new PropertyDescriptor(); desc.setSet(fun); desc.setEnumerable(true); desc.setConfigurable(true); DefineOwnProperty(ToObject(receiver), ToName(name), desc, false); } function ObjectLookupSetter(name) { var receiver = this; if (receiver == null && !IS_UNDETECTABLE(receiver)) { receiver = %GlobalProxy(global); } return %LookupAccessor(ToObject(receiver), ToName(name), SETTER); } function ObjectKeys(obj) { if (!IS_SPEC_OBJECT(obj)) { throw MakeTypeError("called_on_non_object", ["Object.keys"]); } if (%IsJSProxy(obj)) { var handler = %GetHandler(obj); var names = CallTrap0(handler, "keys", DerivedKeysTrap); return ToNameArray(names, "keys", false); } return %OwnKeys(obj); } // ES5 8.10.1. function IsAccessorDescriptor(desc) { if (IS_UNDEFINED(desc)) return false; return desc.hasGetter() || desc.hasSetter(); } // ES5 8.10.2. function IsDataDescriptor(desc) { if (IS_UNDEFINED(desc)) return false; return desc.hasValue() || desc.hasWritable(); } // ES5 8.10.3. function IsGenericDescriptor(desc) { if (IS_UNDEFINED(desc)) return false; return !(IsAccessorDescriptor(desc) || IsDataDescriptor(desc)); } function IsInconsistentDescriptor(desc) { return IsAccessorDescriptor(desc) && IsDataDescriptor(desc); } // ES5 8.10.4 function FromPropertyDescriptor(desc) { if (IS_UNDEFINED(desc)) return desc; if (IsDataDescriptor(desc)) { return { value: desc.getValue(), writable: desc.isWritable(), enumerable: desc.isEnumerable(), configurable: desc.isConfigurable() }; } // Must be an AccessorDescriptor then. We never return a generic descriptor. return { get: desc.getGet(), set: desc.getSet(), enumerable: desc.isEnumerable(), configurable: desc.isConfigurable() }; } // Harmony Proxies function FromGenericPropertyDescriptor(desc) { if (IS_UNDEFINED(desc)) return desc; var obj = new $Object(); if (desc.hasValue()) { %AddNamedProperty(obj, "value", desc.getValue(), NONE); } if (desc.hasWritable()) { %AddNamedProperty(obj, "writable", desc.isWritable(), NONE); } if (desc.hasGetter()) { %AddNamedProperty(obj, "get", desc.getGet(), NONE); } if (desc.hasSetter()) { %AddNamedProperty(obj, "set", desc.getSet(), NONE); } if (desc.hasEnumerable()) { %AddNamedProperty(obj, "enumerable", desc.isEnumerable(), NONE); } if (desc.hasConfigurable()) { %AddNamedProperty(obj, "configurable", desc.isConfigurable(), NONE); } return obj; } // ES5 8.10.5. function ToPropertyDescriptor(obj) { if (!IS_SPEC_OBJECT(obj)) { throw MakeTypeError("property_desc_object", [obj]); } var desc = new PropertyDescriptor(); if ("enumerable" in obj) { desc.setEnumerable(ToBoolean(obj.enumerable)); } if ("configurable" in obj) { desc.setConfigurable(ToBoolean(obj.configurable)); } if ("value" in obj) { desc.setValue(obj.value); } if ("writable" in obj) { desc.setWritable(ToBoolean(obj.writable)); } if ("get" in obj) { var get = obj.get; if (!IS_UNDEFINED(get) && !IS_SPEC_FUNCTION(get)) { throw MakeTypeError("getter_must_be_callable", [get]); } desc.setGet(get); } if ("set" in obj) { var set = obj.set; if (!IS_UNDEFINED(set) && !IS_SPEC_FUNCTION(set)) { throw MakeTypeError("setter_must_be_callable", [set]); } desc.setSet(set); } if (IsInconsistentDescriptor(desc)) { throw MakeTypeError("value_and_accessor", [obj]); } return desc; } // For Harmony proxies. function ToCompletePropertyDescriptor(obj) { var desc = ToPropertyDescriptor(obj); if (IsGenericDescriptor(desc) || IsDataDescriptor(desc)) { if (!desc.hasValue()) desc.setValue(UNDEFINED); if (!desc.hasWritable()) desc.setWritable(false); } else { // Is accessor descriptor. if (!desc.hasGetter()) desc.setGet(UNDEFINED); if (!desc.hasSetter()) desc.setSet(UNDEFINED); } if (!desc.hasEnumerable()) desc.setEnumerable(false); if (!desc.hasConfigurable()) desc.setConfigurable(false); return desc; } function PropertyDescriptor() { // Initialize here so they are all in-object and have the same map. // Default values from ES5 8.6.1. this.value_ = UNDEFINED; this.hasValue_ = false; this.writable_ = false; this.hasWritable_ = false; this.enumerable_ = false; this.hasEnumerable_ = false; this.configurable_ = false; this.hasConfigurable_ = false; this.get_ = UNDEFINED; this.hasGetter_ = false; this.set_ = UNDEFINED; this.hasSetter_ = false; } SetUpLockedPrototype(PropertyDescriptor, $Array( "value_", "hasValue_", "writable_", "hasWritable_", "enumerable_", "hasEnumerable_", "configurable_", "hasConfigurable_", "get_", "hasGetter_", "set_", "hasSetter_" ), $Array( "toString", function() { return "[object PropertyDescriptor]"; }, "setValue", function(value) { this.value_ = value; this.hasValue_ = true; }, "getValue", function() { return this.value_; }, "hasValue", function() { return this.hasValue_; }, "setEnumerable", function(enumerable) { this.enumerable_ = enumerable; this.hasEnumerable_ = true; }, "isEnumerable", function () { return this.enumerable_; }, "hasEnumerable", function() { return this.hasEnumerable_; }, "setWritable", function(writable) { this.writable_ = writable; this.hasWritable_ = true; }, "isWritable", function() { return this.writable_; }, "hasWritable", function() { return this.hasWritable_; }, "setConfigurable", function(configurable) { this.configurable_ = configurable; this.hasConfigurable_ = true; }, "hasConfigurable", function() { return this.hasConfigurable_; }, "isConfigurable", function() { return this.configurable_; }, "setGet", function(get) { this.get_ = get; this.hasGetter_ = true; }, "getGet", function() { return this.get_; }, "hasGetter", function() { return this.hasGetter_; }, "setSet", function(set) { this.set_ = set; this.hasSetter_ = true; }, "getSet", function() { return this.set_; }, "hasSetter", function() { return this.hasSetter_; })); // Converts an array returned from Runtime_GetOwnProperty to an actual // property descriptor. For a description of the array layout please // see the runtime.cc file. function ConvertDescriptorArrayToDescriptor(desc_array) { if (desc_array === false) { throw 'Internal error: invalid desc_array'; } if (IS_UNDEFINED(desc_array)) { return UNDEFINED; } var desc = new PropertyDescriptor(); // This is an accessor. if (desc_array[IS_ACCESSOR_INDEX]) { desc.setGet(desc_array[GETTER_INDEX]); desc.setSet(desc_array[SETTER_INDEX]); } else { desc.setValue(desc_array[VALUE_INDEX]); desc.setWritable(desc_array[WRITABLE_INDEX]); } desc.setEnumerable(desc_array[ENUMERABLE_INDEX]); desc.setConfigurable(desc_array[CONFIGURABLE_INDEX]); return desc; } // For Harmony proxies. function GetTrap(handler, name, defaultTrap) { var trap = handler[name]; if (IS_UNDEFINED(trap)) { if (IS_UNDEFINED(defaultTrap)) { throw MakeTypeError("handler_trap_missing", [handler, name]); } trap = defaultTrap; } else if (!IS_SPEC_FUNCTION(trap)) { throw MakeTypeError("handler_trap_must_be_callable", [handler, name]); } return trap; } function CallTrap0(handler, name, defaultTrap) { return %_CallFunction(handler, GetTrap(handler, name, defaultTrap)); } function CallTrap1(handler, name, defaultTrap, x) { return %_CallFunction(handler, x, GetTrap(handler, name, defaultTrap)); } function CallTrap2(handler, name, defaultTrap, x, y) { return %_CallFunction(handler, x, y, GetTrap(handler, name, defaultTrap)); } // ES5 section 8.12.1. function GetOwnPropertyJS(obj, v) { var p = ToName(v); if (%IsJSProxy(obj)) { // TODO(rossberg): adjust once there is a story for symbols vs proxies. if (IS_SYMBOL(v)) return UNDEFINED; var handler = %GetHandler(obj); var descriptor = CallTrap1( handler, "getOwnPropertyDescriptor", UNDEFINED, p); if (IS_UNDEFINED(descriptor)) return descriptor; var desc = ToCompletePropertyDescriptor(descriptor); if (!desc.isConfigurable()) { throw MakeTypeError("proxy_prop_not_configurable", [handler, "getOwnPropertyDescriptor", p, descriptor]); } return desc; } // GetOwnProperty returns an array indexed by the constants // defined in macros.py. // If p is not a property on obj undefined is returned. var props = %GetOwnProperty(ToObject(obj), p); // A false value here means that access checks failed. if (props === false) return UNDEFINED; return ConvertDescriptorArrayToDescriptor(props); } // ES5 section 8.12.7. function Delete(obj, p, should_throw) { var desc = GetOwnPropertyJS(obj, p); if (IS_UNDEFINED(desc)) return true; if (desc.isConfigurable()) { %DeleteProperty(obj, p, 0); return true; } else if (should_throw) { throw MakeTypeError("define_disallowed", [p]); } else { return; } } // Harmony proxies. function DefineProxyProperty(obj, p, attributes, should_throw) { // TODO(rossberg): adjust once there is a story for symbols vs proxies. if (IS_SYMBOL(p)) return false; var handler = %GetHandler(obj); var result = CallTrap2(handler, "defineProperty", UNDEFINED, p, attributes); if (!ToBoolean(result)) { if (should_throw) { throw MakeTypeError("handler_returned_false", [handler, "defineProperty"]); } else { return false; } } return true; } // ES5 8.12.9. function DefineObjectProperty(obj, p, desc, should_throw) { var current_or_access = %GetOwnProperty(ToObject(obj), ToName(p)); // A false value here means that access checks failed. if (current_or_access === false) return UNDEFINED; var current = ConvertDescriptorArrayToDescriptor(current_or_access); var extensible = %IsExtensible(ToObject(obj)); // Error handling according to spec. // Step 3 if (IS_UNDEFINED(current) && !extensible) { if (should_throw) { throw MakeTypeError("define_disallowed", [p]); } else { return false; } } if (!IS_UNDEFINED(current)) { // Step 5 and 6 if ((IsGenericDescriptor(desc) || IsDataDescriptor(desc) == IsDataDescriptor(current)) && (!desc.hasEnumerable() || SameValue(desc.isEnumerable(), current.isEnumerable())) && (!desc.hasConfigurable() || SameValue(desc.isConfigurable(), current.isConfigurable())) && (!desc.hasWritable() || SameValue(desc.isWritable(), current.isWritable())) && (!desc.hasValue() || SameValue(desc.getValue(), current.getValue())) && (!desc.hasGetter() || SameValue(desc.getGet(), current.getGet())) && (!desc.hasSetter() || SameValue(desc.getSet(), current.getSet()))) { return true; } if (!current.isConfigurable()) { // Step 7 if (desc.isConfigurable() || (desc.hasEnumerable() && desc.isEnumerable() != current.isEnumerable())) { if (should_throw) { throw MakeTypeError("redefine_disallowed", [p]); } else { return false; } } // Step 8 if (!IsGenericDescriptor(desc)) { // Step 9a if (IsDataDescriptor(current) != IsDataDescriptor(desc)) { if (should_throw) { throw MakeTypeError("redefine_disallowed", [p]); } else { return false; } } // Step 10a if (IsDataDescriptor(current) && IsDataDescriptor(desc)) { if (!current.isWritable() && desc.isWritable()) { if (should_throw) { throw MakeTypeError("redefine_disallowed", [p]); } else { return false; } } if (!current.isWritable() && desc.hasValue() && !SameValue(desc.getValue(), current.getValue())) { if (should_throw) { throw MakeTypeError("redefine_disallowed", [p]); } else { return false; } } } // Step 11 if (IsAccessorDescriptor(desc) && IsAccessorDescriptor(current)) { if (desc.hasSetter() && !SameValue(desc.getSet(), current.getSet())) { if (should_throw) { throw MakeTypeError("redefine_disallowed", [p]); } else { return false; } } if (desc.hasGetter() && !SameValue(desc.getGet(),current.getGet())) { if (should_throw) { throw MakeTypeError("redefine_disallowed", [p]); } else { return false; } } } } } } // Send flags - enumerable and configurable are common - writable is // only send to the data descriptor. // Take special care if enumerable and configurable is not defined on // desc (we need to preserve the existing values from current). var flag = NONE; if (desc.hasEnumerable()) { flag |= desc.isEnumerable() ? 0 : DONT_ENUM; } else if (!IS_UNDEFINED(current)) { flag |= current.isEnumerable() ? 0 : DONT_ENUM; } else { flag |= DONT_ENUM; } if (desc.hasConfigurable()) { flag |= desc.isConfigurable() ? 0 : DONT_DELETE; } else if (!IS_UNDEFINED(current)) { flag |= current.isConfigurable() ? 0 : DONT_DELETE; } else flag |= DONT_DELETE; if (IsDataDescriptor(desc) || (IsGenericDescriptor(desc) && (IS_UNDEFINED(current) || IsDataDescriptor(current)))) { // There are 3 cases that lead here: // Step 4a - defining a new data property. // Steps 9b & 12 - replacing an existing accessor property with a data // property. // Step 12 - updating an existing data property with a data or generic // descriptor. if (desc.hasWritable()) { flag |= desc.isWritable() ? 0 : READ_ONLY; } else if (!IS_UNDEFINED(current)) { flag |= current.isWritable() ? 0 : READ_ONLY; } else { flag |= READ_ONLY; } var value = UNDEFINED; // Default value is undefined. if (desc.hasValue()) { value = desc.getValue(); } else if (!IS_UNDEFINED(current) && IsDataDescriptor(current)) { value = current.getValue(); } %DefineDataPropertyUnchecked(obj, p, value, flag); } else { // There are 3 cases that lead here: // Step 4b - defining a new accessor property. // Steps 9c & 12 - replacing an existing data property with an accessor // property. // Step 12 - updating an existing accessor property with an accessor // descriptor. var getter = desc.hasGetter() ? desc.getGet() : null; var setter = desc.hasSetter() ? desc.getSet() : null; %DefineAccessorPropertyUnchecked(obj, p, getter, setter, flag); } return true; } // ES5 section 15.4.5.1. function DefineArrayProperty(obj, p, desc, should_throw) { // Note that the length of an array is not actually stored as part of the // property, hence we use generated code throughout this function instead of // DefineObjectProperty() to modify its value. // Step 3 - Special handling for length property. if (p === "length") { var length = obj.length; var old_length = length; if (!desc.hasValue()) { return DefineObjectProperty(obj, "length", desc, should_throw); } var new_length = ToUint32(desc.getValue()); if (new_length != ToNumber(desc.getValue())) { throw new $RangeError('defineProperty() array length out of range'); } var length_desc = GetOwnPropertyJS(obj, "length"); if (new_length != length && !length_desc.isWritable()) { if (should_throw) { throw MakeTypeError("redefine_disallowed", [p]); } else { return false; } } var threw = false; var emit_splice = %IsObserved(obj) && new_length !== old_length; var removed; if (emit_splice) { BeginPerformSplice(obj); removed = []; if (new_length < old_length) removed.length = old_length - new_length; } while (new_length < length--) { var index = ToString(length); if (emit_splice) { var deletedDesc = GetOwnPropertyJS(obj, index); if (deletedDesc && deletedDesc.hasValue()) removed[length - new_length] = deletedDesc.getValue(); } if (!Delete(obj, index, false)) { new_length = length + 1; threw = true; break; } } // Make sure the below call to DefineObjectProperty() doesn't overwrite // any magic "length" property by removing the value. // TODO(mstarzinger): This hack should be removed once we have addressed the // respective TODO in Runtime_DefineDataPropertyUnchecked. // For the time being, we need a hack to prevent Object.observe from // generating two change records. obj.length = new_length; desc.value_ = UNDEFINED; desc.hasValue_ = false; threw = !DefineObjectProperty(obj, "length", desc, should_throw) || threw; if (emit_splice) { EndPerformSplice(obj); EnqueueSpliceRecord(obj, new_length < old_length ? new_length : old_length, removed, new_length > old_length ? new_length - old_length : 0); } if (threw) { if (should_throw) { throw MakeTypeError("redefine_disallowed", [p]); } else { return false; } } return true; } // Step 4 - Special handling for array index. if (!IS_SYMBOL(p)) { var index = ToUint32(p); var emit_splice = false; if (ToString(index) == p && index != 4294967295) { var length = obj.length; if (index >= length && %IsObserved(obj)) { emit_splice = true; BeginPerformSplice(obj); } var length_desc = GetOwnPropertyJS(obj, "length"); if ((index >= length && !length_desc.isWritable()) || !DefineObjectProperty(obj, p, desc, true)) { if (emit_splice) EndPerformSplice(obj); if (should_throw) { throw MakeTypeError("define_disallowed", [p]); } else { return false; } } if (index >= length) { obj.length = index + 1; } if (emit_splice) { EndPerformSplice(obj); EnqueueSpliceRecord(obj, length, [], index + 1 - length); } return true; } } // Step 5 - Fallback to default implementation. return DefineObjectProperty(obj, p, desc, should_throw); } // ES5 section 8.12.9, ES5 section 15.4.5.1 and Harmony proxies. function DefineOwnProperty(obj, p, desc, should_throw) { if (%IsJSProxy(obj)) { // TODO(rossberg): adjust once there is a story for symbols vs proxies. if (IS_SYMBOL(p)) return false; var attributes = FromGenericPropertyDescriptor(desc); return DefineProxyProperty(obj, p, attributes, should_throw); } else if (IS_ARRAY(obj)) { return DefineArrayProperty(obj, p, desc, should_throw); } else { return DefineObjectProperty(obj, p, desc, should_throw); } } // ES5 section 15.2.3.2. function ObjectGetPrototypeOf(obj) { if (!IS_SPEC_OBJECT(obj)) { throw MakeTypeError("called_on_non_object", ["Object.getPrototypeOf"]); } return %GetPrototype(obj); } // ES6 section 19.1.2.19. function ObjectSetPrototypeOf(obj, proto) { CHECK_OBJECT_COERCIBLE(obj, "Object.setPrototypeOf"); if (proto !== null && !IS_SPEC_OBJECT(proto)) { throw MakeTypeError("proto_object_or_null", [proto]); } if (IS_SPEC_OBJECT(obj)) { %SetPrototype(obj, proto); } return obj; } // ES5 section 15.2.3.3 function ObjectGetOwnPropertyDescriptor(obj, p) { if (!IS_SPEC_OBJECT(obj)) { throw MakeTypeError("called_on_non_object", ["Object.getOwnPropertyDescriptor"]); } var desc = GetOwnPropertyJS(obj, p); return FromPropertyDescriptor(desc); } // For Harmony proxies function ToNameArray(obj, trap, includeSymbols) { if (!IS_SPEC_OBJECT(obj)) { throw MakeTypeError("proxy_non_object_prop_names", [obj, trap]); } var n = ToUint32(obj.length); var array = new $Array(n); var realLength = 0; var names = { __proto__: null }; // TODO(rossberg): use sets once ready. for (var index = 0; index < n; index++) { var s = ToName(obj[index]); // TODO(rossberg): adjust once there is a story for symbols vs proxies. if (IS_SYMBOL(s) && !includeSymbols) continue; if (%HasOwnProperty(names, s)) { throw MakeTypeError("proxy_repeated_prop_name", [obj, trap, s]); } array[index] = s; ++realLength; names[s] = 0; } array.length = realLength; return array; } function ObjectGetOwnPropertyKeys(obj, symbolsOnly) { var nameArrays = new InternalArray(); var filter = symbolsOnly ? PROPERTY_ATTRIBUTES_STRING | PROPERTY_ATTRIBUTES_PRIVATE_SYMBOL : PROPERTY_ATTRIBUTES_SYMBOLIC; // Find all the indexed properties. // Only get own element names if we want to include string keys. if (!symbolsOnly) { var ownElementNames = %GetOwnElementNames(obj); for (var i = 0; i < ownElementNames.length; ++i) { ownElementNames[i] = %_NumberToString(ownElementNames[i]); } nameArrays.push(ownElementNames); // Get names for indexed interceptor properties. var interceptorInfo = %GetInterceptorInfo(obj); if ((interceptorInfo & 1) != 0) { var indexedInterceptorNames = %GetIndexedInterceptorElementNames(obj); if (!IS_UNDEFINED(indexedInterceptorNames)) { nameArrays.push(indexedInterceptorNames); } } } // Find all the named properties. // Get own property names. nameArrays.push(%GetOwnPropertyNames(obj, filter)); // Get names for named interceptor properties if any. if ((interceptorInfo & 2) != 0) { var namedInterceptorNames = %GetNamedInterceptorPropertyNames(obj); if (!IS_UNDEFINED(namedInterceptorNames)) { nameArrays.push(namedInterceptorNames); } } var propertyNames = %Apply(InternalArray.prototype.concat, nameArrays[0], nameArrays, 1, nameArrays.length - 1); // Property names are expected to be unique strings, // but interceptors can interfere with that assumption. if (interceptorInfo != 0) { var seenKeys = { __proto__: null }; var j = 0; for (var i = 0; i < propertyNames.length; ++i) { var name = propertyNames[i]; if (symbolsOnly) { if (!IS_SYMBOL(name) || IS_PRIVATE(name)) continue; } else { if (IS_SYMBOL(name)) continue; name = ToString(name); } if (seenKeys[name]) continue; seenKeys[name] = true; propertyNames[j++] = name; } propertyNames.length = j; } return propertyNames; } // ES5 section 15.2.3.4. function ObjectGetOwnPropertyNames(obj) { if (!IS_SPEC_OBJECT(obj)) { throw MakeTypeError("called_on_non_object", ["Object.getOwnPropertyNames"]); } // Special handling for proxies. if (%IsJSProxy(obj)) { var handler = %GetHandler(obj); var names = CallTrap0(handler, "getOwnPropertyNames", UNDEFINED); return ToNameArray(names, "getOwnPropertyNames", false); } return ObjectGetOwnPropertyKeys(obj, false); } // ES5 section 15.2.3.5. function ObjectCreate(proto, properties) { if (!IS_SPEC_OBJECT(proto) && proto !== null) { throw MakeTypeError("proto_object_or_null", [proto]); } var obj = {}; %InternalSetPrototype(obj, proto); if (!IS_UNDEFINED(properties)) ObjectDefineProperties(obj, properties); return obj; } // ES5 section 15.2.3.6. function ObjectDefineProperty(obj, p, attributes) { if (!IS_SPEC_OBJECT(obj)) { throw MakeTypeError("called_on_non_object", ["Object.defineProperty"]); } var name = ToName(p); if (%IsJSProxy(obj)) { // Clone the attributes object for protection. // TODO(rossberg): not spec'ed yet, so not sure if this should involve // non-own properties as it does (or non-enumerable ones, as it doesn't?). var attributesClone = { __proto__: null }; for (var a in attributes) { attributesClone[a] = attributes[a]; } DefineProxyProperty(obj, name, attributesClone, true); // The following would implement the spec as in the current proposal, // but after recent comments on es-discuss, is most likely obsolete. /* var defineObj = FromGenericPropertyDescriptor(desc); var names = ObjectGetOwnPropertyNames(attributes); var standardNames = {value: 0, writable: 0, get: 0, set: 0, enumerable: 0, configurable: 0}; for (var i = 0; i < names.length; i++) { var N = names[i]; if (!(%HasOwnProperty(standardNames, N))) { var attr = GetOwnPropertyJS(attributes, N); DefineOwnProperty(descObj, N, attr, true); } } // This is really confusing the types, but it is what the proxies spec // currently requires: desc = descObj; */ } else { var desc = ToPropertyDescriptor(attributes); DefineOwnProperty(obj, name, desc, true); } return obj; } function GetOwnEnumerablePropertyNames(object) { var names = new InternalArray(); for (var key in object) { if (%HasOwnProperty(object, key)) { names.push(key); } } var filter = PROPERTY_ATTRIBUTES_STRING | PROPERTY_ATTRIBUTES_PRIVATE_SYMBOL; var symbols = %GetOwnPropertyNames(object, filter); for (var i = 0; i < symbols.length; ++i) { var symbol = symbols[i]; if (IS_SYMBOL(symbol)) { var desc = ObjectGetOwnPropertyDescriptor(object, symbol); if (desc.enumerable) names.push(symbol); } } return names; } // ES5 section 15.2.3.7. function ObjectDefineProperties(obj, properties) { if (!IS_SPEC_OBJECT(obj)) { throw MakeTypeError("called_on_non_object", ["Object.defineProperties"]); } var props = ToObject(properties); var names = GetOwnEnumerablePropertyNames(props); var descriptors = new InternalArray(); for (var i = 0; i < names.length; i++) { descriptors.push(ToPropertyDescriptor(props[names[i]])); } for (var i = 0; i < names.length; i++) { DefineOwnProperty(obj, names[i], descriptors[i], true); } return obj; } // Harmony proxies. function ProxyFix(obj) { var handler = %GetHandler(obj); var props = CallTrap0(handler, "fix", UNDEFINED); if (IS_UNDEFINED(props)) { throw MakeTypeError("handler_returned_undefined", [handler, "fix"]); } if (%IsJSFunctionProxy(obj)) { var callTrap = %GetCallTrap(obj); var constructTrap = %GetConstructTrap(obj); var code = DelegateCallAndConstruct(callTrap, constructTrap); %Fix(obj); // becomes a regular function %SetCode(obj, code); // TODO(rossberg): What about length and other properties? Not specified. // We just put in some half-reasonable defaults for now. var prototype = new $Object(); $Object.defineProperty(prototype, "constructor", {value: obj, writable: true, enumerable: false, configurable: true}); // TODO(v8:1530): defineProperty does not handle prototype and length. %FunctionSetPrototype(obj, prototype); obj.length = 0; } else { %Fix(obj); } ObjectDefineProperties(obj, props); } // ES5 section 15.2.3.8. function ObjectSeal(obj) { if (!IS_SPEC_OBJECT(obj)) { throw MakeTypeError("called_on_non_object", ["Object.seal"]); } if (%IsJSProxy(obj)) { ProxyFix(obj); } var names = ObjectGetOwnPropertyNames(obj); for (var i = 0; i < names.length; i++) { var name = names[i]; var desc = GetOwnPropertyJS(obj, name); if (desc.isConfigurable()) { desc.setConfigurable(false); DefineOwnProperty(obj, name, desc, true); } } %PreventExtensions(obj); return obj; } // ES5 section 15.2.3.9. function ObjectFreezeJS(obj) { if (!IS_SPEC_OBJECT(obj)) { throw MakeTypeError("called_on_non_object", ["Object.freeze"]); } var isProxy = %IsJSProxy(obj); if (isProxy || %HasSloppyArgumentsElements(obj) || %IsObserved(obj)) { if (isProxy) { ProxyFix(obj); } var names = ObjectGetOwnPropertyNames(obj); for (var i = 0; i < names.length; i++) { var name = names[i]; var desc = GetOwnPropertyJS(obj, name); if (desc.isWritable() || desc.isConfigurable()) { if (IsDataDescriptor(desc)) desc.setWritable(false); desc.setConfigurable(false); DefineOwnProperty(obj, name, desc, true); } } %PreventExtensions(obj); } else { // TODO(adamk): Is it worth going to this fast path if the // object's properties are already in dictionary mode? %ObjectFreeze(obj); } return obj; } // ES5 section 15.2.3.10 function ObjectPreventExtension(obj) { if (!IS_SPEC_OBJECT(obj)) { throw MakeTypeError("called_on_non_object", ["Object.preventExtension"]); } if (%IsJSProxy(obj)) { ProxyFix(obj); } %PreventExtensions(obj); return obj; } // ES5 section 15.2.3.11 function ObjectIsSealed(obj) { if (!IS_SPEC_OBJECT(obj)) { throw MakeTypeError("called_on_non_object", ["Object.isSealed"]); } if (%IsJSProxy(obj)) { return false; } if (%IsExtensible(obj)) { return false; } var names = ObjectGetOwnPropertyNames(obj); for (var i = 0; i < names.length; i++) { var name = names[i]; var desc = GetOwnPropertyJS(obj, name); if (desc.isConfigurable()) { return false; } } return true; } // ES5 section 15.2.3.12 function ObjectIsFrozen(obj) { if (!IS_SPEC_OBJECT(obj)) { throw MakeTypeError("called_on_non_object", ["Object.isFrozen"]); } if (%IsJSProxy(obj)) { return false; } if (%IsExtensible(obj)) { return false; } var names = ObjectGetOwnPropertyNames(obj); for (var i = 0; i < names.length; i++) { var name = names[i]; var desc = GetOwnPropertyJS(obj, name); if (IsDataDescriptor(desc) && desc.isWritable()) return false; if (desc.isConfigurable()) return false; } return true; } // ES5 section 15.2.3.13 function ObjectIsExtensible(obj) { if (!IS_SPEC_OBJECT(obj)) { throw MakeTypeError("called_on_non_object", ["Object.isExtensible"]); } if (%IsJSProxy(obj)) { return true; } return %IsExtensible(obj); } // Harmony egal. function ObjectIs(obj1, obj2) { if (obj1 === obj2) { return (obj1 !== 0) || (1 / obj1 === 1 / obj2); } else { return (obj1 !== obj1) && (obj2 !== obj2); } } // ECMA-262, Edition 6, section B.2.2.1.1 function ObjectGetProto() { return %GetPrototype(ToObject(this)); } // ECMA-262, Edition 6, section B.2.2.1.2 function ObjectSetProto(proto) { CHECK_OBJECT_COERCIBLE(this, "Object.prototype.__proto__"); if ((IS_SPEC_OBJECT(proto) || IS_NULL(proto)) && IS_SPEC_OBJECT(this)) { %SetPrototype(this, proto); } } function ObjectConstructor(x) { if (%_IsConstructCall()) { if (x == null) return this; return ToObject(x); } else { if (x == null) return { }; return ToObject(x); } } // ---------------------------------------------------------------------------- // Object function SetUpObject() { %CheckIsBootstrapping(); %SetNativeFlag($Object); %SetCode($Object, ObjectConstructor); %AddNamedProperty($Object.prototype, "constructor", $Object, DONT_ENUM); // Set up non-enumerable functions on the Object.prototype object. InstallFunctions($Object.prototype, DONT_ENUM, $Array( "toString", ObjectToString, "toLocaleString", ObjectToLocaleString, "valueOf", ObjectValueOf, "hasOwnProperty", ObjectHasOwnProperty, "isPrototypeOf", ObjectIsPrototypeOf, "propertyIsEnumerable", ObjectPropertyIsEnumerable, "__defineGetter__", ObjectDefineGetter, "__lookupGetter__", ObjectLookupGetter, "__defineSetter__", ObjectDefineSetter, "__lookupSetter__", ObjectLookupSetter )); InstallGetterSetter($Object.prototype, "__proto__", ObjectGetProto, ObjectSetProto); // Set up non-enumerable functions in the Object object. InstallFunctions($Object, DONT_ENUM, $Array( "keys", ObjectKeys, "create", ObjectCreate, "defineProperty", ObjectDefineProperty, "defineProperties", ObjectDefineProperties, "freeze", ObjectFreezeJS, "getPrototypeOf", ObjectGetPrototypeOf, "setPrototypeOf", ObjectSetPrototypeOf, "getOwnPropertyDescriptor", ObjectGetOwnPropertyDescriptor, "getOwnPropertyNames", ObjectGetOwnPropertyNames, // getOwnPropertySymbols is added in symbol.js. "is", ObjectIs, "isExtensible", ObjectIsExtensible, "isFrozen", ObjectIsFrozen, "isSealed", ObjectIsSealed, "preventExtensions", ObjectPreventExtension, "seal", ObjectSeal // deliverChangeRecords, getNotifier, observe and unobserve are added // in object-observe.js. )); } SetUpObject(); // ---------------------------------------------------------------------------- // Boolean function BooleanConstructor(x) { if (%_IsConstructCall()) { %_SetValueOf(this, ToBoolean(x)); } else { return ToBoolean(x); } } function BooleanToString() { // NOTE: Both Boolean objects and values can enter here as // 'this'. This is not as dictated by ECMA-262. var b = this; if (!IS_BOOLEAN(b)) { if (!IS_BOOLEAN_WRAPPER(b)) { throw new $TypeError('Boolean.prototype.toString is not generic'); } b = %_ValueOf(b); } return b ? 'true' : 'false'; } function BooleanValueOf() { // NOTE: Both Boolean objects and values can enter here as // 'this'. This is not as dictated by ECMA-262. if (!IS_BOOLEAN(this) && !IS_BOOLEAN_WRAPPER(this)) { throw new $TypeError('Boolean.prototype.valueOf is not generic'); } return %_ValueOf(this); } // ---------------------------------------------------------------------------- function SetUpBoolean () { %CheckIsBootstrapping(); %SetCode($Boolean, BooleanConstructor); %FunctionSetPrototype($Boolean, new $Boolean(false)); %AddNamedProperty($Boolean.prototype, "constructor", $Boolean, DONT_ENUM); InstallFunctions($Boolean.prototype, DONT_ENUM, $Array( "toString", BooleanToString, "valueOf", BooleanValueOf )); } SetUpBoolean(); // ---------------------------------------------------------------------------- // Number function NumberConstructor(x) { var value = %_ArgumentsLength() == 0 ? 0 : ToNumber(x); if (%_IsConstructCall()) { %_SetValueOf(this, value); } else { return value; } } // ECMA-262 section 15.7.4.2. function NumberToString(radix) { // NOTE: Both Number objects and values can enter here as // 'this'. This is not as dictated by ECMA-262. var number = this; if (!IS_NUMBER(this)) { if (!IS_NUMBER_WRAPPER(this)) { throw new $TypeError('Number.prototype.toString is not generic'); } // Get the value of this number in case it's an object. number = %_ValueOf(this); } // Fast case: Convert number in radix 10. if (IS_UNDEFINED(radix) || radix === 10) { return %_NumberToString(number); } // Convert the radix to an integer and check the range. radix = TO_INTEGER(radix); if (radix < 2 || radix > 36) { throw new $RangeError('toString() radix argument must be between 2 and 36'); } // Convert the number to a string in the given radix. return %NumberToRadixString(number, radix); } // ECMA-262 section 15.7.4.3 function NumberToLocaleString() { return %_CallFunction(this, NumberToString); } // ECMA-262 section 15.7.4.4 function NumberValueOf() { // NOTE: Both Number objects and values can enter here as // 'this'. This is not as dictated by ECMA-262. if (!IS_NUMBER(this) && !IS_NUMBER_WRAPPER(this)) { throw new $TypeError('Number.prototype.valueOf is not generic'); } return %_ValueOf(this); } // ECMA-262 section 15.7.4.5 function NumberToFixedJS(fractionDigits) { var x = this; if (!IS_NUMBER(this)) { if (!IS_NUMBER_WRAPPER(this)) { throw MakeTypeError("incompatible_method_receiver", ["Number.prototype.toFixed", this]); } // Get the value of this number in case it's an object. x = %_ValueOf(this); } var f = TO_INTEGER(fractionDigits); if (f < 0 || f > 20) { throw new $RangeError("toFixed() digits argument must be between 0 and 20"); } if (NUMBER_IS_NAN(x)) return "NaN"; if (x == INFINITY) return "Infinity"; if (x == -INFINITY) return "-Infinity"; return %NumberToFixed(x, f); } // ECMA-262 section 15.7.4.6 function NumberToExponentialJS(fractionDigits) { var x = this; if (!IS_NUMBER(this)) { if (!IS_NUMBER_WRAPPER(this)) { throw MakeTypeError("incompatible_method_receiver", ["Number.prototype.toExponential", this]); } // Get the value of this number in case it's an object. x = %_ValueOf(this); } var f = IS_UNDEFINED(fractionDigits) ? UNDEFINED : TO_INTEGER(fractionDigits); if (NUMBER_IS_NAN(x)) return "NaN"; if (x == INFINITY) return "Infinity"; if (x == -INFINITY) return "-Infinity"; if (IS_UNDEFINED(f)) { f = -1; // Signal for runtime function that f is not defined. } else if (f < 0 || f > 20) { throw new $RangeError("toExponential() argument must be between 0 and 20"); } return %NumberToExponential(x, f); } // ECMA-262 section 15.7.4.7 function NumberToPrecisionJS(precision) { var x = this; if (!IS_NUMBER(this)) { if (!IS_NUMBER_WRAPPER(this)) { throw MakeTypeError("incompatible_method_receiver", ["Number.prototype.toPrecision", this]); } // Get the value of this number in case it's an object. x = %_ValueOf(this); } if (IS_UNDEFINED(precision)) return ToString(%_ValueOf(this)); var p = TO_INTEGER(precision); if (NUMBER_IS_NAN(x)) return "NaN"; if (x == INFINITY) return "Infinity"; if (x == -INFINITY) return "-Infinity"; if (p < 1 || p > 21) { throw new $RangeError("toPrecision() argument must be between 1 and 21"); } return %NumberToPrecision(x, p); } // Harmony isFinite. function NumberIsFinite(number) { return IS_NUMBER(number) && NUMBER_IS_FINITE(number); } // Harmony isInteger function NumberIsInteger(number) { return NumberIsFinite(number) && TO_INTEGER(number) == number; } // Harmony isNaN. function NumberIsNaN(number) { return IS_NUMBER(number) && NUMBER_IS_NAN(number); } // Harmony isSafeInteger function NumberIsSafeInteger(number) { if (NumberIsFinite(number)) { var integral = TO_INTEGER(number); if (integral == number) return MathAbs(integral) <= $Number.MAX_SAFE_INTEGER; } return false; } // ---------------------------------------------------------------------------- function SetUpNumber() { %CheckIsBootstrapping(); %SetCode($Number, NumberConstructor); %FunctionSetPrototype($Number, new $Number(0)); %OptimizeObjectForAddingMultipleProperties($Number.prototype, 8); // Set up the constructor property on the Number prototype object. %AddNamedProperty($Number.prototype, "constructor", $Number, DONT_ENUM); InstallConstants($Number, $Array( // ECMA-262 section 15.7.3.1. "MAX_VALUE", 1.7976931348623157e+308, // ECMA-262 section 15.7.3.2. "MIN_VALUE", 5e-324, // ECMA-262 section 15.7.3.3. "NaN", NAN, // ECMA-262 section 15.7.3.4. "NEGATIVE_INFINITY", -INFINITY, // ECMA-262 section 15.7.3.5. "POSITIVE_INFINITY", INFINITY, // --- Harmony constants (no spec refs until settled.) "MAX_SAFE_INTEGER", %_MathPow(2, 53) - 1, "MIN_SAFE_INTEGER", -%_MathPow(2, 53) + 1, "EPSILON", %_MathPow(2, -52) )); // Set up non-enumerable functions on the Number prototype object. InstallFunctions($Number.prototype, DONT_ENUM, $Array( "toString", NumberToString, "toLocaleString", NumberToLocaleString, "valueOf", NumberValueOf, "toFixed", NumberToFixedJS, "toExponential", NumberToExponentialJS, "toPrecision", NumberToPrecisionJS )); // Harmony Number constructor additions InstallFunctions($Number, DONT_ENUM, $Array( "isFinite", NumberIsFinite, "isInteger", NumberIsInteger, "isNaN", NumberIsNaN, "isSafeInteger", NumberIsSafeInteger, "parseInt", GlobalParseInt, "parseFloat", GlobalParseFloat )); } SetUpNumber(); // ---------------------------------------------------------------------------- // Function function FunctionSourceString(func) { while (%IsJSFunctionProxy(func)) { func = %GetCallTrap(func); } if (!IS_FUNCTION(func)) { throw new $TypeError('Function.prototype.toString is not generic'); } var source = %FunctionGetSourceCode(func); if (!IS_STRING(source) || %FunctionIsBuiltin(func)) { var name = %FunctionGetName(func); if (name) { // Mimic what KJS does. return 'function ' + name + '() { [native code] }'; } else { return 'function () { [native code] }'; } } if (%FunctionIsArrow(func)) { return source; } var name = %FunctionNameShouldPrintAsAnonymous(func) ? 'anonymous' : %FunctionGetName(func); var head = %FunctionIsGenerator(func) ? 'function* ' : 'function '; return head + name + source; } function FunctionToString() { return FunctionSourceString(this); } // ES5 15.3.4.5 function FunctionBind(this_arg) { // Length is 1. if (!IS_SPEC_FUNCTION(this)) { throw new $TypeError('Bind must be called on a function'); } var boundFunction = function () { // Poison .arguments and .caller, but is otherwise not detectable. "use strict"; // This function must not use any object literals (Object, Array, RegExp), // since the literals-array is being used to store the bound data. if (%_IsConstructCall()) { return %NewObjectFromBound(boundFunction); } var bindings = %BoundFunctionGetBindings(boundFunction); var argc = %_ArgumentsLength(); if (argc == 0) { return %Apply(bindings[0], bindings[1], bindings, 2, bindings.length - 2); } if (bindings.length === 2) { return %Apply(bindings[0], bindings[1], arguments, 0, argc); } var bound_argc = bindings.length - 2; var argv = new InternalArray(bound_argc + argc); for (var i = 0; i < bound_argc; i++) { argv[i] = bindings[i + 2]; } for (var j = 0; j < argc; j++) { argv[i++] = %_Arguments(j); } return %Apply(bindings[0], bindings[1], argv, 0, bound_argc + argc); }; var new_length = 0; var old_length = this.length; // FunctionProxies might provide a non-UInt32 value. If so, ignore it. if ((typeof old_length === "number") && ((old_length >>> 0) === old_length)) { var argc = %_ArgumentsLength(); if (argc > 0) argc--; // Don't count the thisArg as parameter. new_length = old_length - argc; if (new_length < 0) new_length = 0; } // This runtime function finds any remaining arguments on the stack, // so we don't pass the arguments object. var result = %FunctionBindArguments(boundFunction, this, this_arg, new_length); // We already have caller and arguments properties on functions, // which are non-configurable. It therefore makes no sence to // try to redefine these as defined by the spec. The spec says // that bind should make these throw a TypeError if get or set // is called and make them non-enumerable and non-configurable. // To be consistent with our normal functions we leave this as it is. // TODO(lrn): Do set these to be thrower. return result; } function NewFunctionString(arguments, function_token) { var n = arguments.length; var p = ''; if (n > 1) { p = ToString(arguments[0]); for (var i = 1; i < n - 1; i++) { p += ',' + ToString(arguments[i]); } // If the formal parameters string include ) - an illegal // character - it may make the combined function expression // compile. We avoid this problem by checking for this early on. if (%_CallFunction(p, ')', StringIndexOfJS) != -1) { throw MakeSyntaxError('paren_in_arg_string', []); } // If the formal parameters include an unbalanced block comment, the // function must be rejected. Since JavaScript does not allow nested // comments we can include a trailing block comment to catch this. p += '\n/' + '**/'; } var body = (n > 0) ? ToString(arguments[n - 1]) : ''; return '(' + function_token + '(' + p + ') {\n' + body + '\n})'; } function FunctionConstructor(arg1) { // length == 1 var source = NewFunctionString(arguments, 'function'); var global_proxy = %GlobalProxy(global); // Compile the string in the constructor and not a helper so that errors // appear to come from here. var f = %_CallFunction(global_proxy, %CompileString(source, true)); %FunctionMarkNameShouldPrintAsAnonymous(f); return f; } // ---------------------------------------------------------------------------- function SetUpFunction() { %CheckIsBootstrapping(); %SetCode($Function, FunctionConstructor); %AddNamedProperty($Function.prototype, "constructor", $Function, DONT_ENUM); InstallFunctions($Function.prototype, DONT_ENUM, $Array( "bind", FunctionBind, "toString", FunctionToString )); } SetUpFunction(); // ---------------------------------------------------------------------------- // Iterator related spec functions. // ES6 rev 26, 2014-07-18 // 7.4.1 CheckIterable ( obj ) function ToIterable(obj) { if (!IS_SPEC_OBJECT(obj)) { return UNDEFINED; } return obj[symbolIterator]; } // ES6 rev 26, 2014-07-18 // 7.4.2 GetIterator ( obj, method ) function GetIterator(obj, method) { if (IS_UNDEFINED(method)) { method = ToIterable(obj); } if (!IS_SPEC_FUNCTION(method)) { throw MakeTypeError('not_iterable', [obj]); } var iterator = %_CallFunction(obj, method); if (!IS_SPEC_OBJECT(iterator)) { throw MakeTypeError('not_an_iterator', [iterator]); } return iterator; }
const fs = require('fs-extra'); const path = require('path'); const cleanDirs = [ 'dist' ]; cleanDirs.forEach(dir => { const cleanDir = path.join(__dirname, '../', dir); fs.removeSync(cleanDir); });
'use strict'; var fs = require('fs'); var Promise = require('../ext/promise'); var readFile = Promise.denodeify(fs.readFile); var lstat = Promise.denodeify(fs.stat); var chalk = require('chalk'); var EditFileDiff = require('./edit-file-diff'); var EOL = require('os').EOL; var isBinaryFile = require('isbinaryfile').sync; var template = require('lodash/template'); var canEdit = require('../utilities/open-editor').canEdit; function processTemplate(content, context) { var options = { evaluate: /<%([\s\S]+?)%>/g, interpolate: /<%=([\s\S]+?)%>/g, escape: /<%-([\s\S]+?)%>/g }; return template(content, options)(context); } function diffHighlight(line) { if (line[0] === '+') { return chalk.green(line); } else if (line[0] === '-') { return chalk.red(line); } else if (line.match(/^@@/)) { return chalk.cyan(line); } else { return line; } } FileInfo.prototype.confirmOverwrite = function(path) { var promptOptions = { type: 'expand', name: 'answer', default: false, message: chalk.red('Overwrite') + ' ' + path + '?', choices: [ { key: 'y', name: 'Yes, overwrite', value: 'overwrite' }, { key: 'n', name: 'No, skip', value: 'skip' }, { key: 'd', name: 'Diff', value: 'diff' } ] }; if (canEdit()) { promptOptions.choices.push({ key: 'e', name: 'Edit', value: 'edit' }); } return this.ui.prompt(promptOptions) .then(function(response) { return response.answer; }); }; FileInfo.prototype.displayDiff = function() { var info = this, jsdiff = require('diff'); return Promise.hash({ input: this.render(), output: readFile(info.outputPath) }).then(function(result) { var diff = jsdiff.createPatch( info.outputPath, result.output.toString(), result.input ); var lines = diff.split('\n'); for (var i = 0; i < lines.length; i++) { info.ui.write( diffHighlight(lines[i] + EOL) ); } }); }; function FileInfo(options) { this.action = options.action; this.outputPath = options.outputPath; this.displayPath = options.displayPath; this.inputPath = options.inputPath; this.templateVariables = options.templateVariables; this.ui = options.ui; } FileInfo.prototype.render = function() { var path = this.inputPath, context = this.templateVariables; if (!this.rendered) { this.rendered = readFile(path).then(function(content) { return lstat(path).then(function(fileStat) { if (isBinaryFile(content, fileStat.size)) { return content; } else { try { return processTemplate(content.toString(), context); } catch (err) { err.message += ' (Error in blueprint template: ' + path + ')'; throw err; } } }); }); } return this.rendered; }; FileInfo.prototype.checkForConflict = function() { return new Promise(function (resolve, reject) { fs.exists(this.outputPath, function (doesExist, error) { if (error) { reject(error); return; } var result; if (doesExist) { result = Promise.hash({ input: this.render(), output: readFile(this.outputPath) }).then(function(result) { var type; if (result.input === result.output.toString()) { type = 'identical'; } else { type = 'confirm'; } return type; }.bind(this)); } else { result = 'none'; } resolve(result); }.bind(this)); }.bind(this)); }; FileInfo.prototype.confirmOverwriteTask = function() { var info = this; return function() { return new Promise(function(resolve, reject) { function doConfirm() { info.confirmOverwrite(info.displayPath).then(function(action) { if (action === 'diff') { info.displayDiff().then(doConfirm, reject); } else if (action === 'edit') { var editFileDiff = new EditFileDiff({info: info}); editFileDiff.edit().then(function() { info.action = action; resolve(info); }).catch(function() { doConfirm() .finally(function() { resolve(info); }); }); } else { info.action = action; resolve(info); } }, reject); } doConfirm(); }); }.bind(this); }; module.exports = FileInfo;
var everything = function () { return 42; }; anything.prototype.everything = everything;
/* * /MathJax/jax/output/HTML-CSS/fonts/STIX/IntegralsUpSm/Regular/All.js * * Copyright (c) 2009-2016 The MathJax Consortium * * 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. */ MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS.STIXIntegralsUpSm,{32:[0,0,250,0,0],160:[0,0,250,0,0],8748:[690,189,587,52,605],8749:[690,189,817,52,835],8751:[690,189,682,52,642],8752:[690,189,909,52,869],8753:[690,189,480,52,447],8754:[690,189,480,52,448],8755:[690,189,480,52,470],10763:[694,190,556,41,515],10764:[694,190,1044,68,1081],10765:[694,190,420,68,391],10766:[694,190,420,68,391],10767:[694,190,520,39,482],10768:[694,190,324,41,380],10769:[694,190,480,52,447],10770:[694,190,450,68,410],10771:[690,189,450,68,412],10772:[690,189,550,68,512],10773:[690,189,450,50,410],10774:[694,191,450,50,410],10775:[694,190,611,12,585],10776:[694,190,450,48,412],10777:[694,190,450,59,403],10778:[694,190,450,59,403],10779:[784,189,379,68,416],10780:[690,283,357,52,400]});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/IntegralsUpSm/Regular/All.js");
/************************************************************* * * MathJax/jax/output/HTML-CSS/fonts/STIX/General/BoldItalic/BoxDrawing.js * * Copyright (c) 2009-2016 The MathJax Consortium * * 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. * */ MathJax.Hub.Insert( MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['STIXGeneral-bold-italic'], { 0x2500: [340,-267,708,-11,719], // BOX DRAWINGS LIGHT HORIZONTAL 0x2502: [910,303,696,312,385], // BOX DRAWINGS LIGHT VERTICAL 0x250C: [340,303,708,318,720], // BOX DRAWINGS LIGHT DOWN AND RIGHT 0x2510: [340,303,708,-11,390], // BOX DRAWINGS LIGHT DOWN AND LEFT 0x2514: [910,-267,708,318,720], // BOX DRAWINGS LIGHT UP AND RIGHT 0x2518: [910,-267,708,-11,390], // BOX DRAWINGS LIGHT UP AND LEFT 0x251C: [910,303,708,318,720], // BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x2524: [910,303,708,-11,390], // BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x252C: [340,303,708,-11,719], // BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x2534: [910,-267,708,-11,719], // BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x253C: [910,303,708,-11,719], // BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x2550: [433,-174,708,-11,719], // BOX DRAWINGS DOUBLE HORIZONTAL 0x2551: [910,303,708,225,484], // BOX DRAWINGS DOUBLE VERTICAL 0x2552: [433,303,708,318,720], // BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE 0x2553: [340,303,708,225,720], // BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE 0x2554: [433,303,708,225,719], // BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x2555: [433,303,708,-11,390], // BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE 0x2556: [340,303,708,-11,483], // BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE 0x2557: [433,303,708,-11,483], // BOX DRAWINGS DOUBLE DOWN AND LEFT 0x2558: [910,-174,708,318,720], // BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE 0x2559: [910,-267,708,225,720], // BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE 0x255A: [910,-174,708,225,719], // BOX DRAWINGS DOUBLE UP AND RIGHT 0x255B: [910,-174,708,-11,390], // BOX DRAWINGS UP SINGLE AND LEFT DOUBLE 0x255C: [910,-267,708,-11,483], // BOX DRAWINGS UP DOUBLE AND LEFT SINGLE 0x255D: [910,-174,708,-11,483], // BOX DRAWINGS DOUBLE UP AND LEFT 0x255E: [910,303,708,318,720], // BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE 0x255F: [910,303,708,225,720], // BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE 0x2560: [910,303,708,225,720], // BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x2561: [910,303,708,-11,390], // BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE 0x2562: [910,303,708,-11,483], // BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE 0x2563: [910,303,708,-11,483], // BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x2564: [433,303,708,-11,719], // BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE 0x2565: [340,303,708,-11,719], // BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE 0x2566: [433,303,708,-11,719], // BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x2567: [910,-174,708,-11,719], // BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE 0x2568: [910,-267,708,-11,719], // BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE 0x2569: [910,-174,708,-11,719], // BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x256A: [910,303,708,-11,719], // BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE 0x256B: [910,303,708,-11,719], // BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE 0x256C: [910,303,708,-11,719] // BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL } ); MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir + "/General/BoldItalic/BoxDrawing.js");
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * 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. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */ /*global define, brackets, window, $, Mustache */ define(function (require, exports, module) { "use strict"; // Brackets modules var ProjectManager = brackets.getModule("project/ProjectManager"), SidebarView = brackets.getModule("project/SidebarView"), PreferencesManager = brackets.getModule("preferences/PreferencesManager"), Commands = brackets.getModule("command/Commands"), CommandManager = brackets.getModule("command/CommandManager"), KeyBindingManager = brackets.getModule("command/KeyBindingManager"), Menus = brackets.getModule("command/Menus"), MainViewManager = brackets.getModule("view/MainViewManager"), ExtensionUtils = brackets.getModule("utils/ExtensionUtils"), FileSystem = brackets.getModule("filesystem/FileSystem"), AppInit = brackets.getModule("utils/AppInit"), KeyEvent = brackets.getModule("utils/KeyEvent"), FileUtils = brackets.getModule("file/FileUtils"), PopUpManager = brackets.getModule("widgets/PopUpManager"), Strings = brackets.getModule("strings"), ProjectsMenuTemplate = require("text!htmlContent/projects-menu.html"); var KeyboardPrefs = JSON.parse(require("text!keyboard.json")); /** @const {string} Recent Projects commands ID */ var TOGGLE_DROPDOWN = "recentProjects.toggle"; /** @const {number} Maximum number of displayed recent projects */ var MAX_PROJECTS = 20; /** @type {$.Element} jQuery elements used for the dropdown menu */ var $dropdownItem, $dropdown, $links; /** * Get the stored list of recent projects, fixing up paths as appropriate. * Warning: unlike most paths in Brackets, these lack a trailing "/" */ function getRecentProjects() { var recentProjects = PreferencesManager.getViewState("recentProjects") || [], i; for (i = 0; i < recentProjects.length; i++) { // We have to canonicalize & then de-canonicalize the path here, since our pref format uses no trailing "/" recentProjects[i] = FileUtils.stripTrailingSlash(ProjectManager.updateWelcomeProjectPath(recentProjects[i] + "/")); } return recentProjects; } /** * Add a project to the stored list of recent projects, up to MAX_PROJECTS. */ function add() { var root = FileUtils.stripTrailingSlash(ProjectManager.getProjectRoot().fullPath), recentProjects = getRecentProjects(), index = recentProjects.indexOf(root); if (index !== -1) { recentProjects.splice(index, 1); } recentProjects.unshift(root); if (recentProjects.length > MAX_PROJECTS) { recentProjects = recentProjects.slice(0, MAX_PROJECTS); } PreferencesManager.setViewState("recentProjects", recentProjects); } /** * Check the list of items to see if any of them are hovered, and if so trigger a mouseenter. * Normally the mouseenter event handles this, but when a previous item is deleted and the next * item moves up to be underneath the mouse, we don't get a mouseenter event for that item. */ function checkHovers(pageX, pageY) { $dropdown.children().each(function () { var offset = $(this).offset(), width = $(this).outerWidth(), height = $(this).outerHeight(); if (pageX >= offset.left && pageX <= offset.left + width && pageY >= offset.top && pageY <= offset.top + height) { $(".recent-folder-link", this).triggerHandler("mouseenter"); } }); } /** * Create the "delete" button that shows up when you hover over a project. */ function renderDelete() { return $("<div id='recent-folder-delete' class='trash-icon'>&times;</div>") .mouseup(function (e) { // Don't let the click bubble upward. e.stopPropagation(); // Remove the project from the preferences. var recentProjects = getRecentProjects(), index = recentProjects.indexOf($(this).parent().data("path")), newProjects = [], i; for (i = 0; i < recentProjects.length; i++) { if (i !== index) { newProjects.push(recentProjects[i]); } } PreferencesManager.setViewState("recentProjects", newProjects); $(this).closest("li").remove(); checkHovers(e.pageX, e.pageY); if (newProjects.length === 1) { $dropdown.find(".divider").remove(); } }); } /** * Hide the delete button. */ function removeDeleteButton() { $("#recent-folder-delete").remove(); } /** * Show the delete button over a given target. */ function addDeleteButton($target) { removeDeleteButton(); renderDelete() .css("top", $target.position().top + 6) .appendTo($target); } /** * Selects the next or previous item in the list * @param {number} direction +1 for next, -1 for prev */ function selectNextItem(direction) { var $links = $dropdown.find("a"), index = $dropdownItem ? $links.index($dropdownItem) : (direction > 0 ? -1 : 0), $newItem = $links.eq((index + direction) % $links.length); if ($dropdownItem) { $dropdownItem.removeClass("selected"); } $newItem.addClass("selected"); $dropdownItem = $newItem; removeDeleteButton(); } /** * Deletes the selected item and * move the focus to next item in list. * * @return {boolean} TRUE if project is removed */ function removeSelectedItem(e) { var recentProjects = getRecentProjects(), $cacheItem = $dropdownItem, index = recentProjects.indexOf($cacheItem.data("path")); // When focus is not on project item if (index === -1) { return false; } // remove project recentProjects.splice(index, 1); PreferencesManager.setViewState("recentProjects", recentProjects); checkHovers(e.pageX, e.pageY); if (recentProjects.length === 1) { $dropdown.find(".divider").remove(); } selectNextItem(+1); $cacheItem.closest("li").remove(); return true; } /** * Handles the Key Down events * @param {KeyboardEvent} event * @return {boolean} True if the key was handled */ function keydownHook(event) { var keyHandled = false; switch (event.keyCode) { case KeyEvent.DOM_VK_UP: selectNextItem(-1); keyHandled = true; break; case KeyEvent.DOM_VK_DOWN: selectNextItem(+1); keyHandled = true; break; case KeyEvent.DOM_VK_ENTER: case KeyEvent.DOM_VK_RETURN: if ($dropdownItem) { $dropdownItem.trigger("click"); } keyHandled = true; break; case KeyEvent.DOM_VK_BACK_SPACE: case KeyEvent.DOM_VK_DELETE: if ($dropdownItem) { removeSelectedItem(event); keyHandled = true; } break; } if (keyHandled) { event.stopImmediatePropagation(); event.preventDefault(); } return keyHandled; } /** * Close the dropdown. */ function closeDropdown() { // Since we passed "true" for autoRemove to addPopUp(), this will // automatically remove the dropdown from the DOM. Also, PopUpManager // will call cleanupDropdown(). if ($dropdown) { PopUpManager.removePopUp($dropdown); } } /** * Remove the various event handlers that close the dropdown. This is called by the * PopUpManager when the dropdown is closed. */ function cleanupDropdown() { $("html").off("click", closeDropdown); $("#project-files-container").off("scroll", closeDropdown); $(SidebarView).off("hide", closeDropdown); $("#titlebar .nav").off("click", closeDropdown); $dropdown = null; MainViewManager.focusActivePane(); $(window).off("keydown", keydownHook); } /** * Adds the click and mouse enter/leave events to the dropdown */ function _handleListEvents() { $dropdown .on("click", "a", function () { var $link = $(this), id = $link.attr("id"), path = $link.data("path"); if (path) { ProjectManager.openProject(path) .fail(function () { // Remove the project from the list only if it does not exist on disk var recentProjects = getRecentProjects(), index = recentProjects.indexOf(path); if (index !== -1) { FileSystem.resolve(path, function (err, item) { if (err) { recentProjects.splice(index, 1); } }); } }); closeDropdown(); } else if (id === "open-folder-link") { CommandManager.execute(Commands.FILE_OPEN_FOLDER); } }) .on("mouseenter", "a", function () { if ($dropdownItem) { $dropdownItem.removeClass("selected"); } $dropdownItem = $(this).addClass("selected"); if ($dropdownItem.hasClass("recent-folder-link")) { // Note: we can't depend on the event here because this can be triggered // manually from checkHovers(). addDeleteButton($(this)); } }) .on("mouseleave", "a", function () { var $link = $(this).removeClass("selected"); if ($link.get(0) === $dropdownItem.get(0)) { $dropdownItem = null; } if ($link.hasClass("recent-folder-link")) { removeDeleteButton(); } }); } /** * Parses the path and returns an object with the full path, the folder name and the path without the folder. * @param {string} path The full path to the folder. * @return {{path: string, folder: string, rest: string}} */ function parsePath(path) { var lastSlash = path.lastIndexOf("/"), folder, rest; if (lastSlash === path.length - 1) { lastSlash = path.slice(0, path.length - 1).lastIndexOf("/"); } if (lastSlash >= 0) { rest = " - " + (lastSlash ? path.slice(0, lastSlash) : "/"); folder = path.slice(lastSlash + 1); } else { rest = "/"; folder = path; } return {path: path, folder: folder, rest: rest}; } /** * Create the list of projects in the dropdown menu. * @return {string} The html content */ function renderList() { var recentProjects = getRecentProjects(), currentProject = FileUtils.stripTrailingSlash(ProjectManager.getProjectRoot().fullPath), templateVars = { projectList : [], Strings : Strings }; recentProjects.forEach(function (root) { if (root !== currentProject) { templateVars.projectList.push(parsePath(root)); } }); return Mustache.render(ProjectsMenuTemplate, templateVars); } /** * Show or hide the recent projects dropdown. * * @param {{pageX:number, pageY:number}} position - the absolute position where to open the dropdown */ function showDropdown(position) { // If the dropdown is already visible, just return (so the root click handler on html // will close it). if ($dropdown) { return; } Menus.closeAll(); $dropdown = $(renderList()) .css({ left: position.pageX, top: position.pageY }) .appendTo($("body")); PopUpManager.addPopUp($dropdown, cleanupDropdown, true); // TODO: should use capture, otherwise clicking on the menus doesn't close it. More fallout // from the fact that we can't use the Boostrap (1.4) dropdowns. $("html").on("click", closeDropdown); // Hide the menu if the user scrolls in the project tree. Otherwise the Lion scrollbar // overlaps it. // TODO: This duplicates logic that's already in ProjectManager (which calls Menus.close()). // We should fix this when the popup handling is centralized in PopupManager, as well // as making Esc close the dropdown. See issue #1381. $("#project-files-container").on("scroll", closeDropdown); // Hide the menu if the sidebar is hidden. // TODO: Is there some more general way we could handle this for dropdowns? $(SidebarView).on("hide", closeDropdown); // Hacky: if we detect a click in the menubar, close ourselves. // TODO: again, we should have centralized popup management. $("#titlebar .nav").on("click", closeDropdown); _handleListEvents(); $(window).on("keydown", keydownHook); } /** * Show or hide the recent projects dropdown from the toogle command. */ function handleKeyEvent() { if (!$dropdown) { if (!SidebarView.isVisible()) { SidebarView.show(); } $("#project-dropdown-toggle").trigger("click"); $dropdown.focus(); $links = $dropdown.find("a"); // By default, select the most recent project (which is at the top of the list underneath Open Folder), // but if there are none, select Open Folder instead. $dropdownItem = $links.eq($links.length > 1 ? 1 : 0); $dropdownItem.addClass("selected"); // If focusing the dropdown caused a modal bar to close, we need to refocus the dropdown window.setTimeout(function () { $dropdown.focus(); }, 0); } } PreferencesManager.convertPreferences(module, {"recentProjects": "user"}, true); // Register command handlers CommandManager.register(Strings.CMD_TOGGLE_RECENT_PROJECTS, TOGGLE_DROPDOWN, handleKeyEvent); KeyBindingManager.addBinding(TOGGLE_DROPDOWN, KeyboardPrefs.recentProjects); // Initialize extension AppInit.appReady(function () { ExtensionUtils.loadStyleSheet(module, "styles/styles.less"); $(ProjectManager).on("projectOpen", add); $(ProjectManager).on("beforeProjectClose", add); }); AppInit.htmlReady(function () { $("#project-title") .wrap("<div id='project-dropdown-toggle' class='btn-alt-quiet'></div>") .after("<span class='dropdown-arrow'></span>"); var cmenuAdapter = { open: showDropdown, close: closeDropdown, isOpen: function () { return !!$dropdown; } }; Menus.ContextMenu.assignContextMenuToSelector("#project-dropdown-toggle", cmenuAdapter); }); });
const BaseChecker = require('./../base-checker') const ruleId = 'imports-on-top' const meta = { type: 'order', docs: { description: `Import statements must be on top.`, category: 'Style Guide Rules' }, isDefault: false, recommended: true, defaultSetup: 'warn', schema: null } class ImportsOnTopChecker extends BaseChecker { constructor(reporter) { super(reporter, ruleId, meta) } SourceUnit(node) { let hasContractDef = false for (let i = 0; node.children && i < node.children.length; i += 1) { const curItem = node.children[i] if (curItem.type === 'ContractDefinition') { hasContractDef = true } if (hasContractDef && curItem.type === 'ImportDirective') { this._error(curItem) } } } _error(node) { this.error(node, 'Import statements must be on top') } } module.exports = ImportsOnTopChecker
module.exports = { VERSION: '%KARMA_VERSION%', KARMA_URL_ROOT: '%KARMA_URL_ROOT%', KARMA_PROXY_PATH: '%KARMA_PROXY_PATH%', CONTEXT_URL: 'context.html' }
var AreasOfEffect = (() => { 'use strict'; let MENU_CMD = '!areasOfEffectShowMenu'; let ADD_EFFECT_CMD = '!areasOfEffectAddEffect'; let APPLY_EFFECT_CMD = '!areasOfEffectApplyEffet'; let DEL_EFFECT_CMD = '!areasOfEffectDeleteEffect'; let SHOW_EFFECTS_CMD = '!areasOfEffectShowEffects'; let VERSION = '1.0'; let MENU_CSS = { 'effectsTable': { 'width': '100%' }, 'effectThumbnail': { 'height': '50px', 'width': '50px' }, 'menu': { 'background': '#fff', 'border': 'solid 1px #000', 'border-radius': '5px', 'font-weight': 'bold', 'margin-bottom': '1em', 'overflow': 'hidden' }, 'menuBody': { 'padding': '5px', 'text-align': 'center' }, 'menuHeader': { 'background': '#000', 'color': '#fff', 'text-align': 'center' } }; /** * A saved area of effect graphic. * @typedef {object} AreaOfEffect * @property {string} name * @property {number} rotateOffset * The offset of the rotation facing for the effect's graphic * from 0, going clockwise in radians. * @property {Mat3} ptTransform * The offset of the effect's graphic from its origin. * @property {number} scale * The scale of the image's width compared to the length of the segments drawn for it. * @property {string} imgsrc * The URL of the effect's image. */ /** * Applies an effect to a path. * @param {string} who * @param {string} playerid * @param {string} name * @param {Path} path */ function applyEffect(who, playerid, name, path) { let effect = state.AreasOfEffect.saved[name]; let segment = PathMath.toSegments(path)[0]; let u = VecMath.sub(segment[1], segment[0]); let radians = Math.atan2(u[1], u[0]); let rotation = (radians + effect.rotateOffset)/Math.PI*180; let width = VecMath.length(u)*effect.scale; let m = MatrixMath.rotate(radians); m = MatrixMath.multiply(m, MatrixMath.scale(VecMath.length(u))); m = MatrixMath.multiply(m, effect.ptTransform); let v = MatrixMath.multiply(m, [0, 0, 1]); let pt = VecMath.add(segment[0], v); let graphic = createObj('graphic', { name: effect.name, _pageid: path.get('_pageid'), layer: 'objects', left: pt[0], top: pt[1], rotation: rotation, width: width, height: width/effect.aspectRatio, imgsrc: _getCleanImgsrc(effect.imgsrc), controlledby: playerid }); toBack(graphic); path.remove(); } /** * Deletes a saved area of effect. * @param {string} who * @param {string} playerid * @param {string} name */ function deleteEffect(who, playerid, name) { delete state.AreasOfEffect.saved[name]; _showEffectsListMenu(who, playerid); } /** * Fixes msg.who. * @param {string} who * @return {string} */ function _fixWho(who) { return who.replace(/\(GM\)/, '').trim(); } /** * Cookbook.getCleanImgsrc * https://wiki.roll20.net/API:Cookbook#getCleanImgsrc */ function _getCleanImgsrc(imgsrc) { var parts = imgsrc.match(/(.*\/images\/.*)(thumb|med|original|max)(.*)$/); if(parts) return parts[1]+'thumb'+parts[3]; throw new Error('Only images that you have uploaded to your library ' + 'can be used as custom status markers. ' + 'See https://wiki.roll20.net/API:Objects#imgsrc_and_avatar_property_restrictions for more information.'); } /** * Initializes the state of this script. */ function _initState() { _.defaults(state, { AreasOfEffect: {} }); _.defaults(state.AreasOfEffect, { saved: {} }); } /** * Checks if the chat message starts with some API command. * @private * @param {Msg} msg The chat message for the API command. * @param {String} cmdName * @return {Boolean} */ function _msgStartsWith(msg, cmdName) { var msgTxt = msg.content; return (msg.type == 'api' && msgTxt.indexOf(cmdName) !== -1); } /** * Saves an area of effect. * @param {string} who * @param {string} playerid * @param {string} name * @param {Graphic} effect * @param {Path} path */ function saveEffect(who, playerid, name, effect, path) { let segment = PathMath.toSegments(path)[0]; let u = VecMath.sub(segment[1], segment[0]); let pt = [ effect.get('left'), effect.get('top') ]; let scale = effect.get('width')/VecMath.length(u); let radians = -Math.atan2(u[1], u[0]); let v = VecMath.sub(pt, segment[0]); let vHat = VecMath.normalize(v); let m = MatrixMath.identity(3); m = MatrixMath.multiply(m, MatrixMath.scale(VecMath.length(v)/ VecMath.length(u))); m = MatrixMath.multiply(m, MatrixMath.rotate(radians)); m = MatrixMath.multiply(m, MatrixMath.translate(vHat)); // Save the effect. state.AreasOfEffect.saved[name] = { name: name, ptTransform: m, rotateOffset: effect.get('rotation')/180*Math.PI + radians, scale: scale, aspectRatio: effect.get('width')/effect.get('height'), imgsrc: _getCleanImgsrc(effect.get('imgsrc')) }; // Delete the effect graphic and path. effect.remove(); path.remove(); _whisper(who, 'Created Area of Effect: ' + name); _showMainMenu(who, playerid); } /** * Shows the list of effects which can be applied to a selected path. * @param {string} who * @param {string} playerid */ function _showEffectsListMenu(who, playerid) { let content = new HtmlBuilder('div'); let effects = _.values(state.AreasOfEffect.saved).sort(function(a,b) { if(a.name < b.name) return -1; else if(a.name > b.name) return 1; else return 0; }); let table = content.append('table.effectsTable'); _.each(effects, effect => { let row = table.append('tr'); row.append('td.effectThumbnail', new HtmlBuilder('img', '', { src: effect.imgsrc })); row.append('td', '[' + effect.name + '](' + APPLY_EFFECT_CMD + ' ' + effect.name + ')'); // The GM is allowed to delete effects. if(playerIsGM(playerid)) row.append('td', '[❌](' + DEL_EFFECT_CMD + ' ' + effect.name + ' ?{Delete effect: Are you sure?|yes|no})'); }); content.append('div', '[Back](' + MENU_CMD + ')'); let menu = _showMenuPanel('Choose effect', content); _whisper(who, menu.toString(MENU_CSS)); } /** * Shows the main menu for script. * @param {string} who * @param {string} playerid */ function _showMainMenu(who, playerId) { let content = new HtmlBuilder('div'); content.append('div', '[Apply an effect](' + SHOW_EFFECTS_CMD + ')'); if(playerIsGM(playerId)) content.append('div', '[Save effect](' + ADD_EFFECT_CMD + ' ?{Save Area of Effect: name})'); let menu = _showMenuPanel('Main Menu', content); _whisper(who, menu.toString(MENU_CSS)); } /** * Displays one of the script's menus. * @param {string} header * @param {(string|HtmlBuilder)} content * @return {HtmlBuilder} */ function _showMenuPanel(header, content) { let menu = new HtmlBuilder('.menu'); menu.append('.menuHeader', header); menu.append('.menuBody', content) return menu; } /** * @private * Whispers a Marching Order message to someone. */ function _whisper(who, msg) { sendChat('Areas Of Effect', '/w "' + _fixWho(who) + '" ' + msg); } /** * Check that the menu macro for this script is installed. */ on('ready', () => { let menuMacro = findObjs({ _type: 'macro', name: 'AreasOfEffectMenu' })[0]; if(!menuMacro) { let players = findObjs({ _type: 'player' }); let gms = _.filter(players, player => { return playerIsGM(player.get('_id')); }); _.each(gms, gm => { createObj('macro', { _playerid: gm.get('_id'), name: 'AreasOfEffectMenu', action: MENU_CMD, visibleto: 'all' }); }) } _initState(); log('--- Initialized Areas Of Effect v' + VERSION + ' ---'); }); /** * Set up our chat command handler. */ on("chat:message", function(msg) { try { if(_msgStartsWith(msg, ADD_EFFECT_CMD)) { let argv = msg.content.split(' '); let name = argv.slice(1).join('_'); let graphic, path; _.each(msg.selected, item => { if(item._type === 'graphic') graphic = getObj('graphic', item._id); if(item._type === 'path') path = getObj('path', item._id); }); if(graphic && path) { saveEffect(msg.who, msg.playerid, name, graphic, path); } else { _whisper(msg.who, 'ERROR: You must select a graphic and a path to save an effect.'); } } else if(_msgStartsWith(msg, APPLY_EFFECT_CMD)) { let argv = msg.content.split(' '); let name = argv.slice(1).join('_'); let path; _.each(msg.selected, item => { if(item._type === 'path') path = getObj('path', item._id); }); if(path) applyEffect(msg.who, msg.playerid, name, path); else _whisper(msg.who, 'ERROR: You must select a path to apply the effect to.'); } else if(_msgStartsWith(msg, DEL_EFFECT_CMD)) { let argv = msg.content.split(' '); let name = argv[1]; let confirm = argv[2]; if(confirm === 'yes') deleteEffect(msg.who, msg.playerid, name); } else if(_msgStartsWith(msg, SHOW_EFFECTS_CMD)) { _showEffectsListMenu(msg.who, msg.playerid) } else if(_msgStartsWith(msg, MENU_CMD)) { _showMainMenu(msg.who, msg.playerid); } } catch(err) { log('Areas Of Effect ERROR: ' + err.message); sendChat('Areas Of Effect ERROR:', '/w ' + _fixWho(msg.who) + ' ' + err.message); log(err.stack); } }); })();
var fs = require('fs'); var os = require('os'); var path = require('path'); var util = require('./ci-util'); // initialize _package util.initializePackagePath(); // create the tasks.zip util.createTasksZip(); var branch = null; if (process.env.TF_BUILD) { // during CI agent checks out a commit, not a branch. // $(build.sourceBranch) indicates the branch name, e.g. releases/m108 branch = process.env.BUILD_SOURCEBRANCH; } else { // assumes user has checked out a branch. this is a fairly safe assumption. // this code only runs during "package" and "publish" build targets, which // is not typically run locally. branch = util.run('git symbolic-ref HEAD'); } var commitInfo = util.run('git log -1 --format=oneline'); // create the script fs.mkdirSync(util.hotfixLayoutPath); var scriptPath = path.join(util.hotfixLayoutPath, `${process.env.TASK}.ps1`); var scriptContent = '# Hotfix created from branch: ' + branch + os.EOL; scriptContent += '# Commit: ' + commitInfo + os.EOL; scriptContent += '$ErrorActionPreference=\'Stop\'' + os.EOL; scriptContent += 'Update-DistributedTaskDefinitions -TaskZip $PSScriptRoot\\tasks.zip' + os.EOL; fs.writeFileSync(scriptPath, scriptContent); // link the non-aggregate tasks zip var zipDestPath = path.join(util.hotfixLayoutPath, 'tasks.zip'); fs.linkSync(util.tasksZipPath, zipDestPath)
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ (function(){function a(b,c){var d=b.lang.placeholder,e=b.lang.common.generalTab;return{title:d.title,minWidth:300,minHeight:80,contents:[{id:'info',label:e,title:e,elements:[{id:'text',type:'text',style:'width: 100%;',label:d.text,'default':'',required:true,validate:CKEDITOR.dialog.validate.notEmpty(d.textMissing),setup:function(f){if(c)this.setValue(f.getText().slice(2,-2));},commit:function(f){var g='[['+this.getValue()+']]';CKEDITOR.plugins.placeholder.createPlaceholder(b,f,g);}}]}],onShow:function(){if(c)this._element=CKEDITOR.plugins.placeholder.getSelectedPlaceHoder(b);this.setupContent(this._element);},onOk:function(){this.commitContent(this._element);delete this._element;}};};CKEDITOR.dialog.add('createplaceholder',function(b){return a(b);});CKEDITOR.dialog.add('editplaceholder',function(b){return a(b,1);});})();
if(!dojo._hasResource["tests.rpc"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code. dojo._hasResource["tests.rpc"] = true; dojo.provide("tests.rpc"); dojo.require("dojo.rpc.RpcService"); dojo.require("dojo.rpc.JsonService"); dojo.require("dojo.rpc.JsonpService"); doh.register("tests.rpc", [ { name: "JsonRPC-EchoTest", timeout: 2000, setUp: function(){ var testSmd = { serviceURL:"../../dojo/tests/resources/test_JsonRPCMediator.php", methods:[ { name:"myecho", parameters:[ { name:"somestring", type:"STRING" } ] } ] } this.svc = new dojo.rpc.JsonService(testSmd); }, runTest: function(){ var d = new doh.Deferred(); var td = this.svc.myecho("RPC TEST"); if (window.location.protocol=="file:") { var err= new Error("This Test requires a webserver and PHP and will fail intentionally if loaded from file://"); d.errback(err); return d; } td.addCallbacks(function(result) { if(result=="<P>RPC TEST</P>"){ return true; }else{ return new Error("JsonRpc-EchoTest test failed, resultant content didn't match"); } }, function(result){ return new Error(result); }); td.addBoth(d, "callback"); return d; } }, { name: "JsonRPC-EmptyParamTest", timeout: 2000, setUp: function(){ var testSmd={ serviceURL:"../../dojo/tests/resources/test_JsonRPCMediator.php", methods:[ { name:"contentB" } ] } this.svc = new dojo.rpc.JsonService(testSmd); }, runTest: function(){ var d = new doh.Deferred(); var td = this.svc.contentB(); if (window.location.protocol=="file:") { var err= new Error("This Test requires a webserver and PHP and will fail intentionally if loaded from file://"); d.errback(err); return d; } td.addCallbacks(function(result){ if(result=="<P>Content B</P>"){ return true; }else{ return new Error("JsonRpc-EmpytParamTest test failed, resultant content didn't match"); } }, function(result){ return new Error(result); }); td.addBoth(d, "callback"); return d; } }, { name: "JsonRPC_SMD_Loading_test", setUp: function(){ this.svc = new dojo.rpc.JsonService("../../dojo/tests/resources/testClass.smd"); }, runTest: function(){ if (this.svc.objectName=="testClass") { return true; } else { return new Error("Error loading and/or parsing an smd file"); } } }, { name: "JsonP_test", timeout: 10000, setUp: function(){ this.svc = new dojo.rpc.JsonpService(dojo.moduleUrl("dojo.tests.resources","yahoo_smd_v1.smd"), {appid: "foo"}); }, runTest: function(){ var d = new doh.Deferred(); if (window.location.protocol=="file:") { var err= new Error("This Test requires a webserver and will fail intentionally if loaded from file://"); d.errback(err); return d; } var td = this.svc.webSearch({query:"dojotoolkit"}); td.addCallbacks(function(result){ return true; if (result["ResultSet"]["Result"][0]["DisplayUrl"]=="dojotoolkit.org/") { return true; }else{ return new Error("JsonRpc_SMD_Loading_Test failed, resultant content didn't match"); } }, function(result){ return new Error(result); }); td.addBoth(d, "callback"); return d; } } ] ); }
// set default source and build directories var dest = './build'; var src = './src'; module.exports = { // options for Gulp tasks go here markup: { /* there most likely won't be a need for any markup other than a main index.html but you can add more configuration here if necessary */ src: src + '/index.html', dest: dest }, server: { script: 'server/main.js', ext: 'js html', watch: 'server/**/*.*', nodeArgs: ['--debug'], }, };
let helpers = { formatPrice : function(cents) { return '$' + ( (cents / 100).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",") ); }, rando : function(arr) { return arr[Math.floor(Math.random() * arr.length)]; }, slugify : function(text) { return text.toString().toLowerCase() .replace(/\s+/g, '-') // Replace spaces with - .replace(/[^\w\-]+/g, '') // Remove all non-word chars .replace(/\-\-+/g, '-') // Replace multiple - with single - .replace(/^-+/, '') // Trim - from start of text .replace(/-+$/, ''); // Trim - from end of text }, getFunName : function() { var adjectives = ['adorable', 'beautiful', 'clean', 'drab', 'elegant', 'fancy', 'glamorous', 'handsome', 'long', 'magnificent', 'old-fashioned', 'plain', 'quaint', 'sparkling', 'ugliest', 'unsightly', 'angry', 'bewildered', 'clumsy', 'defeated', 'embarrassed', 'fierce', 'grumpy', 'helpless', 'itchy', 'jealous', 'lazy', 'mysterious', 'nervous', 'obnoxious', 'panicky', 'repulsive', 'scary', 'thoughtless', 'uptight', 'worried']; var nouns = ['women', 'men', 'children', 'teeth', 'feet', 'people', 'leaves', 'mice', 'geese', 'halves', 'knives', 'wives', 'lives', 'elves', 'loaves', 'potatoes', 'tomatoes', 'cacti', 'foci', 'fungi', 'nuclei', 'syllabuses', 'analyses', 'diagnoses', 'oases', 'theses', 'crises', 'phenomena', 'criteria', 'data']; return `${this.rando(adjectives)}-${this.rando(adjectives)}-${this.rando(nouns)}`; } } export default helpers;
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.JSEncrypt = {}))); }(this, (function (exports) { 'use strict'; var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; function int2char(n) { return BI_RM.charAt(n); } //#region BIT_OPERATIONS // (public) this & a function op_and(x, y) { return x & y; } // (public) this | a function op_or(x, y) { return x | y; } // (public) this ^ a function op_xor(x, y) { return x ^ y; } // (public) this & ~a function op_andnot(x, y) { return x & ~y; } // return index of lowest 1-bit in x, x < 2^31 function lbit(x) { if (x == 0) { return -1; } var r = 0; if ((x & 0xffff) == 0) { x >>= 16; r += 16; } if ((x & 0xff) == 0) { x >>= 8; r += 8; } if ((x & 0xf) == 0) { x >>= 4; r += 4; } if ((x & 3) == 0) { x >>= 2; r += 2; } if ((x & 1) == 0) { ++r; } return r; } // return number of 1 bits in x function cbit(x) { var r = 0; while (x != 0) { x &= x - 1; ++r; } return r; } //#endregion BIT_OPERATIONS var b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var b64pad = "="; function hex2b64(h) { var i; var c; var ret = ""; for (i = 0; i + 3 <= h.length; i += 3) { c = parseInt(h.substring(i, i + 3), 16); ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63); } if (i + 1 == h.length) { c = parseInt(h.substring(i, i + 1), 16); ret += b64map.charAt(c << 2); } else if (i + 2 == h.length) { c = parseInt(h.substring(i, i + 2), 16); ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4); } while ((ret.length & 3) > 0) { ret += b64pad; } return ret; } // convert a base64 string to hex function b64tohex(s) { var ret = ""; var i; var k = 0; // b64 state, 0-3 var slop = 0; for (i = 0; i < s.length; ++i) { if (s.charAt(i) == b64pad) { break; } var v = b64map.indexOf(s.charAt(i)); if (v < 0) { continue; } if (k == 0) { ret += int2char(v >> 2); slop = v & 3; k = 1; } else if (k == 1) { ret += int2char((slop << 2) | (v >> 4)); slop = v & 0xf; k = 2; } else if (k == 2) { ret += int2char(slop); ret += int2char(v >> 2); slop = v & 3; k = 3; } else { ret += int2char((slop << 2) | (v >> 4)); ret += int2char(v & 0xf); k = 0; } } if (k == 1) { ret += int2char(slop << 2); } return ret; } /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } // Hex JavaScript decoder // Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it> // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */ var decoder; var Hex = { decode: function (a) { var i; if (decoder === undefined) { var hex = "0123456789ABCDEF"; var ignore = " \f\n\r\t\u00A0\u2028\u2029"; decoder = {}; for (i = 0; i < 16; ++i) { decoder[hex.charAt(i)] = i; } hex = hex.toLowerCase(); for (i = 10; i < 16; ++i) { decoder[hex.charAt(i)] = i; } for (i = 0; i < ignore.length; ++i) { decoder[ignore.charAt(i)] = -1; } } var out = []; var bits = 0; var char_count = 0; for (i = 0; i < a.length; ++i) { var c = a.charAt(i); if (c == "=") { break; } c = decoder[c]; if (c == -1) { continue; } if (c === undefined) { throw new Error("Illegal character at offset " + i); } bits |= c; if (++char_count >= 2) { out[out.length] = bits; bits = 0; char_count = 0; } else { bits <<= 4; } } if (char_count) { throw new Error("Hex encoding incomplete: 4 bits missing"); } return out; } }; // Base64 JavaScript decoder // Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it> // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */ var decoder$1; var Base64 = { decode: function (a) { var i; if (decoder$1 === undefined) { var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var ignore = "= \f\n\r\t\u00A0\u2028\u2029"; decoder$1 = Object.create(null); for (i = 0; i < 64; ++i) { decoder$1[b64.charAt(i)] = i; } for (i = 0; i < ignore.length; ++i) { decoder$1[ignore.charAt(i)] = -1; } } var out = []; var bits = 0; var char_count = 0; for (i = 0; i < a.length; ++i) { var c = a.charAt(i); if (c == "=") { break; } c = decoder$1[c]; if (c == -1) { continue; } if (c === undefined) { throw new Error("Illegal character at offset " + i); } bits |= c; if (++char_count >= 4) { out[out.length] = (bits >> 16); out[out.length] = (bits >> 8) & 0xFF; out[out.length] = bits & 0xFF; bits = 0; char_count = 0; } else { bits <<= 6; } } switch (char_count) { case 1: throw new Error("Base64 encoding incomplete: at least 2 bits missing"); case 2: out[out.length] = (bits >> 10); break; case 3: out[out.length] = (bits >> 16); out[out.length] = (bits >> 8) & 0xFF; break; } return out; }, re: /-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/, unarmor: function (a) { var m = Base64.re.exec(a); if (m) { if (m[1]) { a = m[1]; } else if (m[2]) { a = m[2]; } else { throw new Error("RegExp out of sync"); } } return Base64.decode(a); } }; // Big integer base-10 printing library // Copyright (c) 2014 Lapo Luchini <lapo@lapo.it> // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */ var max = 10000000000000; // biggest integer that can still fit 2^53 when multiplied by 256 var Int10 = /** @class */ (function () { function Int10(value) { this.buf = [+value || 0]; } Int10.prototype.mulAdd = function (m, c) { // assert(m <= 256) var b = this.buf; var l = b.length; var i; var t; for (i = 0; i < l; ++i) { t = b[i] * m + c; if (t < max) { c = 0; } else { c = 0 | (t / max); t -= c * max; } b[i] = t; } if (c > 0) { b[i] = c; } }; Int10.prototype.sub = function (c) { // assert(m <= 256) var b = this.buf; var l = b.length; var i; var t; for (i = 0; i < l; ++i) { t = b[i] - c; if (t < 0) { t += max; c = 1; } else { c = 0; } b[i] = t; } while (b[b.length - 1] === 0) { b.pop(); } }; Int10.prototype.toString = function (base) { if ((base || 10) != 10) { throw new Error("only base 10 is supported"); } var b = this.buf; var s = b[b.length - 1].toString(); for (var i = b.length - 2; i >= 0; --i) { s += (max + b[i]).toString().substring(1); } return s; }; Int10.prototype.valueOf = function () { var b = this.buf; var v = 0; for (var i = b.length - 1; i >= 0; --i) { v = v * max + b[i]; } return v; }; Int10.prototype.simplify = function () { var b = this.buf; return (b.length == 1) ? b[0] : this; }; return Int10; }()); // ASN.1 JavaScript decoder var ellipsis = "\u2026"; var reTimeS = /^(\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/; var reTimeL = /^(\d\d\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/; function stringCut(str, len) { if (str.length > len) { str = str.substring(0, len) + ellipsis; } return str; } var Stream = /** @class */ (function () { function Stream(enc, pos) { this.hexDigits = "0123456789ABCDEF"; if (enc instanceof Stream) { this.enc = enc.enc; this.pos = enc.pos; } else { // enc should be an array or a binary string this.enc = enc; this.pos = pos; } } Stream.prototype.get = function (pos) { if (pos === undefined) { pos = this.pos++; } if (pos >= this.enc.length) { throw new Error("Requesting byte offset " + pos + " on a stream of length " + this.enc.length); } return ("string" === typeof this.enc) ? this.enc.charCodeAt(pos) : this.enc[pos]; }; Stream.prototype.hexByte = function (b) { return this.hexDigits.charAt((b >> 4) & 0xF) + this.hexDigits.charAt(b & 0xF); }; Stream.prototype.hexDump = function (start, end, raw) { var s = ""; for (var i = start; i < end; ++i) { s += this.hexByte(this.get(i)); if (raw !== true) { switch (i & 0xF) { case 0x7: s += " "; break; case 0xF: s += "\n"; break; default: s += " "; } } } return s; }; Stream.prototype.isASCII = function (start, end) { for (var i = start; i < end; ++i) { var c = this.get(i); if (c < 32 || c > 176) { return false; } } return true; }; Stream.prototype.parseStringISO = function (start, end) { var s = ""; for (var i = start; i < end; ++i) { s += String.fromCharCode(this.get(i)); } return s; }; Stream.prototype.parseStringUTF = function (start, end) { var s = ""; for (var i = start; i < end;) { var c = this.get(i++); if (c < 128) { s += String.fromCharCode(c); } else if ((c > 191) && (c < 224)) { s += String.fromCharCode(((c & 0x1F) << 6) | (this.get(i++) & 0x3F)); } else { s += String.fromCharCode(((c & 0x0F) << 12) | ((this.get(i++) & 0x3F) << 6) | (this.get(i++) & 0x3F)); } } return s; }; Stream.prototype.parseStringBMP = function (start, end) { var str = ""; var hi; var lo; for (var i = start; i < end;) { hi = this.get(i++); lo = this.get(i++); str += String.fromCharCode((hi << 8) | lo); } return str; }; Stream.prototype.parseTime = function (start, end, shortYear) { var s = this.parseStringISO(start, end); var m = (shortYear ? reTimeS : reTimeL).exec(s); if (!m) { return "Unrecognized time: " + s; } if (shortYear) { // to avoid querying the timer, use the fixed range [1970, 2069] // it will conform with ITU X.400 [-10, +40] sliding window until 2030 m[1] = +m[1]; m[1] += (+m[1] < 70) ? 2000 : 1900; } s = m[1] + "-" + m[2] + "-" + m[3] + " " + m[4]; if (m[5]) { s += ":" + m[5]; if (m[6]) { s += ":" + m[6]; if (m[7]) { s += "." + m[7]; } } } if (m[8]) { s += " UTC"; if (m[8] != "Z") { s += m[8]; if (m[9]) { s += ":" + m[9]; } } } return s; }; Stream.prototype.parseInteger = function (start, end) { var v = this.get(start); var neg = (v > 127); var pad = neg ? 255 : 0; var len; var s = ""; // skip unuseful bits (not allowed in DER) while (v == pad && ++start < end) { v = this.get(start); } len = end - start; if (len === 0) { return neg ? -1 : 0; } // show bit length of huge integers if (len > 4) { s = v; len <<= 3; while (((+s ^ pad) & 0x80) == 0) { s = +s << 1; --len; } s = "(" + len + " bit)\n"; } // decode the integer if (neg) { v = v - 256; } var n = new Int10(v); for (var i = start + 1; i < end; ++i) { n.mulAdd(256, this.get(i)); } return s + n.toString(); }; Stream.prototype.parseBitString = function (start, end, maxLength) { var unusedBit = this.get(start); var lenBit = ((end - start - 1) << 3) - unusedBit; var intro = "(" + lenBit + " bit)\n"; var s = ""; for (var i = start + 1; i < end; ++i) { var b = this.get(i); var skip = (i == end - 1) ? unusedBit : 0; for (var j = 7; j >= skip; --j) { s += (b >> j) & 1 ? "1" : "0"; } if (s.length > maxLength) { return intro + stringCut(s, maxLength); } } return intro + s; }; Stream.prototype.parseOctetString = function (start, end, maxLength) { if (this.isASCII(start, end)) { return stringCut(this.parseStringISO(start, end), maxLength); } var len = end - start; var s = "(" + len + " byte)\n"; maxLength /= 2; // we work in bytes if (len > maxLength) { end = start + maxLength; } for (var i = start; i < end; ++i) { s += this.hexByte(this.get(i)); } if (len > maxLength) { s += ellipsis; } return s; }; Stream.prototype.parseOID = function (start, end, maxLength) { var s = ""; var n = new Int10(); var bits = 0; for (var i = start; i < end; ++i) { var v = this.get(i); n.mulAdd(128, v & 0x7F); bits += 7; if (!(v & 0x80)) { // finished if (s === "") { n = n.simplify(); if (n instanceof Int10) { n.sub(80); s = "2." + n.toString(); } else { var m = n < 80 ? n < 40 ? 0 : 1 : 2; s = m + "." + (n - m * 40); } } else { s += "." + n.toString(); } if (s.length > maxLength) { return stringCut(s, maxLength); } n = new Int10(); bits = 0; } } if (bits > 0) { s += ".incomplete"; } return s; }; return Stream; }()); var ASN1 = /** @class */ (function () { function ASN1(stream, header, length, tag, sub) { if (!(tag instanceof ASN1Tag)) { throw new Error("Invalid tag value."); } this.stream = stream; this.header = header; this.length = length; this.tag = tag; this.sub = sub; } ASN1.prototype.typeName = function () { switch (this.tag.tagClass) { case 0: // universal switch (this.tag.tagNumber) { case 0x00: return "EOC"; case 0x01: return "BOOLEAN"; case 0x02: return "INTEGER"; case 0x03: return "BIT_STRING"; case 0x04: return "OCTET_STRING"; case 0x05: return "NULL"; case 0x06: return "OBJECT_IDENTIFIER"; case 0x07: return "ObjectDescriptor"; case 0x08: return "EXTERNAL"; case 0x09: return "REAL"; case 0x0A: return "ENUMERATED"; case 0x0B: return "EMBEDDED_PDV"; case 0x0C: return "UTF8String"; case 0x10: return "SEQUENCE"; case 0x11: return "SET"; case 0x12: return "NumericString"; case 0x13: return "PrintableString"; // ASCII subset case 0x14: return "TeletexString"; // aka T61String case 0x15: return "VideotexString"; case 0x16: return "IA5String"; // ASCII case 0x17: return "UTCTime"; case 0x18: return "GeneralizedTime"; case 0x19: return "GraphicString"; case 0x1A: return "VisibleString"; // ASCII subset case 0x1B: return "GeneralString"; case 0x1C: return "UniversalString"; case 0x1E: return "BMPString"; } return "Universal_" + this.tag.tagNumber.toString(); case 1: return "Application_" + this.tag.tagNumber.toString(); case 2: return "[" + this.tag.tagNumber.toString() + "]"; // Context case 3: return "Private_" + this.tag.tagNumber.toString(); } }; ASN1.prototype.content = function (maxLength) { if (this.tag === undefined) { return null; } if (maxLength === undefined) { maxLength = Infinity; } var content = this.posContent(); var len = Math.abs(this.length); if (!this.tag.isUniversal()) { if (this.sub !== null) { return "(" + this.sub.length + " elem)"; } return this.stream.parseOctetString(content, content + len, maxLength); } switch (this.tag.tagNumber) { case 0x01: // BOOLEAN return (this.stream.get(content) === 0) ? "false" : "true"; case 0x02: // INTEGER return this.stream.parseInteger(content, content + len); case 0x03: // BIT_STRING return this.sub ? "(" + this.sub.length + " elem)" : this.stream.parseBitString(content, content + len, maxLength); case 0x04: // OCTET_STRING return this.sub ? "(" + this.sub.length + " elem)" : this.stream.parseOctetString(content, content + len, maxLength); // case 0x05: // NULL case 0x06: // OBJECT_IDENTIFIER return this.stream.parseOID(content, content + len, maxLength); // case 0x07: // ObjectDescriptor // case 0x08: // EXTERNAL // case 0x09: // REAL // case 0x0A: // ENUMERATED // case 0x0B: // EMBEDDED_PDV case 0x10: // SEQUENCE case 0x11: // SET if (this.sub !== null) { return "(" + this.sub.length + " elem)"; } else { return "(no elem)"; } case 0x0C: // UTF8String return stringCut(this.stream.parseStringUTF(content, content + len), maxLength); case 0x12: // NumericString case 0x13: // PrintableString case 0x14: // TeletexString case 0x15: // VideotexString case 0x16: // IA5String // case 0x19: // GraphicString case 0x1A: // VisibleString // case 0x1B: // GeneralString // case 0x1C: // UniversalString return stringCut(this.stream.parseStringISO(content, content + len), maxLength); case 0x1E: // BMPString return stringCut(this.stream.parseStringBMP(content, content + len), maxLength); case 0x17: // UTCTime case 0x18: // GeneralizedTime return this.stream.parseTime(content, content + len, (this.tag.tagNumber == 0x17)); } return null; }; ASN1.prototype.toString = function () { return this.typeName() + "@" + this.stream.pos + "[header:" + this.header + ",length:" + this.length + ",sub:" + ((this.sub === null) ? "null" : this.sub.length) + "]"; }; ASN1.prototype.toPrettyString = function (indent) { if (indent === undefined) { indent = ""; } var s = indent + this.typeName() + " @" + this.stream.pos; if (this.length >= 0) { s += "+"; } s += this.length; if (this.tag.tagConstructed) { s += " (constructed)"; } else if ((this.tag.isUniversal() && ((this.tag.tagNumber == 0x03) || (this.tag.tagNumber == 0x04))) && (this.sub !== null)) { s += " (encapsulates)"; } s += "\n"; if (this.sub !== null) { indent += " "; for (var i = 0, max = this.sub.length; i < max; ++i) { s += this.sub[i].toPrettyString(indent); } } return s; }; ASN1.prototype.posStart = function () { return this.stream.pos; }; ASN1.prototype.posContent = function () { return this.stream.pos + this.header; }; ASN1.prototype.posEnd = function () { return this.stream.pos + this.header + Math.abs(this.length); }; ASN1.prototype.toHexString = function () { return this.stream.hexDump(this.posStart(), this.posEnd(), true); }; ASN1.decodeLength = function (stream) { var buf = stream.get(); var len = buf & 0x7F; if (len == buf) { return len; } // no reason to use Int10, as it would be a huge buffer anyways if (len > 6) { throw new Error("Length over 48 bits not supported at position " + (stream.pos - 1)); } if (len === 0) { return null; } // undefined buf = 0; for (var i = 0; i < len; ++i) { buf = (buf * 256) + stream.get(); } return buf; }; /** * Retrieve the hexadecimal value (as a string) of the current ASN.1 element * @returns {string} * @public */ ASN1.prototype.getHexStringValue = function () { var hexString = this.toHexString(); var offset = this.header * 2; var length = this.length * 2; return hexString.substr(offset, length); }; ASN1.decode = function (str) { var stream; if (!(str instanceof Stream)) { stream = new Stream(str, 0); } else { stream = str; } var streamStart = new Stream(stream); var tag = new ASN1Tag(stream); var len = ASN1.decodeLength(stream); var start = stream.pos; var header = start - streamStart.pos; var sub = null; var getSub = function () { var ret = []; if (len !== null) { // definite length var end = start + len; while (stream.pos < end) { ret[ret.length] = ASN1.decode(stream); } if (stream.pos != end) { throw new Error("Content size is not correct for container starting at offset " + start); } } else { // undefined length try { for (;;) { var s = ASN1.decode(stream); if (s.tag.isEOC()) { break; } ret[ret.length] = s; } len = start - stream.pos; // undefined lengths are represented as negative values } catch (e) { throw new Error("Exception while decoding undefined length content: " + e); } } return ret; }; if (tag.tagConstructed) { // must have valid content sub = getSub(); } else if (tag.isUniversal() && ((tag.tagNumber == 0x03) || (tag.tagNumber == 0x04))) { // sometimes BitString and OctetString are used to encapsulate ASN.1 try { if (tag.tagNumber == 0x03) { if (stream.get() != 0) { throw new Error("BIT STRINGs with unused bits cannot encapsulate."); } } sub = getSub(); for (var i = 0; i < sub.length; ++i) { if (sub[i].tag.isEOC()) { throw new Error("EOC is not supposed to be actual content."); } } } catch (e) { // but silently ignore when they don't sub = null; } } if (sub === null) { if (len === null) { throw new Error("We can't skip over an invalid tag with undefined length at offset " + start); } stream.pos = start + Math.abs(len); } return new ASN1(streamStart, header, len, tag, sub); }; return ASN1; }()); var ASN1Tag = /** @class */ (function () { function ASN1Tag(stream) { var buf = stream.get(); this.tagClass = buf >> 6; this.tagConstructed = ((buf & 0x20) !== 0); this.tagNumber = buf & 0x1F; if (this.tagNumber == 0x1F) { // long tag var n = new Int10(); do { buf = stream.get(); n.mulAdd(128, buf & 0x7F); } while (buf & 0x80); this.tagNumber = n.simplify(); } } ASN1Tag.prototype.isUniversal = function () { return this.tagClass === 0x00; }; ASN1Tag.prototype.isEOC = function () { return this.tagClass === 0x00 && this.tagNumber === 0x00; }; return ASN1Tag; }()); // Copyright (c) 2005 Tom Wu // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary & 0xffffff) == 0xefcafe); //#region var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]; var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; //#endregion // (public) Constructor var BigInteger = /** @class */ (function () { function BigInteger(a, b, c) { if (a != null) { if ("number" == typeof a) { this.fromNumber(a, b, c); } else if (b == null && "string" != typeof a) { this.fromString(a, 256); } else { this.fromString(a, b); } } } //#region PUBLIC // BigInteger.prototype.toString = bnToString; // (public) return string representation in given radix BigInteger.prototype.toString = function (b) { if (this.s < 0) { return "-" + this.negate().toString(b); } var k; if (b == 16) { k = 4; } else if (b == 8) { k = 3; } else if (b == 2) { k = 1; } else if (b == 32) { k = 5; } else if (b == 4) { k = 2; } else { return this.toRadix(b); } var km = (1 << k) - 1; var d; var m = false; var r = ""; var i = this.t; var p = this.DB - (i * this.DB) % k; if (i-- > 0) { if (p < this.DB && (d = this[i] >> p) > 0) { m = true; r = int2char(d); } while (i >= 0) { if (p < k) { d = (this[i] & ((1 << p) - 1)) << (k - p); d |= this[--i] >> (p += this.DB - k); } else { d = (this[i] >> (p -= k)) & km; if (p <= 0) { p += this.DB; --i; } } if (d > 0) { m = true; } if (m) { r += int2char(d); } } } return m ? r : "0"; }; // BigInteger.prototype.negate = bnNegate; // (public) -this BigInteger.prototype.negate = function () { var r = nbi(); BigInteger.ZERO.subTo(this, r); return r; }; // BigInteger.prototype.abs = bnAbs; // (public) |this| BigInteger.prototype.abs = function () { return (this.s < 0) ? this.negate() : this; }; // BigInteger.prototype.compareTo = bnCompareTo; // (public) return + if this > a, - if this < a, 0 if equal BigInteger.prototype.compareTo = function (a) { var r = this.s - a.s; if (r != 0) { return r; } var i = this.t; r = i - a.t; if (r != 0) { return (this.s < 0) ? -r : r; } while (--i >= 0) { if ((r = this[i] - a[i]) != 0) { return r; } } return 0; }; // BigInteger.prototype.bitLength = bnBitLength; // (public) return the number of bits in "this" BigInteger.prototype.bitLength = function () { if (this.t <= 0) { return 0; } return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)); }; // BigInteger.prototype.mod = bnMod; // (public) this mod a BigInteger.prototype.mod = function (a) { var r = nbi(); this.abs().divRemTo(a, null, r); if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) { a.subTo(r, r); } return r; }; // BigInteger.prototype.modPowInt = bnModPowInt; // (public) this^e % m, 0 <= e < 2^32 BigInteger.prototype.modPowInt = function (e, m) { var z; if (e < 256 || m.isEven()) { z = new Classic(m); } else { z = new Montgomery(m); } return this.exp(e, z); }; // BigInteger.prototype.clone = bnClone; // (public) BigInteger.prototype.clone = function () { var r = nbi(); this.copyTo(r); return r; }; // BigInteger.prototype.intValue = bnIntValue; // (public) return value as integer BigInteger.prototype.intValue = function () { if (this.s < 0) { if (this.t == 1) { return this[0] - this.DV; } else if (this.t == 0) { return -1; } } else if (this.t == 1) { return this[0]; } else if (this.t == 0) { return 0; } // assumes 16 < DB < 32 return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]; }; // BigInteger.prototype.byteValue = bnByteValue; // (public) return value as byte BigInteger.prototype.byteValue = function () { return (this.t == 0) ? this.s : (this[0] << 24) >> 24; }; // BigInteger.prototype.shortValue = bnShortValue; // (public) return value as short (assumes DB>=16) BigInteger.prototype.shortValue = function () { return (this.t == 0) ? this.s : (this[0] << 16) >> 16; }; // BigInteger.prototype.signum = bnSigNum; // (public) 0 if this == 0, 1 if this > 0 BigInteger.prototype.signum = function () { if (this.s < 0) { return -1; } else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) { return 0; } else { return 1; } }; // BigInteger.prototype.toByteArray = bnToByteArray; // (public) convert to bigendian byte array BigInteger.prototype.toByteArray = function () { var i = this.t; var r = []; r[0] = this.s; var p = this.DB - (i * this.DB) % 8; var d; var k = 0; if (i-- > 0) { if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) { r[k++] = d | (this.s << (this.DB - p)); } while (i >= 0) { if (p < 8) { d = (this[i] & ((1 << p) - 1)) << (8 - p); d |= this[--i] >> (p += this.DB - 8); } else { d = (this[i] >> (p -= 8)) & 0xff; if (p <= 0) { p += this.DB; --i; } } if ((d & 0x80) != 0) { d |= -256; } if (k == 0 && (this.s & 0x80) != (d & 0x80)) { ++k; } if (k > 0 || d != this.s) { r[k++] = d; } } } return r; }; // BigInteger.prototype.equals = bnEquals; BigInteger.prototype.equals = function (a) { return (this.compareTo(a) == 0); }; // BigInteger.prototype.min = bnMin; BigInteger.prototype.min = function (a) { return (this.compareTo(a) < 0) ? this : a; }; // BigInteger.prototype.max = bnMax; BigInteger.prototype.max = function (a) { return (this.compareTo(a) > 0) ? this : a; }; // BigInteger.prototype.and = bnAnd; BigInteger.prototype.and = function (a) { var r = nbi(); this.bitwiseTo(a, op_and, r); return r; }; // BigInteger.prototype.or = bnOr; BigInteger.prototype.or = function (a) { var r = nbi(); this.bitwiseTo(a, op_or, r); return r; }; // BigInteger.prototype.xor = bnXor; BigInteger.prototype.xor = function (a) { var r = nbi(); this.bitwiseTo(a, op_xor, r); return r; }; // BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.andNot = function (a) { var r = nbi(); this.bitwiseTo(a, op_andnot, r); return r; }; // BigInteger.prototype.not = bnNot; // (public) ~this BigInteger.prototype.not = function () { var r = nbi(); for (var i = 0; i < this.t; ++i) { r[i] = this.DM & ~this[i]; } r.t = this.t; r.s = ~this.s; return r; }; // BigInteger.prototype.shiftLeft = bnShiftLeft; // (public) this << n BigInteger.prototype.shiftLeft = function (n) { var r = nbi(); if (n < 0) { this.rShiftTo(-n, r); } else { this.lShiftTo(n, r); } return r; }; // BigInteger.prototype.shiftRight = bnShiftRight; // (public) this >> n BigInteger.prototype.shiftRight = function (n) { var r = nbi(); if (n < 0) { this.lShiftTo(-n, r); } else { this.rShiftTo(n, r); } return r; }; // BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; // (public) returns index of lowest 1-bit (or -1 if none) BigInteger.prototype.getLowestSetBit = function () { for (var i = 0; i < this.t; ++i) { if (this[i] != 0) { return i * this.DB + lbit(this[i]); } } if (this.s < 0) { return this.t * this.DB; } return -1; }; // BigInteger.prototype.bitCount = bnBitCount; // (public) return number of set bits BigInteger.prototype.bitCount = function () { var r = 0; var x = this.s & this.DM; for (var i = 0; i < this.t; ++i) { r += cbit(this[i] ^ x); } return r; }; // BigInteger.prototype.testBit = bnTestBit; // (public) true iff nth bit is set BigInteger.prototype.testBit = function (n) { var j = Math.floor(n / this.DB); if (j >= this.t) { return (this.s != 0); } return ((this[j] & (1 << (n % this.DB))) != 0); }; // BigInteger.prototype.setBit = bnSetBit; // (public) this | (1<<n) BigInteger.prototype.setBit = function (n) { return this.changeBit(n, op_or); }; // BigInteger.prototype.clearBit = bnClearBit; // (public) this & ~(1<<n) BigInteger.prototype.clearBit = function (n) { return this.changeBit(n, op_andnot); }; // BigInteger.prototype.flipBit = bnFlipBit; // (public) this ^ (1<<n) BigInteger.prototype.flipBit = function (n) { return this.changeBit(n, op_xor); }; // BigInteger.prototype.add = bnAdd; // (public) this + a BigInteger.prototype.add = function (a) { var r = nbi(); this.addTo(a, r); return r; }; // BigInteger.prototype.subtract = bnSubtract; // (public) this - a BigInteger.prototype.subtract = function (a) { var r = nbi(); this.subTo(a, r); return r; }; // BigInteger.prototype.multiply = bnMultiply; // (public) this * a BigInteger.prototype.multiply = function (a) { var r = nbi(); this.multiplyTo(a, r); return r; }; // BigInteger.prototype.divide = bnDivide; // (public) this / a BigInteger.prototype.divide = function (a) { var r = nbi(); this.divRemTo(a, r, null); return r; }; // BigInteger.prototype.remainder = bnRemainder; // (public) this % a BigInteger.prototype.remainder = function (a) { var r = nbi(); this.divRemTo(a, null, r); return r; }; // BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; // (public) [this/a,this%a] BigInteger.prototype.divideAndRemainder = function (a) { var q = nbi(); var r = nbi(); this.divRemTo(a, q, r); return [q, r]; }; // BigInteger.prototype.modPow = bnModPow; // (public) this^e % m (HAC 14.85) BigInteger.prototype.modPow = function (e, m) { var i = e.bitLength(); var k; var r = nbv(1); var z; if (i <= 0) { return r; } else if (i < 18) { k = 1; } else if (i < 48) { k = 3; } else if (i < 144) { k = 4; } else if (i < 768) { k = 5; } else { k = 6; } if (i < 8) { z = new Classic(m); } else if (m.isEven()) { z = new Barrett(m); } else { z = new Montgomery(m); } // precomputation var g = []; var n = 3; var k1 = k - 1; var km = (1 << k) - 1; g[1] = z.convert(this); if (k > 1) { var g2 = nbi(); z.sqrTo(g[1], g2); while (n <= km) { g[n] = nbi(); z.mulTo(g2, g[n - 2], g[n]); n += 2; } } var j = e.t - 1; var w; var is1 = true; var r2 = nbi(); var t; i = nbits(e[j]) - 1; while (j >= 0) { if (i >= k1) { w = (e[j] >> (i - k1)) & km; } else { w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i); if (j > 0) { w |= e[j - 1] >> (this.DB + i - k1); } } n = k; while ((w & 1) == 0) { w >>= 1; --n; } if ((i -= n) < 0) { i += this.DB; --j; } if (is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while (n > 1) { z.sqrTo(r, r2); z.sqrTo(r2, r); n -= 2; } if (n > 0) { z.sqrTo(r, r2); } else { t = r; r = r2; r2 = t; } z.mulTo(r2, g[w], r); } while (j >= 0 && (e[j] & (1 << i)) == 0) { z.sqrTo(r, r2); t = r; r = r2; r2 = t; if (--i < 0) { i = this.DB - 1; --j; } } } return z.revert(r); }; // BigInteger.prototype.modInverse = bnModInverse; // (public) 1/this % m (HAC 14.61) BigInteger.prototype.modInverse = function (m) { var ac = m.isEven(); if ((this.isEven() && ac) || m.signum() == 0) { return BigInteger.ZERO; } var u = m.clone(); var v = this.clone(); var a = nbv(1); var b = nbv(0); var c = nbv(0); var d = nbv(1); while (u.signum() != 0) { while (u.isEven()) { u.rShiftTo(1, u); if (ac) { if (!a.isEven() || !b.isEven()) { a.addTo(this, a); b.subTo(m, b); } a.rShiftTo(1, a); } else if (!b.isEven()) { b.subTo(m, b); } b.rShiftTo(1, b); } while (v.isEven()) { v.rShiftTo(1, v); if (ac) { if (!c.isEven() || !d.isEven()) { c.addTo(this, c); d.subTo(m, d); } c.rShiftTo(1, c); } else if (!d.isEven()) { d.subTo(m, d); } d.rShiftTo(1, d); } if (u.compareTo(v) >= 0) { u.subTo(v, u); if (ac) { a.subTo(c, a); } b.subTo(d, b); } else { v.subTo(u, v); if (ac) { c.subTo(a, c); } d.subTo(b, d); } } if (v.compareTo(BigInteger.ONE) != 0) { return BigInteger.ZERO; } if (d.compareTo(m) >= 0) { return d.subtract(m); } if (d.signum() < 0) { d.addTo(m, d); } else { return d; } if (d.signum() < 0) { return d.add(m); } else { return d; } }; // BigInteger.prototype.pow = bnPow; // (public) this^e BigInteger.prototype.pow = function (e) { return this.exp(e, new NullExp()); }; // BigInteger.prototype.gcd = bnGCD; // (public) gcd(this,a) (HAC 14.54) BigInteger.prototype.gcd = function (a) { var x = (this.s < 0) ? this.negate() : this.clone(); var y = (a.s < 0) ? a.negate() : a.clone(); if (x.compareTo(y) < 0) { var t = x; x = y; y = t; } var i = x.getLowestSetBit(); var g = y.getLowestSetBit(); if (g < 0) { return x; } if (i < g) { g = i; } if (g > 0) { x.rShiftTo(g, x); y.rShiftTo(g, y); } while (x.signum() > 0) { if ((i = x.getLowestSetBit()) > 0) { x.rShiftTo(i, x); } if ((i = y.getLowestSetBit()) > 0) { y.rShiftTo(i, y); } if (x.compareTo(y) >= 0) { x.subTo(y, x); x.rShiftTo(1, x); } else { y.subTo(x, y); y.rShiftTo(1, y); } } if (g > 0) { y.lShiftTo(g, y); } return y; }; // BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // (public) test primality with certainty >= 1-.5^t BigInteger.prototype.isProbablePrime = function (t) { var i; var x = this.abs(); if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { for (i = 0; i < lowprimes.length; ++i) { if (x[0] == lowprimes[i]) { return true; } } return false; } if (x.isEven()) { return false; } i = 1; while (i < lowprimes.length) { var m = lowprimes[i]; var j = i + 1; while (j < lowprimes.length && m < lplim) { m *= lowprimes[j++]; } m = x.modInt(m); while (i < j) { if (m % lowprimes[i++] == 0) { return false; } } } return x.millerRabin(t); }; //#endregion PUBLIC //#region PROTECTED // BigInteger.prototype.copyTo = bnpCopyTo; // (protected) copy this to r BigInteger.prototype.copyTo = function (r) { for (var i = this.t - 1; i >= 0; --i) { r[i] = this[i]; } r.t = this.t; r.s = this.s; }; // BigInteger.prototype.fromInt = bnpFromInt; // (protected) set from integer value x, -DV <= x < DV BigInteger.prototype.fromInt = function (x) { this.t = 1; this.s = (x < 0) ? -1 : 0; if (x > 0) { this[0] = x; } else if (x < -1) { this[0] = x + this.DV; } else { this.t = 0; } }; // BigInteger.prototype.fromString = bnpFromString; // (protected) set from string and radix BigInteger.prototype.fromString = function (s, b) { var k; if (b == 16) { k = 4; } else if (b == 8) { k = 3; } else if (b == 256) { k = 8; /* byte array */ } else if (b == 2) { k = 1; } else if (b == 32) { k = 5; } else if (b == 4) { k = 2; } else { this.fromRadix(s, b); return; } this.t = 0; this.s = 0; var i = s.length; var mi = false; var sh = 0; while (--i >= 0) { var x = (k == 8) ? (+s[i]) & 0xff : intAt(s, i); if (x < 0) { if (s.charAt(i) == "-") { mi = true; } continue; } mi = false; if (sh == 0) { this[this.t++] = x; } else if (sh + k > this.DB) { this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh; this[this.t++] = (x >> (this.DB - sh)); } else { this[this.t - 1] |= x << sh; } sh += k; if (sh >= this.DB) { sh -= this.DB; } } if (k == 8 && ((+s[0]) & 0x80) != 0) { this.s = -1; if (sh > 0) { this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh; } } this.clamp(); if (mi) { BigInteger.ZERO.subTo(this, this); } }; // BigInteger.prototype.clamp = bnpClamp; // (protected) clamp off excess high words BigInteger.prototype.clamp = function () { var c = this.s & this.DM; while (this.t > 0 && this[this.t - 1] == c) { --this.t; } }; // BigInteger.prototype.dlShiftTo = bnpDLShiftTo; // (protected) r = this << n*DB BigInteger.prototype.dlShiftTo = function (n, r) { var i; for (i = this.t - 1; i >= 0; --i) { r[i + n] = this[i]; } for (i = n - 1; i >= 0; --i) { r[i] = 0; } r.t = this.t + n; r.s = this.s; }; // BigInteger.prototype.drShiftTo = bnpDRShiftTo; // (protected) r = this >> n*DB BigInteger.prototype.drShiftTo = function (n, r) { for (var i = n; i < this.t; ++i) { r[i - n] = this[i]; } r.t = Math.max(this.t - n, 0); r.s = this.s; }; // BigInteger.prototype.lShiftTo = bnpLShiftTo; // (protected) r = this << n BigInteger.prototype.lShiftTo = function (n, r) { var bs = n % this.DB; var cbs = this.DB - bs; var bm = (1 << cbs) - 1; var ds = Math.floor(n / this.DB); var c = (this.s << bs) & this.DM; for (var i = this.t - 1; i >= 0; --i) { r[i + ds + 1] = (this[i] >> cbs) | c; c = (this[i] & bm) << bs; } for (var i = ds - 1; i >= 0; --i) { r[i] = 0; } r[ds] = c; r.t = this.t + ds + 1; r.s = this.s; r.clamp(); }; // BigInteger.prototype.rShiftTo = bnpRShiftTo; // (protected) r = this >> n BigInteger.prototype.rShiftTo = function (n, r) { r.s = this.s; var ds = Math.floor(n / this.DB); if (ds >= this.t) { r.t = 0; return; } var bs = n % this.DB; var cbs = this.DB - bs; var bm = (1 << bs) - 1; r[0] = this[ds] >> bs; for (var i = ds + 1; i < this.t; ++i) { r[i - ds - 1] |= (this[i] & bm) << cbs; r[i - ds] = this[i] >> bs; } if (bs > 0) { r[this.t - ds - 1] |= (this.s & bm) << cbs; } r.t = this.t - ds; r.clamp(); }; // BigInteger.prototype.subTo = bnpSubTo; // (protected) r = this - a BigInteger.prototype.subTo = function (a, r) { var i = 0; var c = 0; var m = Math.min(a.t, this.t); while (i < m) { c += this[i] - a[i]; r[i++] = c & this.DM; c >>= this.DB; } if (a.t < this.t) { c -= a.s; while (i < this.t) { c += this[i]; r[i++] = c & this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while (i < a.t) { c -= a[i]; r[i++] = c & this.DM; c >>= this.DB; } c -= a.s; } r.s = (c < 0) ? -1 : 0; if (c < -1) { r[i++] = this.DV + c; } else if (c > 0) { r[i++] = c; } r.t = i; r.clamp(); }; // BigInteger.prototype.multiplyTo = bnpMultiplyTo; // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. BigInteger.prototype.multiplyTo = function (a, r) { var x = this.abs(); var y = a.abs(); var i = x.t; r.t = i + y.t; while (--i >= 0) { r[i] = 0; } for (i = 0; i < y.t; ++i) { r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); } r.s = 0; r.clamp(); if (this.s != a.s) { BigInteger.ZERO.subTo(r, r); } }; // BigInteger.prototype.squareTo = bnpSquareTo; // (protected) r = this^2, r != this (HAC 14.16) BigInteger.prototype.squareTo = function (r) { var x = this.abs(); var i = r.t = 2 * x.t; while (--i >= 0) { r[i] = 0; } for (i = 0; i < x.t - 1; ++i) { var c = x.am(i, x[i], r, 2 * i, 0, 1); if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { r[i + x.t] -= x.DV; r[i + x.t + 1] = 1; } } if (r.t > 0) { r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); } r.s = 0; r.clamp(); }; // BigInteger.prototype.divRemTo = bnpDivRemTo; // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. BigInteger.prototype.divRemTo = function (m, q, r) { var pm = m.abs(); if (pm.t <= 0) { return; } var pt = this.abs(); if (pt.t < pm.t) { if (q != null) { q.fromInt(0); } if (r != null) { this.copyTo(r); } return; } if (r == null) { r = nbi(); } var y = nbi(); var ts = this.s; var ms = m.s; var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus if (nsh > 0) { pm.lShiftTo(nsh, y); pt.lShiftTo(nsh, r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y[ys - 1]; if (y0 == 0) { return; } var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0); var d1 = this.FV / yt; var d2 = (1 << this.F1) / yt; var e = 1 << this.F2; var i = r.t; var j = i - ys; var t = (q == null) ? nbi() : q; y.dlShiftTo(j, t); if (r.compareTo(t) >= 0) { r[r.t++] = 1; r.subTo(t, r); } BigInteger.ONE.dlShiftTo(ys, t); t.subTo(y, y); // "negative" y so we can replace sub with am later while (y.t < ys) { y[y.t++] = 0; } while (--j >= 0) { // Estimate quotient digit var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out y.dlShiftTo(j, t); r.subTo(t, r); while (r[i] < --qd) { r.subTo(t, r); } } } if (q != null) { r.drShiftTo(ys, q); if (ts != ms) { BigInteger.ZERO.subTo(q, q); } } r.t = ys; r.clamp(); if (nsh > 0) { r.rShiftTo(nsh, r); } // Denormalize remainder if (ts < 0) { BigInteger.ZERO.subTo(r, r); } }; // BigInteger.prototype.invDigit = bnpInvDigit; // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. BigInteger.prototype.invDigit = function () { if (this.t < 1) { return 0; } var x = this[0]; if ((x & 1) == 0) { return 0; } var y = x & 3; // y == 1/x mod 2^2 y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y > 0) ? this.DV - y : -y; }; // BigInteger.prototype.isEven = bnpIsEven; // (protected) true iff this is even BigInteger.prototype.isEven = function () { return ((this.t > 0) ? (this[0] & 1) : this.s) == 0; }; // BigInteger.prototype.exp = bnpExp; // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) BigInteger.prototype.exp = function (e, z) { if (e > 0xffffffff || e < 1) { return BigInteger.ONE; } var r = nbi(); var r2 = nbi(); var g = z.convert(this); var i = nbits(e) - 1; g.copyTo(r); while (--i >= 0) { z.sqrTo(r, r2); if ((e & (1 << i)) > 0) { z.mulTo(r2, g, r); } else { var t = r; r = r2; r2 = t; } } return z.revert(r); }; // BigInteger.prototype.chunkSize = bnpChunkSize; // (protected) return x s.t. r^x < DV BigInteger.prototype.chunkSize = function (r) { return Math.floor(Math.LN2 * this.DB / Math.log(r)); }; // BigInteger.prototype.toRadix = bnpToRadix; // (protected) convert to radix string BigInteger.prototype.toRadix = function (b) { if (b == null) { b = 10; } if (this.signum() == 0 || b < 2 || b > 36) { return "0"; } var cs = this.chunkSize(b); var a = Math.pow(b, cs); var d = nbv(a); var y = nbi(); var z = nbi(); var r = ""; this.divRemTo(d, y, z); while (y.signum() > 0) { r = (a + z.intValue()).toString(b).substr(1) + r; y.divRemTo(d, y, z); } return z.intValue().toString(b) + r; }; // BigInteger.prototype.fromRadix = bnpFromRadix; // (protected) convert from radix string BigInteger.prototype.fromRadix = function (s, b) { this.fromInt(0); if (b == null) { b = 10; } var cs = this.chunkSize(b); var d = Math.pow(b, cs); var mi = false; var j = 0; var w = 0; for (var i = 0; i < s.length; ++i) { var x = intAt(s, i); if (x < 0) { if (s.charAt(i) == "-" && this.signum() == 0) { mi = true; } continue; } w = b * w + x; if (++j >= cs) { this.dMultiply(d); this.dAddOffset(w, 0); j = 0; w = 0; } } if (j > 0) { this.dMultiply(Math.pow(b, j)); this.dAddOffset(w, 0); } if (mi) { BigInteger.ZERO.subTo(this, this); } }; // BigInteger.prototype.fromNumber = bnpFromNumber; // (protected) alternate constructor BigInteger.prototype.fromNumber = function (a, b, c) { if ("number" == typeof b) { // new BigInteger(int,int,RNG) if (a < 2) { this.fromInt(1); } else { this.fromNumber(a, c); if (!this.testBit(a - 1)) { // force MSB set this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); } if (this.isEven()) { this.dAddOffset(1, 0); } // force odd while (!this.isProbablePrime(b)) { this.dAddOffset(2, 0); if (this.bitLength() > a) { this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); } } } } else { // new BigInteger(int,RNG) var x = []; var t = a & 7; x.length = (a >> 3) + 1; b.nextBytes(x); if (t > 0) { x[0] &= ((1 << t) - 1); } else { x[0] = 0; } this.fromString(x, 256); } }; // BigInteger.prototype.bitwiseTo = bnpBitwiseTo; // (protected) r = this op a (bitwise) BigInteger.prototype.bitwiseTo = function (a, op, r) { var i; var f; var m = Math.min(a.t, this.t); for (i = 0; i < m; ++i) { r[i] = op(this[i], a[i]); } if (a.t < this.t) { f = a.s & this.DM; for (i = m; i < this.t; ++i) { r[i] = op(this[i], f); } r.t = this.t; } else { f = this.s & this.DM; for (i = m; i < a.t; ++i) { r[i] = op(f, a[i]); } r.t = a.t; } r.s = op(this.s, a.s); r.clamp(); }; // BigInteger.prototype.changeBit = bnpChangeBit; // (protected) this op (1<<n) BigInteger.prototype.changeBit = function (n, op) { var r = BigInteger.ONE.shiftLeft(n); this.bitwiseTo(r, op, r); return r; }; // BigInteger.prototype.addTo = bnpAddTo; // (protected) r = this + a BigInteger.prototype.addTo = function (a, r) { var i = 0; var c = 0; var m = Math.min(a.t, this.t); while (i < m) { c += this[i] + a[i]; r[i++] = c & this.DM; c >>= this.DB; } if (a.t < this.t) { c += a.s; while (i < this.t) { c += this[i]; r[i++] = c & this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while (i < a.t) { c += a[i]; r[i++] = c & this.DM; c >>= this.DB; } c += a.s; } r.s = (c < 0) ? -1 : 0; if (c > 0) { r[i++] = c; } else if (c < -1) { r[i++] = this.DV + c; } r.t = i; r.clamp(); }; // BigInteger.prototype.dMultiply = bnpDMultiply; // (protected) this *= n, this >= 0, 1 < n < DV BigInteger.prototype.dMultiply = function (n) { this[this.t] = this.am(0, n - 1, this, 0, 0, this.t); ++this.t; this.clamp(); }; // BigInteger.prototype.dAddOffset = bnpDAddOffset; // (protected) this += n << w words, this >= 0 BigInteger.prototype.dAddOffset = function (n, w) { if (n == 0) { return; } while (this.t <= w) { this[this.t++] = 0; } this[w] += n; while (this[w] >= this.DV) { this[w] -= this.DV; if (++w >= this.t) { this[this.t++] = 0; } ++this[w]; } }; // BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; // (protected) r = lower n words of "this * a", a.t <= n // "this" should be the larger one if appropriate. BigInteger.prototype.multiplyLowerTo = function (a, n, r) { var i = Math.min(this.t + a.t, n); r.s = 0; // assumes a,this >= 0 r.t = i; while (i > 0) { r[--i] = 0; } for (var j = r.t - this.t; i < j; ++i) { r[i + this.t] = this.am(0, a[i], r, i, 0, this.t); } for (var j = Math.min(a.t, n); i < j; ++i) { this.am(0, a[i], r, i, 0, n - i); } r.clamp(); }; // BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. BigInteger.prototype.multiplyUpperTo = function (a, n, r) { --n; var i = r.t = this.t + a.t - n; r.s = 0; // assumes a,this >= 0 while (--i >= 0) { r[i] = 0; } for (i = Math.max(n - this.t, 0); i < a.t; ++i) { r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n); } r.clamp(); r.drShiftTo(1, r); }; // BigInteger.prototype.modInt = bnpModInt; // (protected) this % n, n < 2^26 BigInteger.prototype.modInt = function (n) { if (n <= 0) { return 0; } var d = this.DV % n; var r = (this.s < 0) ? n - 1 : 0; if (this.t > 0) { if (d == 0) { r = this[0] % n; } else { for (var i = this.t - 1; i >= 0; --i) { r = (d * r + this[i]) % n; } } } return r; }; // BigInteger.prototype.millerRabin = bnpMillerRabin; // (protected) true if probably prime (HAC 4.24, Miller-Rabin) BigInteger.prototype.millerRabin = function (t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if (k <= 0) { return false; } var r = n1.shiftRight(k); t = (t + 1) >> 1; if (t > lowprimes.length) { t = lowprimes.length; } var a = nbi(); for (var i = 0; i < t; ++i) { // Pick bases at random, instead of starting at 2 a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]); var y = a.modPow(r, this); if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while (j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2, this); if (y.compareTo(BigInteger.ONE) == 0) { return false; } } if (y.compareTo(n1) != 0) { return false; } } } return true; }; // BigInteger.prototype.square = bnSquare; // (public) this^2 BigInteger.prototype.square = function () { var r = nbi(); this.squareTo(r); return r; }; //#region ASYNC // Public API method BigInteger.prototype.gcda = function (a, callback) { var x = (this.s < 0) ? this.negate() : this.clone(); var y = (a.s < 0) ? a.negate() : a.clone(); if (x.compareTo(y) < 0) { var t = x; x = y; y = t; } var i = x.getLowestSetBit(); var g = y.getLowestSetBit(); if (g < 0) { callback(x); return; } if (i < g) { g = i; } if (g > 0) { x.rShiftTo(g, x); y.rShiftTo(g, y); } // Workhorse of the algorithm, gets called 200 - 800 times per 512 bit keygen. var gcda1 = function () { if ((i = x.getLowestSetBit()) > 0) { x.rShiftTo(i, x); } if ((i = y.getLowestSetBit()) > 0) { y.rShiftTo(i, y); } if (x.compareTo(y) >= 0) { x.subTo(y, x); x.rShiftTo(1, x); } else { y.subTo(x, y); y.rShiftTo(1, y); } if (!(x.signum() > 0)) { if (g > 0) { y.lShiftTo(g, y); } setTimeout(function () { callback(y); }, 0); // escape } else { setTimeout(gcda1, 0); } }; setTimeout(gcda1, 10); }; // (protected) alternate constructor BigInteger.prototype.fromNumberAsync = function (a, b, c, callback) { if ("number" == typeof b) { if (a < 2) { this.fromInt(1); } else { this.fromNumber(a, c); if (!this.testBit(a - 1)) { this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); } if (this.isEven()) { this.dAddOffset(1, 0); } var bnp_1 = this; var bnpfn1_1 = function () { bnp_1.dAddOffset(2, 0); if (bnp_1.bitLength() > a) { bnp_1.subTo(BigInteger.ONE.shiftLeft(a - 1), bnp_1); } if (bnp_1.isProbablePrime(b)) { setTimeout(function () { callback(); }, 0); // escape } else { setTimeout(bnpfn1_1, 0); } }; setTimeout(bnpfn1_1, 0); } } else { var x = []; var t = a & 7; x.length = (a >> 3) + 1; b.nextBytes(x); if (t > 0) { x[0] &= ((1 << t) - 1); } else { x[0] = 0; } this.fromString(x, 256); } }; return BigInteger; }()); //#region REDUCERS //#region NullExp var NullExp = /** @class */ (function () { function NullExp() { } // NullExp.prototype.convert = nNop; NullExp.prototype.convert = function (x) { return x; }; // NullExp.prototype.revert = nNop; NullExp.prototype.revert = function (x) { return x; }; // NullExp.prototype.mulTo = nMulTo; NullExp.prototype.mulTo = function (x, y, r) { x.multiplyTo(y, r); }; // NullExp.prototype.sqrTo = nSqrTo; NullExp.prototype.sqrTo = function (x, r) { x.squareTo(r); }; return NullExp; }()); // Modular reduction using "classic" algorithm var Classic = /** @class */ (function () { function Classic(m) { this.m = m; } // Classic.prototype.convert = cConvert; Classic.prototype.convert = function (x) { if (x.s < 0 || x.compareTo(this.m) >= 0) { return x.mod(this.m); } else { return x; } }; // Classic.prototype.revert = cRevert; Classic.prototype.revert = function (x) { return x; }; // Classic.prototype.reduce = cReduce; Classic.prototype.reduce = function (x) { x.divRemTo(this.m, null, x); }; // Classic.prototype.mulTo = cMulTo; Classic.prototype.mulTo = function (x, y, r) { x.multiplyTo(y, r); this.reduce(r); }; // Classic.prototype.sqrTo = cSqrTo; Classic.prototype.sqrTo = function (x, r) { x.squareTo(r); this.reduce(r); }; return Classic; }()); //#endregion //#region Montgomery // Montgomery reduction var Montgomery = /** @class */ (function () { function Montgomery(m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp & 0x7fff; this.mph = this.mp >> 15; this.um = (1 << (m.DB - 15)) - 1; this.mt2 = 2 * m.t; } // Montgomery.prototype.convert = montConvert; // xR mod m Montgomery.prototype.convert = function (x) { var r = nbi(); x.abs().dlShiftTo(this.m.t, r); r.divRemTo(this.m, null, r); if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) { this.m.subTo(r, r); } return r; }; // Montgomery.prototype.revert = montRevert; // x/R mod m Montgomery.prototype.revert = function (x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }; // Montgomery.prototype.reduce = montReduce; // x = x/R mod m (HAC 14.32) Montgomery.prototype.reduce = function (x) { while (x.t <= this.mt2) { // pad x so am has enough room later x[x.t++] = 0; } for (var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV var j = x[i] & 0x7fff; var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM; // use am to combine the multiply-shift-add into one call j = i + this.m.t; x[j] += this.m.am(0, u0, x, i, 0, this.m.t); // propagate carry while (x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } } x.clamp(); x.drShiftTo(this.m.t, x); if (x.compareTo(this.m) >= 0) { x.subTo(this.m, x); } }; // Montgomery.prototype.mulTo = montMulTo; // r = "xy/R mod m"; x,y != r Montgomery.prototype.mulTo = function (x, y, r) { x.multiplyTo(y, r); this.reduce(r); }; // Montgomery.prototype.sqrTo = montSqrTo; // r = "x^2/R mod m"; x != r Montgomery.prototype.sqrTo = function (x, r) { x.squareTo(r); this.reduce(r); }; return Montgomery; }()); //#endregion Montgomery //#region Barrett // Barrett modular reduction var Barrett = /** @class */ (function () { function Barrett(m) { this.m = m; // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); this.mu = this.r2.divide(m); } // Barrett.prototype.convert = barrettConvert; Barrett.prototype.convert = function (x) { if (x.s < 0 || x.t > 2 * this.m.t) { return x.mod(this.m); } else if (x.compareTo(this.m) < 0) { return x; } else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } }; // Barrett.prototype.revert = barrettRevert; Barrett.prototype.revert = function (x) { return x; }; // Barrett.prototype.reduce = barrettReduce; // x = x mod m (HAC 14.42) Barrett.prototype.reduce = function (x) { x.drShiftTo(this.m.t - 1, this.r2); if (x.t > this.m.t + 1) { x.t = this.m.t + 1; x.clamp(); } this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); while (x.compareTo(this.r2) < 0) { x.dAddOffset(1, this.m.t + 1); } x.subTo(this.r2, x); while (x.compareTo(this.m) >= 0) { x.subTo(this.m, x); } }; // Barrett.prototype.mulTo = barrettMulTo; // r = x*y mod m; x,y != r Barrett.prototype.mulTo = function (x, y, r) { x.multiplyTo(y, r); this.reduce(r); }; // Barrett.prototype.sqrTo = barrettSqrTo; // r = x^2 mod m; x != r Barrett.prototype.sqrTo = function (x, r) { x.squareTo(r); this.reduce(r); }; return Barrett; }()); //#endregion //#endregion REDUCERS // return new, unset BigInteger function nbi() { return new BigInteger(null); } function parseBigInt(str, r) { return new BigInteger(str, r); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i, x, w, j, c, n) { while (--n >= 0) { var v = x * this[i++] + w[j] + c; c = Math.floor(v / 0x4000000); w[j++] = v & 0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i, x, w, j, c, n) { var xl = x & 0x7fff; var xh = x >> 15; while (--n >= 0) { var l = this[i] & 0x7fff; var h = this[i++] >> 15; var m = xh * l + h * xl; l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff); c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); w[j++] = l & 0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i, x, w, j, c, n) { var xl = x & 0x3fff; var xh = x >> 14; while (--n >= 0) { var l = this[i] & 0x3fff; var h = this[i++] >> 14; var m = xh * l + h * xl; l = xl * l + ((m & 0x3fff) << 14) + w[j] + c; c = (l >> 28) + (m >> 14) + xh * h; w[j++] = l & 0xfffffff; } return c; } if (j_lm && (navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if (j_lm && (navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1 << dbits) - 1); BigInteger.prototype.DV = (1 << dbits); var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2, BI_FP); BigInteger.prototype.F1 = BI_FP - dbits; BigInteger.prototype.F2 = 2 * dbits - BI_FP; // Digit conversions var BI_RC = []; var rr; var vv; rr = "0".charCodeAt(0); for (vv = 0; vv <= 9; ++vv) { BI_RC[rr++] = vv; } rr = "a".charCodeAt(0); for (vv = 10; vv < 36; ++vv) { BI_RC[rr++] = vv; } rr = "A".charCodeAt(0); for (vv = 10; vv < 36; ++vv) { BI_RC[rr++] = vv; } function intAt(s, i) { var c = BI_RC[s.charCodeAt(i)]; return (c == null) ? -1 : c; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // returns bit length of the integer x function nbits(x) { var r = 1; var t; if ((t = x >>> 16) != 0) { x = t; r += 16; } if ((t = x >> 8) != 0) { x = t; r += 8; } if ((t = x >> 4) != 0) { x = t; r += 4; } if ((t = x >> 2) != 0) { x = t; r += 2; } if ((t = x >> 1) != 0) { x = t; r += 1; } return r; } // "constants" BigInteger.ZERO = nbv(0); BigInteger.ONE = nbv(1); // prng4.js - uses Arcfour as a PRNG var Arcfour = /** @class */ (function () { function Arcfour() { this.i = 0; this.j = 0; this.S = []; } // Arcfour.prototype.init = ARC4init; // Initialize arcfour context from key, an array of ints, each from [0..255] Arcfour.prototype.init = function (key) { var i; var j; var t; for (i = 0; i < 256; ++i) { this.S[i] = i; } j = 0; for (i = 0; i < 256; ++i) { j = (j + this.S[i] + key[i % key.length]) & 255; t = this.S[i]; this.S[i] = this.S[j]; this.S[j] = t; } this.i = 0; this.j = 0; }; // Arcfour.prototype.next = ARC4next; Arcfour.prototype.next = function () { var t; this.i = (this.i + 1) & 255; this.j = (this.j + this.S[this.i]) & 255; t = this.S[this.i]; this.S[this.i] = this.S[this.j]; this.S[this.j] = t; return this.S[(t + this.S[this.i]) & 255]; }; return Arcfour; }()); // Plug in your RNG constructor here function prng_newstate() { return new Arcfour(); } // Pool size must be a multiple of 4 and greater than 32. // An array of bytes the size of the pool will be passed to init() var rng_psize = 256; // Random number generator - requires a PRNG backend, e.g. prng4.js var rng_state; var rng_pool = null; var rng_pptr; // Initialize the pool with junk if needed. if (rng_pool == null) { rng_pool = []; rng_pptr = 0; var t = void 0; if (window.crypto && window.crypto.getRandomValues) { // Extract entropy (2048 bits) from RNG if available var z = new Uint32Array(256); window.crypto.getRandomValues(z); for (t = 0; t < z.length; ++t) { rng_pool[rng_pptr++] = z[t] & 255; } } // Use mouse events for entropy, if we do not have enough entropy by the time // we need it, entropy will be generated by Math.random. var onMouseMoveListener_1 = function (ev) { this.count = this.count || 0; if (this.count >= 256 || rng_pptr >= rng_psize) { if (window.removeEventListener) { window.removeEventListener("mousemove", onMouseMoveListener_1, false); } else if (window.detachEvent) { window.detachEvent("onmousemove", onMouseMoveListener_1); } return; } try { var mouseCoordinates = ev.x + ev.y; rng_pool[rng_pptr++] = mouseCoordinates & 255; this.count += 1; } catch (e) { // Sometimes Firefox will deny permission to access event properties for some reason. Ignore. } }; if (window.addEventListener) { window.addEventListener("mousemove", onMouseMoveListener_1, false); } else if (window.attachEvent) { window.attachEvent("onmousemove", onMouseMoveListener_1); } } function rng_get_byte() { if (rng_state == null) { rng_state = prng_newstate(); // At this point, we may not have collected enough entropy. If not, fall back to Math.random while (rng_pptr < rng_psize) { var random = Math.floor(65536 * Math.random()); rng_pool[rng_pptr++] = random & 255; } rng_state.init(rng_pool); for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) { rng_pool[rng_pptr] = 0; } rng_pptr = 0; } // TODO: allow reseeding after first request return rng_state.next(); } var SecureRandom = /** @class */ (function () { function SecureRandom() { } SecureRandom.prototype.nextBytes = function (ba) { for (var i = 0; i < ba.length; ++i) { ba[i] = rng_get_byte(); } }; return SecureRandom; }()); // Depends on jsbn.js and rng.js // function linebrk(s,n) { // var ret = ""; // var i = 0; // while(i + n < s.length) { // ret += s.substring(i,i+n) + "\n"; // i += n; // } // return ret + s.substring(i,s.length); // } // function byte2Hex(b) { // if(b < 0x10) // return "0" + b.toString(16); // else // return b.toString(16); // } function pkcs1pad1(s, n) { if (n < s.length + 22) { console.error("Message too long for RSA"); return null; } var len = n - s.length - 6; var filler = ""; for (var f = 0; f < len; f += 2) { filler += "ff"; } var m = "0001" + filler + "00" + s; return parseBigInt(m, 16); } // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint function pkcs1pad2(s, n) { if (n < s.length + 11) { // TODO: fix for utf-8 console.error("Message too long for RSA"); return null; } var ba = []; var i = s.length - 1; while (i >= 0 && n > 0) { var c = s.charCodeAt(i--); if (c < 128) { // encode using utf-8 ba[--n] = c; } else if ((c > 127) && (c < 2048)) { ba[--n] = (c & 63) | 128; ba[--n] = (c >> 6) | 192; } else { ba[--n] = (c & 63) | 128; ba[--n] = ((c >> 6) & 63) | 128; ba[--n] = (c >> 12) | 224; } } ba[--n] = 0; var rng = new SecureRandom(); var x = []; while (n > 2) { // random non-zero pad x[0] = 0; while (x[0] == 0) { rng.nextBytes(x); } ba[--n] = x[0]; } ba[--n] = 2; ba[--n] = 0; return new BigInteger(ba); } // "empty" RSA key constructor var RSAKey = /** @class */ (function () { function RSAKey() { this.n = null; this.e = 0; this.d = null; this.p = null; this.q = null; this.dmp1 = null; this.dmq1 = null; this.coeff = null; } //#region PROTECTED // protected // RSAKey.prototype.doPublic = RSADoPublic; // Perform raw public operation on "x": return x^e (mod n) RSAKey.prototype.doPublic = function (x) { return x.modPowInt(this.e, this.n); }; // RSAKey.prototype.doPrivate = RSADoPrivate; // Perform raw private operation on "x": return x^d (mod n) RSAKey.prototype.doPrivate = function (x) { if (this.p == null || this.q == null) { return x.modPow(this.d, this.n); } // TODO: re-calculate any missing CRT params var xp = x.mod(this.p).modPow(this.dmp1, this.p); var xq = x.mod(this.q).modPow(this.dmq1, this.q); while (xp.compareTo(xq) < 0) { xp = xp.add(this.p); } return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq); }; //#endregion PROTECTED //#region PUBLIC // RSAKey.prototype.setPublic = RSASetPublic; // Set the public key fields N and e from hex strings RSAKey.prototype.setPublic = function (N, E) { if (N != null && E != null && N.length > 0 && E.length > 0) { this.n = parseBigInt(N, 16); this.e = parseInt(E, 16); } else { console.error("Invalid RSA public key"); } }; // RSAKey.prototype.encrypt = RSAEncrypt; // Return the PKCS#1 RSA encryption of "text" as an even-length hex string RSAKey.prototype.encrypt = function (text) { var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3); if (m == null) { return null; } var c = this.doPublic(m); if (c == null) { return null; } var h = c.toString(16); if ((h.length & 1) == 0) { return h; } else { return "0" + h; } }; // RSAKey.prototype.setPrivate = RSASetPrivate; // Set the private key fields N, e, and d from hex strings RSAKey.prototype.setPrivate = function (N, E, D) { if (N != null && E != null && N.length > 0 && E.length > 0) { this.n = parseBigInt(N, 16); this.e = parseInt(E, 16); this.d = parseBigInt(D, 16); } else { console.error("Invalid RSA private key"); } }; // RSAKey.prototype.setPrivateEx = RSASetPrivateEx; // Set the private key fields N, e, d and CRT params from hex strings RSAKey.prototype.setPrivateEx = function (N, E, D, P, Q, DP, DQ, C) { if (N != null && E != null && N.length > 0 && E.length > 0) { this.n = parseBigInt(N, 16); this.e = parseInt(E, 16); this.d = parseBigInt(D, 16); this.p = parseBigInt(P, 16); this.q = parseBigInt(Q, 16); this.dmp1 = parseBigInt(DP, 16); this.dmq1 = parseBigInt(DQ, 16); this.coeff = parseBigInt(C, 16); } else { console.error("Invalid RSA private key"); } }; // RSAKey.prototype.generate = RSAGenerate; // Generate a new random private key B bits long, using public expt E RSAKey.prototype.generate = function (B, E) { var rng = new SecureRandom(); var qs = B >> 1; this.e = parseInt(E, 16); var ee = new BigInteger(E, 16); for (;;) { for (;;) { this.p = new BigInteger(B - qs, 1, rng); if (this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) { break; } } for (;;) { this.q = new BigInteger(qs, 1, rng); if (this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) { break; } } if (this.p.compareTo(this.q) <= 0) { var t = this.p; this.p = this.q; this.q = t; } var p1 = this.p.subtract(BigInteger.ONE); var q1 = this.q.subtract(BigInteger.ONE); var phi = p1.multiply(q1); if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) { this.n = this.p.multiply(this.q); this.d = ee.modInverse(phi); this.dmp1 = this.d.mod(p1); this.dmq1 = this.d.mod(q1); this.coeff = this.q.modInverse(this.p); break; } } }; // RSAKey.prototype.decrypt = RSADecrypt; // Return the PKCS#1 RSA decryption of "ctext". // "ctext" is an even-length hex string and the output is a plain string. RSAKey.prototype.decrypt = function (ctext) { var c = parseBigInt(ctext, 16); var m = this.doPrivate(c); if (m == null) { return null; } return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3); }; // Generate a new random private key B bits long, using public expt E RSAKey.prototype.generateAsync = function (B, E, callback) { var rng = new SecureRandom(); var qs = B >> 1; this.e = parseInt(E, 16); var ee = new BigInteger(E, 16); var rsa = this; // These functions have non-descript names because they were originally for(;;) loops. // I don't know about cryptography to give them better names than loop1-4. var loop1 = function () { var loop4 = function () { if (rsa.p.compareTo(rsa.q) <= 0) { var t = rsa.p; rsa.p = rsa.q; rsa.q = t; } var p1 = rsa.p.subtract(BigInteger.ONE); var q1 = rsa.q.subtract(BigInteger.ONE); var phi = p1.multiply(q1); if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) { rsa.n = rsa.p.multiply(rsa.q); rsa.d = ee.modInverse(phi); rsa.dmp1 = rsa.d.mod(p1); rsa.dmq1 = rsa.d.mod(q1); rsa.coeff = rsa.q.modInverse(rsa.p); setTimeout(function () { callback(); }, 0); // escape } else { setTimeout(loop1, 0); } }; var loop3 = function () { rsa.q = nbi(); rsa.q.fromNumberAsync(qs, 1, rng, function () { rsa.q.subtract(BigInteger.ONE).gcda(ee, function (r) { if (r.compareTo(BigInteger.ONE) == 0 && rsa.q.isProbablePrime(10)) { setTimeout(loop4, 0); } else { setTimeout(loop3, 0); } }); }); }; var loop2 = function () { rsa.p = nbi(); rsa.p.fromNumberAsync(B - qs, 1, rng, function () { rsa.p.subtract(BigInteger.ONE).gcda(ee, function (r) { if (r.compareTo(BigInteger.ONE) == 0 && rsa.p.isProbablePrime(10)) { setTimeout(loop3, 0); } else { setTimeout(loop2, 0); } }); }); }; setTimeout(loop2, 0); }; setTimeout(loop1, 0); }; RSAKey.prototype.sign = function (text, digestMethod, digestName) { var header = getDigestHeader(digestName); var digest = header + digestMethod(text).toString(); var m = pkcs1pad1(digest, this.n.bitLength() / 4); if (m == null) { return null; } var c = this.doPrivate(m); if (c == null) { return null; } var h = c.toString(16); if ((h.length & 1) == 0) { return h; } else { return "0" + h; } }; RSAKey.prototype.verify = function (text, signature, digestMethod) { var c = parseBigInt(signature, 16); var m = this.doPublic(c); if (m == null) { return null; } var unpadded = m.toString(16).replace(/^1f+00/, ""); var digest = removeDigestHeader(unpadded); return digest == digestMethod(text).toString(); }; return RSAKey; }()); // Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext function pkcs1unpad2(d, n) { var b = d.toByteArray(); var i = 0; while (i < b.length && b[i] == 0) { ++i; } if (b.length - i != n - 1 || b[i] != 2) { return null; } ++i; while (b[i] != 0) { if (++i >= b.length) { return null; } } var ret = ""; while (++i < b.length) { var c = b[i] & 255; if (c < 128) { // utf-8 decode ret += String.fromCharCode(c); } else if ((c > 191) && (c < 224)) { ret += String.fromCharCode(((c & 31) << 6) | (b[i + 1] & 63)); ++i; } else { ret += String.fromCharCode(((c & 15) << 12) | ((b[i + 1] & 63) << 6) | (b[i + 2] & 63)); i += 2; } } return ret; } // https://tools.ietf.org/html/rfc3447#page-43 var DIGEST_HEADERS = { md2: "3020300c06082a864886f70d020205000410", md5: "3020300c06082a864886f70d020505000410", sha1: "3021300906052b0e03021a05000414", sha224: "302d300d06096086480165030402040500041c", sha256: "3031300d060960864801650304020105000420", sha384: "3041300d060960864801650304020205000430", sha512: "3051300d060960864801650304020305000440", ripemd160: "3021300906052b2403020105000414", }; function getDigestHeader(name) { return DIGEST_HEADERS[name] || ""; } function removeDigestHeader(str) { for (var name_1 in DIGEST_HEADERS) { if (DIGEST_HEADERS.hasOwnProperty(name_1)) { var header = DIGEST_HEADERS[name_1]; var len = header.length; if (str.substr(0, len) == header) { return str.substr(len); } } } return str; } // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string // function RSAEncryptB64(text) { // var h = this.encrypt(text); // if(h) return hex2b64(h); else return null; // } // public // RSAKey.prototype.encrypt_b64 = RSAEncryptB64; /*! Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0 */ var YAHOO = {}; YAHOO.lang = { /** * Utility to set up the prototype, constructor and superclass properties to * support an inheritance strategy that can chain constructors and methods. * Static members will not be inherited. * * @method extend * @static * @param {Function} subc the object to modify * @param {Function} superc the object to inherit * @param {Object} overrides additional properties/methods to add to the * subclass prototype. These will override the * matching items obtained from the superclass * if present. */ extend: function(subc, superc, overrides) { if (! superc || ! subc) { throw new Error("YAHOO.lang.extend failed, please check that " + "all dependencies are included."); } var F = function() {}; F.prototype = superc.prototype; subc.prototype = new F(); subc.prototype.constructor = subc; subc.superclass = superc.prototype; if (superc.prototype.constructor == Object.prototype.constructor) { superc.prototype.constructor = superc; } if (overrides) { var i; for (i in overrides) { subc.prototype[i] = overrides[i]; } /* * IE will not enumerate native functions in a derived object even if the * function was overridden. This is a workaround for specific functions * we care about on the Object prototype. * @property _IEEnumFix * @param {Function} r the object to receive the augmentation * @param {Function} s the object that supplies the properties to augment * @static * @private */ var _IEEnumFix = function() {}, ADD = ["toString", "valueOf"]; try { if (/MSIE/.test(navigator.userAgent)) { _IEEnumFix = function(r, s) { for (i = 0; i < ADD.length; i = i + 1) { var fname = ADD[i], f = s[fname]; if (typeof f === 'function' && f != Object.prototype[fname]) { r[fname] = f; } } }; } } catch (ex) {} _IEEnumFix(subc.prototype, overrides); } } }; /* asn1-1.0.13.js (c) 2013-2017 Kenji Urushima | kjur.github.com/jsrsasign/license */ /** * @fileOverview * @name asn1-1.0.js * @author Kenji Urushima kenji.urushima@gmail.com * @version asn1 1.0.13 (2017-Jun-02) * @since jsrsasign 2.1 * @license <a href="https://kjur.github.io/jsrsasign/license/">MIT License</a> */ /** * kjur's class library name space * <p> * This name space provides following name spaces: * <ul> * <li>{@link KJUR.asn1} - ASN.1 primitive hexadecimal encoder</li> * <li>{@link KJUR.asn1.x509} - ASN.1 structure for X.509 certificate and CRL</li> * <li>{@link KJUR.crypto} - Java Cryptographic Extension(JCE) style MessageDigest/Signature * class and utilities</li> * </ul> * </p> * NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2. * @name KJUR * @namespace kjur's class library name space */ var KJUR = {}; /** * kjur's ASN.1 class library name space * <p> * This is ITU-T X.690 ASN.1 DER encoder class library and * class structure and methods is very similar to * org.bouncycastle.asn1 package of * well known BouncyCaslte Cryptography Library. * <h4>PROVIDING ASN.1 PRIMITIVES</h4> * Here are ASN.1 DER primitive classes. * <ul> * <li>0x01 {@link KJUR.asn1.DERBoolean}</li> * <li>0x02 {@link KJUR.asn1.DERInteger}</li> * <li>0x03 {@link KJUR.asn1.DERBitString}</li> * <li>0x04 {@link KJUR.asn1.DEROctetString}</li> * <li>0x05 {@link KJUR.asn1.DERNull}</li> * <li>0x06 {@link KJUR.asn1.DERObjectIdentifier}</li> * <li>0x0a {@link KJUR.asn1.DEREnumerated}</li> * <li>0x0c {@link KJUR.asn1.DERUTF8String}</li> * <li>0x12 {@link KJUR.asn1.DERNumericString}</li> * <li>0x13 {@link KJUR.asn1.DERPrintableString}</li> * <li>0x14 {@link KJUR.asn1.DERTeletexString}</li> * <li>0x16 {@link KJUR.asn1.DERIA5String}</li> * <li>0x17 {@link KJUR.asn1.DERUTCTime}</li> * <li>0x18 {@link KJUR.asn1.DERGeneralizedTime}</li> * <li>0x30 {@link KJUR.asn1.DERSequence}</li> * <li>0x31 {@link KJUR.asn1.DERSet}</li> * </ul> * <h4>OTHER ASN.1 CLASSES</h4> * <ul> * <li>{@link KJUR.asn1.ASN1Object}</li> * <li>{@link KJUR.asn1.DERAbstractString}</li> * <li>{@link KJUR.asn1.DERAbstractTime}</li> * <li>{@link KJUR.asn1.DERAbstractStructured}</li> * <li>{@link KJUR.asn1.DERTaggedObject}</li> * </ul> * <h4>SUB NAME SPACES</h4> * <ul> * <li>{@link KJUR.asn1.cades} - CAdES long term signature format</li> * <li>{@link KJUR.asn1.cms} - Cryptographic Message Syntax</li> * <li>{@link KJUR.asn1.csr} - Certificate Signing Request (CSR/PKCS#10)</li> * <li>{@link KJUR.asn1.tsp} - RFC 3161 Timestamping Protocol Format</li> * <li>{@link KJUR.asn1.x509} - RFC 5280 X.509 certificate and CRL</li> * </ul> * </p> * NOTE: Please ignore method summary and document of this namespace. * This caused by a bug of jsdoc2. * @name KJUR.asn1 * @namespace */ if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) KJUR.asn1 = {}; /** * ASN1 utilities class * @name KJUR.asn1.ASN1Util * @class ASN1 utilities class * @since asn1 1.0.2 */ KJUR.asn1.ASN1Util = new function() { this.integerToByteHex = function(i) { var h = i.toString(16); if ((h.length % 2) == 1) h = '0' + h; return h; }; this.bigIntToMinTwosComplementsHex = function(bigIntegerValue) { var h = bigIntegerValue.toString(16); if (h.substr(0, 1) != '-') { if (h.length % 2 == 1) { h = '0' + h; } else { if (! h.match(/^[0-7]/)) { h = '00' + h; } } } else { var hPos = h.substr(1); var xorLen = hPos.length; if (xorLen % 2 == 1) { xorLen += 1; } else { if (! h.match(/^[0-7]/)) { xorLen += 2; } } var hMask = ''; for (var i = 0; i < xorLen; i++) { hMask += 'f'; } var biMask = new BigInteger(hMask, 16); var biNeg = biMask.xor(bigIntegerValue).add(BigInteger.ONE); h = biNeg.toString(16).replace(/^-/, ''); } return h; }; /** * get PEM string from hexadecimal data and header string * @name getPEMStringFromHex * @memberOf KJUR.asn1.ASN1Util * @function * @param {String} dataHex hexadecimal string of PEM body * @param {String} pemHeader PEM header string (ex. 'RSA PRIVATE KEY') * @return {String} PEM formatted string of input data * @description * This method converts a hexadecimal string to a PEM string with * a specified header. Its line break will be CRLF("\r\n"). * @example * var pem = KJUR.asn1.ASN1Util.getPEMStringFromHex('616161', 'RSA PRIVATE KEY'); * // value of pem will be: * -----BEGIN PRIVATE KEY----- * YWFh * -----END PRIVATE KEY----- */ this.getPEMStringFromHex = function(dataHex, pemHeader) { return hextopem(dataHex, pemHeader); }; /** * generate ASN1Object specifed by JSON parameters * @name newObject * @memberOf KJUR.asn1.ASN1Util * @function * @param {Array} param JSON parameter to generate ASN1Object * @return {KJUR.asn1.ASN1Object} generated object * @since asn1 1.0.3 * @description * generate any ASN1Object specified by JSON param * including ASN.1 primitive or structured. * Generally 'param' can be described as follows: * <blockquote> * {TYPE-OF-ASNOBJ: ASN1OBJ-PARAMETER} * </blockquote> * 'TYPE-OF-ASN1OBJ' can be one of following symbols: * <ul> * <li>'bool' - DERBoolean</li> * <li>'int' - DERInteger</li> * <li>'bitstr' - DERBitString</li> * <li>'octstr' - DEROctetString</li> * <li>'null' - DERNull</li> * <li>'oid' - DERObjectIdentifier</li> * <li>'enum' - DEREnumerated</li> * <li>'utf8str' - DERUTF8String</li> * <li>'numstr' - DERNumericString</li> * <li>'prnstr' - DERPrintableString</li> * <li>'telstr' - DERTeletexString</li> * <li>'ia5str' - DERIA5String</li> * <li>'utctime' - DERUTCTime</li> * <li>'gentime' - DERGeneralizedTime</li> * <li>'seq' - DERSequence</li> * <li>'set' - DERSet</li> * <li>'tag' - DERTaggedObject</li> * </ul> * @example * newObject({'prnstr': 'aaa'}); * newObject({'seq': [{'int': 3}, {'prnstr': 'aaa'}]}) * // ASN.1 Tagged Object * newObject({'tag': {'tag': 'a1', * 'explicit': true, * 'obj': {'seq': [{'int': 3}, {'prnstr': 'aaa'}]}}}); * // more simple representation of ASN.1 Tagged Object * newObject({'tag': ['a1', * true, * {'seq': [ * {'int': 3}, * {'prnstr': 'aaa'}]} * ]}); */ this.newObject = function(param) { var _KJUR = KJUR, _KJUR_asn1 = _KJUR.asn1, _DERBoolean = _KJUR_asn1.DERBoolean, _DERInteger = _KJUR_asn1.DERInteger, _DERBitString = _KJUR_asn1.DERBitString, _DEROctetString = _KJUR_asn1.DEROctetString, _DERNull = _KJUR_asn1.DERNull, _DERObjectIdentifier = _KJUR_asn1.DERObjectIdentifier, _DEREnumerated = _KJUR_asn1.DEREnumerated, _DERUTF8String = _KJUR_asn1.DERUTF8String, _DERNumericString = _KJUR_asn1.DERNumericString, _DERPrintableString = _KJUR_asn1.DERPrintableString, _DERTeletexString = _KJUR_asn1.DERTeletexString, _DERIA5String = _KJUR_asn1.DERIA5String, _DERUTCTime = _KJUR_asn1.DERUTCTime, _DERGeneralizedTime = _KJUR_asn1.DERGeneralizedTime, _DERSequence = _KJUR_asn1.DERSequence, _DERSet = _KJUR_asn1.DERSet, _DERTaggedObject = _KJUR_asn1.DERTaggedObject, _newObject = _KJUR_asn1.ASN1Util.newObject; var keys = Object.keys(param); if (keys.length != 1) throw "key of param shall be only one."; var key = keys[0]; if (":bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:seq:set:tag:".indexOf(":" + key + ":") == -1) throw "undefined key: " + key; if (key == "bool") return new _DERBoolean(param[key]); if (key == "int") return new _DERInteger(param[key]); if (key == "bitstr") return new _DERBitString(param[key]); if (key == "octstr") return new _DEROctetString(param[key]); if (key == "null") return new _DERNull(param[key]); if (key == "oid") return new _DERObjectIdentifier(param[key]); if (key == "enum") return new _DEREnumerated(param[key]); if (key == "utf8str") return new _DERUTF8String(param[key]); if (key == "numstr") return new _DERNumericString(param[key]); if (key == "prnstr") return new _DERPrintableString(param[key]); if (key == "telstr") return new _DERTeletexString(param[key]); if (key == "ia5str") return new _DERIA5String(param[key]); if (key == "utctime") return new _DERUTCTime(param[key]); if (key == "gentime") return new _DERGeneralizedTime(param[key]); if (key == "seq") { var paramList = param[key]; var a = []; for (var i = 0; i < paramList.length; i++) { var asn1Obj = _newObject(paramList[i]); a.push(asn1Obj); } return new _DERSequence({'array': a}); } if (key == "set") { var paramList = param[key]; var a = []; for (var i = 0; i < paramList.length; i++) { var asn1Obj = _newObject(paramList[i]); a.push(asn1Obj); } return new _DERSet({'array': a}); } if (key == "tag") { var tagParam = param[key]; if (Object.prototype.toString.call(tagParam) === '[object Array]' && tagParam.length == 3) { var obj = _newObject(tagParam[2]); return new _DERTaggedObject({tag: tagParam[0], explicit: tagParam[1], obj: obj}); } else { var newParam = {}; if (tagParam.explicit !== undefined) newParam.explicit = tagParam.explicit; if (tagParam.tag !== undefined) newParam.tag = tagParam.tag; if (tagParam.obj === undefined) throw "obj shall be specified for 'tag'."; newParam.obj = _newObject(tagParam.obj); return new _DERTaggedObject(newParam); } } }; /** * get encoded hexadecimal string of ASN1Object specifed by JSON parameters * @name jsonToASN1HEX * @memberOf KJUR.asn1.ASN1Util * @function * @param {Array} param JSON parameter to generate ASN1Object * @return hexadecimal string of ASN1Object * @since asn1 1.0.4 * @description * As for ASN.1 object representation of JSON object, * please see {@link newObject}. * @example * jsonToASN1HEX({'prnstr': 'aaa'}); */ this.jsonToASN1HEX = function(param) { var asn1Obj = this.newObject(param); return asn1Obj.getEncodedHex(); }; }; /** * get dot noted oid number string from hexadecimal value of OID * @name oidHexToInt * @memberOf KJUR.asn1.ASN1Util * @function * @param {String} hex hexadecimal value of object identifier * @return {String} dot noted string of object identifier * @since jsrsasign 4.8.3 asn1 1.0.7 * @description * This static method converts from hexadecimal string representation of * ASN.1 value of object identifier to oid number string. * @example * KJUR.asn1.ASN1Util.oidHexToInt('550406') &rarr; "2.5.4.6" */ KJUR.asn1.ASN1Util.oidHexToInt = function(hex) { var s = ""; var i01 = parseInt(hex.substr(0, 2), 16); var i0 = Math.floor(i01 / 40); var i1 = i01 % 40; var s = i0 + "." + i1; var binbuf = ""; for (var i = 2; i < hex.length; i += 2) { var value = parseInt(hex.substr(i, 2), 16); var bin = ("00000000" + value.toString(2)).slice(- 8); binbuf = binbuf + bin.substr(1, 7); if (bin.substr(0, 1) == "0") { var bi = new BigInteger(binbuf, 2); s = s + "." + bi.toString(10); binbuf = ""; } } return s; }; /** * get hexadecimal value of object identifier from dot noted oid value * @name oidIntToHex * @memberOf KJUR.asn1.ASN1Util * @function * @param {String} oidString dot noted string of object identifier * @return {String} hexadecimal value of object identifier * @since jsrsasign 4.8.3 asn1 1.0.7 * @description * This static method converts from object identifier value string. * to hexadecimal string representation of it. * @example * KJUR.asn1.ASN1Util.oidIntToHex("2.5.4.6") &rarr; "550406" */ KJUR.asn1.ASN1Util.oidIntToHex = function(oidString) { var itox = function(i) { var h = i.toString(16); if (h.length == 1) h = '0' + h; return h; }; var roidtox = function(roid) { var h = ''; var bi = new BigInteger(roid, 10); var b = bi.toString(2); var padLen = 7 - b.length % 7; if (padLen == 7) padLen = 0; var bPad = ''; for (var i = 0; i < padLen; i++) bPad += '0'; b = bPad + b; for (var i = 0; i < b.length - 1; i += 7) { var b8 = b.substr(i, 7); if (i != b.length - 7) b8 = '1' + b8; h += itox(parseInt(b8, 2)); } return h; }; if (! oidString.match(/^[0-9.]+$/)) { throw "malformed oid string: " + oidString; } var h = ''; var a = oidString.split('.'); var i0 = parseInt(a[0]) * 40 + parseInt(a[1]); h += itox(i0); a.splice(0, 2); for (var i = 0; i < a.length; i++) { h += roidtox(a[i]); } return h; }; // ******************************************************************** // Abstract ASN.1 Classes // ******************************************************************** // ******************************************************************** /** * base class for ASN.1 DER encoder object * @name KJUR.asn1.ASN1Object * @class base class for ASN.1 DER encoder object * @property {Boolean} isModified flag whether internal data was changed * @property {String} hTLV hexadecimal string of ASN.1 TLV * @property {String} hT hexadecimal string of ASN.1 TLV tag(T) * @property {String} hL hexadecimal string of ASN.1 TLV length(L) * @property {String} hV hexadecimal string of ASN.1 TLV value(V) * @description */ KJUR.asn1.ASN1Object = function() { var hV = ''; /** * get hexadecimal ASN.1 TLV length(L) bytes from TLV value(V) * @name getLengthHexFromValue * @memberOf KJUR.asn1.ASN1Object# * @function * @return {String} hexadecimal string of ASN.1 TLV length(L) */ this.getLengthHexFromValue = function() { if (typeof this.hV == "undefined" || this.hV == null) { throw "this.hV is null or undefined."; } if (this.hV.length % 2 == 1) { throw "value hex must be even length: n=" + hV.length + ",v=" + this.hV; } var n = this.hV.length / 2; var hN = n.toString(16); if (hN.length % 2 == 1) { hN = "0" + hN; } if (n < 128) { return hN; } else { var hNlen = hN.length / 2; if (hNlen > 15) { throw "ASN.1 length too long to represent by 8x: n = " + n.toString(16); } var head = 128 + hNlen; return head.toString(16) + hN; } }; /** * get hexadecimal string of ASN.1 TLV bytes * @name getEncodedHex * @memberOf KJUR.asn1.ASN1Object# * @function * @return {String} hexadecimal string of ASN.1 TLV */ this.getEncodedHex = function() { if (this.hTLV == null || this.isModified) { this.hV = this.getFreshValueHex(); this.hL = this.getLengthHexFromValue(); this.hTLV = this.hT + this.hL + this.hV; this.isModified = false; //alert("first time: " + this.hTLV); } return this.hTLV; }; /** * get hexadecimal string of ASN.1 TLV value(V) bytes * @name getValueHex * @memberOf KJUR.asn1.ASN1Object# * @function * @return {String} hexadecimal string of ASN.1 TLV value(V) bytes */ this.getValueHex = function() { this.getEncodedHex(); return this.hV; }; this.getFreshValueHex = function() { return ''; }; }; // == BEGIN DERAbstractString ================================================ /** * base class for ASN.1 DER string classes * @name KJUR.asn1.DERAbstractString * @class base class for ASN.1 DER string classes * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) * @property {String} s internal string of value * @extends KJUR.asn1.ASN1Object * @description * <br/> * As for argument 'params' for constructor, you can specify one of * following properties: * <ul> * <li>str - specify initial ASN.1 value(V) by a string</li> * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li> * </ul> * NOTE: 'params' can be omitted. */ KJUR.asn1.DERAbstractString = function(params) { KJUR.asn1.DERAbstractString.superclass.constructor.call(this); /** * get string value of this string object * @name getString * @memberOf KJUR.asn1.DERAbstractString# * @function * @return {String} string value of this string object */ this.getString = function() { return this.s; }; /** * set value by a string * @name setString * @memberOf KJUR.asn1.DERAbstractString# * @function * @param {String} newS value by a string to set */ this.setString = function(newS) { this.hTLV = null; this.isModified = true; this.s = newS; this.hV = stohex(this.s); }; /** * set value by a hexadecimal string * @name setStringHex * @memberOf KJUR.asn1.DERAbstractString# * @function * @param {String} newHexString value by a hexadecimal string to set */ this.setStringHex = function(newHexString) { this.hTLV = null; this.isModified = true; this.s = null; this.hV = newHexString; }; this.getFreshValueHex = function() { return this.hV; }; if (typeof params != "undefined") { if (typeof params == "string") { this.setString(params); } else if (typeof params['str'] != "undefined") { this.setString(params['str']); } else if (typeof params['hex'] != "undefined") { this.setStringHex(params['hex']); } } }; YAHOO.lang.extend(KJUR.asn1.DERAbstractString, KJUR.asn1.ASN1Object); // == END DERAbstractString ================================================ // == BEGIN DERAbstractTime ================================================== /** * base class for ASN.1 DER Generalized/UTCTime class * @name KJUR.asn1.DERAbstractTime * @class base class for ASN.1 DER Generalized/UTCTime class * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'}) * @extends KJUR.asn1.ASN1Object * @description * @see KJUR.asn1.ASN1Object - superclass */ KJUR.asn1.DERAbstractTime = function(params) { KJUR.asn1.DERAbstractTime.superclass.constructor.call(this); // --- PRIVATE METHODS -------------------- this.localDateToUTC = function(d) { utc = d.getTime() + (d.getTimezoneOffset() * 60000); var utcDate = new Date(utc); return utcDate; }; /* * format date string by Data object * @name formatDate * @memberOf KJUR.asn1.AbstractTime; * @param {Date} dateObject * @param {string} type 'utc' or 'gen' * @param {boolean} withMillis flag for with millisections or not * @description * 'withMillis' flag is supported from asn1 1.0.6. */ this.formatDate = function(dateObject, type, withMillis) { var pad = this.zeroPadding; var d = this.localDateToUTC(dateObject); var year = String(d.getFullYear()); if (type == 'utc') year = year.substr(2, 2); var month = pad(String(d.getMonth() + 1), 2); var day = pad(String(d.getDate()), 2); var hour = pad(String(d.getHours()), 2); var min = pad(String(d.getMinutes()), 2); var sec = pad(String(d.getSeconds()), 2); var s = year + month + day + hour + min + sec; if (withMillis === true) { var millis = d.getMilliseconds(); if (millis != 0) { var sMillis = pad(String(millis), 3); sMillis = sMillis.replace(/[0]+$/, ""); s = s + "." + sMillis; } } return s + "Z"; }; this.zeroPadding = function(s, len) { if (s.length >= len) return s; return new Array(len - s.length + 1).join('0') + s; }; // --- PUBLIC METHODS -------------------- /** * get string value of this string object * @name getString * @memberOf KJUR.asn1.DERAbstractTime# * @function * @return {String} string value of this time object */ this.getString = function() { return this.s; }; /** * set value by a string * @name setString * @memberOf KJUR.asn1.DERAbstractTime# * @function * @param {String} newS value by a string to set such like "130430235959Z" */ this.setString = function(newS) { this.hTLV = null; this.isModified = true; this.s = newS; this.hV = stohex(newS); }; /** * set value by a Date object * @name setByDateValue * @memberOf KJUR.asn1.DERAbstractTime# * @function * @param {Integer} year year of date (ex. 2013) * @param {Integer} month month of date between 1 and 12 (ex. 12) * @param {Integer} day day of month * @param {Integer} hour hours of date * @param {Integer} min minutes of date * @param {Integer} sec seconds of date */ this.setByDateValue = function(year, month, day, hour, min, sec) { var dateObject = new Date(Date.UTC(year, month - 1, day, hour, min, sec, 0)); this.setByDate(dateObject); }; this.getFreshValueHex = function() { return this.hV; }; }; YAHOO.lang.extend(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object); // == END DERAbstractTime ================================================== // == BEGIN DERAbstractStructured ============================================ /** * base class for ASN.1 DER structured class * @name KJUR.asn1.DERAbstractStructured * @class base class for ASN.1 DER structured class * @property {Array} asn1Array internal array of ASN1Object * @extends KJUR.asn1.ASN1Object * @description * @see KJUR.asn1.ASN1Object - superclass */ KJUR.asn1.DERAbstractStructured = function(params) { KJUR.asn1.DERAbstractString.superclass.constructor.call(this); /** * set value by array of ASN1Object * @name setByASN1ObjectArray * @memberOf KJUR.asn1.DERAbstractStructured# * @function * @param {array} asn1ObjectArray array of ASN1Object to set */ this.setByASN1ObjectArray = function(asn1ObjectArray) { this.hTLV = null; this.isModified = true; this.asn1Array = asn1ObjectArray; }; /** * append an ASN1Object to internal array * @name appendASN1Object * @memberOf KJUR.asn1.DERAbstractStructured# * @function * @param {ASN1Object} asn1Object to add */ this.appendASN1Object = function(asn1Object) { this.hTLV = null; this.isModified = true; this.asn1Array.push(asn1Object); }; this.asn1Array = new Array(); if (typeof params != "undefined") { if (typeof params['array'] != "undefined") { this.asn1Array = params['array']; } } }; YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured, KJUR.asn1.ASN1Object); // ******************************************************************** // ASN.1 Object Classes // ******************************************************************** // ******************************************************************** /** * class for ASN.1 DER Boolean * @name KJUR.asn1.DERBoolean * @class class for ASN.1 DER Boolean * @extends KJUR.asn1.ASN1Object * @description * @see KJUR.asn1.ASN1Object - superclass */ KJUR.asn1.DERBoolean = function() { KJUR.asn1.DERBoolean.superclass.constructor.call(this); this.hT = "01"; this.hTLV = "0101ff"; }; YAHOO.lang.extend(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object); // ******************************************************************** /** * class for ASN.1 DER Integer * @name KJUR.asn1.DERInteger * @class class for ASN.1 DER Integer * @extends KJUR.asn1.ASN1Object * @description * <br/> * As for argument 'params' for constructor, you can specify one of * following properties: * <ul> * <li>int - specify initial ASN.1 value(V) by integer value</li> * <li>bigint - specify initial ASN.1 value(V) by BigInteger object</li> * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li> * </ul> * NOTE: 'params' can be omitted. */ KJUR.asn1.DERInteger = function(params) { KJUR.asn1.DERInteger.superclass.constructor.call(this); this.hT = "02"; /** * set value by Tom Wu's BigInteger object * @name setByBigInteger * @memberOf KJUR.asn1.DERInteger# * @function * @param {BigInteger} bigIntegerValue to set */ this.setByBigInteger = function(bigIntegerValue) { this.hTLV = null; this.isModified = true; this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue); }; /** * set value by integer value * @name setByInteger * @memberOf KJUR.asn1.DERInteger * @function * @param {Integer} integer value to set */ this.setByInteger = function(intValue) { var bi = new BigInteger(String(intValue), 10); this.setByBigInteger(bi); }; /** * set value by integer value * @name setValueHex * @memberOf KJUR.asn1.DERInteger# * @function * @param {String} hexadecimal string of integer value * @description * <br/> * NOTE: Value shall be represented by minimum octet length of * two's complement representation. * @example * new KJUR.asn1.DERInteger(123); * new KJUR.asn1.DERInteger({'int': 123}); * new KJUR.asn1.DERInteger({'hex': '1fad'}); */ this.setValueHex = function(newHexString) { this.hV = newHexString; }; this.getFreshValueHex = function() { return this.hV; }; if (typeof params != "undefined") { if (typeof params['bigint'] != "undefined") { this.setByBigInteger(params['bigint']); } else if (typeof params['int'] != "undefined") { this.setByInteger(params['int']); } else if (typeof params == "number") { this.setByInteger(params); } else if (typeof params['hex'] != "undefined") { this.setValueHex(params['hex']); } } }; YAHOO.lang.extend(KJUR.asn1.DERInteger, KJUR.asn1.ASN1Object); // ******************************************************************** /** * class for ASN.1 DER encoded BitString primitive * @name KJUR.asn1.DERBitString * @class class for ASN.1 DER encoded BitString primitive * @extends KJUR.asn1.ASN1Object * @description * <br/> * As for argument 'params' for constructor, you can specify one of * following properties: * <ul> * <li>bin - specify binary string (ex. '10111')</li> * <li>array - specify array of boolean (ex. [true,false,true,true])</li> * <li>hex - specify hexadecimal string of ASN.1 value(V) including unused bits</li> * <li>obj - specify {@link KJUR.asn1.ASN1Util.newObject} * argument for "BitString encapsulates" structure.</li> * </ul> * NOTE1: 'params' can be omitted.<br/> * NOTE2: 'obj' parameter have been supported since * asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).<br/> * @example * // default constructor * o = new KJUR.asn1.DERBitString(); * // initialize with binary string * o = new KJUR.asn1.DERBitString({bin: "1011"}); * // initialize with boolean array * o = new KJUR.asn1.DERBitString({array: [true,false,true,true]}); * // initialize with hexadecimal string (04 is unused bits) * o = new KJUR.asn1.DEROctetString({hex: "04bac0"}); * // initialize with ASN1Util.newObject argument for encapsulated * o = new KJUR.asn1.DERBitString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}}); * // above generates a ASN.1 data like this: * // BIT STRING, encapsulates { * // SEQUENCE { * // INTEGER 3 * // PrintableString 'aaa' * // } * // } */ KJUR.asn1.DERBitString = function(params) { if (params !== undefined && typeof params.obj !== "undefined") { var o = KJUR.asn1.ASN1Util.newObject(params.obj); params.hex = "00" + o.getEncodedHex(); } KJUR.asn1.DERBitString.superclass.constructor.call(this); this.hT = "03"; /** * set ASN.1 value(V) by a hexadecimal string including unused bits * @name setHexValueIncludingUnusedBits * @memberOf KJUR.asn1.DERBitString# * @function * @param {String} newHexStringIncludingUnusedBits */ this.setHexValueIncludingUnusedBits = function(newHexStringIncludingUnusedBits) { this.hTLV = null; this.isModified = true; this.hV = newHexStringIncludingUnusedBits; }; /** * set ASN.1 value(V) by unused bit and hexadecimal string of value * @name setUnusedBitsAndHexValue * @memberOf KJUR.asn1.DERBitString# * @function * @param {Integer} unusedBits * @param {String} hValue */ this.setUnusedBitsAndHexValue = function(unusedBits, hValue) { if (unusedBits < 0 || 7 < unusedBits) { throw "unused bits shall be from 0 to 7: u = " + unusedBits; } var hUnusedBits = "0" + unusedBits; this.hTLV = null; this.isModified = true; this.hV = hUnusedBits + hValue; }; /** * set ASN.1 DER BitString by binary string<br/> * @name setByBinaryString * @memberOf KJUR.asn1.DERBitString# * @function * @param {String} binaryString binary value string (i.e. '10111') * @description * Its unused bits will be calculated automatically by length of * 'binaryValue'. <br/> * NOTE: Trailing zeros '0' will be ignored. * @example * o = new KJUR.asn1.DERBitString(); * o.setByBooleanArray("01011"); */ this.setByBinaryString = function(binaryString) { binaryString = binaryString.replace(/0+$/, ''); var unusedBits = 8 - binaryString.length % 8; if (unusedBits == 8) unusedBits = 0; for (var i = 0; i <= unusedBits; i++) { binaryString += '0'; } var h = ''; for (var i = 0; i < binaryString.length - 1; i += 8) { var b = binaryString.substr(i, 8); var x = parseInt(b, 2).toString(16); if (x.length == 1) x = '0' + x; h += x; } this.hTLV = null; this.isModified = true; this.hV = '0' + unusedBits + h; }; /** * set ASN.1 TLV value(V) by an array of boolean<br/> * @name setByBooleanArray * @memberOf KJUR.asn1.DERBitString# * @function * @param {array} booleanArray array of boolean (ex. [true, false, true]) * @description * NOTE: Trailing falses will be ignored in the ASN.1 DER Object. * @example * o = new KJUR.asn1.DERBitString(); * o.setByBooleanArray([false, true, false, true, true]); */ this.setByBooleanArray = function(booleanArray) { var s = ''; for (var i = 0; i < booleanArray.length; i++) { if (booleanArray[i] == true) { s += '1'; } else { s += '0'; } } this.setByBinaryString(s); }; /** * generate an array of falses with specified length<br/> * @name newFalseArray * @memberOf KJUR.asn1.DERBitString * @function * @param {Integer} nLength length of array to generate * @return {array} array of boolean falses * @description * This static method may be useful to initialize boolean array. * @example * o = new KJUR.asn1.DERBitString(); * o.newFalseArray(3) &rarr; [false, false, false] */ this.newFalseArray = function(nLength) { var a = new Array(nLength); for (var i = 0; i < nLength; i++) { a[i] = false; } return a; }; this.getFreshValueHex = function() { return this.hV; }; if (typeof params != "undefined") { if (typeof params == "string" && params.toLowerCase().match(/^[0-9a-f]+$/)) { this.setHexValueIncludingUnusedBits(params); } else if (typeof params['hex'] != "undefined") { this.setHexValueIncludingUnusedBits(params['hex']); } else if (typeof params['bin'] != "undefined") { this.setByBinaryString(params['bin']); } else if (typeof params['array'] != "undefined") { this.setByBooleanArray(params['array']); } } }; YAHOO.lang.extend(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object); // ******************************************************************** /** * class for ASN.1 DER OctetString<br/> * @name KJUR.asn1.DEROctetString * @class class for ASN.1 DER OctetString * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) * @extends KJUR.asn1.DERAbstractString * @description * This class provides ASN.1 OctetString simple type.<br/> * Supported "params" attributes are: * <ul> * <li>str - to set a string as a value</li> * <li>hex - to set a hexadecimal string as a value</li> * <li>obj - to set a encapsulated ASN.1 value by JSON object * which is defined in {@link KJUR.asn1.ASN1Util.newObject}</li> * </ul> * NOTE: A parameter 'obj' have been supported * for "OCTET STRING, encapsulates" structure. * since asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25). * @see KJUR.asn1.DERAbstractString - superclass * @example * // default constructor * o = new KJUR.asn1.DEROctetString(); * // initialize with string * o = new KJUR.asn1.DEROctetString({str: "aaa"}); * // initialize with hexadecimal string * o = new KJUR.asn1.DEROctetString({hex: "616161"}); * // initialize with ASN1Util.newObject argument * o = new KJUR.asn1.DEROctetString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}}); * // above generates a ASN.1 data like this: * // OCTET STRING, encapsulates { * // SEQUENCE { * // INTEGER 3 * // PrintableString 'aaa' * // } * // } */ KJUR.asn1.DEROctetString = function(params) { if (params !== undefined && typeof params.obj !== "undefined") { var o = KJUR.asn1.ASN1Util.newObject(params.obj); params.hex = o.getEncodedHex(); } KJUR.asn1.DEROctetString.superclass.constructor.call(this, params); this.hT = "04"; }; YAHOO.lang.extend(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString); // ******************************************************************** /** * class for ASN.1 DER Null * @name KJUR.asn1.DERNull * @class class for ASN.1 DER Null * @extends KJUR.asn1.ASN1Object * @description * @see KJUR.asn1.ASN1Object - superclass */ KJUR.asn1.DERNull = function() { KJUR.asn1.DERNull.superclass.constructor.call(this); this.hT = "05"; this.hTLV = "0500"; }; YAHOO.lang.extend(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object); // ******************************************************************** /** * class for ASN.1 DER ObjectIdentifier * @name KJUR.asn1.DERObjectIdentifier * @class class for ASN.1 DER ObjectIdentifier * @param {Array} params associative array of parameters (ex. {'oid': '2.5.4.5'}) * @extends KJUR.asn1.ASN1Object * @description * <br/> * As for argument 'params' for constructor, you can specify one of * following properties: * <ul> * <li>oid - specify initial ASN.1 value(V) by a oid string (ex. 2.5.4.13)</li> * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li> * </ul> * NOTE: 'params' can be omitted. */ KJUR.asn1.DERObjectIdentifier = function(params) { var itox = function(i) { var h = i.toString(16); if (h.length == 1) h = '0' + h; return h; }; var roidtox = function(roid) { var h = ''; var bi = new BigInteger(roid, 10); var b = bi.toString(2); var padLen = 7 - b.length % 7; if (padLen == 7) padLen = 0; var bPad = ''; for (var i = 0; i < padLen; i++) bPad += '0'; b = bPad + b; for (var i = 0; i < b.length - 1; i += 7) { var b8 = b.substr(i, 7); if (i != b.length - 7) b8 = '1' + b8; h += itox(parseInt(b8, 2)); } return h; }; KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this); this.hT = "06"; /** * set value by a hexadecimal string * @name setValueHex * @memberOf KJUR.asn1.DERObjectIdentifier# * @function * @param {String} newHexString hexadecimal value of OID bytes */ this.setValueHex = function(newHexString) { this.hTLV = null; this.isModified = true; this.s = null; this.hV = newHexString; }; /** * set value by a OID string<br/> * @name setValueOidString * @memberOf KJUR.asn1.DERObjectIdentifier# * @function * @param {String} oidString OID string (ex. 2.5.4.13) * @example * o = new KJUR.asn1.DERObjectIdentifier(); * o.setValueOidString("2.5.4.13"); */ this.setValueOidString = function(oidString) { if (! oidString.match(/^[0-9.]+$/)) { throw "malformed oid string: " + oidString; } var h = ''; var a = oidString.split('.'); var i0 = parseInt(a[0]) * 40 + parseInt(a[1]); h += itox(i0); a.splice(0, 2); for (var i = 0; i < a.length; i++) { h += roidtox(a[i]); } this.hTLV = null; this.isModified = true; this.s = null; this.hV = h; }; /** * set value by a OID name * @name setValueName * @memberOf KJUR.asn1.DERObjectIdentifier# * @function * @param {String} oidName OID name (ex. 'serverAuth') * @since 1.0.1 * @description * OID name shall be defined in 'KJUR.asn1.x509.OID.name2oidList'. * Otherwise raise error. * @example * o = new KJUR.asn1.DERObjectIdentifier(); * o.setValueName("serverAuth"); */ this.setValueName = function(oidName) { var oid = KJUR.asn1.x509.OID.name2oid(oidName); if (oid !== '') { this.setValueOidString(oid); } else { throw "DERObjectIdentifier oidName undefined: " + oidName; } }; this.getFreshValueHex = function() { return this.hV; }; if (params !== undefined) { if (typeof params === "string") { if (params.match(/^[0-2].[0-9.]+$/)) { this.setValueOidString(params); } else { this.setValueName(params); } } else if (params.oid !== undefined) { this.setValueOidString(params.oid); } else if (params.hex !== undefined) { this.setValueHex(params.hex); } else if (params.name !== undefined) { this.setValueName(params.name); } } }; YAHOO.lang.extend(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object); // ******************************************************************** /** * class for ASN.1 DER Enumerated * @name KJUR.asn1.DEREnumerated * @class class for ASN.1 DER Enumerated * @extends KJUR.asn1.ASN1Object * @description * <br/> * As for argument 'params' for constructor, you can specify one of * following properties: * <ul> * <li>int - specify initial ASN.1 value(V) by integer value</li> * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li> * </ul> * NOTE: 'params' can be omitted. * @example * new KJUR.asn1.DEREnumerated(123); * new KJUR.asn1.DEREnumerated({int: 123}); * new KJUR.asn1.DEREnumerated({hex: '1fad'}); */ KJUR.asn1.DEREnumerated = function(params) { KJUR.asn1.DEREnumerated.superclass.constructor.call(this); this.hT = "0a"; /** * set value by Tom Wu's BigInteger object * @name setByBigInteger * @memberOf KJUR.asn1.DEREnumerated# * @function * @param {BigInteger} bigIntegerValue to set */ this.setByBigInteger = function(bigIntegerValue) { this.hTLV = null; this.isModified = true; this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue); }; /** * set value by integer value * @name setByInteger * @memberOf KJUR.asn1.DEREnumerated# * @function * @param {Integer} integer value to set */ this.setByInteger = function(intValue) { var bi = new BigInteger(String(intValue), 10); this.setByBigInteger(bi); }; /** * set value by integer value * @name setValueHex * @memberOf KJUR.asn1.DEREnumerated# * @function * @param {String} hexadecimal string of integer value * @description * <br/> * NOTE: Value shall be represented by minimum octet length of * two's complement representation. */ this.setValueHex = function(newHexString) { this.hV = newHexString; }; this.getFreshValueHex = function() { return this.hV; }; if (typeof params != "undefined") { if (typeof params['int'] != "undefined") { this.setByInteger(params['int']); } else if (typeof params == "number") { this.setByInteger(params); } else if (typeof params['hex'] != "undefined") { this.setValueHex(params['hex']); } } }; YAHOO.lang.extend(KJUR.asn1.DEREnumerated, KJUR.asn1.ASN1Object); // ******************************************************************** /** * class for ASN.1 DER UTF8String * @name KJUR.asn1.DERUTF8String * @class class for ASN.1 DER UTF8String * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) * @extends KJUR.asn1.DERAbstractString * @description * @see KJUR.asn1.DERAbstractString - superclass */ KJUR.asn1.DERUTF8String = function(params) { KJUR.asn1.DERUTF8String.superclass.constructor.call(this, params); this.hT = "0c"; }; YAHOO.lang.extend(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString); // ******************************************************************** /** * class for ASN.1 DER NumericString * @name KJUR.asn1.DERNumericString * @class class for ASN.1 DER NumericString * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) * @extends KJUR.asn1.DERAbstractString * @description * @see KJUR.asn1.DERAbstractString - superclass */ KJUR.asn1.DERNumericString = function(params) { KJUR.asn1.DERNumericString.superclass.constructor.call(this, params); this.hT = "12"; }; YAHOO.lang.extend(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString); // ******************************************************************** /** * class for ASN.1 DER PrintableString * @name KJUR.asn1.DERPrintableString * @class class for ASN.1 DER PrintableString * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) * @extends KJUR.asn1.DERAbstractString * @description * @see KJUR.asn1.DERAbstractString - superclass */ KJUR.asn1.DERPrintableString = function(params) { KJUR.asn1.DERPrintableString.superclass.constructor.call(this, params); this.hT = "13"; }; YAHOO.lang.extend(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString); // ******************************************************************** /** * class for ASN.1 DER TeletexString * @name KJUR.asn1.DERTeletexString * @class class for ASN.1 DER TeletexString * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) * @extends KJUR.asn1.DERAbstractString * @description * @see KJUR.asn1.DERAbstractString - superclass */ KJUR.asn1.DERTeletexString = function(params) { KJUR.asn1.DERTeletexString.superclass.constructor.call(this, params); this.hT = "14"; }; YAHOO.lang.extend(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString); // ******************************************************************** /** * class for ASN.1 DER IA5String * @name KJUR.asn1.DERIA5String * @class class for ASN.1 DER IA5String * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) * @extends KJUR.asn1.DERAbstractString * @description * @see KJUR.asn1.DERAbstractString - superclass */ KJUR.asn1.DERIA5String = function(params) { KJUR.asn1.DERIA5String.superclass.constructor.call(this, params); this.hT = "16"; }; YAHOO.lang.extend(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString); // ******************************************************************** /** * class for ASN.1 DER UTCTime * @name KJUR.asn1.DERUTCTime * @class class for ASN.1 DER UTCTime * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'}) * @extends KJUR.asn1.DERAbstractTime * @description * <br/> * As for argument 'params' for constructor, you can specify one of * following properties: * <ul> * <li>str - specify initial ASN.1 value(V) by a string (ex.'130430235959Z')</li> * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li> * <li>date - specify Date object.</li> * </ul> * NOTE: 'params' can be omitted. * <h4>EXAMPLES</h4> * @example * d1 = new KJUR.asn1.DERUTCTime(); * d1.setString('130430125959Z'); * * d2 = new KJUR.asn1.DERUTCTime({'str': '130430125959Z'}); * d3 = new KJUR.asn1.DERUTCTime({'date': new Date(Date.UTC(2015, 0, 31, 0, 0, 0, 0))}); * d4 = new KJUR.asn1.DERUTCTime('130430125959Z'); */ KJUR.asn1.DERUTCTime = function(params) { KJUR.asn1.DERUTCTime.superclass.constructor.call(this, params); this.hT = "17"; /** * set value by a Date object<br/> * @name setByDate * @memberOf KJUR.asn1.DERUTCTime# * @function * @param {Date} dateObject Date object to set ASN.1 value(V) * @example * o = new KJUR.asn1.DERUTCTime(); * o.setByDate(new Date("2016/12/31")); */ this.setByDate = function(dateObject) { this.hTLV = null; this.isModified = true; this.date = dateObject; this.s = this.formatDate(this.date, 'utc'); this.hV = stohex(this.s); }; this.getFreshValueHex = function() { if (typeof this.date == "undefined" && typeof this.s == "undefined") { this.date = new Date(); this.s = this.formatDate(this.date, 'utc'); this.hV = stohex(this.s); } return this.hV; }; if (params !== undefined) { if (params.str !== undefined) { this.setString(params.str); } else if (typeof params == "string" && params.match(/^[0-9]{12}Z$/)) { this.setString(params); } else if (params.hex !== undefined) { this.setStringHex(params.hex); } else if (params.date !== undefined) { this.setByDate(params.date); } } }; YAHOO.lang.extend(KJUR.asn1.DERUTCTime, KJUR.asn1.DERAbstractTime); // ******************************************************************** /** * class for ASN.1 DER GeneralizedTime * @name KJUR.asn1.DERGeneralizedTime * @class class for ASN.1 DER GeneralizedTime * @param {Array} params associative array of parameters (ex. {'str': '20130430235959Z'}) * @property {Boolean} withMillis flag to show milliseconds or not * @extends KJUR.asn1.DERAbstractTime * @description * <br/> * As for argument 'params' for constructor, you can specify one of * following properties: * <ul> * <li>str - specify initial ASN.1 value(V) by a string (ex.'20130430235959Z')</li> * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li> * <li>date - specify Date object.</li> * <li>millis - specify flag to show milliseconds (from 1.0.6)</li> * </ul> * NOTE1: 'params' can be omitted. * NOTE2: 'withMillis' property is supported from asn1 1.0.6. */ KJUR.asn1.DERGeneralizedTime = function(params) { KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, params); this.hT = "18"; this.withMillis = false; /** * set value by a Date object * @name setByDate * @memberOf KJUR.asn1.DERGeneralizedTime# * @function * @param {Date} dateObject Date object to set ASN.1 value(V) * @example * When you specify UTC time, use 'Date.UTC' method like this:<br/> * o1 = new DERUTCTime(); * o1.setByDate(date); * * date = new Date(Date.UTC(2015, 0, 31, 23, 59, 59, 0)); #2015JAN31 23:59:59 */ this.setByDate = function(dateObject) { this.hTLV = null; this.isModified = true; this.date = dateObject; this.s = this.formatDate(this.date, 'gen', this.withMillis); this.hV = stohex(this.s); }; this.getFreshValueHex = function() { if (this.date === undefined && this.s === undefined) { this.date = new Date(); this.s = this.formatDate(this.date, 'gen', this.withMillis); this.hV = stohex(this.s); } return this.hV; }; if (params !== undefined) { if (params.str !== undefined) { this.setString(params.str); } else if (typeof params == "string" && params.match(/^[0-9]{14}Z$/)) { this.setString(params); } else if (params.hex !== undefined) { this.setStringHex(params.hex); } else if (params.date !== undefined) { this.setByDate(params.date); } if (params.millis === true) { this.withMillis = true; } } }; YAHOO.lang.extend(KJUR.asn1.DERGeneralizedTime, KJUR.asn1.DERAbstractTime); // ******************************************************************** /** * class for ASN.1 DER Sequence * @name KJUR.asn1.DERSequence * @class class for ASN.1 DER Sequence * @extends KJUR.asn1.DERAbstractStructured * @description * <br/> * As for argument 'params' for constructor, you can specify one of * following properties: * <ul> * <li>array - specify array of ASN1Object to set elements of content</li> * </ul> * NOTE: 'params' can be omitted. */ KJUR.asn1.DERSequence = function(params) { KJUR.asn1.DERSequence.superclass.constructor.call(this, params); this.hT = "30"; this.getFreshValueHex = function() { var h = ''; for (var i = 0; i < this.asn1Array.length; i++) { var asn1Obj = this.asn1Array[i]; h += asn1Obj.getEncodedHex(); } this.hV = h; return this.hV; }; }; YAHOO.lang.extend(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured); // ******************************************************************** /** * class for ASN.1 DER Set * @name KJUR.asn1.DERSet * @class class for ASN.1 DER Set * @extends KJUR.asn1.DERAbstractStructured * @description * <br/> * As for argument 'params' for constructor, you can specify one of * following properties: * <ul> * <li>array - specify array of ASN1Object to set elements of content</li> * <li>sortflag - flag for sort (default: true). ASN.1 BER is not sorted in 'SET OF'.</li> * </ul> * NOTE1: 'params' can be omitted.<br/> * NOTE2: sortflag is supported since 1.0.5. */ KJUR.asn1.DERSet = function(params) { KJUR.asn1.DERSet.superclass.constructor.call(this, params); this.hT = "31"; this.sortFlag = true; // item shall be sorted only in ASN.1 DER this.getFreshValueHex = function() { var a = new Array(); for (var i = 0; i < this.asn1Array.length; i++) { var asn1Obj = this.asn1Array[i]; a.push(asn1Obj.getEncodedHex()); } if (this.sortFlag == true) a.sort(); this.hV = a.join(''); return this.hV; }; if (typeof params != "undefined") { if (typeof params.sortflag != "undefined" && params.sortflag == false) this.sortFlag = false; } }; YAHOO.lang.extend(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured); // ******************************************************************** /** * class for ASN.1 DER TaggedObject * @name KJUR.asn1.DERTaggedObject * @class class for ASN.1 DER TaggedObject * @extends KJUR.asn1.ASN1Object * @description * <br/> * Parameter 'tagNoNex' is ASN.1 tag(T) value for this object. * For example, if you find '[1]' tag in a ASN.1 dump, * 'tagNoHex' will be 'a1'. * <br/> * As for optional argument 'params' for constructor, you can specify *ANY* of * following properties: * <ul> * <li>explicit - specify true if this is explicit tag otherwise false * (default is 'true').</li> * <li>tag - specify tag (default is 'a0' which means [0])</li> * <li>obj - specify ASN1Object which is tagged</li> * </ul> * @example * d1 = new KJUR.asn1.DERUTF8String({'str':'a'}); * d2 = new KJUR.asn1.DERTaggedObject({'obj': d1}); * hex = d2.getEncodedHex(); */ KJUR.asn1.DERTaggedObject = function(params) { KJUR.asn1.DERTaggedObject.superclass.constructor.call(this); this.hT = "a0"; this.hV = ''; this.isExplicit = true; this.asn1Object = null; /** * set value by an ASN1Object * @name setString * @memberOf KJUR.asn1.DERTaggedObject# * @function * @param {Boolean} isExplicitFlag flag for explicit/implicit tag * @param {Integer} tagNoHex hexadecimal string of ASN.1 tag * @param {ASN1Object} asn1Object ASN.1 to encapsulate */ this.setASN1Object = function(isExplicitFlag, tagNoHex, asn1Object) { this.hT = tagNoHex; this.isExplicit = isExplicitFlag; this.asn1Object = asn1Object; if (this.isExplicit) { this.hV = this.asn1Object.getEncodedHex(); this.hTLV = null; this.isModified = true; } else { this.hV = null; this.hTLV = asn1Object.getEncodedHex(); this.hTLV = this.hTLV.replace(/^../, tagNoHex); this.isModified = false; } }; this.getFreshValueHex = function() { return this.hV; }; if (typeof params != "undefined") { if (typeof params['tag'] != "undefined") { this.hT = params['tag']; } if (typeof params['explicit'] != "undefined") { this.isExplicit = params['explicit']; } if (typeof params['obj'] != "undefined") { this.asn1Object = params['obj']; this.setASN1Object(this.isExplicit, this.hT, this.asn1Object); } } }; YAHOO.lang.extend(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object); /** * Create a new JSEncryptRSAKey that extends Tom Wu's RSA key object. * This object is just a decorator for parsing the key parameter * @param {string|Object} key - The key in string format, or an object containing * the parameters needed to build a RSAKey object. * @constructor */ var JSEncryptRSAKey = /** @class */ (function (_super) { __extends(JSEncryptRSAKey, _super); function JSEncryptRSAKey(key) { var _this = _super.call(this) || this; // Call the super constructor. // RSAKey.call(this); // If a key key was provided. if (key) { // If this is a string... if (typeof key === "string") { _this.parseKey(key); } else if (JSEncryptRSAKey.hasPrivateKeyProperty(key) || JSEncryptRSAKey.hasPublicKeyProperty(key)) { // Set the values for the key. _this.parsePropertiesFrom(key); } } return _this; } /** * Method to parse a pem encoded string containing both a public or private key. * The method will translate the pem encoded string in a der encoded string and * will parse private key and public key parameters. This method accepts public key * in the rsaencryption pkcs #1 format (oid: 1.2.840.113549.1.1.1). * * @todo Check how many rsa formats use the same format of pkcs #1. * * The format is defined as: * PublicKeyInfo ::= SEQUENCE { * algorithm AlgorithmIdentifier, * PublicKey BIT STRING * } * Where AlgorithmIdentifier is: * AlgorithmIdentifier ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1) * } * and PublicKey is a SEQUENCE encapsulated in a BIT STRING * RSAPublicKey ::= SEQUENCE { * modulus INTEGER, -- n * publicExponent INTEGER -- e * } * it's possible to examine the structure of the keys obtained from openssl using * an asn.1 dumper as the one used here to parse the components: http://lapo.it/asn1js/ * @argument {string} pem the pem encoded string, can include the BEGIN/END header/footer * @private */ JSEncryptRSAKey.prototype.parseKey = function (pem) { try { var modulus = 0; var public_exponent = 0; var reHex = /^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/; var der = reHex.test(pem) ? Hex.decode(pem) : Base64.unarmor(pem); var asn1 = ASN1.decode(der); // Fixes a bug with OpenSSL 1.0+ private keys if (asn1.sub.length === 3) { asn1 = asn1.sub[2].sub[0]; } if (asn1.sub.length === 9) { // Parse the private key. modulus = asn1.sub[1].getHexStringValue(); // bigint this.n = parseBigInt(modulus, 16); public_exponent = asn1.sub[2].getHexStringValue(); // int this.e = parseInt(public_exponent, 16); var private_exponent = asn1.sub[3].getHexStringValue(); // bigint this.d = parseBigInt(private_exponent, 16); var prime1 = asn1.sub[4].getHexStringValue(); // bigint this.p = parseBigInt(prime1, 16); var prime2 = asn1.sub[5].getHexStringValue(); // bigint this.q = parseBigInt(prime2, 16); var exponent1 = asn1.sub[6].getHexStringValue(); // bigint this.dmp1 = parseBigInt(exponent1, 16); var exponent2 = asn1.sub[7].getHexStringValue(); // bigint this.dmq1 = parseBigInt(exponent2, 16); var coefficient = asn1.sub[8].getHexStringValue(); // bigint this.coeff = parseBigInt(coefficient, 16); } else if (asn1.sub.length === 2) { // Parse the public key. var bit_string = asn1.sub[1]; var sequence = bit_string.sub[0]; modulus = sequence.sub[0].getHexStringValue(); this.n = parseBigInt(modulus, 16); public_exponent = sequence.sub[1].getHexStringValue(); this.e = parseInt(public_exponent, 16); } else { return false; } return true; } catch (ex) { return false; } }; /** * Translate rsa parameters in a hex encoded string representing the rsa key. * * The translation follow the ASN.1 notation : * RSAPrivateKey ::= SEQUENCE { * version Version, * modulus INTEGER, -- n * publicExponent INTEGER, -- e * privateExponent INTEGER, -- d * prime1 INTEGER, -- p * prime2 INTEGER, -- q * exponent1 INTEGER, -- d mod (p1) * exponent2 INTEGER, -- d mod (q-1) * coefficient INTEGER, -- (inverse of q) mod p * } * @returns {string} DER Encoded String representing the rsa private key * @private */ JSEncryptRSAKey.prototype.getPrivateBaseKey = function () { var options = { array: [ new KJUR.asn1.DERInteger({ int: 0 }), new KJUR.asn1.DERInteger({ bigint: this.n }), new KJUR.asn1.DERInteger({ int: this.e }), new KJUR.asn1.DERInteger({ bigint: this.d }), new KJUR.asn1.DERInteger({ bigint: this.p }), new KJUR.asn1.DERInteger({ bigint: this.q }), new KJUR.asn1.DERInteger({ bigint: this.dmp1 }), new KJUR.asn1.DERInteger({ bigint: this.dmq1 }), new KJUR.asn1.DERInteger({ bigint: this.coeff }) ] }; var seq = new KJUR.asn1.DERSequence(options); return seq.getEncodedHex(); }; /** * base64 (pem) encoded version of the DER encoded representation * @returns {string} pem encoded representation without header and footer * @public */ JSEncryptRSAKey.prototype.getPrivateBaseKeyB64 = function () { return hex2b64(this.getPrivateBaseKey()); }; /** * Translate rsa parameters in a hex encoded string representing the rsa public key. * The representation follow the ASN.1 notation : * PublicKeyInfo ::= SEQUENCE { * algorithm AlgorithmIdentifier, * PublicKey BIT STRING * } * Where AlgorithmIdentifier is: * AlgorithmIdentifier ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1) * } * and PublicKey is a SEQUENCE encapsulated in a BIT STRING * RSAPublicKey ::= SEQUENCE { * modulus INTEGER, -- n * publicExponent INTEGER -- e * } * @returns {string} DER Encoded String representing the rsa public key * @private */ JSEncryptRSAKey.prototype.getPublicBaseKey = function () { var first_sequence = new KJUR.asn1.DERSequence({ array: [ new KJUR.asn1.DERObjectIdentifier({ oid: "1.2.840.113549.1.1.1" }), new KJUR.asn1.DERNull() ] }); var second_sequence = new KJUR.asn1.DERSequence({ array: [ new KJUR.asn1.DERInteger({ bigint: this.n }), new KJUR.asn1.DERInteger({ int: this.e }) ] }); var bit_string = new KJUR.asn1.DERBitString({ hex: "00" + second_sequence.getEncodedHex() }); var seq = new KJUR.asn1.DERSequence({ array: [ first_sequence, bit_string ] }); return seq.getEncodedHex(); }; /** * base64 (pem) encoded version of the DER encoded representation * @returns {string} pem encoded representation without header and footer * @public */ JSEncryptRSAKey.prototype.getPublicBaseKeyB64 = function () { return hex2b64(this.getPublicBaseKey()); }; /** * wrap the string in block of width chars. The default value for rsa keys is 64 * characters. * @param {string} str the pem encoded string without header and footer * @param {Number} [width=64] - the length the string has to be wrapped at * @returns {string} * @private */ JSEncryptRSAKey.wordwrap = function (str, width) { width = width || 64; if (!str) { return str; } var regex = "(.{1," + width + "})( +|$\n?)|(.{1," + width + "})"; return str.match(RegExp(regex, "g")).join("\n"); }; /** * Retrieve the pem encoded private key * @returns {string} the pem encoded private key with header/footer * @public */ JSEncryptRSAKey.prototype.getPrivateKey = function () { var key = "-----BEGIN RSA PRIVATE KEY-----\n"; key += JSEncryptRSAKey.wordwrap(this.getPrivateBaseKeyB64()) + "\n"; key += "-----END RSA PRIVATE KEY-----"; return key; }; /** * Retrieve the pem encoded public key * @returns {string} the pem encoded public key with header/footer * @public */ JSEncryptRSAKey.prototype.getPublicKey = function () { var key = "-----BEGIN PUBLIC KEY-----\n"; key += JSEncryptRSAKey.wordwrap(this.getPublicBaseKeyB64()) + "\n"; key += "-----END PUBLIC KEY-----"; return key; }; /** * Check if the object contains the necessary parameters to populate the rsa modulus * and public exponent parameters. * @param {Object} [obj={}] - An object that may contain the two public key * parameters * @returns {boolean} true if the object contains both the modulus and the public exponent * properties (n and e) * @todo check for types of n and e. N should be a parseable bigInt object, E should * be a parseable integer number * @private */ JSEncryptRSAKey.hasPublicKeyProperty = function (obj) { obj = obj || {}; return (obj.hasOwnProperty("n") && obj.hasOwnProperty("e")); }; /** * Check if the object contains ALL the parameters of an RSA key. * @param {Object} [obj={}] - An object that may contain nine rsa key * parameters * @returns {boolean} true if the object contains all the parameters needed * @todo check for types of the parameters all the parameters but the public exponent * should be parseable bigint objects, the public exponent should be a parseable integer number * @private */ JSEncryptRSAKey.hasPrivateKeyProperty = function (obj) { obj = obj || {}; return (obj.hasOwnProperty("n") && obj.hasOwnProperty("e") && obj.hasOwnProperty("d") && obj.hasOwnProperty("p") && obj.hasOwnProperty("q") && obj.hasOwnProperty("dmp1") && obj.hasOwnProperty("dmq1") && obj.hasOwnProperty("coeff")); }; /** * Parse the properties of obj in the current rsa object. Obj should AT LEAST * include the modulus and public exponent (n, e) parameters. * @param {Object} obj - the object containing rsa parameters * @private */ JSEncryptRSAKey.prototype.parsePropertiesFrom = function (obj) { this.n = obj.n; this.e = obj.e; if (obj.hasOwnProperty("d")) { this.d = obj.d; this.p = obj.p; this.q = obj.q; this.dmp1 = obj.dmp1; this.dmq1 = obj.dmq1; this.coeff = obj.coeff; } }; return JSEncryptRSAKey; }(RSAKey)); /** * * @param {Object} [options = {}] - An object to customize JSEncrypt behaviour * possible parameters are: * - default_key_size {number} default: 1024 the key size in bit * - default_public_exponent {string} default: '010001' the hexadecimal representation of the public exponent * - log {boolean} default: false whether log warn/error or not * @constructor */ var JSEncrypt = /** @class */ (function () { function JSEncrypt(options) { options = options || {}; this.default_key_size = parseInt(options.default_key_size, 10) || 1024; this.default_public_exponent = options.default_public_exponent || "010001"; // 65537 default openssl public exponent for rsa key type this.log = options.log || false; // The private and public key. this.key = null; } /** * Method to set the rsa key parameter (one method is enough to set both the public * and the private key, since the private key contains the public key paramenters) * Log a warning if logs are enabled * @param {Object|string} key the pem encoded string or an object (with or without header/footer) * @public */ JSEncrypt.prototype.setKey = function (key) { if (this.log && this.key) { console.warn("A key was already set, overriding existing."); } this.key = new JSEncryptRSAKey(key); }; /** * Proxy method for setKey, for api compatibility * @see setKey * @public */ JSEncrypt.prototype.setPrivateKey = function (privkey) { // Create the key. this.setKey(privkey); }; /** * Proxy method for setKey, for api compatibility * @see setKey * @public */ JSEncrypt.prototype.setPublicKey = function (pubkey) { // Sets the public key. this.setKey(pubkey); }; /** * Proxy method for RSAKey object's decrypt, decrypt the string using the private * components of the rsa key object. Note that if the object was not set will be created * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor * @param {string} str base64 encoded crypted string to decrypt * @return {string} the decrypted string * @public */ JSEncrypt.prototype.decrypt = function (str) { // Return the decrypted string. try { return this.getKey().decrypt(b64tohex(str)); } catch (ex) { return false; } }; /** * Proxy method for RSAKey object's encrypt, encrypt the string using the public * components of the rsa key object. Note that if the object was not set will be created * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor * @param {string} str the string to encrypt * @return {string} the encrypted string encoded in base64 * @public */ JSEncrypt.prototype.encrypt = function (str) { // Return the encrypted string. try { return hex2b64(this.getKey().encrypt(str)); } catch (ex) { return false; } }; /** * Proxy method for RSAKey object's sign. * @param {string} str the string to sign * @param {function} digestMethod hash method * @param {string} digestName the name of the hash algorithm * @return {string} the signature encoded in base64 * @public */ JSEncrypt.prototype.sign = function (str, digestMethod, digestName) { // return the RSA signature of 'str' in 'hex' format. try { return hex2b64(this.getKey().sign(str, digestMethod, digestName)); } catch (ex) { return false; } }; /** * Proxy method for RSAKey object's verify. * @param {string} str the string to verify * @param {string} signature the signature encoded in base64 to compare the string to * @param {function} digestMethod hash method * @return {boolean} whether the data and signature match * @public */ JSEncrypt.prototype.verify = function (str, signature, digestMethod) { // Return the decrypted 'digest' of the signature. try { return this.getKey().verify(str, b64tohex(signature), digestMethod); } catch (ex) { return false; } }; /** * Getter for the current JSEncryptRSAKey object. If it doesn't exists a new object * will be created and returned * @param {callback} [cb] the callback to be called if we want the key to be generated * in an async fashion * @returns {JSEncryptRSAKey} the JSEncryptRSAKey object * @public */ JSEncrypt.prototype.getKey = function (cb) { // Only create new if it does not exist. if (!this.key) { // Get a new private key. this.key = new JSEncryptRSAKey(); if (cb && {}.toString.call(cb) === "[object Function]") { this.key.generateAsync(this.default_key_size, this.default_public_exponent, cb); return; } // Generate the key. this.key.generate(this.default_key_size, this.default_public_exponent); } return this.key; }; /** * Returns the pem encoded representation of the private key * If the key doesn't exists a new key will be created * @returns {string} pem encoded representation of the private key WITH header and footer * @public */ JSEncrypt.prototype.getPrivateKey = function () { // Return the private representation of this key. return this.getKey().getPrivateKey(); }; /** * Returns the pem encoded representation of the private key * If the key doesn't exists a new key will be created * @returns {string} pem encoded representation of the private key WITHOUT header and footer * @public */ JSEncrypt.prototype.getPrivateKeyB64 = function () { // Return the private representation of this key. return this.getKey().getPrivateBaseKeyB64(); }; /** * Returns the pem encoded representation of the public key * If the key doesn't exists a new key will be created * @returns {string} pem encoded representation of the public key WITH header and footer * @public */ JSEncrypt.prototype.getPublicKey = function () { // Return the private representation of this key. return this.getKey().getPublicKey(); }; /** * Returns the pem encoded representation of the public key * If the key doesn't exists a new key will be created * @returns {string} pem encoded representation of the public key WITHOUT header and footer * @public */ JSEncrypt.prototype.getPublicKeyB64 = function () { // Return the private representation of this key. return this.getKey().getPublicBaseKeyB64(); }; JSEncrypt.version = "3.0.0-rc.1"; return JSEncrypt; }()); window.JSEncrypt = JSEncrypt; exports.JSEncrypt = JSEncrypt; exports.default = JSEncrypt; Object.defineProperty(exports, '__esModule', { value: true }); })));
'use strict'; /** * Lazily required module dependencies */ var lazy = require('lazy-cache')(require); var fn = require; require = lazy; require('falsey', 'isFalsey'); require('delimiter-regex', 'delims'); require('get-view'); require = fn; /** * Expose `utils` */ module.exports = lazy;
interface A { 'C': string; } interface B { "D": boolean; }
"use strict"; var render = require("../../render"); var src = __dirname + "/src.js"; render( { src: src, template: __dirname + "/../template.hbs", "global-index-format": "none", source: src }, __dirname + "/readme.md" );
Ext.define("Ext.menu.Separator",{extend:"Ext.menu.Item",alias:"widget.menuseparator",canActivate:false,focusable:false,hideOnClick:false,plain:true,separatorCls:Ext.baseCSSPrefix+"menu-item-separator",text:"&#160;",beforeRender:function(a,c){var b=this;b.callParent();b.addCls(b.separatorCls)}});
'use strict'; /* globals getInputCompileHelper: false */ describe('ngModel', function() { describe('NgModelController', function() { /* global NgModelController: false */ var ctrl, scope, ngModelAccessor, element, parentFormCtrl; beforeEach(inject(function($rootScope, $controller) { var attrs = {name: 'testAlias', ngModel: 'value'}; parentFormCtrl = { $$setPending: jasmine.createSpy('$$setPending'), $setValidity: jasmine.createSpy('$setValidity'), $setDirty: jasmine.createSpy('$setDirty'), $$clearControlValidity: noop }; element = jqLite('<form><input></form>'); scope = $rootScope; ngModelAccessor = jasmine.createSpy('ngModel accessor'); ctrl = $controller(NgModelController, { $scope: scope, $element: element.find('input'), $attrs: attrs }); //Assign the mocked parentFormCtrl to the model controller ctrl.$$parentForm = parentFormCtrl; })); afterEach(function() { dealoc(element); }); it('should init the properties', function() { expect(ctrl.$untouched).toBe(true); expect(ctrl.$touched).toBe(false); expect(ctrl.$dirty).toBe(false); expect(ctrl.$pristine).toBe(true); expect(ctrl.$valid).toBe(true); expect(ctrl.$invalid).toBe(false); expect(ctrl.$viewValue).toBeDefined(); expect(ctrl.$modelValue).toBeDefined(); expect(ctrl.$formatters).toEqual([]); expect(ctrl.$parsers).toEqual([]); expect(ctrl.$name).toBe('testAlias'); }); describe('setValidity', function() { function expectOneError() { expect(ctrl.$error).toEqual({someError: true}); expect(ctrl.$$success).toEqual({}); expect(ctrl.$pending).toBeUndefined(); } function expectOneSuccess() { expect(ctrl.$error).toEqual({}); expect(ctrl.$$success).toEqual({someError: true}); expect(ctrl.$pending).toBeUndefined(); } function expectOnePending() { expect(ctrl.$error).toEqual({}); expect(ctrl.$$success).toEqual({}); expect(ctrl.$pending).toEqual({someError: true}); } function expectCleared() { expect(ctrl.$error).toEqual({}); expect(ctrl.$$success).toEqual({}); expect(ctrl.$pending).toBeUndefined(); } it('should propagate validity to the parent form', function() { expect(parentFormCtrl.$setValidity).not.toHaveBeenCalled(); ctrl.$setValidity('ERROR', false); expect(parentFormCtrl.$setValidity).toHaveBeenCalledOnceWith('ERROR', false, ctrl); }); it('should transition from states correctly', function() { expectCleared(); ctrl.$setValidity('someError', false); expectOneError(); ctrl.$setValidity('someError', undefined); expectOnePending(); ctrl.$setValidity('someError', true); expectOneSuccess(); ctrl.$setValidity('someError', null); expectCleared(); }); it('should set valid/invalid with multiple errors', function() { ctrl.$setValidity('first', false); expect(ctrl.$valid).toBe(false); expect(ctrl.$invalid).toBe(true); ctrl.$setValidity('second', false); expect(ctrl.$valid).toBe(false); expect(ctrl.$invalid).toBe(true); ctrl.$setValidity('third', undefined); expect(ctrl.$valid).toBe(undefined); expect(ctrl.$invalid).toBe(undefined); ctrl.$setValidity('third', null); expect(ctrl.$valid).toBe(false); expect(ctrl.$invalid).toBe(true); ctrl.$setValidity('second', true); expect(ctrl.$valid).toBe(false); expect(ctrl.$invalid).toBe(true); ctrl.$setValidity('first', true); expect(ctrl.$valid).toBe(true); expect(ctrl.$invalid).toBe(false); }); }); describe('setPristine', function() { it('should set control to its pristine state', function() { ctrl.$setViewValue('edit'); expect(ctrl.$dirty).toBe(true); expect(ctrl.$pristine).toBe(false); ctrl.$setPristine(); expect(ctrl.$dirty).toBe(false); expect(ctrl.$pristine).toBe(true); }); }); describe('setDirty', function() { it('should set control to its dirty state', function() { expect(ctrl.$pristine).toBe(true); expect(ctrl.$dirty).toBe(false); ctrl.$setDirty(); expect(ctrl.$pristine).toBe(false); expect(ctrl.$dirty).toBe(true); }); it('should set parent form to its dirty state', function() { ctrl.$setDirty(); expect(parentFormCtrl.$setDirty).toHaveBeenCalled(); }); }); describe('setUntouched', function() { it('should set control to its untouched state', function() { ctrl.$setTouched(); ctrl.$setUntouched(); expect(ctrl.$touched).toBe(false); expect(ctrl.$untouched).toBe(true); }); }); describe('setTouched', function() { it('should set control to its touched state', function() { ctrl.$setUntouched(); ctrl.$setTouched(); expect(ctrl.$touched).toBe(true); expect(ctrl.$untouched).toBe(false); }); }); describe('view -> model', function() { it('should set the value to $viewValue', function() { ctrl.$setViewValue('some-val'); expect(ctrl.$viewValue).toBe('some-val'); }); it('should pipeline all registered parsers and set result to $modelValue', function() { var log = []; ctrl.$parsers.push(function(value) { log.push(value); return value + '-a'; }); ctrl.$parsers.push(function(value) { log.push(value); return value + '-b'; }); ctrl.$setViewValue('init'); expect(log).toEqual(['init', 'init-a']); expect(ctrl.$modelValue).toBe('init-a-b'); }); it('should fire viewChangeListeners when the value changes in the view (even if invalid)', function() { var spy = jasmine.createSpy('viewChangeListener'); ctrl.$viewChangeListeners.push(spy); ctrl.$setViewValue('val'); expect(spy).toHaveBeenCalledOnce(); spy.reset(); // invalid ctrl.$parsers.push(function() {return undefined;}); ctrl.$setViewValue('val2'); expect(spy).toHaveBeenCalledOnce(); }); it('should reset the model when the view is invalid', function() { ctrl.$setViewValue('aaaa'); expect(ctrl.$modelValue).toBe('aaaa'); // add a validator that will make any input invalid ctrl.$parsers.push(function() {return undefined;}); expect(ctrl.$modelValue).toBe('aaaa'); ctrl.$setViewValue('bbbb'); expect(ctrl.$modelValue).toBeUndefined(); }); it('should not reset the model when the view is invalid due to an external validator', function() { ctrl.$setViewValue('aaaa'); expect(ctrl.$modelValue).toBe('aaaa'); ctrl.$setValidity('someExternalError', false); ctrl.$setViewValue('bbbb'); expect(ctrl.$modelValue).toBe('bbbb'); }); it('should not reset the view when the view is invalid', function() { // this test fails when the view changes the model and // then the model listener in ngModel picks up the change and // tries to update the view again. // add a validator that will make any input invalid ctrl.$parsers.push(function() {return undefined;}); spyOn(ctrl, '$render'); // first digest ctrl.$setViewValue('bbbb'); expect(ctrl.$modelValue).toBeUndefined(); expect(ctrl.$viewValue).toBe('bbbb'); expect(ctrl.$render).not.toHaveBeenCalled(); expect(scope.value).toBeUndefined(); // further digests scope.$apply('value = "aaa"'); expect(ctrl.$viewValue).toBe('aaa'); ctrl.$render.reset(); ctrl.$setViewValue('cccc'); expect(ctrl.$modelValue).toBeUndefined(); expect(ctrl.$viewValue).toBe('cccc'); expect(ctrl.$render).not.toHaveBeenCalled(); expect(scope.value).toBeUndefined(); }); it('should call parentForm.$setDirty only when pristine', function() { ctrl.$setViewValue(''); expect(ctrl.$pristine).toBe(false); expect(ctrl.$dirty).toBe(true); expect(parentFormCtrl.$setDirty).toHaveBeenCalledOnce(); parentFormCtrl.$setDirty.reset(); ctrl.$setViewValue(''); expect(ctrl.$pristine).toBe(false); expect(ctrl.$dirty).toBe(true); expect(parentFormCtrl.$setDirty).not.toHaveBeenCalled(); }); it('should remove all other errors when any parser returns undefined', function() { var a, b, val = function(val, x) { return x ? val : x; }; ctrl.$parsers.push(function(v) { return val(v, a); }); ctrl.$parsers.push(function(v) { return val(v, b); }); ctrl.$validators.high = function(value) { return !isDefined(value) || value > 5; }; ctrl.$validators.even = function(value) { return !isDefined(value) || value % 2 === 0; }; a = b = true; ctrl.$setViewValue('3'); expect(ctrl.$error).toEqual({ high: true, even: true }); ctrl.$setViewValue('10'); expect(ctrl.$error).toEqual({}); a = undefined; ctrl.$setViewValue('12'); expect(ctrl.$error).toEqual({ parse: true }); a = true; b = undefined; ctrl.$setViewValue('14'); expect(ctrl.$error).toEqual({ parse: true }); a = undefined; b = undefined; ctrl.$setViewValue('16'); expect(ctrl.$error).toEqual({ parse: true }); a = b = false; //not undefined ctrl.$setViewValue('2'); expect(ctrl.$error).toEqual({ high: true }); }); it('should not remove external validators when a parser failed', function() { ctrl.$parsers.push(function(v) { return undefined; }); ctrl.$setValidity('externalError', false); ctrl.$setViewValue('someValue'); expect(ctrl.$error).toEqual({ externalError: true, parse: true }); }); it('should remove all non-parse-related CSS classes from the form when a parser fails', inject(function($compile, $rootScope) { var element = $compile('<form name="myForm">' + '<input name="myControl" ng-model="value" >' + '</form>')($rootScope); var inputElm = element.find('input'); var ctrl = $rootScope.myForm.myControl; var parserIsFailing = false; ctrl.$parsers.push(function(value) { return parserIsFailing ? undefined : value; }); ctrl.$validators.alwaysFail = function() { return false; }; ctrl.$setViewValue('123'); scope.$digest(); expect(element).toHaveClass('ng-valid-parse'); expect(element).not.toHaveClass('ng-invalid-parse'); expect(element).toHaveClass('ng-invalid-always-fail'); parserIsFailing = true; ctrl.$setViewValue('12345'); scope.$digest(); expect(element).not.toHaveClass('ng-valid-parse'); expect(element).toHaveClass('ng-invalid-parse'); expect(element).not.toHaveClass('ng-invalid-always-fail'); dealoc(element); })); it('should set the ng-invalid-parse and ng-valid-parse CSS class when parsers fail and pass', function() { var pass = true; ctrl.$parsers.push(function(v) { return pass ? v : undefined; }); var input = element.find('input'); ctrl.$setViewValue('1'); expect(input).toHaveClass('ng-valid-parse'); expect(input).not.toHaveClass('ng-invalid-parse'); pass = undefined; ctrl.$setViewValue('2'); expect(input).not.toHaveClass('ng-valid-parse'); expect(input).toHaveClass('ng-invalid-parse'); }); it('should update the model after all async validators resolve', inject(function($q) { var defer; ctrl.$asyncValidators.promiseValidator = function(value) { defer = $q.defer(); return defer.promise; }; // set view value on first digest ctrl.$setViewValue('b'); expect(ctrl.$modelValue).toBeUndefined(); expect(scope.value).toBeUndefined(); defer.resolve(); scope.$digest(); expect(ctrl.$modelValue).toBe('b'); expect(scope.value).toBe('b'); // set view value on further digests ctrl.$setViewValue('c'); expect(ctrl.$modelValue).toBe('b'); expect(scope.value).toBe('b'); defer.resolve(); scope.$digest(); expect(ctrl.$modelValue).toBe('c'); expect(scope.value).toBe('c'); })); }); describe('model -> view', function() { it('should set the value to $modelValue', function() { scope.$apply('value = 10'); expect(ctrl.$modelValue).toBe(10); }); it('should pipeline all registered formatters in reversed order and set result to $viewValue', function() { var log = []; ctrl.$formatters.unshift(function(value) { log.push(value); return value + 2; }); ctrl.$formatters.unshift(function(value) { log.push(value); return value + ''; }); scope.$apply('value = 3'); expect(log).toEqual([3, 5]); expect(ctrl.$viewValue).toBe('5'); }); it('should $render only if value changed', function() { spyOn(ctrl, '$render'); scope.$apply('value = 3'); expect(ctrl.$render).toHaveBeenCalledOnce(); ctrl.$render.reset(); ctrl.$formatters.push(function() {return 3;}); scope.$apply('value = 5'); expect(ctrl.$render).not.toHaveBeenCalled(); }); it('should clear the view even if invalid', function() { spyOn(ctrl, '$render'); ctrl.$formatters.push(function() {return undefined;}); scope.$apply('value = 5'); expect(ctrl.$render).toHaveBeenCalledOnce(); }); it('should render immediately even if there are async validators', inject(function($q) { spyOn(ctrl, '$render'); ctrl.$asyncValidators.someValidator = function() { return $q.defer().promise; }; scope.$apply('value = 5'); expect(ctrl.$viewValue).toBe(5); expect(ctrl.$render).toHaveBeenCalledOnce(); })); it('should not rerender nor validate in case view value is not changed', function() { ctrl.$formatters.push(function(value) { return 'nochange'; }); spyOn(ctrl, '$render'); ctrl.$validators.spyValidator = jasmine.createSpy('spyValidator'); scope.$apply('value = "first"'); scope.$apply('value = "second"'); expect(ctrl.$validators.spyValidator).toHaveBeenCalledOnce(); expect(ctrl.$render).toHaveBeenCalledOnce(); }); it('should always format the viewValue as a string for a blank input type when the value is present', inject(function($compile, $rootScope, $sniffer) { var form = $compile('<form name="form"><input name="field" ng-model="val" /></form>')($rootScope); $rootScope.val = 123; $rootScope.$digest(); expect($rootScope.form.field.$viewValue).toBe('123'); $rootScope.val = null; $rootScope.$digest(); expect($rootScope.form.field.$viewValue).toBe(null); dealoc(form); })); it('should always format the viewValue as a string for a `text` input type when the value is present', inject(function($compile, $rootScope, $sniffer) { var form = $compile('<form name="form"><input type="text" name="field" ng-model="val" /></form>')($rootScope); $rootScope.val = 123; $rootScope.$digest(); expect($rootScope.form.field.$viewValue).toBe('123'); $rootScope.val = null; $rootScope.$digest(); expect($rootScope.form.field.$viewValue).toBe(null); dealoc(form); })); it('should always format the viewValue as a string for an `email` input type when the value is present', inject(function($compile, $rootScope, $sniffer) { var form = $compile('<form name="form"><input type="email" name="field" ng-model="val" /></form>')($rootScope); $rootScope.val = 123; $rootScope.$digest(); expect($rootScope.form.field.$viewValue).toBe('123'); $rootScope.val = null; $rootScope.$digest(); expect($rootScope.form.field.$viewValue).toBe(null); dealoc(form); })); it('should always format the viewValue as a string for a `url` input type when the value is present', inject(function($compile, $rootScope, $sniffer) { var form = $compile('<form name="form"><input type="url" name="field" ng-model="val" /></form>')($rootScope); $rootScope.val = 123; $rootScope.$digest(); expect($rootScope.form.field.$viewValue).toBe('123'); $rootScope.val = null; $rootScope.$digest(); expect($rootScope.form.field.$viewValue).toBe(null); dealoc(form); })); it('should set NaN as the $modelValue when an asyncValidator is present', inject(function($q) { ctrl.$asyncValidators.test = function() { return $q(function(resolve, reject) { resolve(); }); }; scope.$apply('value = 10'); expect(ctrl.$modelValue).toBe(10); expect(function() { scope.$apply(function() { scope.value = NaN; }); }).not.toThrow(); expect(ctrl.$modelValue).toBeNaN(); })); }); describe('validation', function() { describe('$validate', function() { it('should perform validations when $validate() is called', function() { scope.$apply('value = ""'); var validatorResult = false; ctrl.$validators.someValidator = function(value) { return validatorResult; }; ctrl.$validate(); expect(ctrl.$valid).toBe(false); validatorResult = true; ctrl.$validate(); expect(ctrl.$valid).toBe(true); }); it('should pass the last parsed modelValue to the validators', function() { ctrl.$parsers.push(function(modelValue) { return modelValue + 'def'; }); ctrl.$setViewValue('abc'); ctrl.$validators.test = function(modelValue, viewValue) { return true; }; spyOn(ctrl.$validators, 'test'); ctrl.$validate(); expect(ctrl.$validators.test).toHaveBeenCalledWith('abcdef', 'abc'); }); it('should set the model to undefined when it becomes invalid', function() { var valid = true; ctrl.$validators.test = function(modelValue, viewValue) { return valid; }; scope.$apply('value = "abc"'); expect(scope.value).toBe('abc'); valid = false; ctrl.$validate(); expect(scope.value).toBeUndefined(); }); it('should update the model when it becomes valid', function() { var valid = true; ctrl.$validators.test = function(modelValue, viewValue) { return valid; }; scope.$apply('value = "abc"'); expect(scope.value).toBe('abc'); valid = false; ctrl.$validate(); expect(scope.value).toBeUndefined(); valid = true; ctrl.$validate(); expect(scope.value).toBe('abc'); }); it('should not update the model when it is valid, but there is a parse error', function() { ctrl.$parsers.push(function(modelValue) { return undefined; }); ctrl.$setViewValue('abc'); expect(ctrl.$error.parse).toBe(true); expect(scope.value).toBeUndefined(); ctrl.$validators.test = function(modelValue, viewValue) { return true; }; ctrl.$validate(); expect(ctrl.$error).toEqual({parse: true}); expect(scope.value).toBeUndefined(); }); it('should not set an invalid model to undefined when validity is the same', function() { ctrl.$validators.test = function() { return false; }; scope.$apply('value = "invalid"'); expect(ctrl.$valid).toBe(false); expect(scope.value).toBe('invalid'); ctrl.$validate(); expect(ctrl.$valid).toBe(false); expect(scope.value).toBe('invalid'); }); it('should not change a model that has a formatter', function() { ctrl.$validators.test = function() { return true; }; ctrl.$formatters.push(function(modelValue) { return 'xyz'; }); scope.$apply('value = "abc"'); expect(ctrl.$viewValue).toBe('xyz'); ctrl.$validate(); expect(scope.value).toBe('abc'); }); it('should not change a model that has a parser', function() { ctrl.$validators.test = function() { return true; }; ctrl.$parsers.push(function(modelValue) { return 'xyz'; }); scope.$apply('value = "abc"'); ctrl.$validate(); expect(scope.value).toBe('abc'); }); }); describe('view -> model update', function() { it('should always perform validations using the parsed model value', function() { var captures; ctrl.$validators.raw = function() { captures = arguments; return captures[0]; }; ctrl.$parsers.push(function(value) { return value.toUpperCase(); }); ctrl.$setViewValue('my-value'); expect(captures).toEqual(['MY-VALUE', 'my-value']); }); it('should always perform validations using the formatted view value', function() { var captures; ctrl.$validators.raw = function() { captures = arguments; return captures[0]; }; ctrl.$formatters.push(function(value) { return value + '...'; }); scope.$apply('value = "matias"'); expect(captures).toEqual(['matias', 'matias...']); }); it('should only perform validations if the view value is different', function() { var count = 0; ctrl.$validators.countMe = function() { count++; }; ctrl.$setViewValue('my-value'); expect(count).toBe(1); ctrl.$setViewValue('my-value'); expect(count).toBe(1); ctrl.$setViewValue('your-value'); expect(count).toBe(2); }); }); it('should perform validations twice each time the model value changes within a digest', function() { var count = 0; ctrl.$validators.number = function(value) { count++; return (/^\d+$/).test(value); }; scope.$apply('value = ""'); expect(count).toBe(1); scope.$apply('value = 1'); expect(count).toBe(2); scope.$apply('value = 1'); expect(count).toBe(2); scope.$apply('value = ""'); expect(count).toBe(3); }); it('should only validate to true if all validations are true', function() { var curry = function(v) { return function() { return v; }; }; ctrl.$modelValue = undefined; ctrl.$validators.a = curry(true); ctrl.$validators.b = curry(true); ctrl.$validators.c = curry(false); ctrl.$validate(); expect(ctrl.$valid).toBe(false); ctrl.$validators.c = curry(true); ctrl.$validate(); expect(ctrl.$valid).toBe(true); }); it('should register invalid validations on the $error object', function() { var curry = function(v) { return function() { return v; }; }; ctrl.$modelValue = undefined; ctrl.$validators.unique = curry(false); ctrl.$validators.tooLong = curry(false); ctrl.$validators.notNumeric = curry(true); ctrl.$validate(); expect(ctrl.$error.unique).toBe(true); expect(ctrl.$error.tooLong).toBe(true); expect(ctrl.$error.notNumeric).not.toBe(true); }); it('should render a validator asynchronously when a promise is returned', inject(function($q) { var defer; ctrl.$asyncValidators.promiseValidator = function(value) { defer = $q.defer(); return defer.promise; }; scope.$apply('value = ""'); expect(ctrl.$valid).toBeUndefined(); expect(ctrl.$invalid).toBeUndefined(); expect(ctrl.$pending.promiseValidator).toBe(true); defer.resolve(); scope.$digest(); expect(ctrl.$valid).toBe(true); expect(ctrl.$invalid).toBe(false); expect(ctrl.$pending).toBeUndefined(); scope.$apply('value = "123"'); defer.reject(); scope.$digest(); expect(ctrl.$valid).toBe(false); expect(ctrl.$invalid).toBe(true); expect(ctrl.$pending).toBeUndefined(); })); it('should throw an error when a promise is not returned for an asynchronous validator', inject(function($q) { ctrl.$asyncValidators.async = function(value) { return true; }; expect(function() { scope.$apply('value = "123"'); }).toThrowMinErr("ngModel", "nopromise", "Expected asynchronous validator to return a promise but got 'true' instead."); })); it('should only run the async validators once all the sync validators have passed', inject(function($q) { var stages = {}; stages.sync = { status1: false, status2: false, count: 0 }; ctrl.$validators.syncValidator1 = function(modelValue, viewValue) { stages.sync.count++; return stages.sync.status1; }; ctrl.$validators.syncValidator2 = function(modelValue, viewValue) { stages.sync.count++; return stages.sync.status2; }; stages.async = { defer: null, count: 0 }; ctrl.$asyncValidators.asyncValidator = function(modelValue, viewValue) { stages.async.defer = $q.defer(); stages.async.count++; return stages.async.defer.promise; }; scope.$apply('value = "123"'); expect(ctrl.$valid).toBe(false); expect(ctrl.$invalid).toBe(true); expect(stages.sync.count).toBe(2); expect(stages.async.count).toBe(0); stages.sync.status1 = true; scope.$apply('value = "456"'); expect(stages.sync.count).toBe(4); expect(stages.async.count).toBe(0); stages.sync.status2 = true; scope.$apply('value = "789"'); expect(stages.sync.count).toBe(6); expect(stages.async.count).toBe(1); stages.async.defer.resolve(); scope.$apply(); expect(ctrl.$valid).toBe(true); expect(ctrl.$invalid).toBe(false); })); it('should ignore expired async validation promises once delivered', inject(function($q) { var defer, oldDefer, newDefer; ctrl.$asyncValidators.async = function(value) { defer = $q.defer(); return defer.promise; }; scope.$apply('value = ""'); oldDefer = defer; scope.$apply('value = "123"'); newDefer = defer; newDefer.reject(); scope.$digest(); oldDefer.resolve(); scope.$digest(); expect(ctrl.$valid).toBe(false); expect(ctrl.$invalid).toBe(true); expect(ctrl.$pending).toBeUndefined(); })); it('should clear and ignore all pending promises when the model value changes', inject(function($q) { ctrl.$validators.sync = function(value) { return true; }; var defers = []; ctrl.$asyncValidators.async = function(value) { var defer = $q.defer(); defers.push(defer); return defer.promise; }; scope.$apply('value = "123"'); expect(ctrl.$pending).toEqual({async: true}); expect(ctrl.$valid).toBe(undefined); expect(ctrl.$invalid).toBe(undefined); expect(defers.length).toBe(1); expect(isObject(ctrl.$pending)).toBe(true); scope.$apply('value = "456"'); expect(ctrl.$pending).toEqual({async: true}); expect(ctrl.$valid).toBe(undefined); expect(ctrl.$invalid).toBe(undefined); expect(defers.length).toBe(2); expect(isObject(ctrl.$pending)).toBe(true); defers[1].resolve(); scope.$digest(); expect(ctrl.$valid).toBe(true); expect(ctrl.$invalid).toBe(false); expect(isObject(ctrl.$pending)).toBe(false); })); it('should clear and ignore all pending promises when a parser fails', inject(function($q) { var failParser = false; ctrl.$parsers.push(function(value) { return failParser ? undefined : value; }); var defer; ctrl.$asyncValidators.async = function(value) { defer = $q.defer(); return defer.promise; }; ctrl.$setViewValue('x..y..z'); expect(ctrl.$valid).toBe(undefined); expect(ctrl.$invalid).toBe(undefined); failParser = true; ctrl.$setViewValue('1..2..3'); expect(ctrl.$valid).toBe(false); expect(ctrl.$invalid).toBe(true); expect(isObject(ctrl.$pending)).toBe(false); defer.resolve(); scope.$digest(); expect(ctrl.$valid).toBe(false); expect(ctrl.$invalid).toBe(true); expect(isObject(ctrl.$pending)).toBe(false); })); it('should clear all errors from async validators if a parser fails', inject(function($q) { var failParser = false; ctrl.$parsers.push(function(value) { return failParser ? undefined : value; }); ctrl.$asyncValidators.async = function(value) { return $q.reject(); }; ctrl.$setViewValue('x..y..z'); expect(ctrl.$error).toEqual({async: true}); failParser = true; ctrl.$setViewValue('1..2..3'); expect(ctrl.$error).toEqual({parse: true}); })); it('should clear all errors from async validators if a sync validator fails', inject(function($q) { var failValidator = false; ctrl.$validators.sync = function(value) { return !failValidator; }; ctrl.$asyncValidators.async = function(value) { return $q.reject(); }; ctrl.$setViewValue('x..y..z'); expect(ctrl.$error).toEqual({async: true}); failValidator = true; ctrl.$setViewValue('1..2..3'); expect(ctrl.$error).toEqual({sync: true}); })); it('should be possible to extend Object prototype and still be able to do form validation', inject(function($compile, $rootScope) { Object.prototype.someThing = function() {}; var element = $compile('<form name="myForm">' + '<input type="text" name="username" ng-model="username" minlength="10" required />' + '</form>')($rootScope); var inputElm = element.find('input'); var formCtrl = $rootScope.myForm; var usernameCtrl = formCtrl.username; $rootScope.$digest(); expect(usernameCtrl.$invalid).toBe(true); expect(formCtrl.$invalid).toBe(true); usernameCtrl.$setViewValue('valid-username'); $rootScope.$digest(); expect(usernameCtrl.$invalid).toBe(false); expect(formCtrl.$invalid).toBe(false); delete Object.prototype.someThing; dealoc(element); })); it('should re-evaluate the form validity state once the asynchronous promise has been delivered', inject(function($compile, $rootScope, $q) { var element = $compile('<form name="myForm">' + '<input type="text" name="username" ng-model="username" minlength="10" required />' + '<input type="number" name="age" ng-model="age" min="10" required />' + '</form>')($rootScope); var inputElm = element.find('input'); var formCtrl = $rootScope.myForm; var usernameCtrl = formCtrl.username; var ageCtrl = formCtrl.age; var usernameDefer; usernameCtrl.$asyncValidators.usernameAvailability = function() { usernameDefer = $q.defer(); return usernameDefer.promise; }; $rootScope.$digest(); expect(usernameCtrl.$invalid).toBe(true); expect(formCtrl.$invalid).toBe(true); usernameCtrl.$setViewValue('valid-username'); $rootScope.$digest(); expect(formCtrl.$pending.usernameAvailability).toBeTruthy(); expect(usernameCtrl.$invalid).toBe(undefined); expect(formCtrl.$invalid).toBe(undefined); usernameDefer.resolve(); $rootScope.$digest(); expect(usernameCtrl.$invalid).toBe(false); expect(formCtrl.$invalid).toBe(true); ageCtrl.$setViewValue(22); $rootScope.$digest(); expect(usernameCtrl.$invalid).toBe(false); expect(ageCtrl.$invalid).toBe(false); expect(formCtrl.$invalid).toBe(false); usernameCtrl.$setViewValue('valid'); $rootScope.$digest(); expect(usernameCtrl.$invalid).toBe(true); expect(ageCtrl.$invalid).toBe(false); expect(formCtrl.$invalid).toBe(true); usernameCtrl.$setViewValue('another-valid-username'); $rootScope.$digest(); usernameDefer.resolve(); $rootScope.$digest(); expect(usernameCtrl.$invalid).toBe(false); expect(formCtrl.$invalid).toBe(false); expect(formCtrl.$pending).toBeFalsy(); expect(ageCtrl.$invalid).toBe(false); dealoc(element); })); it('should always use the most recent $viewValue for validation', function() { ctrl.$parsers.push(function(value) { if (value && value.substr(-1) === 'b') { value = 'a'; ctrl.$setViewValue(value); ctrl.$render(); } return value; }); ctrl.$validators.mock = function(modelValue) { return true; }; spyOn(ctrl.$validators, 'mock').andCallThrough(); ctrl.$setViewValue('ab'); expect(ctrl.$validators.mock).toHaveBeenCalledWith('a', 'a'); expect(ctrl.$validators.mock.calls.length).toEqual(2); }); it('should validate even if the modelValue did not change', function() { ctrl.$parsers.push(function(value) { if (value && value.substr(-1) === 'b') { value = 'a'; } return value; }); ctrl.$validators.mock = function(modelValue) { return true; }; spyOn(ctrl.$validators, 'mock').andCallThrough(); ctrl.$setViewValue('a'); expect(ctrl.$validators.mock).toHaveBeenCalledWith('a', 'a'); expect(ctrl.$validators.mock.calls.length).toEqual(1); ctrl.$setViewValue('ab'); expect(ctrl.$validators.mock).toHaveBeenCalledWith('a', 'ab'); expect(ctrl.$validators.mock.calls.length).toEqual(2); }); it('should validate correctly when $parser name equals $validator key', function() { ctrl.$validators.parserOrValidator = function(value) { switch (value) { case 'allInvalid': case 'parseValid-validatorsInvalid': case 'stillParseValid-validatorsInvalid': return false; default: return true; } }; ctrl.$validators.validator = function(value) { switch (value) { case 'allInvalid': case 'parseValid-validatorsInvalid': case 'stillParseValid-validatorsInvalid': return false; default: return true; } }; ctrl.$$parserName = 'parserOrValidator'; ctrl.$parsers.push(function(value) { switch (value) { case 'allInvalid': case 'stillAllInvalid': case 'parseInvalid-validatorsValid': case 'stillParseInvalid-validatorsValid': return undefined; default: return value; } }); //Parser and validators are invalid scope.$apply('value = "allInvalid"'); expect(scope.value).toBe('allInvalid'); expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true}); ctrl.$validate(); expect(scope.value).toEqual('allInvalid'); expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true}); ctrl.$setViewValue('stillAllInvalid'); expect(scope.value).toBeUndefined(); expect(ctrl.$error).toEqual({parserOrValidator: true}); ctrl.$validate(); expect(scope.value).toBeUndefined(); expect(ctrl.$error).toEqual({parserOrValidator: true}); //Parser is valid, validators are invalid scope.$apply('value = "parseValid-validatorsInvalid"'); expect(scope.value).toBe('parseValid-validatorsInvalid'); expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true}); ctrl.$validate(); expect(scope.value).toBe('parseValid-validatorsInvalid'); expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true}); ctrl.$setViewValue('stillParseValid-validatorsInvalid'); expect(scope.value).toBeUndefined(); expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true}); ctrl.$validate(); expect(scope.value).toBeUndefined(); expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true}); //Parser is invalid, validators are valid scope.$apply('value = "parseInvalid-validatorsValid"'); expect(scope.value).toBe('parseInvalid-validatorsValid'); expect(ctrl.$error).toEqual({}); ctrl.$validate(); expect(scope.value).toBe('parseInvalid-validatorsValid'); expect(ctrl.$error).toEqual({}); ctrl.$setViewValue('stillParseInvalid-validatorsValid'); expect(scope.value).toBeUndefined(); expect(ctrl.$error).toEqual({parserOrValidator: true}); ctrl.$validate(); expect(scope.value).toBeUndefined(); expect(ctrl.$error).toEqual({parserOrValidator: true}); }); }); }); describe('CSS classes', function() { var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i; it('should set ng-empty or ng-not-empty when the view value changes', inject(function($compile, $rootScope, $sniffer) { var element = $compile('<input ng-model="value" />')($rootScope); $rootScope.$digest(); expect(element).toBeEmpty(); $rootScope.value = 'XXX'; $rootScope.$digest(); expect(element).toBeNotEmpty(); element.val(''); browserTrigger(element, $sniffer.hasEvent('input') ? 'input' : 'change'); expect(element).toBeEmpty(); element.val('YYY'); browserTrigger(element, $sniffer.hasEvent('input') ? 'input' : 'change'); expect(element).toBeNotEmpty(); })); it('should set css classes (ng-valid, ng-invalid, ng-pristine, ng-dirty, ng-untouched, ng-touched)', inject(function($compile, $rootScope, $sniffer) { var element = $compile('<input type="email" ng-model="value" />')($rootScope); $rootScope.$digest(); expect(element).toBeValid(); expect(element).toBePristine(); expect(element).toBeUntouched(); expect(element.hasClass('ng-valid-email')).toBe(true); expect(element.hasClass('ng-invalid-email')).toBe(false); $rootScope.$apply("value = 'invalid-email'"); expect(element).toBeInvalid(); expect(element).toBePristine(); expect(element.hasClass('ng-valid-email')).toBe(false); expect(element.hasClass('ng-invalid-email')).toBe(true); element.val('invalid-again'); browserTrigger(element, ($sniffer.hasEvent('input')) ? 'input' : 'change'); expect(element).toBeInvalid(); expect(element).toBeDirty(); expect(element.hasClass('ng-valid-email')).toBe(false); expect(element.hasClass('ng-invalid-email')).toBe(true); element.val('vojta@google.com'); browserTrigger(element, $sniffer.hasEvent('input') ? 'input' : 'change'); expect(element).toBeValid(); expect(element).toBeDirty(); expect(element.hasClass('ng-valid-email')).toBe(true); expect(element.hasClass('ng-invalid-email')).toBe(false); browserTrigger(element, 'blur'); expect(element).toBeTouched(); dealoc(element); })); it('should set invalid classes on init', inject(function($compile, $rootScope) { var element = $compile('<input type="email" ng-model="value" required />')($rootScope); $rootScope.$digest(); expect(element).toBeInvalid(); expect(element).toHaveClass('ng-invalid-required'); dealoc(element); })); }); describe('custom formatter and parser that are added by a directive in post linking', function() { var inputElm, scope; beforeEach(module(function($compileProvider) { $compileProvider.directive('customFormat', function() { return { require: 'ngModel', link: function(scope, element, attrs, ngModelCtrl) { ngModelCtrl.$formatters.push(function(value) { return value.part; }); ngModelCtrl.$parsers.push(function(value) { return {part: value}; }); } }; }); })); afterEach(function() { dealoc(inputElm); }); function createInput(type) { inject(function($compile, $rootScope) { scope = $rootScope; inputElm = $compile('<input type="' + type + '" ng-model="val" custom-format/>')($rootScope); }); } it('should use them after the builtin ones for text inputs', function() { createInput('text'); scope.$apply('val = {part: "a"}'); expect(inputElm.val()).toBe('a'); inputElm.val('b'); browserTrigger(inputElm, 'change'); expect(scope.val).toEqual({part: 'b'}); }); it('should use them after the builtin ones for number inputs', function() { createInput('number'); scope.$apply('val = {part: 1}'); expect(inputElm.val()).toBe('1'); inputElm.val('2'); browserTrigger(inputElm, 'change'); expect(scope.val).toEqual({part: 2}); }); it('should use them after the builtin ones for date inputs', function() { createInput('date'); scope.$apply(function() { scope.val = {part: new Date(2000, 10, 8)}; }); expect(inputElm.val()).toBe('2000-11-08'); inputElm.val('2001-12-09'); browserTrigger(inputElm, 'change'); expect(scope.val).toEqual({part: new Date(2001, 11, 9)}); }); }); describe('$touched', function() { it('should set the control touched state on "blur" event', inject(function($compile, $rootScope) { var element = $compile('<form name="myForm">' + '<input name="myControl" ng-model="value" >' + '</form>')($rootScope); var inputElm = element.find('input'); var control = $rootScope.myForm.myControl; expect(control.$touched).toBe(false); expect(control.$untouched).toBe(true); browserTrigger(inputElm, 'blur'); expect(control.$touched).toBe(true); expect(control.$untouched).toBe(false); dealoc(element); })); it('should not cause a digest on "blur" event if control is already touched', inject(function($compile, $rootScope) { var element = $compile('<form name="myForm">' + '<input name="myControl" ng-model="value" >' + '</form>')($rootScope); var inputElm = element.find('input'); var control = $rootScope.myForm.myControl; control.$setTouched(); spyOn($rootScope, '$apply'); browserTrigger(inputElm, 'blur'); expect($rootScope.$apply).not.toHaveBeenCalled(); dealoc(element); })); it('should digest asynchronously on "blur" event if a apply is already in progress', inject(function($compile, $rootScope) { var element = $compile('<form name="myForm">' + '<input name="myControl" ng-model="value" >' + '</form>')($rootScope); var inputElm = element.find('input'); var control = $rootScope.myForm.myControl; $rootScope.$apply(function() { expect(control.$touched).toBe(false); expect(control.$untouched).toBe(true); browserTrigger(inputElm, 'blur'); expect(control.$touched).toBe(false); expect(control.$untouched).toBe(true); }); expect(control.$touched).toBe(true); expect(control.$untouched).toBe(false); dealoc(element); })); }); describe('nested in a form', function() { it('should register/deregister a nested ngModel with parent form when entering or leaving DOM', inject(function($compile, $rootScope) { var element = $compile('<form name="myForm">' + '<input ng-if="inputPresent" name="myControl" ng-model="value" required >' + '</form>')($rootScope); var isFormValid; $rootScope.inputPresent = false; $rootScope.$watch('myForm.$valid', function(value) { isFormValid = value; }); $rootScope.$apply(); expect($rootScope.myForm.$valid).toBe(true); expect(isFormValid).toBe(true); expect($rootScope.myForm.myControl).toBeUndefined(); $rootScope.inputPresent = true; $rootScope.$apply(); expect($rootScope.myForm.$valid).toBe(false); expect(isFormValid).toBe(false); expect($rootScope.myForm.myControl).toBeDefined(); $rootScope.inputPresent = false; $rootScope.$apply(); expect($rootScope.myForm.$valid).toBe(true); expect(isFormValid).toBe(true); expect($rootScope.myForm.myControl).toBeUndefined(); dealoc(element); })); it('should register/deregister a nested ngModel with parent form when entering or leaving DOM with animations', function() { // ngAnimate performs the dom manipulation after digest, and since the form validity can be affected by a form // control going away we must ensure that the deregistration happens during the digest while we are still doing // dirty checking. module('ngAnimate'); inject(function($compile, $rootScope) { var element = $compile('<form name="myForm">' + '<input ng-if="inputPresent" name="myControl" ng-model="value" required >' + '</form>')($rootScope); var isFormValid; $rootScope.inputPresent = false; // this watch ensure that the form validity gets updated during digest (so that we can observe it) $rootScope.$watch('myForm.$valid', function(value) { isFormValid = value; }); $rootScope.$apply(); expect($rootScope.myForm.$valid).toBe(true); expect(isFormValid).toBe(true); expect($rootScope.myForm.myControl).toBeUndefined(); $rootScope.inputPresent = true; $rootScope.$apply(); expect($rootScope.myForm.$valid).toBe(false); expect(isFormValid).toBe(false); expect($rootScope.myForm.myControl).toBeDefined(); $rootScope.inputPresent = false; $rootScope.$apply(); expect($rootScope.myForm.$valid).toBe(true); expect(isFormValid).toBe(true); expect($rootScope.myForm.myControl).toBeUndefined(); dealoc(element); }); }); it('should keep previously defined watches consistent when changes in validity are made', inject(function($compile, $rootScope) { var isFormValid; $rootScope.$watch('myForm.$valid', function(value) { isFormValid = value; }); var element = $compile('<form name="myForm">' + '<input name="myControl" ng-model="value" required >' + '</form>')($rootScope); $rootScope.$apply(); expect(isFormValid).toBe(false); expect($rootScope.myForm.$valid).toBe(false); $rootScope.value='value'; $rootScope.$apply(); expect(isFormValid).toBe(true); expect($rootScope.myForm.$valid).toBe(true); dealoc(element); })); }); describe('animations', function() { function findElementAnimations(element, queue) { var node = element[0]; var animations = []; for (var i = 0; i < queue.length; i++) { var animation = queue[i]; if (animation.element[0] == node) { animations.push(animation); } } return animations; } function assertValidAnimation(animation, event, classNameA, classNameB) { expect(animation.event).toBe(event); expect(animation.args[1]).toBe(classNameA); if (classNameB) expect(animation.args[2]).toBe(classNameB); } var doc, input, scope, model; beforeEach(module('ngAnimateMock')); beforeEach(inject(function($rootScope, $compile, $rootElement, $animate) { scope = $rootScope.$new(); doc = jqLite('<form name="myForm">' + ' <input type="text" ng-model="input" name="myInput" />' + '</form>'); $rootElement.append(doc); $compile(doc)(scope); $animate.queue = []; input = doc.find('input'); model = scope.myForm.myInput; })); afterEach(function() { dealoc(input); }); it('should trigger an animation when invalid', inject(function($animate) { model.$setValidity('required', false); var animations = findElementAnimations(input, $animate.queue); assertValidAnimation(animations[0], 'removeClass', 'ng-valid'); assertValidAnimation(animations[1], 'addClass', 'ng-invalid'); assertValidAnimation(animations[2], 'addClass', 'ng-invalid-required'); })); it('should trigger an animation when valid', inject(function($animate) { model.$setValidity('required', false); $animate.queue = []; model.$setValidity('required', true); var animations = findElementAnimations(input, $animate.queue); assertValidAnimation(animations[0], 'addClass', 'ng-valid'); assertValidAnimation(animations[1], 'removeClass', 'ng-invalid'); assertValidAnimation(animations[2], 'addClass', 'ng-valid-required'); assertValidAnimation(animations[3], 'removeClass', 'ng-invalid-required'); })); it('should trigger an animation when dirty', inject(function($animate) { model.$setViewValue('some dirty value'); var animations = findElementAnimations(input, $animate.queue); assertValidAnimation(animations[0], 'removeClass', 'ng-empty'); assertValidAnimation(animations[1], 'addClass', 'ng-not-empty'); assertValidAnimation(animations[2], 'removeClass', 'ng-pristine'); assertValidAnimation(animations[3], 'addClass', 'ng-dirty'); })); it('should trigger an animation when pristine', inject(function($animate) { model.$setPristine(); var animations = findElementAnimations(input, $animate.queue); assertValidAnimation(animations[0], 'removeClass', 'ng-dirty'); assertValidAnimation(animations[1], 'addClass', 'ng-pristine'); })); it('should trigger an animation when untouched', inject(function($animate) { model.$setUntouched(); var animations = findElementAnimations(input, $animate.queue); assertValidAnimation(animations[0], 'setClass', 'ng-untouched'); expect(animations[0].args[2]).toBe('ng-touched'); })); it('should trigger an animation when touched', inject(function($animate) { model.$setTouched(); var animations = findElementAnimations(input, $animate.queue); assertValidAnimation(animations[0], 'setClass', 'ng-touched', 'ng-untouched'); expect(animations[0].args[2]).toBe('ng-untouched'); })); it('should trigger custom errors as addClass/removeClass when invalid/valid', inject(function($animate) { model.$setValidity('custom-error', false); var animations = findElementAnimations(input, $animate.queue); assertValidAnimation(animations[0], 'removeClass', 'ng-valid'); assertValidAnimation(animations[1], 'addClass', 'ng-invalid'); assertValidAnimation(animations[2], 'addClass', 'ng-invalid-custom-error'); $animate.queue = []; model.$setValidity('custom-error', true); animations = findElementAnimations(input, $animate.queue); assertValidAnimation(animations[0], 'addClass', 'ng-valid'); assertValidAnimation(animations[1], 'removeClass', 'ng-invalid'); assertValidAnimation(animations[2], 'addClass', 'ng-valid-custom-error'); assertValidAnimation(animations[3], 'removeClass', 'ng-invalid-custom-error'); })); }); }); describe('ngModelOptions attributes', function() { var helper, $rootScope, $compile, $timeout, $q; beforeEach(function() { helper = getInputCompileHelper(this); }); afterEach(function() { helper.dealoc(); }); beforeEach(inject(function(_$compile_, _$rootScope_, _$timeout_, _$q_) { $compile = _$compile_; $rootScope = _$rootScope_; $timeout = _$timeout_; $q = _$q_; })); it('should allow overriding the model update trigger event on text inputs', function() { var inputElm = helper.compileInput( '<input type="text" ng-model="name" name="alias" ' + 'ng-model-options="{ updateOn: \'blur\' }"' + '/>'); helper.changeInputValueTo('a'); expect($rootScope.name).toBeUndefined(); browserTrigger(inputElm, 'blur'); expect($rootScope.name).toEqual('a'); }); it('should not dirty the input if nothing was changed before updateOn trigger', function() { var inputElm = helper.compileInput( '<input type="text" ng-model="name" name="alias" ' + 'ng-model-options="{ updateOn: \'blur\' }"' + '/>'); browserTrigger(inputElm, 'blur'); expect($rootScope.form.alias.$pristine).toBeTruthy(); }); it('should allow overriding the model update trigger event on text areas', function() { var inputElm = helper.compileInput( '<textarea ng-model="name" name="alias" ' + 'ng-model-options="{ updateOn: \'blur\' }"' + '/>'); helper.changeInputValueTo('a'); expect($rootScope.name).toBeUndefined(); browserTrigger(inputElm, 'blur'); expect($rootScope.name).toEqual('a'); }); it('should bind the element to a list of events', function() { var inputElm = helper.compileInput( '<input type="text" ng-model="name" name="alias" ' + 'ng-model-options="{ updateOn: \'blur mousemove\' }"' + '/>'); helper.changeInputValueTo('a'); expect($rootScope.name).toBeUndefined(); browserTrigger(inputElm, 'blur'); expect($rootScope.name).toEqual('a'); helper.changeInputValueTo('b'); expect($rootScope.name).toEqual('a'); browserTrigger(inputElm, 'mousemove'); expect($rootScope.name).toEqual('b'); }); it('should allow keeping the default update behavior on text inputs', function() { var inputElm = helper.compileInput( '<input type="text" ng-model="name" name="alias" ' + 'ng-model-options="{ updateOn: \'default\' }"' + '/>'); helper.changeInputValueTo('a'); expect($rootScope.name).toEqual('a'); }); it('should allow sharing options between multiple inputs', function() { $rootScope.options = {updateOn: 'default'}; var inputElm = helper.compileInput( '<input type="text" ng-model="name1" name="alias1" ' + 'ng-model-options="options"' + '/>' + '<input type="text" ng-model="name2" name="alias2" ' + 'ng-model-options="options"' + '/>'); helper.changeGivenInputTo(inputElm.eq(0), 'a'); helper.changeGivenInputTo(inputElm.eq(1), 'b'); expect($rootScope.name1).toEqual('a'); expect($rootScope.name2).toEqual('b'); }); it('should hold a copy of the options object', function() { $rootScope.options = {updateOn: 'default'}; var inputElm = helper.compileInput( '<input type="text" ng-model="name" name="alias" ' + 'ng-model-options="options"' + '/>'); expect($rootScope.options).toEqual({updateOn: 'default'}); expect($rootScope.form.alias.$options).not.toBe($rootScope.options); }); it('should allow overriding the model update trigger event on checkboxes', function() { var inputElm = helper.compileInput( '<input type="checkbox" ng-model="checkbox" ' + 'ng-model-options="{ updateOn: \'blur\' }"' + '/>'); browserTrigger(inputElm, 'click'); expect($rootScope.checkbox).toBe(undefined); browserTrigger(inputElm, 'blur'); expect($rootScope.checkbox).toBe(true); browserTrigger(inputElm, 'click'); expect($rootScope.checkbox).toBe(true); }); it('should allow keeping the default update behavior on checkboxes', function() { var inputElm = helper.compileInput( '<input type="checkbox" ng-model="checkbox" ' + 'ng-model-options="{ updateOn: \'blur default\' }"' + '/>'); browserTrigger(inputElm, 'click'); expect($rootScope.checkbox).toBe(true); browserTrigger(inputElm, 'click'); expect($rootScope.checkbox).toBe(false); }); it('should allow overriding the model update trigger event on radio buttons', function() { var inputElm = helper.compileInput( '<input type="radio" ng-model="color" value="white" ' + 'ng-model-options="{ updateOn: \'blur\'}"' + '/>' + '<input type="radio" ng-model="color" value="red" ' + 'ng-model-options="{ updateOn: \'blur\'}"' + '/>' + '<input type="radio" ng-model="color" value="blue" ' + 'ng-model-options="{ updateOn: \'blur\'}"' + '/>'); $rootScope.$apply("color = 'white'"); browserTrigger(inputElm[2], 'click'); expect($rootScope.color).toBe('white'); browserTrigger(inputElm[2], 'blur'); expect($rootScope.color).toBe('blue'); }); it('should allow keeping the default update behavior on radio buttons', function() { var inputElm = helper.compileInput( '<input type="radio" ng-model="color" value="white" ' + 'ng-model-options="{ updateOn: \'blur default\' }"' + '/>' + '<input type="radio" ng-model="color" value="red" ' + 'ng-model-options="{ updateOn: \'blur default\' }"' + '/>' + '<input type="radio" ng-model="color" value="blue" ' + 'ng-model-options="{ updateOn: \'blur default\' }"' + '/>'); $rootScope.$apply("color = 'white'"); browserTrigger(inputElm[2], 'click'); expect($rootScope.color).toBe('blue'); }); it('should trigger only after timeout in text inputs', function() { var inputElm = helper.compileInput( '<input type="text" ng-model="name" name="alias" ' + 'ng-model-options="{ debounce: 10000 }"' + '/>'); helper.changeInputValueTo('a'); helper.changeInputValueTo('b'); helper.changeInputValueTo('c'); expect($rootScope.name).toEqual(undefined); $timeout.flush(2000); expect($rootScope.name).toEqual(undefined); $timeout.flush(9000); expect($rootScope.name).toEqual('c'); }); it('should trigger only after timeout in checkboxes', function() { var inputElm = helper.compileInput( '<input type="checkbox" ng-model="checkbox" ' + 'ng-model-options="{ debounce: 10000 }"' + '/>'); browserTrigger(inputElm, 'click'); expect($rootScope.checkbox).toBe(undefined); $timeout.flush(2000); expect($rootScope.checkbox).toBe(undefined); $timeout.flush(9000); expect($rootScope.checkbox).toBe(true); }); it('should trigger only after timeout in radio buttons', function() { var inputElm = helper.compileInput( '<input type="radio" ng-model="color" value="white" />' + '<input type="radio" ng-model="color" value="red" ' + 'ng-model-options="{ debounce: 20000 }"' + '/>' + '<input type="radio" ng-model="color" value="blue" ' + 'ng-model-options="{ debounce: 30000 }"' + '/>'); browserTrigger(inputElm[0], 'click'); expect($rootScope.color).toBe('white'); browserTrigger(inputElm[1], 'click'); expect($rootScope.color).toBe('white'); $timeout.flush(12000); expect($rootScope.color).toBe('white'); $timeout.flush(10000); expect($rootScope.color).toBe('red'); }); it('should not trigger digest while debouncing', function() { var inputElm = helper.compileInput( '<input type="text" ng-model="name" name="alias" ' + 'ng-model-options="{ debounce: 10000 }"' + '/>'); var watchSpy = jasmine.createSpy('watchSpy'); $rootScope.$watch(watchSpy); helper.changeInputValueTo('a'); expect(watchSpy).not.toHaveBeenCalled(); $timeout.flush(10000); expect(watchSpy).toHaveBeenCalled(); }); it('should allow selecting different debounce timeouts for each event', function() { var inputElm = helper.compileInput( '<input type="text" ng-model="name" name="alias" ' + 'ng-model-options="{' + 'updateOn: \'default blur\', ' + 'debounce: { default: 10000, blur: 5000 }' + '}"' + '/>'); helper.changeInputValueTo('a'); expect($rootScope.checkbox).toBe(undefined); $timeout.flush(6000); expect($rootScope.checkbox).toBe(undefined); $timeout.flush(4000); expect($rootScope.name).toEqual('a'); helper.changeInputValueTo('b'); browserTrigger(inputElm, 'blur'); $timeout.flush(4000); expect($rootScope.name).toEqual('a'); $timeout.flush(2000); expect($rootScope.name).toEqual('b'); }); it('should allow selecting different debounce timeouts for each event on checkboxes', function() { var inputElm = helper.compileInput('<input type="checkbox" ng-model="checkbox" ' + 'ng-model-options="{ ' + 'updateOn: \'default blur\', debounce: { default: 10000, blur: 5000 } }"' + '/>'); inputElm[0].checked = false; browserTrigger(inputElm, 'click'); expect($rootScope.checkbox).toBe(undefined); $timeout.flush(8000); expect($rootScope.checkbox).toBe(undefined); $timeout.flush(3000); expect($rootScope.checkbox).toBe(true); inputElm[0].checked = true; browserTrigger(inputElm, 'click'); browserTrigger(inputElm, 'blur'); $timeout.flush(3000); expect($rootScope.checkbox).toBe(true); $timeout.flush(3000); expect($rootScope.checkbox).toBe(false); }); it('should allow selecting 0 for non-default debounce timeouts for each event on checkboxes', function() { var inputElm = helper.compileInput('<input type="checkbox" ng-model="checkbox" ' + 'ng-model-options="{ ' + 'updateOn: \'default blur\', debounce: { default: 10000, blur: 0 } }"' + '/>'); inputElm[0].checked = false; browserTrigger(inputElm, 'click'); expect($rootScope.checkbox).toBe(undefined); $timeout.flush(8000); expect($rootScope.checkbox).toBe(undefined); $timeout.flush(3000); expect($rootScope.checkbox).toBe(true); inputElm[0].checked = true; browserTrigger(inputElm, 'click'); browserTrigger(inputElm, 'blur'); $timeout.flush(0); expect($rootScope.checkbox).toBe(false); }); it('should inherit model update settings from ancestor elements', function() { var doc = $compile( '<form name="test" ' + 'ng-model-options="{ debounce: 10000, updateOn: \'blur\' }" >' + '<input type="text" ng-model="name" name="alias" />' + '</form>')($rootScope); $rootScope.$digest(); var inputElm = doc.find('input').eq(0); helper.changeGivenInputTo(inputElm, 'a'); expect($rootScope.name).toEqual(undefined); browserTrigger(inputElm, 'blur'); expect($rootScope.name).toBe(undefined); $timeout.flush(2000); expect($rootScope.name).toBe(undefined); $timeout.flush(9000); expect($rootScope.name).toEqual('a'); dealoc(doc); }); it('should flush debounced events when calling $commitViewValue directly', function() { var inputElm = helper.compileInput( '<input type="text" ng-model="name" name="alias" ' + 'ng-model-options="{ debounce: 1000 }" />'); helper.changeInputValueTo('a'); expect($rootScope.name).toEqual(undefined); $rootScope.form.alias.$commitViewValue(); expect($rootScope.name).toEqual('a'); }); it('should cancel debounced events when calling $commitViewValue', function() { var inputElm = helper.compileInput( '<input type="text" ng-model="name" name="alias" ' + 'ng-model-options="{ debounce: 1000 }"/>'); helper.changeInputValueTo('a'); $rootScope.form.alias.$commitViewValue(); expect($rootScope.name).toEqual('a'); $rootScope.form.alias.$setPristine(); $timeout.flush(1000); expect($rootScope.form.alias.$pristine).toBeTruthy(); }); it('should reset input val if rollbackViewValue called during pending update', function() { var inputElm = helper.compileInput( '<input type="text" ng-model="name" name="alias" ' + 'ng-model-options="{ updateOn: \'blur\' }" />'); helper.changeInputValueTo('a'); expect(inputElm.val()).toBe('a'); $rootScope.form.alias.$rollbackViewValue(); expect(inputElm.val()).toBe(''); browserTrigger(inputElm, 'blur'); expect(inputElm.val()).toBe(''); }); it('should allow canceling pending updates', function() { var inputElm = helper.compileInput( '<input type="text" ng-model="name" name="alias" ' + 'ng-model-options="{ updateOn: \'blur\' }" />'); helper.changeInputValueTo('a'); expect($rootScope.name).toEqual(undefined); $rootScope.form.alias.$rollbackViewValue(); expect($rootScope.name).toEqual(undefined); browserTrigger(inputElm, 'blur'); expect($rootScope.name).toEqual(undefined); }); it('should allow canceling debounced updates', function() { var inputElm = helper.compileInput( '<input type="text" ng-model="name" name="alias" ' + 'ng-model-options="{ debounce: 10000 }" />'); helper.changeInputValueTo('a'); expect($rootScope.name).toEqual(undefined); $timeout.flush(2000); $rootScope.form.alias.$rollbackViewValue(); expect($rootScope.name).toEqual(undefined); $timeout.flush(10000); expect($rootScope.name).toEqual(undefined); }); it('should handle model updates correctly even if rollbackViewValue is not invoked', function() { var inputElm = helper.compileInput( '<input type="text" ng-model="name" name="alias" ' + 'ng-model-options="{ updateOn: \'blur\' }" />'); helper.changeInputValueTo('a'); $rootScope.$apply("name = 'b'"); browserTrigger(inputElm, 'blur'); expect($rootScope.name).toBe('b'); }); it('should reset input val if rollbackViewValue called during debounce', function() { var inputElm = helper.compileInput( '<input type="text" ng-model="name" name="alias" ' + 'ng-model-options="{ debounce: 2000 }" />'); helper.changeInputValueTo('a'); expect(inputElm.val()).toBe('a'); $rootScope.form.alias.$rollbackViewValue(); expect(inputElm.val()).toBe(''); $timeout.flush(3000); expect(inputElm.val()).toBe(''); }); it('should not try to invoke a model if getterSetter is false', function() { var inputElm = helper.compileInput( '<input type="text" ng-model="name" ' + 'ng-model-options="{ getterSetter: false }" />'); var spy = $rootScope.name = jasmine.createSpy('setterSpy'); helper.changeInputValueTo('a'); expect(spy).not.toHaveBeenCalled(); expect(inputElm.val()).toBe('a'); }); it('should not try to invoke a model if getterSetter is not set', function() { var inputElm = helper.compileInput('<input type="text" ng-model="name" />'); var spy = $rootScope.name = jasmine.createSpy('setterSpy'); helper.changeInputValueTo('a'); expect(spy).not.toHaveBeenCalled(); expect(inputElm.val()).toBe('a'); }); it('should try to invoke a function model if getterSetter is true', function() { var inputElm = helper.compileInput( '<input type="text" ng-model="name" ' + 'ng-model-options="{ getterSetter: true }" />'); var spy = $rootScope.name = jasmine.createSpy('setterSpy').andCallFake(function() { return 'b'; }); $rootScope.$apply(); expect(inputElm.val()).toBe('b'); helper.changeInputValueTo('a'); expect(inputElm.val()).toBe('b'); expect(spy).toHaveBeenCalledWith('a'); expect($rootScope.name).toBe(spy); }); it('should assign to non-function models if getterSetter is true', function() { var inputElm = helper.compileInput( '<input type="text" ng-model="name" ' + 'ng-model-options="{ getterSetter: true }" />'); $rootScope.name = 'c'; helper.changeInputValueTo('d'); expect(inputElm.val()).toBe('d'); expect($rootScope.name).toBe('d'); }); it('should fail on non-assignable model binding if getterSetter is false', function() { expect(function() { var inputElm = helper.compileInput('<input type="text" ng-model="accessor(user, \'name\')" />'); }).toThrowMinErr('ngModel', 'nonassign', 'Expression \'accessor(user, \'name\')\' is non-assignable.'); }); it('should not fail on non-assignable model binding if getterSetter is true', function() { var inputElm = helper.compileInput( '<input type="text" ng-model="accessor(user, \'name\')" ' + 'ng-model-options="{ getterSetter: true }" />'); }); it('should invoke a model in the correct context if getterSetter is true', function() { var inputElm = helper.compileInput( '<input type="text" ng-model="someService.getterSetter" ' + 'ng-model-options="{ getterSetter: true }" />'); $rootScope.someService = { value: 'a', getterSetter: function(newValue) { this.value = newValue || this.value; return this.value; } }; spyOn($rootScope.someService, 'getterSetter').andCallThrough(); $rootScope.$apply(); expect(inputElm.val()).toBe('a'); expect($rootScope.someService.getterSetter).toHaveBeenCalledWith(); expect($rootScope.someService.value).toBe('a'); helper.changeInputValueTo('b'); expect($rootScope.someService.getterSetter).toHaveBeenCalledWith('b'); expect($rootScope.someService.value).toBe('b'); $rootScope.someService.value = 'c'; $rootScope.$apply(); expect(inputElm.val()).toBe('c'); expect($rootScope.someService.getterSetter).toHaveBeenCalledWith(); }); it('should assign invalid values to the scope if allowInvalid is true', function() { var inputElm = helper.compileInput('<input type="text" name="input" ng-model="value" maxlength="1" ' + 'ng-model-options="{allowInvalid: true}" />'); helper.changeInputValueTo('12345'); expect($rootScope.value).toBe('12345'); expect(inputElm).toBeInvalid(); }); it('should not assign not parsable values to the scope if allowInvalid is true', function() { var inputElm = helper.compileInput('<input type="number" name="input" ng-model="value" ' + 'ng-model-options="{allowInvalid: true}" />', { valid: false, badInput: true }); helper.changeInputValueTo('abcd'); expect($rootScope.value).toBeUndefined(); expect(inputElm).toBeInvalid(); }); it('should update the scope before async validators execute if allowInvalid is true', function() { var inputElm = helper.compileInput('<input type="text" name="input" ng-model="value" ' + 'ng-model-options="{allowInvalid: true}" />'); var defer; $rootScope.form.input.$asyncValidators.promiseValidator = function(value) { defer = $q.defer(); return defer.promise; }; helper.changeInputValueTo('12345'); expect($rootScope.value).toBe('12345'); expect($rootScope.form.input.$pending.promiseValidator).toBe(true); defer.reject(); $rootScope.$digest(); expect($rootScope.value).toBe('12345'); expect(inputElm).toBeInvalid(); }); it('should update the view before async validators execute if allowInvalid is true', function() { var inputElm = helper.compileInput('<input type="text" name="input" ng-model="value" ' + 'ng-model-options="{allowInvalid: true}" />'); var defer; $rootScope.form.input.$asyncValidators.promiseValidator = function(value) { defer = $q.defer(); return defer.promise; }; $rootScope.$apply('value = \'12345\''); expect(inputElm.val()).toBe('12345'); expect($rootScope.form.input.$pending.promiseValidator).toBe(true); defer.reject(); $rootScope.$digest(); expect(inputElm.val()).toBe('12345'); expect(inputElm).toBeInvalid(); }); it('should not call ng-change listeners twice if the model did not change with allowInvalid', function() { var inputElm = helper.compileInput('<input type="text" name="input" ng-model="value" ' + 'ng-model-options="{allowInvalid: true}" ng-change="changed()" />'); $rootScope.changed = jasmine.createSpy('changed'); $rootScope.form.input.$parsers.push(function(value) { return 'modelValue'; }); helper.changeInputValueTo('input1'); expect($rootScope.value).toBe('modelValue'); expect($rootScope.changed).toHaveBeenCalledOnce(); helper.changeInputValueTo('input2'); expect($rootScope.value).toBe('modelValue'); expect($rootScope.changed).toHaveBeenCalledOnce(); }); });
module("Director.js", { setup: function() { window.location.hash = ""; shared = {}; }, teardown: function() { window.location.hash = ""; shared = {}; } }); var shared; function createTest(name, config, use, test) { if (typeof use === 'function') { test = use; use = undefined; } asyncTest(name, function() { setTimeout(function() { var router = new Router(config), context; if (use !== undefined) { router.configure(use); } router.init(); test.call(context = { router: router, navigate: function(url, callback) { window.location.hash = url; setTimeout(function() { callback.call(context); }, 14); }, finish: function() { router.destroy(); start(); } }); }, 14); }); };
({"he":"עברית","hello":"שלום","yi":"Yiddish","en-us-texas":"English (Texas)","es":"Spanish","de":"German","pl":"Polish","hello_dojo":"${hello}, ${dojo}!","fa":"Farsi","pt":"Portugese","zh-tw":"Chinese (Traditional)","sw":"Kiswahili","ar":"Arabic","en-us-new_york-brooklyn":"English (Brooklynese)","ru":"Russian","fr":"French","th":"Thai","it":"Italian","cs":"Czech","hi":"Hindi","en-us-hawaii":"English (US-Hawaii)","file_not_found":"The file you requested, ${0}, is not found.","en-au":"English (Australia)","el":"Greek","ko":"Korean","tr":"Turkish","en":"English","ja":"Japanese","zh-cn":"Chinese (Simplified)","dojo":"Dojo"})
// @flow // $ExpectError: No negative tests here const skipNegativeTest: string = true; var inquirer = require('inquirer'); var directionsPrompt = { type: 'list', name: 'direction', message: 'Which direction would you like to go?', choices: ['Forward', 'Right', 'Left', 'Back'] }; function main() { console.log('You find youself in a small room, there is a door in front of you.'); exitHouse(); } function exitHouse() { inquirer.prompt(directionsPrompt).then(function (answers) { if (answers.direction === 'Forward') { console.log('You find yourself in a forest'); console.log('There is a wolf in front of you; a friendly looking dwarf to the right and an impasse to the left.'); encounter1(); } else { console.log('You cannot go that way. Try again'); exitHouse(); } }); } function encounter1() { inquirer.prompt(directionsPrompt).then(function (answers) { var direction = answers.direction; if (direction === 'Forward') { console.log('You attempt to fight the wolf'); console.log('Theres a stick and some stones lying around you could use as a weapon'); encounter2b(); } else if (direction === 'Right') { console.log('You befriend the dwarf'); console.log('He helps you kill the wolf. You can now move forward'); encounter2a(); } else { console.log('You cannot go that way'); encounter1(); } }); } function encounter2a() { inquirer.prompt(directionsPrompt).then(function (answers) { var direction = answers.direction; if (direction === 'Forward') { var output = 'You find a painted wooden sign that says:'; output += ' \n'; output += ' ____ _____ ____ _____ \n'; output += '(_ _)( _ )( _ \\( _ ) \n'; output += ' )( )(_)( )(_) ))(_)( \n'; output += ' (__) (_____)(____/(_____) \n'; console.log(output); } else { console.log('You cannot go that way'); encounter2a(); } }); } function encounter2b() { inquirer.prompt({ type: 'list', name: 'weapon', message: 'Pick one', choices: [ 'Use the stick', 'Grab a large rock', 'Try and make a run for it', 'Attack the wolf unarmed' ] }).then(function () { console.log('The wolf mauls you. You die. The end.'); }); } main();
/** * Module dependencies. */ var express = require('../../'); var cookie-parser = require('cookie-parser'); var app = module.exports = express(); // pass a secret to cookieParser() for signed cookies app.use(cookieParser('manny is cool')); // add req.session cookie support app.use(cookieSession()); // do something with the session app.use(count); // custom middleware function count(req, res) { req.session.count = req.session.count || 0; var n = req.session.count++; res.send('viewed ' + n + ' times\n'); } /* istanbul ignore next */ if (!module.parent) { app.listen(3000); console.log('Express started on port 3000'); }
/***************************************************************************** * * Author: Kerri Shotts <kerrishotts@gmail.com> * http://www.photokandy.com/books/mastering-phonegap * * MIT LICENSED * * Copyright (c) 2016 Kerri Shotts (photoKandy Studios LLC) * Portions Copyright various third parties where noted. * * 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. * *****************************************************************************/ /* @flow */ "use strict"; /*globals cordova*/ import Emitter from "yasmf-emitter"; // private properties -- we need some symbols let _selectors = Symbol(); let _useSmoothScrolling = Symbol(); let _smoothScrollDuration = Symbol(); let _showElementUnderKeyboard = Symbol(); /** * given a selector string, return matching elements in an Array * @param {string} selectorString * @return Array<Node> */ function getScrollContainers(selectorString/*: string*/)/*: Array<Node>*/ { return Array.from(document.querySelectorAll(selectorString)); } /** * Given an element, returns an array representing the start and end of * the current selection. * @param {Node} focusedElement * @return Array<number> */ function getElementSelection(focusedElement/*: Node*/)/*: Array<number>*/ { return [focusedElement.selectionStart, focusedElement.selectionEnd]; } /** * Given an element and a tuple representing the start and end of the selection, * set the selection on the element. * @param {Node} focusedElement * @param {number} selectionStart the start of the selection * @param {number} selectionEnd the end of the selection */ function setElementSelection(focusedElement/*: Node*/, [selectionStart/*: number*/, selectionEnd/*: number*/] = [0, 0])/*: void*/ { focusedElement.selectionStart = selectionStart; focusedElement.selectionEnd = selectionEnd; } function showElementUnderKeyboard(keyboardHeight/*: number*/) { let e = document.createElement("div"); e.className = "sk-element-under-keyboard"; e.style.position = "absolute"; e.style.bottom = "0"; e.style.left = "0"; e.style.right = "0"; e.style.zIndex = "9999999999999"; e.style.height = `${keyboardHeight}px`; document.body.appendChild(e); } function hideElementUnderKeyboard()/*: void*/ { let els = Array.from(document.querySelectorAll(".sk-element-under-keyboard")); els.forEach((el) => document.body.removeChild(el)); } /** * Saves the element's current text selection, then resets it to 0. After a tick, it * restores the element's saved text selection. * This is to fix iOS's buggy behavior regarding cursor positioning after the scrolling * of an element. * * @param {Node} focusedElement */ function handleTextSelection(focusedElement/*: Node*/)/*: void*/ { setTimeout(() => { // save the selection let selection = getElementSelection(focusedElement); // reset the selection to 0,0 setElementSelection(focusedElement); // after a short delay, restore the selection setTimeout(() => setElementSelection(focusedElement, selection), 33); }, 0); } /** * Provides methods for avoiding the soft keyboard. This tries to be automatic, * but you will need to supply scrollable selectors. */ export default class SoftKeyboard extends Emitter { /** * Construct an instance of the SoftKeyboard * * @return SoftKeyboard */ constructor(options) { super(options); } /** * Initialize a SoftKeyboard. Will be called automatically during construction * @param {Array<string>} [selectors] defaults to an empty array * @param {boolean} [useSmoothScrolling] defaults to true * @param {number} [smoothScrollDuration] defaults to 100 * @param {boolean} [showElementUnderKeyboard] defaults to false */ init({selectors=[], useSmoothScrolling = true, smoothScrollDuration = 100, showElementUnderKeyboard = false} = {}) { // selectors: Array, useSmoothScrolling: boolean, smoothScrollDuration: number if (typeof cordova !== "undefined") { if (cordova.plugins && cordova.plugins.Keyboard) { cordova.plugins.Keyboard.disableScroll(true); window.addEventListener("native.keyboardshow", this.keyboardShown.bind(this)); window.addEventListener("native.keyboardhide", this.keyboardHidden.bind(this)); } } this[_selectors] = new Set(); selectors.forEach(sel => this.addSelector(sel)); this[_useSmoothScrolling] = useSmoothScrolling; this[_smoothScrollDuration] = smoothScrollDuration; this[_showElementUnderKeyboard] = showElementUnderKeyboard; } /** * Adds a selector * @param {string} selector A CSS selector that identifies a scrolling container * @return {SoftKeyboard} */ addSelector(selector/*: string*/)/*: SoftKeyboard*/ { this[_selectors].add(selector); return this; } /** * Removes a selector * @param {string} selector A CSS selector that identifies a scrolling container * @return {SoftKeyboard} */ removeSelector(selector/*: string*/)/*: SoftKeyboard*/ { this[_selectors].delete(selector); return this; } get selectors()/*: Array*/ { return Array.from(this[_selectors]); } get selectorString()/*: string*/ { return this.selectors.join(", "); } get useSmoothScrolling()/*: boolean*/ { return this[_useSmoothScrolling]; } set useSmoothScrolling(b/*: boolean*/)/*: void*/ { this[_useSmoothScrolling] = b; } get smoothScrollDuration()/*: number*/ { return this[_smoothScrollDuration]; } set smoothScrollDuration(d/*: number*/)/*: void*/ { this[_smoothScrollDuration] = d; } get showElementUnderKeyboard()/*: boolean*/ { return this[_showElementUnderKeyboard]; } set showElementUnderKeyboard(b/*: boolean*/)/*: void*/ { this[_showElementUnderKeyboard] = b; } /** * Shows the keyboard, if possible */ showKeyboard(force/*: boolean*/ = false)/*: void*/ { if (typeof cordova !== "undefined") { if (cordova.plugins && cordova.plugins.Keyboard) { cordova.plugins.Keyboard.show(); return; } } if (force) { this.keyboardShown({keyboardHeight: 240}); } } /** * Hide the keyboard, if possible */ hideKeyboard(force/*: boolean*/ = false)/*: void*/ { if (typeof cordova !== "undefined") { if (cordova.plugins && cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hide(); return; } } if (force) { this.keyboardHidden({}); } } /** * Triggered when the soft keyboard is displayed * @param {{keyboardHeight: number}} e the event triggered from the keyboard plugin */ keyboardShown(e)/*: void*/ { this.emit("keyboardShown", e); this.emit("willResize", e); console.log ("keyboard shown", e.keyboardHeight); setTimeout(() => { let screenHeight = window.innerHeight; //(document.body.clientWidth === window.screen.height ? window.screen.width : window.screen.height); let scrollContainers = getScrollContainers(this.selectorString); let keyboardHeight = 0; //e.keyboardHeight; if (this.showElementUnderKeyboard) { showElementUnderKeyboard(keyboardHeight); } // for each scroll container in the DOM, we need to calculate the // the height it should be to fit in the reduced view scrollContainers.forEach((sc) => { let scTop = sc.getBoundingClientRect().top; // now that we know the top of the scroll container, the height of the // the screen, and the height of the keyboard, we can calculate the // appropriate max-height for the container. let maxHeight = "" + (screenHeight - keyboardHeight - scTop); console.log("New height", maxHeight); if (maxHeight > 100) { sc.style.maxHeight = maxHeight + "px"; } }); this.emit("didResize", e); // changing the height isn't sufficient: we need to scroll any focused // element into view. setTimeout(() => { let focusedElement = document.querySelector(":focus"); if (focusedElement) { if (!this.useSmoothScrolling || !window.requestAnimationFrame) { // scroll the element into view, but only if we have to if (focusedElement.scrollIntoViewIfNeeded) { focusedElement.scrollIntoViewIfNeeded(); } else { // aim for the bottom of the viewport focusedElement.scrollIntoView(false); } // iOS doesn't always position the cursor correctly after // a scroll operation. Clear the selection so that iOS is // forced to recompute where the cursor should appear. handleTextSelection(focusedElement); } else { // to scroll the element smoothly into view, things become a little // more difficult. let fElTop = focusedElement.getBoundingClientRect().top, sc = focusedElement, scTop, scBottom, selectorString = this.selectorString; // find the containing scroll container if we can while (sc && !sc.matches(selectorString)) { sc = sc.parentElement; } if (sc) { scTop = sc.getBoundingClientRect().top; scBottom = sc.getBoundingClientRect().bottom; if (fElTop < scTop || fElTop > (((scBottom - scTop) / 2) + scTop)) { // the element isn't above the keyboard (or is too far above), // scroll it into view smoothly let targetTop = ((scBottom - scTop) / 2) + scTop, deltaTop = fElTop - targetTop, origScrollTop = sc.scrollTop, startTimestamp = null; // animate our scroll let scrollStep; window.requestAnimationFrame(scrollStep = (timestamp) => { if (!startTimestamp) { startTimestamp = timestamp; } var progressDelta = timestamp - startTimestamp, pct = progressDelta / this.smoothScrollDuration; sc.scrollTop = origScrollTop + (deltaTop * pct); if (progressDelta < this.smoothScrollDuration) { window.requestAnimationFrame(scrollStep); } else { // set the scroll to the final desired position, just in case // we didn't actually get there (or overshot) sc.scrollTop = origScrollTop + deltaTop; handleTextSelection(focusedElement); } }); } } } } }, 0); }, 0); } /** * Triggered when the soft keyboard is hidden * @param {*} e */ keyboardHidden(e)/*: void*/ { setTimeout(() => { this.emit("keyboardHidden", e); this.emit("willResize", e); let scrollContainers = getScrollContainers(this.selectorString); scrollContainers.forEach(el => el.style.maxHeight = ""); hideElementUnderKeyboard(); this.emit("didResize", e); }, 0); } } export function createSoftKeyboard(...args) { return new SoftKeyboard(...args); }
import { ElementRef, Input, Component, NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { Calendar } from '@fullcalendar/core'; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var FullCalendar = /** @class */ (function () { function FullCalendar(el) { this.el = el; } FullCalendar.prototype.ngOnInit = function () { this.config = { theme: true }; if (this.options) { for (var prop in this.options) { this.config[prop] = this.options[prop]; } } }; FullCalendar.prototype.ngAfterViewChecked = function () { if (!this.initialized && this.el.nativeElement.offsetParent) { this.initialize(); } }; Object.defineProperty(FullCalendar.prototype, "events", { get: function () { return this._events; }, set: function (value) { this._events = value; if (this._events && this.calendar) { this.calendar.removeAllEventSources(); this.calendar.addEventSource(this._events); } }, enumerable: true, configurable: true }); Object.defineProperty(FullCalendar.prototype, "options", { get: function () { return this._options; }, set: function (value) { this._options = value; if (this._options && this.calendar) { for (var prop in this._options) { var optionValue = this._options[prop]; this.config[prop] = optionValue; this.calendar.setOption(prop, optionValue); } } }, enumerable: true, configurable: true }); FullCalendar.prototype.initialize = function () { this.calendar = new Calendar(this.el.nativeElement.children[0], this.config); this.calendar.render(); this.initialized = true; if (this.events) { this.calendar.removeAllEventSources(); this.calendar.addEventSource(this.events); } }; FullCalendar.prototype.getCalendar = function () { return this.calendar; }; FullCalendar.prototype.ngOnDestroy = function () { if (this.calendar) { this.calendar.destroy(); this.initialized = false; this.calendar = null; } }; FullCalendar.ctorParameters = function () { return [ { type: ElementRef } ]; }; __decorate([ Input() ], FullCalendar.prototype, "style", void 0); __decorate([ Input() ], FullCalendar.prototype, "styleClass", void 0); __decorate([ Input() ], FullCalendar.prototype, "events", null); __decorate([ Input() ], FullCalendar.prototype, "options", null); FullCalendar = __decorate([ Component({ selector: 'p-fullCalendar', template: '<div [ngStyle]="style" [class]="styleClass"></div>' }) ], FullCalendar); return FullCalendar; }()); var FullCalendarModule = /** @class */ (function () { function FullCalendarModule() { } FullCalendarModule = __decorate([ NgModule({ imports: [CommonModule], exports: [FullCalendar], declarations: [FullCalendar] }) ], FullCalendarModule); return FullCalendarModule; }()); /** * Generated bundle index. Do not edit. */ export { FullCalendar, FullCalendarModule }; //# sourceMappingURL=primeng-fullcalendar.js.map
export const EXAMPLE_REPOSITORIES = { clock: { repo: 'https://github.com/meteor/clock' }, leaderboard: { repo: 'https://github.com/meteor/leaderboard' }, localmarket: { repo: 'https://github.com/meteor/localmarket' }, 'simple-todos': { repo: 'https://github.com/meteor/simple-todos' }, 'simple-todos-react': { repo: 'https://github.com/meteor/simple-todos-react' }, 'simple-todos-angular': { repo: 'https://github.com/meteor/simple-todos-angular' }, todos: { repo: 'https://github.com/meteor/todos' }, 'todos-react': { 'repo': 'https://github.com/meteor/todos', 'branch': 'react', }, 'angular2-boilerplate': { repo: 'https://github.com/bsliran/angular2-meteor-base' } };
import EmptyObject from 'ember-data/-private/system/empty-object'; import parseResponseHeaders from 'ember-data/-private/utils/parse-response-headers'; import { module, test } from 'qunit'; const CRLF = '\u000d\u000a'; module('unit/adapters/parse-response-headers'); test('returns an EmptyObject when headersString is undefined', function(assert) { let headers = parseResponseHeaders(undefined); assert.deepEqual(headers, new EmptyObject(), 'EmptyObject is returned'); }); test('header parsing', function(assert) { let headersString = [ 'Content-Encoding: gzip', 'content-type: application/json; charset=utf-8', 'date: Fri, 05 Feb 2016 21:47:56 GMT' ].join(CRLF); let headers = parseResponseHeaders(headersString); assert.equal(headers['Content-Encoding'], 'gzip', 'parses basic header pair'); assert.equal(headers['content-type'], 'application/json; charset=utf-8', 'parses header with complex value'); assert.equal(headers['date'], 'Fri, 05 Feb 2016 21:47:56 GMT', 'parses header with date value'); }); test('field-name parsing', function(assert) { let headersString = [ ' name-with-leading-whitespace: some value', 'name-with-whitespace-before-colon : another value' ].join(CRLF); let headers = parseResponseHeaders(headersString); assert.equal(headers['name-with-leading-whitespace'], 'some value', 'strips leading whitespace from field-name'); assert.equal(headers['name-with-whitespace-before-colon'], 'another value', 'strips whitespace before colon from field-name'); }); test('field-value parsing', function(assert) { let headersString = [ 'value-with-leading-space: value with leading whitespace', 'value-without-leading-space:value without leading whitespace', 'value-with-colon: value with: a colon', 'value-with-trailing-whitespace: banana ' ].join(CRLF); let headers = parseResponseHeaders(headersString); assert.equal(headers['value-with-leading-space'], 'value with leading whitespace', 'strips leading whitespace in field-value'); assert.equal(headers['value-without-leading-space'], 'value without leading whitespace', 'works without leaading whitespace in field-value'); assert.equal(headers['value-with-colon'], 'value with: a colon', 'has correct value when value contains a colon'); assert.equal(headers['value-with-trailing-whitespace'], 'banana', 'strips trailing whitespace from field-value'); }); test('ignores headers that do not contain a colon', function(assert) { let headersString = [ 'Content-Encoding: gzip', 'I am ignored because I do not contain a colon' ].join(CRLF); let headers = parseResponseHeaders(headersString); assert.deepEqual(headers['Content-Encoding'], 'gzip', 'parses basic header pair'); assert.equal(Object.keys(headers).length, 1, 'only has the one valid header'); });
ace.define("ace/theme/kuroir",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { exports.isDark = false; exports.cssClass = "ace-kuroir"; exports.cssText = "\ .ace-kuroir .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ .ace-kuroir .ace_print-margin {\ width: 1px;\ background: #e8e8e8;\ }\ .ace-kuroir {\ background-color: #E8E9E8;\ color: #363636;\ }\ .ace-kuroir .ace_cursor {\ color: #202020;\ }\ .ace-kuroir .ace_marker-layer .ace_selection {\ background: rgba(245, 170, 0, 0.57);\ }\ .ace-kuroir.ace_multiselect .ace_selection.ace_start {\ box-shadow: 0 0 3px 0px #E8E9E8;\ border-radius: 2px;\ }\ .ace-kuroir .ace_marker-layer .ace_step {\ background: rgb(198, 219, 174);\ }\ .ace-kuroir .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgba(0, 0, 0, 0.29);\ }\ .ace-kuroir .ace_marker-layer .ace_active-line {\ background: rgba(203, 220, 47, 0.22);\ }\ .ace-kuroir .ace_gutter-active-line {\ background-color: rgba(203, 220, 47, 0.22);\ }\ .ace-kuroir .ace_marker-layer .ace_selected-word {\ border: 1px solid rgba(245, 170, 0, 0.57);\ }\ .ace-kuroir .ace_invisible {\ color: #BFBFBF\ }\ .ace-kuroir .ace_fold {\ border-color: #363636;\ }\ .ace-kuroir .ace_constant{color:#CD6839;}.ace-kuroir .ace_constant.ace_numeric{color:#9A5925;}.ace-kuroir .ace_support{color:#104E8B;}.ace-kuroir .ace_support.ace_function{color:#005273;}.ace-kuroir .ace_support.ace_constant{color:#CF6A4C;}.ace-kuroir .ace_storage{color:#A52A2A;}.ace-kuroir .ace_invalid.ace_illegal{color:#FD1224;\ background-color:rgba(255, 6, 0, 0.15);}.ace-kuroir .ace_invalid.ace_deprecated{text-decoration:underline;\ font-style:italic;\ color:#FD1732;\ background-color:#E8E9E8;}.ace-kuroir .ace_string{color:#639300;}.ace-kuroir .ace_string.ace_regexp{color:#417E00;\ background-color:#C9D4BE;}.ace-kuroir .ace_comment{color:rgba(148, 148, 148, 0.91);\ background-color:rgba(220, 220, 220, 0.56);}.ace-kuroir .ace_variable{color:#009ACD;}.ace-kuroir .ace_meta.ace_tag{color:#005273;}.ace-kuroir .ace_markup.ace_heading{color:#B8012D;\ background-color:rgba(191, 97, 51, 0.051);}.ace-kuroir .ace_markup.ace_list{color:#8F5B26;}\ "; var dom = acequire("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
let util = require('../../util'); let Hammer = require('../../module/hammer'); let hammerUtil = require('../../hammerUtil'); /** * clears the toolbar div element of children * * @private */ class ManipulationSystem { constructor(body, canvas, selectionHandler) { this.body = body; this.canvas = canvas; this.selectionHandler = selectionHandler; this.editMode = false; this.manipulationDiv = undefined; this.editModeDiv = undefined; this.closeDiv = undefined; this.manipulationHammers = []; this.temporaryUIFunctions = {}; this.temporaryEventFunctions = []; this.touchTime = 0; this.temporaryIds = {nodes: [], edges:[]}; this.guiEnabled = false; this.inMode = false; this.selectedControlNode = undefined; this.options = {}; this.defaultOptions = { enabled: false, initiallyActive: false, addNode: true, addEdge: true, editNode: undefined, editEdge: true, deleteNode: true, deleteEdge: true, controlNodeStyle:{ shape:'dot', size:6, color: {background: '#ff0000', border: '#3c3c3c', highlight: {background: '#07f968', border: '#3c3c3c'}}, borderWidth: 2, borderWidthSelected: 2 } }; util.extend(this.options, this.defaultOptions); this.body.emitter.on('destroy', () => {this._clean();}); this.body.emitter.on('_dataChanged',this._restore.bind(this)); this.body.emitter.on('_resetData', this._restore.bind(this)); } /** * If something changes in the data during editing, switch back to the initial datamanipulation state and close all edit modes. * @private */ _restore() { if (this.inMode !== false) { if (this.options.initiallyActive === true) { this.enableEditMode(); } else { this.disableEditMode(); } } } /** * Set the Options * @param options */ setOptions(options, allOptions, globalOptions) { if (allOptions !== undefined) { if (allOptions.locale !== undefined) {this.options.locale = allOptions.locale} else {this.options.locale = globalOptions.locale;} if (allOptions.locales !== undefined) {this.options.locales = allOptions.locales} else {this.options.locales = globalOptions.locales;} } if (options !== undefined) { if (typeof options === 'boolean') { this.options.enabled = options; } else { this.options.enabled = true; util.deepExtend(this.options, options); } if (this.options.initiallyActive === true) { this.editMode = true; } this._setup(); } } /** * Enable or disable edit-mode. Draws the DOM required and cleans up after itself. * * @private */ toggleEditMode() { if (this.editMode === true) { this.disableEditMode(); } else { this.enableEditMode(); } } enableEditMode() { this.editMode = true; this._clean(); if (this.guiEnabled === true) { this.manipulationDiv.style.display = 'block'; this.closeDiv.style.display = 'block'; this.editModeDiv.style.display = 'none'; this.showManipulatorToolbar(); } } disableEditMode() { this.editMode = false; this._clean(); if (this.guiEnabled === true) { this.manipulationDiv.style.display = 'none'; this.closeDiv.style.display = 'none'; this.editModeDiv.style.display = 'block'; this._createEditButton(); } } /** * Creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar. * * @private */ showManipulatorToolbar() { // restore the state of any bound functions or events, remove control nodes, restore physics this._clean(); // reset global variables this.manipulationDOM = {}; // if the gui is enabled, draw all elements. if (this.guiEnabled === true) { // a _restore will hide these menus this.editMode = true; this.manipulationDiv.style.display = 'block'; this.closeDiv.style.display = 'block'; let selectedNodeCount = this.selectionHandler._getSelectedNodeCount(); let selectedEdgeCount = this.selectionHandler._getSelectedEdgeCount(); let selectedTotalCount = selectedNodeCount + selectedEdgeCount; let locale = this.options.locales[this.options.locale]; let needSeperator = false; if (this.options.addNode !== false) { this._createAddNodeButton(locale); needSeperator = true; } if (this.options.addEdge !== false) { if (needSeperator === true) { this._createSeperator(1); } else { needSeperator = true; } this._createAddEdgeButton(locale); } if (selectedNodeCount === 1 && typeof this.options.editNode === 'function') { if (needSeperator === true) { this._createSeperator(2); } else { needSeperator = true; } this._createEditNodeButton(locale); } else if (selectedEdgeCount === 1 && selectedNodeCount === 0 && this.options.editEdge !== false) { if (needSeperator === true) { this._createSeperator(3); } else { needSeperator = true; } this._createEditEdgeButton(locale); } // remove buttons if (selectedTotalCount !== 0) { if (selectedNodeCount > 0 && this.options.deleteNode !== false) { if (needSeperator === true) { this._createSeperator(4); } this._createDeleteButton(locale); } else if (selectedNodeCount === 0 && this.options.deleteEdge !== false) { if (needSeperator === true) { this._createSeperator(4); } this._createDeleteButton(locale); } } // bind the close button this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); // refresh this bar based on what has been selected this._temporaryBindEvent('select', this.showManipulatorToolbar.bind(this)); } // redraw to show any possible changes this.body.emitter.emit('_redraw'); } /** * Create the toolbar for adding Nodes */ addNodeMode() { // when using the gui, enable edit mode if it wasnt already. if (this.editMode !== true) { this.enableEditMode(); } // restore the state of any bound functions or events, remove control nodes, restore physics this._clean(); this.inMode = 'addNode'; if (this.guiEnabled === true) { let locale = this.options.locales[this.options.locale]; this.manipulationDOM = {}; this._createBackButton(locale); this._createSeperator(); this._createDescription(locale['addDescription'] || this.options.locales['en']['addDescription']); // bind the close button this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); } this._temporaryBindEvent('click', this._performAddNode.bind(this)); } /** * call the bound function to handle the editing of the node. The node has to be selected. */ editNode() { // when using the gui, enable edit mode if it wasnt already. if (this.editMode !== true) { this.enableEditMode(); } // restore the state of any bound functions or events, remove control nodes, restore physics this._clean(); let node = this.selectionHandler._getSelectedNode(); if (node !== undefined) { this.inMode = 'editNode'; if (typeof this.options.editNode === 'function') { if (node.isCluster !== true) { let data = util.deepExtend({}, node.options, false); data.x = node.x; data.y = node.y; if (this.options.editNode.length === 2) { this.options.editNode(data, (finalizedData) => { if (finalizedData !== null && finalizedData !== undefined && this.inMode === 'editNode') { // if for whatever reason the mode has changes (due to dataset change) disregard the callback) { this.body.data.nodes.getDataSet().update(finalizedData); } this.showManipulatorToolbar(); }); } else { throw new Error('The function for edit does not support two arguments (data, callback)'); } } else { alert(this.options.locales[this.options.locale]['editClusterError'] || this.options.locales['en']['editClusterError']); } } else { throw new Error('No function has been configured to handle the editing of nodes.'); } } else { this.showManipulatorToolbar(); } } /** * create the toolbar to connect nodes */ addEdgeMode() { // when using the gui, enable edit mode if it wasnt already. if (this.editMode !== true) { this.enableEditMode(); } // restore the state of any bound functions or events, remove control nodes, restore physics this._clean(); this.inMode = 'addEdge'; if (this.guiEnabled === true) { let locale = this.options.locales[this.options.locale]; this.manipulationDOM = {}; this._createBackButton(locale); this._createSeperator(); this._createDescription(locale['edgeDescription'] || this.options.locales['en']['edgeDescription']); // bind the close button this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); } // temporarily overload functions this._temporaryBindUI('onTouch', this._handleConnect.bind(this)); this._temporaryBindUI('onDragEnd', this._finishConnect.bind(this)); this._temporaryBindUI('onDrag', this._dragControlNode.bind(this)); this._temporaryBindUI('onRelease', this._finishConnect.bind(this)); this._temporaryBindUI('onDragStart', () => {}); this._temporaryBindUI('onHold', () => {}); } /** * create the toolbar to edit edges */ editEdgeMode() { // when using the gui, enable edit mode if it wasn't already. if (this.editMode !== true) { this.enableEditMode(); } // restore the state of any bound functions or events, remove control nodes, restore physics this._clean(); this.inMode = 'editEdge'; if (typeof this.options.editEdge === 'object' && typeof this.options.editEdge.editWithoutDrag === "function") { this.edgeBeingEditedId = this.selectionHandler.getSelectedEdges()[0]; if (this.edgeBeingEditedId !== undefined) { var edge = this.body.edges[this.edgeBeingEditedId]; this._performEditEdge(edge.from, edge.to); return; } } if (this.guiEnabled === true) { let locale = this.options.locales[this.options.locale]; this.manipulationDOM = {}; this._createBackButton(locale); this._createSeperator(); this._createDescription(locale['editEdgeDescription'] || this.options.locales['en']['editEdgeDescription']); // bind the close button this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this)); } this.edgeBeingEditedId = this.selectionHandler.getSelectedEdges()[0]; if (this.edgeBeingEditedId !== undefined) { let edge = this.body.edges[this.edgeBeingEditedId]; // create control nodes let controlNodeFrom = this._getNewTargetNode(edge.from.x, edge.from.y); let controlNodeTo = this._getNewTargetNode(edge.to.x, edge.to.y); this.temporaryIds.nodes.push(controlNodeFrom.id); this.temporaryIds.nodes.push(controlNodeTo.id); this.body.nodes[controlNodeFrom.id] = controlNodeFrom; this.body.nodeIndices.push(controlNodeFrom.id); this.body.nodes[controlNodeTo.id] = controlNodeTo; this.body.nodeIndices.push(controlNodeTo.id); // temporarily overload UI functions, cleaned up automatically because of _temporaryBindUI this._temporaryBindUI('onTouch', this._controlNodeTouch.bind(this)); // used to get the position this._temporaryBindUI('onTap', () => {}); // disabled this._temporaryBindUI('onHold', () => {}); // disabled this._temporaryBindUI('onDragStart', this._controlNodeDragStart.bind(this));// used to select control node this._temporaryBindUI('onDrag', this._controlNodeDrag.bind(this)); // used to drag control node this._temporaryBindUI('onDragEnd', this._controlNodeDragEnd.bind(this)); // used to connect or revert control nodes this._temporaryBindUI('onMouseMove', () => {}); // disabled // create function to position control nodes correctly on movement // automatically cleaned up because we use the temporary bind this._temporaryBindEvent('beforeDrawing', (ctx) => { let positions = edge.edgeType.findBorderPositions(ctx); if (controlNodeFrom.selected === false) { controlNodeFrom.x = positions.from.x; controlNodeFrom.y = positions.from.y; } if (controlNodeTo.selected === false) { controlNodeTo.x = positions.to.x; controlNodeTo.y = positions.to.y; } }); this.body.emitter.emit('_redraw'); } else { this.showManipulatorToolbar(); } } /** * delete everything in the selection */ deleteSelected() { // when using the gui, enable edit mode if it wasnt already. if (this.editMode !== true) { this.enableEditMode(); } // restore the state of any bound functions or events, remove control nodes, restore physics this._clean(); this.inMode = 'delete'; let selectedNodes = this.selectionHandler.getSelectedNodes(); let selectedEdges = this.selectionHandler.getSelectedEdges(); let deleteFunction = undefined; if (selectedNodes.length > 0) { for (let i = 0; i < selectedNodes.length; i++) { if (this.body.nodes[selectedNodes[i]].isCluster === true) { alert(this.options.locales[this.options.locale]['deleteClusterError'] || this.options.locales['en']['deleteClusterError']); return; } } if (typeof this.options.deleteNode === 'function') { deleteFunction = this.options.deleteNode; } } else if (selectedEdges.length > 0) { if (typeof this.options.deleteEdge === 'function') { deleteFunction = this.options.deleteEdge; } } if (typeof deleteFunction === 'function') { let data = {nodes: selectedNodes, edges: selectedEdges}; if (deleteFunction.length === 2) { deleteFunction(data, (finalizedData) => { if (finalizedData !== null && finalizedData !== undefined && this.inMode === 'delete') { // if for whatever reason the mode has changes (due to dataset change) disregard the callback) { this.body.data.edges.getDataSet().remove(finalizedData.edges); this.body.data.nodes.getDataSet().remove(finalizedData.nodes); this.body.emitter.emit('startSimulation'); this.showManipulatorToolbar(); } else { this.body.emitter.emit('startSimulation'); this.showManipulatorToolbar(); } }); } else { throw new Error('The function for delete does not support two arguments (data, callback)') } } else { this.body.data.edges.getDataSet().remove(selectedEdges); this.body.data.nodes.getDataSet().remove(selectedNodes); this.body.emitter.emit('startSimulation'); this.showManipulatorToolbar(); } } //********************************************** PRIVATE ***************************************// /** * draw or remove the DOM * @private */ _setup() { if (this.options.enabled === true) { // Enable the GUI this.guiEnabled = true; this._createWrappers(); if (this.editMode === false) { this._createEditButton(); } else { this.showManipulatorToolbar(); } } else { this._removeManipulationDOM(); // disable the gui this.guiEnabled = false; } } /** * create the div overlays that contain the DOM * @private */ _createWrappers() { // load the manipulator HTML elements. All styling done in css. if (this.manipulationDiv === undefined) { this.manipulationDiv = document.createElement('div'); this.manipulationDiv.className = 'vis-manipulation'; if (this.editMode === true) { this.manipulationDiv.style.display = 'block'; } else { this.manipulationDiv.style.display = 'none'; } this.canvas.frame.appendChild(this.manipulationDiv); } // container for the edit button. if (this.editModeDiv === undefined) { this.editModeDiv = document.createElement('div'); this.editModeDiv.className = 'vis-edit-mode'; if (this.editMode === true) { this.editModeDiv.style.display = 'none'; } else { this.editModeDiv.style.display = 'block'; } this.canvas.frame.appendChild(this.editModeDiv); } // container for the close div button if (this.closeDiv === undefined) { this.closeDiv = document.createElement('div'); this.closeDiv.className = 'vis-close'; this.closeDiv.style.display = this.manipulationDiv.style.display; this.canvas.frame.appendChild(this.closeDiv); } } /** * generate a new target node. Used for creating new edges and editing edges * @param x * @param y * @returns {*} * @private */ _getNewTargetNode(x,y) { let controlNodeStyle = util.deepExtend({}, this.options.controlNodeStyle); controlNodeStyle.id = 'targetNode' + util.randomUUID(); controlNodeStyle.hidden = false; controlNodeStyle.physics = false; controlNodeStyle.x = x; controlNodeStyle.y = y; // we have to define the bounding box in order for the nodes to be drawn immediately let node = this.body.functions.createNode(controlNodeStyle); node.shape.boundingBox = {left: x, right:x, top:y, bottom:y}; return node; } /** * Create the edit button */ _createEditButton() { // restore everything to it's original state (if applicable) this._clean(); // reset the manipulationDOM this.manipulationDOM = {}; // empty the editModeDiv util.recursiveDOMDelete(this.editModeDiv); // create the contents for the editMode button let locale = this.options.locales[this.options.locale]; let button = this._createButton('editMode', 'vis-button vis-edit vis-edit-mode', locale['edit'] || this.options.locales['en']['edit']); this.editModeDiv.appendChild(button); // bind a hammer listener to the button, calling the function toggleEditMode. this._bindHammerToDiv(button, this.toggleEditMode.bind(this)); } /** * this function cleans up after everything this module does. Temporary elements, functions and events are removed, physics restored, hammers removed. * @private */ _clean() { // not in mode this.inMode = false; // _clean the divs if (this.guiEnabled === true) { util.recursiveDOMDelete(this.editModeDiv); util.recursiveDOMDelete(this.manipulationDiv); // removes all the bindings and overloads this._cleanManipulatorHammers(); } // remove temporary nodes and edges this._cleanupTemporaryNodesAndEdges(); // restore overloaded UI functions this._unbindTemporaryUIs(); // remove the temporaryEventFunctions this._unbindTemporaryEvents(); // restore the physics if required this.body.emitter.emit('restorePhysics'); } /** * Each dom element has it's own hammer. They are stored in this.manipulationHammers. This cleans them up. * @private */ _cleanManipulatorHammers() { // _clean hammer bindings if (this.manipulationHammers.length != 0) { for (let i = 0; i < this.manipulationHammers.length; i++) { this.manipulationHammers[i].destroy(); } this.manipulationHammers = []; } } /** * Remove all DOM elements created by this module. * @private */ _removeManipulationDOM() { // removes all the bindings and overloads this._clean(); // empty the manipulation divs util.recursiveDOMDelete(this.manipulationDiv); util.recursiveDOMDelete(this.editModeDiv); util.recursiveDOMDelete(this.closeDiv); // remove the manipulation divs if (this.manipulationDiv) {this.canvas.frame.removeChild(this.manipulationDiv);} if (this.editModeDiv) {this.canvas.frame.removeChild(this.editModeDiv);} if (this.closeDiv) {this.canvas.frame.removeChild(this.closeDiv);} // set the references to undefined this.manipulationDiv = undefined; this.editModeDiv = undefined; this.closeDiv = undefined; } /** * create a seperator line. the index is to differentiate in the manipulation dom * @param index * @private */ _createSeperator(index = 1) { this.manipulationDOM['seperatorLineDiv' + index] = document.createElement('div'); this.manipulationDOM['seperatorLineDiv' + index].className = 'vis-separator-line'; this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv' + index]); } // ---------------------- DOM functions for buttons --------------------------// _createAddNodeButton(locale) { let button = this._createButton('addNode', 'vis-button vis-add', locale['addNode'] || this.options.locales['en']['addNode']); this.manipulationDiv.appendChild(button); this._bindHammerToDiv(button, this.addNodeMode.bind(this)); } _createAddEdgeButton(locale) { let button = this._createButton('addEdge', 'vis-button vis-connect', locale['addEdge'] || this.options.locales['en']['addEdge']); this.manipulationDiv.appendChild(button); this._bindHammerToDiv(button, this.addEdgeMode.bind(this)); } _createEditNodeButton(locale) { let button = this._createButton('editNode', 'vis-button vis-edit', locale['editNode'] || this.options.locales['en']['editNode']); this.manipulationDiv.appendChild(button); this._bindHammerToDiv(button, this.editNode.bind(this)); } _createEditEdgeButton(locale) { let button = this._createButton('editEdge', 'vis-button vis-edit', locale['editEdge'] || this.options.locales['en']['editEdge']); this.manipulationDiv.appendChild(button); this._bindHammerToDiv(button, this.editEdgeMode.bind(this)); } _createDeleteButton(locale) { if (this.options.rtl) { var deleteBtnClass = 'vis-button vis-delete-rtl'; } else { var deleteBtnClass = 'vis-button vis-delete'; } let button = this._createButton('delete', deleteBtnClass, locale['del'] || this.options.locales['en']['del']); this.manipulationDiv.appendChild(button); this._bindHammerToDiv(button, this.deleteSelected.bind(this)); } _createBackButton(locale) { let button = this._createButton('back', 'vis-button vis-back', locale['back'] || this.options.locales['en']['back']); this.manipulationDiv.appendChild(button); this._bindHammerToDiv(button, this.showManipulatorToolbar.bind(this)); } _createButton(id, className, label, labelClassName = 'vis-label') { this.manipulationDOM[id+'Div'] = document.createElement('div'); this.manipulationDOM[id+'Div'].className = className; this.manipulationDOM[id+'Label'] = document.createElement('div'); this.manipulationDOM[id+'Label'].className = labelClassName; this.manipulationDOM[id+'Label'].innerHTML = label; this.manipulationDOM[id+'Div'].appendChild(this.manipulationDOM[id+'Label']); return this.manipulationDOM[id+'Div']; } _createDescription(label) { this.manipulationDiv.appendChild( this._createButton('description', 'vis-button vis-none', label) ); } // -------------------------- End of DOM functions for buttons ------------------------------// /** * this binds an event until cleanup by the clean functions. * @param event * @param newFunction * @private */ _temporaryBindEvent(event, newFunction) { this.temporaryEventFunctions.push({event:event, boundFunction:newFunction}); this.body.emitter.on(event, newFunction); } /** * this overrides an UI function until cleanup by the clean function * @param UIfunctionName * @param newFunction * @private */ _temporaryBindUI(UIfunctionName, newFunction) { if (this.body.eventListeners[UIfunctionName] !== undefined) { this.temporaryUIFunctions[UIfunctionName] = this.body.eventListeners[UIfunctionName]; this.body.eventListeners[UIfunctionName] = newFunction; } else { throw new Error('This UI function does not exist. Typo? You tried: ' + UIfunctionName + ' possible are: ' + JSON.stringify(Object.keys(this.body.eventListeners))); } } /** * Restore the overridden UI functions to their original state. * * @private */ _unbindTemporaryUIs() { for (let functionName in this.temporaryUIFunctions) { if (this.temporaryUIFunctions.hasOwnProperty(functionName)) { this.body.eventListeners[functionName] = this.temporaryUIFunctions[functionName]; delete this.temporaryUIFunctions[functionName]; } } this.temporaryUIFunctions = {}; } /** * Unbind the events created by _temporaryBindEvent * @private */ _unbindTemporaryEvents() { for (let i = 0; i < this.temporaryEventFunctions.length; i++) { let eventName = this.temporaryEventFunctions[i].event; let boundFunction = this.temporaryEventFunctions[i].boundFunction; this.body.emitter.off(eventName, boundFunction); } this.temporaryEventFunctions = []; } /** * Bind an hammer instance to a DOM element. * @param domElement * @param funct */ _bindHammerToDiv(domElement, boundFunction) { let hammer = new Hammer(domElement, {}); hammerUtil.onTouch(hammer, boundFunction); this.manipulationHammers.push(hammer); } /** * Neatly clean up temporary edges and nodes * @private */ _cleanupTemporaryNodesAndEdges() { // _clean temporary edges for (let i = 0; i < this.temporaryIds.edges.length; i++) { this.body.edges[this.temporaryIds.edges[i]].disconnect(); delete this.body.edges[this.temporaryIds.edges[i]]; let indexTempEdge = this.body.edgeIndices.indexOf(this.temporaryIds.edges[i]); if (indexTempEdge !== -1) {this.body.edgeIndices.splice(indexTempEdge,1);} } // _clean temporary nodes for (let i = 0; i < this.temporaryIds.nodes.length; i++) { delete this.body.nodes[this.temporaryIds.nodes[i]]; let indexTempNode = this.body.nodeIndices.indexOf(this.temporaryIds.nodes[i]); if (indexTempNode !== -1) {this.body.nodeIndices.splice(indexTempNode,1);} } this.temporaryIds = {nodes: [], edges: []}; } // ------------------------------------------ EDIT EDGE FUNCTIONS -----------------------------------------// /** * the touch is used to get the position of the initial click * @param event * @private */ _controlNodeTouch(event) { this.selectionHandler.unselectAll(); this.lastTouch = this.body.functions.getPointer(event.center); this.lastTouch.translation = util.extend({},this.body.view.translation); // copy the object } /** * the drag start is used to mark one of the control nodes as selected. * @param event * @private */ _controlNodeDragStart(event) { let pointer = this.lastTouch; let pointerObj = this.selectionHandler._pointerToPositionObject(pointer); let from = this.body.nodes[this.temporaryIds.nodes[0]]; let to = this.body.nodes[this.temporaryIds.nodes[1]]; let edge = this.body.edges[this.edgeBeingEditedId]; this.selectedControlNode = undefined; let fromSelect = from.isOverlappingWith(pointerObj); let toSelect = to.isOverlappingWith(pointerObj); if (fromSelect === true) { this.selectedControlNode = from; edge.edgeType.from = from; } else if (toSelect === true) { this.selectedControlNode = to; edge.edgeType.to = to; } // we use the selection to find the node that is being dragged. We explicitly select it here. if (this.selectedControlNode !== undefined) { this.selectionHandler.selectObject(this.selectedControlNode) } this.body.emitter.emit('_redraw'); } /** * dragging the control nodes or the canvas * @param event * @private */ _controlNodeDrag(event) { this.body.emitter.emit('disablePhysics'); let pointer = this.body.functions.getPointer(event.center); let pos = this.canvas.DOMtoCanvas(pointer); if (this.selectedControlNode !== undefined) { this.selectedControlNode.x = pos.x; this.selectedControlNode.y = pos.y; } else { // if the drag was not started properly because the click started outside the network div, start it now. let diffX = pointer.x - this.lastTouch.x; let diffY = pointer.y - this.lastTouch.y; this.body.view.translation = {x:this.lastTouch.translation.x + diffX, y:this.lastTouch.translation.y + diffY}; } this.body.emitter.emit('_redraw'); } /** * connecting or restoring the control nodes. * @param event * @private */ _controlNodeDragEnd(event) { let pointer = this.body.functions.getPointer(event.center); let pointerObj = this.selectionHandler._pointerToPositionObject(pointer); let edge = this.body.edges[this.edgeBeingEditedId]; // if the node that was dragged is not a control node, return if (this.selectedControlNode === undefined) { return; } // we use the selection to find the node that is being dragged. We explicitly DEselect the control node here. this.selectionHandler.unselectAll(); let overlappingNodeIds = this.selectionHandler._getAllNodesOverlappingWith(pointerObj); let node = undefined; for (let i = overlappingNodeIds.length-1; i >= 0; i--) { if (overlappingNodeIds[i] !== this.selectedControlNode.id) { node = this.body.nodes[overlappingNodeIds[i]]; break; } } // perform the connection if (node !== undefined && this.selectedControlNode !== undefined) { if (node.isCluster === true) { alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']) } else { let from = this.body.nodes[this.temporaryIds.nodes[0]]; if (this.selectedControlNode.id === from.id) { this._performEditEdge(node.id, edge.to.id); } else { this._performEditEdge(edge.from.id, node.id); } } } else { edge.updateEdgeType(); this.body.emitter.emit('restorePhysics'); } this.body.emitter.emit('_redraw'); } // ------------------------------------ END OF EDIT EDGE FUNCTIONS -----------------------------------------// // ------------------------------------------- ADD EDGE FUNCTIONS -----------------------------------------// /** * the function bound to the selection event. It checks if you want to connect a cluster and changes the description * to walk the user through the process. * * @private */ _handleConnect(event) { // check to avoid double fireing of this function. if (new Date().valueOf() - this.touchTime > 100) { this.lastTouch = this.body.functions.getPointer(event.center); this.lastTouch.translation = util.extend({},this.body.view.translation); // copy the object let pointer = this.lastTouch; let node = this.selectionHandler.getNodeAt(pointer); if (node !== undefined) { if (node.isCluster === true) { alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']) } else { // create a node the temporary line can look at let targetNode = this._getNewTargetNode(node.x,node.y); this.body.nodes[targetNode.id] = targetNode; this.body.nodeIndices.push(targetNode.id); // create a temporary edge let connectionEdge = this.body.functions.createEdge({ id: 'connectionEdge' + util.randomUUID(), from: node.id, to: targetNode.id, physics: false, smooth: { enabled: true, type: 'continuous', roundness: 0.5 } }); this.body.edges[connectionEdge.id] = connectionEdge; this.body.edgeIndices.push(connectionEdge.id); this.temporaryIds.nodes.push(targetNode.id); this.temporaryIds.edges.push(connectionEdge.id); } } this.touchTime = new Date().valueOf(); } } _dragControlNode(event) { let pointer = this.body.functions.getPointer(event.center); if (this.temporaryIds.nodes[0] !== undefined) { let targetNode = this.body.nodes[this.temporaryIds.nodes[0]]; // there is only one temp node in the add edge mode. targetNode.x = this.canvas._XconvertDOMtoCanvas(pointer.x); targetNode.y = this.canvas._YconvertDOMtoCanvas(pointer.y); this.body.emitter.emit('_redraw'); } else { let diffX = pointer.x - this.lastTouch.x; let diffY = pointer.y - this.lastTouch.y; this.body.view.translation = {x:this.lastTouch.translation.x + diffX, y:this.lastTouch.translation.y + diffY}; } } /** * Connect the new edge to the target if one exists, otherwise remove temp line * @param event * @private */ _finishConnect(event) { let pointer = this.body.functions.getPointer(event.center); let pointerObj = this.selectionHandler._pointerToPositionObject(pointer); // remember the edge id let connectFromId = undefined; if (this.temporaryIds.edges[0] !== undefined) { connectFromId = this.body.edges[this.temporaryIds.edges[0]].fromId; } // get the overlapping node but NOT the temporary node; let overlappingNodeIds = this.selectionHandler._getAllNodesOverlappingWith(pointerObj); let node = undefined; for (let i = overlappingNodeIds.length-1; i >= 0; i--) { // if the node id is NOT a temporary node, accept the node. if (this.temporaryIds.nodes.indexOf(overlappingNodeIds[i]) === -1) { node = this.body.nodes[overlappingNodeIds[i]]; break; } } // clean temporary nodes and edges. this._cleanupTemporaryNodesAndEdges(); // perform the connection if (node !== undefined) { if (node.isCluster === true) { alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']); } else { if (this.body.nodes[connectFromId] !== undefined && this.body.nodes[node.id] !== undefined) { this._performAddEdge(connectFromId, node.id); } } } this.body.emitter.emit('_redraw'); } // --------------------------------------- END OF ADD EDGE FUNCTIONS -------------------------------------// // ------------------------------ Performing all the actual data manipulation ------------------------// /** * Adds a node on the specified location */ _performAddNode(clickData) { let defaultData = { id: util.randomUUID(), x: clickData.pointer.canvas.x, y: clickData.pointer.canvas.y, label: 'new' }; if (typeof this.options.addNode === 'function') { if (this.options.addNode.length === 2) { this.options.addNode(defaultData, (finalizedData) => { if (finalizedData !== null && finalizedData !== undefined && this.inMode === 'addNode') { // if for whatever reason the mode has changes (due to dataset change) disregard the callback this.body.data.nodes.getDataSet().add(finalizedData); this.showManipulatorToolbar(); } }); } else { throw new Error('The function for add does not support two arguments (data,callback)'); this.showManipulatorToolbar(); } } else { this.body.data.nodes.getDataSet().add(defaultData); this.showManipulatorToolbar(); } } /** * connect two nodes with a new edge. * * @private */ _performAddEdge(sourceNodeId, targetNodeId) { let defaultData = {from: sourceNodeId, to: targetNodeId}; if (typeof this.options.addEdge === 'function') { if (this.options.addEdge.length === 2) { this.options.addEdge(defaultData, (finalizedData) => { if (finalizedData !== null && finalizedData !== undefined && this.inMode === 'addEdge') { // if for whatever reason the mode has changes (due to dataset change) disregard the callback this.body.data.edges.getDataSet().add(finalizedData); this.selectionHandler.unselectAll(); this.showManipulatorToolbar(); } }); } else { throw new Error('The function for connect does not support two arguments (data,callback)'); } } else { this.body.data.edges.getDataSet().add(defaultData); this.selectionHandler.unselectAll(); this.showManipulatorToolbar(); } } /** * connect two nodes with a new edge. * * @private */ _performEditEdge(sourceNodeId, targetNodeId) { let defaultData = {id: this.edgeBeingEditedId, from: sourceNodeId, to: targetNodeId, label: this.body.data.edges._data[this.edgeBeingEditedId].label }; let eeFunct = this.options.editEdge; if (typeof eeFunct === 'object') { eeFunct = eeFunct.editWithoutDrag; } if (typeof eeFunct === 'function') { if (eeFunct.length === 2) { eeFunct(defaultData, (finalizedData) => { if (finalizedData === null || finalizedData === undefined || this.inMode !== 'editEdge') { // if for whatever reason the mode has changes (due to dataset change) disregard the callback) { this.body.edges[defaultData.id].updateEdgeType(); this.body.emitter.emit('_redraw'); this.showManipulatorToolbar(); } else { this.body.data.edges.getDataSet().update(finalizedData); this.selectionHandler.unselectAll(); this.showManipulatorToolbar(); } }); } else { throw new Error('The function for edit does not support two arguments (data, callback)'); } } else { this.body.data.edges.getDataSet().update(defaultData); this.selectionHandler.unselectAll(); this.showManipulatorToolbar(); } } } export default ManipulationSystem;
/* This file is part of Ext JS 4.2 Copyright (c) 2011-2013 Sencha Inc Contact: http://www.sencha.com/contact Commercial Usage Licensees holding valid commercial licenses may use this file in accordance with the Commercial Software License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Sencha. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. Build date: 2013-05-16 14:36:50 (f9be68accb407158ba2b1be2c226a6ce1f649314) */ /** * This class is intended to be extended or created via the {@link Ext.Component#componentLayout layout} * configuration property. See {@link Ext.Component#componentLayout} for additional details. * @private */ Ext.define('Ext.layout.component.Component', { /* Begin Definitions */ extend: 'Ext.layout.Layout', /* End Definitions */ type: 'component', isComponentLayout: true, nullBox: {}, usesContentHeight: true, usesContentWidth: true, usesHeight: true, usesWidth: true, beginLayoutCycle: function (ownerContext, firstCycle) { var me = this, owner = me.owner, ownerCtContext = ownerContext.ownerCtContext, heightModel = ownerContext.heightModel, widthModel = ownerContext.widthModel, body = owner.el.dom === document.body, lastBox = owner.lastBox || me.nullBox, lastSize = owner.el.lastBox || me.nullBox, dirty = !body, ownerLayout, v, widthName, heightName; me.callParent(arguments); if (firstCycle) { if (me.usesContentWidth) { ++ownerContext.consumersContentWidth; } if (me.usesContentHeight) { ++ownerContext.consumersContentHeight; } if (me.usesWidth) { ++ownerContext.consumersWidth; } if (me.usesHeight) { ++ownerContext.consumersHeight; } if (ownerCtContext && !ownerCtContext.hasRawContent) { ownerLayout = owner.ownerLayout; if (ownerLayout.usesWidth) { ++ownerContext.consumersWidth; } if (ownerLayout.usesHeight) { ++ownerContext.consumersHeight; } } } // we want to publish configured dimensions as early as possible and since this is // a write phase... if (widthModel.configured) { // If the owner.el is the body, owner.width is not dirty (we don't want to write // it to the body el). For other el's, the width may already be correct in the // DOM (e.g., it is rendered in the markup initially). If the width is not // correct in the DOM, this is only going to be the case on the first cycle. widthName = widthModel.names.width; if (!body) { dirty = firstCycle ? owner[widthName] !== lastSize.width : widthModel.constrained; } ownerContext.setWidth(owner[widthName], dirty); } else if (ownerContext.isTopLevel) { if (widthModel.calculated) { v = lastBox.width; ownerContext.setWidth(v, /*dirty=*/v != lastSize.width); } v = lastBox.x; ownerContext.setProp('x', v, /*dirty=*/v != lastSize.x); } if (heightModel.configured) { heightName = heightModel.names.height; if (!body) { dirty = firstCycle ? owner[heightName] !== lastSize.height : heightModel.constrained; } ownerContext.setHeight(owner[heightName], dirty); } else if (ownerContext.isTopLevel) { if (heightModel.calculated) { v = lastBox.height; ownerContext.setHeight(v, v != lastSize.height); } v = lastBox.y; ownerContext.setProp('y', v, /*dirty=*/v != lastSize.y); } }, finishedLayout: function(ownerContext) { var me = this, elementChildren = ownerContext.children, owner = me.owner, len, i, elContext, lastBox, props; // NOTE: In the code below we cannot use getProp because that will generate a layout dependency // Set lastBox on managed child Elements. // So that ContextItem.constructor can snag the lastBox for use by its undo method. if (elementChildren) { len = elementChildren.length; for (i = 0; i < len; i++) { elContext = elementChildren[i]; elContext.el.lastBox = elContext.props; } } // Cache the size from which we are changing so that notifyOwner can notify the owningComponent with all essential information ownerContext.previousSize = me.lastComponentSize; // Cache the currently layed out size me.lastComponentSize = owner.el.lastBox = props = ownerContext.props; // lastBox is a copy of the defined props to allow save/restore of these (panel // collapse needs this) lastBox = owner.lastBox || (owner.lastBox = {}); lastBox.x = props.x; lastBox.y = props.y; lastBox.width = props.width; lastBox.height = props.height; lastBox.invalid = false; me.callParent(arguments); }, notifyOwner: function(ownerContext) { var me = this, currentSize = me.lastComponentSize, prevSize = ownerContext.previousSize, args = [currentSize.width, currentSize.height]; if (prevSize) { args.push(prevSize.width, prevSize.height); } // Call afterComponentLayout passing new size, and only passing old size if there *was* an old size. me.owner.afterComponentLayout.apply(me.owner, args); }, /** * Returns the owner component's resize element. * @return {Ext.Element} */ getTarget : function() { return this.owner.el; }, /** * Returns the element into which rendering must take place. Defaults to the owner Component's encapsulating element. * * May be overridden in Component layout managers which implement an inner element. * @return {Ext.Element} */ getRenderTarget : function() { return this.owner.el; }, cacheTargetInfo: function(ownerContext) { var me = this, targetInfo = me.targetInfo, target; if (!targetInfo) { target = ownerContext.getEl('getTarget', me); me.targetInfo = targetInfo = { padding: target.getPaddingInfo(), border: target.getBorderInfo() }; } return targetInfo; }, measureAutoDimensions: function (ownerContext, dimensions) { // Subtle But Important: // // We don't want to call getProp/hasProp et.al. unless we in fact need that value // for our results! If we call it and don't need it, the layout manager will think // we depend on it and will schedule us again should it change. var me = this, owner = me.owner, containerLayout = owner.layout, heightModel = ownerContext.heightModel, widthModel = ownerContext.widthModel, boxParent = ownerContext.boxParent, isBoxParent = ownerContext.isBoxParent, props = ownerContext.props, isContainer, ret = { gotWidth: false, gotHeight: false, isContainer: (isContainer = !ownerContext.hasRawContent) }, hv = dimensions || 3, zeroWidth, zeroHeight, needed = 0, got = 0, ready, size, temp; // Note: this method is called *a lot*, so we have to be careful not to waste any // time or make useless calls or, especially, read the DOM when we can avoid it. //--------------------------------------------------------------------- // Width if (widthModel.shrinkWrap && ownerContext.consumersContentWidth) { ++needed; zeroWidth = !(hv & 1); if (isContainer) { // as a componentLayout for a container, we rely on the container layout to // produce contentWidth... if (zeroWidth) { ret.contentWidth = 0; ret.gotWidth = true; ++got; } else if ((ret.contentWidth = ownerContext.getProp('contentWidth')) !== undefined) { ret.gotWidth = true; ++got; } } else { size = props.contentWidth; if (typeof size == 'number') { // if (already determined) ret.contentWidth = size; ret.gotWidth = true; ++got; } else { if (zeroWidth) { ready = true; } else if (!ownerContext.hasDomProp('containerChildrenSizeDone')) { ready = false; } else if (isBoxParent || !boxParent || boxParent.widthModel.shrinkWrap) { // if we have no boxParent, we are ready, but a shrinkWrap boxParent // artificially provides width early in the measurement process so // we are ready to go in that case as well... ready = true; } else { // lastly, we have a boxParent that will be given a width, so we // can wait for that width to be set in order to properly measure // whatever is inside... ready = boxParent.hasDomProp('width'); } if (ready) { if (zeroWidth) { temp = 0; } else if (containerLayout && containerLayout.measureContentWidth) { // Allow the container layout to do the measurement since it // may have a better idea of how to do it even with no items: temp = containerLayout.measureContentWidth(ownerContext); } else { temp = me.measureContentWidth(ownerContext); } if (!isNaN(ret.contentWidth = temp)) { ownerContext.setContentWidth(temp, true); ret.gotWidth = true; ++got; } } } } } else if (widthModel.natural && ownerContext.consumersWidth) { ++needed; size = props.width; // zeroWidth does not apply if (typeof size == 'number') { // if (already determined) ret.width = size; ret.gotWidth = true; ++got; } else { if (isBoxParent || !boxParent) { ready = true; } else { // lastly, we have a boxParent that will be given a width, so we // can wait for that width to be set in order to properly measure // whatever is inside... ready = boxParent.hasDomProp('width'); } if (ready) { if (!isNaN(ret.width = me.measureOwnerWidth(ownerContext))) { ownerContext.setWidth(ret.width, false); ret.gotWidth = true; ++got; } } } } //--------------------------------------------------------------------- // Height if (heightModel.shrinkWrap && ownerContext.consumersContentHeight) { ++needed; zeroHeight = !(hv & 2); if (isContainer) { // don't ask unless we need to know... if (zeroHeight) { ret.contentHeight = 0; ret.gotHeight = true; ++got; } else if ((ret.contentHeight = ownerContext.getProp('contentHeight')) !== undefined) { ret.gotHeight = true; ++got; } } else { size = props.contentHeight; if (typeof size == 'number') { // if (already determined) ret.contentHeight = size; ret.gotHeight = true; ++got; } else { if (zeroHeight) { ready = true; } else if (!ownerContext.hasDomProp('containerChildrenSizeDone')) { ready = false; } else if (owner.noWrap) { ready = true; } else if (!widthModel.shrinkWrap) { // fixed width, so we need the width to determine the height... ready = (ownerContext.bodyContext || ownerContext).hasDomProp('width');// && (!ownerContext.bodyContext || ownerContext.bodyContext.hasDomProp('width')); } else if (isBoxParent || !boxParent || boxParent.widthModel.shrinkWrap) { // if we have no boxParent, we are ready, but an autoWidth boxParent // artificially provides width early in the measurement process so // we are ready to go in that case as well... ready = true; } else { // lastly, we have a boxParent that will be given a width, so we // can wait for that width to be set in order to properly measure // whatever is inside... ready = boxParent.hasDomProp('width'); } if (ready) { if (zeroHeight) { temp = 0; } else if (containerLayout && containerLayout.measureContentHeight) { // Allow the container layout to do the measurement since it // may have a better idea of how to do it even with no items: temp = containerLayout.measureContentHeight(ownerContext); } else { temp = me.measureContentHeight(ownerContext); } if (!isNaN(ret.contentHeight = temp)) { ownerContext.setContentHeight(temp, true); ret.gotHeight = true; ++got; } } } } } else if (heightModel.natural && ownerContext.consumersHeight) { ++needed; size = props.height; // zeroHeight does not apply if (typeof size == 'number') { // if (already determined) ret.height = size; ret.gotHeight = true; ++got; } else { if (isBoxParent || !boxParent) { ready = true; } else { // lastly, we have a boxParent that will be given a width, so we // can wait for that width to be set in order to properly measure // whatever is inside... ready = boxParent.hasDomProp('width'); } if (ready) { if (!isNaN(ret.height = me.measureOwnerHeight(ownerContext))) { ownerContext.setHeight(ret.height, false); ret.gotHeight = true; ++got; } } } } if (boxParent) { ownerContext.onBoxMeasured(); } ret.gotAll = got == needed; // see if we can avoid calling this method by storing something on ownerContext. return ret; }, measureContentWidth: function (ownerContext) { // contentWidth includes padding, but not border, framing or margins return ownerContext.el.getWidth() - ownerContext.getFrameInfo().width; }, measureContentHeight: function (ownerContext) { // contentHeight includes padding, but not border, framing or margins return ownerContext.el.getHeight() - ownerContext.getFrameInfo().height; }, measureOwnerHeight: function (ownerContext) { return ownerContext.el.getHeight(); }, measureOwnerWidth: function (ownerContext) { return ownerContext.el.getWidth(); } });
'use strict'; /* Services */ // Demonstrate how to register services // In this case it is a simple value service. angular.module('blog.services', []). value('version', '0.1');
/** * videojs-flash * @version 1.0.0-RC.1 * @copyright 2017 Brightcove, Inc. * @license Apache-2.0 */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.videojsFlash = 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(require,module,exports){ 'use strict'; exports.__esModule = true; /** * @file flash-rtmp.js * @module flash-rtmp */ /** * Add RTMP properties to the {@link Flash} Tech. * * @param {Flash} Flash * The flash tech class. * * @mixin FlashRtmpDecorator */ function FlashRtmpDecorator(Flash) { Flash.streamingFormats = { 'rtmp/mp4': 'MP4', 'rtmp/flv': 'FLV' }; /** * Join connection and stream with an ampersand. * * @param {string} connection * The connection string. * * @param {string} stream * The stream string. */ Flash.streamFromParts = function (connection, stream) { return connection + '&' + stream; }; /** * The flash parts object that contains connection and stream info. * * @typedef {Object} Flash~PartsObject * * @property {string} connection * The connection string of a source, defaults to an empty string. * * @property {string} stream * The stream string of the source, defaults to an empty string. */ /** * Convert a source url into a stream and connection parts. * * @param {string} src * the source url * * @return {Flash~PartsObject} * The parts object that contains a connection and a stream */ Flash.streamToParts = function (src) { var parts = { connection: '', stream: '' }; if (!src) { return parts; } // Look for the normal URL separator we expect, '&'. // If found, we split the URL into two pieces around the // first '&'. var connEnd = src.search(/&(?!\w+=)/); var streamBegin = void 0; if (connEnd !== -1) { streamBegin = connEnd + 1; } else { // If there's not a '&', we use the last '/' as the delimiter. connEnd = streamBegin = src.lastIndexOf('/') + 1; if (connEnd === 0) { // really, there's not a '/'? connEnd = streamBegin = src.length; } } parts.connection = src.substring(0, connEnd); parts.stream = src.substring(streamBegin, src.length); return parts; }; /** * Check if the source type is a streaming type. * * @param {string} srcType * The mime type to check. * * @return {boolean} * - True if the source type is a streaming type. * - False if the source type is not a streaming type. */ Flash.isStreamingType = function (srcType) { return srcType in Flash.streamingFormats; }; // RTMP has four variations, any string starting // with one of these protocols should be valid /** * Regular expression used to check if the source is an rtmp source. * * @property {RegExp} Flash.RTMP_RE */ Flash.RTMP_RE = /^rtmp[set]?:\/\//i; /** * Check if the source itself is a streaming type. * * @param {string} src * The url to the source. * * @return {boolean} * - True if the source url indicates that the source is streaming. * - False if the shource url indicates that the source url is not streaming. */ Flash.isStreamingSrc = function (src) { return Flash.RTMP_RE.test(src); }; /** * A source handler for RTMP urls * @type {Object} */ Flash.rtmpSourceHandler = {}; /** * Check if Flash can play the given mime type. * * @param {string} type * The mime type to check * * @return {string} * 'maybe', or '' (empty string) */ Flash.rtmpSourceHandler.canPlayType = function (type) { if (Flash.isStreamingType(type)) { return 'maybe'; } return ''; }; /** * Check if Flash can handle the source natively * * @param {Object} source * The source object * * @param {Object} [options] * The options passed to the tech * * @return {string} * 'maybe', or '' (empty string) */ Flash.rtmpSourceHandler.canHandleSource = function (source, options) { var can = Flash.rtmpSourceHandler.canPlayType(source.type); if (can) { return can; } if (Flash.isStreamingSrc(source.src)) { return 'maybe'; } return ''; }; /** * Pass the source to the flash object. * * @param {Object} source * The source object * * @param {Flash} tech * The instance of the Flash tech * * @param {Object} [options] * The options to pass to the source */ Flash.rtmpSourceHandler.handleSource = function (source, tech, options) { var srcParts = Flash.streamToParts(source.src); tech.setRtmpConnection(srcParts.connection); tech.setRtmpStream(srcParts.stream); }; // Register the native source handler Flash.registerSourceHandler(Flash.rtmpSourceHandler); return Flash; } exports['default'] = FlashRtmpDecorator; },{}],2:[function(require,module,exports){ (function (global){ if (typeof window !== "undefined") { module.exports = window; } else if (typeof global !== "undefined") { module.exports = global; } else if (typeof self !== "undefined"){ module.exports = self; } else { module.exports = {}; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],3:[function(require,module,exports){ module.exports={ "name": "videojs-swf", "description": "The Flash-fallback video player for video.js (http://videojs.com)", "version": "5.2.0", "copyright": "Copyright 2014 Brightcove, Inc. https://github.com/videojs/video-js-swf/blob/master/LICENSE", "keywords": [ "flash", "video", "player" ], "homepage": "http://videojs.com", "author": { "name": "Brightcove" }, "repository": { "type": "git", "url": "git+https://github.com/videojs/video-js-swf.git" }, "devDependencies": { "async": "~0.2.9", "chg": "^0.3.2", "flex-sdk": "4.6.0-0", "grunt": "~0.4.0", "grunt-bumpup": "~0.5.0", "grunt-cli": "~0.1.0", "grunt-connect": "~0.2.0", "grunt-contrib-jshint": "~0.4.3", "grunt-contrib-qunit": "~0.2.1", "grunt-contrib-watch": "~0.1.4", "grunt-npm": "~0.0.2", "grunt-prompt": "~0.1.2", "grunt-shell": "~0.6.1", "grunt-tagrelease": "~0.3.1", "qunitjs": "~1.12.0", "video.js": "^5.9.2" }, "scripts": { "version": "chg release -y && grunt dist && git add -f dist/ && git add CHANGELOG.md" }, "gitHead": "b903e6abdb2a1b1565dee8e550bcbecb655d27c2", "bugs": { "url": "https://github.com/videojs/video-js-swf/issues" }, "_id": "videojs-swf@5.2.0", "_shasum": "ae20a60f8dc7746ce52de845b51dd46798ea5cfa", "_from": "videojs-swf@>=5.2.0 <6.0.0", "_npmVersion": "2.15.6", "_nodeVersion": "4.4.3", "_npmUser": { "name": "gkatsev", "email": "me@gkatsev.com" }, "dist": { "shasum": "ae20a60f8dc7746ce52de845b51dd46798ea5cfa", "tarball": "https://registry.npmjs.org/videojs-swf/-/videojs-swf-5.2.0.tgz" }, "maintainers": [ { "name": "heff", "email": "npm@heff.me" }, { "name": "seniorflexdeveloper", "email": "seniorflexdeveloper@gmail.com" }, { "name": "gkatsev", "email": "me@gkatsev.com" }, { "name": "dmlap", "email": "dlapalomento@gmail.com" }, { "name": "bclwhitaker", "email": "lwhitaker@brightcove.com" } ], "_npmOperationalInternal": { "host": "packages-18-east.internal.npmjs.com", "tmp": "tmp/videojs-swf-5.2.0.tgz_1486496894096_0.4415081855840981" }, "directories": {}, "_resolved": "https://registry.npmjs.org/videojs-swf/-/videojs-swf-5.2.0.tgz", "readme": "ERROR: No README data found!" } },{}],4:[function(require,module,exports){ (function (global){ 'use strict'; exports.__esModule = true; var _video = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null); var _video2 = _interopRequireDefault(_video); var _rtmp = require('./rtmp'); var _rtmp2 = _interopRequireDefault(_rtmp); var _window = require('global/window'); var _window2 = _interopRequireDefault(_window); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file flash.js * VideoJS-SWF - Custom Flash Player with HTML5-ish API * https://github.com/zencoder/video-js-swf * Not using setupTriggers. Using global onEvent func to distribute events */ var Tech = _video2['default'].getComponent('Tech'); var Dom = _video2['default'].dom; var Url = _video2['default'].url; var createTimeRange = _video2['default'].createTimeRange; var mergeOptions = _video2['default'].mergeOptions; var navigator = _window2['default'].navigator; /** * Flash Media Controller - Wrapper for Flash Media API * * @mixes FlashRtmpDecorator * @mixes Tech~SouceHandlerAdditions * @extends Tech */ var Flash = function (_Tech) { _inherits(Flash, _Tech); /** * Create an instance of this Tech. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} ready * Callback function to call when the `Flash` Tech is ready. */ function Flash(options, ready) { _classCallCheck(this, Flash); // Set the source when ready var _this = _possibleConstructorReturn(this, _Tech.call(this, options, ready)); if (options.source) { _this.ready(function () { this.setSource(options.source); }, true); } // Having issues with Flash reloading on certain page actions (hide/resize/fullscreen) in certain browsers // This allows resetting the playhead when we catch the reload if (options.startTime) { _this.ready(function () { this.load(); this.play(); this.currentTime(options.startTime); }, true); } // Add global window functions that the swf expects // A 4.x workflow we weren't able to solve for in 5.0 // because of the need to hard code these functions // into the swf for security reasons _window2['default'].videojs = _window2['default'].videojs || {}; _window2['default'].videojs.Flash = _window2['default'].videojs.Flash || {}; _window2['default'].videojs.Flash.onReady = Flash.onReady; _window2['default'].videojs.Flash.onEvent = Flash.onEvent; _window2['default'].videojs.Flash.onError = Flash.onError; _this.on('seeked', function () { this.lastSeekTarget_ = undefined; }); return _this; } /** * Create the `Flash` Tech's DOM element. * * @return {Element} * The element that gets created. */ Flash.prototype.createEl = function createEl() { var options = this.options_; // If video.js is hosted locally you should also set the location // for the hosted swf, which should be relative to the page (not video.js) // Otherwise this adds a CDN url. // The CDN also auto-adds a swf URL for that specific version. if (!options.swf) { var ver = require('videojs-swf/package.json').version; options.swf = '//vjs.zencdn.net/swf/' + ver + '/video-js.swf'; } // Generate ID for swf object var objId = options.techId; // Merge default flashvars with ones passed in to init var flashVars = mergeOptions({ // SWF Callback Functions readyFunction: 'videojs.Flash.onReady', eventProxyFunction: 'videojs.Flash.onEvent', errorEventProxyFunction: 'videojs.Flash.onError', // Player Settings autoplay: options.autoplay, preload: options.preload, loop: options.loop, muted: options.muted }, options.flashVars); // Merge default parames with ones passed in var params = mergeOptions({ // Opaque is needed to overlay controls, but can affect playback performance wmode: 'opaque', // Using bgcolor prevents a white flash when the object is loading bgcolor: '#000000' }, options.params); // Merge default attributes with ones passed in var attributes = mergeOptions({ // Both ID and Name needed or swf to identify itself id: objId, name: objId, 'class': 'vjs-tech' }, options.attributes); this.el_ = Flash.embed(options.swf, flashVars, params, attributes); this.el_.tech = this; return this.el_; }; /** * Called by {@link Player#play} to play using the `Flash` `Tech`. */ Flash.prototype.play = function play() { if (this.ended()) { this.setCurrentTime(0); } this.el_.vjs_play(); }; /** * Called by {@link Player#pause} to pause using the `Flash` `Tech`. */ Flash.prototype.pause = function pause() { this.el_.vjs_pause(); }; /** * A getter/setter for the `Flash` Tech's source object. * > Note: Please use {@link Flash#setSource} * * @param {Tech~SourceObject} [src] * The source object you want to set on the `Flash` techs. * * @return {Tech~SourceObject|undefined} * - The current source object when a source is not passed in. * - undefined when setting * * @deprecated Since version 5. */ Flash.prototype.src = function src(_src) { if (_src === undefined) { return this.currentSrc(); } // Setting src through `src` not `setSrc` will be deprecated return this.setSrc(_src); }; /** * A getter/setter for the `Flash` Tech's source object. * * @param {Tech~SourceObject} [src] * The source object you want to set on the `Flash` techs. * * @return {Tech~SourceObject|undefined} * - The current source object when a source is not passed in. * - undefined when setting */ Flash.prototype.setSrc = function setSrc(src) { var _this2 = this; // Make sure source URL is absolute. src = Url.getAbsoluteURL(src); this.el_.vjs_src(src); // Currently the SWF doesn't autoplay if you load a source later. // e.g. Load player w/ no source, wait 2s, set src. if (this.autoplay()) { this.setTimeout(function () { return _this2.play(); }, 0); } }; /** * Indicates whether the media is currently seeking to a new position or not. * * @return {boolean} * - True if seeking to a new position * - False otherwise */ Flash.prototype.seeking = function seeking() { return this.lastSeekTarget_ !== undefined; }; /** * Returns the current time in seconds that the media is at in playback. * * @param {number} time * Current playtime of the media in seconds. */ Flash.prototype.setCurrentTime = function setCurrentTime(time) { var seekable = this.seekable(); if (seekable.length) { // clamp to the current seekable range time = time > seekable.start(0) ? time : seekable.start(0); time = time < seekable.end(seekable.length - 1) ? time : seekable.end(seekable.length - 1); this.lastSeekTarget_ = time; this.trigger('seeking'); this.el_.vjs_setProperty('currentTime', time); _Tech.prototype.setCurrentTime.call(this); } }; /** * Get the current playback time in seconds * * @return {number} * The current time of playback in seconds. */ Flash.prototype.currentTime = function currentTime() { // when seeking make the reported time keep up with the requested time // by reading the time we're seeking to if (this.seeking()) { return this.lastSeekTarget_ || 0; } return this.el_.vjs_getProperty('currentTime'); }; /** * Get the current source * * @method currentSrc * @return {Tech~SourceObject} * The current source */ Flash.prototype.currentSrc = function currentSrc() { if (this.currentSource_) { return this.currentSource_.src; } return this.el_.vjs_getProperty('currentSrc'); }; /** * Get the total duration of the current media. * * @return {number} 8 The total duration of the current media. */ Flash.prototype.duration = function duration() { if (this.readyState() === 0) { return NaN; } var duration = this.el_.vjs_getProperty('duration'); return duration >= 0 ? duration : Infinity; }; /** * Load media into Tech. */ Flash.prototype.load = function load() { this.el_.vjs_load(); }; /** * Get the poster image that was set on the tech. */ Flash.prototype.poster = function poster() { this.el_.vjs_getProperty('poster'); }; /** * Poster images are not handled by the Flash tech so make this is a no-op. */ Flash.prototype.setPoster = function setPoster() {}; /** * Determine the time ranges that can be seeked to in the media. * * @return {TimeRange} * Returns the time ranges that can be seeked to. */ Flash.prototype.seekable = function seekable() { var duration = this.duration(); if (duration === 0) { return createTimeRange(); } return createTimeRange(0, duration); }; /** * Get and create a `TimeRange` object for buffering. * * @return {TimeRange} * The time range object that was created. */ Flash.prototype.buffered = function buffered() { var ranges = this.el_.vjs_getProperty('buffered'); if (ranges.length === 0) { return createTimeRange(); } return createTimeRange(ranges[0][0], ranges[0][1]); }; /** * Get fullscreen support - * * Flash does not allow fullscreen through javascript * so this always returns false. * * @return {boolean} * The Flash tech does not support fullscreen, so it will always return false. */ Flash.prototype.supportsFullScreen = function supportsFullScreen() { // Flash does not allow fullscreen through javascript return false; }; /** * Flash does not allow fullscreen through javascript * so this always returns false. * * @return {boolean} * The Flash tech does not support fullscreen, so it will always return false. */ Flash.prototype.enterFullScreen = function enterFullScreen() { return false; }; return Flash; }(Tech); // Create setters and getters for attributes var _readWrite = ['rtmpConnection', 'rtmpStream', 'preload', 'defaultPlaybackRate', 'playbackRate', 'autoplay', 'loop', 'controls', 'volume', 'muted', 'defaultMuted']; var _readOnly = ['networkState', 'readyState', 'initialTime', 'startOffsetTime', 'paused', 'ended', 'videoWidth', 'videoHeight']; var _api = Flash.prototype; function _createSetter(attr) { var attrUpper = attr.charAt(0).toUpperCase() + attr.slice(1); _api['set' + attrUpper] = function (val) { return this.el_.vjs_setProperty(attr, val); }; } function _createGetter(attr) { _api[attr] = function () { return this.el_.vjs_getProperty(attr); }; } // Create getter and setters for all read/write attributes for (var i = 0; i < _readWrite.length; i++) { _createGetter(_readWrite[i]); _createSetter(_readWrite[i]); } // Create getters for read-only attributes for (var _i = 0; _i < _readOnly.length; _i++) { _createGetter(_readOnly[_i]); } /** ------------------------------ Getters ------------------------------ **/ /** * Get the value of `rtmpConnection` from the swf. * * @method Flash#rtmpConnection * @return {string} * The current value of `rtmpConnection` on the swf. */ /** * Get the value of `rtmpStream` from the swf. * * @method Flash#rtmpStream * @return {string} * The current value of `rtmpStream` on the swf. */ /** * Get the value of `preload` from the swf. `preload` indicates * what should download before the media is interacted with. It can have the following * values: * - none: nothing should be downloaded * - metadata: poster and the first few frames of the media may be downloaded to get * media dimensions and other metadata * - auto: allow the media and metadata for the media to be downloaded before * interaction * * @method Flash#preload * @return {string} * The value of `preload` from the swf. Will be 'none', 'metadata', * or 'auto'. */ /** * Get the value of `defaultPlaybackRate` from the swf. * * @method Flash#defaultPlaybackRate * @return {number} * The current value of `defaultPlaybackRate` on the swf. */ /** * Get the value of `playbackRate` from the swf. `playbackRate` indicates * the rate at which the media is currently playing back. Examples: * - if playbackRate is set to 2, media will play twice as fast. * - if playbackRate is set to 0.5, media will play half as fast. * * @method Flash#playbackRate * @return {number} * The value of `playbackRate` from the swf. A number indicating * the current playback speed of the media, where 1 is normal speed. */ /** * Get the value of `autoplay` from the swf. `autoplay` indicates * that the media should start to play as soon as the page is ready. * * @method Flash#autoplay * @return {boolean} * - The value of `autoplay` from the swf. * - True indicates that the media ashould start as soon as the page loads. * - False indicates that the media should not start as soon as the page loads. */ /** * Get the value of `loop` from the swf. `loop` indicates * that the media should return to the start of the media and continue playing once * it reaches the end. * * @method Flash#loop * @return {boolean} * - The value of `loop` from the swf. * - True indicates that playback should seek back to start once * the end of a media is reached. * - False indicates that playback should not loop back to the start when the * end of the media is reached. */ /** * Get the value of `mediaGroup` from the swf. * * @method Flash#mediaGroup * @return {string} * The current value of `mediaGroup` on the swf. */ /** * Get the value of `controller` from the swf. * * @method Flash#controller * @return {string} * The current value of `controller` on the swf. */ /** * Get the value of `controls` from the swf. `controls` indicates * whether the native flash controls should be shown or hidden. * * @method Flash#controls * @return {boolean} * - The value of `controls` from the swf. * - True indicates that native controls should be showing. * - False indicates that native controls should be hidden. */ /** * Get the value of the `volume` from the swf. `volume` indicates the current * audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and * so on. * * @method Flash#volume * @return {number} * The volume percent as a decimal. Value will be between 0-1. */ /** * Get the value of the `muted` from the swf. `muted` indicates the current * audio level should be silent. * * @method Flash#muted * @return {boolean} * - True if the audio should be set to silent * - False otherwise */ /** * Get the value of `defaultMuted` from the swf. `defaultMuted` indicates * whether the media should start muted or not. Only changes the default state of the * media. `muted` and `defaultMuted` can have different values. `muted` indicates the * current state. * * @method Flash#defaultMuted * @return {boolean} * - The value of `defaultMuted` from the swf. * - True indicates that the media should start muted. * - False indicates that the media should not start muted. */ /** * Get the value of `networkState` from the swf. `networkState` indicates * the current network state. It returns an enumeration from the following list: * - 0: NETWORK_EMPTY * - 1: NEWORK_IDLE * - 2: NETWORK_LOADING * - 3: NETWORK_NO_SOURCE * * @method Flash#networkState * @return {number} * The value of `networkState` from the swf. This will be a number * from the list in the description. */ /** * Get the value of `readyState` from the swf. `readyState` indicates * the current state of the media element. It returns an enumeration from the * following list: * - 0: HAVE_NOTHING * - 1: HAVE_METADATA * - 2: HAVE_CURRENT_DATA * - 3: HAVE_FUTURE_DATA * - 4: HAVE_ENOUGH_DATA * * @method Flash#readyState * @return {number} * The value of `readyState` from the swf. This will be a number * from the list in the description. */ /** * Get the value of `readyState` from the swf. `readyState` indicates * the current state of the media element. It returns an enumeration from the * following list: * - 0: HAVE_NOTHING * - 1: HAVE_METADATA * - 2: HAVE_CURRENT_DATA * - 3: HAVE_FUTURE_DATA * - 4: HAVE_ENOUGH_DATA * * @method Flash#readyState * @return {number} * The value of `readyState` from the swf. This will be a number * from the list in the description. */ /** * Get the value of `initialTime` from the swf. * * @method Flash#initialTime * @return {number} * The `initialTime` proprety on the swf. */ /** * Get the value of `startOffsetTime` from the swf. * * @method Flash#startOffsetTime * @return {number} * The `startOffsetTime` proprety on the swf. */ /** * Get the value of `paused` from the swf. `paused` indicates whether the swf * is current paused or not. * * @method Flash#paused * @return {boolean} * The value of `paused` from the swf. */ /** * Get the value of `ended` from the swf. `ended` indicates whether * the media has reached the end or not. * * @method Flash#ended * @return {boolean} * - True indicates that the media has ended. * - False indicates that the media has not ended. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-ended} */ /** * Get the value of `videoWidth` from the swf. `videoWidth` indicates * the current width of the media in css pixels. * * @method Flash#videoWidth * @return {number} * The value of `videoWidth` from the swf. This will be a number * in css pixels. */ /** * Get the value of `videoHeight` from the swf. `videoHeigth` indicates * the current height of the media in css pixels. * * @method Flassh.prototype.videoHeight * @return {number} * The value of `videoHeight` from the swf. This will be a number * in css pixels. */ /** ------------------------------ Setters ------------------------------ **/ /** * Set the value of `rtmpConnection` on the swf. * * @method Flash#setRtmpConnection * @param {string} rtmpConnection * New value to set the `rtmpConnection` property to. */ /** * Set the value of `rtmpStream` on the swf. * * @method Flash#setRtmpStream * @param {string} rtmpStream * New value to set the `rtmpStream` property to. */ /** * Set the value of `preload` on the swf. `preload` indicates * what should download before the media is interacted with. It can have the following * values: * - none: nothing should be downloaded * - metadata: poster and the first few frames of the media may be downloaded to get * media dimensions and other metadata * - auto: allow the media and metadata for the media to be downloaded before * interaction * * @method Flash#setPreload * @param {string} preload * The value of `preload` to set on the swf. Should be 'none', 'metadata', * or 'auto'. */ /** * Set the value of `defaultPlaybackRate` on the swf. * * @method Flash#setDefaultPlaybackRate * @param {number} defaultPlaybackRate * New value to set the `defaultPlaybackRate` property to. */ /** * Set the value of `playbackRate` on the swf. `playbackRate` indicates * the rate at which the media is currently playing back. Examples: * - if playbackRate is set to 2, media will play twice as fast. * - if playbackRate is set to 0.5, media will play half as fast. * * @method Flash#setPlaybackRate * @param {number} playbackRate * New value of `playbackRate` on the swf. A number indicating * the current playback speed of the media, where 1 is normal speed. */ /** * Set the value of `autoplay` on the swf. `autoplay` indicates * that the media should start to play as soon as the page is ready. * * @method Flash#setAutoplay * @param {boolean} autoplay * - The value of `autoplay` from the swf. * - True indicates that the media ashould start as soon as the page loads. * - False indicates that the media should not start as soon as the page loads. */ /** * Set the value of `loop` on the swf. `loop` indicates * that the media should return to the start of the media and continue playing once * it reaches the end. * * @method Flash#setLoop * @param {boolean} loop * - True indicates that playback should seek back to start once * the end of a media is reached. * - False indicates that playback should not loop back to the start when the * end of the media is reached. */ /** * Set the value of `mediaGroup` on the swf. * * @method Flash#setMediaGroup * @param {string} mediaGroup * New value of `mediaGroup` to set on the swf. */ /** * Set the value of `controller` on the swf. * * @method Flash#setController * @param {string} controller * New value the current value of `controller` on the swf. */ /** * Get the value of `controls` from the swf. `controls` indicates * whether the native flash controls should be shown or hidden. * * @method Flash#controls * @return {boolean} * - The value of `controls` from the swf. * - True indicates that native controls should be showing. * - False indicates that native controls should be hidden. */ /** * Set the value of the `volume` on the swf. `volume` indicates the current * audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and * so on. * * @method Flash#setVolume * @param {number} percentAsDecimal * The volume percent as a decimal. Value will be between 0-1. */ /** * Set the value of the `muted` on the swf. `muted` indicates that the current * audio level should be silent. * * @method Flash#setMuted * @param {boolean} muted * - True if the audio should be set to silent * - False otherwise */ /** * Set the value of `defaultMuted` on the swf. `defaultMuted` indicates * whether the media should start muted or not. Only changes the default state of the * media. `muted` and `defaultMuted` can have different values. `muted` indicates the * current state. * * @method Flash#setDefaultMuted * @param {boolean} defaultMuted * - True indicates that the media should start muted. * - False indicates that the media should not start muted. */ /* Flash Support Testing -------------------------------------------------------- */ /** * Check if the Flash tech is currently supported. * * @return {boolean} * - True if the flash tech is supported. * - False otherwise. */ Flash.isSupported = function () { return Flash.version()[0] >= 10; // return swfobject.hasFlashPlayerVersion('10'); }; // Add Source Handler pattern functions to this tech Tech.withSourceHandlers(Flash); /* * Native source handler for flash, simply passes the source to the swf element. * * @property {Tech~SourceObject} source * The source object * * @property {Flash} tech * The instance of the Flash tech */ Flash.nativeSourceHandler = {}; /** * Check if the Flash can play the given mime type. * * @param {string} type * The mimetype to check * * @return {string} * 'maybe', or '' (empty string) */ Flash.nativeSourceHandler.canPlayType = function (type) { if (type in Flash.formats) { return 'maybe'; } return ''; }; /** * Check if the media element can handle a source natively. * * @param {Tech~SourceObject} source * The source object * * @param {Object} [options] * Options to be passed to the tech. * * @return {string} * 'maybe', or '' (empty string). */ Flash.nativeSourceHandler.canHandleSource = function (source, options) { var type = void 0; function guessMimeType(src) { var ext = Url.getFileExtension(src); if (ext) { return 'video/' + ext; } return ''; } if (!source.type) { type = guessMimeType(source.src); } else { // Strip code information from the type because we don't get that specific type = source.type.replace(/;.*/, '').toLowerCase(); } return Flash.nativeSourceHandler.canPlayType(type); }; /** * Pass the source to the swf. * * @param {Tech~SourceObject} source * The source object * * @param {Flash} tech * The instance of the Flash tech * * @param {Object} [options] * The options to pass to the source */ Flash.nativeSourceHandler.handleSource = function (source, tech, options) { tech.setSrc(source.src); }; /** * noop for native source handler dispose, as cleanup will happen automatically. */ Flash.nativeSourceHandler.dispose = function () {}; // Register the native source handler Flash.registerSourceHandler(Flash.nativeSourceHandler); /** * Flash supported mime types. * * @constant {Object} */ Flash.formats = { 'video/flv': 'FLV', 'video/x-flv': 'FLV', 'video/mp4': 'MP4', 'video/m4v': 'MP4' }; /** * Called when the the swf is "ready", and makes sure that the swf is really * ready using {@link Flash#checkReady} */ Flash.onReady = function (currSwf) { var el = Dom.$('#' + currSwf); var tech = el && el.tech; // if there is no el then the tech has been disposed // and the tech element was removed from the player div if (tech && tech.el()) { // check that the flash object is really ready Flash.checkReady(tech); } }; /** * The SWF isn't always ready when it says it is. Sometimes the API functions still * need to be added to the object. If it's not ready, we set a timeout to check again * shortly. * * @param {Flash} tech * The instance of the flash tech to check. */ Flash.checkReady = function (tech) { // stop worrying if the tech has been disposed if (!tech.el()) { return; } // check if API property exists if (tech.el().vjs_getProperty) { // tell tech it's ready tech.triggerReady(); } else { // wait longer this.setTimeout(function () { Flash.checkReady(tech); }, 50); } }; /** * Trigger events from the swf on the Flash Tech. * * @param {number} swfID * The id of the swf that had the event * * @param {string} eventName * The name of the event to trigger */ Flash.onEvent = function (swfID, eventName) { var tech = Dom.$('#' + swfID).tech; var args = Array.prototype.slice.call(arguments, 2); // dispatch Flash events asynchronously for two reasons: // - Flash swallows any exceptions generated by javascript it // invokes // - Flash is suspended until the javascript returns which may cause // playback performance issues tech.setTimeout(function () { tech.trigger(eventName, args); }, 1); }; /** * Log errors from the swf on the Flash tech. * * @param {number} swfID * The id of the swf that had an error. * * @param {string} The error string * The error to set on the Flash Tech. * * @return {MediaError|undefined} * - Returns a MediaError when err is 'srcnotfound' * - Returns undefined otherwise. */ Flash.onError = function (swfID, err) { var tech = Dom.$('#' + swfID).tech; // trigger MEDIA_ERR_SRC_NOT_SUPPORTED if (err === 'srcnotfound') { return tech.error(4); } // trigger a custom error tech.error('FLASH: ' + err); }; /** * Get the current version of Flash that is in use on the page. * * @return {Array} * an array of versions that are available. */ Flash.version = function () { var version = '0,0,0'; // IE try { version = new _window2['default'].ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; // other browsers } catch (e) { try { if (navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) { version = (navigator.plugins['Shockwave Flash 2.0'] || navigator.plugins['Shockwave Flash']).description.replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; } } catch (err) { // satisfy linter } } return version.split(','); }; /** * Only use for non-iframe embeds. * * @param {Object} swf * The videojs-swf object. * * @param {Object} flashVars * Names and values to use as flash option variables. * * @param {Object} params * Style parameters to set on the object. * * @param {Object} attributes * Attributes to set on the element. * * @return {Element} * The embeded Flash DOM element. */ Flash.embed = function (swf, flashVars, params, attributes) { var code = Flash.getEmbedCode(swf, flashVars, params, attributes); // Get element by embedding code and retrieving created element var obj = Dom.createEl('div', { innerHTML: code }).childNodes[0]; return obj; }; /** * Only use for non-iframe embeds. * * @param {Object} swf * The videojs-swf object. * * @param {Object} flashVars * Names and values to use as flash option variables. * * @param {Object} params * Style parameters to set on the object. * * @param {Object} attributes * Attributes to set on the element. * * @return {Element} * The embeded Flash DOM element. */ Flash.getEmbedCode = function (swf, flashVars, params, attributes) { var objTag = '<object type="application/x-shockwave-flash" '; var flashVarsString = ''; var paramsString = ''; var attrsString = ''; // Convert flash vars to string if (flashVars) { Object.getOwnPropertyNames(flashVars).forEach(function (key) { flashVarsString += key + '=' + flashVars[key] + '&amp;'; }); } // Add swf, flashVars, and other default params params = mergeOptions({ movie: swf, flashvars: flashVarsString, // Required to talk to swf allowScriptAccess: 'always', // All should be default, but having security issues. allowNetworking: 'all' }, params); // Create param tags string Object.getOwnPropertyNames(params).forEach(function (key) { paramsString += '<param name="' + key + '" value="' + params[key] + '" />'; }); attributes = mergeOptions({ // Add swf to attributes (need both for IE and Others to work) data: swf, // Default to 100% width/height width: '100%', height: '100%' }, attributes); // Create Attributes string Object.getOwnPropertyNames(attributes).forEach(function (key) { attrsString += key + '="' + attributes[key] + '" '; }); return '' + objTag + attrsString + '>' + paramsString + '</object>'; }; // Run Flash through the RTMP decorator (0, _rtmp2['default'])(Flash); if (Tech.getTech('Flash')) { _video2['default'].log.warn('Not using videojs-flash as it appears to already be registered'); _video2['default'].log.warn('videojs-flash should only be used with video.js@6 and above'); } else { _video2['default'].registerTech('Flash', Flash); } exports['default'] = Flash; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./rtmp":1,"global/window":2,"videojs-swf/package.json":3}]},{},[4])(4) });
/** @module ember @submodule ember-htmlbars */ import isEnabled from 'ember-metal/features'; import { keyword } from 'htmlbars-runtime/hooks'; import closureAction from 'ember-routing-htmlbars/keywords/closure-action'; /** The `{{action}}` helper provides a useful shortcut for registering an HTML element within a template for a single DOM event and forwarding that interaction to the template's controller or specified `target` option. If the controller does not implement the specified action, the event is sent to the current route, and it bubbles up the route hierarchy from there. For more advanced event handling see [Ember.Component](/api/classes/Ember.Component.html) ### Use Given the following application Handlebars template on the page ```handlebars <div {{action 'anActionName'}}> click me </div> ``` And application code ```javascript App.ApplicationController = Ember.Controller.extend({ actions: { anActionName: function() { } } }); ``` Will result in the following rendered HTML ```html <div class="ember-view"> <div data-ember-action="1"> click me </div> </div> ``` Clicking "click me" will trigger the `anActionName` action of the `App.ApplicationController`. In this case, no additional parameters will be passed. If you provide additional parameters to the helper: ```handlebars <button {{action 'edit' post}}>Edit</button> ``` Those parameters will be passed along as arguments to the JavaScript function implementing the action. ### Event Propagation Events triggered through the action helper will automatically have `.preventDefault()` called on them. You do not need to do so in your event handlers. If you need to allow event propagation (to handle file inputs for example) you can supply the `preventDefault=false` option to the `{{action}}` helper: ```handlebars <div {{action "sayHello" preventDefault=false}}> <input type="file" /> <input type="checkbox" /> </div> ``` To disable bubbling, pass `bubbles=false` to the helper: ```handlebars <button {{action 'edit' post bubbles=false}}>Edit</button> ``` If you need the default handler to trigger you should either register your own event handler, or use event methods on your view class. See [Ember.View](/api/classes/Ember.View.html) 'Responding to Browser Events' for more information. ### Specifying DOM event type By default the `{{action}}` helper registers for DOM `click` events. You can supply an `on` option to the helper to specify a different DOM event name: ```handlebars <div {{action "anActionName" on="doubleClick"}}> click me </div> ``` See `Ember.View` 'Responding to Browser Events' for a list of acceptable DOM event names. ### Specifying whitelisted modifier keys By default the `{{action}}` helper will ignore click event with pressed modifier keys. You can supply an `allowedKeys` option to specify which keys should not be ignored. ```handlebars <div {{action "anActionName" allowedKeys="alt"}}> click me </div> ``` This way the `{{action}}` will fire when clicking with the alt key pressed down. Alternatively, supply "any" to the `allowedKeys` option to accept any combination of modifier keys. ```handlebars <div {{action "anActionName" allowedKeys="any"}}> click me with any key pressed </div> ``` ### Specifying a Target There are several possible target objects for `{{action}}` helpers: In a typical Ember application, where templates are managed through use of the `{{outlet}}` helper, actions will bubble to the current controller, then to the current route, and then up the route hierarchy. Alternatively, a `target` option can be provided to the helper to change which object will receive the method call. This option must be a path to an object, accessible in the current context: ```handlebars {{! the application template }} <div {{action "anActionName" target=view}}> click me </div> ``` ```javascript App.ApplicationView = Ember.View.extend({ actions: { anActionName: function() {} } }); ``` ### Additional Parameters You may specify additional parameters to the `{{action}}` helper. These parameters are passed along as the arguments to the JavaScript function implementing the action. ```handlebars {{#each people as |person|}} <div {{action "edit" person}}> click me </div> {{/each}} ``` Clicking "click me" will trigger the `edit` method on the current controller with the value of `person` as a parameter. @method action @for Ember.Handlebars.helpers @public */ export default function(morph, env, scope, params, hash, template, inverse, visitor) { if (isEnabled('ember-routing-htmlbars-improved-actions')) { if (morph) { keyword('@element_action', morph, env, scope, params, hash, template, inverse, visitor); return true; } return closureAction(morph, env, scope, params, hash, template, inverse, visitor); } else { keyword('@element_action', morph, env, scope, params, hash, template, inverse, visitor); return true; } }
/* * WYMeditor : what you see is What You Mean web-based editor * Copyright (c) 2005 - 2009 Jean-Francois Hovinne, http://www.wymeditor.org/ * Dual licensed under the MIT (MIT-license.txt) * and GPL (GPL-license.txt) licenses. * * For further information visit: * http://www.wymeditor.org/ * * File Name: * jquery.wymeditor.fullscreen.js * Fullscreen plugin for WYMeditor * * File Authors: * Luis Santos (luis.santos a-t openquest dotpt) * Jonatan Lundin (jonatan.lundin a-t gmail dotcom) * Gerd Riesselmann (gerd a-t gyro-php dot org) : Fixed issue with new skin layout * Philipp Cordes (pc a-t irgendware dotnet) */ //Extend WYMeditor WYMeditor.editor.prototype.fullscreen = function() { var wym = this, $box = jQuery(this._box), $iframe = jQuery(this._iframe), $overlay = null, $window = jQuery(window), editorMargin = 15; // Margin from window (without padding) //construct the button's html var html = '' + "<li class='wym_tools_fullscreen'>" + "<a name='Fullscreen' href='#' " + "title='Fullscreen' " + "style='background-image: url(" + wym._options.basePath + "plugins/fullscreen/icon_fullscreen.gif)'>" + "Fullscreen" + "</a>" + "</li>"; //add the button to the tools box $box.find(wym._options.toolsSelector + wym._options.toolsListSelector) .append(html); function resize () { // Calculate margins var uiHeight = $box.outerHeight(true) - $iframe.outerHeight(true); var editorPadding = $box.outerWidth() - $box.width(); // Calculate heights var screenHeight = $window.height(); var iframeHeight = (screenHeight - uiHeight - (editorMargin * 2)) + 'px'; // Calculate witdths var screenWidth = $window.width(); var boxWidth = (screenWidth - editorPadding - (editorMargin * 2)) + 'px'; $box.css('width', boxWidth); $iframe.css('height', iframeHeight); $overlay.css({ 'height': screenHeight + 'px', 'width': screenWidth + 'px' }); } //handle click event $box.find('li.wym_tools_fullscreen a').click(function() { if ($box.css('position') != 'fixed') { // Store previous inline styles $box.data('wym-inline-css', $box.attr('style')); $iframe.data('wym-inline-css', $iframe.attr('style')); // Create overlay $overlay = jQuery('<div id="wym-fullscreen-overlay"></div>') .appendTo('body').css({ 'position': 'fixed', 'background-color': 'rgb(0, 0, 0)', 'opacity': '0.75', 'z-index': '98', 'top': '0px', 'left': '0px' }); // Possition the editor $box.css({ 'position': 'fixed', 'z-index': '99', 'top': editorMargin + 'px', 'left': editorMargin + 'px' }); // Bind event listeners $window.bind('resize', resize); $box.find('li.wym_tools_html a').bind('click', resize); // Force resize resize(); } else { // Unbind event listeners $window.unbind('resize', resize); $box.find('li.wym_tools_html a').unbind('click', resize); // Remove inline styles $box.css({ 'position': 'static', 'z-index': '', 'width': '', 'top': '', 'left': '' }); $iframe.css('height', ''); // Remove overlay $overlay.remove(); $overlay = null; // Retore previous inline styles $box.attr('style', $box.data('wym-inline-css')); $iframe.attr('style', $iframe.data('wym-inline-css')); } return false; }); };
define("ace/snippets/plain_text",["require","exports","module"], function(require, exports, module) { "use strict"; exports.snippetText = ""; exports.scope = "plain_text"; }); (function() { window.require(["ace/snippets/plain_text"], function(m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })();
module.exports={A:{A:{"2":"J C G E B A UB"},B:{"1":"X g H L","2":"D"},C:{"1":"0 1 4 5 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s","2":"2 SB F I J C G E B A D X g H L M N O P Q R S T U QB PB"},D:{"1":"0 1 4 5 8 i j k l m n o p q r w x v z t s EB BB TB CB","2":"F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h"},E:{"1":"B A JB KB","2":"9 F I J C G E DB FB GB HB IB"},F:{"1":"V W u Y Z a b c d e f K h i j k l m n o p q r","2":"6 7 E A D H L M N O P Q R S T U LB MB NB OB RB y"},G:{"1":"A bB cB","2":"3 9 G AB VB WB XB YB ZB aB"},H:{"2":"dB"},I:{"1":"s","2":"2 3 F eB fB gB hB iB jB"},J:{"2":"C B"},K:{"1":"K","2":"6 7 B A D y"},L:{"1":"8"},M:{"1":"t"},N:{"2":"B A"},O:{"1":"kB"},P:{"1":"F I"},Q:{"2":"lB"},R:{"1":"mB"}},B:6,C:"ES6 Generators"};
// 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. // Copyright 2007 Google Inc. All Rights Reserved. /** * @fileoverview A menu class for showing popups. A single popup can be * attached to multiple anchor points. The menu will try to reposition itself * if it goes outside the viewport. * * Decoration is the same as goog.ui.Menu except that the outer DIV can have a * 'for' property, which is the ID of the element which triggers the popup. * * Decorate Example: * <button id="dButton">Decorated Popup</button> * <div id="dMenu" for="dButton" class="goog-menu"> * <div class="goog-menuitem">A a</div> * <div class="goog-menuitem">B b</div> * <div class="goog-menuitem">C c</div> * <div class="goog-menuitem">D d</div> * <div class="goog-menuitem">E e</div> * <div class="goog-menuitem">F f</div> * </div> * * TESTED=FireFox 2.0, IE6, Opera 9, Chrome. * TODO: Key handling is flakey in Opera and Chrome * * @see ../demos/popupmenu.html */ goog.provide('goog.ui.PopupMenu'); goog.require('goog.events.EventType'); goog.require('goog.positioning.AnchoredViewportPosition'); goog.require('goog.positioning.Corner'); goog.require('goog.positioning.ViewportClientPosition'); goog.require('goog.structs'); goog.require('goog.structs.Map'); goog.require('goog.style'); goog.require('goog.ui.Component.EventType'); goog.require('goog.ui.Menu'); goog.require('goog.ui.PopupBase'); goog.require('goog.userAgent'); /** * A basic menu class. * @param {goog.dom.DomHelper} opt_domHelper Optional DOM helper. * @extends {goog.ui.Menu} * @constructor */ goog.ui.PopupMenu = function(opt_domHelper) { goog.ui.Menu.call(this, opt_domHelper); this.setAllowAutoFocus(true); // Popup menus are hidden by default. this.setVisible(false, true); /** * Map of attachment points for the menu. Key -> Object * @type {!goog.structs.Map} * @private */ this.targets_ = new goog.structs.Map(); }; goog.inherits(goog.ui.PopupMenu, goog.ui.Menu); /** * If true, then if the menu will toggle off if it is already visible. * @type {boolean} * @private */ goog.ui.PopupMenu.prototype.toggleMode_ = false; /** * Time that the menu was last shown. * @type {number} * @private */ goog.ui.PopupMenu.prototype.lastHide_ = 0; /** * Current element where the popup menu is anchored. * @type {Element?} * @private */ goog.ui.PopupMenu.prototype.currentAnchor_ = null; /** * Decorate an existing HTML structure with the menu. Menu items will be * constructed from elements with classname 'goog-menuitem', separators will be * made from HR elements. * @param {Element} element Element to decorate. */ goog.ui.PopupMenu.prototype.decorateInternal = function(element) { goog.ui.PopupMenu.superClass_.decorateInternal.call(this, element); // 'for' is a custom attribute for attaching the menu to a click target var htmlFor = element.getAttribute('for') || element.htmlFor; if (htmlFor) { this.attach( this.getDomHelper().getElement(htmlFor), goog.positioning.Corner.BOTTOM_LEFT); } }; /** * The menu has been added to the document. */ goog.ui.PopupMenu.prototype.enterDocument = function() { goog.ui.PopupMenu.superClass_.enterDocument.call(this); goog.structs.forEach(this.targets_, this.attachEvent_, this); var handler = this.getHandler(); handler.listen( this, goog.ui.Component.EventType.ACTION, this.onAction_); handler.listen(this.getDomHelper().getDocument(), goog.events.EventType.MOUSEDOWN, this.onDocClick, true); // Webkit doesn't fire a mousedown event when opening the context menu, // but we need one to update menu visibility properly. So in Safari handle // contextmenu mouse events like mousedown. // {@link http://bugs.webkit.org/show_bug.cgi?id=6595} if (goog.userAgent.WEBKIT) { handler.listen(this.getDomHelper().getDocument(), goog.events.EventType.CONTEXTMENU, this.onDocClick, true); } }; /** * Attaches the menu to a new popup position and anchor element. A menu can * only be attached to an element once, since attaching the same menu for * multiple positions doesn't make sense. * * @param {Element} element Element whose click event should trigger the menu. * @param {goog.positioning.Corner} opt_targetCorner Corner of the target that * the menu should be anchored to. * @param {goog.positioning.Corner} opt_menuCorner Corner of the menu that * should be anchored. * @param {boolean} opt_contextMenu Whether the menu should show on * {@link goog.events.EventType.CONTEXTMENU} events, false if it should * show on {@link goog.events.EventType.MOUSEDOWN} events. Default is * MOUSEDOWN. * @param {goog.math.Box} opt_margin Margin for the popup used in positioning * algorithms. */ goog.ui.PopupMenu.prototype.attach = function( element, opt_targetCorner, opt_menuCorner, opt_contextMenu, opt_margin) { if (this.isAttachTarget(element)) { // Already in the popup, so just return. return; } var target = this.createAttachTarget(element, opt_targetCorner, opt_menuCorner, opt_contextMenu, opt_margin); if (this.isInDocument()) { this.attachEvent_(target); } }; /** * Creates an object describing how the popup menu should be attached to the * anchoring element based on the given parameters. The created object is * stored, keyed by {@code element} and is retrievable later by invoking * {@link #getAttachTarget(element)} at a later point. * * Subclass may add more properties to the returned object, as needed. * * @param {Element} element Element whose click event should trigger the menu. * @param {goog.positioning.Corner} opt_targetCorner Corner of the target that * the menu should be anchored to. * @param {goog.positioning.Corner} opt_menuCorner Corner of the menu that * should be anchored. * @param {boolean} opt_contextMenu Whether the menu should show on * {@link goog.events.EventType.CONTEXTMENU} events, false if it should * show on {@link goog.events.EventType.MOUSEDOWN} events. Default is * MOUSEDOWN. * @param {goog.math.Box} opt_margin Margin for the popup used in positioning * algorithms. * * @return {Object} An object that describes how the popup menu should be * attached to the anchoring element. * * @protected */ goog.ui.PopupMenu.prototype.createAttachTarget = function( element, opt_targetCorner, opt_menuCorner, opt_contextMenu, opt_margin) { if (!element) { return null; } var target = { element_: element, targetCorner_: opt_targetCorner, menuCorner_: opt_menuCorner, eventType_: opt_contextMenu ? goog.events.EventType.CONTEXTMENU : goog.events.EventType.MOUSEDOWN, margin_: opt_margin }; this.targets_.set(goog.getHashCode(element), target); return target; }; /** * Returns the object describing how the popup menu should be attach to given * element or {@code null}. The object is created and the association is formed * when {@link #attach} is invoked. * * @param {Element} element DOM element. * @return {Object} The object created when {@link attach} is invoked on * {@code element}. Returns {@code null} if the element does not trigger * the menu (i.e. {@link attach} has never been invoked on * {@code element}). * @protected */ goog.ui.PopupMenu.prototype.getAttachTarget = function(element) { return element ? /** @type {Object} */(this.targets_.get(goog.getHashCode(element))) : null; }; /** * @param {Element} element Any DOM element. * @return {boolean} Whether clicking on the given element will trigger the * menu. * * @protected */ goog.ui.PopupMenu.prototype.isAttachTarget = function(element) { return element ? this.targets_.containsKey(goog.getHashCode(element)) : false; }; /** * @return {Element?} The current element where the popup is anchored, if it's * visible. */ goog.ui.PopupMenu.prototype.getAttachedElement = function() { return this.currentAnchor_; }; /** * Attaches an event listener to a target * @param {Object} target The target to attach an event to. * @private */ goog.ui.PopupMenu.prototype.attachEvent_ = function(target) { this.getHandler().listen( target.element_, target.eventType_, this.onTargetClick_); }; /** * Detaches all listeners */ goog.ui.PopupMenu.prototype.detachAll = function() { if (this.isInDocument()) { var keys = this.targets_.getKeys(); for (var i = 0; i < keys.length; i++) { this.detachEvent_(/** @type {Object} */ (this.targets_.get(keys[i]))); } } this.targets_.clear(); }; /** * Detaches a menu from a given element. * @param {Element} element Element whose click event should trigger the menu. */ goog.ui.PopupMenu.prototype.detach = function(element) { if (!this.isAttachTarget(element)) { throw Error('Menu not attached to provided element, unable to detach.'); } var key = goog.getHashCode(element); if (this.isInDocument()) { this.detachEvent_(/** @type {Object} */ (this.targets_.get(key))); } this.targets_.remove(key); }; /** * Detaches an event listener to a target * @param {Object} target The target to detach events from. * @private */ goog.ui.PopupMenu.prototype.detachEvent_ = function(target) { this.getHandler().unlisten( target.element_, target.eventType_, this.onTargetClick_); }; /** * Sets whether the menu should toggle if it is already open. For context * menus this should be false, for toolbar menus it makes more sense to be true. * @param {boolean} toggle The new toggle mode. */ goog.ui.PopupMenu.prototype.setToggleMode = function(toggle) { this.toggleMode_ = toggle; }; /** * Gets whether the menu is in toggle mode * @return {boolean} toggle. */ goog.ui.PopupMenu.prototype.getToggleMode = function() { return this.toggleMode_; }; /** * Show the menu at a given attached target. * @param {Object} target Popup target. * @param {number} x The client-X associated with the show event. * @param {number} y The client-Y associated with the show event. * @protected */ goog.ui.PopupMenu.prototype.showMenu = function(target, x, y) { var isVisible = this.isVisible(); if ((isVisible || this.wasRecentlyHidden()) && this.toggleMode_) { this.hide(); return; } // Notify event handlers that the menu is about to be shown. if (!this.dispatchEvent(goog.ui.Component.EventType.BEFORE_SHOW)) { return; } var position = goog.isDef(target.targetCorner_) ? new goog.positioning.AnchoredViewportPosition(target.element_, target.targetCorner_) : new goog.positioning.ViewportClientPosition(x, y); var menuCorner = goog.isDef(target.menuCorner_) ? target.menuCorner_ : goog.positioning.Corner.TOP_START; // This is a little hacky so that we can position the menu with minimal // flicker. if (!isVisible) { // On IE, setting visibility = 'hidden' on a visible menu // will cause a blur, forcing the menu to close immediately. this.getElement().style.visibility = 'hidden'; } goog.style.showElement(this.getElement(), true); position.reposition(this.getElement(), menuCorner, target.margin_); if (!isVisible) { this.getElement().style.visibility = 'visible'; } this.currentAnchor_ = target.element_; this.setHighlightedIndex(-1); // setVisible dispatches a goog.ui.Component.EventType.SHOW event, which may // be canceled to prevent the menu from being shown. this.setVisible(true); }; /** * Shows the menu immediately at the given client coordinates. * @param {number} x The client-X associated with the show event. * @param {number} y The client-Y associated with the show event. * @param {goog.positioning.Corner} opt_menuCorner Corner of the menu that * should be anchored. */ goog.ui.PopupMenu.prototype.showAt = function(x, y, opt_menuCorner) { this.showMenu({menuCorner_: opt_menuCorner}, x, y); }; /** * Shows the menu immediately attached to the given element * @param {Element} element The element to show at. * @param {goog.positioning.Corner} targetCorner The corner of the target to * anchor to. * @param {goog.positioning.Corner} opt_menuCorner Corner of the menu that * should be anchored. */ goog.ui.PopupMenu.prototype.showAtElement = function(element, targetCorner, opt_menuCorner) { this.showMenu({ menuCorner_: opt_menuCorner, element_: element, targetCorner_: targetCorner }, 0, 0); }; /** * Hides the menu. */ goog.ui.PopupMenu.prototype.hide = function() { // setVisible dispatches a goog.ui.Component.EventType.HIDE event, which may // be canceled to prevent the menu from being hidden. this.setVisible(false); if (!this.isVisible()) { // HIDE event wasn't canceled; the menu is now hidden. this.lastHide_ = goog.now(); this.currentAnchor_ = null; } }; /** * Used to stop the menu toggling back on if the toggleMode == false. * @return {boolean} Whether the menu was recently hidden. * @protected */ goog.ui.PopupMenu.prototype.wasRecentlyHidden = function() { return goog.now() - this.lastHide_ < goog.ui.PopupBase.DEBOUNCE_DELAY_MS; }; /** * Dismiss the popup menu when an action fires. * @param {goog.events.Event} opt_e The optional event. * @private */ goog.ui.PopupMenu.prototype.onAction_ = function(opt_e) { this.hide(); }; /** * Handles a browser event on one of the popup targets * @param {goog.events.BrowserEvent} e The browser event. * @private */ goog.ui.PopupMenu.prototype.onTargetClick_ = function(e) { var keys = this.targets_.getKeys(); for (var i = 0; i < keys.length; i++) { var target = /** @type {Object} */(this.targets_.get(keys[i])); if (target.element_ == e.currentTarget) { this.showMenu(target, /** @type {number} */ (e.clientX), /** @type {number} */ (e.clientY)); e.preventDefault(); e.stopPropagation(); return; } } }; /** * Handles click events that propagate to the document. * @param {goog.events.BrowserEvent} e The browser event. * @protected */ goog.ui.PopupMenu.prototype.onDocClick = function(e) { if (this.isVisible() && !this.containsElement(/** @type {Element} */ (e.target))) { this.hide(); } }; /** * Handles the key event target loosing focus. * @param {goog.events.BrowserEvent} e The browser event. * @protected */ goog.ui.PopupMenu.prototype.handleBlur = function(e) { goog.ui.PopupMenu.superClass_.handleBlur.call(this, e); this.hide(); }; /** @inheritDoc */ goog.ui.PopupMenu.prototype.disposeInternal = function() { // Always call the superclass' disposeInternal() first (Bug 715885). goog.ui.PopupMenu.superClass_.disposeInternal.call(this); // Disposes of the attachment target map. if (this.targets_) { this.targets_.clear(); delete this.targets_; } };
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Number format/parse library with locale support. */ /** * Namespace for locale number format functions */ goog.provide('goog.i18n.NumberFormat'); goog.require('goog.i18n.NumberFormatSymbols'); goog.require('goog.i18n.currencyCodeMap'); /** * Constructor of NumberFormat. * @param {number|string} pattern The number that indicates a predefined * number format pattern. * @param {string=} opt_currency Optional international currency code. This * determines the currency code/symbol used in format/parse. If not given, * the currency code for current locale will be used. * @constructor */ goog.i18n.NumberFormat = function(pattern, opt_currency) { this.intlCurrencyCode_ = opt_currency || goog.i18n.NumberFormatSymbols.DEF_CURRENCY_CODE; this.currencySymbol_ = goog.i18n.currencyCodeMap[this.intlCurrencyCode_]; this.maximumIntegerDigits_ = 40; this.minimumIntegerDigits_ = 1; this.maximumFractionDigits_ = 3; // invariant, >= minFractionDigits this.minimumFractionDigits_ = 0; this.minExponentDigits_ = 0; this.useSignForPositiveExponent_ = false; this.positivePrefix_ = ''; this.positiveSuffix_ = ''; this.negativePrefix_ = '-'; this.negativeSuffix_ = ''; // The multiplier for use in percent, per mille, etc. this.multiplier_ = 1; this.groupingSize_ = 3; this.decimalSeparatorAlwaysShown_ = false; this.useExponentialNotation_ = false; if (typeof pattern == 'number') { this.applyStandardPattern_(pattern); } else { this.applyPattern_(pattern); } }; /** * Standard number formatting patterns. * @enum {number} */ goog.i18n.NumberFormat.Format = { DECIMAL: 1, SCIENTIFIC: 2, PERCENT: 3, CURRENCY: 4 }; /** * Apply provided pattern, result are stored in member variables. * * @param {string} pattern String pattern being applied. * @private */ goog.i18n.NumberFormat.prototype.applyPattern_ = function(pattern) { this.pattern_ = pattern.replace(/ /g, '\u00a0'); var pos = [0]; this.positivePrefix_ = this.parseAffix_(pattern, pos); var trunkStart = pos[0]; this.parseTrunk_(pattern, pos); var trunkLen = pos[0] - trunkStart; this.positiveSuffix_ = this.parseAffix_(pattern, pos); if (pos[0] < pattern.length && pattern.charAt(pos[0]) == goog.i18n.NumberFormat.PATTERN_SEPARATOR_) { pos[0]++; this.negativePrefix_ = this.parseAffix_(pattern, pos); // we assume this part is identical to positive part. // user must make sure the pattern is correctly constructed. pos[0] += trunkLen; this.negativeSuffix_ = this.parseAffix_(pattern, pos); } else { // if no negative affix specified, they share the same positive affix this.negativePrefix_ = this.positivePrefix_ + this.negativePrefix_; this.negativeSuffix_ += this.positiveSuffix_; } }; /** * Apply a predefined pattern to NumberFormat object. * @param {number} patternType The number that indicates a predefined number * format pattern. * @private */ goog.i18n.NumberFormat.prototype.applyStandardPattern_ = function(patternType) { switch (patternType) { case goog.i18n.NumberFormat.Format.DECIMAL: this.applyPattern_(goog.i18n.NumberFormatSymbols.DECIMAL_PATTERN); break; case goog.i18n.NumberFormat.Format.SCIENTIFIC: this.applyPattern_(goog.i18n.NumberFormatSymbols.SCIENTIFIC_PATTERN); break; case goog.i18n.NumberFormat.Format.PERCENT: this.applyPattern_(goog.i18n.NumberFormatSymbols.PERCENT_PATTERN); break; case goog.i18n.NumberFormat.Format.CURRENCY: this.applyPattern_(goog.i18n.NumberFormatSymbols.CURRENCY_PATTERN); break; default: throw Error('Unsupported pattern type.'); } }; /** * Parses text string to produce a Number. * * This method attempts to parse text starting from position "opt_pos" if it * is given. Otherwise the parse will start from the beginning of the text. * When opt_pos presents, opt_pos will be updated to the character next to where * parsing stops after the call. If an error occurs, opt_pos won't be updated. * * @param {string} text The string to be parsed. * @param {Array.<number>=} opt_pos Position to pass in and get back. * @return {number} Parsed number. This throws an error if the text cannot be * parsed. */ goog.i18n.NumberFormat.prototype.parse = function(text, opt_pos) { var pos = opt_pos || [0]; var start = pos[0]; var ret = NaN; // we don't want to handle 2 kind of space in parsing, normalize it to nbsp text = text.replace(/ /g, '\u00a0'); var gotPositive = text.indexOf(this.positivePrefix_, pos[0]) == pos[0]; var gotNegative = text.indexOf(this.negativePrefix_, pos[0]) == pos[0]; // check for the longest match if (gotPositive && gotNegative) { if (this.positivePrefix_.length > this.negativePrefix_.length) { gotNegative = false; } else if (this.positivePrefix_.length < this.negativePrefix_.length) { gotPositive = false; } } if (gotPositive) { pos[0] += this.positivePrefix_.length; } else if (gotNegative) { pos[0] += this.negativePrefix_.length; } // process digits or Inf, find decimal position if (text.indexOf(goog.i18n.NumberFormatSymbols.INFINITY, pos[0]) == pos[0]) { pos[0] += goog.i18n.NumberFormatSymbols.INFINITY.length; ret = Infinity; } else { ret = this.parseNumber_(text, pos); } // check for suffix if (gotPositive) { if (!(text.indexOf(this.positiveSuffix_, pos[0]) == pos[0])) { return NaN; } pos[0] += this.positiveSuffix_.length; } else if (gotNegative) { if (!(text.indexOf(this.negativeSuffix_, pos[0]) == pos[0])) { return NaN; } pos[0] += this.negativeSuffix_.length; } return gotNegative ? -ret : ret; }; /** * This function will parse a "localized" text into a Number. It needs to * handle locale specific decimal, grouping, exponent and digits. * * @param {string} text The text that need to be parsed. * @param {Array.<number>} pos In/out parsing position. In case of failure, * pos value won't be changed. * @return {number} Number value, or NaN if nothing can be parsed. * @private */ goog.i18n.NumberFormat.prototype.parseNumber_ = function(text, pos) { var sawDecimal = false; var sawExponent = false; var sawDigit = false; var scale = 1; var decimal = goog.i18n.NumberFormatSymbols.DECIMAL_SEP; var grouping = goog.i18n.NumberFormatSymbols.GROUP_SEP; var exponentChar = goog.i18n.NumberFormatSymbols.EXP_SYMBOL; var normalizedText = ''; for (; pos[0] < text.length; pos[0]++) { var ch = text.charAt(pos[0]); var digit = this.getDigit_(ch); if (digit >= 0 && digit <= 9) { normalizedText += digit; sawDigit = true; } else if (ch == decimal.charAt(0)) { if (sawDecimal || sawExponent) { break; } normalizedText += '.'; sawDecimal = true; } else if (ch == grouping.charAt(0) && ('\u00a0' != grouping.charAt(0) || pos[0] + 1 < text.length && this.getDigit_(text.charAt(pos[0] + 1)) >= 0)) { // Got a grouping character here. When grouping character is nbsp, need // to make sure the character following it is a digit. if (sawDecimal || sawExponent) { break; } continue; } else if (ch == exponentChar.charAt(0)) { if (sawExponent) { break; } normalizedText += 'E'; sawExponent = true; } else if (ch == '+' || ch == '-') { normalizedText += ch; } else if (ch == goog.i18n.NumberFormatSymbols.PERCENT.charAt(0)) { if (scale != 1) { break; } scale = 100; if (sawDigit) { pos[0]++; // eat this character if parse end here break; } } else if (ch == goog.i18n.NumberFormatSymbols.PERMILL.charAt(0)) { if (scale != 1) { break; } scale = 1000; if (sawDigit) { pos[0]++; // eat this character if parse end here break; } } else { break; } } return parseFloat(normalizedText) / scale; }; /** * Formats a Number to produce a string. * * @param {number} number The Number to be formatted. * @return {string} The formatted number string. */ goog.i18n.NumberFormat.prototype.format = function(number) { if (isNaN(number)) { return goog.i18n.NumberFormatSymbols.NAN; } var parts = []; // in icu code, it is commented that certain computation need to keep the // negative sign for 0. var isNegative = number < 0.0 || number == 0.0 && 1 / number < 0.0; parts.push(isNegative ? this.negativePrefix_ : this.positivePrefix_); if (!isFinite(number)) { parts.push(goog.i18n.NumberFormatSymbols.INFINITY); } else { // convert number to non-negative value number *= isNegative ? -1 : 1; number *= this.multiplier_; this.useExponentialNotation_ ? this.subformatExponential_(number, parts) : this.subformatFixed_(number, this.minimumIntegerDigits_, parts); } parts.push(isNegative ? this.negativeSuffix_ : this.positiveSuffix_); return parts.join(''); }; /** * Formats a Number in fraction format. * * @param {number} number Value need to be formated. * @param {number} minIntDigits Minimum integer digits. * @param {Array} parts This array holds the pieces of formatted string. * This function will add its formatted pieces to the array. * @private */ goog.i18n.NumberFormat.prototype.subformatFixed_ = function(number, minIntDigits, parts) { // round the number var power = Math.pow(10, this.maximumFractionDigits_); number = Math.round(number * power); var intValue = Math.floor(number / power); var fracValue = Math.floor(number - intValue * power); var fractionPresent = this.minimumFractionDigits_ > 0 || fracValue > 0; var intPart = ''; var translatableInt = intValue; while (translatableInt > 1E20) { // here it goes beyond double precision, add '0' make it look better intPart = '0' + intPart; translatableInt = Math.round(translatableInt / 10); } intPart = translatableInt + intPart; var decimal = goog.i18n.NumberFormatSymbols.DECIMAL_SEP; var grouping = goog.i18n.NumberFormatSymbols.GROUP_SEP; var zeroCode = goog.i18n.NumberFormatSymbols.ZERO_DIGIT.charCodeAt(0); var digitLen = intPart.length; if (intValue > 0 || minIntDigits > 0) { for (var i = digitLen; i < minIntDigits; i++) { parts.push(goog.i18n.NumberFormatSymbols.ZERO_DIGIT); } for (var i = 0; i < digitLen; i++) { parts.push(String.fromCharCode(zeroCode + intPart.charAt(i) * 1)); if (digitLen - i > 1 && this.groupingSize_ > 0 && ((digitLen - i) % this.groupingSize_ == 1)) { parts.push(grouping); } } } else if (!fractionPresent) { // If there is no fraction present, and we haven't printed any // integer digits, then print a zero. parts.push(goog.i18n.NumberFormatSymbols.ZERO_DIGIT); } // Output the decimal separator if we always do so. if (this.decimalSeparatorAlwaysShown_ || fractionPresent) { parts.push(decimal); } var fracPart = '' + (fracValue + power); var fracLen = fracPart.length; while (fracPart.charAt(fracLen - 1) == '0' && fracLen > this.minimumFractionDigits_ + 1) { fracLen--; } for (var i = 1; i < fracLen; i++) { parts.push(String.fromCharCode(zeroCode + fracPart.charAt(i) * 1)); } }; /** * Formats exponent part of a Number. * * @param {number} exponent Exponential value. * @param {Array.<string>} parts The array that holds the pieces of formatted * string. This function will append more formatted pieces to the array. * @private */ goog.i18n.NumberFormat.prototype.addExponentPart_ = function(exponent, parts) { parts.push(goog.i18n.NumberFormatSymbols.EXP_SYMBOL); if (exponent < 0) { exponent = -exponent; parts.push(goog.i18n.NumberFormatSymbols.MINUS_SIGN); } else if (this.useSignForPositiveExponent_) { parts.push(goog.i18n.NumberFormatSymbols.PLUS_SIGN); } var exponentDigits = '' + exponent; for (var i = exponentDigits.length; i < this.minExponentDigits_; i++) { parts.push(goog.i18n.NumberFormatSymbols.ZERO_DIGIT); } parts.push(exponentDigits); }; /** * Formats Number in exponential format. * * @param {number} number Value need to be formated. * @param {Array.<string>} parts The array that holds the pieces of formatted * string. This function will append more formatted pieces to the array. * @private */ goog.i18n.NumberFormat.prototype.subformatExponential_ = function(number, parts) { if (number == 0.0) { this.subformatFixed_(number, this.minimumIntegerDigits_, parts); this.addExponentPart_(0, parts); return; } var exponent = Math.floor(Math.log(number) / Math.log(10)); number /= Math.pow(10, exponent); var minIntDigits = this.minimumIntegerDigits_; if (this.maximumIntegerDigits_ > 1 && this.maximumIntegerDigits_ > this.minimumIntegerDigits_) { // A repeating range is defined; adjust to it as follows. // If repeat == 3, we have 6,5,4=>3; 3,2,1=>0; 0,-1,-2=>-3; // -3,-4,-5=>-6, etc. This takes into account that the // exponent we have here is off by one from what we expect; // it is for the format 0.MMMMMx10^n. while ((exponent % this.maximumIntegerDigits_) != 0) { number *= 10; exponent--; } minIntDigits = 1; } else { // No repeating range is defined; use minimum integer digits. if (this.minimumIntegerDigits_ < 1) { exponent++; number /= 10; } else { exponent -= this.minimumIntegerDigits_ - 1; number *= Math.pow(10, this.minimumIntegerDigits_ - 1); } } this.subformatFixed_(number, minIntDigits, parts); this.addExponentPart_(exponent, parts); }; /** * Returns the digit value of current character. The character could be either * '0' to '9', or a locale specific digit. * * @param {string} ch Character that represents a digit. * @return {number} The digit value, or -1 on error. * @private */ goog.i18n.NumberFormat.prototype.getDigit_ = function(ch) { var code = ch.charCodeAt(0); // between '0' to '9' if (48 <= code && code < 58) { return code - 48; } else { var zeroCode = goog.i18n.NumberFormatSymbols.ZERO_DIGIT.charCodeAt(0); return zeroCode <= code && code < zeroCode + 10 ? code - zeroCode : -1; } }; // ---------------------------------------------------------------------- // CONSTANTS // ---------------------------------------------------------------------- // Constants for characters used in programmatic (unlocalized) patterns. /** * A zero digit character. * @type {string} * @private */ goog.i18n.NumberFormat.PATTERN_ZERO_DIGIT_ = '0'; /** * A grouping separator character. * @type {string} * @private */ goog.i18n.NumberFormat.PATTERN_GROUPING_SEPARATOR_ = ','; /** * A decimal separator character. * @type {string} * @private */ goog.i18n.NumberFormat.PATTERN_DECIMAL_SEPARATOR_ = '.'; /** * A per mille character. * @type {string} * @private */ goog.i18n.NumberFormat.PATTERN_PER_MILLE_ = '\u2030'; /** * A percent character. * @type {string} * @private */ goog.i18n.NumberFormat.PATTERN_PERCENT_ = '%'; /** * A digit character. * @type {string} * @private */ goog.i18n.NumberFormat.PATTERN_DIGIT_ = '#'; /** * A separator character. * @type {string} * @private */ goog.i18n.NumberFormat.PATTERN_SEPARATOR_ = ';'; /** * An exponent character. * @type {string} * @private */ goog.i18n.NumberFormat.PATTERN_EXPONENT_ = 'E'; /** * An plus character. * @type {string} * @private */ goog.i18n.NumberFormat.PATTERN_PLUS_ = '+'; /** * A minus character. * @type {string} * @private */ goog.i18n.NumberFormat.PATTERN_MINUS_ = '-'; /** * A quote character. * @type {string} * @private */ goog.i18n.NumberFormat.PATTERN_CURRENCY_SIGN_ = '\u00A4'; /** * A quote character. * @type {string} * @private */ goog.i18n.NumberFormat.QUOTE_ = '\''; /** * Parses affix part of pattern. * * @param {string} pattern Pattern string that need to be parsed. * @param {Array.<number>} pos One element position array to set and receive * parsing position. * * @return {string} Affix received from parsing. * @private */ goog.i18n.NumberFormat.prototype.parseAffix_ = function(pattern, pos) { var affix = ''; var inQuote = false; var len = pattern.length; for (; pos[0] < len; pos[0]++) { var ch = pattern.charAt(pos[0]); if (ch == goog.i18n.NumberFormat.QUOTE_) { if (pos[0] + 1 < len && pattern.charAt(pos[0] + 1) == goog.i18n.NumberFormat.QUOTE_) { pos[0]++; affix += '\''; // 'don''t' } else { inQuote = !inQuote; } continue; } if (inQuote) { affix += ch; } else { switch (ch) { case goog.i18n.NumberFormat.PATTERN_DIGIT_: case goog.i18n.NumberFormat.PATTERN_ZERO_DIGIT_: case goog.i18n.NumberFormat.PATTERN_GROUPING_SEPARATOR_: case goog.i18n.NumberFormat.PATTERN_DECIMAL_SEPARATOR_: case goog.i18n.NumberFormat.PATTERN_SEPARATOR_: return affix; case goog.i18n.NumberFormat.PATTERN_CURRENCY_SIGN_: if ((pos[0] + 1) < len && pattern.charAt(pos[0] + 1) == goog.i18n.NumberFormat.PATTERN_CURRENCY_SIGN_) { pos[0]++; affix += this.intlCurrencyCode_; } else { affix += this.currencySymbol_; } break; case goog.i18n.NumberFormat.PATTERN_PERCENT_: if (this.multiplier_ != 1) { throw Error('Too many percent/permill'); } this.multiplier_ = 100; affix += goog.i18n.NumberFormatSymbols.PERCENT; break; case goog.i18n.NumberFormat.PATTERN_PER_MILLE_: if (this.multiplier_ != 1) { throw Error('Too many percent/permill'); } this.multiplier_ = 1000; affix += goog.i18n.NumberFormatSymbols.PERMILL; break; default: affix += ch; } } } return affix; }; /** * Parses the trunk part of a pattern. * * @param {string} pattern Pattern string that need to be parsed. * @param {Array.<number>} pos One element position array to set and receive * parsing position. * @private */ goog.i18n.NumberFormat.prototype.parseTrunk_ = function(pattern, pos) { var decimalPos = -1; var digitLeftCount = 0; var zeroDigitCount = 0; var digitRightCount = 0; var groupingCount = -1; var len = pattern.length; for (var loop = true; pos[0] < len && loop; pos[0]++) { var ch = pattern.charAt(pos[0]); switch (ch) { case goog.i18n.NumberFormat.PATTERN_DIGIT_: if (zeroDigitCount > 0) { digitRightCount++; } else { digitLeftCount++; } if (groupingCount >= 0 && decimalPos < 0) { groupingCount++; } break; case goog.i18n.NumberFormat.PATTERN_ZERO_DIGIT_: if (digitRightCount > 0) { throw Error('Unexpected "0" in pattern "' + pattern + '"'); } zeroDigitCount++; if (groupingCount >= 0 && decimalPos < 0) { groupingCount++; } break; case goog.i18n.NumberFormat.PATTERN_GROUPING_SEPARATOR_: groupingCount = 0; break; case goog.i18n.NumberFormat.PATTERN_DECIMAL_SEPARATOR_: if (decimalPos >= 0) { throw Error('Multiple decimal separators in pattern "' + pattern + '"'); } decimalPos = digitLeftCount + zeroDigitCount + digitRightCount; break; case goog.i18n.NumberFormat.PATTERN_EXPONENT_: if (this.useExponentialNotation_) { throw Error('Multiple exponential symbols in pattern "' + pattern + '"'); } this.useExponentialNotation_ = true; this.minExponentDigits_ = 0; // exponent pattern can have a optional '+'. if ((pos[0] + 1) < len && pattern.charAt(pos[0] + 1) == goog.i18n.NumberFormat.PATTERN_PLUS_) { pos[0]++; this.useSignForPositiveExponent_ = true; } // Use lookahead to parse out the exponential part // of the pattern, then jump into phase 2. while ((pos[0] + 1) < len && pattern.charAt(pos[0] + 1) == goog.i18n.NumberFormat.PATTERN_ZERO_DIGIT_) { pos[0]++; this.minExponentDigits_++; } if ((digitLeftCount + zeroDigitCount) < 1 || this.minExponentDigits_ < 1) { throw Error('Malformed exponential pattern "' + pattern + '"'); } loop = false; break; default: pos[0]--; loop = false; break; } } if (zeroDigitCount == 0 && digitLeftCount > 0 && decimalPos >= 0) { // Handle '###.###' and '###.' and '.###' var n = decimalPos; if (n == 0) { // Handle '.###' n++; } digitRightCount = digitLeftCount - n; digitLeftCount = n - 1; zeroDigitCount = 1; } // Do syntax checking on the digits. if (decimalPos < 0 && digitRightCount > 0 || decimalPos >= 0 && (decimalPos < digitLeftCount || decimalPos > digitLeftCount + zeroDigitCount) || groupingCount == 0) { throw Error('Malformed pattern "' + pattern + '"'); } var totalDigits = digitLeftCount + zeroDigitCount + digitRightCount; this.maximumFractionDigits_ = decimalPos >= 0 ? totalDigits - decimalPos : 0; if (decimalPos >= 0) { this.minimumFractionDigits_ = digitLeftCount + zeroDigitCount - decimalPos; if (this.minimumFractionDigits_ < 0) { this.minimumFractionDigits_ = 0; } } // The effectiveDecimalPos is the position the decimal is at or would be at // if there is no decimal. Note that if decimalPos<0, then digitTotalCount == // digitLeftCount + zeroDigitCount. var effectiveDecimalPos = decimalPos >= 0 ? decimalPos : totalDigits; this.minimumIntegerDigits_ = effectiveDecimalPos - digitLeftCount; if (this.useExponentialNotation_) { this.maximumIntegerDigits_ = digitLeftCount + this.minimumIntegerDigits_; // in exponential display, we need to at least show something. if (this.maximumFractionDigits_ == 0 && this.minimumIntegerDigits_ == 0) { this.minimumIntegerDigits_ = 1; } } this.groupingSize_ = Math.max(0, groupingCount); this.decimalSeparatorAlwaysShown_ = decimalPos == 0 || decimalPos == totalDigits; };
import { Platform, Dimensions } from "react-native"; import variable from "./../variables/platform"; const deviceHeight = Dimensions.get("window").height; export default (variables = variable) => { const theme = { flex: 1, height: Platform.OS === "ios" ? deviceHeight : deviceHeight - 20 }; return theme; };
define("rollbar", [], function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(1); /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var rollbar = __webpack_require__(2); var options = window && window._rollbarConfig; var alias = options && options.globalAlias || 'Rollbar'; var shimRunning = window && window[alias] && typeof window[alias].shimId === 'function' && window[alias].shimId() !== undefined; if (window && !window._rollbarStartTime) { window._rollbarStartTime = (new Date()).getTime(); } if (!shimRunning && options) { var Rollbar = new rollbar(options); window[alias] = Rollbar; } else { window.rollbar = rollbar; window._rollbarDidLoad = true; } module.exports = rollbar; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var Client = __webpack_require__(3); var _ = __webpack_require__(6); var API = __webpack_require__(11); var logger = __webpack_require__(13); var globals = __webpack_require__(16); var transport = __webpack_require__(17); var urllib = __webpack_require__(18); var transforms = __webpack_require__(19); var sharedTransforms = __webpack_require__(23); var predicates = __webpack_require__(24); var errorParser = __webpack_require__(20); var Instrumenter = __webpack_require__(25); function Rollbar(options, client) { this.options = _.extend(true, defaultOptions, options); var api = new API(this.options, transport, urllib); this.client = client || new Client(this.options, api, logger, 'browser'); addTransformsToNotifier(this.client.notifier); addPredicatesToQueue(this.client.queue); if (this.options.captureUncaught || this.options.handleUncaughtExceptions) { globals.captureUncaughtExceptions(window, this); globals.wrapGlobals(window, this); } if (this.options.captureUnhandledRejections || this.options.handleUnhandledRejections) { globals.captureUnhandledRejections(window, this); } this.instrumenter = new Instrumenter(this.options, this.client.telemeter, this, window, document); this.instrumenter.instrument(); } var _instance = null; Rollbar.init = function(options, client) { if (_instance) { return _instance.global(options).configure(options); } _instance = new Rollbar(options, client); return _instance; }; function handleUninitialized(maybeCallback) { var message = 'Rollbar is not initialized'; logger.error(message); if (maybeCallback) { maybeCallback(new Error(message)); } } Rollbar.prototype.global = function(options) { this.client.global(options); return this; }; Rollbar.global = function(options) { if (_instance) { return _instance.global(options); } else { handleUninitialized(); } }; Rollbar.prototype.configure = function(options, payloadData) { var oldOptions = this.options; var payload = {}; if (payloadData) { payload = {payload: payloadData}; } this.options = _.extend(true, {}, oldOptions, options, payload); this.client.configure(options, payloadData); this.instrumenter.configure(options); return this; }; Rollbar.configure = function(options, payloadData) { if (_instance) { return _instance.configure(options, payloadData); } else { handleUninitialized(); } }; Rollbar.prototype.lastError = function() { return this.client.lastError; }; Rollbar.lastError = function() { if (_instance) { return _instance.lastError(); } else { handleUninitialized(); } }; Rollbar.prototype.log = function() { var item = this._createItem(arguments); var uuid = item.uuid; this.client.log(item); return {uuid: uuid}; }; Rollbar.log = function() { if (_instance) { return _instance.log.apply(_instance, arguments); } else { var maybeCallback = _getFirstFunction(arguments); handleUninitialized(maybeCallback); } }; Rollbar.prototype.debug = function() { var item = this._createItem(arguments); var uuid = item.uuid; this.client.debug(item); return {uuid: uuid}; }; Rollbar.debug = function() { if (_instance) { return _instance.debug.apply(_instance, arguments); } else { var maybeCallback = _getFirstFunction(arguments); handleUninitialized(maybeCallback); } }; Rollbar.prototype.info = function() { var item = this._createItem(arguments); var uuid = item.uuid; this.client.info(item); return {uuid: uuid}; }; Rollbar.info = function() { if (_instance) { return _instance.info.apply(_instance, arguments); } else { var maybeCallback = _getFirstFunction(arguments); handleUninitialized(maybeCallback); } }; Rollbar.prototype.warn = function() { var item = this._createItem(arguments); var uuid = item.uuid; this.client.warn(item); return {uuid: uuid}; }; Rollbar.warn = function() { if (_instance) { return _instance.warn.apply(_instance, arguments); } else { var maybeCallback = _getFirstFunction(arguments); handleUninitialized(maybeCallback); } }; Rollbar.prototype.warning = function() { var item = this._createItem(arguments); var uuid = item.uuid; this.client.warning(item); return {uuid: uuid}; }; Rollbar.warning = function() { if (_instance) { return _instance.warning.apply(_instance, arguments); } else { var maybeCallback = _getFirstFunction(arguments); handleUninitialized(maybeCallback); } }; Rollbar.prototype.error = function() { var item = this._createItem(arguments); var uuid = item.uuid; this.client.error(item); return {uuid: uuid}; }; Rollbar.error = function() { if (_instance) { return _instance.error.apply(_instance, arguments); } else { var maybeCallback = _getFirstFunction(arguments); handleUninitialized(maybeCallback); } }; Rollbar.prototype.critical = function() { var item = this._createItem(arguments); var uuid = item.uuid; this.client.critical(item); return {uuid: uuid}; }; Rollbar.critical = function() { if (_instance) { return _instance.critical.apply(_instance, arguments); } else { var maybeCallback = _getFirstFunction(arguments); handleUninitialized(maybeCallback); } }; Rollbar.prototype.handleUncaughtException = function(message, url, lineno, colno, error, context) { var item; var stackInfo = _.makeUnhandledStackInfo( message, url, lineno, colno, error, 'onerror', 'uncaught exception', errorParser ); if (_.isError(error)) { item = this._createItem([message, error, context]); item._unhandledStackInfo = stackInfo; } else if (_.isError(url)) { item = this._createItem([message, url, context]); item._unhandledStackInfo = stackInfo; } else { item = this._createItem([message, context]); item.stackInfo = stackInfo; } item.level = this.options.uncaughtErrorLevel; item._isUncaught = true; this.client.log(item); }; Rollbar.prototype.handleUnhandledRejection = function(reason, promise) { var message = 'unhandled rejection was null or undefined!'; message = reason ? (reason.message || String(reason)) : message; var context = (reason && reason._rollbarContext) || (promise && promise._rollbarContext); var item; if (_.isError(reason)) { item = this._createItem([message, reason, context]); } else { item = this._createItem([message, reason, context]); item.stackInfo = _.makeUnhandledStackInfo( message, '', 0, 0, null, 'unhandledrejection', '', errorParser ); } item.level = this.options.uncaughtErrorLevel; item._isUncaught = true; item._originalArgs = item._originalArgs || []; item._originalArgs.push(promise); this.client.log(item); }; Rollbar.prototype.wrap = function(f, context, _before) { try { var ctxFn; if(_.isFunction(context)) { ctxFn = context; } else { ctxFn = function() { return context || {}; }; } if (!_.isFunction(f)) { return f; } if (f._isWrap) { return f; } if (!f._rollbar_wrapped) { f._rollbar_wrapped = function () { if (_before && _.isFunction(_before)) { _before.apply(this, arguments); } try { return f.apply(this, arguments); } catch(exc) { var e = exc; if (_.isType(e, 'string')) { e = new String(e); } e._rollbarContext = ctxFn() || {}; e._rollbarContext._wrappedSource = f.toString(); window._rollbarWrappedError = e; throw e; } }; f._rollbar_wrapped._isWrap = true; if (f.hasOwnProperty) { for (var prop in f) { if (f.hasOwnProperty(prop)) { f._rollbar_wrapped[prop] = f[prop]; } } } } return f._rollbar_wrapped; } catch (e) { // Return the original function if the wrap fails. return f; } }; Rollbar.wrap = function(f, context) { if (_instance) { return _instance.wrap(f, context); } else { handleUninitialized(); } }; Rollbar.prototype.captureEvent = function(metadata, level) { return this.client.captureEvent(metadata, level); }; Rollbar.captureEvent = function(metadata, level) { if (_instance) { return _instance.captureEvent(metadata, level); } else { handleUninitialized(); } }; // The following two methods are used internally and are not meant for public use Rollbar.prototype.captureDomContentLoaded = function(e, ts) { if (!ts) { ts = new Date(); } return this.client.captureDomContentLoaded(ts); }; Rollbar.prototype.captureLoad = function(e, ts) { if (!ts) { ts = new Date(); } return this.client.captureLoad(ts); }; /* Internal */ function addTransformsToNotifier(notifier) { notifier .addTransform(transforms.handleItemWithError) .addTransform(transforms.ensureItemHasSomethingToSay) .addTransform(transforms.addBaseInfo) .addTransform(transforms.addRequestInfo(window)) .addTransform(transforms.addClientInfo(window)) .addTransform(transforms.addPluginInfo(window)) .addTransform(transforms.addBody) .addTransform(sharedTransforms.addMessageWithError) .addTransform(sharedTransforms.addTelemetryData) .addTransform(transforms.scrubPayload) .addTransform(transforms.userTransform) .addTransform(sharedTransforms.itemToPayload); } function addPredicatesToQueue(queue) { queue .addPredicate(predicates.checkIgnore) .addPredicate(predicates.userCheckIgnore) .addPredicate(predicates.urlIsNotBlacklisted) .addPredicate(predicates.urlIsWhitelisted) .addPredicate(predicates.messageIsIgnored); } Rollbar.prototype._createItem = function(args) { return _.createItem(args, logger, this); }; function _getFirstFunction(args) { for (var i = 0, len = args.length; i < len; ++i) { if (_.isFunction(args[i])) { return args[i]; } } return undefined; } /* global __NOTIFIER_VERSION__:false */ /* global __DEFAULT_BROWSER_SCRUB_FIELDS__:false */ /* global __DEFAULT_LOG_LEVEL__:false */ /* global __DEFAULT_REPORT_LEVEL__:false */ /* global __DEFAULT_UNCAUGHT_ERROR_LEVEL:false */ /* global __DEFAULT_ENDPOINT__:false */ var defaultOptions = { version: ("2.3.1"), scrubFields: (["pw","pass","passwd","password","secret","confirm_password","confirmPassword","password_confirmation","passwordConfirmation","access_token","accessToken","secret_key","secretKey","secretToken"]), logLevel: ("debug"), reportLevel: ("debug"), uncaughtErrorLevel: ("error"), endpoint: ("api.rollbar.com/api/1/item/"), verbose: false, enabled: true }; module.exports = Rollbar; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var RateLimiter = __webpack_require__(4); var Queue = __webpack_require__(5); var Notifier = __webpack_require__(9); var Telemeter = __webpack_require__(10); var _ = __webpack_require__(6); /* * Rollbar - the interface to Rollbar * * @param options * @param api * @param logger */ function Rollbar(options, api, logger, platform) { this.options = _.extend(true, {}, options); this.logger = logger; Rollbar.rateLimiter.configureGlobal(this.options); Rollbar.rateLimiter.setPlatformOptions(platform, this.options); this.queue = new Queue(Rollbar.rateLimiter, api, logger, this.options); this.notifier = new Notifier(this.queue, this.options); this.telemeter = new Telemeter(this.options); this.lastError = null; } var defaultOptions = { maxItems: 0, itemsPerMinute: 60 }; Rollbar.rateLimiter = new RateLimiter(defaultOptions); Rollbar.prototype.global = function(options) { Rollbar.rateLimiter.configureGlobal(options); return this; }; Rollbar.prototype.configure = function(options, payloadData) { this.notifier && this.notifier.configure(options); this.telemeter && this.telemeter.configure(options); var oldOptions = this.options; var payload = {}; if (payloadData) { payload = {payload: payloadData}; } this.options = _.extend(true, {}, oldOptions, options, payload); this.global(this.options); return this; }; Rollbar.prototype.log = function(item) { var level = this._defaultLogLevel(); return this._log(level, item); }; Rollbar.prototype.debug = function(item) { this._log('debug', item); }; Rollbar.prototype.info = function(item) { this._log('info', item); }; Rollbar.prototype.warn = function(item) { this._log('warning', item); }; Rollbar.prototype.warning = function(item) { this._log('warning', item); }; Rollbar.prototype.error = function(item) { this._log('error', item); }; Rollbar.prototype.critical = function(item) { this._log('critical', item); }; Rollbar.prototype.wait = function(callback) { this.queue.wait(callback); }; Rollbar.prototype.captureEvent = function(metadata, level) { return this.telemeter.captureEvent(metadata, level); }; Rollbar.prototype.captureDomContentLoaded = function(ts) { return this.telemeter.captureDomContentLoaded(ts); }; Rollbar.prototype.captureLoad = function(ts) { return this.telemeter.captureLoad(ts); }; /* Internal */ Rollbar.prototype._log = function(defaultLevel, item) { if (this._sameAsLastError(item)) { return; } try { var callback = null; if (item.callback) { callback = item.callback; delete item.callback; } item.level = item.level || defaultLevel; item.telemetryEvents = this.telemeter.copyEvents(); this.telemeter._captureRollbarItem(item); this.notifier.log(item, callback); } catch (e) { this.logger.error(e) } }; Rollbar.prototype._defaultLogLevel = function() { return this.options.logLevel || 'debug'; }; Rollbar.prototype._sameAsLastError = function(item) { if (this.lastError && this.lastError === item.err) { return true; } this.lastError = item.err; return false; }; module.exports = Rollbar; /***/ }), /* 4 */ /***/ (function(module, exports) { 'use strict'; /* * RateLimiter - an object that encapsulates the logic for counting items sent to Rollbar * * @param options - the same options that are accepted by configureGlobal offered as a convenience */ function RateLimiter(options) { this.startTime = (new Date()).getTime(); this.counter = 0; this.perMinCounter = 0; this.platform = null; this.platformOptions = {}; this.configureGlobal(options); } RateLimiter.globalSettings = { startTime: (new Date()).getTime(), maxItems: undefined, itemsPerMinute: undefined }; /* * configureGlobal - set the global rate limiter options * * @param options - Only the following values are recognized: * startTime: a timestamp of the form returned by (new Date()).getTime() * maxItems: the maximum items * itemsPerMinute: the max number of items to send in a given minute */ RateLimiter.prototype.configureGlobal = function(options) { if (options.startTime !== undefined) { RateLimiter.globalSettings.startTime = options.startTime; } if (options.maxItems !== undefined) { RateLimiter.globalSettings.maxItems = options.maxItems; } if (options.itemsPerMinute !== undefined) { RateLimiter.globalSettings.itemsPerMinute = options.itemsPerMinute; } }; /* * shouldSend - determine if we should send a given item based on rate limit settings * * @param item - the item we are about to send * @returns An object with the following structure: * error: (Error|null) * shouldSend: bool * payload: (Object|null) * If shouldSend is false, the item passed as a parameter should not be sent to Rollbar, and * exactly one of error or payload will be non-null. If error is non-null, the returned Error will * describe the situation, but it means that we were already over a rate limit (either globally or * per minute) when this item was checked. If error is null, and therefore payload is non-null, it * means this item put us over the global rate limit and the payload should be sent to Rollbar in * place of the passed in item. */ RateLimiter.prototype.shouldSend = function(item, now) { now = now || (new Date()).getTime(); if (now - this.startTime >= 60000) { this.startTime = now; this.perMinCounter = 0; } var globalRateLimit = RateLimiter.globalSettings.maxItems; var globalRateLimitPerMin = RateLimiter.globalSettings.itemsPerMinute; if (checkRate(item, globalRateLimit, this.counter)) { return shouldSendValue(this.platform, this.platformOptions, globalRateLimit + ' max items reached', false); } else if (checkRate(item, globalRateLimitPerMin, this.perMinCounter)) { return shouldSendValue(this.platform, this.platformOptions, globalRateLimitPerMin + ' items per minute reached', false); } this.counter++; this.perMinCounter++; var shouldSend = !checkRate(item, globalRateLimit, this.counter); shouldSend = shouldSend && !checkRate(item, globalRateLimitPerMin, this.perMinCounter); return shouldSendValue(this.platform, this.platformOptions, null, shouldSend, globalRateLimit); }; RateLimiter.prototype.setPlatformOptions = function(platform, options) { this.platform = platform; this.platformOptions = options; }; /* Helpers */ function checkRate(item, limit, counter) { return !item.ignoreRateLimit && limit >= 1 && counter > limit; } function shouldSendValue(platform, options, error, shouldSend, globalRateLimit) { var payload = null; if (error) { error = new Error(error); } if (!error && !shouldSend) { payload = rateLimitPayload(platform, options, globalRateLimit); } return {error: error, shouldSend: shouldSend, payload: payload}; } function rateLimitPayload(platform, options, globalRateLimit) { var environment = options.environment || (options.payload && options.payload.environment); var item = { body: { message: { body: 'maxItems has been hit. Ignoring errors until reset.', extra: { maxItems: globalRateLimit } } }, language: 'javascript', environment: environment, notifier: { version: (options.notifier && options.notifier.version) || options.version } }; if (platform === 'browser') { item.platform = 'browser'; item.framework = 'browser-js'; item.notifier.name = 'rollbar-browser-js'; } else if (platform === 'server') { item.framework = options.framework || 'node-js'; item.notifier.name = options.notifier.name; } else if (platform === 'react-native') { item.framework = options.framework || 'react-native'; item.notifier.name = options.notifier.name; } return item; } module.exports = RateLimiter; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _ = __webpack_require__(6); /* * Queue - an object which handles which handles a queue of items to be sent to Rollbar. * This object handles rate limiting via a passed in rate limiter, retries based on connection * errors, and filtering of items based on a set of configurable predicates. The communication to * the backend is performed via a given API object. * * @param rateLimiter - An object which conforms to the interface * rateLimiter.shouldSend(item) -> bool * @param api - An object which conforms to the interface * api.postItem(payload, function(err, response)) * @param logger - An object used to log verbose messages if desired * @param options - see Queue.prototype.configure */ function Queue(rateLimiter, api, logger, options) { this.rateLimiter = rateLimiter; this.api = api; this.logger = logger; this.options = options; this.predicates = []; this.pendingItems = []; this.pendingRequests = []; this.retryQueue = []; this.retryHandle = null; this.waitCallback = null; this.waitIntervalID = null; } /* * configure - updates the options this queue uses * * @param options */ Queue.prototype.configure = function(options) { this.api && this.api.configure(options); var oldOptions = this.options; this.options = _.extend(true, {}, oldOptions, options); return this; }; /* * addPredicate - adds a predicate to the end of the list of predicates for this queue * * @param predicate - function(item, options) -> (bool|{err: Error}) * Returning true means that this predicate passes and the item is okay to go on the queue * Returning false means do not add the item to the queue, but it is not an error * Returning {err: Error} means do not add the item to the queue, and the given error explains why * Returning {err: undefined} is equivalent to returning true but don't do that */ Queue.prototype.addPredicate = function(predicate) { if (_.isFunction(predicate)) { this.predicates.push(predicate); } return this; }; Queue.prototype.addPendingItem = function(item) { this.pendingItems.push(item); }; Queue.prototype.removePendingItem = function(item) { var idx = this.pendingItems.indexOf(item); if (idx !== -1) { this.pendingItems.splice(idx, 1); } }; /* * addItem - Send an item to the Rollbar API if all of the predicates are satisfied * * @param item - The payload to send to the backend * @param callback - function(error, repsonse) which will be called with the response from the API * in the case of a success, otherwise response will be null and error will have a value. If both * error and response are null then the item was stopped by a predicate which did not consider this * to be an error condition, but nonetheless did not send the item to the API. * @param originalError - The original error before any transformations that is to be logged if any */ Queue.prototype.addItem = function(item, callback, originalError, originalItem) { if (!callback || !_.isFunction(callback)) { callback = function() { return; }; } var predicateResult = this._applyPredicates(item); if (predicateResult.stop) { this.removePendingItem(originalItem); callback(predicateResult.err); return; } this._maybeLog(item, originalError); this.removePendingItem(originalItem); this.pendingRequests.push(item); try { this._makeApiRequest(item, function(err, resp) { this._dequeuePendingRequest(item); callback(err, resp); }.bind(this)); } catch (e) { this._dequeuePendingRequest(item); callback(e); } }; /* * wait - Stop any further errors from being added to the queue, and get called back when all items * currently processing have finished sending to the backend. * * @param callback - function() called when all pending items have been sent */ Queue.prototype.wait = function(callback) { if (!_.isFunction(callback)) { return; } this.waitCallback = callback; if (this._maybeCallWait()) { return; } if (this.waitIntervalID) { this.waitIntervalID = clearInterval(this.waitIntervalID); } this.waitIntervalID = setInterval(function() { this._maybeCallWait(); }.bind(this), 500); }; /* _applyPredicates - Sequentially applies the predicates that have been added to the queue to the * given item with the currently configured options. * * @param item - An item in the queue * @returns {stop: bool, err: (Error|null)} - stop being true means do not add item to the queue, * the error value should be passed up to a callbak if we are stopping. */ Queue.prototype._applyPredicates = function(item) { var p = null; for (var i = 0, len = this.predicates.length; i < len; i++) { p = this.predicates[i](item, this.options); if (!p || p.err !== undefined) { return {stop: true, err: p.err}; } } return {stop: false, err: null}; }; /* * _makeApiRequest - Send an item to Rollbar, callback when done, if there is an error make an * effort to retry if we are configured to do so. * * @param item - an item ready to send to the backend * @param callback - function(err, response) */ Queue.prototype._makeApiRequest = function(item, callback) { var rateLimitResponse = this.rateLimiter.shouldSend(item); if (rateLimitResponse.shouldSend) { this.api.postItem(item, function(err, resp) { if (err) { this._maybeRetry(err, item, callback); } else { callback(err, resp); } }.bind(this)); } else if (rateLimitResponse.error) { callback(rateLimitResponse.error); } else { this.api.postItem(rateLimitResponse.payload, callback); } }; // These are errors basically mean there is no internet connection var RETRIABLE_ERRORS = ['ECONNRESET', 'ENOTFOUND', 'ESOCKETTIMEDOUT', 'ETIMEDOUT', 'ECONNREFUSED', 'EHOSTUNREACH', 'EPIPE', 'EAI_AGAIN']; /* * _maybeRetry - Given the error returned by the API, decide if we should retry or just callback * with the error. * * @param err - an error returned by the API transport * @param item - the item that was trying to be sent when this error occured * @param callback - function(err, response) */ Queue.prototype._maybeRetry = function(err, item, callback) { var shouldRetry = false; if (this.options.retryInterval) { for (var i = 0, len = RETRIABLE_ERRORS.length; i < len; i++) { if (err.code === RETRIABLE_ERRORS[i]) { shouldRetry = true; break; } } } if (shouldRetry) { this._retryApiRequest(item, callback); } else { callback(err); } }; /* * _retryApiRequest - Add an item and a callback to a queue and possibly start a timer to process * that queue based on the retryInterval in the options for this queue. * * @param item - an item that failed to send due to an error we deem retriable * @param callback - function(err, response) */ Queue.prototype._retryApiRequest = function(item, callback) { this.retryQueue.push({item: item, callback: callback}); if (!this.retryHandle) { this.retryHandle = setInterval(function() { while (this.retryQueue.length) { var retryObject = this.retryQueue.shift(); this._makeApiRequest(retryObject.item, retryObject.callback); } }.bind(this), this.options.retryInterval); } }; /* * _dequeuePendingRequest - Removes the item from the pending request queue, this queue is used to * enable to functionality of providing a callback that clients can pass to `wait` to be notified * when the pending request queue has been emptied. This must be called when the API finishes * processing this item. If a `wait` callback is configured, it is called by this function. * * @param item - the item previously added to the pending request queue */ Queue.prototype._dequeuePendingRequest = function(item) { var idx = this.pendingRequests.indexOf(item); if (idx !== -1) { this.pendingRequests.splice(idx, 1); this._maybeCallWait(); } }; Queue.prototype._maybeLog = function(data, originalError) { if (this.logger && this.options.verbose) { var message = originalError; message = message || _.get(data, 'body.trace.exception.message'); message = message || _.get(data, 'body.trace_chain.0.exception.message'); if (message) { this.logger.error(message); return; } message = _.get(data, 'body.message.body'); if (message) { this.logger.log(message); } } }; Queue.prototype._maybeCallWait = function() { if (_.isFunction(this.waitCallback) && this.pendingItems.length === 0 && this.pendingRequests.length === 0) { if (this.waitIntervalID) { this.waitIntervalID = clearInterval(this.waitIntervalID); } this.waitCallback(); return true; } return false; }; module.exports = Queue; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var extend = __webpack_require__(7); var RollbarJSON = {}; var __initRollbarJSON = false; function setupJSON() { if (__initRollbarJSON) { return; } __initRollbarJSON = true; if (isDefined(JSON)) { if (isNativeFunction(JSON.stringify)) { RollbarJSON.stringify = JSON.stringify; } if (isNativeFunction(JSON.parse)) { RollbarJSON.parse = JSON.parse; } } if (!isFunction(RollbarJSON.stringify) || !isFunction(RollbarJSON.parse)) { var setupCustomJSON = __webpack_require__(8); setupCustomJSON(RollbarJSON); } } setupJSON(); /* * isType - Given a Javascript value and a string, returns true if the type of the value matches the * given string. * * @param x - any value * @param t - a lowercase string containing one of the following type names: * - undefined * - null * - error * - number * - boolean * - string * - symbol * - function * - object * - array * @returns true if x is of type t, otherwise false */ function isType(x, t) { return t === typeName(x); } /* * typeName - Given a Javascript value, returns the type of the object as a string */ function typeName(x) { var name = typeof x; if (name !== 'object') { return name; } if (!x) { return 'null'; } if (x instanceof Error) { return 'error'; } return ({}).toString.call(x).match(/\s([a-zA-Z]+)/)[1].toLowerCase(); } /* isFunction - a convenience function for checking if a value is a function * * @param f - any value * @returns true if f is a function, otherwise false */ function isFunction(f) { return isType(f, 'function'); } /* isNativeFunction - a convenience function for checking if a value is a native JS function * * @param f - any value * @returns true if f is a native JS function, otherwise false */ function isNativeFunction(f) { var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; var funcMatchString = Function.prototype.toString.call(Object.prototype.hasOwnProperty) .replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?'); var reIsNative = RegExp('^' + funcMatchString + '$'); return isObject(f) && reIsNative.test(f); } /* isObject - Checks if the argument is an object * * @param value - any value * @returns true is value is an object function is an object) */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } /* * isDefined - a convenience function for checking if a value is not equal to undefined * * @param u - any value * @returns true if u is anything other than undefined */ function isDefined(u) { return !isType(u, 'undefined'); } /* * isIterable - convenience function for checking if a value can be iterated, essentially * whether it is an object or an array. * * @param i - any value * @returns true if i is an object or an array as determined by `typeName` */ function isIterable(i) { var type = typeName(i); return (type === 'object' || type === 'array'); } /* * isError - convenience function for checking if a value is of an error type * * @param e - any value * @returns true if e is an error */ function isError(e) { return isType(e, 'error'); } function traverse(obj, func, seen) { var k, v, i; var isObj = isType(obj, 'object'); var isArray = isType(obj, 'array'); var keys = []; if (isObj && seen.indexOf(obj) !== -1) { return obj; } seen.push(obj); if (isObj) { for (k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) { keys.push(k); } } } else if (isArray) { for (i = 0; i < obj.length; ++i) { keys.push(i); } } for (i = 0; i < keys.length; ++i) { k = keys[i]; v = obj[k]; obj[k] = func(k, v, seen); } return obj; } function redact() { return '********'; } // from http://stackoverflow.com/a/8809472/1138191 function uuid4() { var d = now(); var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16); }); return uuid; } var LEVELS = { debug: 0, info: 1, warning: 2, error: 3, critical: 4 }; function sanitizeUrl(url) { var baseUrlParts = parseUri(url); // remove a trailing # if there is no anchor if (baseUrlParts.anchor === '') { baseUrlParts.source = baseUrlParts.source.replace('#', ''); } url = baseUrlParts.source.replace('?' + baseUrlParts.query, ''); return url; } var parseUriOptions = { strictMode: false, key: [ 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor' ], q: { name: 'queryKey', parser: /(?:^|&)([^&=]*)=?([^&]*)/g }, parser: { strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ } }; function parseUri(str) { if (!isType(str, 'string')) { throw new Error('received invalid input'); } var o = parseUriOptions; var m = o.parser[o.strictMode ? 'strict' : 'loose'].exec(str); var uri = {}; var i = o.key.length; while (i--) { uri[o.key[i]] = m[i] || ''; } uri[o.q.name] = {}; uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { if ($1) { uri[o.q.name][$1] = $2; } }); return uri; } function addParamsAndAccessTokenToPath(accessToken, options, params) { params = params || {}; params.access_token = accessToken; var paramsArray = []; var k; for (k in params) { if (Object.prototype.hasOwnProperty.call(params, k)) { paramsArray.push([k, params[k]].join('=')); } } var query = '?' + paramsArray.sort().join('&'); options = options || {}; options.path = options.path || ''; var qs = options.path.indexOf('?'); var h = options.path.indexOf('#'); var p; if (qs !== -1 && (h === -1 || h > qs)) { p = options.path; options.path = p.substring(0,qs) + query + '&' + p.substring(qs+1); } else { if (h !== -1) { p = options.path; options.path = p.substring(0,h) + query + p.substring(h); } else { options.path = options.path + query; } } } function formatUrl(u, protocol) { protocol = protocol || u.protocol; if (!protocol && u.port) { if (u.port === 80) { protocol = 'http:'; } else if (u.port === 443) { protocol = 'https:'; } } protocol = protocol || 'https:'; if (!u.hostname) { return null; } var result = protocol + '//' + u.hostname; if (u.port) { result = result + ':' + u.port; } if (u.path) { result = result + u.path; } return result; } function stringify(obj, backup) { var value, error; try { value = RollbarJSON.stringify(obj); } catch (jsonError) { if (backup && isFunction(backup)) { try { value = backup(obj); } catch (backupError) { error = backupError; } } else { error = jsonError; } } return {error: error, value: value}; } function jsonParse(s) { var value, error; try { value = RollbarJSON.parse(s); } catch (e) { error = e; } return {error: error, value: value}; } function makeUnhandledStackInfo( message, url, lineno, colno, error, mode, backupMessage, errorParser ) { var location = { url: url || '', line: lineno, column: colno }; location.func = errorParser.guessFunctionName(location.url, location.line); location.context = errorParser.gatherContext(location.url, location.line); var href = document && document.location && document.location.href; var useragent = window && window.navigator && window.navigator.userAgent; return { 'mode': mode, 'message': error ? String(error) : (message || backupMessage), 'url': href, 'stack': [location], 'useragent': useragent }; } function wrapCallback(logger, f) { return function(err, resp) { try { f(err, resp); } catch (e) { logger.error(e); } }; } function createItem(args, logger, notifier, requestKeys, lambdaContext) { var message, err, custom, callback, request; var arg; var extraArgs = []; for (var i = 0, l = args.length; i < l; ++i) { arg = args[i]; var typ = typeName(arg); switch (typ) { case 'undefined': break; case 'string': message ? extraArgs.push(arg) : message = arg; break; case 'function': callback = wrapCallback(logger, arg); break; case 'date': extraArgs.push(arg); break; case 'error': case 'domexception': err ? extraArgs.push(arg) : err = arg; break; case 'object': case 'array': if (arg instanceof Error || (typeof DOMException !== 'undefined' && arg instanceof DOMException)) { err ? extraArgs.push(arg) : err = arg; break; } if (requestKeys && typ === 'object' && !request) { for (var j = 0, len = requestKeys.length; j < len; ++j) { if (arg[requestKeys[j]] !== undefined) { request = arg; break; } } if (request) { break; } } custom ? extraArgs.push(arg) : custom = arg; break; default: if (arg instanceof Error || (typeof DOMException !== 'undefined' && arg instanceof DOMException)) { err ? extraArgs.push(arg) : err = arg; break; } extraArgs.push(arg); } } if (extraArgs.length > 0) { // if custom is an array this turns it into an object with integer keys custom = extend(true, {}, custom); custom.extraArgs = extraArgs; } var item = { message: message, err: err, custom: custom, timestamp: now(), callback: callback, uuid: uuid4() }; if (custom && custom.level !== undefined) { item.level = custom.level; delete custom.level; } if (requestKeys && request) { item.request = request; } if (lambdaContext) { item.lambdaContext = lambdaContext; } item._originalArgs = args; return item; } /* * get - given an obj/array and a keypath, return the value at that keypath or * undefined if not possible. * * @param obj - an object or array * @param path - a string of keys separated by '.' such as 'plugin.jquery.0.message' * which would correspond to 42 in `{plugin: {jquery: [{message: 42}]}}` */ function get(obj, path) { if (!obj) { return undefined; } var keys = path.split('.'); var result = obj; try { for (var i = 0, len = keys.length; i < len; ++i) { result = result[keys[i]]; } } catch (e) { result = undefined; } return result; } function set(obj, path, value) { if (!obj) { return; } var keys = path.split('.'); var len = keys.length; if (len < 1) { return; } if (len === 1) { obj[keys[0]] = value; return; } try { var temp = obj[keys[0]] || {}; var replacement = temp; for (var i = 1; i < len-1; i++) { temp[keys[i]] = temp[keys[i]] || {}; temp = temp[keys[i]]; } temp[keys[len-1]] = value; obj[keys[0]] = replacement; } catch (e) { return; } } function scrub(data, scrubFields) { scrubFields = scrubFields || []; var paramRes = _getScrubFieldRegexs(scrubFields); var queryRes = _getScrubQueryParamRegexs(scrubFields); function redactQueryParam(dummy0, paramPart, dummy1, dummy2, dummy3, valPart) { return paramPart + redact(valPart); } function paramScrubber(v) { var i; if (isType(v, 'string')) { for (i = 0; i < queryRes.length; ++i) { v = v.replace(queryRes[i], redactQueryParam); } } return v; } function valScrubber(k, v) { var i; for (i = 0; i < paramRes.length; ++i) { if (paramRes[i].test(k)) { v = redact(v); break; } } return v; } function scrubber(k, v, seen) { var tmpV = valScrubber(k, v); if (tmpV === v) { if (isType(v, 'object') || isType(v, 'array')) { return traverse(v, scrubber, seen); } return paramScrubber(tmpV); } else { return tmpV; } } traverse(data, scrubber, []); return data; } function _getScrubFieldRegexs(scrubFields) { var ret = []; var pat; for (var i = 0; i < scrubFields.length; ++i) { pat = '\\[?(%5[bB])?' + scrubFields[i] + '\\[?(%5[bB])?\\]?(%5[dD])?'; ret.push(new RegExp(pat, 'i')); } return ret; } function _getScrubQueryParamRegexs(scrubFields) { var ret = []; var pat; for (var i = 0; i < scrubFields.length; ++i) { pat = '\\[?(%5[bB])?' + scrubFields[i] + '\\[?(%5[bB])?\\]?(%5[dD])?'; ret.push(new RegExp('(' + pat + '=)([^&\\n]+)', 'igm')); } return ret; } function formatArgsAsString(args) { var i, len, arg; var result = []; for (i = 0, len = args.length; i < len; i++) { arg = args[i]; if (typeof arg === 'object') { arg = stringify(arg); arg = arg.error || arg.value; if (arg.length > 500) arg = arg.substr(0,500)+'...'; } else if (typeof arg === 'undefined') { arg = 'undefined'; } result.push(arg); } return result.join(' '); } function now() { if (Date.now) { return +Date.now(); } return +new Date(); } module.exports = { isType: isType, typeName: typeName, isFunction: isFunction, isNativeFunction: isNativeFunction, isIterable: isIterable, isError: isError, extend: extend, traverse: traverse, redact: redact, uuid4: uuid4, LEVELS: LEVELS, sanitizeUrl: sanitizeUrl, addParamsAndAccessTokenToPath: addParamsAndAccessTokenToPath, formatUrl: formatUrl, stringify: stringify, jsonParse: jsonParse, makeUnhandledStackInfo: makeUnhandledStackInfo, createItem: createItem, get: get, set: set, scrub: scrub, formatArgsAsString: formatArgsAsString, now: now }; /***/ }), /* 7 */ /***/ (function(module, exports) { 'use strict'; var hasOwn = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var isArray = function isArray(arr) { if (typeof Array.isArray === 'function') { return Array.isArray(arr); } return toStr.call(arr) === '[object Array]'; }; var isPlainObject = function isPlainObject(obj) { if (!obj || toStr.call(obj) !== '[object Object]') { return false; } var hasOwnConstructor = hasOwn.call(obj, 'constructor'); var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); // Not own constructor property must be Object if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { 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 typeof key === 'undefined' || hasOwn.call(obj, key); }; module.exports = function extend() { 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; } else if ((typeof target !== 'object' && typeof target !== 'function') || target == null) { target = {}; } for (; i < length; ++i) { options = arguments[i]; // Only deal with non-null/undefined values if (options != null) { // Extend the base object for (name in options) { src = target[name]; copy = options[name]; // Prevent never-ending loop if (target !== copy) { // Recurse if we're merging plain objects or arrays if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { clone = src && isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[name] = extend(deep, clone, copy); // Don't bring in undefined values } else if (typeof copy !== 'undefined') { target[name] = copy; } } } } } // Return the modified object return target; }; /***/ }), /* 8 */ /***/ (function(module, exports) { // json3.js // 2017-02-21 // Public Domain. // NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. // See http://www.JSON.org/js.html // This code should be minified before deployment. // See http://javascript.crockford.com/jsmin.html // USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO // NOT CONTROL. // This file creates a global JSON object containing two methods: stringify // and parse. This file provides the ES5 JSON capability to ES3 systems. // If a project might run on IE8 or earlier, then this file should be included. // This file does nothing on ES5 systems. // JSON.stringify(value, replacer, space) // value any JavaScript value, usually an object or array. // replacer an optional parameter that determines how object // values are stringified for objects. It can be a // function or an array of strings. // space an optional parameter that specifies the indentation // of nested structures. If it is omitted, the text will // be packed without extra whitespace. If it is a number, // it will specify the number of spaces to indent at each // level. If it is a string (such as "\t" or "&nbsp;"), // it contains the characters used to indent at each level. // This method produces a JSON text from a JavaScript value. // When an object value is found, if the object contains a toJSON // method, its toJSON method will be called and the result will be // stringified. A toJSON method does not serialize: it returns the // value represented by the name/value pair that should be serialized, // or undefined if nothing should be serialized. The toJSON method // will be passed the key associated with the value, and this will be // bound to the value. // For example, this would serialize Dates as ISO strings. // Date.prototype.toJSON = function (key) { // function f(n) { // // Format integers to have at least two digits. // return (n < 10) // ? "0" + n // : n; // } // return this.getUTCFullYear() + "-" + // f(this.getUTCMonth() + 1) + "-" + // f(this.getUTCDate()) + "T" + // f(this.getUTCHours()) + ":" + // f(this.getUTCMinutes()) + ":" + // f(this.getUTCSeconds()) + "Z"; // }; // You can provide an optional replacer method. It will be passed the // key and value of each member, with this bound to the containing // object. The value that is returned from your method will be // serialized. If your method returns undefined, then the member will // be excluded from the serialization. // If the replacer parameter is an array of strings, then it will be // used to select the members to be serialized. It filters the results // such that only members with keys listed in the replacer array are // stringified. // Values that do not have JSON representations, such as undefined or // functions, will not be serialized. Such values in objects will be // dropped; in arrays they will be replaced with null. You can use // a replacer function to replace those with JSON values. // JSON.stringify(undefined) returns undefined. // The optional space parameter produces a stringification of the // value that is filled with line breaks and indentation to make it // easier to read. // If the space parameter is a non-empty string, then that string will // be used for indentation. If the space parameter is a number, then // the indentation will be that many spaces. // Example: // text = JSON.stringify(["e", {pluribus: "unum"}]); // // text is '["e",{"pluribus":"unum"}]' // text = JSON.stringify(["e", {pluribus: "unum"}], null, "\t"); // // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' // text = JSON.stringify([new Date()], function (key, value) { // return this[key] instanceof Date // ? "Date(" + this[key] + ")" // : value; // }); // // text is '["Date(---current time---)"]' // JSON.parse(text, reviver) // This method parses a JSON text to produce an object or array. // It can throw a SyntaxError exception. // This has been modified to use JSON-js/json_parse_state.js as the // parser instead of the one built around eval found in JSON-js/json2.js // The optional reviver parameter is a function that can filter and // transform the results. It receives each of the keys and values, // and its return value is used instead of the original value. // If it returns what it received, then the structure is not modified. // If it returns undefined then the member is deleted. // Example: // // Parse the text. Values that look like ISO date strings will // // be converted to Date objects. // myData = JSON.parse(text, function (key, value) { // var a; // if (typeof value === "string") { // a = // /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); // if (a) { // return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], // +a[5], +a[6])); // } // } // return value; // }); // myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { // var d; // if (typeof value === "string" && // value.slice(0, 5) === "Date(" && // value.slice(-1) === ")") { // d = new Date(value.slice(5, -1)); // if (d) { // return d; // } // } // return value; // }); // This is a reference implementation. You are free to copy, modify, or // redistribute. /*jslint for, this */ /*property JSON, apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ var setupCustomJSON = function(JSON) { var rx_one = /^[\],:{}\s]*$/; var rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g; var rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g; var rx_four = /(?:^|:|,)(?:\s*\[)+/g; var rx_escapable = /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; var rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; function f(n) { // Format integers to have at least two digits. return n < 10 ? "0" + n : n; } function this_value() { return this.valueOf(); } 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; }; Boolean.prototype.toJSON = this_value; Number.prototype.toJSON = this_value; String.prototype.toJSON = this_value; } var gap; var indent; var meta; var rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. rx_escapable.lastIndex = 0; return rx_escapable.test(string) ? "\"" + string.replace(rx_escapable, function (a) { var c = meta[a]; return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); }) + "\"" : "\"" + string + "\""; } function str(key, holder) { // Produce a string from holder[key]. var i; // The loop counter. var k; // The member key. var v; // The member value. var length; var mind = gap; var partial; var value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === "object" && typeof value.toJSON === "function") { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === "function") { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case "string": return quote(value); case "number": // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : "null"; case "boolean": case "null": // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce "null". The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is "object", we might be dealing with an object or an array or // null. case "object": // Due to a specification blunder in ECMAScript, typeof null is "object", // so watch out for that case. if (!value) { return "null"; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === "[object Array]") { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || "null"; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? "[]" : gap ? "[\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "]" : "[" + partial.join(",") + "]"; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === "object") { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === "string") { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + ( gap ? ": " : ":" ) + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + ( gap ? ": " : ":" ) + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? "{}" : gap ? "{\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "}" : "{" + partial.join(",") + "}"; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== "function") { meta = { // table of character substitutions "\b": "\\b", "\t": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", "\"": "\\\"", "\\": "\\\\" }; JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ""; indent = ""; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === "number") { for (i = 0; i < space; i += 1) { indent += " "; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === "string") { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== "function" && (typeof replacer !== "object" || typeof replacer.length !== "number")) { throw new Error("JSON.stringify"); } // Make a fake root object containing our value under the key of "". // Return the result of stringifying the value. return str("", {"": value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== "function") { JSON.parse = (function () { // This function creates a JSON parse function that uses a state machine rather // than the dangerous eval function to parse a JSON text. var state; // The state of the parser, one of // 'go' The starting state // 'ok' The final, accepting state // 'firstokey' Ready for the first key of the object or // the closing of an empty object // 'okey' Ready for the next key of the object // 'colon' Ready for the colon // 'ovalue' Ready for the value half of a key/value pair // 'ocomma' Ready for a comma or closing } // 'firstavalue' Ready for the first value of an array or // an empty array // 'avalue' Ready for the next value of an array // 'acomma' Ready for a comma or closing ] var stack; // The stack, for controlling nesting. var container; // The current container object or array var key; // The current key var value; // The current value var escapes = { // Escapement translation table "\\": "\\", "\"": "\"", "/": "/", "t": "\t", "n": "\n", "r": "\r", "f": "\f", "b": "\b" }; var string = { // The actions for string tokens go: function () { state = "ok"; }, firstokey: function () { key = value; state = "colon"; }, okey: function () { key = value; state = "colon"; }, ovalue: function () { state = "ocomma"; }, firstavalue: function () { state = "acomma"; }, avalue: function () { state = "acomma"; } }; var number = { // The actions for number tokens go: function () { state = "ok"; }, ovalue: function () { state = "ocomma"; }, firstavalue: function () { state = "acomma"; }, avalue: function () { state = "acomma"; } }; var action = { // The action table describes the behavior of the machine. It contains an // object for each token. Each object contains a method that is called when // a token is matched in a state. An object will lack a method for illegal // states. "{": { go: function () { stack.push({state: "ok"}); container = {}; state = "firstokey"; }, ovalue: function () { stack.push({container: container, state: "ocomma", key: key}); container = {}; state = "firstokey"; }, firstavalue: function () { stack.push({container: container, state: "acomma"}); container = {}; state = "firstokey"; }, avalue: function () { stack.push({container: container, state: "acomma"}); container = {}; state = "firstokey"; } }, "}": { firstokey: function () { var pop = stack.pop(); value = container; container = pop.container; key = pop.key; state = pop.state; }, ocomma: function () { var pop = stack.pop(); container[key] = value; value = container; container = pop.container; key = pop.key; state = pop.state; } }, "[": { go: function () { stack.push({state: "ok"}); container = []; state = "firstavalue"; }, ovalue: function () { stack.push({container: container, state: "ocomma", key: key}); container = []; state = "firstavalue"; }, firstavalue: function () { stack.push({container: container, state: "acomma"}); container = []; state = "firstavalue"; }, avalue: function () { stack.push({container: container, state: "acomma"}); container = []; state = "firstavalue"; } }, "]": { firstavalue: function () { var pop = stack.pop(); value = container; container = pop.container; key = pop.key; state = pop.state; }, acomma: function () { var pop = stack.pop(); container.push(value); value = container; container = pop.container; key = pop.key; state = pop.state; } }, ":": { colon: function () { if (Object.hasOwnProperty.call(container, key)) { throw new SyntaxError("Duplicate key '" + key + "\""); } state = "ovalue"; } }, ",": { ocomma: function () { container[key] = value; state = "okey"; }, acomma: function () { container.push(value); state = "avalue"; } }, "true": { go: function () { value = true; state = "ok"; }, ovalue: function () { value = true; state = "ocomma"; }, firstavalue: function () { value = true; state = "acomma"; }, avalue: function () { value = true; state = "acomma"; } }, "false": { go: function () { value = false; state = "ok"; }, ovalue: function () { value = false; state = "ocomma"; }, firstavalue: function () { value = false; state = "acomma"; }, avalue: function () { value = false; state = "acomma"; } }, "null": { go: function () { value = null; state = "ok"; }, ovalue: function () { value = null; state = "ocomma"; }, firstavalue: function () { value = null; state = "acomma"; }, avalue: function () { value = null; state = "acomma"; } } }; function debackslashify(text) { // Remove and replace any backslash escapement. return text.replace(/\\(?:u(.{4})|([^u]))/g, function (ignore, b, c) { return b ? String.fromCharCode(parseInt(b, 16)) : escapes[c]; }); } return function (source, reviver) { // A regular expression is used to extract tokens from the JSON text. // The extraction process is cautious. var result; var tx = /^[\u0020\t\n\r]*(?:([,:\[\]{}]|true|false|null)|(-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)|"((?:[^\r\n\t\\\"]|\\(?:["\\\/trnfb]|u[0-9a-fA-F]{4}))*)")/; // Set the starting state. state = "go"; // The stack records the container, key, and state for each object or array // that contains another object or array while processing nested structures. stack = []; // If any error occurs, we will catch it and ultimately throw a syntax error. try { // For each token... while (true) { result = tx.exec(source); if (!result) { break; } // result is the result array from matching the tokenizing regular expression. // result[0] contains everything that matched, including any initial whitespace. // result[1] contains any punctuation that was matched, or true, false, or null. // result[2] contains a matched number, still in string form. // result[3] contains a matched string, without quotes but with escapement. if (result[1]) { // Token: Execute the action for this state and token. action[result[1]][state](); } else if (result[2]) { // Number token: Convert the number string into a number value and execute // the action for this state and number. value = +result[2]; number[state](); } else { // String token: Replace the escapement sequences and execute the action for // this state and string. value = debackslashify(result[3]); string[state](); } // Remove the token from the string. The loop will continue as long as there // are tokens. This is a slow process, but it allows the use of ^ matching, // which assures that no illegal tokens slip through. source = source.slice(result[0].length); } // If we find a state/token combination that is illegal, then the action will // cause an error. We handle the error by simply changing the state. } catch (e) { state = e; } // The parsing is finished. If we are not in the final "ok" state, or if the // remaining source contains anything except whitespace, then we did not have //a well-formed JSON text. if (state !== "ok" || (/[^\u0020\t\n\r]/.test(source))) { throw (state instanceof SyntaxError) ? state : new SyntaxError("JSON"); } // If there is a reviver function, we recursively walk the new structure, // passing each name/value pair to the reviver function for possible // transformation, starting with a temporary root object that holds the current // value in an empty key. If there is not a reviver function, we simply return // that value. return (typeof reviver === "function") ? (function walk(holder, key) { var k; var v; var val = holder[key]; if (val && typeof val === "object") { for (k in value) { if (Object.prototype.hasOwnProperty.call(val, k)) { v = walk(val, k); if (v !== undefined) { val[k] = v; } else { delete val[k]; } } } } return reviver.call(holder, key, val); }({"": value}, "")) : value; }; }()); } } module.exports = setupCustomJSON; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _ = __webpack_require__(6); /* * Notifier - the internal object responsible for delegating between the client exposed API, the * chain of transforms necessary to turn an item into something that can be sent to Rollbar, and the * queue which handles the communcation with the Rollbar API servers. * * @param queue - an object that conforms to the interface: addItem(item, callback) * @param options - an object representing the options to be set for this notifier, this should have * any defaults already set by the caller */ function Notifier(queue, options) { this.queue = queue; this.options = options; this.transforms = []; } /* * configure - updates the options for this notifier with the passed in object * * @param options - an object which gets merged with the current options set on this notifier * @returns this */ Notifier.prototype.configure = function(options) { this.queue && this.queue.configure(options); var oldOptions = this.options; this.options = _.extend(true, {}, oldOptions, options); return this; }; /* * addTransform - adds a transform onto the end of the queue of transforms for this notifier * * @param transform - a function which takes three arguments: * * item: An Object representing the data to eventually be sent to Rollbar * * options: The current value of the options for this notifier * * callback: function(err: (Null|Error), item: (Null|Object)) the transform must call this * callback with a null value for error if it wants the processing chain to continue, otherwise * with an error to terminate the processing. The item should be the updated item after this * transform is finished modifying it. */ Notifier.prototype.addTransform = function(transform) { if (_.isFunction(transform)) { this.transforms.push(transform); } return this; }; /* * log - the internal log function which applies the configured transforms and then pushes onto the * queue to be sent to the backend. * * @param item - An object with the following structure: * message [String] - An optional string to be sent to rollbar * error [Error] - An optional error * * @param callback - A function of type function(err, resp) which will be called with exactly one * null argument and one non-null argument. The callback will be called once, either during the * transform stage if an error occurs inside a transform, or in response to the communication with * the backend. The second argument will be the response from the backend in case of success. */ Notifier.prototype.log = function(item, callback) { if (!callback || !_.isFunction(callback)) { callback = function() {}; } if (!this.options.enabled) { return callback(new Error('Rollbar is not enabled')); } this.queue.addPendingItem(item); var originalError = item.err; this._applyTransforms(item, function(err, i) { if (err) { this.queue.removePendingItem(item); return callback(err, null); } this.queue.addItem(i, callback, originalError, item); }.bind(this)); }; /* Internal */ /* * _applyTransforms - Applies the transforms that have been added to this notifier sequentially. See * `addTransform` for more information. * * @param item - An item to be transformed * @param callback - A function of type function(err, item) which will be called with a non-null * error and a null item in the case of a transform failure, or a null error and non-null item after * all transforms have been applied. */ Notifier.prototype._applyTransforms = function(item, callback) { var transformIndex = -1; var transformsLength = this.transforms.length; var transforms = this.transforms; var options = this.options; var cb = function(err, i) { if (err) { callback(err, null); return; } transformIndex++; if (transformIndex === transformsLength) { callback(null, i); return; } transforms[transformIndex](i, options, cb); }; cb(null, item); }; module.exports = Notifier; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _ = __webpack_require__(6); var MAX_EVENTS = 100; function Telemeter(options) { this.queue = []; this.options = _.extend(true, {}, options); var maxTelemetryEvents = this.options.maxTelemetryEvents || MAX_EVENTS; this.maxQueueSize = Math.max(0, Math.min(maxTelemetryEvents, MAX_EVENTS)); } Telemeter.prototype.configure = function(options) { var oldOptions = this.options; this.options = _.extend(true, {}, oldOptions, options); var maxTelemetryEvents = this.options.maxTelemetryEvents || MAX_EVENTS; var newMaxEvents = Math.max(0, Math.min(maxTelemetryEvents, MAX_EVENTS)); var deleteCount = 0; if (this.maxQueueSize > newMaxEvents) { deleteCount = this.maxQueueSize - newMaxEvents; } this.maxQueueSize = newMaxEvents; this.queue.splice(0, deleteCount); }; Telemeter.prototype.copyEvents = function() { return Array.prototype.slice.call(this.queue, 0); }; Telemeter.prototype.capture = function(type, metadata, level, rollbarUUID, timestamp) { var e = { level: getLevel(type, level), type: type, timestamp_ms: timestamp || _.now(), body: metadata, source: 'client' }; if (rollbarUUID) { e.uuid = rollbarUUID; } this.push(e); return e; }; Telemeter.prototype.captureEvent = function(metadata, level, rollbarUUID) { return this.capture('manual', metadata, level, rollbarUUID); }; Telemeter.prototype.captureError = function(err, level, rollbarUUID, timestamp) { var metadata = { message: err.message || String(err) }; if (err.stack) { metadata.stack = err.stack; } return this.capture('error', metadata, level, rollbarUUID, timestamp); }; Telemeter.prototype.captureLog = function(message, level, rollbarUUID, timestamp) { return this.capture('log', { message: message }, level, rollbarUUID, timestamp); }; Telemeter.prototype.captureNetwork = function(metadata, subtype, rollbarUUID) { subtype = subtype || 'xhr'; metadata.subtype = metadata.subtype || subtype; var level = this.levelFromStatus(metadata.status_code); return this.capture('network', metadata, level, rollbarUUID); }; Telemeter.prototype.levelFromStatus = function(statusCode) { if (statusCode >= 200 && statusCode < 400) { return 'info'; } if (statusCode === 0 || statusCode >= 400) { return 'error'; } return 'info'; }; Telemeter.prototype.captureDom = function(subtype, element, value, checked, rollbarUUID) { var metadata = { subtype: subtype, element: element }; if (value !== undefined) { metadata.value = value; } if (checked !== undefined) { metadata.checked = checked; } return this.capture('dom', metadata, 'info', rollbarUUID); }; Telemeter.prototype.captureNavigation = function(from, to, rollbarUUID) { return this.capture('navigation', {from: from, to: to}, 'info', rollbarUUID); }; Telemeter.prototype.captureDomContentLoaded = function(ts) { return this.capture('navigation', {subtype: 'DOMContentLoaded'}, 'info', undefined, ts && ts.getTime()); /** * If we decide to make this a dom event instead, then use the line below: return this.capture('dom', {subtype: 'DOMContentLoaded'}, 'info', undefined, ts && ts.getTime()); */ }; Telemeter.prototype.captureLoad = function(ts) { return this.capture('navigation', {subtype: 'load'}, 'info', undefined, ts && ts.getTime()); /** * If we decide to make this a dom event instead, then use the line below: return this.capture('dom', {subtype: 'load'}, 'info', undefined, ts && ts.getTime()); */ }; Telemeter.prototype.captureConnectivityChange = function(type, rollbarUUID) { return this.captureNetwork({change: type}, 'connectivity', rollbarUUID); }; // Only intended to be used internally by the notifier Telemeter.prototype._captureRollbarItem = function(item) { if (item.err) { return this.captureError(item.err, item.level, item.uuid, item.timestamp); } if (item.message) { return this.captureLog(item.message, item.level, item.uuid, item.timestamp); } if (item.custom) { return this.capture('log', item.custom, item.level, item.uuid, item.timestamp); } }; Telemeter.prototype.push = function(e) { this.queue.push(e); if (this.queue.length > this.maxQueueSize) { this.queue.shift(); } }; function getLevel(type, level) { if (level) { return level; } var defaultLevel = { error: 'error', manual: 'info' }; return defaultLevel[type] || 'info'; } module.exports = Telemeter; /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _ = __webpack_require__(6); var helpers = __webpack_require__(12); var defaultOptions = { hostname: 'api.rollbar.com', path: '/api/1/item/', search: null, version: '1', protocol: 'https:', port: 443 }; /** * Api is an object that encapsulates methods of communicating with * the Rollbar API. It is a standard interface with some parts implemented * differently for server or browser contexts. It is an object that should * be instantiated when used so it can contain non-global options that may * be different for another instance of RollbarApi. * * @param options { * accessToken: the accessToken to use for posting items to rollbar * endpoint: an alternative endpoint to send errors to * must be a valid, fully qualified URL. * The default is: https://api.rollbar.com/api/1/item * proxy: if you wish to proxy requests provide an object * with the following keys: * host or hostname (required): foo.example.com * port (optional): 123 * protocol (optional): https * } */ function Api(options, t, u, j) { this.options = options; this.transport = t; this.url = u; this.jsonBackup = j; this.accessToken = options.accessToken; this.transportOptions = _getTransport(options, u); } /** * * @param data * @param callback */ Api.prototype.postItem = function(data, callback) { var transportOptions = helpers.transportOptions(this.transportOptions, 'POST'); var payload = helpers.buildPayload(this.accessToken, data, this.jsonBackup); this.transport.post(this.accessToken, transportOptions, payload, callback); }; Api.prototype.configure = function(options) { var oldOptions = this.oldOptions; this.options = _.extend(true, {}, oldOptions, options); this.transportOptions = _getTransport(this.options, this.url); if (this.options.accessToken !== undefined) { this.accessToken = this.options.accessToken; } return this; }; function _getTransport(options, url) { return helpers.getTransportFromOptions(options, defaultOptions, url); } module.exports = Api; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _ = __webpack_require__(6); function buildPayload(accessToken, data, jsonBackup) { if (_.isType(data.context, 'object')) { var contextResult = _.stringify(data.context, jsonBackup); if (contextResult.error) { data.context = 'Error: could not serialize \'context\''; } else { data.context = contextResult.value || ''; } if (data.context.length > 255) { data.context = data.context.substr(0, 255); } } return { access_token: accessToken, data: data }; } function getTransportFromOptions(options, defaults, url) { var hostname = defaults.hostname; var protocol = defaults.protocol; var port = defaults.port; var path = defaults.path; var search = defaults.search; var proxy = options.proxy; if (options.endpoint) { var opts = url.parse(options.endpoint); hostname = opts.hostname; protocol = opts.protocol; port = opts.port; path = opts.pathname; search = opts.search; } return { hostname: hostname, protocol: protocol, port: port, path: path, search: search, proxy: proxy }; } function transportOptions(transport, method) { var protocol = transport.protocol || 'https:'; var port = transport.port || (protocol === 'http:' ? 80 : protocol === 'https:' ? 443 : undefined); var hostname = transport.hostname; var path = transport.path; if (transport.search) { path = path + transport.search; } if (transport.proxy) { path = protocol + '//' + hostname + path; hostname = transport.proxy.host || transport.proxy.hostname; port = transport.proxy.port; protocol = transport.proxy.protocol || protocol; } return { protocol: protocol, hostname: hostname, path: path, port: port, method: method }; } function appendPathToPath(base, path) { var baseTrailingSlash = /\/$/.test(base); var pathBeginningSlash = /^\//.test(path); if (baseTrailingSlash && pathBeginningSlash) { path = path.substring(1); } else if (!baseTrailingSlash && !pathBeginningSlash) { path = '/' + path; } return base + path; } module.exports = { buildPayload: buildPayload, getTransportFromOptions: getTransportFromOptions, transportOptions: transportOptions, appendPathToPath: appendPathToPath }; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; /* eslint-disable no-console */ __webpack_require__(14); var detection = __webpack_require__(15); var _ = __webpack_require__(6); function error() { var args = Array.prototype.slice.call(arguments, 0); args.unshift('Rollbar:'); if (detection.ieVersion() <= 8) { console.error(_.formatArgsAsString(args)); } else { console.error.apply(console, args); } } function info() { var args = Array.prototype.slice.call(arguments, 0); args.unshift('Rollbar:'); if (detection.ieVersion() <= 8) { console.info(_.formatArgsAsString(args)); } else { console.info.apply(console, args); } } function log() { var args = Array.prototype.slice.call(arguments, 0); args.unshift('Rollbar:'); if (detection.ieVersion() <= 8) { console.log(_.formatArgsAsString(args)); } else { console.log.apply(console, args); } } /* eslint-enable no-console */ module.exports = { error: error, info: info, log: log }; /***/ }), /* 14 */ /***/ (function(module, exports) { // Console-polyfill. MIT license. // https://github.com/paulmillr/console-polyfill // Make it safe to do console.log() always. (function(global) { 'use strict'; if (!global.console) { global.console = {}; } var con = global.console; var prop, method; var dummy = function() {}; var properties = ['memory']; var methods = ('assert,clear,count,debug,dir,dirxml,error,exception,group,' + 'groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,' + 'show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn').split(','); while (prop = properties.pop()) if (!con[prop]) con[prop] = {}; while (method = methods.pop()) if (!con[method]) con[method] = dummy; // Using `this` for web workers & supports Browserify / Webpack. })(typeof window === 'undefined' ? this : window); /***/ }), /* 15 */ /***/ (function(module, exports) { 'use strict'; // This detection.js module is used to encapsulate any ugly browser/feature // detection we may need to do. // Figure out which version of IE we're using, if any. // This is gleaned from http://stackoverflow.com/questions/5574842/best-way-to-check-for-ie-less-than-9-in-javascript-without-library // Will return an integer on IE (i.e. 8) // Will return undefined otherwise function getIEVersion() { var undef; if (!document) { return undef; } var v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i'); while ( div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->', all[0] ); return v > 4 ? v : undef; } var Detection = { ieVersion: getIEVersion }; module.exports = Detection; /***/ }), /* 16 */ /***/ (function(module, exports) { 'use strict'; function captureUncaughtExceptions(window, handler, shim) { if (!window) { return; } var oldOnError; if (typeof handler._rollbarOldOnError === 'function') { oldOnError = handler._rollbarOldOnError; } else if (window.onerror && !window.onerror.belongsToShim) { oldOnError = window.onerror; handler._rollbarOldOnError = oldOnError; } var fn = function() { var args = Array.prototype.slice.call(arguments, 0); _rollbarWindowOnError(window, handler, oldOnError, args); }; fn.belongsToShim = shim; window.onerror = fn; } function _rollbarWindowOnError(window, r, old, args) { if (window._rollbarWrappedError) { if (!args[4]) { args[4] = window._rollbarWrappedError; } if (!args[5]) { args[5] = window._rollbarWrappedError._rollbarContext; } window._rollbarWrappedError = null; } r.handleUncaughtException.apply(r, args); if (old) { old.apply(window, args); } } function captureUnhandledRejections(window, handler, shim) { if (!window) { return; } if (typeof window._rollbarURH === 'function' && window._rollbarURH.belongsToShim) { window.removeEventListener('unhandledrejection', window._rollbarURH); } var rejectionHandler = function (event) { var reason = event.reason; var promise = event.promise; var detail = event.detail; if (!reason && detail) { reason = detail.reason; promise = detail.promise; } if (handler && handler.handleUnhandledRejection) { handler.handleUnhandledRejection(reason, promise); } }; rejectionHandler.belongsToShim = shim; window._rollbarURH = rejectionHandler; window.addEventListener('unhandledrejection', rejectionHandler); } function wrapGlobals(window, handler, shim) { if (!window) { return; } // Adapted from https://github.com/bugsnag/bugsnag-js var globals = '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'.split(','); var i, global; for (i = 0; i < globals.length; ++i) { global = globals[i]; if (window[global] && window[global].prototype) { _extendListenerPrototype(handler, window[global].prototype, shim); } } } function _extendListenerPrototype(handler, prototype, shim) { if (prototype.hasOwnProperty && prototype.hasOwnProperty('addEventListener')) { var oldAddEventListener = prototype.addEventListener; while (oldAddEventListener._rollbarOldAdd && oldAddEventListener.belongsToShim) { oldAddEventListener = oldAddEventListener._rollbarOldAdd; } var addFn = function(event, callback, bubble) { oldAddEventListener.call(this, event, handler.wrap(callback), bubble); }; addFn._rollbarOldAdd = oldAddEventListener; addFn.belongsToShim = shim; prototype.addEventListener = addFn; var oldRemoveEventListener = prototype.removeEventListener; while (oldRemoveEventListener._rollbarOldRemove && oldRemoveEventListener.belongsToShim) { oldRemoveEventListener = oldRemoveEventListener._rollbarOldRemove; } var removeFn = function(event, callback, bubble) { oldRemoveEventListener.call(this, event, callback && callback._rollbar_wrapped || callback, bubble); }; removeFn._rollbarOldRemove = oldRemoveEventListener; removeFn.belongsToShim = shim; prototype.removeEventListener = removeFn; } } module.exports = { captureUncaughtExceptions: captureUncaughtExceptions, captureUnhandledRejections: captureUnhandledRejections, wrapGlobals: wrapGlobals }; /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _ = __webpack_require__(6); var logger = __webpack_require__(13); /* * accessToken may be embedded in payload but that should not * be assumed * * options: { * hostname * protocol * path * port * method * } * * params is an object containing key/value pairs. These * will be appended to the path as 'key=value&key=value' * * payload is an unserialized object */ function get(accessToken, options, params, callback, requestFactory) { if (!callback || !_.isFunction(callback)) { callback = function() {}; } _.addParamsAndAccessTokenToPath(accessToken, options, params); var method = 'GET'; var url = _.formatUrl(options); _makeRequest(accessToken, url, method, null, callback, requestFactory); } function post(accessToken, options, payload, callback, requestFactory) { if (!callback || !_.isFunction(callback)) { callback = function() {}; } if (!payload) { return callback(new Error('Cannot send empty request')); } var stringifyResult = _.stringify(payload); if (stringifyResult.error) { return callback(stringifyResult.error); } var writeData = stringifyResult.value; var method = 'POST'; var url = _.formatUrl(options); _makeRequest(accessToken, url, method, writeData, callback, requestFactory); } function _makeRequest(accessToken, url, method, data, callback, requestFactory) { var request; if (requestFactory) { request = requestFactory(); } else { request = _createXMLHTTPObject(); } if (!request) { // Give up, no way to send requests return callback(new Error('No way to send a request')); } try { try { var onreadystatechange = function() { try { if (onreadystatechange && request.readyState === 4) { onreadystatechange = undefined; var parseResponse = _.jsonParse(request.responseText); if (_isSuccess(request)) { callback(parseResponse.error, parseResponse.value); return; } else if (_isNormalFailure(request)) { if (request.status === 403) { // likely caused by using a server access token var message = parseResponse.value && parseResponse.value.message; logger.error(message); } // return valid http status codes callback(new Error(String(request.status))); } else { // IE will return a status 12000+ on some sort of connection failure, // so we return a blank error // http://msdn.microsoft.com/en-us/library/aa383770%28VS.85%29.aspx var msg = 'XHR response had no status code (likely connection failure)'; callback(_newRetriableError(msg)); } } } catch (ex) { //jquery source mentions firefox may error out while accessing the //request members if there is a network error //https://github.com/jquery/jquery/blob/a938d7b1282fc0e5c52502c225ae8f0cef219f0a/src/ajax/xhr.js#L111 var exc; if (ex && ex.stack) { exc = ex; } else { exc = new Error(ex); } callback(exc); } }; request.open(method, url, true); if (request.setRequestHeader) { request.setRequestHeader('Content-Type', 'application/json'); request.setRequestHeader('X-Rollbar-Access-Token', accessToken); } request.onreadystatechange = onreadystatechange; request.send(data); } catch (e1) { // Sending using the normal xmlhttprequest object didn't work, try XDomainRequest if (typeof XDomainRequest !== 'undefined') { // Assume we are in a really old browser which has a bunch of limitations: // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx // Extreme paranoia: if we have XDomainRequest then we have a window, but just in case if (!window || !window.location) { return callback(new Error('No window available during request, unknown environment')); } // If the current page is http, try and send over http if (window.location.href.substring(0, 5) === 'http:' && url.substring(0, 5) === 'https') { url = 'http' + url.substring(5); } var xdomainrequest = new XDomainRequest(); xdomainrequest.onprogress = function() {}; xdomainrequest.ontimeout = function() { var msg = 'Request timed out'; var code = 'ETIMEDOUT'; callback(_newRetriableError(msg, code)); }; xdomainrequest.onerror = function() { callback(new Error('Error during request')); }; xdomainrequest.onload = function() { var parseResponse = _.jsonParse(xdomainrequest.responseText); callback(parseResponse.error, parseResponse.value); }; xdomainrequest.open(method, url, true); xdomainrequest.send(data); } else { callback(new Error('Cannot find a method to transport a request')); } } } catch (e2) { callback(e2); } } function _createXMLHTTPObject() { /* global ActiveXObject:false */ var factories = [ function () { return new XMLHttpRequest(); }, function () { return new ActiveXObject('Msxml2.XMLHTTP'); }, function () { return new ActiveXObject('Msxml3.XMLHTTP'); }, function () { return new ActiveXObject('Microsoft.XMLHTTP'); } ]; var xmlhttp; var i; var numFactories = factories.length; for (i = 0; i < numFactories; i++) { /* eslint-disable no-empty */ try { xmlhttp = factories[i](); break; } catch (e) { // pass } /* eslint-enable no-empty */ } return xmlhttp; } function _isSuccess(r) { return r && r.status && r.status === 200; } function _isNormalFailure(r) { return r && _.isType(r.status, 'number') && r.status >= 400 && r.status < 600; } function _newRetriableError(message, code) { var err = new Error(message); err.code = code || 'ENOTFOUND'; return err; } module.exports = { get: get, post: post }; /***/ }), /* 18 */ /***/ (function(module, exports) { 'use strict'; // See https://nodejs.org/docs/latest/api/url.html function parse(url) { var result = { protocol: null, auth: null, host: null, path: null, hash: null, href: url, hostname: null, port: null, pathname: null, search: null, query: null }; var i, last; i = url.indexOf('//'); if (i !== -1) { result.protocol = url.substring(0,i); last = i+2; } else { last = 0; } i = url.indexOf('@', last); if (i !== -1) { result.auth = url.substring(last, i); last = i+1; } i = url.indexOf('/', last); if (i === -1) { i = url.indexOf('?', last); if (i === -1) { i = url.indexOf('#', last); if (i === -1) { result.host = url.substring(last); } else { result.host = url.substring(last, i); result.hash = url.substring(i); } result.hostname = result.host.split(':')[0]; result.port = result.host.split(':')[1]; if (result.port) { result.port = parseInt(result.port, 10); } return result; } else { result.host = url.substring(last, i); result.hostname = result.host.split(':')[0]; result.port = result.host.split(':')[1]; if (result.port) { result.port = parseInt(result.port, 10); } last = i; } } else { result.host = url.substring(last, i); result.hostname = result.host.split(':')[0]; result.port = result.host.split(':')[1]; if (result.port) { result.port = parseInt(result.port, 10); } last = i; } i = url.indexOf('#', last); if (i === -1) { result.path = url.substring(last); } else { result.path = url.substring(last, i); result.hash = url.substring(i); } if (result.path) { var pathParts = result.path.split('?'); result.pathname = pathParts[0]; result.query = pathParts[1]; result.search = result.query ? '?' + result.query : null; } return result; } module.exports = { parse: parse }; /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _ = __webpack_require__(6); var errorParser = __webpack_require__(20); var logger = __webpack_require__(13); function handleItemWithError(item, options, callback) { item.data = item.data || {}; if (item.err) { try { item.stackInfo = item.err._savedStackTrace || errorParser.parse(item.err); } catch (e) /* istanbul ignore next */ { logger.error('Error while parsing the error object.', e); item.message = item.err.message || item.err.description || item.message || String(item.err); delete item.err; } } callback(null, item); } function ensureItemHasSomethingToSay(item, options, callback) { if (!item.message && !item.stackInfo && !item.custom) { callback(new Error('No message, stack info, or custom data'), null); } callback(null, item); } function addBaseInfo(item, options, callback) { var environment = (options.payload && options.payload.environment) || options.environment; item.data = _.extend(true, {}, item.data, { environment: environment, level: item.level, endpoint: options.endpoint, platform: 'browser', framework: 'browser-js', language: 'javascript', server: {}, uuid: item.uuid, notifier: { name: 'rollbar-browser-js', version: options.version } }); callback(null, item); } function addRequestInfo(window) { return function(item, options, callback) { if (!window || !window.location) { return callback(null, item); } _.set(item, 'data.request', { url: window.location.href, query_string: window.location.search, user_ip: '$remote_ip' }); callback(null, item); }; } function addClientInfo(window) { return function(item, options, callback) { if (!window) { return callback(null, item); } _.set(item, 'data.client', { runtime_ms: item.timestamp - window._rollbarStartTime, timestamp: Math.round(item.timestamp / 1000), javascript: { browser: window.navigator.userAgent, language: window.navigator.language, cookie_enabled: window.navigator.cookieEnabled, screen: { width: window.screen.width, height: window.screen.height } } }); callback(null, item); }; } function addPluginInfo(window) { return function(item, options, callback) { if (!window || !window.navigator) { return callback(null, item); } var plugins = []; var navPlugins = window.navigator.plugins || []; var cur; for (var i=0, l=navPlugins.length; i < l; ++i) { cur = navPlugins[i]; plugins.push({name: cur.name, description: cur.description}); } _.set(item, 'data.client.javascript.plugins', plugins); callback(null, item); }; } function addBody(item, options, callback) { if (item.stackInfo) { addBodyTrace(item, options, callback); } else { addBodyMessage(item, options, callback); } } function addBodyMessage(item, options, callback) { var message = item.message; var custom = item.custom; if (!message) { if (custom) { var scrubFields = options.scrubFields; var messageResult = _.stringify(_.scrub(custom, scrubFields)); message = messageResult.error || messageResult.value || ''; } else { message = ''; } } var result = { body: message }; if (custom) { result.extra = _.extend(true, {}, custom); } _.set(item, 'data.body', {message: result}); callback(null, item); } function addBodyTrace(item, options, callback) { var description = item.data.description; var stackInfo = item.stackInfo; var custom = item.custom; var guess = errorParser.guessErrorClass(stackInfo.message); var className = stackInfo.name || guess[0]; var message = guess[1]; var trace = { exception: { 'class': className, message: message } }; if (description) { trace.exception.description = description; } // Transform a TraceKit stackInfo object into a Rollbar trace var stack = stackInfo.stack; if (stack && stack.length === 0 && item._unhandledStackInfo && item._unhandledStackInfo.stack) { stack = item._unhandledStackInfo.stack; } if (stack) { var stackFrame; var frame; var code; var pre; var post; var contextLength; var i, mid; trace.frames = []; for (i = 0; i < stack.length; ++i) { stackFrame = stack[i]; frame = { filename: stackFrame.url ? _.sanitizeUrl(stackFrame.url) : '(unknown)', lineno: stackFrame.line || null, method: (!stackFrame.func || stackFrame.func === '?') ? '[anonymous]' : stackFrame.func, colno: stackFrame.column }; if (frame.method && frame.method.endsWith && frame.method.endsWith('_rollbar_wrapped')) { continue; } code = pre = post = null; contextLength = stackFrame.context ? stackFrame.context.length : 0; if (contextLength) { mid = Math.floor(contextLength / 2); pre = stackFrame.context.slice(0, mid); code = stackFrame.context[mid]; post = stackFrame.context.slice(mid); } if (code) { frame.code = code; } if (pre || post) { frame.context = {}; if (pre && pre.length) { frame.context.pre = pre; } if (post && post.length) { frame.context.post = post; } } if (stackFrame.args) { frame.args = stackFrame.args; } trace.frames.push(frame); } // NOTE(cory): reverse the frames since rollbar.com expects the most recent call last trace.frames.reverse(); if (custom) { trace.extra = _.extend(true, {}, custom); } _.set(item, 'data.body', {trace: trace}); callback(null, item); } else { item.message = className + ': ' + message; addBodyMessage(item, options, callback); } } function scrubPayload(item, options, callback) { var scrubFields = options.scrubFields; _.scrub(item.data, scrubFields); callback(null, item); } function userTransform(item, options, callback) { var newItem = _.extend(true, {}, item); try { if (_.isFunction(options.transform)) { options.transform(newItem.data); } } catch (e) { options.transform = null; logger.error('Error while calling custom transform() function. Removing custom transform().', e); callback(null, item); return; } callback(null, newItem); } module.exports = { handleItemWithError: handleItemWithError, ensureItemHasSomethingToSay: ensureItemHasSomethingToSay, addBaseInfo: addBaseInfo, addRequestInfo: addRequestInfo, addClientInfo: addClientInfo, addPluginInfo: addPluginInfo, addBody: addBody, scrubPayload: scrubPayload, userTransform: userTransform }; /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var ErrorStackParser = __webpack_require__(21); var UNKNOWN_FUNCTION = '?'; var ERR_CLASS_REGEXP = new RegExp('^(([a-zA-Z0-9-_$ ]*): *)?(Uncaught )?([a-zA-Z0-9-_$ ]*): '); function guessFunctionName() { return UNKNOWN_FUNCTION; } function gatherContext() { return null; } function Frame(stackFrame) { var data = {}; data._stackFrame = stackFrame; data.url = stackFrame.fileName; data.line = stackFrame.lineNumber; data.func = stackFrame.functionName; data.column = stackFrame.columnNumber; data.args = stackFrame.args; data.context = gatherContext(data.url, data.line); return data; } function Stack(exception) { function getStack() { var parserStack = []; try { parserStack = ErrorStackParser.parse(exception); } catch(e) { parserStack = []; } var stack = []; for (var i = 0; i < parserStack.length; i++) { stack.push(new Frame(parserStack[i])); } return stack; } return { stack: getStack(), message: exception.message, name: exception.name }; } function parse(e) { return new Stack(e); } function guessErrorClass(errMsg) { if (!errMsg) { return ['Unknown error. There was no error message to display.', '']; } var errClassMatch = errMsg.match(ERR_CLASS_REGEXP); var errClass = '(unknown)'; if (errClassMatch) { errClass = errClassMatch[errClassMatch.length - 1]; errMsg = errMsg.replace((errClassMatch[errClassMatch.length - 2] || '') + errClass + ':', ''); errMsg = errMsg.replace(/(^[\s]+|[\s]+$)/g, ''); } return [errClass, errMsg]; } module.exports = { guessFunctionName: guessFunctionName, guessErrorClass: guessErrorClass, gatherContext: gatherContext, parse: parse, Stack: Stack, Frame: Frame }; /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (root, factory) { 'use strict'; // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers. /* istanbul ignore next */ if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(22)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof exports === 'object') { module.exports = factory(require('stackframe')); } else { root.ErrorStackParser = factory(root.StackFrame); } }(this, function ErrorStackParser(StackFrame) { 'use strict'; var FIREFOX_SAFARI_STACK_REGEXP = /(^|@)\S+\:\d+/; var CHROME_IE_STACK_REGEXP = /^\s*at .*(\S+\:\d+|\(native\))/m; var SAFARI_NATIVE_CODE_REGEXP = /^(eval@)?(\[native code\])?$/; function _map(array, fn, thisArg) { if (typeof Array.prototype.map === 'function') { return array.map(fn, thisArg); } else { var output = new Array(array.length); for (var i = 0; i < array.length; i++) { output[i] = fn.call(thisArg, array[i]); } return output; } } function _filter(array, fn, thisArg) { if (typeof Array.prototype.filter === 'function') { return array.filter(fn, thisArg); } else { var output = []; for (var i = 0; i < array.length; i++) { if (fn.call(thisArg, array[i])) { output.push(array[i]); } } return output; } } return { /** * Given an Error object, extract the most information from it. * @param error {Error} * @return Array[StackFrame] */ parse: function ErrorStackParser$$parse(error) { if (typeof error.stacktrace !== 'undefined' || typeof error['opera#sourceloc'] !== 'undefined') { return this.parseOpera(error); } else if (error.stack && error.stack.match(CHROME_IE_STACK_REGEXP)) { return this.parseV8OrIE(error); } else if (error.stack) { return this.parseFFOrSafari(error); } else { throw new Error('Cannot parse given Error object'); } }, /** * Separate line and column numbers from a URL-like string. * @param urlLike String * @return Array[String] */ extractLocation: function ErrorStackParser$$extractLocation(urlLike) { // Fail-fast but return locations like "(native)" if (urlLike.indexOf(':') === -1) { return [urlLike]; } var locationParts = urlLike.replace(/[\(\)\s]/g, '').split(':'); var lastNumber = locationParts.pop(); var possibleNumber = locationParts[locationParts.length - 1]; if (!isNaN(parseFloat(possibleNumber)) && isFinite(possibleNumber)) { var lineNumber = locationParts.pop(); return [locationParts.join(':'), lineNumber, lastNumber]; } else { return [locationParts.join(':'), lastNumber, undefined]; } }, parseV8OrIE: function ErrorStackParser$$parseV8OrIE(error) { var filtered = _filter(error.stack.split('\n'), function (line) { return !!line.match(CHROME_IE_STACK_REGEXP); }, this); return _map(filtered, function (line) { if (line.indexOf('(eval ') > -1) { // Throw away eval information until we implement stacktrace.js/stackframe#8 line = line.replace(/eval code/g, 'eval').replace(/(\(eval at [^\()]*)|(\)\,.*$)/g, ''); } var tokens = line.replace(/^\s+/, '').replace(/\(eval code/g, '(').split(/\s+/).slice(1); var locationParts = this.extractLocation(tokens.pop()); var functionName = tokens.join(' ') || undefined; var fileName = locationParts[0] === 'eval' ? undefined : locationParts[0]; return new StackFrame(functionName, undefined, fileName, locationParts[1], locationParts[2], line); }, this); }, parseFFOrSafari: function ErrorStackParser$$parseFFOrSafari(error) { var filtered = _filter(error.stack.split('\n'), function (line) { return !line.match(SAFARI_NATIVE_CODE_REGEXP); }, this); return _map(filtered, function (line) { // Throw away eval information until we implement stacktrace.js/stackframe#8 if (line.indexOf(' > eval') > -1) { line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval\:\d+\:\d+/g, ':$1'); } if (line.indexOf('@') === -1 && line.indexOf(':') === -1) { // Safari eval frames only have function names and nothing else return new StackFrame(line); } else { var tokens = line.split('@'); var locationParts = this.extractLocation(tokens.pop()); var functionName = tokens.shift() || undefined; return new StackFrame(functionName, undefined, locationParts[0], locationParts[1], locationParts[2], line); } }, this); }, parseOpera: function ErrorStackParser$$parseOpera(e) { if (!e.stacktrace || (e.message.indexOf('\n') > -1 && e.message.split('\n').length > e.stacktrace.split('\n').length)) { return this.parseOpera9(e); } else if (!e.stack) { return this.parseOpera10(e); } else { return this.parseOpera11(e); } }, parseOpera9: function ErrorStackParser$$parseOpera9(e) { var lineRE = /Line (\d+).*script (?:in )?(\S+)/i; var lines = e.message.split('\n'); var result = []; for (var i = 2, len = lines.length; i < len; i += 2) { var match = lineRE.exec(lines[i]); if (match) { result.push(new StackFrame(undefined, undefined, match[2], match[1], undefined, lines[i])); } } return result; }, parseOpera10: function ErrorStackParser$$parseOpera10(e) { var lineRE = /Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i; var lines = e.stacktrace.split('\n'); var result = []; for (var i = 0, len = lines.length; i < len; i += 2) { var match = lineRE.exec(lines[i]); if (match) { result.push(new StackFrame(match[3] || undefined, undefined, match[2], match[1], undefined, lines[i])); } } return result; }, // Opera 10.65+ Error.stack very similar to FF/Safari parseOpera11: function ErrorStackParser$$parseOpera11(error) { var filtered = _filter(error.stack.split('\n'), function (line) { return !!line.match(FIREFOX_SAFARI_STACK_REGEXP) && !line.match(/^Error created at/); }, this); return _map(filtered, function (line) { var tokens = line.split('@'); var locationParts = this.extractLocation(tokens.pop()); var functionCall = (tokens.shift() || ''); var functionName = functionCall .replace(/<anonymous function(: (\w+))?>/, '$2') .replace(/\([^\)]*\)/g, '') || undefined; var argsRaw; if (functionCall.match(/\(([^\)]*)\)/)) { argsRaw = functionCall.replace(/^[^\(]+\(([^\)]*)\)$/, '$1'); } var args = (argsRaw === undefined || argsRaw === '[arguments not available]') ? undefined : argsRaw.split(','); return new StackFrame(functionName, args, locationParts[0], locationParts[1], locationParts[2], line); }, this); } }; })); /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (root, factory) { 'use strict'; // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers. /* istanbul ignore next */ if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof exports === 'object') { module.exports = factory(); } else { root.StackFrame = factory(); } }(this, function () { 'use strict'; function _isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } function StackFrame(functionName, args, fileName, lineNumber, columnNumber, source) { if (functionName !== undefined) { this.setFunctionName(functionName); } if (args !== undefined) { this.setArgs(args); } if (fileName !== undefined) { this.setFileName(fileName); } if (lineNumber !== undefined) { this.setLineNumber(lineNumber); } if (columnNumber !== undefined) { this.setColumnNumber(columnNumber); } if (source !== undefined) { this.setSource(source); } } StackFrame.prototype = { getFunctionName: function () { return this.functionName; }, setFunctionName: function (v) { this.functionName = String(v); }, getArgs: function () { return this.args; }, setArgs: function (v) { if (Object.prototype.toString.call(v) !== '[object Array]') { throw new TypeError('Args must be an Array'); } this.args = v; }, // NOTE: Property name may be misleading as it includes the path, // but it somewhat mirrors V8's JavaScriptStackTraceApi // https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi and Gecko's // http://mxr.mozilla.org/mozilla-central/source/xpcom/base/nsIException.idl#14 getFileName: function () { return this.fileName; }, setFileName: function (v) { this.fileName = String(v); }, getLineNumber: function () { return this.lineNumber; }, setLineNumber: function (v) { if (!_isNumber(v)) { throw new TypeError('Line Number must be a Number'); } this.lineNumber = Number(v); }, getColumnNumber: function () { return this.columnNumber; }, setColumnNumber: function (v) { if (!_isNumber(v)) { throw new TypeError('Column Number must be a Number'); } this.columnNumber = Number(v); }, getSource: function () { return this.source; }, setSource: function (v) { this.source = String(v); }, toString: function() { var functionName = this.getFunctionName() || '{anonymous}'; var args = '(' + (this.getArgs() || []).join(',') + ')'; var fileName = this.getFileName() ? ('@' + this.getFileName()) : ''; var lineNumber = _isNumber(this.getLineNumber()) ? (':' + this.getLineNumber()) : ''; var columnNumber = _isNumber(this.getColumnNumber()) ? (':' + this.getColumnNumber()) : ''; return functionName + args + fileName + lineNumber + columnNumber; } }; return StackFrame; })); /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _ = __webpack_require__(6); function itemToPayload(item, options, callback) { var payloadOptions = options.payload || {}; if (payloadOptions.body) { delete payloadOptions.body; } var data = _.extend(true, {}, item.data, payloadOptions); if (item._isUncaught) { data._isUncaught = true; } if (item._originalArgs) { data._originalArgs = item._originalArgs; } callback(null, data); } function addTelemetryData(item, options, callback) { if (item.telemetryEvents) { _.set(item, 'data.body.telemetry', item.telemetryEvents); } callback(null, item); } function addMessageWithError(item, options, callback) { if (!item.message) { callback(null, item); return; } var tracePath = 'data.body.trace_chain.0'; var trace = _.get(item, tracePath); if (!trace) { tracePath = 'data.body.trace'; trace = _.get(item, tracePath); } if (trace) { if (!(trace.exception && trace.exception.description)) { _.set(item, tracePath+'.exception.description', item.message); callback(null, item); return; } var extra = _.get(item, tracePath+'.extra') || {}; var newExtra = _.extend(true, {}, extra, {message: item.message}); _.set(item, tracePath+'.extra', newExtra); } callback(null, item); } module.exports = { itemToPayload: itemToPayload, addTelemetryData: addTelemetryData, addMessageWithError: addMessageWithError }; /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _ = __webpack_require__(6); var logger = __webpack_require__(13); function checkIgnore(item, settings) { var level = item.level; var levelVal = _.LEVELS[level] || 0; var reportLevel = _.LEVELS[settings.reportLevel] || 0; if (levelVal < reportLevel) { return false; } if (_.get(settings, 'plugins.jquery.ignoreAjaxErrors')) { return !_.get(item, 'body.message.extra.isAjax'); } return true; } function userCheckIgnore(item, settings) { var isUncaught = !!item._isUncaught; delete item._isUncaught; var args = item._originalArgs; delete item._originalArgs; try { if (_.isFunction(settings.checkIgnore) && settings.checkIgnore(isUncaught, args, item)) { return false; } } catch (e) { settings.checkIgnore = null; logger.error('Error while calling custom checkIgnore(), removing', e); } return true; } function urlIsNotBlacklisted(item, settings) { return !urlIsOnAList(item, settings, 'blacklist'); } function urlIsWhitelisted(item, settings) { return urlIsOnAList(item, settings, 'whitelist'); } function urlIsOnAList(item, settings, whiteOrBlack) { // whitelist is the default var black = false; if (whiteOrBlack === 'blacklist') { black = true; } var list, trace, frame, filename, frameLength, url, listLength, urlRegex; var i, j; try { list = black ? settings.hostBlackList : settings.hostWhiteList; listLength = list && list.length; trace = _.get(item, 'body.trace'); // These two checks are important to come first as they are defaults // in case the list is missing or the trace is missing or not well-formed if (!list || listLength === 0) { return !black; } if (!trace || !trace.frames) { return !black; } frameLength = trace.frames.length; for (i = 0; i < frameLength; i++) { frame = trace.frames[i]; filename = frame.filename; if (!_.isType(filename, 'string')) { return !black; } for (j = 0; j < listLength; j++) { url = list[j]; urlRegex = new RegExp(url); if (urlRegex.test(filename)) { return true; } } } } catch (e) /* istanbul ignore next */ { if (black) { settings.hostBlackList = null; } else { settings.hostWhiteList = null; } var listName = black ? 'hostBlackList' : 'hostWhiteList'; logger.error('Error while reading your configuration\'s ' + listName + ' option. Removing custom ' + listName + '.', e); return !black; } return false; } function messageIsIgnored(item, settings) { var exceptionMessage, i, ignoredMessages, len, messageIsIgnored, rIgnoredMessage, body, traceMessage, bodyMessage; try { messageIsIgnored = false; ignoredMessages = settings.ignoredMessages; if (!ignoredMessages || ignoredMessages.length === 0) { return true; } body = item.body; traceMessage = _.get(body, 'trace.exception.message'); bodyMessage = _.get(body, 'message.body'); exceptionMessage = traceMessage || bodyMessage; if (!exceptionMessage){ return true; } len = ignoredMessages.length; for (i = 0; i < len; i++) { rIgnoredMessage = new RegExp(ignoredMessages[i], 'gi'); messageIsIgnored = rIgnoredMessage.test(exceptionMessage); if (messageIsIgnored) { break; } } } catch(e) /* istanbul ignore next */ { settings.ignoredMessages = null; logger.error('Error while reading your configuration\'s ignoredMessages option. Removing custom ignoredMessages.'); } return !messageIsIgnored; } module.exports = { checkIgnore: checkIgnore, userCheckIgnore: userCheckIgnore, urlIsNotBlacklisted: urlIsNotBlacklisted, urlIsWhitelisted: urlIsWhitelisted, messageIsIgnored: messageIsIgnored }; /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _ = __webpack_require__(6); var urlparser = __webpack_require__(18); var domUtil = __webpack_require__(26); var defaults = { network: true, log: true, dom: true, navigation: true, connectivity: true }; function replace(obj, name, replacement, replacements, type) { var orig = obj[name]; obj[name] = replacement(orig); if (replacements) { replacements[type].push([obj, name, orig]); } } function restore(replacements, type) { var b; while (replacements[type].length) { b = replacements[type].shift(); b[0][b[1]] = b[2]; } } function Instrumenter(options, telemeter, rollbar, _window, _document) { var autoInstrument = options.autoInstrument; if (options.enabled === false || autoInstrument === false) { this.autoInstrument = {}; } else { if (!_.isType(autoInstrument, 'object')) { autoInstrument = defaults; } this.autoInstrument = _.extend(true, {}, defaults, autoInstrument); } this.scrubTelemetryInputs = !!options.scrubTelemetryInputs; this.telemetryScrubber = options.telemetryScrubber; this.telemeter = telemeter; this.rollbar = rollbar; this._window = _window || {}; this._document = _document || {}; this.replacements = { network: [], log: [], navigation: [], connectivity: [] }; this.eventRemovers = { dom: [], connectivity: [] }; this._location = this._window.location; this._lastHref = this._location && this._location.href; } Instrumenter.prototype.configure = function(options) { var autoInstrument = options.autoInstrument; var oldSettings = _.extend(true, {}, this.autoInstrument); if (options.enabled === false || autoInstrument === false) { this.autoInstrument = {}; } else { if (!_.isType(autoInstrument, 'object')) { autoInstrument = defaults; } this.autoInstrument = _.extend(true, {}, defaults, autoInstrument); } this.instrument(oldSettings); if (options.scrubTelemetryInputs !== undefined) { this.scrubTelemetryInputs = !!options.scrubTelemetryInputs; } if (options.telemetryScrubber !== undefined) { this.telemetryScrubber = options.telemetryScrubber; } }; Instrumenter.prototype.instrument = function(oldSettings) { if (this.autoInstrument.network && !(oldSettings && oldSettings.network)) { this.instrumentNetwork(); } else if (!this.autoInstrument.network && oldSettings && oldSettings.network) { this.deinstrumentNetwork(); } if (this.autoInstrument.log && !(oldSettings && oldSettings.log)) { this.instrumentConsole(); } else if (!this.autoInstrument.log && oldSettings && oldSettings.log) { this.deinstrumentConsole(); } if (this.autoInstrument.dom && !(oldSettings && oldSettings.dom)) { this.instrumentDom(); } else if (!this.autoInstrument.dom && oldSettings && oldSettings.dom) { this.deinstrumentDom(); } if (this.autoInstrument.navigation && !(oldSettings && oldSettings.navigation)) { this.instrumentNavigation(); } else if (!this.autoInstrument.navigation && oldSettings && oldSettings.navigation) { this.deinstrumentNavigation(); } if (this.autoInstrument.connectivity && !(oldSettings && oldSettings.connectivity)) { this.instrumentConnectivity(); } else if (!this.autoInstrument.connectivity && oldSettings && oldSettings.connectivity) { this.deinstrumentConnectivity(); } }; Instrumenter.prototype.deinstrumentNetwork = function() { restore(this.replacements, 'network'); }; Instrumenter.prototype.instrumentNetwork = function() { var self = this; function wrapProp(prop, xhr) { if (prop in xhr && _.isFunction(xhr[prop])) { replace(xhr, prop, function(orig) { return self.rollbar.wrap(orig); }); } } if ('XMLHttpRequest' in this._window) { var xhrp = this._window.XMLHttpRequest.prototype; replace(xhrp, 'open', function(orig) { return function(method, url) { if (_.isType(url, 'string')) { this.__rollbar_xhr = { method: method, url: url, status_code: null, start_time_ms: _.now(), end_time_ms: null }; } return orig.apply(this, arguments); }; }, this.replacements, 'network'); replace(xhrp, 'send', function(orig) { /* eslint-disable no-unused-vars */ return function(data) { /* eslint-enable no-unused-vars */ var xhr = this; function onreadystatechangeHandler() { if (xhr.__rollbar_xhr && (xhr.readyState === 1 || xhr.readyState === 4)) { if (xhr.__rollbar_xhr.status_code === null) { xhr.__rollbar_xhr.status_code = 0; xhr.__rollbar_event = self.telemeter.captureNetwork(xhr.__rollbar_xhr, 'xhr'); } if (xhr.readyState === 1) { xhr.__rollbar_xhr.start_time_ms = _.now(); } else { xhr.__rollbar_xhr.end_time_ms = _.now(); } try { var code = xhr.status; code = code === 1223 ? 204 : code; xhr.__rollbar_xhr.status_code = code; xhr.__rollbar_event.level = self.telemeter.levelFromStatus(code); } catch (e) { /* ignore possible exception from xhr.status */ } } } wrapProp('onload', xhr); wrapProp('onerror', xhr); wrapProp('onprogress', xhr); if ('onreadystatechange' in xhr && _.isFunction(xhr.onreadystatechange)) { replace(xhr, 'onreadystatechange', function(orig) { return self.rollbar.wrap(orig, undefined, onreadystatechangeHandler); }); } else { xhr.onreadystatechange = onreadystatechangeHandler; } return orig.apply(this, arguments); } }, this.replacements, 'network'); } if ('fetch' in this._window) { replace(this._window, 'fetch', function(orig) { /* eslint-disable no-unused-vars */ return function(fn, t) { /* eslint-enable no-unused-vars */ var args = new Array(arguments.length); for (var i=0, len=args.length; i < len; i++) { args[i] = arguments[i]; } var input = args[0]; var method = 'GET'; var url; if (_.isType(input, 'string')) { url = input; } else { url = input.url; if (input.method) { method = input.method; } } if (args[1] && args[1].method) { method = args[1].method; } var metadata = { method: method, url: url, status_code: null, start_time_ms: _.now(), end_time_ms: null }; self.telemeter.captureNetwork(metadata, 'fetch'); return orig.apply(this, args).then(function (resp) { metadata.end_time_ms = _.now(); metadata.status_code = resp.status; return resp; }); }; }, this.replacements, 'network'); } }; Instrumenter.prototype.deinstrumentConsole = function() { if (!('console' in this._window && this._window.console.log)) { return; } var b; while (this.replacements['log'].length) { b = this.replacements['log'].shift(); this._window.console[b[0]] = b[1]; } }; Instrumenter.prototype.instrumentConsole = function() { if (!('console' in this._window && this._window.console.log)) { return; } var self = this; var c = this._window.console; function wrapConsole(method) { var orig = c[method]; var origConsole = c; var level = method === 'warn' ? 'warning' : method; c[method] = function() { var args = Array.prototype.slice.call(arguments); var message = _.formatArgsAsString(args); self.telemeter.captureLog(message, level); if (orig) { Function.prototype.apply.call(orig, origConsole, args); } }; self.replacements['log'].push([method, orig]); } var methods = ['debug','info','warn','error','log']; for (var i=0, len=methods.length; i < len; i++) { wrapConsole(methods[i]); } }; Instrumenter.prototype.deinstrumentDom = function() { if (!('addEventListener' in this._window || 'attachEvent' in this._window)) { return; } this.removeListeners('dom'); }; Instrumenter.prototype.instrumentDom = function() { if (!('addEventListener' in this._window || 'attachEvent' in this._window)) { return; } var clickHandler = this.handleClick.bind(this); var blurHandler = this.handleBlur.bind(this); this.addListener('dom', this._window, 'click', 'onclick', clickHandler, true); this.addListener('dom', this._window, 'blur', 'onfocusout', blurHandler, true); }; Instrumenter.prototype.handleClick = function(evt) { try { var e = domUtil.getElementFromEvent(evt, this._document); var hasTag = e && e.tagName; var anchorOrButton = domUtil.isDescribedElement(e, 'a') || domUtil.isDescribedElement(e, 'button'); if (hasTag && (anchorOrButton || domUtil.isDescribedElement(e, 'input', ['button', 'submit']))) { this.captureDomEvent('click', e); } else if (domUtil.isDescribedElement(e, 'input', ['checkbox', 'radio'])) { this.captureDomEvent('input', e, e.value, e.checked); } } catch (exc) { // TODO: Not sure what to do here } }; Instrumenter.prototype.handleBlur = function(evt) { try { var e = domUtil.getElementFromEvent(evt, this._document); if (e && e.tagName) { if (domUtil.isDescribedElement(e, 'textarea')) { this.captureDomEvent('input', e, e.value); } else if (domUtil.isDescribedElement(e, 'select') && e.options && e.options.length) { this.handleSelectInputChanged(e); } else if (domUtil.isDescribedElement(e, 'input') && !domUtil.isDescribedElement(e, 'input', ['button', 'submit', 'hidden', 'checkbox', 'radio'])) { this.captureDomEvent('input', e, e.value); } } } catch (exc) { // TODO: Not sure what to do here } }; Instrumenter.prototype.handleSelectInputChanged = function(elem) { if (elem.multiple) { for (var i = 0; i < elem.options.length; i++) { if (elem.options[i].selected) { this.captureDomEvent('input', elem, elem.options[i].value); } } } else if (elem.selectedIndex >= 0 && elem.options[elem.selectedIndex]) { this.captureDomEvent('input', elem, elem.options[elem.selectedIndex].value); } }; Instrumenter.prototype.captureDomEvent = function(subtype, element, value, isChecked) { if (value !== undefined) { if (this.scrubTelemetryInputs || (domUtil.getElementType(element) === 'password')) { value = '[scrubbed]'; } else if (this.telemetryScrubber) { var description = domUtil.describeElement(element); if (this.telemetryScrubber(description)) { value = '[scrubbed]'; } } } var elementString = domUtil.elementArrayToString(domUtil.treeToArray(element)); this.telemeter.captureDom(subtype, elementString, value, isChecked); }; Instrumenter.prototype.deinstrumentNavigation = function() { var chrome = this._window.chrome; var chromePackagedApp = chrome && chrome.app && chrome.app.runtime; // See https://github.com/angular/angular.js/pull/13945/files var hasPushState = !chromePackagedApp && this._window.history && this._window.history.pushState; if (!hasPushState) { return; } restore(this.replacements, 'navigation'); }; Instrumenter.prototype.instrumentNavigation = function() { var chrome = this._window.chrome; var chromePackagedApp = chrome && chrome.app && chrome.app.runtime; // See https://github.com/angular/angular.js/pull/13945/files var hasPushState = !chromePackagedApp && this._window.history && this._window.history.pushState; if (!hasPushState) { return; } var self = this; replace(this._window, 'onpopstate', function(orig) { return function() { var current = self._location.href; self.handleUrlChange(self._lastHref, current); if (orig) { orig.apply(this, arguments); } }; }, this.replacements, 'navigation'); replace(this._window.history, 'pushState', function(orig) { return function() { var url = arguments.length > 2 ? arguments[2] : undefined; if (url) { self.handleUrlChange(self._lastHref, url + ''); } return orig.apply(this, arguments); }; }, this.replacements, 'navigation'); }; Instrumenter.prototype.handleUrlChange = function(from, to) { var parsedHref = urlparser.parse(this._location.href); var parsedTo = urlparser.parse(to); var parsedFrom = urlparser.parse(from); this._lastHref = to; if (parsedHref.protocol === parsedTo.protocol && parsedHref.host === parsedTo.host) { to = parsedTo.path + (parsedTo.hash || ''); } if (parsedHref.protocol === parsedFrom.protocol && parsedHref.host === parsedFrom.host) { from = parsedFrom.path + (parsedFrom.hash || ''); } this.telemeter.captureNavigation(from, to); }; Instrumenter.prototype.deinstrumentConnectivity = function() { if (!('addEventListener' in this._window || 'body' in this._document)) { return; } if (this._window.addEventListener) { this.removeListeners('connectivity'); } else { restore(this.replacements, 'connectivity'); } }; Instrumenter.prototype.instrumentConnectivity = function() { if (!('addEventListener' in this._window || 'body' in this._document)) { return; } if (this._window.addEventListener) { this.addListener('connectivity', this._window, 'online', undefined, function() { this.telemeter.captureConnectivityChange('online'); }.bind(this), true); this.addListener('connectivity', this._window, 'offline', undefined, function() { this.telemeter.captureConnectivityChange('offline'); }.bind(this), true); } else { var self = this; replace(this._document.body, 'ononline', function(orig) { return function() { self.telemeter.captureConnectivityChange('online'); if (orig) { orig.apply(this, arguments); } } }, this.replacements, 'connectivity'); replace(this._document.body, 'onoffline', function(orig) { return function() { self.telemeter.captureConnectivityChange('offline'); if (orig) { orig.apply(this, arguments); } } }, this.replacements, 'connectivity'); } }; Instrumenter.prototype.addListener = function(section, obj, type, altType, handler, capture) { if (obj.addEventListener) { obj.addEventListener(type, handler, capture); this.eventRemovers[section].push(function() { obj.removeEventListener(type, handler, capture); }); } else if (altType) { obj.attachEvent(altType, handler); this.eventRemovers[section].push(function() { obj.detachEvent(altType, handler); }); } }; Instrumenter.prototype.removeListeners = function(section) { var r; while (this.eventRemovers[section].length) { r = this.eventRemovers[section].shift(); r(); } }; module.exports = Instrumenter; /***/ }), /* 26 */ /***/ (function(module, exports) { 'use strict'; function getElementType(e) { return (e.getAttribute('type') || '').toLowerCase(); } function isDescribedElement(element, type, subtypes) { if (element.tagName.toLowerCase() !== type.toLowerCase()) { return false; } if (!subtypes) { return true; } element = getElementType(element); for (var i = 0; i < subtypes.length; i++) { if (subtypes[i] === element) { return true; } } return false; } function getElementFromEvent(evt, doc) { if (evt.target) { return evt.target; } if (doc && doc.elementFromPoint) { return doc.elementFromPoint(evt.clientX, evt.clientY); } return undefined; } function treeToArray(elem) { var MAX_HEIGHT = 5; var out = []; var nextDescription; for (var height = 0; elem && height < MAX_HEIGHT; height++) { nextDescription = describeElement(elem); if (nextDescription.tagName === 'html') { break; } out.unshift(nextDescription); elem = elem.parentNode; } return out; } function elementArrayToString(a) { var MAX_LENGTH = 80; var separator = ' > ', separatorLength = separator.length; var out = [], len = 0, nextStr, totalLength; for (var i = a.length - 1; i >= 0; i--) { nextStr = descriptionToString(a[i]); totalLength = len + (out.length * separatorLength) + nextStr.length; if (i < a.length - 1 && totalLength >= MAX_LENGTH + 3) { out.unshift('...'); break; } out.unshift(nextStr); len += nextStr.length; } return out.join(separator); } function descriptionToString(desc) { if (!desc || !desc.tagName) { return ''; } var out = [desc.tagName]; if (desc.id) { out.push('#' + desc.id); } if (desc.classes) { out.push('.' + desc.classes.join('.')); } for (var i = 0; i < desc.attributes.length; i++) { out.push('[' + desc.attributes[i].key + '="' + desc.attributes[i].value + '"]'); } return out.join(''); } /** * Input: a dom element * Output: null if tagName is falsey or input is falsey, else * { * tagName: String, * id: String | undefined, * classes: [String] | undefined, * attributes: [ * { * key: OneOf(type, name, title, alt), * value: String * } * ] * } */ function describeElement(elem) { if (!elem || !elem.tagName) { return null; } var out = {}, className, key, attr, i; out.tagName = elem.tagName.toLowerCase(); if (elem.id) { out.id = elem.id; } className = elem.className; if (className && (typeof className === 'string')) { out.classes = className.split(/\s+/); } var attributes = ['type', 'name', 'title', 'alt']; out.attributes = []; for (i = 0; i < attributes.length; i++) { key = attributes[i]; attr = elem.getAttribute(key); if (attr) { out.attributes.push({key: key, value: attr}); } } return out; } module.exports = { describeElement: describeElement, descriptionToString: descriptionToString, elementArrayToString: elementArrayToString, treeToArray: treeToArray, getElementFromEvent: getElementFromEvent, isDescribedElement: isDescribedElement, getElementType: getElementType }; /***/ }) /******/ ])});;
var reporter_1 = require('./reporter'); function isTS14(typescript) { return !('findConfigFile' in typescript); } exports.isTS14 = isTS14; function getFileName(thing) { if (thing.filename) return thing.filename; // TS 1.4 return thing.fileName; // TS 1.5 } exports.getFileName = getFileName; function getDiagnosticsAndEmit(program) { var result = reporter_1.emptyCompilationResult(); if (program.getDiagnostics) { var errors = program.getDiagnostics(); result.syntaxErrors = errors.length; if (!errors.length) { // If there are no syntax errors, check types var checker = program.getTypeChecker(true); var semanticErrors = checker.getDiagnostics(); var emitErrors = checker.emitFiles().diagnostics; errors = semanticErrors.concat(emitErrors); result.semanticErrors = errors.length; } else { result.emitSkipped = true; } return [errors, result]; } else { var errors = program.getSyntacticDiagnostics(); result.syntaxErrors = errors.length; if (errors.length === 0) { errors = program.getGlobalDiagnostics(); // Remove error: "File '...' is not under 'rootDir' '...'. 'rootDir' is expected to contain all source files." // This is handled by ICompiler#correctSourceMap, so this error can be muted. errors = errors.filter(function (item) { return item.code !== 6059; }); result.globalErrors = errors.length; } if (errors.length === 0) { errors = program.getSemanticDiagnostics(); result.semanticErrors = errors.length; } var emitOutput = program.emit(); result.emitErrors = emitOutput.diagnostics.length; result.emitSkipped = emitOutput.emitSkipped; return [errors.concat(emitOutput.diagnostics), result]; } } exports.getDiagnosticsAndEmit = getDiagnosticsAndEmit; function getLineAndCharacterOfPosition(typescript, file, position) { if (file.getLineAndCharacterOfPosition) { var lineAndCharacter = file.getLineAndCharacterOfPosition(position); return { line: lineAndCharacter.line + 1, character: lineAndCharacter.character + 1 }; } else { return file.getLineAndCharacterFromPosition(position); } } exports.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition; function createSourceFile(typescript, fileName, content, target, version) { if (version === void 0) { version = '0'; } if (typescript.findConfigFile) { return typescript.createSourceFile(fileName, content, target, true); } else { return typescript.createSourceFile(fileName, content, target, version); } } exports.createSourceFile = createSourceFile; function flattenDiagnosticMessageText(typescript, messageText) { if (typeof messageText === 'string') { return messageText; } else { return typescript.flattenDiagnosticMessageText(messageText, "\n"); } } exports.flattenDiagnosticMessageText = flattenDiagnosticMessageText; function transpile(typescript, input, compilerOptions, fileName, diagnostics) { if (!typescript.transpile) { throw new Error('gulp-typescript: Single file compilation is not supported using TypeScript 1.4'); } return typescript.transpile(input, compilerOptions, fileName, diagnostics); } exports.transpile = transpile;
/** * This class should not be used directly by an application developer. Instead, use * {@link Location}. * * `PlatformLocation` encapsulates all calls to DOM apis, which allows the Router to be platform * agnostic. * This means that we can have different implementation of `PlatformLocation` for the different * platforms * that angular supports. For example, the default `PlatformLocation` is {@link * BrowserPlatformLocation}, * however when you run your app in a WebWorker you use {@link WebWorkerPlatformLocation}. * * The `PlatformLocation` class is used directly by all implementations of {@link LocationStrategy} * when * they need to interact with the DOM apis like pushState, popState, etc... * * {@link LocationStrategy} in turn is used by the {@link Location} service which is used directly * by * the {@link Router} in order to navigate between routes. Since all interactions between {@link * Router} / * {@link Location} / {@link LocationStrategy} and DOM apis flow through the `PlatformLocation` * class * they are all platform independent. */ export class PlatformLocation { /* abstract */ get pathname() { return null; } /* abstract */ get search() { return null; } /* abstract */ get hash() { return null; } }
!function ($) { $(function(){ map = new GMaps({ div: '#gmap_geocoding', lat: 40.0000, lng: -100.0000, zoom: 4 }); map.addMarker({ lat: 40.0000, lng: -100.0000, title: 'Marker', infoWindow: { content: 'Info content here...' } }); $('#geocoding_form').submit(function(e){ e.preventDefault(); GMaps.geocode({ address: $('#address').val().trim(), callback: function(results, status){ if(status=='OK'){ var latlng = results[0].geometry.location; map.setCenter(latlng.lat(), latlng.lng()); map.addMarker({ lat: latlng.lat(), lng: latlng.lng() }); } } }); }); }); }(window.jQuery);
"use strict";var sjcl={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString=function(){return"CORRUPT: "+this.message};this.message=a},invalid:function(a){this.toString=function(){return"INVALID: "+this.message};this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message};this.message=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}}}; "undefined"!==typeof module&&module.exports&&(module.exports=sjcl);"function"===typeof define&&define([],function(){return sjcl}); sjcl.cipher.aes=function(a){this.s[0][0][0]||this.O();var b,c,d,e,g=this.s[0][4],f=this.s[1];b=a.length;var h=1;if(4!==b&&6!==b&&8!==b)throw new sjcl.exception.invalid("invalid aes key size");this.b=[d=a.slice(0),e=[]];for(a=b;a<4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=g[c>>>24]<<24^g[c>>16&255]<<16^g[c>>8&255]<<8^g[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:f[0][g[c>>>24]]^f[1][g[c>>16&255]]^f[2][g[c>>8&255]]^f[3][g[c& 255]]}; sjcl.cipher.aes.prototype={encrypt:function(a){return u(this,a,0)},decrypt:function(a){return u(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,g,f,h=[],l=[],k,m,n,p;for(e=0;0x100>e;e++)l[(h[e]=e<<1^283*(e>>7))^e]=e;for(g=f=0;!c[g];g^=k||1,f=l[f]||1)for(n=f^f<<1^f<<2^f<<3^f<<4,n=n>>8^n&255^99,c[g]=n,d[n]=g,m=h[e=h[k=h[g]]],p=0x1010101*m^0x10001*e^0x101*k^0x1010100*g,m=0x101*h[n]^0x1010100*n,e=0;4>e;e++)a[e][g]=m=m<<24^m>>>8,b[e][n]=p=p<<24^p>>>8;for(e= 0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}}; function u(a,b,c){if(4!==b.length)throw new sjcl.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],g=b[c?3:1]^d[1],f=b[2]^d[2];b=b[c?1:3]^d[3];var h,l,k,m=d.length/4-2,n,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],t=h[2],w=h[3],x=h[4];for(n=0;n<m;n++)h=a[e>>>24]^q[g>>16&255]^t[f>>8&255]^w[b&255]^d[p],l=a[g>>>24]^q[f>>16&255]^t[b>>8&255]^w[e&255]^d[p+1],k=a[f>>>24]^q[b>>16&255]^t[e>>8&255]^w[g&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^t[g>>8&255]^w[f&255]^d[p+3],p+=4,e=h,g=l,f=k;for(n= 0;4>n;n++)r[c?3&-n:n]=x[e>>>24]<<24^x[g>>16&255]<<16^x[f>>8&255]<<8^x[b&255]^d[p++],h=e,e=g,g=f,f=b,b=h;return r} sjcl.bitArray={bitSlice:function(a,b,c){a=sjcl.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl.bitArray.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<<c)-1},concat:function(a,b){if(0===a.length||0===b.length)return a.concat(b);var c=a[a.length-1],d=sjcl.bitArray.getPartial(c);return 32===d?a.concat(b):sjcl.bitArray.$(b,d,c|0,a.slice(0,a.length-1))},bitLength:function(a){var b=a.length;return 0=== b?0:32*(b-1)+sjcl.bitArray.getPartial(a[b-1])},clamp:function(a,b){if(32*a.length<b)return a;a=a.slice(0,Math.ceil(b/32));var c=a.length;b=b&31;0<c&&b&&(a[c-1]=sjcl.bitArray.partial(b,a[c-1]&2147483648>>b-1,1));return a},partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+0x10000000000*a},getPartial:function(a){return Math.round(a/0x10000000000)||32},equal:function(a,b){if(sjcl.bitArray.bitLength(a)!==sjcl.bitArray.bitLength(b))return!1;var c=0,d;for(d=0;d<a.length;d++)c|=a[d]^b[d];return 0=== c},$:function(a,b,c,d){var e;e=0;for(void 0===d&&(d=[]);32<=b;b-=32)d.push(c),c=0;if(0===b)return d.concat(a);for(e=0;e<a.length;e++)d.push(c|a[e]>>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl.bitArray.getPartial(e);d.push(sjcl.bitArray.partial(b+a&31,32<b+a?c:d.pop(),1));return d},i:function(a,b){return[a[0]^b[0],a[1]^b[1],a[2]^b[2],a[3]^b[3]]},byteswapM:function(a){var b,c;for(b=0;b<a.length;++b)c=a[b],a[b]=c>>>24|c>>>8&0xff00|(c&0xff00)<<8|c<<24;return a}}; sjcl.codec.utf8String={fromBits:function(a){var b="",c=sjcl.bitArray.bitLength(a),d,e;for(d=0;d<c/8;d++)0===(d&3)&&(e=a[d/4]),b+=String.fromCharCode(e>>>24),e<<=8;return decodeURIComponent(escape(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c<a.length;c++)d=d<<8|a.charCodeAt(c),3===(c&3)&&(b.push(d),d=0);c&3&&b.push(sjcl.bitArray.partial(8*(c&3),d));return b}}; sjcl.codec.hex={fromBits:function(a){var b="",c;for(c=0;c<a.length;c++)b+=((a[c]|0)+0xf00000000000).toString(16).substr(4);return b.substr(0,sjcl.bitArray.bitLength(a)/4)},toBits:function(a){var b,c=[],d;a=a.replace(/\s|0x/g,"");d=a.length;a=a+"00000000";for(b=0;b<a.length;b+=8)c.push(parseInt(a.substr(b,8),16)^0);return sjcl.bitArray.clamp(c,4*d)}}; sjcl.codec.base32={B:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",X:"0123456789ABCDEFGHIJKLMNOPQRSTUV",BITS:32,BASE:5,REMAINING:27,fromBits:function(a,b,c){var d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,g="",f=0,h=sjcl.codec.base32.B,l=0,k=sjcl.bitArray.bitLength(a);c&&(h=sjcl.codec.base32.X);for(c=0;g.length*d<k;)g+=h.charAt((l^a[c]>>>f)>>>e),f<d?(l=a[c]<<d-f,f+=e,c++):(l<<=d,f-=d);for(;g.length&7&&!b;)g+="=";return g},toBits:function(a,b){a=a.replace(/\s|=/g,"").toUpperCase();var c=sjcl.codec.base32.BITS, d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,g=[],f,h=0,l=sjcl.codec.base32.B,k=0,m,n="base32";b&&(l=sjcl.codec.base32.X,n="base32hex");for(f=0;f<a.length;f++){m=l.indexOf(a.charAt(f));if(0>m){if(!b)try{return sjcl.codec.base32hex.toBits(a)}catch(p){}throw new sjcl.exception.invalid("this isn't "+n+"!");}h>e?(h-=e,g.push(k^m>>>h),k=m<<c-h):(h+=d,k^=m<<c-h)}h&56&&g.push(sjcl.bitArray.partial(h&56,k,1));return g}}; sjcl.codec.base32hex={fromBits:function(a,b){return sjcl.codec.base32.fromBits(a,b,1)},toBits:function(a){return sjcl.codec.base32.toBits(a,1)}}; sjcl.codec.base64={B:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",fromBits:function(a,b,c){var d="",e=0,g=sjcl.codec.base64.B,f=0,h=sjcl.bitArray.bitLength(a);c&&(g=g.substr(0,62)+"-_");for(c=0;6*d.length<h;)d+=g.charAt((f^a[c]>>>e)>>>26),6>e?(f=a[c]<<6-e,e+=26,c++):(f<<=6,e-=6);for(;d.length&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,g=sjcl.codec.base64.B,f=0,h;b&&(g=g.substr(0,62)+"-_");for(d=0;d<a.length;d++){h=g.indexOf(a.charAt(d)); if(0>h)throw new sjcl.exception.invalid("this isn't base64!");26<e?(e-=26,c.push(f^h>>>e),f=h<<32-e):(e+=6,f^=h<<32-e)}e&56&&c.push(sjcl.bitArray.partial(e&56,f,1));return c}};sjcl.codec.base64url={fromBits:function(a){return sjcl.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl.codec.base64.toBits(a,1)}};sjcl.hash.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl.hash.sha256.hash=function(a){return(new sjcl.hash.sha256).update(a).finalize()}; sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.A=sjcl.bitArray.concat(this.A,a);b=this.l;a=this.l=b+sjcl.bitArray.bitLength(a);for(b=512+b&-512;b<=a;b+=512)v(this,c.splice(0,16));return this},finalize:function(){var a,b=this.A,c=this.F,b=sjcl.bitArray.concat(b,[sjcl.bitArray.partial(1,1)]);for(a=b.length+2;a&15;a++)b.push(0);b.push(Math.floor(this.l/ 4294967296));for(b.push(this.l|0);b.length;)v(this,b.splice(0,16));this.reset();return c},Y:[],b:[],O:function(){function a(a){return 0x100000000*(a-Math.floor(a))|0}var b=0,c=2,d;a:for(;64>b;c++){for(d=2;d*d<=c;d++)if(0===c%d)continue a;8>b&&(this.Y[b]=a(Math.pow(c,.5)));this.b[b]=a(Math.pow(c,1/3));b++}}}; function v(a,b){var c,d,e,g=b.slice(0),f=a.F,h=a.b,l=f[0],k=f[1],m=f[2],n=f[3],p=f[4],r=f[5],q=f[6],t=f[7];for(c=0;64>c;c++)16>c?d=g[c]:(d=g[c+1&15],e=g[c+14&15],d=g[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+g[c&15]+g[c+9&15]|0),d=d+t+(p>>>6^p>>>11^p>>>25^p<<26^p<<21^p<<7)+(q^p&(r^q))+h[c],t=q,q=r,r=p,p=n+d|0,n=m,m=k,k=l,l=d+(k&m^n&(k^m))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+l|0;f[1]=f[1]+k|0;f[2]=f[2]+m|0;f[3]=f[3]+n|0;f[4]=f[4]+p|0;f[5]=f[5]+r|0;f[6]= f[6]+q|0;f[7]=f[7]+t|0} sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl.mode.ccm.G.indexOf(a);-1<a&&sjcl.mode.ccm.G.splice(a,1)},fa:function(a){var b=sjcl.mode.ccm.G.slice(),c;for(c=0;c<b.length;c+=1)b[c](a)},encrypt:function(a,b,c,d,e){var g,f=b.slice(0),h=sjcl.bitArray,l=h.bitLength(c)/8,k=h.bitLength(f)/8;e=e||64;d=d||[];if(7>l)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(g=2;4>g&&k>>>8*g;g++);g<15-l&&(g=15-l);c=h.clamp(c, 8*(15-g));b=sjcl.mode.ccm.V(a,b,c,d,e,g);f=sjcl.mode.ccm.C(a,f,c,b,e,g);return h.concat(f.data,f.tag)},decrypt:function(a,b,c,d,e){e=e||64;d=d||[];var g=sjcl.bitArray,f=g.bitLength(c)/8,h=g.bitLength(b),l=g.clamp(b,h-e),k=g.bitSlice(b,h-e),h=(h-e)/8;if(7>f)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);b<15-f&&(b=15-f);c=g.clamp(c,8*(15-b));l=sjcl.mode.ccm.C(a,l,c,k,e,b);a=sjcl.mode.ccm.V(a,l.data,c,d,e,b);if(!g.equal(l.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match"); return l.data},na:function(a,b,c,d,e,g){var f=[],h=sjcl.bitArray,l=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|g-1)];d=h.concat(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?f=[h.partial(16,c)]:0xffffffff>=c&&(f=h.concat([h.partial(16,65534)],[c])),f=h.concat(f,b),b=0;b<f.length;b+=4)d=a.encrypt(l(d,f.slice(b,b+4).concat([0,0,0])));return d},V:function(a,b,c,d,e,g){var f=sjcl.bitArray,h=f.i;e/=8;if(e%2||4>e||16<e)throw new sjcl.exception.invalid("ccm: invalid tag length"); if(0xffffffff<d.length||0xffffffff<b.length)throw new sjcl.exception.bug("ccm: can't deal with 4GiB or more data");c=sjcl.mode.ccm.na(a,d,c,e,f.bitLength(b)/8,g);for(d=0;d<b.length;d+=4)c=a.encrypt(h(c,b.slice(d,d+4).concat([0,0,0])));return f.clamp(c,8*e)},C:function(a,b,c,d,e,g){var f,h=sjcl.bitArray;f=h.i;var l=b.length,k=h.bitLength(b),m=l/50,n=m;c=h.concat([h.partial(8,g-1)],c).concat([0,0,0]).slice(0,4);d=h.bitSlice(f(d,a.encrypt(c)),0,e);if(!l)return{tag:d,data:[]};for(f=0;f<l;f+=4)f>m&&(sjcl.mode.ccm.fa(f/ l),m+=n),c[3]++,e=a.encrypt(c),b[f]^=e[0],b[f+1]^=e[1],b[f+2]^=e[2],b[f+3]^=e[3];return{tag:d,data:h.clamp(b,k)}}}; sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,g){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");var f,h=sjcl.mode.ocb2.S,l=sjcl.bitArray,k=l.i,m=[0,0,0,0];c=h(a.encrypt(c));var n,p=[];d=d||[];e=e||64;for(f=0;f+4<b.length;f+=4)n=b.slice(f,f+4),m=k(m,n),p=p.concat(k(c,a.encrypt(k(c,n)))),c=h(c);n=b.slice(f);b=l.bitLength(n);f=a.encrypt(k(c,[0,0,0,b]));n=l.clamp(k(n.concat([0,0,0]),f),b);m=k(m,k(n.concat([0,0,0]),f));m=a.encrypt(k(m,k(c,h(c)))); d.length&&(m=k(m,g?d:sjcl.mode.ocb2.pmac(a,d)));return p.concat(l.concat(n,l.clamp(m,e)))},decrypt:function(a,b,c,d,e,g){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");e=e||64;var f=sjcl.mode.ocb2.S,h=sjcl.bitArray,l=h.i,k=[0,0,0,0],m=f(a.encrypt(c)),n,p,r=sjcl.bitArray.bitLength(b)-e,q=[];d=d||[];for(c=0;c+4<r/32;c+=4)n=l(m,a.decrypt(l(m,b.slice(c,c+4)))),k=l(k,n),q=q.concat(n),m=f(m);p=r-32*c;n=a.encrypt(l(m,[0,0,0,p]));n=l(n,h.clamp(b.slice(c),p).concat([0, 0,0]));k=l(k,n);k=a.encrypt(l(k,l(m,f(m))));d.length&&(k=l(k,g?d:sjcl.mode.ocb2.pmac(a,d)));if(!h.equal(h.clamp(k,e),h.bitSlice(b,r)))throw new sjcl.exception.corrupt("ocb: tag doesn't match");return q.concat(h.clamp(n,p))},pmac:function(a,b){var c,d=sjcl.mode.ocb2.S,e=sjcl.bitArray,g=e.i,f=[0,0,0,0],h=a.encrypt([0,0,0,0]),h=g(h,d(d(h)));for(c=0;c+4<b.length;c+=4)h=d(h),f=g(f,a.encrypt(g(h,b.slice(c,c+4))));c=b.slice(c);128>e.bitLength(c)&&(h=g(h,d(h)),c=e.concat(c,[-2147483648,0,0,0]));f=g(f,c); return a.encrypt(g(d(g(h,d(h))),f))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]<<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}}; sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var g=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.C(!0,a,g,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var g=b.slice(0),f=sjcl.bitArray,h=f.bitLength(g);e=e||128;d=d||[];e<=h?(b=f.bitSlice(g,h-e),g=f.bitSlice(g,0,h-e)):(b=g,g=[]);a=sjcl.mode.gcm.C(!1,a,g,d,c,e);if(!f.equal(a.tag,b))throw new sjcl.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,g,f,h=sjcl.bitArray.i;e=[0,0, 0,0];g=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,g));f=0!==(g[3]&1);for(d=3;0<d;d--)g[d]=g[d]>>>1|(g[d-1]&1)<<31;g[0]>>>=1;f&&(g[0]^=-0x1f000000)}return e},j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;d<e;d+=4)b[0]^=0xffffffff&c[d],b[1]^=0xffffffff&c[d+1],b[2]^=0xffffffff&c[d+2],b[3]^=0xffffffff&c[d+3],b=sjcl.mode.gcm.ka(b,a);return b},C:function(a,b,c,d,e,g){var f,h,l,k,m,n,p,r,q=sjcl.bitArray;n=c.length;p=q.bitLength(c);r=q.bitLength(d);h=q.bitLength(e); f=b.encrypt([0,0,0,0]);96===h?(e=e.slice(0),e=q.concat(e,[1])):(e=sjcl.mode.gcm.j(f,[0,0,0,0],e),e=sjcl.mode.gcm.j(f,e,[0,0,Math.floor(h/0x100000000),h&0xffffffff]));h=sjcl.mode.gcm.j(f,[0,0,0,0],d);m=e.slice(0);d=h.slice(0);a||(d=sjcl.mode.gcm.j(f,h,c));for(k=0;k<n;k+=4)m[3]++,l=b.encrypt(m),c[k]^=l[0],c[k+1]^=l[1],c[k+2]^=l[2],c[k+3]^=l[3];c=q.clamp(c,p);a&&(d=sjcl.mode.gcm.j(f,h,c));a=[Math.floor(r/0x100000000),r&0xffffffff,Math.floor(p/0x100000000),p&0xffffffff];d=sjcl.mode.gcm.j(f,d,a);l=b.encrypt(e); d[0]^=l[0];d[1]^=l[1];d[2]^=l[2];d[3]^=l[3];return{tag:q.bitSlice(d,0,g),data:c}}};sjcl.misc.hmac=function(a,b){this.W=b=b||sjcl.hash.sha256;var c=[[],[]],d,e=b.prototype.blockSize/32;this.w=[new b,new b];a.length>e&&(a=b.hash(a));for(d=0;d<e;d++)c[0][d]=a[d]^909522486,c[1][d]=a[d]^1549556828;this.w[0].update(c[0]);this.w[1].update(c[1]);this.R=new b(this.w[0])}; sjcl.misc.hmac.prototype.encrypt=sjcl.misc.hmac.prototype.mac=function(a){if(this.aa)throw new sjcl.exception.invalid("encrypt on already updated hmac called!");this.update(a);return this.digest(a)};sjcl.misc.hmac.prototype.reset=function(){this.R=new this.W(this.w[0]);this.aa=!1};sjcl.misc.hmac.prototype.update=function(a){this.aa=!0;this.R.update(a)};sjcl.misc.hmac.prototype.digest=function(){var a=this.R.finalize(),a=(new this.W(this.w[1])).update(a).finalize();this.reset();return a}; sjcl.misc.pbkdf2=function(a,b,c,d,e){c=c||1E3;if(0>d||0>c)throw sjcl.exception.invalid("invalid params to pbkdf2");"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits(b));e=e||sjcl.misc.hmac;a=new e(a);var g,f,h,l,k=[],m=sjcl.bitArray;for(l=1;32*k.length<(d||1);l++){e=g=a.encrypt(m.concat(b,[l]));for(f=1;f<c;f++)for(g=a.encrypt(g),h=0;h<g.length;h++)e[h]^=g[h];k=k.concat(e)}d&&(k=m.clamp(k,d));return k}; sjcl.prng=function(a){this.c=[new sjcl.hash.sha256];this.m=[0];this.P=0;this.H={};this.N=0;this.U={};this.Z=this.f=this.o=this.ha=0;this.b=[0,0,0,0,0,0,0,0];this.h=[0,0,0,0];this.L=void 0;this.M=a;this.D=!1;this.K={progress:{},seeded:{}};this.u=this.ga=0;this.I=1;this.J=2;this.ca=0x10000;this.T=[0,48,64,96,128,192,0x100,384,512,768,1024];this.da=3E4;this.ba=80}; sjcl.prng.prototype={randomWords:function(a,b){var c=[],d;d=this.isReady(b);var e;if(d===this.u)throw new sjcl.exception.notReady("generator isn't seeded");if(d&this.J){d=!(d&this.I);e=[];var g=0,f;this.Z=e[0]=(new Date).valueOf()+this.da;for(f=0;16>f;f++)e.push(0x100000000*Math.random()|0);for(f=0;f<this.c.length&&(e=e.concat(this.c[f].finalize()),g+=this.m[f],this.m[f]=0,d||!(this.P&1<<f));f++);this.P>=1<<this.c.length&&(this.c.push(new sjcl.hash.sha256),this.m.push(0));this.f-=g;g>this.o&&(this.o= g);this.P++;this.b=sjcl.hash.sha256.hash(this.b.concat(e));this.L=new sjcl.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d<a;d+=4)0===(d+1)%this.ca&&y(this),e=z(this),c.push(e[0],e[1],e[2],e[3]);y(this);return c.slice(0,a)},setDefaultParanoia:function(a,b){if(0===a&&"Setting paranoia=0 will ruin your security; use it only for testing"!==b)throw"Setting paranoia=0 will ruin your security; use it only for testing";this.M=a},addEntropy:function(a,b,c){c=c||"user"; var d,e,g=(new Date).valueOf(),f=this.H[c],h=this.isReady(),l=0;d=this.U[c];void 0===d&&(d=this.U[c]=this.ha++);void 0===f&&(f=this.H[c]=0);this.H[c]=(this.H[c]+1)%this.c.length;switch(typeof a){case "number":void 0===b&&(b=1);this.c[f].update([d,this.N++,1,b,g,1,a|0]);break;case "object":c=Object.prototype.toString.call(a);if("[object Uint32Array]"===c){e=[];for(c=0;c<a.length;c++)e.push(a[c]);a=e}else for("[object Array]"!==c&&(l=1),c=0;c<a.length&&!l;c++)"number"!==typeof a[c]&&(l=1);if(!l){if(void 0=== b)for(c=b=0;c<a.length;c++)for(e=a[c];0<e;)b++,e=e>>>1;this.c[f].update([d,this.N++,2,b,g,a.length].concat(a))}break;case "string":void 0===b&&(b=a.length);this.c[f].update([d,this.N++,3,b,g,a.length]);this.c[f].update(a);break;default:l=1}if(l)throw new sjcl.exception.bug("random: addEntropy only supports number, array of numbers or string");this.m[f]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math.max(this.o,this.f)),A("progress",this.getProgress()))},isReady:function(a){a=this.T[void 0!== a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&(new Date).valueOf()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o>=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window.addEventListener)window.addEventListener("load",this.a.loadTimeCollector, !1),window.addEventListener("mousemove",this.a.mouseCollector,!1),window.addEventListener("keypress",this.a.keyboardCollector,!1),window.addEventListener("devicemotion",this.a.accelerometerCollector,!1),window.addEventListener("touchmove",this.a.touchCollector,!1);else if(document.attachEvent)document.attachEvent("onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent("keypress",this.a.keyboardCollector);else throw new sjcl.exception.bug("can't attach event"); this.D=!0}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this.a.loadTimeCollector,!1),window.removeEventListener("mousemove",this.a.mouseCollector,!1),window.removeEventListener("keypress",this.a.keyboardCollector,!1),window.removeEventListener("devicemotion",this.a.accelerometerCollector,!1),window.removeEventListener("touchmove",this.a.touchCollector,!1)):document.detachEvent&&(document.detachEvent("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove", this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=!1)},addEventListener:function(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],g=[];for(d in e)e.hasOwnProperty(d)&&e[d]===b&&g.push(d);for(c=0;c<g.length;c++)d=g[c],delete e[d]},la:function(){C(1)},oa:function(a){var b,c;try{b=a.x||a.clientX||a.offsetX||0,c=a.y||a.clientY||a.offsetY||0}catch(d){c=b=0}0!=b&&0!=c&&sjcl.random.addEntropy([b,c],2,"mouse");C(0)},qa:function(a){a= a.touches[0]||a.changedTouches[0];sjcl.random.addEntropy([a.pageX||a.clientX,a.pageY||a.clientY],1,"touch");C(0)},ma:function(){C(2)},ea:function(a){a=a.accelerationIncludingGravity.x||a.accelerationIncludingGravity.y||a.accelerationIncludingGravity.z;if(window.orientation){var b=window.orientation;"number"===typeof b&&sjcl.random.addEntropy(b,1,"accelerometer")}a&&sjcl.random.addEntropy(a,2,"accelerometer");C(0)}}; function A(a,b){var c,d=sjcl.random.K[a],e=[];for(c in d)d.hasOwnProperty(c)&&e.push(d[c]);for(c=0;c<e.length;c++)e[c](b)}function C(a){"undefined"!==typeof window&&window.performance&&"function"===typeof window.performance.now?sjcl.random.addEntropy(window.performance.now(),a,"loadtime"):sjcl.random.addEntropy((new Date).valueOf(),a,"loadtime")}function y(a){a.b=z(a).concat(z(a));a.L=new sjcl.cipher.aes(a.b)} function z(a){for(var b=0;4>b&&(a.h[b]=a.h[b]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}function B(a,b){return function(){b.apply(a,arguments)}}sjcl.random=new sjcl.prng(6); a:try{var D,E,F,G;if(G="undefined"!==typeof module&&module.exports){var H;try{H=require("crypto")}catch(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array((new Uint8Array(D)).buffer),sjcl.random.addEntropy(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F); else break a;sjcl.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console.log(a))} sjcl.json={defaults:{v:1,iter:1E3,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl.json,g=e.g({iv:sjcl.random.randomWords(4,0)},e.defaults),f;e.g(g,c);c=g.adata;"string"===typeof g.salt&&(g.salt=sjcl.codec.base64.toBits(g.salt));"string"===typeof g.iv&&(g.iv=sjcl.codec.base64.toBits(g.iv));if(!sjcl.mode[g.mode]||!sjcl.cipher[g.cipher]||"string"===typeof a&&100>=g.iter||64!==g.ts&&96!==g.ts&&128!==g.ts||128!==g.ks&&192!==g.ks&&0x100!==g.ks||2>g.iv.length|| 4<g.iv.length)throw new sjcl.exception.invalid("json encrypt: invalid parameters");"string"===typeof a?(f=sjcl.misc.cachedPbkdf2(a,g),a=f.key.slice(0,g.ks/32),g.salt=f.salt):sjcl.ecc&&a instanceof sjcl.ecc.elGamal.publicKey&&(f=a.kem(),g.kemtag=f.tag,a=f.key.slice(0,g.ks/32));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits(b));"string"===typeof c&&(g.adata=c=sjcl.codec.utf8String.toBits(c));f=new sjcl.cipher[g.cipher](a);e.g(d,g);d.key=a;g.ct="ccm"===g.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&& b instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.encrypt(f,b,g.iv,c,g.ts):sjcl.mode[g.mode].encrypt(f,b,g.iv,c,g.ts);return g},encrypt:function(a,b,c,d){var e=sjcl.json,g=e.ja.apply(e,arguments);return e.encode(g)},ia:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl.json;b=e.g(e.g(e.g({},e.defaults),b),c,!0);var g,f;g=b.adata;"string"===typeof b.salt&&(b.salt=sjcl.codec.base64.toBits(b.salt));"string"===typeof b.iv&&(b.iv=sjcl.codec.base64.toBits(b.iv));if(!sjcl.mode[b.mode]||!sjcl.cipher[b.cipher]||"string"=== typeof a&&100>=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&0x100!==b.ks||!b.iv||2>b.iv.length||4<b.iv.length)throw new sjcl.exception.invalid("json decrypt: invalid parameters");"string"===typeof a?(f=sjcl.misc.cachedPbkdf2(a,b),a=f.key.slice(0,b.ks/32),b.salt=f.salt):sjcl.ecc&&a instanceof sjcl.ecc.elGamal.secretKey&&(a=a.unkem(sjcl.codec.base64.toBits(b.kemtag)).slice(0,b.ks/32));"string"===typeof g&&(g=sjcl.codec.utf8String.toBits(g));f=new sjcl.cipher[b.cipher](a);g="ccm"=== b.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&b.ct instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.decrypt(f,b.ct,b.iv,b.tag,g,b.ts):sjcl.mode[b.mode].decrypt(f,b.ct,b.iv,g,b.ts);e.g(d,b);d.key=a;return 1===c.raw?g:sjcl.codec.utf8String.fromBits(g)},decrypt:function(a,b,c,d){var e=sjcl.json;return e.ia(a,e.decode(b),c,d)},encode:function(a){var b,c="{",d="";for(b in a)if(a.hasOwnProperty(b)){if(!b.match(/^[a-z0-9]+$/i))throw new sjcl.exception.invalid("json encode: invalid property name");c+=d+'"'+ b+'":';d=",";switch(typeof a[b]){case "number":case "boolean":c+=a[b];break;case "string":c+='"'+escape(a[b])+'"';break;case "object":c+='"'+sjcl.codec.base64.fromBits(a[b],0)+'"';break;default:throw new sjcl.exception.bug("json encode: unsupported type");}}return c+"}"},decode:function(a){a=a.replace(/\s/g,"");if(!a.match(/^\{.*\}$/))throw new sjcl.exception.invalid("json decode: this isn't json!");a=a.replace(/^\{|\}$/g,"").split(/,/);var b={},c,d;for(c=0;c<a.length;c++){if(!(d=a[c].match(/^\s*(?:(["']?)([a-z][a-z0-9]*)\1)\s*:\s*(?:(-?\d+)|"([a-z0-9+\/%*_.@=\-]*)"|(true|false))$/i)))throw new sjcl.exception.invalid("json decode: this isn't json!"); null!=d[3]?b[d[2]]=parseInt(d[3],10):null!=d[4]?b[d[2]]=d[2].match(/^(ct|adata|salt|iv)$/)?sjcl.codec.base64.toBits(d[4]):unescape(d[4]):null!=d[5]&&(b[d[2]]="true"===d[5])}return b},g:function(a,b,c){void 0===a&&(a={});if(void 0===b)return a;for(var d in b)if(b.hasOwnProperty(d)){if(c&&void 0!==a[d]&&a[d]!==b[d])throw new sjcl.exception.invalid("required parameter overridden");a[d]=b[d]}return a},sa:function(a,b){var c={},d;for(d in a)a.hasOwnProperty(d)&&a[d]!==b[d]&&(c[d]=a[d]);return c},ra:function(a, b){var c={},d;for(d=0;d<b.length;d++)void 0!==a[b[d]]&&(c[b[d]]=a[b[d]]);return c}};sjcl.encrypt=sjcl.json.encrypt;sjcl.decrypt=sjcl.json.decrypt;sjcl.misc.pa={};sjcl.misc.cachedPbkdf2=function(a,b){var c=sjcl.misc.pa,d;b=b||{};d=b.iter||1E3;c=c[a]=c[a]||{};d=c[d]=c[d]||{firstSalt:b.salt&&b.salt.length?b.salt.slice(0):sjcl.random.randomWords(2,0)};c=void 0===b.salt?d.firstSalt:b.salt;d[c]=d[c]||sjcl.misc.pbkdf2(a,c,b.iter);return{key:d[c].slice(0),salt:c.slice(0)}};
// seedrandom.js // Author: David Bau 12/25/2010 // // Defines a method Math.seedrandom() that, when called, substitutes // an explicitly seeded RC4-based algorithm for Math.random(). Also // supports automatic seeding from local or network sources of entropy. // // Usage: // // <script src=http://davidbau.com/encode/seedrandom-min.js></script> // // Math.seedrandom('yipee'); Sets Math.random to a function that is // initialized using the given explicit seed. // // Math.seedrandom(); Sets Math.random to a function that is // seeded using the current time, dom state, // and other accumulated local entropy. // The generated seed string is returned. // // Math.seedrandom('yowza', true); // Seeds using the given explicit seed mixed // together with accumulated entropy. // // <script src="http://bit.ly/srandom-512"></script> // Seeds using physical random bits downloaded // from random.org. // // <script src="https://jsonlib.appspot.com/urandom?callback=Math.seedrandom"> // </script> Seeds using urandom bits from call.jsonlib.com, // which is faster than random.org. // // Examples: // // Math.seedrandom("hello"); // Use "hello" as the seed. // document.write(Math.random()); // Always 0.5463663768140734 // document.write(Math.random()); // Always 0.43973793770592234 // var rng1 = Math.random; // Remember the current prng. // // var autoseed = Math.seedrandom(); // New prng with an automatic seed. // document.write(Math.random()); // Pretty much unpredictable. // // Math.random = rng1; // Continue "hello" prng sequence. // document.write(Math.random()); // Always 0.554769432473455 // // Math.seedrandom(autoseed); // Restart at the previous seed. // document.write(Math.random()); // Repeat the 'unpredictable' value. // // Notes: // // Each time seedrandom('arg') is called, entropy from the passed seed // is accumulated in a pool to help generate future seeds for the // zero-argument form of Math.seedrandom, so entropy can be injected over // time by calling seedrandom with explicit data repeatedly. // // On speed - This javascript implementation of Math.random() is about // 3-10x slower than the built-in Math.random() because it is not native // code, but this is typically fast enough anyway. Seeding is more expensive, // especially if you use auto-seeding. Some details (timings on Chrome 4): // // Our Math.random() - avg less than 0.002 milliseconds per call // seedrandom('explicit') - avg less than 0.5 milliseconds per call // seedrandom('explicit', true) - avg less than 2 milliseconds per call // seedrandom() - avg about 38 milliseconds per call // // LICENSE (BSD): // // Copyright 2010 David Bau, all rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of this module nor the names of its contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /** * All code is in an anonymous closure to keep the global namespace clean. * * @param {number=} overflow * @param {number=} startdenom */ (function (pool, math, width, chunks, significance, overflow, startdenom) { // // seedrandom() // This is the seedrandom function described above. // math['seedrandom'] = function seedrandom(seed, use_entropy) { var key = []; var arc4; // Flatten the seed string or build one from local entropy if needed. seed = mixkey(flatten( use_entropy ? [seed, pool] : arguments.length ? seed : [new Date().getTime(), pool, window], 3), key); // Use the seed to initialize an ARC4 generator. arc4 = new ARC4(key); // Mix the randomness into accumulated entropy. mixkey(arc4.S, pool); // Override Math.random // This function returns a random double in [0, 1) that contains // randomness in every bit of the mantissa of the IEEE 754 value. math['random'] = function random() { // Closure to return a random double: var n = arc4.g(chunks); // Start with a numerator n < 2 ^ 48 var d = startdenom; // and denominator d = 2 ^ 48. var x = 0; // and no 'extra last byte'. while (n < significance) { // Fill up all significant digits by n = (n + x) * width; // shifting numerator and d *= width; // denominator and generating a x = arc4.g(1); // new least-significant-byte. } while (n >= overflow) { // To avoid rounding up, before adding n /= 2; // last byte, shift everything d /= 2; // right using integer math until x >>>= 1; // we have exactly the desired bits. } return (n + x) / d; // Form the number within [0, 1). }; // Return the seed that was used return seed; }; // // ARC4 // // An ARC4 implementation. The constructor takes a key in the form of // an array of at most (width) integers that should be 0 <= x < (width). // // The g(count) method returns a pseudorandom integer that concatenates // the next (count) outputs from ARC4. Its return value is a number x // that is in the range 0 <= x < (width ^ count). // /** @constructor */ function ARC4(key) { var t, u, me = this, keylen = key.length; var i = 0, j = me.i = me.j = me.m = 0; me.S = []; me.c = []; // The empty key [] is treated as [0]. if (!keylen) { key = [keylen++]; } // Set up S using the standard key scheduling algorithm. while (i < width) { me.S[i] = i++; } for (i = 0; i < width; i++) { t = me.S[i]; j = lowbits(j + t + key[i % keylen]); u = me.S[j]; me.S[i] = u; me.S[j] = t; } // The "g" method returns the next (count) outputs as one number. me.g = function getnext(count) { var s = me.S; var i = lowbits(me.i + 1); var t = s[i]; var j = lowbits(me.j + t); var u = s[j]; s[i] = u; s[j] = t; var r = s[lowbits(t + u)]; while (--count) { i = lowbits(i + 1); t = s[i]; j = lowbits(j + t); u = s[j]; s[i] = u; s[j] = t; r = r * width + s[lowbits(t + u)]; } me.i = i; me.j = j; return r; }; // For robust unpredictability discard an initial batch of values. // See http://www.rsa.com/rsalabs/node.asp?id=2009 me.g(width); } // // flatten() // Converts an object tree to nested arrays of strings. // /** @param {Object=} result * @param {string=} prop */ function flatten(obj, depth, result, prop) { result = []; if (depth && typeof(obj) == 'object') { for (prop in obj) { if (prop.indexOf('S') < 5) { // Avoid FF3 bug (local/sessionStorage) try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {} } } } return result.length ? result : '' + obj; } // // mixkey() // Mixes a string seed into a key that is an array of integers, and // returns a shortened string seed that is equivalent to the result key. // /** @param {number=} smear * @param {number=} j */ function mixkey(seed, key, smear, j) { seed += ''; // Ensure the seed is a string smear = 0; for (j = 0; j < seed.length; j++) { key[lowbits(j)] = lowbits((smear ^= key[lowbits(j)] * 19) + seed.charCodeAt(j)); } seed = ''; for (j in key) { seed += String.fromCharCode(key[j]); } return seed; } // // lowbits() // A quick "n mod width" for width a power of 2. // function lowbits(n) { return n & (width - 1); } // // The following constants are related to IEEE 754 limits. // startdenom = math.pow(width, chunks); significance = math.pow(2, significance); overflow = significance * 2; // // When seedrandom.js is loaded, we immediately mix a few bits // from the built-in RNG into the entropy pool. Because we do // not want to intefere with determinstic PRNG state later, // seedrandom will not call math.random on its own again after // initialization. // mixkey(math.random(), pool); // End anonymous scope, and pass initial values. })( [], // pool: entropy pool starts empty Math, // math: package containing random, pow, and seedrandom 256, // width: each RC4 output is 0 <= x < 256 6, // chunks: at least six RC4 outputs for each double 52 // significance: there are 52 significant digits in a double );
// # Surrounds given text with Markdown syntax /*global $, CodeMirror, Showdown, moment */ (function () { 'use strict'; var Markdown = { init : function (options, elem) { var self = this; self.elem = elem; self.style = (typeof options === 'string') ? options : options.style; self.options = $.extend({}, CodeMirror.prototype.addMarkdown.options, options); self.replace(); }, replace: function () { var text = this.elem.getSelection(), pass = true, cursor = this.elem.getCursor(), line = this.elem.getLine(cursor.line), md, word, letterCount, converter, textIndex, position; switch (this.style) { case 'h1': this.elem.setLine(cursor.line, '# ' + line); this.elem.setCursor(cursor.line, cursor.ch + 2); pass = false; break; case 'h2': this.elem.setLine(cursor.line, '## ' + line); this.elem.setCursor(cursor.line, cursor.ch + 3); pass = false; break; case 'h3': this.elem.setLine(cursor.line, '### ' + line); this.elem.setCursor(cursor.line, cursor.ch + 4); pass = false; break; case 'h4': this.elem.setLine(cursor.line, '#### ' + line); this.elem.setCursor(cursor.line, cursor.ch + 5); pass = false; break; case 'h5': this.elem.setLine(cursor.line, '##### ' + line); this.elem.setCursor(cursor.line, cursor.ch + 6); pass = false; break; case 'h6': this.elem.setLine(cursor.line, '###### ' + line); this.elem.setCursor(cursor.line, cursor.ch + 7); pass = false; break; case 'link': md = this.options.syntax.link.replace('$1', text); this.elem.replaceSelection(md, 'end'); if (!text) { this.elem.setCursor(cursor.line, cursor.ch + 1); } else { textIndex = line.indexOf(text, cursor.ch - text.length); position = textIndex + md.length - 1; this.elem.setSelection({line: cursor.line, ch: position - 7}, {line: cursor.line, ch: position}); } pass = false; break; case 'image': md = this.options.syntax.image.replace('$1', text); if (line !== '') { md = "\n\n" + md; } this.elem.replaceSelection(md, "end"); cursor = this.elem.getCursor(); this.elem.setSelection({line: cursor.line, ch: cursor.ch - 8}, {line: cursor.line, ch: cursor.ch - 1}); pass = false; break; case 'uppercase': md = text.toLocaleUpperCase(); break; case 'lowercase': md = text.toLocaleLowerCase(); break; case 'titlecase': md = text.toTitleCase(); break; case 'selectword': word = this.elem.getTokenAt(cursor); if (!/\w$/g.test(word.string)) { this.elem.setSelection({line: cursor.line, ch: word.start}, {line: cursor.line, ch: word.end - 1}); } else { this.elem.setSelection({line: cursor.line, ch: word.start}, {line: cursor.line, ch: word.end}); } break; case 'copyHTML': converter = new Showdown.converter(); if (text) { md = converter.makeHtml(text); } else { md = converter.makeHtml(this.elem.getValue()); } $(".modal-copyToHTML-content").text(md).selectText(); pass = false; break; case 'list': md = text.replace(/^(\s*)(\w\W*)/gm, '$1* $2'); this.elem.replaceSelection(md, 'end'); pass = false; break; case 'currentDate': md = moment(new Date()).format('D MMMM YYYY'); this.elem.replaceSelection(md, 'end'); pass = false; break; case 'newLine': if (line !== "") { this.elem.setLine(cursor.line, line + "\n\n"); } pass = false; break; default: if (this.options.syntax[this.style]) { md = this.options.syntax[this.style].replace('$1', text); } } if (pass && md) { this.elem.replaceSelection(md, 'end'); if (!text) { letterCount = md.length; this.elem.setCursor({line: cursor.line, ch: cursor.ch - (letterCount / 2)}); } } } }; CodeMirror.prototype.addMarkdown = function (options) { var markdown = Object.create(Markdown); markdown.init(options, this); }; CodeMirror.prototype.addMarkdown.options = { style: null, syntax: { bold: '**$1**', italic: '*$1*', strike: '~~$1~~', code: '`$1`', link: '[$1](http://)', image: '![$1](http://)', blockquote: '> $1' } }; }());
/* * QtWebKit-powered headless test runner using PhantomJS * * PhantomJS binaries: http://phantomjs.org/download.html * Requires PhantomJS 1.6+ (1.7+ recommended) * * Run with: * phantomjs runner.js [url-of-your-qunit-testsuite] * * e.g. * phantomjs runner.js http://localhost/qunit/test/index.html */ /*global phantom:false, require:false, console:false, window:false, QUnit:false */ (function() { 'use strict'; var url, page, timeout, args = require('system').args; // arg[0]: scriptName, args[1...]: arguments if (args.length < 2 || args.length > 3) { console.error('Usage:\n phantomjs runner.js [url-of-your-qunit-testsuite] [timeout-in-seconds]'); phantom.exit(1); } url = args[1]; page = require('webpage').create(); page.settings.clearMemoryCaches = true; if (args[2] !== undefined) { timeout = parseInt(args[2], 10); } // Route `console.log()` calls from within the Page context to the main Phantom context (i.e. current `this`) page.onConsoleMessage = function(msg) { console.log(msg); }; page.onInitialized = function() { page.evaluate(addLogging); }; page.onCallback = function(message) { var result, failed; if (message) { if (message.name === 'QUnit.done') { result = message.data; failed = !result || !result.total || result.failed; if (!result.total) { console.error('No tests were executed. Are you loading tests asynchronously?'); } phantom.exit(failed ? 1 : 0); } } }; page.open(url, function(status) { if (status !== 'success') { console.error('Unable to access network: ' + status); phantom.exit(1); } else { // Cannot do this verification with the 'DOMContentLoaded' handler because it // will be too late to attach it if a page does not have any script tags. var qunitMissing = page.evaluate(function() { return (typeof QUnit === 'undefined' || !QUnit); }); if (qunitMissing) { console.error('The `QUnit` object is not present on this page.'); phantom.exit(1); } // Set a timeout on the test running, otherwise tests with async problems will hang forever if (typeof timeout === 'number') { setTimeout(function() { console.error('The specified timeout of ' + timeout + ' seconds has expired. Aborting...'); phantom.exit(1); }, timeout * 1000); } // Do nothing... the callback mechanism will handle everything! } }); function addLogging() { window.document.addEventListener('DOMContentLoaded', function() { var currentTestAssertions = []; QUnit.log(function(details) { var response; // Ignore passing assertions if (details.result) { return; } response = details.message || ''; if (typeof details.expected !== 'undefined') { if (response) { response += ', '; } response += 'expected: ' + details.expected + ', but was: ' + details.actual; } if (details.source) { response += "\n" + details.source; } currentTestAssertions.push('Failed assertion: ' + response); }); QUnit.testDone(function(result) { var i, len, name = result.module + ': ' + result.name; if (result.failed) { console.log('Test failed: ' + name); for (i = 0, len = currentTestAssertions.length; i < len; i++) { console.log(' ' + currentTestAssertions[i]); } } currentTestAssertions.length = 0; }); QUnit.done(function(result) { console.log('Took ' + result.runtime + 'ms to run ' + result.total + ' tests. ' + result.passed + ' passed, ' + result.failed + ' failed.'); if (typeof window.callPhantom === 'function') { window.callPhantom({ 'name': 'QUnit.done', 'data': result }); } }); }, false); } })();
var struct___s_y_s_t_e_m___t_h_r_e_a_d___i_n_f_o_r_m_a_t_i_o_n = [ [ "BasePriority", "struct___s_y_s_t_e_m___t_h_r_e_a_d___i_n_f_o_r_m_a_t_i_o_n.html#a83350567ec26fc4723ac14b5864ae4f9", null ], [ "ClientId", "struct___s_y_s_t_e_m___t_h_r_e_a_d___i_n_f_o_r_m_a_t_i_o_n.html#a5f4ab183c0202edb1e4b9a2be1ace0db", null ], [ "ContextSwitches", "struct___s_y_s_t_e_m___t_h_r_e_a_d___i_n_f_o_r_m_a_t_i_o_n.html#ac52132a613e80356b9fbdeab8f010d53", null ], [ "CreateTime", "struct___s_y_s_t_e_m___t_h_r_e_a_d___i_n_f_o_r_m_a_t_i_o_n.html#a440670e511c4480f7017340c5ebe7a2f", null ], [ "KernelTime", "struct___s_y_s_t_e_m___t_h_r_e_a_d___i_n_f_o_r_m_a_t_i_o_n.html#a3e9ff2a68079e122720519502209e5e1", null ], [ "Priority", "struct___s_y_s_t_e_m___t_h_r_e_a_d___i_n_f_o_r_m_a_t_i_o_n.html#aa993a3a9535780f563e42fcb4e4f32c6", null ], [ "StartAddress", "struct___s_y_s_t_e_m___t_h_r_e_a_d___i_n_f_o_r_m_a_t_i_o_n.html#a9295c62e359e2ba76519e05baf2a4087", null ], [ "ThreadState", "struct___s_y_s_t_e_m___t_h_r_e_a_d___i_n_f_o_r_m_a_t_i_o_n.html#ac5dc1ba3985f4cac702124910e7712c7", null ], [ "UserTime", "struct___s_y_s_t_e_m___t_h_r_e_a_d___i_n_f_o_r_m_a_t_i_o_n.html#a860336a48384d8088ffd8c0abe38d170", null ], [ "WaitReason", "struct___s_y_s_t_e_m___t_h_r_e_a_d___i_n_f_o_r_m_a_t_i_o_n.html#a250406522090d84f67d275aff60e6079", null ], [ "WaitTime", "struct___s_y_s_t_e_m___t_h_r_e_a_d___i_n_f_o_r_m_a_t_i_o_n.html#ad7e29844c70b124dfbb6d57a52724d21", null ] ];
/* * Copyright (C) 2010 Google Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @constructor * @param {string} label * @param {string} className * @param {string=} tooltip */ WebInspector.Checkbox = function(label, className, tooltip) { this.element = document.createElementWithClass("label", className); this._inputElement = this.element.createChild("input"); this._inputElement.type = "checkbox"; this.element.createTextChild(label); if (tooltip) this.element.title = tooltip; } WebInspector.Checkbox.prototype = { set checked(checked) { this._inputElement.checked = checked; }, get checked() { return this._inputElement.checked; }, addEventListener: function(listener) { function listenerWrapper(event) { if (listener) listener(event); event.consume(); return true; } this._inputElement.addEventListener("click", listenerWrapper, false); this.element.addEventListener("click", listenerWrapper, false); } }
/** * Template JS for Internet Explorer 8 and lower - mainly workaround for missing selectors */ (function($) { // Standard template setup for IE $.fn.addTemplateSetup(function() { // Clean existing classes this.find('.first-child').removeClass('first-child'); this.find('.last-child').removeClass('last-child'); this.find('.last-of-type').removeClass('last-of-type'); this.find('.even').removeClass('even'); this.find('.odd').removeClass('odd'); // Missing selectors this.find(':first-child').addClass('first-child'); this.find(':last-child').addClass('last-child'); // Specific classes this.find('.head').each(function () { $(this).children('div:last').addClass('last-of-type'); }); this.find('tbody tr:even, .task-dialog > li:even, .planning > li.planning-header > ul > li:even').addClass('even'); this.find('tbody tr:odd, .planning > li:odd').addClass('odd'); this.find('.form fieldset:has(legend)').addClass('fieldset-with-legend').filter(':first-child').addClass('fieldset-with-legend-first-child'); // Disabled buttons this.find('button:disabled').addClass('disabled'); // IE 7 if ($.browser.version < 8) { // Clean existing classes this.find('.after-h1').removeClass('after-h1'); this.find('.block-content h1:first-child, .block-content .h1:first-child').next().addClass('after-h1'); this.find('.calendar .add-event').prepend('<span class="before"></span>'); } // Input switches this.find('input[type=radio].switch:checked + .switch-replace, input[type=checkbox].switch:checked + .switch-replace').addClass('switch-replace-checked'); this.find('input[type=radio].switch:disabled + .switch-replace, input[type=checkbox].switch:disabled + .switch-replace').addClass('switch-replace-disabled'); this.find('input[type=radio].mini-switch:checked + .mini-switch-replace, input[type=checkbox].mini-switch:checked + .mini-switch-replace').addClass('mini-switch-replace-checked'); this.find('input[type=radio].mini-switch:disabled + .mini-switch-replace, input[type=checkbox].mini-switch:disabled + .mini-switch-replace').addClass('mini-switch-replace-disabled'); }); // Document initial setup $(document).ready(function() { // Input switches $('input[type=radio].switch, input[type=checkbox].switch').click(function() { if (!this.checked) { $(this).next('.switch-replace').addClass('switch-replace-checked'); } else { $(this).next('.switch-replace').removeClass('switch-replace-checked'); } }); $('input[type=radio].mini-switch, input[type=checkbox].mini-switch').click(function() { if (!this.checked) { $(this).next('.mini-switch-replace').addClass('mini-switch-replace-checked'); } else { $(this).next('.mini-switch-replace').removeClass('mini-switch-replace-checked'); } }); }); })(jQuery);
import Ember from 'ember'; import MaterializeNavBar from './md-navbar'; export default MaterializeNavBar.extend({ init() { this._super(...arguments); Ember.deprecate("{{materialize-navbar}} has been deprecated. Please use {{md-navbar}} instead", false, {url: "https://github.com/sgasser/ember-cli-materialize/issues/67"}); } });
var _ = require('underscore'); module.exports = { 'passport-number': { labelClassName: 'visuallyhidden', validate: [ 'required' ] }, 'can-sign': { legend: { className: 'visuallyhidden' }, formatter: 'boolean', validate: ['required'], options: [ { value: true, label: 'I understand and will sign my passport', }, { value: false, label: 'I can’t sign my name', toggle: 'no-sign' } ] }, 'no-sign-reason': { className: 'textarea', validate: [ 'required', { type: 'maxlength', arguments: 250 } ], dependent: { field: 'can-sign', value: false } }, 'age-year': { labelClassName: 'form-label', formatter: 'removehyphens', validate: [ 'numeric', 'required' ] }, 'age-month': { labelClassName: 'form-label', formatter: 'removehyphens', validate: [ 'numeric', 'required' ] }, 'age-day': { labelClassName: 'form-label', formatter: 'removehyphens', validate: [ 'numeric', 'required' ] }, 'title':{ legend: { value: 'Your title', className: 'visuallyhidden' }, options: [ {value: 'Mr', label: 'Mr'}, {value: 'Mrs', label: 'Mrs'}, {value: 'Miss', label: 'Miss'}, {value: 'Ms', label: 'Ms'}, {value: 'Other', label: 'Other', toggle: 'other-titles'} ], validate: [ 'required' ] }, 'name': { }, 'lastname': { }, 'previous-name': { formatter: 'boolean', validate: 'required', legend: { className: 'form-label-bold' }, className: 'inline', options: [ { value: true, label: 'Yes', toggle: 'previous-names', child: 'input-text' }, { value: false, label: 'No' } ] }, 'previous-names': { validate: [ 'required', { type: 'maxlength', arguments: 100 } ], dependent: { field: 'previous-name', value: true } }, 'gender': { validate: [ 'required' ], legend: { value: 'Your gender', className: 'visuallyhidden' }, options: [ { value: 'F', label: 'Female' }, { value: 'M', label: 'Male' } ] }, 'town-of-birth': { validate: [ 'required' ] }, 'born-in-uk': { formatter: 'boolean', validate: 'required', legend: { className: 'form-label-bold' }, options: [ { value: true, label: 'Yes' }, { value: false, label: 'No', toggle: 'birth-country' } ], className: 'inline' }, 'country-of-birth': { validate: 'required', dependent: { field: 'born-in-uk', value: false }, }, 'expiry-year': { labelClassName: 'form-label', formatter: 'removehyphens', validate: [ 'numeric', 'required' ] }, 'expiry-month': { labelClassName: 'form-label', formatter: 'removehyphens', validate: [ 'numeric', 'required' ] }, 'address1': { validate: [ 'required' ] }, 'address2': { labelClassName: 'visuallyhidden', formatter: 'removehyphens' }, 'address3': { labelClassName: 'visuallyhidden', formatter: 'removehyphens' }, 'address4': { labelClassName: 'visuallyhidden', formatter: 'removehyphens' }, 'address5': { labelClassName: 'visuallyhidden', formatter: 'removehyphens' }, 'town': { validate: [ 'required' ] }, 'postcode': { validate: [ 'required' ] }, 'email': { validate: [ 'required' ] }, 'country-code': { labelClassName: 'visuallyhidden', formatter: 'removehyphens', validate: [ 'required' ] }, 'mobile': { validate: [ 'numeric', 'required' ] }, 'passport-options-dps':{ legend: { value: 'Passport size' }, options: [ {value: '32', label: 'Standard adult 32-page passport (£128)'}, {value: '48', label: 'Jumbo adult 48-page passport (£137)'} ], validate: [ 'required' ] }, 'passport-size': { formatter: 'boolean', validate: 'required', legend: { value: 'What size passport would you like?', className: 'form-label' }, options: [ { value: false, label: '32-page passport (free)' }, { value: true, label: '48-page passport ({{#currency}}{{largePassportCost}}{{/currency}})' } ], dependent: { field: 'passport-size-dependent', value: 'true' } }, braille: { formatter: 'boolean-strict', legend: { value: 'Add a Braille sticker' }, }, 'return-passport':{ legend: { value: 'How would you like us to return your ols passport?', className: 'visuallyhidden' }, options: [ {value: 'Special-delivery', label: 'Special delivery (£3 extra)'}, {value: 'Standard', label: 'Standard post (free)'} ], validate: [ 'required' ] }, 'secure-return': { formatter: 'boolean', validate: 'required', legend: { value: 'How would you like us to send your old passport back to you?', className: 'form-label-bold' }, options: [ { value: true, label: 'Special delivery (&#163;3 extra)' }, { value: false, label: 'Standard post (free)' } ] }, };
var searchData= [ ['data',['data',['../classv8_1_1_string_1_1_external_string_resource.html#a987309199b848511adb708e221e0fb0a',1,'v8::String::ExternalStringResource::data()'],['../classv8_1_1_string_1_1_external_one_byte_string_resource.html#aaeca31240d3dbf990d1b974e3c64593e',1,'v8::String::ExternalOneByteStringResource::data()'],['../classv8_1_1_external_one_byte_string_resource_impl.html#a37ada5dc21ecb982c50482c90fffe529',1,'v8::ExternalOneByteStringResourceImpl::data()']]], ['datetimeconfigurationchangenotification',['DateTimeConfigurationChangeNotification',['../classv8_1_1_date.html#adb084ec0683d3d195ad0f78af5f6f72b',1,'v8::Date']]], ['delete',['Delete',['../classv8_1_1_cpu_profile.html#a70c93f0c14d07a7e1bad42ee95665ca0',1,'v8::CpuProfile::Delete()'],['../classv8_1_1_heap_snapshot.html#aeaa6073009e4041839dff7a860d2548a',1,'v8::HeapSnapshot::Delete()']]], ['deleteallheapsnapshots',['DeleteAllHeapSnapshots',['../classv8_1_1_heap_profiler.html#a6a75bcc6d8350858597b6a6ce5e349a2',1,'v8::HeapProfiler']]], ['deoptimizeall',['DeoptimizeAll',['../classv8_1_1_testing.html#ae541bd8d75667db1d83c8aef7f8c1cf3',1,'v8::Testing']]], ['detachglobal',['DetachGlobal',['../classv8_1_1_context.html#a841c7dd92eb8c57df92a268a164dea97',1,'v8::Context']]], ['dispose',['Dispose',['../classv8_1_1_retained_object_info.html#a5011203f7c5949049ba36b8059f03eca',1,'v8::RetainedObjectInfo::Dispose()'],['../classv8_1_1_string_1_1_external_string_resource_base.html#af4720342ae31e1ab4656df3f15d069c0',1,'v8::String::ExternalStringResourceBase::Dispose()'],['../classv8_1_1_isolate.html#a1a5a5762e4221aff8c6b10f9e3cec0af',1,'v8::Isolate::Dispose()'],['../classv8_1_1_v8.html#a566450d632c0a63770682b9da3cae08d',1,'v8::V8::Dispose()']]] ];
/************************************************************* * * MathJax/localization/cdo/TeX.js * * Copyright (c) 2009-2016 The MathJax Consortium * * 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. * */ MathJax.Localization.addTranslation("cdo","TeX",{ version: "2.7.2", isLoaded: true, strings: { } }); MathJax.Ajax.loadComplete("[MathJax]/localization/cdo/TeX.js");
var should = require('should'), rewire = require('rewire'), configUtils = require('../../../../test/utils/configUtils'), // Stuff we are testing ampContentHelper = rewire('../lib/helpers/amp_content'); // TODO: Amperize really needs to get stubbed, so we can test returning errors // properly and make this test faster! describe('{{amp_content}} helper', function () { afterEach(function () { ampContentHelper.__set__('amperizeCache', {}); }); it('can render content', function (done) { var testData = { html: 'Hello World', updated_at: 'Wed Jul 27 2016 18:17:22 GMT+0200 (CEST)', id: 1 }, ampResult = ampContentHelper.call(testData); ampResult.then(function (rendered) { should.exist(rendered); rendered.string.should.equal(testData.html); done(); }).catch(done); }); it('returns if no html is provided', function (done) { var testData = { updated_at: 'Wed Jul 27 2016 18:17:22 GMT+0200 (CEST)', id: 1 }, ampResult = ampContentHelper.call(testData); ampResult.then(function (rendered) { should.exist(rendered); rendered.string.should.be.equal(''); done(); }).catch(done); }); describe('Cache', function () { it('can render content from cache', function (done) { var testData = { html: 'Hello World', updated_at: 'Wed Jul 27 2016 18:17:22 GMT+0200 (CEST)', id: 1 }, ampCachedResult, ampResult = ampContentHelper.call(testData), amperizeCache = ampContentHelper.__get__('amperizeCache'); ampResult.then(function (rendered) { should.exist(rendered); should.exist(amperizeCache); rendered.string.should.equal(testData.html); amperizeCache[1].should.have.property('updated_at', 'Wed Jul 27 2016 18:17:22 GMT+0200 (CEST)'); amperizeCache[1].should.have.property('amp', testData.html); // call it again, to make it fetch from cache ampCachedResult = ampContentHelper.call(testData); ampCachedResult.then(function (rendered) { should.exist(rendered); should.exist(amperizeCache); amperizeCache[1].should.have.property('updated_at', 'Wed Jul 27 2016 18:17:22 GMT+0200 (CEST)'); amperizeCache[1].should.have.property('amp', testData.html); done(); }); }).catch(done); }); it('fetches new AMP HTML if post was changed', function (done) { var testData1 = { html: 'Hello World', updated_at: 'Wed Jul 27 2016 18:17:22 GMT+0200 (CEST)', id: 1 }, testData2 = { html: 'Hello Ghost', updated_at: 'Wed Jul 30 2016 18:17:22 GMT+0200 (CEST)', id: 1 }, ampResult = ampContentHelper.call(testData1), amperizeCache = ampContentHelper.__get__('amperizeCache'); ampResult.then(function (rendered) { should.exist(rendered); should.exist(amperizeCache); rendered.string.should.equal(testData1.html); amperizeCache[1].should.have.property('updated_at', 'Wed Jul 27 2016 18:17:22 GMT+0200 (CEST)'); amperizeCache[1].should.have.property('amp', testData1.html); // call it again with different values to fetch from Amperize and not from cache ampResult = ampContentHelper.call(testData2); ampResult.then(function (rendered) { should.exist(rendered); should.exist(amperizeCache); // it should not have the old value, amperizeCache[1].should.not.have.property('Wed Jul 30 2016 18:17:22 GMT+0200 (CEST)'); // only the new one rendered.string.should.equal(testData2.html); amperizeCache[1].should.have.property('updated_at', 'Wed Jul 30 2016 18:17:22 GMT+0200 (CEST)'); amperizeCache[1].should.have.property('amp', testData2.html); done(); }); }).catch(done); }); }); describe('Transforms and sanitizes HTML', function () { beforeEach(function () { configUtils.set({url: 'https://blog.ghost.org/'}); }); afterEach(function () { ampContentHelper.__set__('amperizeCache', {}); configUtils.restore(); }); it('can transform img tags to amp-img', function (done) { var testData = { html: '<img src="/content/images/2016/08/scheduled2-1.jpg" alt="The Ghost Logo" />', updated_at: 'Wed Jul 27 2016 18:17:22 GMT+0200 (CEST)', id: 1 }, expectedResult = '<amp-img src="https://blog.ghost.org/content/images/2016/08/scheduled2-1.jpg" alt="The Ghost Logo" width="1000" height="281" layout="responsive"></amp-img>', ampResult = ampContentHelper.call(testData); ampResult.then(function (rendered) { should.exist(rendered); rendered.string.should.equal(expectedResult); done(); }).catch(done); }); it('can transform audio tags to amp-audio', function (done) { var testData = { html: '<audio controls="controls" width="auto" height="50" autoplay="mobile">Your browser does not support the <code>audio</code> element.<source src="https://audio.com/foo.wav" type="audio/wav"></audio>' + '<audio src="http://audio.com/foo.ogg"><track kind="captions" src="http://audio.com/foo.en.vtt" srclang="en" label="English"><source kind="captions" src="http://audio.com/foo.sv.vtt" srclang="sv" label="Svenska"></audio>', updated_at: 'Wed Jul 27 2016 18:17:22 GMT+0200 (CEST)', id: 1 }, expectedResult = '<amp-audio controls="controls" width="auto" height="50" autoplay="mobile">Your browser does not support the <code>audio</code> element.<source src="https://audio.com/foo.wav" type="audio/wav" /></amp-audio>' + '<amp-audio src="https://audio.com/foo.ogg"><track kind="captions" src="https://audio.com/foo.en.vtt" srclang="en" label="English" /><source kind="captions" src="https://audio.com/foo.sv.vtt" srclang="sv" label="Svenska" /></amp-audio>', ampResult = ampContentHelper.call(testData); ampResult.then(function (rendered) { should.exist(rendered); rendered.string.should.equal(expectedResult); done(); }).catch(done); }); it('removes video tags including source children', function (done) { var testData = { html: '<video width="480" controls poster="https://archive.org/download/WebmVp8Vorbis/webmvp8.gif" >' + '<track kind="captions" src="https://archive.org/download/WebmVp8Vorbis/webmvp8.webm" srclang="en">' + '<source src="https://archive.org/download/WebmVp8Vorbis/webmvp8.webm" type="video/webm">' + '<source src="https://archive.org/download/WebmVp8Vorbis/webmvp8_512kb.mp4" type="video/mp4">' + 'Your browser doesn\'t support HTML5 video tag.' + '</video>', updated_at: 'Wed Jul 27 2016 18:17:22 GMT+0200 (CEST)', id: 1 }, expectedResult = 'Your browser doesn\'t support HTML5 video tag.', ampResult = ampContentHelper.call(testData); ampResult.then(function (rendered) { should.exist(rendered); rendered.string.should.equal(expectedResult); done(); }).catch(done); }); it('removes inline style', function (done) { var testData = { html: '<amp-img src="/content/images/2016/08/aileen_small.jpg" style="border-radius: 50%"; !important' + 'border="0" align="center" font="Arial" width="50" height="50" layout="responsive"></amp-img>' + '<p align="right" style="color: red; !important" bgcolor="white">Hello</p>' + '<table style="width:100%"><tr bgcolor="tomato" colspan="2"><th font="Arial">Name:</th> ' + '<td color="white" colspan="2">Bill Gates</td></tr><tr><th rowspan="2" valign="center">Telephone:</th> ' + '<td>55577854</td></tr></table>', updated_at: 'Wed Jul 27 2016 18:17:22 GMT+0200 (CEST)', id: 1 }, expectedResult = '<amp-img src="https://blog.ghost.org/content/images/2016/08/aileen_small.jpg" width="50" ' + 'height="50" layout="responsive"></amp-img><p align="right">Hello</p>' + '<table><tr bgcolor="tomato"><th>Name:</th> ' + '<td colspan="2">Bill Gates</td></tr><tr><th rowspan="2" valign="center">Telephone:</th> ' + '<td>55577854</td></tr></table>', ampResult = ampContentHelper.call(testData); ampResult.then(function (rendered) { should.exist(rendered); rendered.string.should.equal(expectedResult); done(); }).catch(done); }); it('removes prohibited iframe attributes', function (done) { var testData = { html: '<iframe src="https://player.vimeo.com/video/180069681?color=ffffff" width="640" height="267" frameborder="0" ' + 'webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>', updated_at: 'Wed Jul 27 2016 18:17:22 GMT+0200 (CEST)', id: 1 }, expectedResult = '<amp-iframe src="https://player.vimeo.com/video/180069681?color=ffffff" width="640" height="267" ' + 'frameborder="0" allowfullscreen sandbox="allow-scripts allow-same-origin" layout="responsive"></amp-iframe>', ampResult = ampContentHelper.call(testData); ampResult.then(function (rendered) { should.exist(rendered); rendered.string.should.equal(expectedResult); done(); }).catch(done); }); it('can handle incomplete HTML tags by returning not Amperized HTML', function (done) { var testData = { html: '<img><///img>', updated_at: 'Wed Jul 27 2016 18:17:22 GMT+0200 (CEST)', id: 1 }, ampResult = ampContentHelper.call(testData), sanitizedHTML, ampedHTML; ampResult.then(function (rendered) { sanitizedHTML = ampContentHelper.__get__('cleanHTML'); ampedHTML = ampContentHelper.__get__('ampHTML'); should.exist(rendered); rendered.string.should.equal(''); should.exist(ampedHTML); ampedHTML.should.be.equal('<img>'); should.exist(sanitizedHTML); sanitizedHTML.should.be.equal(''); done(); }).catch(done); }); it('can handle not existing img src by returning not Amperized HTML', function (done) { var testData = { html: '<img src="/content/images/does-not-exist.jpg" alt="The Ghost Logo" />', updated_at: 'Wed Jul 27 2016 18:17:22 GMT+0200 (CEST)', id: 1 }, ampResult = ampContentHelper.call(testData), sanitizedHTML, ampedHTML; ampResult.then(function (rendered) { sanitizedHTML = ampContentHelper.__get__('cleanHTML'); ampedHTML = ampContentHelper.__get__('ampHTML'); should.exist(rendered); rendered.string.should.equal(''); should.exist(ampedHTML); ampedHTML.should.be.equal('<img src="https://blog.ghost.org/content/images/does-not-exist.jpg" alt="The Ghost Logo">'); should.exist(sanitizedHTML); sanitizedHTML.should.be.equal(''); done(); }).catch(done); }); it('sanitizes remaining and not valid tags', function (done) { var testData = { html: '<form<input type="text" placeholder="Hi AMP tester"></form>' + '<script>some script here</script>' + '<style> h1 {color:red;} p {color:blue;}</style>', updated_at: 'Wed Jul 27 2016 18:17:22 GMT+0200 (CEST)', id: 1 }, ampResult = ampContentHelper.call(testData); ampResult.then(function (rendered) { should.exist(rendered); rendered.string.should.be.equal(''); done(); }).catch(done); }); }); });
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'pastetext', 'el', { button: 'Επικόλληση ως απλό κείμενο', title: 'Επικόλληση ως απλό κείμενο' } );
/** * Prev Rollover * (c) 2013 Bill, BunKat LLC. * * Determines if a value will cause a particualr constraint to rollover to the * previous largest time period. Used primarily when a constraint has a * variable extent. * * Later is freely distributable under the MIT license. * For all details and documentation: * http://github.com/bunkat/later */ later.date.prevRollover = function(d, val, constraint, period) { var cur = constraint.val(d); return (val >= cur || !val) ? period.start(period.prev(d, period.val(d)-1)) : period.start(d); };
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v10.1.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var component_1 = require("../widgets/component"); var componentAnnotations_1 = require("../widgets/componentAnnotations"); var context_1 = require("../context/context"); var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var utils_1 = require("../utils"); var DEFAULT_TRANSLATIONS = { equals: 'Equals', notEqual: 'Not equal', lessThan: 'Less than', greaterThan: 'Greater than', inRange: 'In range', lessThanOrEqual: 'Less than or equals', greaterThanOrEqual: 'Greater than or equals', filterOoo: 'Filter...', contains: 'Contains', notContains: 'Not contains', startsWith: 'Starts with', endsWith: 'Ends with', searchOoo: 'Search...', selectAll: 'Select All', applyFilter: 'Apply Filter', clearFilter: 'Clear Filter' }; /** * T(ype) The type of this filter. ie in DateFilter T=Date * P(arams) The params that this filter can take * M(model getModel/setModel) The object that this filter serializes to * F Floating filter params * * Contains common logic to ALL filters.. Translation, apply and clear button * get/setModel context wiring.... */ var BaseFilter = (function (_super) { __extends(BaseFilter, _super); function BaseFilter() { return _super !== null && _super.apply(this, arguments) || this; } BaseFilter.prototype.init = function (params) { this.filterParams = params; this.defaultFilter = this.filterParams.defaultOption; if (this.filterParams.filterOptions) { if (this.filterParams.filterOptions.lastIndexOf(BaseFilter.EQUALS) < 0) { this.defaultFilter = this.filterParams.filterOptions[0]; } } this.customInit(); this.filter = this.defaultFilter; this.clearActive = params.clearButton === true; //Allowing for old param property apply, even though is not advertised through the interface this.applyActive = ((params.applyButton === true) || (params.apply === true)); this.newRowsActionKeep = params.newRowsAction === 'keep'; this.setTemplate(this.generateTemplate()); utils_1._.setVisible(this.eApplyButton, this.applyActive); if (this.applyActive) { this.addDestroyableEventListener(this.eApplyButton, "click", this.filterParams.filterChangedCallback); } utils_1._.setVisible(this.eClearButton, this.clearActive); if (this.clearActive) { this.addDestroyableEventListener(this.eClearButton, "click", this.onClearButton.bind(this)); } var anyButtonVisible = this.applyActive || this.clearActive; utils_1._.setVisible(this.eButtonsPanel, anyButtonVisible); this.instantiate(this.context); this.initialiseFilterBodyUi(); this.refreshFilterBodyUi(); }; BaseFilter.prototype.onClearButton = function () { this.setModel(null); this.onFilterChanged(); }; BaseFilter.prototype.floatingFilter = function (from) { if (from !== '') { var model = this.modelFromFloatingFilter(from); this.setModel(model); } else { this.resetState(); } this.onFilterChanged(); }; BaseFilter.prototype.onNewRowsLoaded = function () { if (!this.newRowsActionKeep) { this.resetState(); } }; BaseFilter.prototype.getModel = function () { if (this.isFilterActive()) { return this.serialize(); } else { return null; } }; BaseFilter.prototype.getNullableModel = function () { return this.serialize(); }; BaseFilter.prototype.setModel = function (model) { if (model) { this.parse(model); } else { this.resetState(); } this.refreshFilterBodyUi(); }; BaseFilter.prototype.doOnFilterChanged = function (applyNow) { if (applyNow === void 0) { applyNow = false; } this.filterParams.filterModifiedCallback(); var requiresApplyAndIsApplying = this.applyActive && applyNow; var notRequiresApply = !this.applyActive; var shouldFilter = notRequiresApply || requiresApplyAndIsApplying; if (shouldFilter) { this.filterParams.filterChangedCallback(); } this.refreshFilterBodyUi(); return shouldFilter; }; BaseFilter.prototype.onFilterChanged = function () { this.doOnFilterChanged(); }; BaseFilter.prototype.onFloatingFilterChanged = function (change) { //It has to be of the type FloatingFilterWithApplyChange if it gets here var casted = change; this.setModel(casted ? casted.model : null); return this.doOnFilterChanged(casted ? casted.apply : false); }; BaseFilter.prototype.generateFilterHeader = function () { return ''; }; BaseFilter.prototype.generateTemplate = function () { var translate = this.translate.bind(this); var body = this.bodyTemplate(); return "<div>\n " + this.generateFilterHeader() + "\n " + body + "\n <div class=\"ag-filter-apply-panel\" id=\"applyPanel\">\n <button type=\"button\" id=\"clearButton\">" + translate('clearFilter') + "</button>\n <button type=\"button\" id=\"applyButton\">" + translate('applyFilter') + "</button>\n </div>\n </div>"; }; BaseFilter.prototype.translate = function (toTranslate) { var translate = this.gridOptionsWrapper.getLocaleTextFunc(); return translate(toTranslate, DEFAULT_TRANSLATIONS[toTranslate]); }; return BaseFilter; }(component_1.Component)); BaseFilter.EQUALS = 'equals'; BaseFilter.NOT_EQUAL = 'notEqual'; BaseFilter.LESS_THAN = 'lessThan'; BaseFilter.LESS_THAN_OR_EQUAL = 'lessThanOrEqual'; BaseFilter.GREATER_THAN = 'greaterThan'; BaseFilter.GREATER_THAN_OR_EQUAL = 'greaterThanOrEqual'; BaseFilter.IN_RANGE = 'inRange'; BaseFilter.CONTAINS = 'contains'; //1; BaseFilter.NOT_CONTAINS = 'notContains'; //1; BaseFilter.STARTS_WITH = 'startsWith'; //4; BaseFilter.ENDS_WITH = 'endsWith'; //5; __decorate([ componentAnnotations_1.QuerySelector('#applyPanel'), __metadata("design:type", HTMLElement) ], BaseFilter.prototype, "eButtonsPanel", void 0); __decorate([ componentAnnotations_1.QuerySelector('#applyButton'), __metadata("design:type", HTMLElement) ], BaseFilter.prototype, "eApplyButton", void 0); __decorate([ componentAnnotations_1.QuerySelector('#clearButton'), __metadata("design:type", HTMLElement) ], BaseFilter.prototype, "eClearButton", void 0); __decorate([ context_1.Autowired('context'), __metadata("design:type", context_1.Context) ], BaseFilter.prototype, "context", void 0); __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], BaseFilter.prototype, "gridOptionsWrapper", void 0); exports.BaseFilter = BaseFilter; /** * Every filter with a dropdown where the user can specify a comparing type against the filter values */ var ComparableBaseFilter = (function (_super) { __extends(ComparableBaseFilter, _super); function ComparableBaseFilter() { return _super !== null && _super.apply(this, arguments) || this; } ComparableBaseFilter.prototype.init = function (params) { _super.prototype.init.call(this, params); this.addDestroyableEventListener(this.eTypeSelector, "change", this.onFilterTypeChanged.bind(this)); }; ComparableBaseFilter.prototype.customInit = function () { if (!this.defaultFilter) { this.defaultFilter = this.getDefaultType(); } }; ComparableBaseFilter.prototype.generateFilterHeader = function () { var _this = this; var defaultFilterTypes = this.getApplicableFilterTypes(); var restrictedFilterTypes = this.filterParams.filterOptions; var actualFilterTypes = restrictedFilterTypes ? restrictedFilterTypes : defaultFilterTypes; var optionsHtml = actualFilterTypes.map(function (filterType) { var localeFilterName = _this.translate(filterType); return "<option value=\"" + filterType + "\">" + localeFilterName + "</option>"; }); var readOnly = optionsHtml.length == 1 ? 'disabled' : ''; return optionsHtml.length <= 0 ? '' : "<div>\n <select class=\"ag-filter-select\" id=\"filterType\" " + readOnly + ">\n " + optionsHtml.join('') + "\n </select>\n </div>"; }; ComparableBaseFilter.prototype.initialiseFilterBodyUi = function () { this.setFilterType(this.filter); }; ComparableBaseFilter.prototype.onFilterTypeChanged = function () { this.filter = this.eTypeSelector.value; this.refreshFilterBodyUi(); this.onFilterChanged(); }; ComparableBaseFilter.prototype.isFilterActive = function () { var rawFilterValues = this.filterValues(); if (this.filter === BaseFilter.IN_RANGE) { var filterValueArray = rawFilterValues; return filterValueArray[0] != null && filterValueArray[1] != null; } else { return rawFilterValues != null; } }; ComparableBaseFilter.prototype.setFilterType = function (filterType) { this.filter = filterType; this.eTypeSelector.value = filterType; }; return ComparableBaseFilter; }(BaseFilter)); __decorate([ componentAnnotations_1.QuerySelector('#filterType'), __metadata("design:type", HTMLSelectElement) ], ComparableBaseFilter.prototype, "eTypeSelector", void 0); exports.ComparableBaseFilter = ComparableBaseFilter; /** * Comparable filter with scalar underlying values (ie numbers and dates. Strings are not scalar so have to extend * ComparableBaseFilter) */ var ScalarBaseFilter = (function (_super) { __extends(ScalarBaseFilter, _super); function ScalarBaseFilter() { return _super !== null && _super.apply(this, arguments) || this; } ScalarBaseFilter.prototype.getDefaultType = function () { return BaseFilter.EQUALS; }; ScalarBaseFilter.prototype.doesFilterPass = function (params) { var value = this.filterParams.valueGetter(params.node); var comparator = this.comparator(); var rawFilterValues = this.filterValues(); var from = Array.isArray(rawFilterValues) ? rawFilterValues[0] : rawFilterValues; if (from == null) return true; var compareResult = comparator(from, value); if (this.filter === BaseFilter.EQUALS) { return compareResult === 0; } if (this.filter === BaseFilter.GREATER_THAN) { return compareResult > 0; } if (this.filter === BaseFilter.GREATER_THAN_OR_EQUAL) { return compareResult >= 0 && (value != null); } if (this.filter === BaseFilter.LESS_THAN_OR_EQUAL) { return compareResult <= 0 && (value != null); } if (this.filter === BaseFilter.LESS_THAN) { return compareResult < 0; } if (this.filter === BaseFilter.NOT_EQUAL) { return compareResult != 0; } //From now on the type is a range and rawFilterValues must be an array! var compareToResult = comparator(rawFilterValues[1], value); if (this.filter === BaseFilter.IN_RANGE) { if (!this.filterParams.inRangeInclusive) { return compareResult > 0 && compareToResult < 0; } else { return compareResult >= 0 && compareToResult <= 0; } } throw new Error('Unexpected type of date filter!: ' + this.filter); }; return ScalarBaseFilter; }(ComparableBaseFilter)); exports.ScalarBaseFilter = ScalarBaseFilter;
export function foo4() {}; export const { a: [{ foo4: foo }], b, c: { foo2: [{ foo3: foo4 }] } } = bar;
Meteor.methods({ getStatistics(refresh) { if (!Meteor.userId()) { throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getStatistics' }); } if (RocketChat.authz.hasPermission(Meteor.userId(), 'view-statistics') !== true) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'getStatistics' }); } if (refresh) { return RocketChat.statistics.save(); } else { return RocketChat.models.Statistics.findLast(); } } });