code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
/**
* @license
* Copyright Google LLC 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
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
global.ng = global.ng || {};
global.ng.common = global.ng.common || {};
global.ng.common.locales = global.ng.common.locales || {};
const u = undefined;
function plural(n) {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length;
if (i === 1 && v === 0) return 1;
return 5;
}
global.ng.common.locales['en-be'] = [
'en-BE',
[['a', 'p'], ['am', 'pm'], u],
[['am', 'pm'], u, u],
[
['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
],
u,
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
[
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
'October', 'November', 'December'
]
],
u,
[['B', 'A'], ['BC', 'AD'], ['Before Christ', 'Anno Domini']],
1,
[6, 0],
['dd/MM/yy', 'dd MMM y', 'd MMMM y', 'EEEE, d MMMM y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'],
['{1}, {0}', u, '{1} \'at\' {0}', u],
[',', '.', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '#,##0.00 ¤', '#E0'],
'EUR',
'€',
'Euro',
{'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']},
'ltr',
plural,
[
[
['mi', 'n', 'in the morning', 'in the afternoon', 'in the evening', 'at night'],
['midnight', 'noon', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], u
],
[['midnight', 'noon', 'morning', 'afternoon', 'evening', 'night'], u, u],
[
'00:00', '12:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'],
['21:00', '06:00']
]
]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window);
| wKoza/angular | packages/common/locales/global/en-BE.js | JavaScript | mit | 2,279 |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const minimist = require('minimist');
const runESLint = require('../eslint');
console.log('Linting changed files...');
const cliOptions = minimist(process.argv.slice(2));
if (runESLint({onlyChanged: true, ...cliOptions})) {
console.log('Lint passed for changed files.');
} else {
console.log('Lint failed for changed files.');
process.exit(1);
}
| cpojer/react | scripts/tasks/linc.js | JavaScript | mit | 559 |
/*!
* ScrollMagic v2.0.6 (2018-10-08)
* The javascript library for magical scroll interactions.
* (c) 2018 Jan Paepke (@janpaepke)
* Project Website: http://scrollmagic.io
*
* @version 2.0.6
* @license Dual licensed under MIT license and GPL.
* @author Jan Paepke - e-mail@janpaepke.de
*
* @file ScrollMagic Velocity Animation Plugin.
*
* requires: velocity ~1.2
* Powered by VelocityJS: http://VelocityJS.org
* Velocity is published under MIT license.
*/
/**
* This plugin is meant to be used in conjunction with the Velocity animation framework.
* It offers an easy API to __trigger__ Velocity animations.
*
* With the current version of Velocity scrollbound animations (scenes with duration) are not supported.
* This feature will be added as soon as Velocity provides the appropriate API.
*
* To have access to this extension, please include `plugins/animation.velocity.js`.
* @requires {@link http://julian.com/research/velocity/|Velocity ~1.2.0}
* @mixin animation.Velocity
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ScrollMagic', 'velocity'], factory);
} else if (typeof exports === 'object') {
// CommonJS
factory(require('scrollmagic'), require('velocity'));
} else {
// Browser globals
factory(root.ScrollMagic || (root.jQuery && root.jQuery.ScrollMagic), root.Velocity || (root.jQuery && root.jQuery.Velocity));
}
}(this, function (ScrollMagic, velocity) {
"use strict";
var NAMESPACE = "animation.velocity";
var
console = window.console || {},
err = Function.prototype.bind.call(console.error || console.log ||
function () {}, console);
if (!ScrollMagic) {
err("(" + NAMESPACE + ") -> ERROR: The ScrollMagic main module could not be found. Please make sure it's loaded before this plugin or use an asynchronous loader like requirejs.");
}
if (!velocity) {
err("(" + NAMESPACE + ") -> ERROR: Velocity could not be found. Please make sure it's loaded before ScrollMagic or use an asynchronous loader like requirejs.");
}
var autoindex = 0;
ScrollMagic.Scene.extend(function () {
var
Scene = this,
_util = ScrollMagic._util,
_currentProgress = 0,
_elems, _properties, _options, _dataID; // used to identify element data related to this scene, will be defined everytime a new velocity animation is added
var log = function () {
if (Scene._log) { // not available, when main source minified
Array.prototype.splice.call(arguments, 1, 0, "(" + NAMESPACE + ")", "->");
Scene._log.apply(this, arguments);
}
};
// set listeners
Scene.on("progress.plugin_velocity", function () {
updateAnimationProgress();
});
Scene.on("destroy.plugin_velocity", function (e) {
Scene.off("*.plugin_velocity");
Scene.removeVelocity(e.reset);
});
var animate = function (elem, properties, options) {
if (_util.type.Array(elem)) {
elem.forEach(function (elem) {
animate(elem, properties, options);
});
} else {
// set reverse values
if (!velocity.Utilities.data(elem, _dataID)) {
velocity.Utilities.data(elem, _dataID, {
reverseProps: _util.css(elem, Object.keys(_properties))
});
}
// animate
velocity(elem, properties, options);
if (options.queue !== undefined) {
velocity.Utilities.dequeue(elem, options.queue);
}
}
};
var reverse = function (elem, options) {
if (_util.type.Array(elem)) {
elem.forEach(function (elem) {
reverse(elem, options);
});
} else {
var data = velocity.Utilities.data(elem, _dataID);
if (data && data.reverseProps) {
velocity(elem, data.reverseProps, options);
if (options.queue !== undefined) {
velocity.Utilities.dequeue(elem, options.queue);
}
}
}
};
/**
* Update the tween progress to current position.
* @private
*/
var updateAnimationProgress = function () {
if (_elems) {
var progress = Scene.progress();
if (progress != _currentProgress) { // do we even need to update the progress?
if (Scene.duration() === 0) {
// play the animation
if (progress > 0) { // play forward
animate(_elems, _properties, _options);
} else { // play reverse
reverse(_elems, _options);
// velocity(_elems, _propertiesReverse, _options);
// velocity("reverse");
}
} else {
// TODO: Scrollbound animations not supported yet...
}
_currentProgress = progress;
}
}
};
/**
* Add a Velocity animation to the scene.
* The method accepts the same parameters as Velocity, with the first parameter being the target element.
*
* To gain better understanding, check out the [Velocity example](../examples/basic/simple_velocity.html).
* @memberof! animation.Velocity#
*
* @example
* // trigger a Velocity animation
* scene.setVelocity("#myElement", {opacity: 0.5}, {duration: 1000, easing: "linear"});
*
* @param {(object|string)} elems - One or more Dom Elements or a Selector that should be used as the target of the animation.
* @param {object} properties - The CSS properties that should be animated.
* @param {object} options - Options for the animation, like duration or easing.
* @returns {Scene} Parent object for chaining.
*/
Scene.setVelocity = function (elems, properties, options) {
if (_elems) { // kill old ani?
Scene.removeVelocity();
}
_elems = _util.get.elements(elems);
_properties = properties || {};
_options = options || {};
_dataID = "ScrollMagic." + NAMESPACE + "[" + (autoindex++) + "]";
if (_options.queue !== undefined) {
// we'll use the queue to identify the animation. When defined it will always stop the previously running one.
// if undefined the animation will always fully run, as is expected.
// defining anything other than 'false' as the que doesn't make much sense, because ScrollMagic takes control over the trigger.
// thus it is also overwritten.
_options.queue = _dataID + "_queue";
}
var checkDuration = function () {
if (Scene.duration() !== 0) {
log(1, "ERROR: The Velocity animation plugin does not support scrollbound animations (scenes with duration) yet.");
}
};
Scene.on("change.plugin_velocity", function (e) {
if (e.what == 'duration') {
checkDuration();
}
});
checkDuration();
log(3, "added animation");
updateAnimationProgress();
return Scene;
};
/**
* Remove the animation from the scene.
* This will stop the scene from triggering the animation.
*
* Using the reset option you can decide if the animation should remain in the current state or be rewound to set the target elements back to the state they were in before the animation was added to the scene.
* @memberof! animation.Velocity#
*
* @example
* // remove the animation from the scene without resetting it
* scene.removeVelocity();
*
* // remove the animation from the scene and reset the elements to initial state
* scene.removeVelocity(true);
*
* @param {boolean} [reset=false] - If `true` the animation will rewound.
* @returns {Scene} Parent object for chaining.
*/
Scene.removeVelocity = function (reset) {
if (_elems) {
// stop running animations
if (_options.queue !== undefined) {
velocity(_elems, "stop", _options.queue);
}
if (reset) {
reverse(_elems, {
duration: 0
});
}
_elems.forEach(function (elem) {
velocity.Utilities.removeData(elem, _dataID);
});
_elems = _properties = _options = _dataID = undefined;
}
return Scene;
};
});
})); | jonobr1/cdnjs | ajax/libs/ScrollMagic/2.0.6/plugins/animation.velocity.js | JavaScript | mit | 7,678 |
'use strict'
var chai = require('chai')
var expect = chai.expect
var helper = require('../../lib/agent_helper')
var ParsedStatement = require('../../../lib/db/parsed-statement')
var Transaction = require('../../../lib/transaction')
function makeSegment(options) {
var segment = options.transaction.trace.root.add('MongoDB/users/find')
segment.setDurationInMillis(options.duration)
segment._setExclusiveDurationInMillis(options.exclusive)
segment.host = 'localhost'
segment.port = 27017
return segment
}
function makeRecorder(model, operation) {
var statement = new ParsedStatement('MongoDB', operation, model)
return statement.recordMetrics.bind(statement)
}
function recordMongoDB(segment, scope) {
makeRecorder('users', 'find')(segment, scope)
}
function record(options) {
if (options.apdexT) options.transaction.metrics.apdexT = options.apdexT
var segment = makeSegment(options)
var transaction = options.transaction
transaction.setName(options.url, options.code)
recordMongoDB(segment, options.transaction.name)
}
describe("record ParsedStatement with MongoDB", function () {
var agent
var trans
beforeEach(function () {
agent = helper.loadMockedAgent()
trans = new Transaction(agent)
})
afterEach(function () {
helper.unloadAgent(agent)
})
describe("when scope is undefined", function () {
var segment
beforeEach(function () {
segment = makeSegment({
transaction : trans,
duration : 0,
exclusive : 0
})
})
it("shouldn't crash on recording", function () {
expect(function () { recordMongoDB(segment, undefined); }).not.throws()
})
it("should record no scoped metrics", function () {
recordMongoDB(segment, undefined)
var result = [
[{name: "Datastore/operation/MongoDB/find"},
[1, 0, 0, 0, 0, 0]],
[{name: "Datastore/allOther"},
[1, 0, 0, 0, 0, 0]],
[{name: "Datastore/MongoDB/allOther"},
[1, 0, 0, 0, 0, 0]],
[{name: "Datastore/MongoDB/all"},
[1, 0, 0, 0, 0, 0]],
[{name: "Datastore/all"},
[1, 0, 0, 0, 0, 0]],
[{name: "Datastore/statement/MongoDB/users/find"},
[1, 0, 0, 0, 0, 0]],
]
expect(JSON.stringify(trans.metrics)).equal(JSON.stringify(result))
})
})
describe("with scope", function () {
it("should record scoped metrics", function () {
record({
transaction : trans,
url : '/test',
code : 200,
apdexT : 10,
duration : 30,
exclusive : 2,
})
var result = [[
{name: 'Datastore/operation/MongoDB/find'},
[1, 0.03, 0.002, 0.03, 0.03, 0.0009]
], [
{name: 'Datastore/allWeb'},
[1, 0.03, 0.002, 0.03, 0.03, 0.0009]
], [
{name: 'Datastore/MongoDB/allWeb'},
[1, 0.03, 0.002, 0.03, 0.03, 0.0009]
], [
{name: 'Datastore/MongoDB/all'},
[1, 0.03, 0.002, 0.03, 0.03, 0.0009]
], [
{name: 'Datastore/all'},
[1, 0.03, 0.002, 0.03, 0.03, 0.0009]
], [
{name: 'Datastore/statement/MongoDB/users/find'},
[1, 0.03, 0.002, 0.03, 0.03, 0.0009]
], [
{name: 'Datastore/statement/MongoDB/users/find', scope: 'WebTransaction/NormalizedUri/*'},
[1, 0.03, 0.002, 0.03, 0.03, 0.0009]
]]
expect(JSON.stringify(trans.metrics)).equal(JSON.stringify(result))
})
})
it("should report exclusive time correctly", function () {
var root = trans.trace.root
, parent = root.add('Datastore/statement/MongoDB/users/find',
makeRecorder('users', 'find'))
, child1 = parent.add('Datastore/statement/MongoDB/users/insert',
makeRecorder('users', 'insert'))
, child2 = child1.add('Datastore/statement/MongoDB/cache/update',
makeRecorder('cache', 'update'))
root.setDurationInMillis( 32, 0)
parent.setDurationInMillis(32, 0)
child1.setDurationInMillis(16, 11)
child2.setDurationInMillis( 5, 2)
var result = [[
{name: 'Datastore/operation/MongoDB/find'},
[1, 0.032, 0.011, 0.032, 0.032, 0.001024]
], [
{name: 'Datastore/allOther'},
[3, 0.053, 0.027, 0.005, 0.032, 0.001305]
], [
{name: 'Datastore/MongoDB/allOther'},
[3, 0.053, 0.027, 0.005, 0.032, 0.001305]
], [
{name: 'Datastore/MongoDB/all'},
[3, 0.053, 0.027, 0.005, 0.032, 0.001305]
], [
{name: 'Datastore/all'},
[3, 0.053, 0.027, 0.005, 0.032, 0.001305]
], [
{name: 'Datastore/statement/MongoDB/users/find'},
[1, 0.032, 0.011, 0.032, 0.032, 0.001024]
], [
{name: 'Datastore/operation/MongoDB/insert'},
[1, 0.016, 0.011, 0.016, 0.016, 0.000256]
], [
{name: 'Datastore/statement/MongoDB/users/insert'},
[1, 0.016, 0.011, 0.016, 0.016, 0.000256]
], [
{name: 'Datastore/operation/MongoDB/update'},
[1, 0.005, 0.005, 0.005, 0.005, 0.000025]
], [
{name: 'Datastore/statement/MongoDB/cache/update'},
[1, 0.005, 0.005, 0.005, 0.005, 0.000025]
]]
trans.end(function(){
expect(JSON.stringify(trans.metrics)).equal(JSON.stringify(result))
})
})
})
| allspiritseve/mindlikewater | node_modules/newrelic/test/unit/metrics-recorder/mongodb.test.js | JavaScript | mit | 5,306 |
/*
#########################################################################
#
# Copyright (C) 2019 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
*/
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import HoverPaper from '../../atoms/hover-paper';
import styles from './styles';
import actions from './actions';
const mapStateToProps = (state) => ({
interval: state.interval.interval,
response: state.geonodeAverageResponse.response,
timestamp: state.interval.timestamp,
uptime: state.uptime.response,
});
@connect(mapStateToProps, actions)
class Uptime extends React.Component {
static propTypes = {
get: PropTypes.func.isRequired,
interval: PropTypes.number,
reset: PropTypes.func.isRequired,
style: PropTypes.object,
timestamp: PropTypes.instanceOf(Date),
uptime: PropTypes.object,
}
constructor(props) {
super(props);
this.get = () => {
this.props.get();
};
}
componentWillMount() {
this.get();
}
render() {
const style = {
...styles.content,
...this.props.style,
};
let uptime = 0;
if (this.props.uptime && this.props.uptime.data) {
const data = this.props.uptime.data.data;
if (data.length > 0) {
if (data[0].data.length > 0) {
const metric = data[0].data[0];
uptime = Math.floor(Number(metric.max) / (60 * 60 * 24));
}
}
}
return (
<HoverPaper style={style}>
<h3>Uptime</h3>
<span style={styles.stat}>{uptime} days</span>
</HoverPaper>
);
}
}
export default Uptime;
| francbartoli/geonode | geonode/monitoring/frontend/monitoring/src/components/cels/uptime/index.js | JavaScript | gpl-3.0 | 2,298 |
/*
#########################################################################
#
# Copyright (C) 2019 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
*/
import WS_SERVICE_DATA from './constants';
export default function wsServiceData(
state = { status: 'initial' },
action,
) {
switch (action.type) {
case WS_SERVICE_DATA:
return action.payload;
default:
return state;
}
}
| tomkralidis/geonode | geonode/monitoring/frontend/monitoring/src/components/cels/ws-data/reducers.js | JavaScript | gpl-3.0 | 1,070 |
var group__dac__mamp2 =
[
[ "DAC_CR_MAMP2_1", "group__dac__mamp2.html#ga860032e8196838cd36a655c1749139d6", null ],
[ "DAC_CR_MAMP2_10", "group__dac__mamp2.html#ga15719bc54b9efc94588278ab66b083ee", null ],
[ "DAC_CR_MAMP2_11", "group__dac__mamp2.html#gad275a996c8d74c10e9b50391149f2a0a", null ],
[ "DAC_CR_MAMP2_12", "group__dac__mamp2.html#ga7225092211f4ab06244a26bbed4df669", null ],
[ "DAC_CR_MAMP2_2", "group__dac__mamp2.html#ga2147ffa3282e9ff22475e5d6040f269e", null ],
[ "DAC_CR_MAMP2_3", "group__dac__mamp2.html#gaa0fe77a2029873111cbe723a5cba9c57", null ],
[ "DAC_CR_MAMP2_4", "group__dac__mamp2.html#ga63d06c6d19fbaa7035fcebcfc1cce2fb", null ],
[ "DAC_CR_MAMP2_5", "group__dac__mamp2.html#ga831c455497fd93ac644c4c283d3cf53d", null ],
[ "DAC_CR_MAMP2_6", "group__dac__mamp2.html#ga629e22c121da1b9f4aa0ed3e37395619", null ],
[ "DAC_CR_MAMP2_7", "group__dac__mamp2.html#gae506d8258724df4599dadc1943db136f", null ],
[ "DAC_CR_MAMP2_8", "group__dac__mamp2.html#ga1485f0918efb9b01ac1312f5a32b8644", null ],
[ "DAC_CR_MAMP2_9", "group__dac__mamp2.html#ga56e1bc5d1b943cb36431a4e426b3e99d", null ]
]; | Aghosh993/TARS_codebase | libopencm3/doc/stm32l1/html/group__dac__mamp2.js | JavaScript | gpl-3.0 | 1,146 |
class foo extends null {
constructor() {
// If you return an object, we don't care that |this| went
// uninitialized
return {};
}
}
for (let i = 0; i < 1100; i++)
new foo();
if (typeof reportCompare === 'function')
reportCompare(0,0,"OK");
| cstipkovic/spidermonkey-research | js/src/tests/ecma_6/Class/derivedConstructorTDZReturnObject.js | JavaScript | mpl-2.0 | 282 |
var net = require('net'),
tls = require('tls'),
util = require('util'),
dns = require('dns'),
_ = require('lodash'),
winston = require('winston'),
EventBinder = require('./eventbinder.js'),
IrcServer = require('./server.js'),
IrcCommands = require('./commands.js'),
IrcChannel = require('./channel.js'),
IrcUser = require('./user.js'),
EE = require('../ee.js'),
iconv = require('iconv-lite'),
Proxy = require('../proxy.js'),
Socks;
// Break the Node.js version down into usable parts
var version_values = process.version.substr(1).split('.').map(function (item) {
return parseInt(item, 10);
});
// If we have a suitable Nodejs version, bring int he socks functionality
if (version_values[1] >= 10) {
Socks = require('socksjs');
}
var IrcConnection = function (hostname, port, ssl, nick, user, options, state, con_num) {
var that = this;
EE.call(this,{
wildcard: true,
delimiter: ' '
});
this.setMaxListeners(0);
options = options || {};
// Socket state
this.connected = false;
// IRCd write buffers (flood controll)
this.write_buffer = [];
// In process of writing the buffer?
this.writing_buffer = false;
// Max number of lines to write a second
this.write_buffer_lines_second = 2;
// If registeration with the IRCd has completed
this.registered = false;
// If we are in the CAP negotiation stage
this.cap_negotiation = true;
// User information
this.nick = nick;
this.user = user; // Contains users real hostname and address
this.username = this.nick.replace(/[^0-9a-zA-Z\-_.\/]/, '');
this.password = options.password || '';
// Set the passed encoding. or the default if none giving or it fails
if (!options.encoding || !this.setEncoding(options.encoding)) {
this.setEncoding(global.config.default_encoding);
}
// State object
this.state = state;
// Connection ID in the state
this.con_num = con_num;
// IRC protocol handling
this.irc_commands = new IrcCommands(this);
// IrcServer object
this.server = new IrcServer(this, hostname, port);
// IrcUser objects
this.irc_users = Object.create(null);
// TODO: use `this.nick` instead of `'*'` when using an IrcUser per nick
this.irc_users[this.nick] = new IrcUser(this, '*');
// IrcChannel objects
this.irc_channels = Object.create(null);
// IRC connection information
this.irc_host = {hostname: hostname, port: port};
this.ssl = !(!ssl);
// SOCKS proxy details
// TODO: Wildcard matching of hostnames and/or CIDR ranges of IP addresses
if ((global.config.socks_proxy && global.config.socks_proxy.enabled) && ((global.config.socks_proxy.all) || (_.contains(global.config.socks_proxy.proxy_hosts, this.irc_host.hostname)))) {
this.socks = {
host: global.config.socks_proxy.address,
port: global.config.socks_proxy.port,
user: global.config.socks_proxy.user,
pass: global.config.socks_proxy.pass
};
} else {
this.socks = false;
}
// Kiwi proxy info may be set within a server module. {port: 7779, host: 'kiwi.proxy.com', ssl: false}
this.proxy = false;
// Net. interface this connection should be made through
this.outgoing_interface = false;
// Options sent by the IRCd
this.options = Object.create(null);
this.options.PREFIX = [
{symbol: '~', mode: 'q'},
{symbol: '&', mode: 'a'},
{symbol: '@', mode: 'o'},
{symbol: '%', mode: 'h'},
{symbol: '+', mode: 'v'}
];
this.cap = {requested: [], enabled: []};
// Is SASL supported on the IRCd
this.sasl = false;
// Buffers for data sent from the IRCd
this.hold_last = false;
this.held_data = null;
this.applyIrcEvents();
};
util.inherits(IrcConnection, EE);
module.exports.IrcConnection = IrcConnection;
IrcConnection.prototype.applyIrcEvents = function () {
// Listen for events on the IRC connection
this.irc_events = {
'server * connect': onServerConnect,
'channel * join': onChannelJoin,
// TODO: uncomment when using an IrcUser per nick
//'user:*:privmsg': onUserPrivmsg,
'user * nick': onUserNick,
'channel * part': onUserParts,
'channel * quit': onUserParts,
'channel * kick': onUserKick
};
EventBinder.bindIrcEvents('', this.irc_events, this, this);
};
/**
* Start the connection to the IRCd
*/
IrcConnection.prototype.connect = function () {
var that = this;
// The socket connect event to listener for
var socket_connect_event_name = 'connect';
// The destination address
var dest_addr;
if (this.socks) {
dest_addr = this.socks.host;
} else if (this.proxy) {
dest_addr = this.proxy.host;
} else {
dest_addr = this.irc_host.hostname;
}
// Make sure we don't already have an open connection
this.disposeSocket();
// Get the IP family for the dest_addr (either socks or IRCd destination)
getConnectionFamily(dest_addr, function getConnectionFamilyCb(err, family, host) {
var outgoing;
// Decide which net. interface to make the connection through
if (that.outgoing_interface) {
// An specific interface has been given for this connection
outgoing = this.outgoing_interface;
} else if (global.config.outgoing_address) {
// Pick an interface from the config
if ((family === 'IPv6') && (global.config.outgoing_address.IPv6)) {
outgoing = global.config.outgoing_address.IPv6;
} else {
outgoing = global.config.outgoing_address.IPv4 || '0.0.0.0';
// We don't have an IPv6 interface but dest_addr may still resolve to
// an IPv4 address. Reset `host` and try connecting anyway, letting it
// fail if an IPv4 resolved address is not found
host = dest_addr;
}
// If we have an array of interfaces, select a random one
if (typeof outgoing !== 'string' && outgoing.length) {
outgoing = outgoing[Math.floor(Math.random() * outgoing.length)];
}
// Make sure we have a valid interface address
if (typeof outgoing !== 'string')
outgoing = '0.0.0.0';
} else {
// No config was found so use the default
outgoing = '0.0.0.0';
}
// Are we connecting through a SOCKS proxy?
if (that.socks) {
that.socket = Socks.connect({
host: that.irc_host.host,
port: that.irc_host.port,
ssl: that.ssl,
rejectUnauthorized: global.config.reject_unauthorised_certificates
}, {host: host,
port: that.socks.port,
user: that.socks.user,
pass: that.socks.pass,
localAddress: outgoing
});
} else if (that.proxy) {
that.socket = new Proxy.ProxySocket(that.proxy.port, host, {
username: that.username,
interface: that.proxy.interface
}, {ssl: that.proxy.ssl});
if (that.ssl) {
that.socket.connectTls(that.irc_host.port, that.irc_host.hostname);
} else {
that.socket.connect(that.irc_host.port, that.irc_host.hostname);
}
} else {
// No socks connection, connect directly to the IRCd
if (that.ssl) {
that.socket = tls.connect({
host: host,
port: that.irc_host.port,
rejectUnauthorized: global.config.reject_unauthorised_certificates,
localAddress: outgoing
});
// We need the raw socket connect event
that.socket.socket.on('connect', function() { rawSocketConnect.call(that, this); });
socket_connect_event_name = 'secureConnect';
} else {
that.socket = net.connect({
host: host,
port: that.irc_host.port,
localAddress: outgoing
});
}
}
// Apply the socket listeners
that.socket.on(socket_connect_event_name, function socketConnectCb() {
// TLS connections have the actual socket as a property
var is_tls = (typeof this.socket !== 'undefined') ?
true :
false;
// TLS sockets have already called this
if (!is_tls)
rawSocketConnect.call(that, this);
that.connected = true;
socketConnectHandler.call(that);
});
that.socket.on('error', function socketErrorCb(event) {
that.emit('error', event);
});
that.socket.on('data', function () {
socketOnData.apply(that, arguments);
});
that.socket.on('close', function socketCloseCb(had_error) {
that.connected = false;
// Remove this socket form the identd lookup
if (that.identd_port_pair) {
delete global.clients.port_pairs[that.identd_port_pair];
}
that.emit('close');
// Close the whole socket down
that.disposeSocket();
});
});
};
/**
* Send an event to the client
*/
IrcConnection.prototype.clientEvent = function (event_name, data, callback) {
data.server = this.con_num;
this.state.sendIrcCommand(event_name, data, callback);
};
/**
* Write a line of data to the IRCd
* @param data The line of data to be sent
* @param force Write the data now, ignoring any write queue
*/
IrcConnection.prototype.write = function (data, force) {
//ENCODE string to encoding of the server
encoded_buffer = iconv.encode(data + '\r\n', this.encoding);
if (force) {
this.socket.write(encoded_buffer);
return;
}
this.write_buffer.push(encoded_buffer);
// Only flush if we're not writing already
if (!this.writing_buffer)
this.flushWriteBuffer();
};
/**
* Flush the write buffer to the server in a throttled fashion
*/
IrcConnection.prototype.flushWriteBuffer = function () {
// In case the socket closed between writing our queue.. clean up
if (!this.connected) {
this.write_buffer = [];
this.writing_buffer = false;
return;
}
this.writing_buffer = true;
// Disabled write buffer? Send everything we have
if (!this.write_buffer_lines_second) {
this.write_buffer.forEach(function(buffer, idx) {
this.socket.write(buffer);
this.write_buffer = null;
});
this.write_buffer = [];
this.writing_buffer = false;
return;
}
// Nothing to write? Stop writing and leave
if (this.write_buffer.length === 0) {
this.writing_buffer = false;
return;
}
this.socket.write(this.write_buffer[0]);
this.write_buffer = this.write_buffer.slice(1);
// Call this function again at some point if we still have data to write
if (this.write_buffer.length > 0) {
setTimeout(this.flushWriteBuffer.bind(this), 1000 / this.write_buffer_lines_second);
} else {
// No more buffers to write.. so we've finished
this.writing_buffer = false;
}
};
/**
* Close the connection to the IRCd after forcing one last line
*/
IrcConnection.prototype.end = function (data, callback) {
if (!this.socket)
return;
if (data)
this.write(data, true);
this.socket.end();
};
/**
* Clean up this IrcConnection instance and any sockets
*/
IrcConnection.prototype.dispose = function () {
// If we're still connected, wait until the socket is closed before disposing
// so that all the events are still correctly triggered
if (this.socket && this.connected) {
this.end();
return;
}
if (this.socket) {
this.disposeSocket();
}
_.each(this.irc_users, function (user) {
user.dispose();
});
_.each(this.irc_channels, function (chan) {
chan.dispose();
});
this.irc_users = undefined;
this.irc_channels = undefined;
this.server.dispose();
this.server = undefined;
this.irc_commands = undefined;
EventBinder.unbindIrcEvents('', this.irc_events, this);
this.removeAllListeners();
};
/**
* Clean up any sockets for this IrcConnection
*/
IrcConnection.prototype.disposeSocket = function () {
if (this.socket) {
this.socket.end();
this.socket.removeAllListeners();
this.socket = null;
}
};
/**
* Set a new encoding for this connection
* Return true in case of success
*/
IrcConnection.prototype.setEncoding = function (encoding) {
var encoded_test;
try {
encoded_test = iconv.encode("TEST", encoding);
//This test is done to check if this encoding also supports
//the ASCII charset required by the IRC protocols
//(Avoid the use of base64 or incompatible encodings)
if (encoded_test == "TEST") {
this.encoding = encoding;
return true;
}
return false;
} catch (err) {
return false;
}
};
function getConnectionFamily(host, callback) {
if (net.isIP(host)) {
if (net.isIPv4(host)) {
callback(null, 'IPv4', host);
} else {
callback(null, 'IPv6', host);
}
} else {
dns.resolve6(host, function resolve6Cb(err, addresses) {
if (!err) {
callback(null, 'IPv6', addresses[0]);
} else {
dns.resolve4(host, function resolve4Cb(err, addresses) {
if (!err) {
callback(null, 'IPv4',addresses[0]);
} else {
callback(err);
}
});
}
});
}
}
function onChannelJoin(event) {
var chan;
// Only deal with ourselves joining a channel
if (event.nick !== this.nick)
return;
// We should only ever get a JOIN command for a channel
// we're not already a member of.. but check we don't
// have this channel in case something went wrong somewhere
// at an earlier point
if (!this.irc_channels[event.channel]) {
chan = new IrcChannel(this, event.channel);
this.irc_channels[event.channel] = chan;
chan.irc_events.join.call(chan, event);
}
}
function onServerConnect(event) {
this.nick = event.nick;
}
function onUserPrivmsg(event) {
var user;
// Only deal with messages targetted to us
if (event.channel !== this.nick)
return;
if (!this.irc_users[event.nick]) {
user = new IrcUser(this, event.nick);
this.irc_users[event.nick] = user;
user.irc_events.privmsg.call(user, event);
}
}
function onUserNick(event) {
var user;
// Only deal with messages targetted to us
if (event.nick !== this.nick)
return;
this.nick = event.newnick;
}
function onUserParts(event) {
// Only deal with ourselves leaving a channel
if (event.nick !== this.nick)
return;
if (this.irc_channels[event.channel]) {
this.irc_channels[event.channel].dispose();
delete this.irc_channels[event.channel];
}
}
function onUserKick(event){
// Only deal with ourselves being kicked from a channel
if (event.kicked !== this.nick)
return;
if (this.irc_channels[event.channel]) {
this.irc_channels[event.channel].dispose();
delete this.irc_channels[event.channel];
}
}
/**
* When a socket connects to an IRCd
* May be called before any socket handshake are complete (eg. TLS)
*/
var rawSocketConnect = function(socket) {
// Make note of the port numbers for any identd lookups
// Nodejs < 0.9.6 has no socket.localPort so check this first
if (typeof socket.localPort != 'undefined') {
this.identd_port_pair = socket.localPort.toString() + '_' + socket.remotePort.toString();
global.clients.port_pairs[this.identd_port_pair] = this;
}
};
/**
* Handle the socket connect event, starting the IRCd registration
*/
var socketConnectHandler = function () {
var that = this,
connect_data;
// Build up data to be used for webirc/etc detection
connect_data = {
connection: this,
// Array of lines to be sent to the IRCd before anything else
prepend_data: []
};
// Let the webirc/etc detection modify any required parameters
connect_data = findWebIrc.call(this, connect_data);
global.modules.emit('irc authorize', connect_data).done(function ircAuthorizeCb() {
var gecos = '[www.kiwiirc.com] ' + that.nick;
if (global.config.default_gecos) {
gecos = global.config.default_gecos.toString().replace('%n', that.nick);
gecos = gecos.toString().replace('%h', that.user.hostname);
}
// Send any initial data for webirc/etc
if (connect_data.prepend_data) {
_.each(connect_data.prepend_data, function(data) {
that.write(data);
});
}
that.write('CAP LS');
if (that.password)
that.write('PASS ' + that.password);
that.write('NICK ' + that.nick);
that.write('USER ' + that.username + ' 0 0 :' + gecos);
that.emit('connected');
});
};
/**
* Load any WEBIRC or alternative settings for this connection
* Called in scope of the IrcConnection instance
*/
function findWebIrc(connect_data) {
var webirc_pass = global.config.webirc_pass,
ip_as_username = global.config.ip_as_username,
tmp;
// Do we have a WEBIRC password for this?
if (webirc_pass && webirc_pass[this.irc_host.hostname]) {
// Build the WEBIRC line to be sent before IRC registration
tmp = 'WEBIRC ' + webirc_pass[this.irc_host.hostname] + ' KiwiIRC ';
tmp += this.user.hostname + ' ' + this.user.address;
connect_data.prepend_data = [tmp];
}
// Check if we need to pass the users IP as its username/ident
if (ip_as_username && ip_as_username.indexOf(this.irc_host.hostname) > -1) {
// Get a hex value of the clients IP
this.username = this.user.address.split('.').map(function ipSplitMapCb(i, idx){
var hex = parseInt(i, 10).toString(16);
// Pad out the hex value if it's a single char
if (hex.length === 1)
hex = '0' + hex;
return hex;
}).join('');
}
return connect_data;
}
/**
* Buffer any data we get from the IRCd until we have complete lines.
*/
function socketOnData(data) {
var data_pos, // Current position within the data Buffer
line_start = 0,
lines = [],
line = '',
max_buffer_size = 1024; // 1024 bytes is the maximum length of two RFC1459 IRC messages.
// May need tweaking when IRCv3 message tags are more widespread
// Split data chunk into individual lines
for (data_pos = 0; data_pos < data.length; data_pos++) {
if (data[data_pos] === 0x0A) { // Check if byte is a line feed
lines.push(data.slice(line_start, data_pos));
line_start = data_pos + 1;
}
}
// No complete lines of data? Check to see if buffering the data would exceed the max buffer size
if (!lines[0]) {
if ((this.held_data ? this.held_data.length : 0 ) + data.length > max_buffer_size) {
// Buffering this data would exeed our max buffer size
this.emit('error', 'Message buffer too large');
this.socket.destroy();
} else {
// Append the incomplete line to our held_data and wait for more
if (this.held_data) {
this.held_data = Buffer.concat([this.held_data, data], this.held_data.length + data.length);
} else {
this.held_data = data;
}
}
// No complete lines to process..
return;
}
// If we have an incomplete line held from the previous chunk of data
// merge it with the first line from this chunk of data
if (this.hold_last && this.held_data !== null) {
lines[0] = Buffer.concat([this.held_data, lines[0]], this.held_data.length + lines[0].length);
this.hold_last = false;
this.held_data = null;
}
// If the last line of data in this chunk is not complete, hold it so
// it can be merged with the first line from the next chunk
if (line_start < data_pos) {
if ((data.length - line_start) > max_buffer_size) {
// Buffering this data would exeed our max buffer size
this.emit('error', 'Message buffer too large');
this.socket.destroy();
return;
}
this.hold_last = true;
this.held_data = new Buffer(data.length - line_start);
data.copy(this.held_data, 0, line_start);
}
// Process our data line by line
for (i = 0; i < lines.length; i++)
parseIrcLine.call(this, lines[i]);
}
/**
* The regex that parses a line of data from the IRCd
* Deviates from the RFC a little to support the '/' character now used in some
* IRCds
*/
var parse_regex = /^(?:(?:(?:@([^ ]+) )?):(?:([^\s!]+)|([^\s!]+)!([^\s@]+)@?([^\s]+)?) )?(\S+)(?: (?!:)(.+?))?(?: :(.*))?$/i;
function parseIrcLine(buffer_line) {
var msg,
i,
tags = [],
tag,
line = '',
msg_obj;
// Decode server encoding
line = iconv.decode(buffer_line, this.encoding);
if (!line) {
return;
}
// Parse the complete line, removing any carriage returns
msg = parse_regex.exec(line.replace(/^\r+|\r+$/, ''));
if (!msg) {
// The line was not parsed correctly, must be malformed
winston.warn('Malformed IRC line: %s', line.replace(/^\r+|\r+$/, ''));
return;
}
// Extract any tags (msg[1])
if (msg[1]) {
tags = msg[1].split(';');
for (i = 0; i < tags.length; i++) {
tag = tags[i].split('=');
tags[i] = {tag: tag[0], value: tag[1]};
}
}
msg_obj = {
tags: tags,
prefix: msg[2],
nick: msg[3],
ident: msg[4],
hostname: msg[5] || '',
command: msg[6],
params: msg[7] ? msg[7].split(/ +/) : []
};
if (msg[8]) {
msg_obj.params.push(msg[8].trim());
}
this.irc_commands.dispatch(msg_obj.command.toUpperCase(), msg_obj);
}
| spadgos/KiwiIRC | server/irc/connection.js | JavaScript | agpl-3.0 | 23,138 |
module.exports = {
AddressComponents: require('./address-components'),
Campaign: require('./campaign'),
CanonicalAddress: require('./canonical-address'),
CaptchaSolution: require('./captcha-solution'),
Error: require('./error'),
FormElement: require('./form-element'),
Legislator: require('./legislator'),
LegislatorFormElements: require('./legislator-form-elements'),
Message: require('./message'),
MessageSender: require('./message-sender'),
MessageResponse: require('./message-response'),
NgException: require('./ng-exception'),
SubscriptionRequest: require('./subscription-request')
};
| beni55/democracy.io | models/index.js | JavaScript | agpl-3.0 | 616 |
/**
* @license
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('shaka.media.StreamInfoProcessor');
goog.require('shaka.log');
goog.require('shaka.media.PeriodInfo');
goog.require('shaka.media.StreamInfo');
goog.require('shaka.media.StreamSetInfo');
goog.require('shaka.player.Player');
/**
* Creates a StreamInfoProcessor, which chooses the streams that the
* application and browser can support, and sorts StreamInfos.
*
* @constructor
* @struct
*/
shaka.media.StreamInfoProcessor = function() {};
/**
* Processes the given PeriodInfos.
* This function modifies |periodInfos| but does not take ownership of it.
*
* @param {!Array.<shaka.media.PeriodInfo>} periodInfos
*/
shaka.media.StreamInfoProcessor.prototype.process = function(periodInfos) {
this.filterPeriodInfos_(periodInfos);
this.sortStreamSetInfos_(periodInfos);
};
/**
* Removes unsupported StreamInfos from |periodInfos|.
*
* @param {!Array.<!shaka.media.PeriodInfo>} periodInfos
* @private
*/
shaka.media.StreamInfoProcessor.prototype.filterPeriodInfos_ = function(
periodInfos) {
for (var i = 0; i < periodInfos.length; ++i) {
var periodInfo = periodInfos[i];
for (var j = 0; j < periodInfo.streamSetInfos.length; ++j) {
var streamSetInfo = periodInfo.streamSetInfos[j];
this.filterStreamSetInfo_(streamSetInfo);
if (streamSetInfo.streamInfos.length == 0) {
// Drop any StreamSetInfo that is empty.
// An error has already been logged.
periodInfo.streamSetInfos.splice(j, 1);
--j;
}
}
}
};
/**
* Removes any StreamInfo from the given StreamSetInfo that has
* an unsupported MIME type.
*
* @param {!shaka.media.StreamSetInfo} streamSetInfo
* @private
*/
shaka.media.StreamInfoProcessor.prototype.filterStreamSetInfo_ =
function(streamSetInfo) {
// Alias.
var Player = shaka.player.Player;
for (var i = 0; i < streamSetInfo.streamInfos.length; ++i) {
var streamInfo = streamSetInfo.streamInfos[i];
if (!Player.isTypeSupported(streamInfo.getFullMimeType())) {
// Drop the stream if its MIME type is not supported by the browser.
shaka.log.warning('Stream uses an unsupported MIME type.', streamInfo);
streamSetInfo.streamInfos.splice(i, 1);
--i;
}
}
};
/**
* Sorts StreamInfos by bandwidth.
*
* @param {!Array.<!shaka.media.PeriodInfo>} periodInfos
* @private
*/
shaka.media.StreamInfoProcessor.prototype.sortStreamSetInfos_ = function(
periodInfos) {
for (var i = 0; i < periodInfos.length; ++i) {
var periodInfo = periodInfos[i];
for (var j = 0; j < periodInfo.streamSetInfos.length; ++j) {
var streamSetInfo = periodInfo.streamSetInfos[j];
streamSetInfo.streamInfos.sort(
shaka.media.StreamInfoProcessor.compareByBandwidth_);
}
}
};
/**
* Compares two StreamInfos by bandwidth.
*
* @param {!shaka.media.StreamInfo} streamInfo1
* @param {!shaka.media.StreamInfo} streamInfo2
* @return {number}
* @private
*/
shaka.media.StreamInfoProcessor.compareByBandwidth_ = function(
streamInfo1, streamInfo2) {
var b1 = streamInfo1.bandwidth || Number.MAX_VALUE;
var b2 = streamInfo2.bandwidth || Number.MAX_VALUE;
if (b1 < b2) {
return -1;
} else if (b1 > b2) {
return 1;
}
return 0;
};
| sanbornhnewyyz/shaka-player | lib/media/stream_info_processor.js | JavaScript | apache-2.0 | 3,848 |
{
"global" : {
"save" : "Mentés",
"cancel" : "Mégsem",
"delete" : "Törlés",
"required" : "Szükséges",
"download" : "Letöltés",
"link" : "Link",
"bookmark" : "Könyvjelző",
"close" : "Bezár",
"tags" : "Címkék"
},
"tree" : {
"subscribe" : "Feliratkozás",
"import" : "Importálás",
"new_category" : "Új kategória",
"all" : "Összes",
"starred" : "Csillagozott"
},
"subscribe" : {
"feed_url" : "Hírcsatorna URL",
"feed_name" : "Hírcsatorna neve",
"category" : "Kategória"
},
"import" : {
"google_reader_prefix" : "Engedd meg, hogy importáljuk a hírcsatornáidat a ",
"google_reader_suffix" : " fiókjából.",
"google_download" : "Alternatívaként, feltöltheti a subscriptions.xml fájlt.",
"google_download_link" : "Letöltheti innen.",
"xml_file" : "OPML Fájl"
},
"new_category" : {
"name" : "Név",
"parent" : "Szülő"
},
"toolbar" : {
"unread" : "Olvasatlan",
"all" : "Összes",
"previous_entry" : "Előző elem",
"next_entry" : "Következő elem",
"refresh" : "Frissítés",
"refresh_all" : "Force refresh all my feeds ",
"sort_by_asc_desc" : "Rendezés időrend szerint",
"titles_only" : "Csak cím",
"expanded_view" : "Részletes nézet",
"mark_all_as_read" : "Az összes megjelölése olvasottként",
"mark_all_older_12_hours" : "Régebbiek 12 óránál",
"mark_all_older_day" : "Régebbiek, mint egy nap",
"mark_all_older_week" : "Régebbiek, mint egy hét",
"mark_all_older_two_weeks" : "Régebbiek, mint két hét",
"settings" : "Beállítások",
"profile" : "Profil",
"admin" : "Admin",
"about" : "Névjegy",
"logout" : "Kilépés",
"donate" : "Anyagi támogatás "
},
"view" : {
"entry_source" : "forrás",
"entry_author" : "szerző",
"error_while_loading_feed" : "Hiba történt ennek a hírcsatornának a betöltésekor",
"keep_unread" : "Megtartása olvasatlanként",
"no_unread_items" : "nincsen olvasatlan eleme.",
"mark_up_to_here" : "Megjelölés olvasottnak eddig",
"search_for" : "keresés erre: ",
"no_search_results" : "Nem található semmi erre a keresett szóra"
},
"feedsearch" : {
"hint" : "Keressen a hírcsatornák között...",
"help" : "Használja a nyíl billentyűket a navigáláshoz, az enter-t a kiválasztáshoz.",
"result_prefix" : "Az ön feliratkozásai:"
},
"settings" : {
"general" : {
"value" : "Általános",
"language" : "Nyelv",
"language_contribute" : "Segítsen a fordításban",
"show_unread" : "Mutassa azokat a hírcsatornákat és kategóriákat amelyekben nincsen olvasatlan bejegyzés",
"social_buttons" : "Mutassa a közösségi oldalak megosztás gombjait",
"scroll_marks" : "Kiterjesztett nézetben, görgetéssel olvasottként jelöli meg a bejegyzést"
},
"appearance" : "Megjelenés",
"scroll_speed" : "A görgetés sebessége, amikor a cikkek között navigál (miliszekundumban)",
"scroll_speed_help" : "Írjon be 0-át a letiltáshoz",
"theme" : "Téma",
"submit_your_theme" : "Küldje el a témáját",
"custom_css" : "Saját CSS"
},
"details" : {
"feed_details" : "Hírcsatorna részletei",
"url" : "URL",
"website" : "Weboldal",
"name" : "Név",
"category" : "Kategória",
"position" : "Pozició",
"last_refresh" : "Utolsó frissítés",
"message" : "Utolsó frissítési üzenet",
"next_refresh" : "Következő frissítés",
"queued_for_refresh" : "Frissítésre vár",
"feed_url" : "Hírcsatorna URL",
"generate_api_key_first" : "A profiljában először egy API kulcsot kell generálnia.",
"unsubscribe" : "Leiratkozás",
"unsubscribe_confirmation" : "Biztos, hogy le akar iratkozni errről a csatornáról?",
"delete_category_confirmation" : "Biztos, hog törölni akarja ezt a kategóriát?",
"category_details" : "Kategória részletei",
"tag_details" : "Címke részletei",
"parent_category" : "Szülő kategória"
},
"profile" : {
"user_name" : "Felhasználói név",
"email" : "E-mail",
"change_password" : "Jelszó megváltoztatás",
"confirm_password" : "Jelszó megerősítése",
"minimum_6_chars" : "Legalább 8 karakter",
"passwords_do_not_match" : "A jelszavak nem egyeznek",
"api_key" : "API kulcs",
"api_key_not_generated" : "Még nincsen generálva",
"generate_new_api_key" : "Új API kulcs generálása",
"generate_new_api_key_info" : "A jelszó megváltoztatása új API kulcsot generál",
"opml_export" : "OPML exportálása",
"delete_account" : "Fiók törlése",
"delete_account_confirmation" : "Törli a fiókját? Innen már nincs visszatérés!"
},
"about" : {
"rest_api" : {
"value" : "REST API",
"line1" : "A CommaFeed a JAX-RS-re és az AngularJS-re épül. Ezért a RESTA API elérhető.",
"link_to_documentation" : "Link a dokumentációhoz."
},
"keyboard_shortcuts" : "Gyorsbillentyűk",
"version" : "CommaFeed verzió",
"line1_prefix" : "A CommaFeed egy nyílt forrású projekt. A forrás megtalálható a ",
"line1_suffix" : "oldalán.",
"line2_prefix" : "Ha hibába ütközik, kérjük jelentse azt a ",
"line2_suffix" : "projekt oldalán.",
"line3" : "Ha tetszik önnek ez a szolgáltatás, akkor kérjük támogassa a fejlesztőket és, hogy fentarthassák a weboldalt.",
"line4" : "Akik jobban szeretnék az oldalt bitcon-nal támogatni, itt a cím",
"goodies" : {
"value" : "Hasznos dolgok",
"android_app" : "Android alkalmazás",
"subscribe_url" : "Feliratkozás az URL-re",
"chrome_extension" : "Chrome bővítmény",
"firefox_extension" : "Firefox kiterjesztés",
"opera_extension" : "Opera kiterjesztés",
"subscribe_bookmarklet" : "Feliratkozás bookmarklet hozzáadása (klikkeléssel)",
"subscribe_bookmarklet_asc" : "Régebbiek először",
"subscribe_bookmarklet_desc" : "Újak először",
"next_unread_bookmarklet" : "Következő olvasatlan elem bookmarklet (húzza fel a könyvjelzősávba)"
},
"translation" : {
"value" : "Fordítás",
"message" : "Segítségét kérjük a CommaFeed fordításához.",
"link" : "Nézze meg, hogyan tud segíteni ebben."
},
"announcements" : "Bejelentések ",
"shortcuts" : {
"mouse_middleclick" : "középső egérgomb ",
"open_next_entry" : "következő hír megnyitása",
"open_previous_entry" : "előző hír megnyitása",
"spacebar" : "szóköz/shift+szóköz",
"move_page_down_up" : "fel/le lépkedhet az oldalon",
"focus_next_entry" : "megnyitás nélkül fókuszál a övetkező elemre",
"focus_previous_entry" : "megnyitás nélkül fókuszál az előző elemre",
"open_next_feed" : "a következő hírcsatorna vagy kategória megnyitása",
"open_previous_feed" : "az előző hírcsatorna vagy kategória megnyitása",
"open_close_current_entry" : "a jelenlegi elem megnyitása/bezárása",
"open_current_entry_in_new_window" : "a jelenlegi elem megnyitása új ablakban",
"open_current_entry_in_new_window_background" : "a jelenlegi elem megnyitása a háttérben, új ablakban",
"star_unstar" : "hírelem csillagozása",
"mark_current_entry" : "elem megjelölése olvasottként",
"mark_all_as_read" : "az összes elem megjelölése olvasottként",
"open_in_new_tab_mark_as_read" : "elem megnyitása új fülön és megjelölése olvasottként",
"fullscreen" : "teljes képernyős mód bekapcsolása",
"font_size" : "a jelenlegi elemnél növeli/csökkenti a betűméretet",
"go_to_all" : "átkapcsol az Összes nézetre",
"go_to_starred" : "átkapcsol a Csillagozott nézetre",
"feed_search" : "név szerinti keresés a hírcsatornák között"
}
}
} | syshk/commafeed | src/main/app/i18n/hu.js | JavaScript | apache-2.0 | 8,164 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import _ from 'lodash';
import controller from './controller';
import templateUrl from './template.tpl.pug';
import {CancellationError} from 'app/errors/CancellationError';
export default class UserNotificationsService {
static $inject = ['$http', '$modal', '$q', 'IgniteMessages'];
/** @type {ng.IQService} */
$q;
/**
* @param {ng.IHttpService} $http
* @param {mgcrea.ngStrap.modal.IModalService} $modal
* @param {ng.IQService} $q
* @param {ReturnType<typeof import('app/services/Messages.service').default>} Messages
*/
constructor($http, $modal, $q, Messages) {
this.$http = $http;
this.$modal = $modal;
this.$q = $q;
this.Messages = Messages;
this.message = null;
this.isShown = false;
}
set notification(notification) {
this.message = _.get(notification, 'message');
this.isShown = _.get(notification, 'isShown');
}
editor() {
const deferred = this.$q.defer();
const modal = this.$modal({
templateUrl,
resolve: {
deferred: () => deferred,
message: () => this.message,
isShown: () => this.isShown
},
controller,
controllerAs: '$ctrl'
});
const modalHide = modal.hide;
modal.hide = () => deferred.reject(new CancellationError());
return deferred.promise
.finally(modalHide)
.then(({ message, isShown }) => {
this.$http.put('/api/v1/admin/notifications', { message, isShown })
.catch(this.Messages.showError);
});
}
}
| ilantukh/ignite | modules/web-console/frontend/app/components/user-notifications/service.js | JavaScript | apache-2.0 | 2,506 |
/*
* L.Handler.ShiftDragZoom is used to add shift-drag zoom interaction to the map
* (zoom to a selected bounding box), enabled by default.
*/
L.Map.mergeOptions({
boxZoom: true
});
L.Map.BoxZoom = L.Handler.extend({
initialize: function (map) {
this._map = map;
this._container = map._container;
this._pane = map._panes.overlayPane;
},
addHooks: function () {
L.DomEvent.on(this._container, 'mousedown', this._onMouseDown, this);
},
removeHooks: function () {
L.DomEvent.off(this._container, 'mousedown', this._onMouseDown, this);
},
moved: function () {
return this._moved;
},
_onMouseDown: function (e) {
if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
this._moved = false;
L.DomUtil.disableTextSelection();
L.DomUtil.disableImageDrag();
this._startPoint = this._map.mouseEventToContainerPoint(e);
L.DomEvent.on(document, {
contextmenu: L.DomEvent.stop,
mousemove: this._onMouseMove,
mouseup: this._onMouseUp,
keydown: this._onKeyDown
}, this);
},
_onMouseMove: function (e) {
if (!this._moved) {
this._moved = true;
this._box = L.DomUtil.create('div', 'leaflet-zoom-box', this._container);
L.DomUtil.addClass(this._container, 'leaflet-crosshair');
this._map.fire('boxzoomstart');
}
this._point = this._map.mouseEventToContainerPoint(e);
var bounds = new L.Bounds(this._point, this._startPoint),
size = bounds.getSize();
L.DomUtil.setPosition(this._box, bounds.min);
this._box.style.width = size.x + 'px';
this._box.style.height = size.y + 'px';
},
_finish: function () {
if (this._moved) {
L.DomUtil.remove(this._box);
L.DomUtil.removeClass(this._container, 'leaflet-crosshair');
}
L.DomUtil.enableTextSelection();
L.DomUtil.enableImageDrag();
L.DomEvent.off(document, {
contextmenu: L.DomEvent.stop,
mousemove: this._onMouseMove,
mouseup: this._onMouseUp,
keydown: this._onKeyDown
}, this);
},
_onMouseUp: function (e) {
if ((e.which !== 1) && (e.button !== 1)) { return false; }
this._finish();
if (!this._moved) { return; }
var bounds = new L.LatLngBounds(
this._map.containerPointToLatLng(this._startPoint),
this._map.containerPointToLatLng(this._point));
this._map
.fitBounds(bounds)
.fire('boxzoomend', {boxZoomBounds: bounds});
},
_onKeyDown: function (e) {
if (e.keyCode === 27) {
this._finish();
}
}
});
L.Map.addInitHook('addHandler', 'boxZoom', L.Map.BoxZoom);
| Mark-Wood/Leaflet | src/map/handler/Map.BoxZoom.js | JavaScript | bsd-2-clause | 2,498 |
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactCompositeComponent
*/
'use strict';
var React = require('react');
var ReactComponentEnvironment = require('ReactComponentEnvironment');
var ReactCompositeComponentTypes = require('ReactCompositeComponentTypes');
var ReactErrorUtils = require('ReactErrorUtils');
var ReactInstanceMap = require('ReactInstanceMap');
var ReactInstrumentation = require('ReactInstrumentation');
var ReactNodeTypes = require('ReactNodeTypes');
var ReactReconciler = require('ReactReconciler');
var {ReactCurrentOwner} = require('ReactGlobalSharedState');
if (__DEV__) {
var {ReactDebugCurrentFrame} = require('ReactGlobalSharedState');
var warningAboutMissingGetChildContext = {};
}
var checkPropTypes = require('prop-types/checkPropTypes');
var emptyObject = require('fbjs/lib/emptyObject');
var invariant = require('fbjs/lib/invariant');
var shallowEqual = require('fbjs/lib/shallowEqual');
var shouldUpdateReactComponent = require('shouldUpdateReactComponent');
var warning = require('fbjs/lib/warning');
function StatelessComponent(Component) {}
StatelessComponent.prototype.render = function() {
var Component = ReactInstanceMap.get(this)._currentElement.type;
var element = Component(this.props, this.context, this.updater);
return element;
};
function shouldConstruct(Component) {
return !!(Component.prototype && Component.prototype.isReactComponent);
}
function isPureComponent(Component) {
return !!(Component.prototype && Component.prototype.isPureReactComponent);
}
// Separated into a function to contain deoptimizations caused by try/finally.
function measureLifeCyclePerf(fn, debugID, timerType) {
if (debugID === 0) {
// Top-level wrappers (see ReactMount) and empty components (see
// ReactDOMEmptyComponent) are invisible to hooks and devtools.
// Both are implementation details that should go away in the future.
return fn();
}
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(debugID, timerType);
try {
return fn();
} finally {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(debugID, timerType);
}
}
/**
* ------------------ The Life-Cycle of a Composite Component ------------------
*
* - constructor: Initialization of state. The instance is now retained.
* - componentWillMount
* - render
* - [children's constructors]
* - [children's componentWillMount and render]
* - [children's componentDidMount]
* - componentDidMount
*
* Update Phases:
* - componentWillReceiveProps (only called if parent updated)
* - shouldComponentUpdate
* - componentWillUpdate
* - render
* - [children's constructors or receive props phases]
* - componentDidUpdate
*
* - componentWillUnmount
* - [children's componentWillUnmount]
* - [children destroyed]
* - (destroyed): The instance is now blank, released by React and ready for GC.
*
* -----------------------------------------------------------------------------
*/
/**
* An incrementing ID assigned to each component when it is mounted. This is
* used to enforce the order in which `ReactUpdates` updates dirty components.
*
* @private
*/
var nextMountID = 1;
/**
* @lends {ReactCompositeComponent.prototype}
*/
var ReactCompositeComponent = {
/**
* Base constructor for all composite component.
*
* @param {ReactElement} element
* @final
* @internal
*/
construct: function(element) {
this._currentElement = element;
this._rootNodeID = 0;
this._compositeType = null;
this._instance = null;
this._hostParent = null;
this._hostContainerInfo = null;
// See ReactUpdateQueue
this._updateBatchNumber = null;
this._pendingElement = null;
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
this._renderedNodeType = null;
this._renderedComponent = null;
this._context = null;
this._mountOrder = 0;
this._topLevelWrapper = null;
// See ReactUpdates and ReactUpdateQueue.
this._pendingCallbacks = null;
// ComponentWillUnmount shall only be called once
this._calledComponentWillUnmount = false;
if (__DEV__) {
this._warnedAboutRefsInRender = false;
}
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {?object} hostParent
* @param {?object} hostContainerInfo
* @param {?object} context
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: function(
transaction,
hostParent,
hostContainerInfo,
context,
) {
this._context = context;
this._mountOrder = nextMountID++;
this._hostParent = hostParent;
this._hostContainerInfo = hostContainerInfo;
var publicProps = this._currentElement.props;
var publicContext = this._processContext(context);
var Component = this._currentElement.type;
var updateQueue = transaction.getUpdateQueue();
// Initialize the public class
var doConstruct = shouldConstruct(Component);
var inst = this._constructComponent(
doConstruct,
publicProps,
publicContext,
updateQueue,
);
var renderedElement;
// Support functional components
if (!doConstruct && (inst == null || inst.render == null)) {
renderedElement = inst;
if (__DEV__) {
warning(
!Component.childContextTypes,
'%s(...): childContextTypes cannot be defined on a functional component.',
Component.displayName || Component.name || 'Component',
);
}
invariant(
inst === null || inst === false || React.isValidElement(inst),
'%s(...): A valid React element (or null) must be returned. You may have ' +
'returned undefined, an array or some other invalid object.',
Component.displayName || Component.name || 'Component',
);
inst = new StatelessComponent(Component);
this._compositeType = ReactCompositeComponentTypes.StatelessFunctional;
} else {
if (isPureComponent(Component)) {
this._compositeType = ReactCompositeComponentTypes.PureClass;
} else {
this._compositeType = ReactCompositeComponentTypes.ImpureClass;
}
}
if (__DEV__) {
// This will throw later in _renderValidatedComponent, but add an early
// warning now to help debugging
if (inst.render == null) {
warning(
false,
'%s(...): No `render` method found on the returned component ' +
'instance: you may have forgotten to define `render`.',
Component.displayName || Component.name || 'Component',
);
}
var propsMutated = inst.props !== publicProps;
var componentName =
Component.displayName || Component.name || 'Component';
warning(
inst.props === undefined || !propsMutated,
'%s(...): When calling super() in `%s`, make sure to pass ' +
"up the same props that your component's constructor was passed.",
componentName,
componentName,
);
}
// These should be set up in the constructor, but as a convenience for
// simpler class abstractions, we set them up after the fact.
inst.props = publicProps;
inst.context = publicContext;
inst.refs = emptyObject;
inst.updater = updateQueue;
this._instance = inst;
// Store a reference from the instance back to the internal representation
ReactInstanceMap.set(inst, this);
if (__DEV__) {
// Since plain JS classes are defined without any special initialization
// logic, we can not catch common errors early. Therefore, we have to
// catch them here, at initialization time, instead.
warning(
!inst.getInitialState ||
inst.getInitialState.isReactClassApproved ||
inst.state,
'getInitialState was defined on %s, a plain JavaScript class. ' +
'This is only supported for classes created using React.createClass. ' +
'Did you mean to define a state property instead?',
this.getName() || 'a component',
);
warning(
!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved,
'getDefaultProps was defined on %s, a plain JavaScript class. ' +
'This is only supported for classes created using React.createClass. ' +
'Use a static property to define defaultProps instead.',
this.getName() || 'a component',
);
warning(
!inst.propTypes,
'propTypes was defined as an instance property on %s. Use a static ' +
'property to define propTypes instead.',
this.getName() || 'a component',
);
warning(
!inst.contextTypes,
'contextTypes was defined as an instance property on %s. Use a ' +
'static property to define contextTypes instead.',
this.getName() || 'a component',
);
warning(
typeof inst.componentShouldUpdate !== 'function',
'%s has a method called ' +
'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
'The name is phrased as a question because the function is ' +
'expected to return a value.',
this.getName() || 'A component',
);
warning(
typeof inst.componentDidUnmount !== 'function',
'%s has a method called ' +
'componentDidUnmount(). But there is no such lifecycle method. ' +
'Did you mean componentWillUnmount()?',
this.getName() || 'A component',
);
warning(
typeof inst.componentWillRecieveProps !== 'function',
'%s has a method called ' +
'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?',
this.getName() || 'A component',
);
if (
isPureComponent(Component) &&
typeof inst.shouldComponentUpdate !== 'undefined'
) {
warning(
false,
'%s has a method called shouldComponentUpdate(). ' +
'shouldComponentUpdate should not be used when extending React.PureComponent. ' +
'Please extend React.Component if shouldComponentUpdate is used.',
this.getName() || 'A pure component',
);
}
warning(
!inst.defaultProps,
'Setting defaultProps as an instance property on %s is not supported and will be ignored.' +
' Instead, define defaultProps as a static property on %s.',
this.getName() || 'a component',
this.getName() || 'a component',
);
}
var initialState = inst.state;
if (initialState === undefined) {
inst.state = initialState = null;
}
invariant(
typeof initialState === 'object' && !Array.isArray(initialState),
'%s.state: must be set to an object or null',
this.getName() || 'ReactCompositeComponent',
);
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
if (inst.componentWillMount) {
if (__DEV__) {
measureLifeCyclePerf(
() => inst.componentWillMount(),
this._debugID,
'componentWillMount',
);
} else {
inst.componentWillMount();
}
// When mounting, calls to `setState` by `componentWillMount` will set
// `this._pendingStateQueue` without triggering a re-render.
if (this._pendingStateQueue) {
inst.state = this._processPendingState(inst.props, inst.context);
}
}
var markup;
if (inst.unstable_handleError) {
markup = this.performInitialMountWithErrorHandling(
renderedElement,
hostParent,
hostContainerInfo,
transaction,
context,
);
} else {
markup = this.performInitialMount(
renderedElement,
hostParent,
hostContainerInfo,
transaction,
context,
);
}
if (inst.componentDidMount) {
if (__DEV__) {
transaction.getReactMountReady().enqueue(() => {
measureLifeCyclePerf(
() => inst.componentDidMount(),
this._debugID,
'componentDidMount',
);
});
} else {
transaction.getReactMountReady().enqueue(inst.componentDidMount, inst);
}
}
// setState callbacks during willMount should end up here
const callbacks = this._pendingCallbacks;
if (callbacks) {
this._pendingCallbacks = null;
for (let i = 0; i < callbacks.length; i++) {
transaction.getReactMountReady().enqueue(callbacks[i], inst);
}
}
return markup;
},
_constructComponent: function(
doConstruct,
publicProps,
publicContext,
updateQueue,
) {
if (__DEV__) {
ReactCurrentOwner.current = this;
try {
return this._constructComponentWithoutOwner(
doConstruct,
publicProps,
publicContext,
updateQueue,
);
} finally {
ReactCurrentOwner.current = null;
}
} else {
return this._constructComponentWithoutOwner(
doConstruct,
publicProps,
publicContext,
updateQueue,
);
}
},
_constructComponentWithoutOwner: function(
doConstruct,
publicProps,
publicContext,
updateQueue,
) {
var Component = this._currentElement.type;
if (doConstruct) {
if (__DEV__) {
return measureLifeCyclePerf(
() => new Component(publicProps, publicContext, updateQueue),
this._debugID,
'ctor',
);
} else {
return new Component(publicProps, publicContext, updateQueue);
}
}
// This can still be an instance in case of factory components
// but we'll count this as time spent rendering as the more common case.
if (__DEV__) {
return measureLifeCyclePerf(
() => Component(publicProps, publicContext, updateQueue),
this._debugID,
'render',
);
} else {
return Component(publicProps, publicContext, updateQueue);
}
},
performInitialMountWithErrorHandling: function(
renderedElement,
hostParent,
hostContainerInfo,
transaction,
context,
) {
var markup;
var checkpoint = transaction.checkpoint();
try {
markup = this.performInitialMount(
renderedElement,
hostParent,
hostContainerInfo,
transaction,
context,
);
} catch (e) {
// Roll back to checkpoint, handle error (which may add items to the transaction), and take a new checkpoint
transaction.rollback(checkpoint);
this._instance.unstable_handleError(e);
if (this._pendingStateQueue) {
this._instance.state = this._processPendingState(
this._instance.props,
this._instance.context,
);
}
checkpoint = transaction.checkpoint();
this._renderedComponent.unmountComponent(
true /* safely */,
// Don't call componentWillUnmount() because they never fully mounted:
true /* skipLifecyle */,
);
transaction.rollback(checkpoint);
// Try again - we've informed the component about the error, so they can render an error message this time.
// If this throws again, the error will bubble up (and can be caught by a higher error boundary).
markup = this.performInitialMount(
renderedElement,
hostParent,
hostContainerInfo,
transaction,
context,
);
}
return markup;
},
performInitialMount: function(
renderedElement,
hostParent,
hostContainerInfo,
transaction,
context,
) {
// If not a stateless component, we now render
if (renderedElement === undefined) {
renderedElement = this._renderValidatedComponent();
}
var nodeType = ReactNodeTypes.getType(renderedElement);
this._renderedNodeType = nodeType;
var child = this._instantiateReactComponent(
renderedElement,
nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */,
);
this._renderedComponent = child;
var debugID = 0;
if (__DEV__) {
debugID = this._debugID;
}
var markup = ReactReconciler.mountComponent(
child,
transaction,
hostParent,
hostContainerInfo,
this._processChildContext(context),
debugID,
);
if (__DEV__) {
if (debugID !== 0) {
var childDebugIDs = child._debugID !== 0 ? [child._debugID] : [];
ReactInstrumentation.debugTool.onSetChildren(debugID, childDebugIDs);
}
}
return markup;
},
getHostNode: function() {
return ReactReconciler.getHostNode(this._renderedComponent);
},
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function(safely, skipLifecycle) {
if (!this._renderedComponent) {
return;
}
var inst = this._instance;
if (inst.componentWillUnmount && !inst._calledComponentWillUnmount) {
inst._calledComponentWillUnmount = true;
if (safely) {
if (!skipLifecycle) {
var name = this.getName() + '.componentWillUnmount()';
ReactErrorUtils.invokeGuardedCallbackAndCatchFirstError(
name,
inst.componentWillUnmount,
inst,
);
}
} else {
if (__DEV__) {
measureLifeCyclePerf(
() => inst.componentWillUnmount(),
this._debugID,
'componentWillUnmount',
);
} else {
inst.componentWillUnmount();
}
}
}
if (this._renderedComponent) {
ReactReconciler.unmountComponent(
this._renderedComponent,
safely,
skipLifecycle,
);
this._renderedNodeType = null;
this._renderedComponent = null;
this._instance = null;
}
// Reset pending fields
// Even if this component is scheduled for another update in ReactUpdates,
// it would still be ignored because these fields are reset.
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
this._pendingCallbacks = null;
this._pendingElement = null;
// These fields do not really need to be reset since this object is no
// longer accessible.
this._context = null;
this._rootNodeID = 0;
this._topLevelWrapper = null;
// Delete the reference from the instance to this internal representation
// which allow the internals to be properly cleaned up even if the user
// leaks a reference to the public instance.
ReactInstanceMap.remove(inst);
// Some existing components rely on inst.props even after they've been
// destroyed (in event handlers).
// TODO: inst.props = null;
// TODO: inst.state = null;
// TODO: inst.context = null;
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`
*
* @param {object} context
* @return {?object}
* @private
*/
_maskContext: function(context) {
var Component = this._currentElement.type;
var contextTypes = Component.contextTypes;
if (!contextTypes) {
return emptyObject;
}
var maskedContext = {};
for (var contextName in contextTypes) {
maskedContext[contextName] = context[contextName];
}
return maskedContext;
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`, and asserts that they are valid.
*
* @param {object} context
* @return {?object}
* @private
*/
_processContext: function(context) {
var maskedContext = this._maskContext(context);
if (__DEV__) {
var Component = this._currentElement.type;
if (Component.contextTypes) {
this._checkContextTypes(
Component.contextTypes,
maskedContext,
'context',
);
}
}
return maskedContext;
},
/**
* @param {object} currentContext
* @return {object}
* @private
*/
_processChildContext: function(currentContext) {
var Component = this._currentElement.type;
var inst = this._instance;
var childContext;
if (typeof inst.getChildContext === 'function') {
if (__DEV__) {
ReactInstrumentation.debugTool.onBeginProcessingChildContext();
try {
childContext = inst.getChildContext();
} finally {
ReactInstrumentation.debugTool.onEndProcessingChildContext();
}
} else {
childContext = inst.getChildContext();
}
invariant(
typeof Component.childContextTypes === 'object',
'%s.getChildContext(): childContextTypes must be defined in order to ' +
'use getChildContext().',
this.getName() || 'ReactCompositeComponent',
);
if (__DEV__) {
this._checkContextTypes(
Component.childContextTypes,
childContext,
'child context',
);
}
for (var name in childContext) {
invariant(
name in Component.childContextTypes,
'%s.getChildContext(): key "%s" is not defined in childContextTypes.',
this.getName() || 'ReactCompositeComponent',
name,
);
}
return Object.assign({}, currentContext, childContext);
} else {
if (__DEV__) {
const componentName = this.getName();
if (!warningAboutMissingGetChildContext[componentName]) {
warningAboutMissingGetChildContext[componentName] = true;
warning(
!Component.childContextTypes,
'%s.childContextTypes is specified but there is no getChildContext() method ' +
'on the instance. You can either define getChildContext() on %s or remove ' +
'childContextTypes from it.',
componentName,
componentName,
);
}
}
}
return currentContext;
},
/**
* Assert that the context types are valid
*
* @param {object} typeSpecs Map of context field to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @private
*/
_checkContextTypes: function(typeSpecs, values, location: string) {
if (__DEV__) {
ReactDebugCurrentFrame.current = this._debugID;
checkPropTypes(
typeSpecs,
values,
location,
this.getName(),
ReactDebugCurrentFrame.getStackAddendum,
);
ReactDebugCurrentFrame.current = null;
}
},
receiveComponent: function(nextElement, transaction, nextContext) {
var prevElement = this._currentElement;
var prevContext = this._context;
this._pendingElement = null;
this.updateComponent(
transaction,
prevElement,
nextElement,
prevContext,
nextContext,
);
},
/**
* If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate`
* is set, update the component.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function(transaction) {
if (this._pendingElement != null) {
ReactReconciler.receiveComponent(
this,
this._pendingElement,
transaction,
this._context,
);
} else if (this._pendingStateQueue !== null || this._pendingForceUpdate) {
this.updateComponent(
transaction,
this._currentElement,
this._currentElement,
this._context,
this._context,
);
} else {
var callbacks = this._pendingCallbacks;
this._pendingCallbacks = null;
if (callbacks) {
for (var j = 0; j < callbacks.length; j++) {
transaction
.getReactMountReady()
.enqueue(callbacks[j], this.getPublicInstance());
}
}
this._updateBatchNumber = null;
}
},
/**
* Perform an update to a mounted component. The componentWillReceiveProps and
* shouldComponentUpdate methods are called, then (assuming the update isn't
* skipped) the remaining update lifecycle methods are called and the DOM
* representation is updated.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @param {ReactElement} prevParentElement
* @param {ReactElement} nextParentElement
* @internal
* @overridable
*/
updateComponent: function(
transaction,
prevParentElement,
nextParentElement,
prevUnmaskedContext,
nextUnmaskedContext,
) {
var inst = this._instance;
invariant(
inst != null,
'Attempted to update component `%s` that has already been unmounted ' +
'(or failed to mount).',
this.getName() || 'ReactCompositeComponent',
);
var willReceive = false;
var nextContext;
// Determine if the context has changed or not
if (this._context === nextUnmaskedContext) {
nextContext = inst.context;
} else {
nextContext = this._processContext(nextUnmaskedContext);
willReceive = true;
}
var prevProps = prevParentElement.props;
var nextProps = nextParentElement.props;
// Not a simple state update but a props update
if (prevParentElement !== nextParentElement) {
willReceive = true;
}
// An update here will schedule an update but immediately set
// _pendingStateQueue which will ensure that any state updates gets
// immediately reconciled instead of waiting for the next batch.
if (willReceive && inst.componentWillReceiveProps) {
const beforeState = inst.state;
if (__DEV__) {
measureLifeCyclePerf(
() => inst.componentWillReceiveProps(nextProps, nextContext),
this._debugID,
'componentWillReceiveProps',
);
} else {
inst.componentWillReceiveProps(nextProps, nextContext);
}
const afterState = inst.state;
if (beforeState !== afterState) {
inst.state = beforeState;
inst.updater.enqueueReplaceState(inst, afterState);
if (__DEV__) {
warning(
false,
'%s.componentWillReceiveProps(): Assigning directly to ' +
"this.state is deprecated (except inside a component's " +
'constructor). Use setState instead.',
this.getName() || 'ReactCompositeComponent',
);
}
}
}
// If updating happens to enqueue any new updates, we shouldn't execute new
// callbacks until the next render happens, so stash the callbacks first.
var callbacks = this._pendingCallbacks;
this._pendingCallbacks = null;
var nextState = this._processPendingState(nextProps, nextContext);
var shouldUpdate = true;
if (!this._pendingForceUpdate) {
var prevState = inst.state;
shouldUpdate = willReceive || nextState !== prevState;
if (inst.shouldComponentUpdate) {
if (__DEV__) {
shouldUpdate = measureLifeCyclePerf(
() => inst.shouldComponentUpdate(nextProps, nextState, nextContext),
this._debugID,
'shouldComponentUpdate',
);
} else {
shouldUpdate = inst.shouldComponentUpdate(
nextProps,
nextState,
nextContext,
);
}
} else {
if (this._compositeType === ReactCompositeComponentTypes.PureClass) {
shouldUpdate =
!shallowEqual(prevProps, nextProps) ||
!shallowEqual(inst.state, nextState);
}
}
}
if (__DEV__) {
warning(
shouldUpdate !== undefined,
'%s.shouldComponentUpdate(): Returned undefined instead of a ' +
'boolean value. Make sure to return true or false.',
this.getName() || 'ReactCompositeComponent',
);
}
this._updateBatchNumber = null;
if (shouldUpdate) {
this._pendingForceUpdate = false;
// Will set `this.props`, `this.state` and `this.context`.
this._performComponentUpdate(
nextParentElement,
nextProps,
nextState,
nextContext,
transaction,
nextUnmaskedContext,
);
} else {
// If it's determined that a component should not update, we still want
// to set props and state but we shortcut the rest of the update.
this._currentElement = nextParentElement;
this._context = nextUnmaskedContext;
inst.props = nextProps;
inst.state = nextState;
inst.context = nextContext;
}
if (callbacks) {
for (var j = 0; j < callbacks.length; j++) {
transaction
.getReactMountReady()
.enqueue(callbacks[j], this.getPublicInstance());
}
}
},
_processPendingState: function(props, context) {
var inst = this._instance;
var queue = this._pendingStateQueue;
var replace = this._pendingReplaceState;
this._pendingReplaceState = false;
this._pendingStateQueue = null;
if (!queue) {
return inst.state;
}
if (replace && queue.length === 1) {
return queue[0];
}
var nextState = replace ? queue[0] : inst.state;
var dontMutate = true;
for (var i = replace ? 1 : 0; i < queue.length; i++) {
var partial = queue[i];
let partialState = typeof partial === 'function'
? partial.call(inst, nextState, props, context)
: partial;
if (partialState) {
if (dontMutate) {
dontMutate = false;
nextState = Object.assign({}, nextState, partialState);
} else {
Object.assign(nextState, partialState);
}
}
}
return nextState;
},
/**
* Merges new props and state, notifies delegate methods of update and
* performs update.
*
* @param {ReactElement} nextElement Next element
* @param {object} nextProps Next public object to set as properties.
* @param {?object} nextState Next object to set as state.
* @param {?object} nextContext Next public object to set as context.
* @param {ReactReconcileTransaction} transaction
* @param {?object} unmaskedContext
* @private
*/
_performComponentUpdate: function(
nextElement,
nextProps,
nextState,
nextContext,
transaction,
unmaskedContext,
) {
var inst = this._instance;
var hasComponentDidUpdate = !!inst.componentDidUpdate;
var prevProps;
var prevState;
if (hasComponentDidUpdate) {
prevProps = inst.props;
prevState = inst.state;
}
if (inst.componentWillUpdate) {
if (__DEV__) {
measureLifeCyclePerf(
() => inst.componentWillUpdate(nextProps, nextState, nextContext),
this._debugID,
'componentWillUpdate',
);
} else {
inst.componentWillUpdate(nextProps, nextState, nextContext);
}
}
this._currentElement = nextElement;
this._context = unmaskedContext;
inst.props = nextProps;
inst.state = nextState;
inst.context = nextContext;
if (inst.unstable_handleError) {
this._updateRenderedComponentWithErrorHandling(
transaction,
unmaskedContext,
);
} else {
this._updateRenderedComponent(transaction, unmaskedContext);
}
if (hasComponentDidUpdate) {
if (__DEV__) {
transaction.getReactMountReady().enqueue(() => {
measureLifeCyclePerf(
inst.componentDidUpdate.bind(inst, prevProps, prevState),
this._debugID,
'componentDidUpdate',
);
});
} else {
transaction
.getReactMountReady()
.enqueue(
inst.componentDidUpdate.bind(inst, prevProps, prevState),
inst,
);
}
}
},
/**
* Call the component's `render` method and update the DOM accordingly.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
_updateRenderedComponentWithErrorHandling: function(transaction, context) {
var checkpoint = transaction.checkpoint();
try {
this._updateRenderedComponent(transaction, context);
} catch (e) {
// Roll back to checkpoint, handle error (which may add items to the transaction),
// and take a new checkpoint
transaction.rollback(checkpoint);
this._instance.unstable_handleError(e);
if (this._pendingStateQueue) {
this._instance.state = this._processPendingState(
this._instance.props,
this._instance.context,
);
}
checkpoint = transaction.checkpoint();
// Gracefully update to a clean state
this._updateRenderedComponentWithNextElement(
transaction,
context,
null,
true /* safely */,
);
// Try again - we've informed the component about the error, so they can render an error message this time.
// If this throws again, the error will bubble up (and can be caught by a higher error boundary).
this._updateRenderedComponent(transaction, context);
}
},
/**
* Call the component's `render` method and update the DOM accordingly.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
_updateRenderedComponent: function(transaction, context) {
var nextRenderedElement = this._renderValidatedComponent();
this._updateRenderedComponentWithNextElement(
transaction,
context,
nextRenderedElement,
false /* safely */,
);
},
/**
* Call the component's `render` method and update the DOM accordingly.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
_updateRenderedComponentWithNextElement: function(
transaction,
context,
nextRenderedElement,
safely,
) {
var prevComponentInstance = this._renderedComponent;
var prevRenderedElement = prevComponentInstance._currentElement;
var debugID = 0;
if (__DEV__) {
debugID = this._debugID;
}
if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) {
ReactReconciler.receiveComponent(
prevComponentInstance,
nextRenderedElement,
transaction,
this._processChildContext(context),
);
} else {
var oldHostNode = ReactReconciler.getHostNode(prevComponentInstance);
var nodeType = ReactNodeTypes.getType(nextRenderedElement);
this._renderedNodeType = nodeType;
var child = this._instantiateReactComponent(
nextRenderedElement,
nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */,
);
this._renderedComponent = child;
var nextMarkup = ReactReconciler.mountComponent(
child,
transaction,
this._hostParent,
this._hostContainerInfo,
this._processChildContext(context),
debugID,
);
ReactReconciler.unmountComponent(
prevComponentInstance,
safely,
false /* skipLifecycle */,
);
if (__DEV__) {
if (debugID !== 0) {
var childDebugIDs = child._debugID !== 0 ? [child._debugID] : [];
ReactInstrumentation.debugTool.onSetChildren(debugID, childDebugIDs);
}
}
this._replaceNodeWithMarkup(
oldHostNode,
nextMarkup,
prevComponentInstance,
);
}
},
/**
* Overridden in shallow rendering.
*
* @protected
*/
_replaceNodeWithMarkup: function(oldHostNode, nextMarkup, prevInstance) {
ReactComponentEnvironment.replaceNodeWithMarkup(
oldHostNode,
nextMarkup,
prevInstance,
);
},
/**
* @protected
*/
_renderValidatedComponentWithoutOwnerOrContext: function() {
var inst = this._instance;
var renderedElement;
if (__DEV__) {
renderedElement = measureLifeCyclePerf(
() => inst.render(),
this._debugID,
'render',
);
} else {
renderedElement = inst.render();
}
if (__DEV__) {
// We allow auto-mocks to proceed as if they're returning null.
if (renderedElement === undefined && inst.render._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
renderedElement = null;
}
}
return renderedElement;
},
/**
* @private
*/
_renderValidatedComponent: function() {
var renderedElement;
if (
__DEV__ ||
this._compositeType !== ReactCompositeComponentTypes.StatelessFunctional
) {
ReactCurrentOwner.current = this;
try {
renderedElement = this._renderValidatedComponentWithoutOwnerOrContext();
} finally {
ReactCurrentOwner.current = null;
}
} else {
renderedElement = this._renderValidatedComponentWithoutOwnerOrContext();
}
invariant(
// TODO: An `isValidNode` function would probably be more appropriate
renderedElement === null ||
renderedElement === false ||
React.isValidElement(renderedElement),
'%s.render(): A valid React element (or null) must be returned. You may have ' +
'returned undefined, an array or some other invalid object.',
this.getName() || 'ReactCompositeComponent',
);
return renderedElement;
},
/**
* Lazily allocates the refs object and stores `component` as `ref`.
*
* @param {string} ref Reference name.
* @param {component} component Component to store as `ref`.
* @final
* @private
*/
attachRef: function(ref, component) {
var inst = this.getPublicInstance();
invariant(inst != null, 'Stateless function components cannot have refs.');
var publicComponentInstance = component.getPublicInstance();
var refs = inst.refs === emptyObject ? (inst.refs = {}) : inst.refs;
refs[ref] = publicComponentInstance;
},
/**
* Detaches a reference name.
*
* @param {string} ref Name to dereference.
* @final
* @private
*/
detachRef: function(ref) {
var refs = this.getPublicInstance().refs;
delete refs[ref];
},
/**
* Get a text description of the component that can be used to identify it
* in error messages.
* @return {string} The name or null.
* @internal
*/
getName: function() {
var type = this._currentElement.type;
var constructor = this._instance && this._instance.constructor;
return (
type.displayName ||
(constructor && constructor.displayName) ||
type.name ||
(constructor && constructor.name) ||
null
);
},
/**
* Get the publicly accessible representation of this component - i.e. what
* is exposed by refs and returned by render. Can be null for stateless
* components.
*
* @return {ReactComponent} the public component instance.
* @internal
*/
getPublicInstance: function() {
var inst = this._instance;
if (
this._compositeType === ReactCompositeComponentTypes.StatelessFunctional
) {
return null;
}
return inst;
},
// Stub
_instantiateReactComponent: null,
};
module.exports = ReactCompositeComponent;
| jquense/react | src/renderers/shared/stack/reconciler/ReactCompositeComponent.js | JavaScript | bsd-3-clause | 39,777 |
// @flow
// $ExpectError: No negative tests here
const skipNegativeTest: string = true;
var inquirer = require('inquirer');
var questions = [
{
type: 'confirm',
name: 'bacon',
message: 'Do you like bacon?'
},
{
type: 'input',
name: 'favorite',
message: 'Bacon lover, what is your favorite type of bacon?',
when: function (answers) {
return !!answers.bacon;
}
},
{
type: 'confirm',
name: 'pizza',
message: 'Ok... Do you like pizza?',
when: function (answers) {
return !likesFood('bacon')(answers);
}
},
{
type: 'input',
name: 'favorite',
message: 'Whew! What is your favorite type of pizza?',
when: likesFood('pizza')
}
];
function likesFood(aFood) {
return function (answers) {
return !!answers[aFood];
};
}
inquirer.prompt(questions).then(function (answers) {
console.log(JSON.stringify(answers, null, ' '));
});
| echenley/flow-typed | definitions/npm/inquirer_v2.x.x/test_when_v2.x.x.js | JavaScript | mit | 926 |
/*! Raven.js 3.25.0 (80dffad) | github.com/getsentry/raven-js */
/*
* Includes TraceKit
* https://github.com/getsentry/TraceKit
*
* Copyright 2018 Matt Robenolt and other contributors
* Released under the BSD license
* https://github.com/getsentry/raven-js/blob/master/LICENSE
*
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Raven = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
/**
* console plugin
*
* Monkey patches console.* calls into Sentry messages with
* their appropriate log levels. (Experimental)
*
* Options:
*
* `levels`: An array of levels (methods on `console`) to report to Sentry.
* Defaults to debug, info, warn, and error.
*/
var wrapConsoleMethod = _dereq_(6).wrapMethod;
function consolePlugin(Raven, console, pluginOptions) {
console = console || window.console || {};
pluginOptions = pluginOptions || {};
var logLevels = pluginOptions.levels || ['debug', 'info', 'warn', 'error'];
if ('assert' in console) logLevels.push('assert');
var callback = function(msg, data) {
Raven.captureMessage(msg, data);
};
var level = logLevels.pop();
while (level) {
wrapConsoleMethod(console, level, callback);
level = logLevels.pop();
}
}
module.exports = consolePlugin;
_dereq_(8).addPlugin(module.exports);
},{"6":6,"8":8}],2:[function(_dereq_,module,exports){
/**
* Ember.js plugin
*
* Patches event handler callbacks and ajax callbacks.
*/
function emberPlugin(Raven, Ember) {
Ember = Ember || window.Ember;
// quit if Ember isn't on the page
if (!Ember) return;
var _oldOnError = Ember.onerror;
Ember.onerror = function EmberOnError(error) {
Raven.captureException(error);
if (typeof _oldOnError === 'function') {
_oldOnError.call(this, error);
}
};
Ember.RSVP.on('error', function(reason) {
if (reason instanceof Error) {
Raven.captureException(reason, {
extra: {context: 'Unhandled Promise error detected'}
});
} else {
Raven.captureMessage('Unhandled Promise error detected', {extra: {reason: reason}});
}
});
}
module.exports = emberPlugin;
_dereq_(8).addPlugin(module.exports);
},{"8":8}],3:[function(_dereq_,module,exports){
/*global define*/
/**
* require.js plugin
*
* Automatically wrap define/require callbacks. (Experimental)
*/
function requirePlugin(Raven) {
if (typeof define === 'function' && define.amd) {
window.define = Raven.wrap({deep: false}, define);
window.require = Raven.wrap({deep: false}, _dereq_);
}
}
module.exports = requirePlugin;
_dereq_(8).addPlugin(module.exports);
},{"8":8}],4:[function(_dereq_,module,exports){
/**
* Vue.js 2.0 plugin
*
*/
function formatComponentName(vm) {
if (vm.$root === vm) {
return 'root instance';
}
var name = vm._isVue ? vm.$options.name || vm.$options._componentTag : vm.name;
return (
(name ? 'component <' + name + '>' : 'anonymous component') +
(vm._isVue && vm.$options.__file ? ' at ' + vm.$options.__file : '')
);
}
function vuePlugin(Raven, Vue) {
Vue = Vue || window.Vue;
// quit if Vue isn't on the page
if (!Vue || !Vue.config) return;
var _oldOnError = Vue.config.errorHandler;
Vue.config.errorHandler = function VueErrorHandler(error, vm, info) {
var metaData = {};
// vm and lifecycleHook are not always available
if (Object.prototype.toString.call(vm) === '[object Object]') {
metaData.componentName = formatComponentName(vm);
metaData.propsData = vm.$options.propsData;
}
if (typeof info !== 'undefined') {
metaData.lifecycleHook = info;
}
Raven.captureException(error, {
extra: metaData
});
if (typeof _oldOnError === 'function') {
_oldOnError.call(this, error, vm, info);
}
};
}
module.exports = vuePlugin;
_dereq_(8).addPlugin(module.exports);
},{"8":8}],5:[function(_dereq_,module,exports){
function RavenConfigError(message) {
this.name = 'RavenConfigError';
this.message = message;
}
RavenConfigError.prototype = new Error();
RavenConfigError.prototype.constructor = RavenConfigError;
module.exports = RavenConfigError;
},{}],6:[function(_dereq_,module,exports){
var utils = _dereq_(9);
var wrapMethod = function(console, level, callback) {
var originalConsoleLevel = console[level];
var originalConsole = console;
if (!(level in console)) {
return;
}
var sentryLevel = level === 'warn' ? 'warning' : level;
console[level] = function() {
var args = [].slice.call(arguments);
var msg = utils.safeJoin(args, ' ');
var data = {level: sentryLevel, logger: 'console', extra: {arguments: args}};
if (level === 'assert') {
if (args[0] === false) {
// Default browsers message
msg =
'Assertion failed: ' + (utils.safeJoin(args.slice(1), ' ') || 'console.assert');
data.extra.arguments = args.slice(1);
callback && callback(msg, data);
}
} else {
callback && callback(msg, data);
}
// this fails for some browsers. :(
if (originalConsoleLevel) {
// IE9 doesn't allow calling apply on console functions directly
// See: https://stackoverflow.com/questions/5472938/does-ie9-support-console-log-and-is-it-a-real-function#answer-5473193
Function.prototype.apply.call(originalConsoleLevel, originalConsole, args);
}
};
};
module.exports = {
wrapMethod: wrapMethod
};
},{"9":9}],7:[function(_dereq_,module,exports){
(function (global){
/*global XDomainRequest:false */
var TraceKit = _dereq_(10);
var stringify = _dereq_(11);
var md5 = _dereq_(12);
var RavenConfigError = _dereq_(5);
var utils = _dereq_(9);
var isErrorEvent = utils.isErrorEvent;
var isDOMError = utils.isDOMError;
var isDOMException = utils.isDOMException;
var isError = utils.isError;
var isObject = utils.isObject;
var isPlainObject = utils.isPlainObject;
var isUndefined = utils.isUndefined;
var isFunction = utils.isFunction;
var isString = utils.isString;
var isArray = utils.isArray;
var isEmptyObject = utils.isEmptyObject;
var each = utils.each;
var objectMerge = utils.objectMerge;
var truncate = utils.truncate;
var objectFrozen = utils.objectFrozen;
var hasKey = utils.hasKey;
var joinRegExp = utils.joinRegExp;
var urlencode = utils.urlencode;
var uuid4 = utils.uuid4;
var htmlTreeAsString = utils.htmlTreeAsString;
var isSameException = utils.isSameException;
var isSameStacktrace = utils.isSameStacktrace;
var parseUrl = utils.parseUrl;
var fill = utils.fill;
var supportsFetch = utils.supportsFetch;
var supportsReferrerPolicy = utils.supportsReferrerPolicy;
var serializeKeysForMessage = utils.serializeKeysForMessage;
var serializeException = utils.serializeException;
var sanitize = utils.sanitize;
var wrapConsoleMethod = _dereq_(6).wrapMethod;
var dsnKeys = 'source protocol user pass host port path'.split(' '),
dsnPattern = /^(?:(\w+):)?\/\/(?:(\w+)(:\w+)?@)?([\w\.-]+)(?::(\d+))?(\/.*)/;
function now() {
return +new Date();
}
// This is to be defensive in environments where window does not exist (see https://github.com/getsentry/raven-js/pull/785)
var _window =
typeof window !== 'undefined'
? window
: typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
var _document = _window.document;
var _navigator = _window.navigator;
function keepOriginalCallback(original, callback) {
return isFunction(callback)
? function(data) {
return callback(data, original);
}
: callback;
}
// First, check for JSON support
// If there is no JSON, we no-op the core features of Raven
// since JSON is required to encode the payload
function Raven() {
this._hasJSON = !!(typeof JSON === 'object' && JSON.stringify);
// Raven can run in contexts where there's no document (react-native)
this._hasDocument = !isUndefined(_document);
this._hasNavigator = !isUndefined(_navigator);
this._lastCapturedException = null;
this._lastData = null;
this._lastEventId = null;
this._globalServer = null;
this._globalKey = null;
this._globalProject = null;
this._globalContext = {};
this._globalOptions = {
// SENTRY_RELEASE can be injected by https://github.com/getsentry/sentry-webpack-plugin
release: _window.SENTRY_RELEASE && _window.SENTRY_RELEASE.id,
logger: 'javascript',
ignoreErrors: [],
ignoreUrls: [],
whitelistUrls: [],
includePaths: [],
headers: null,
collectWindowErrors: true,
captureUnhandledRejections: true,
maxMessageLength: 0,
// By default, truncates URL values to 250 chars
maxUrlLength: 250,
stackTraceLimit: 50,
autoBreadcrumbs: true,
instrument: true,
sampleRate: 1,
sanitizeKeys: []
};
this._fetchDefaults = {
method: 'POST',
keepalive: true,
// Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default
// https://caniuse.com/#feat=referrer-policy
// It doesn't. And it throw exception instead of ignoring this parameter...
// REF: https://github.com/getsentry/raven-js/issues/1233
referrerPolicy: supportsReferrerPolicy() ? 'origin' : ''
};
this._ignoreOnError = 0;
this._isRavenInstalled = false;
this._originalErrorStackTraceLimit = Error.stackTraceLimit;
// capture references to window.console *and* all its methods first
// before the console plugin has a chance to monkey patch
this._originalConsole = _window.console || {};
this._originalConsoleMethods = {};
this._plugins = [];
this._startTime = now();
this._wrappedBuiltIns = [];
this._breadcrumbs = [];
this._lastCapturedEvent = null;
this._keypressTimeout;
this._location = _window.location;
this._lastHref = this._location && this._location.href;
this._resetBackoff();
// eslint-disable-next-line guard-for-in
for (var method in this._originalConsole) {
this._originalConsoleMethods[method] = this._originalConsole[method];
}
}
/*
* The core Raven singleton
*
* @this {Raven}
*/
Raven.prototype = {
// Hardcode version string so that raven source can be loaded directly via
// webpack (using a build step causes webpack #1617). Grunt verifies that
// this value matches package.json during build.
// See: https://github.com/getsentry/raven-js/issues/465
VERSION: '3.25.0',
debug: false,
TraceKit: TraceKit, // alias to TraceKit
/*
* Configure Raven with a DSN and extra options
*
* @param {string} dsn The public Sentry DSN
* @param {object} options Set of global options [optional]
* @return {Raven}
*/
config: function(dsn, options) {
var self = this;
if (self._globalServer) {
this._logDebug('error', 'Error: Raven has already been configured');
return self;
}
if (!dsn) return self;
var globalOptions = self._globalOptions;
// merge in options
if (options) {
each(options, function(key, value) {
// tags and extra are special and need to be put into context
if (key === 'tags' || key === 'extra' || key === 'user') {
self._globalContext[key] = value;
} else {
globalOptions[key] = value;
}
});
}
self.setDSN(dsn);
// "Script error." is hard coded into browsers for errors that it can't read.
// this is the result of a script being pulled in from an external domain and CORS.
globalOptions.ignoreErrors.push(/^Script error\.?$/);
globalOptions.ignoreErrors.push(/^Javascript error: Script error\.? on line 0$/);
// join regexp rules into one big rule
globalOptions.ignoreErrors = joinRegExp(globalOptions.ignoreErrors);
globalOptions.ignoreUrls = globalOptions.ignoreUrls.length
? joinRegExp(globalOptions.ignoreUrls)
: false;
globalOptions.whitelistUrls = globalOptions.whitelistUrls.length
? joinRegExp(globalOptions.whitelistUrls)
: false;
globalOptions.includePaths = joinRegExp(globalOptions.includePaths);
globalOptions.maxBreadcrumbs = Math.max(
0,
Math.min(globalOptions.maxBreadcrumbs || 100, 100)
); // default and hard limit is 100
var autoBreadcrumbDefaults = {
xhr: true,
console: true,
dom: true,
location: true,
sentry: true
};
var autoBreadcrumbs = globalOptions.autoBreadcrumbs;
if ({}.toString.call(autoBreadcrumbs) === '[object Object]') {
autoBreadcrumbs = objectMerge(autoBreadcrumbDefaults, autoBreadcrumbs);
} else if (autoBreadcrumbs !== false) {
autoBreadcrumbs = autoBreadcrumbDefaults;
}
globalOptions.autoBreadcrumbs = autoBreadcrumbs;
var instrumentDefaults = {
tryCatch: true
};
var instrument = globalOptions.instrument;
if ({}.toString.call(instrument) === '[object Object]') {
instrument = objectMerge(instrumentDefaults, instrument);
} else if (instrument !== false) {
instrument = instrumentDefaults;
}
globalOptions.instrument = instrument;
TraceKit.collectWindowErrors = !!globalOptions.collectWindowErrors;
// return for chaining
return self;
},
/*
* Installs a global window.onerror error handler
* to capture and report uncaught exceptions.
* At this point, install() is required to be called due
* to the way TraceKit is set up.
*
* @return {Raven}
*/
install: function() {
var self = this;
if (self.isSetup() && !self._isRavenInstalled) {
TraceKit.report.subscribe(function() {
self._handleOnErrorStackInfo.apply(self, arguments);
});
if (self._globalOptions.captureUnhandledRejections) {
self._attachPromiseRejectionHandler();
}
self._patchFunctionToString();
if (self._globalOptions.instrument && self._globalOptions.instrument.tryCatch) {
self._instrumentTryCatch();
}
if (self._globalOptions.autoBreadcrumbs) self._instrumentBreadcrumbs();
// Install all of the plugins
self._drainPlugins();
self._isRavenInstalled = true;
}
Error.stackTraceLimit = self._globalOptions.stackTraceLimit;
return this;
},
/*
* Set the DSN (can be called multiple time unlike config)
*
* @param {string} dsn The public Sentry DSN
*/
setDSN: function(dsn) {
var self = this,
uri = self._parseDSN(dsn),
lastSlash = uri.path.lastIndexOf('/'),
path = uri.path.substr(1, lastSlash);
self._dsn = dsn;
self._globalKey = uri.user;
self._globalSecret = uri.pass && uri.pass.substr(1);
self._globalProject = uri.path.substr(lastSlash + 1);
self._globalServer = self._getGlobalServer(uri);
self._globalEndpoint =
self._globalServer + '/' + path + 'api/' + self._globalProject + '/store/';
// Reset backoff state since we may be pointing at a
// new project/server
this._resetBackoff();
},
/*
* Wrap code within a context so Raven can capture errors
* reliably across domains that is executed immediately.
*
* @param {object} options A specific set of options for this context [optional]
* @param {function} func The callback to be immediately executed within the context
* @param {array} args An array of arguments to be called with the callback [optional]
*/
context: function(options, func, args) {
if (isFunction(options)) {
args = func || [];
func = options;
options = undefined;
}
return this.wrap(options, func).apply(this, args);
},
/*
* Wrap code within a context and returns back a new function to be executed
*
* @param {object} options A specific set of options for this context [optional]
* @param {function} func The function to be wrapped in a new context
* @param {function} func A function to call before the try/catch wrapper [optional, private]
* @return {function} The newly wrapped functions with a context
*/
wrap: function(options, func, _before) {
var self = this;
// 1 argument has been passed, and it's not a function
// so just return it
if (isUndefined(func) && !isFunction(options)) {
return options;
}
// options is optional
if (isFunction(options)) {
func = options;
options = undefined;
}
// At this point, we've passed along 2 arguments, and the second one
// is not a function either, so we'll just return the second argument.
if (!isFunction(func)) {
return func;
}
// We don't wanna wrap it twice!
try {
if (func.__raven__) {
return func;
}
// If this has already been wrapped in the past, return that
if (func.__raven_wrapper__) {
return func.__raven_wrapper__;
}
} catch (e) {
// Just accessing custom props in some Selenium environments
// can cause a "Permission denied" exception (see raven-js#495).
// Bail on wrapping and return the function as-is (defers to window.onerror).
return func;
}
function wrapped() {
var args = [],
i = arguments.length,
deep = !options || (options && options.deep !== false);
if (_before && isFunction(_before)) {
_before.apply(this, arguments);
}
// Recursively wrap all of a function's arguments that are
// functions themselves.
while (i--) args[i] = deep ? self.wrap(options, arguments[i]) : arguments[i];
try {
// Attempt to invoke user-land function
// NOTE: If you are a Sentry user, and you are seeing this stack frame, it
// means Raven caught an error invoking your application code. This is
// expected behavior and NOT indicative of a bug with Raven.js.
return func.apply(this, args);
} catch (e) {
self._ignoreNextOnError();
self.captureException(e, options);
throw e;
}
}
// copy over properties of the old function
for (var property in func) {
if (hasKey(func, property)) {
wrapped[property] = func[property];
}
}
wrapped.prototype = func.prototype;
func.__raven_wrapper__ = wrapped;
// Signal that this function has been wrapped/filled already
// for both debugging and to prevent it to being wrapped/filled twice
wrapped.__raven__ = true;
wrapped.__orig__ = func;
return wrapped;
},
/**
* Uninstalls the global error handler.
*
* @return {Raven}
*/
uninstall: function() {
TraceKit.report.uninstall();
this._detachPromiseRejectionHandler();
this._unpatchFunctionToString();
this._restoreBuiltIns();
this._restoreConsole();
Error.stackTraceLimit = this._originalErrorStackTraceLimit;
this._isRavenInstalled = false;
return this;
},
/**
* Callback used for `unhandledrejection` event
*
* @param {PromiseRejectionEvent} event An object containing
* promise: the Promise that was rejected
* reason: the value with which the Promise was rejected
* @return void
*/
_promiseRejectionHandler: function(event) {
this._logDebug('debug', 'Raven caught unhandled promise rejection:', event);
this.captureException(event.reason, {
extra: {
unhandledPromiseRejection: true
}
});
},
/**
* Installs the global promise rejection handler.
*
* @return {raven}
*/
_attachPromiseRejectionHandler: function() {
this._promiseRejectionHandler = this._promiseRejectionHandler.bind(this);
_window.addEventListener &&
_window.addEventListener('unhandledrejection', this._promiseRejectionHandler);
return this;
},
/**
* Uninstalls the global promise rejection handler.
*
* @return {raven}
*/
_detachPromiseRejectionHandler: function() {
_window.removeEventListener &&
_window.removeEventListener('unhandledrejection', this._promiseRejectionHandler);
return this;
},
/**
* Manually capture an exception and send it over to Sentry
*
* @param {error} ex An exception to be logged
* @param {object} options A specific set of options for this error [optional]
* @return {Raven}
*/
captureException: function(ex, options) {
options = objectMerge({trimHeadFrames: 0}, options ? options : {});
if (isErrorEvent(ex) && ex.error) {
// If it is an ErrorEvent with `error` property, extract it to get actual Error
ex = ex.error;
} else if (isDOMError(ex) || isDOMException(ex)) {
// If it is a DOMError or DOMException (which are legacy APIs, but still supported in some browsers)
// then we just extract the name and message, as they don't provide anything else
// https://developer.mozilla.org/en-US/docs/Web/API/DOMError
// https://developer.mozilla.org/en-US/docs/Web/API/DOMException
var name = ex.name || (isDOMError(ex) ? 'DOMError' : 'DOMException');
var message = ex.message ? name + ': ' + ex.message : name;
return this.captureMessage(
message,
objectMerge(options, {
// neither DOMError or DOMException provide stack trace and we most likely wont get it this way as well
// but it's barely any overhead so we may at least try
stacktrace: true,
trimHeadFrames: options.trimHeadFrames + 1
})
);
} else if (isError(ex)) {
// we have a real Error object
ex = ex;
} else if (isPlainObject(ex)) {
// If it is plain Object, serialize it manually and extract options
// This will allow us to group events based on top-level keys
// which is much better than creating new group when any key/value change
options = this._getCaptureExceptionOptionsFromPlainObject(options, ex);
ex = new Error(options.message);
} else {
// If none of previous checks were valid, then it means that
// it's not a DOMError/DOMException
// it's not a plain Object
// it's not a valid ErrorEvent (one with an error property)
// it's not an Error
// So bail out and capture it as a simple message:
return this.captureMessage(
ex,
objectMerge(options, {
stacktrace: true, // if we fall back to captureMessage, default to attempting a new trace
trimHeadFrames: options.trimHeadFrames + 1
})
);
}
// Store the raw exception object for potential debugging and introspection
this._lastCapturedException = ex;
// TraceKit.report will re-raise any exception passed to it,
// which means you have to wrap it in try/catch. Instead, we
// can wrap it here and only re-raise if TraceKit.report
// raises an exception different from the one we asked to
// report on.
try {
var stack = TraceKit.computeStackTrace(ex);
this._handleStackInfo(stack, options);
} catch (ex1) {
if (ex !== ex1) {
throw ex1;
}
}
return this;
},
_getCaptureExceptionOptionsFromPlainObject: function(currentOptions, ex) {
var exKeys = Object.keys(ex).sort();
var options = objectMerge(currentOptions, {
message:
'Non-Error exception captured with keys: ' + serializeKeysForMessage(exKeys),
fingerprint: [md5(exKeys)],
extra: currentOptions.extra || {}
});
options.extra.__serialized__ = serializeException(ex);
return options;
},
/*
* Manually send a message to Sentry
*
* @param {string} msg A plain message to be captured in Sentry
* @param {object} options A specific set of options for this message [optional]
* @return {Raven}
*/
captureMessage: function(msg, options) {
// config() automagically converts ignoreErrors from a list to a RegExp so we need to test for an
// early call; we'll error on the side of logging anything called before configuration since it's
// probably something you should see:
if (
!!this._globalOptions.ignoreErrors.test &&
this._globalOptions.ignoreErrors.test(msg)
) {
return;
}
options = options || {};
msg = msg + ''; // Make sure it's actually a string
var data = objectMerge(
{
message: msg
},
options
);
var ex;
// Generate a "synthetic" stack trace from this point.
// NOTE: If you are a Sentry user, and you are seeing this stack frame, it is NOT indicative
// of a bug with Raven.js. Sentry generates synthetic traces either by configuration,
// or if it catches a thrown object without a "stack" property.
try {
throw new Error(msg);
} catch (ex1) {
ex = ex1;
}
// null exception name so `Error` isn't prefixed to msg
ex.name = null;
var stack = TraceKit.computeStackTrace(ex);
// stack[0] is `throw new Error(msg)` call itself, we are interested in the frame that was just before that, stack[1]
var initialCall = isArray(stack.stack) && stack.stack[1];
// if stack[1] is `Raven.captureException`, it means that someone passed a string to it and we redirected that call
// to be handled by `captureMessage`, thus `initialCall` is the 3rd one, not 2nd
// initialCall => captureException(string) => captureMessage(string)
if (initialCall && initialCall.func === 'Raven.captureException') {
initialCall = stack.stack[2];
}
var fileurl = (initialCall && initialCall.url) || '';
if (
!!this._globalOptions.ignoreUrls.test &&
this._globalOptions.ignoreUrls.test(fileurl)
) {
return;
}
if (
!!this._globalOptions.whitelistUrls.test &&
!this._globalOptions.whitelistUrls.test(fileurl)
) {
return;
}
if (this._globalOptions.stacktrace || (options && options.stacktrace)) {
// fingerprint on msg, not stack trace (legacy behavior, could be revisited)
data.fingerprint = data.fingerprint == null ? msg : data.fingerprint;
options = objectMerge(
{
trimHeadFrames: 0
},
options
);
// Since we know this is a synthetic trace, the top frame (this function call)
// MUST be from Raven.js, so mark it for trimming
// We add to the trim counter so that callers can choose to trim extra frames, such
// as utility functions.
options.trimHeadFrames += 1;
var frames = this._prepareFrames(stack, options);
data.stacktrace = {
// Sentry expects frames oldest to newest
frames: frames.reverse()
};
}
// Make sure that fingerprint is always wrapped in an array
if (data.fingerprint) {
data.fingerprint = isArray(data.fingerprint)
? data.fingerprint
: [data.fingerprint];
}
// Fire away!
this._send(data);
return this;
},
captureBreadcrumb: function(obj) {
var crumb = objectMerge(
{
timestamp: now() / 1000
},
obj
);
if (isFunction(this._globalOptions.breadcrumbCallback)) {
var result = this._globalOptions.breadcrumbCallback(crumb);
if (isObject(result) && !isEmptyObject(result)) {
crumb = result;
} else if (result === false) {
return this;
}
}
this._breadcrumbs.push(crumb);
if (this._breadcrumbs.length > this._globalOptions.maxBreadcrumbs) {
this._breadcrumbs.shift();
}
return this;
},
addPlugin: function(plugin /*arg1, arg2, ... argN*/) {
var pluginArgs = [].slice.call(arguments, 1);
this._plugins.push([plugin, pluginArgs]);
if (this._isRavenInstalled) {
this._drainPlugins();
}
return this;
},
/*
* Set/clear a user to be sent along with the payload.
*
* @param {object} user An object representing user data [optional]
* @return {Raven}
*/
setUserContext: function(user) {
// Intentionally do not merge here since that's an unexpected behavior.
this._globalContext.user = user;
return this;
},
/*
* Merge extra attributes to be sent along with the payload.
*
* @param {object} extra An object representing extra data [optional]
* @return {Raven}
*/
setExtraContext: function(extra) {
this._mergeContext('extra', extra);
return this;
},
/*
* Merge tags to be sent along with the payload.
*
* @param {object} tags An object representing tags [optional]
* @return {Raven}
*/
setTagsContext: function(tags) {
this._mergeContext('tags', tags);
return this;
},
/*
* Clear all of the context.
*
* @return {Raven}
*/
clearContext: function() {
this._globalContext = {};
return this;
},
/*
* Get a copy of the current context. This cannot be mutated.
*
* @return {object} copy of context
*/
getContext: function() {
// lol javascript
return JSON.parse(stringify(this._globalContext));
},
/*
* Set environment of application
*
* @param {string} environment Typically something like 'production'.
* @return {Raven}
*/
setEnvironment: function(environment) {
this._globalOptions.environment = environment;
return this;
},
/*
* Set release version of application
*
* @param {string} release Typically something like a git SHA to identify version
* @return {Raven}
*/
setRelease: function(release) {
this._globalOptions.release = release;
return this;
},
/*
* Set the dataCallback option
*
* @param {function} callback The callback to run which allows the
* data blob to be mutated before sending
* @return {Raven}
*/
setDataCallback: function(callback) {
var original = this._globalOptions.dataCallback;
this._globalOptions.dataCallback = keepOriginalCallback(original, callback);
return this;
},
/*
* Set the breadcrumbCallback option
*
* @param {function} callback The callback to run which allows filtering
* or mutating breadcrumbs
* @return {Raven}
*/
setBreadcrumbCallback: function(callback) {
var original = this._globalOptions.breadcrumbCallback;
this._globalOptions.breadcrumbCallback = keepOriginalCallback(original, callback);
return this;
},
/*
* Set the shouldSendCallback option
*
* @param {function} callback The callback to run which allows
* introspecting the blob before sending
* @return {Raven}
*/
setShouldSendCallback: function(callback) {
var original = this._globalOptions.shouldSendCallback;
this._globalOptions.shouldSendCallback = keepOriginalCallback(original, callback);
return this;
},
/**
* Override the default HTTP transport mechanism that transmits data
* to the Sentry server.
*
* @param {function} transport Function invoked instead of the default
* `makeRequest` handler.
*
* @return {Raven}
*/
setTransport: function(transport) {
this._globalOptions.transport = transport;
return this;
},
/*
* Get the latest raw exception that was captured by Raven.
*
* @return {error}
*/
lastException: function() {
return this._lastCapturedException;
},
/*
* Get the last event id
*
* @return {string}
*/
lastEventId: function() {
return this._lastEventId;
},
/*
* Determine if Raven is setup and ready to go.
*
* @return {boolean}
*/
isSetup: function() {
if (!this._hasJSON) return false; // needs JSON support
if (!this._globalServer) {
if (!this.ravenNotConfiguredError) {
this.ravenNotConfiguredError = true;
this._logDebug('error', 'Error: Raven has not been configured.');
}
return false;
}
return true;
},
afterLoad: function() {
// TODO: remove window dependence?
// Attempt to initialize Raven on load
var RavenConfig = _window.RavenConfig;
if (RavenConfig) {
this.config(RavenConfig.dsn, RavenConfig.config).install();
}
},
showReportDialog: function(options) {
if (
!_document // doesn't work without a document (React native)
)
return;
options = options || {};
var lastEventId = options.eventId || this.lastEventId();
if (!lastEventId) {
throw new RavenConfigError('Missing eventId');
}
var dsn = options.dsn || this._dsn;
if (!dsn) {
throw new RavenConfigError('Missing DSN');
}
var encode = encodeURIComponent;
var qs = '';
qs += '?eventId=' + encode(lastEventId);
qs += '&dsn=' + encode(dsn);
var user = options.user || this._globalContext.user;
if (user) {
if (user.name) qs += '&name=' + encode(user.name);
if (user.email) qs += '&email=' + encode(user.email);
}
var globalServer = this._getGlobalServer(this._parseDSN(dsn));
var script = _document.createElement('script');
script.async = true;
script.src = globalServer + '/api/embed/error-page/' + qs;
(_document.head || _document.body).appendChild(script);
},
/**** Private functions ****/
_ignoreNextOnError: function() {
var self = this;
this._ignoreOnError += 1;
setTimeout(function() {
// onerror should trigger before setTimeout
self._ignoreOnError -= 1;
});
},
_triggerEvent: function(eventType, options) {
// NOTE: `event` is a native browser thing, so let's avoid conflicting wiht it
var evt, key;
if (!this._hasDocument) return;
options = options || {};
eventType = 'raven' + eventType.substr(0, 1).toUpperCase() + eventType.substr(1);
if (_document.createEvent) {
evt = _document.createEvent('HTMLEvents');
evt.initEvent(eventType, true, true);
} else {
evt = _document.createEventObject();
evt.eventType = eventType;
}
for (key in options)
if (hasKey(options, key)) {
evt[key] = options[key];
}
if (_document.createEvent) {
// IE9 if standards
_document.dispatchEvent(evt);
} else {
// IE8 regardless of Quirks or Standards
// IE9 if quirks
try {
_document.fireEvent('on' + evt.eventType.toLowerCase(), evt);
} catch (e) {
// Do nothing
}
}
},
/**
* Wraps addEventListener to capture UI breadcrumbs
* @param evtName the event name (e.g. "click")
* @returns {Function}
* @private
*/
_breadcrumbEventHandler: function(evtName) {
var self = this;
return function(evt) {
// reset keypress timeout; e.g. triggering a 'click' after
// a 'keypress' will reset the keypress debounce so that a new
// set of keypresses can be recorded
self._keypressTimeout = null;
// It's possible this handler might trigger multiple times for the same
// event (e.g. event propagation through node ancestors). Ignore if we've
// already captured the event.
if (self._lastCapturedEvent === evt) return;
self._lastCapturedEvent = evt;
// try/catch both:
// - accessing evt.target (see getsentry/raven-js#838, #768)
// - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly
// can throw an exception in some circumstances.
var target;
try {
target = htmlTreeAsString(evt.target);
} catch (e) {
target = '<unknown>';
}
self.captureBreadcrumb({
category: 'ui.' + evtName, // e.g. ui.click, ui.input
message: target
});
};
},
/**
* Wraps addEventListener to capture keypress UI events
* @returns {Function}
* @private
*/
_keypressEventHandler: function() {
var self = this,
debounceDuration = 1000; // milliseconds
// TODO: if somehow user switches keypress target before
// debounce timeout is triggered, we will only capture
// a single breadcrumb from the FIRST target (acceptable?)
return function(evt) {
var target;
try {
target = evt.target;
} catch (e) {
// just accessing event properties can throw an exception in some rare circumstances
// see: https://github.com/getsentry/raven-js/issues/838
return;
}
var tagName = target && target.tagName;
// only consider keypress events on actual input elements
// this will disregard keypresses targeting body (e.g. tabbing
// through elements, hotkeys, etc)
if (
!tagName ||
(tagName !== 'INPUT' && tagName !== 'TEXTAREA' && !target.isContentEditable)
)
return;
// record first keypress in a series, but ignore subsequent
// keypresses until debounce clears
var timeout = self._keypressTimeout;
if (!timeout) {
self._breadcrumbEventHandler('input')(evt);
}
clearTimeout(timeout);
self._keypressTimeout = setTimeout(function() {
self._keypressTimeout = null;
}, debounceDuration);
};
},
/**
* Captures a breadcrumb of type "navigation", normalizing input URLs
* @param to the originating URL
* @param from the target URL
* @private
*/
_captureUrlChange: function(from, to) {
var parsedLoc = parseUrl(this._location.href);
var parsedTo = parseUrl(to);
var parsedFrom = parseUrl(from);
// because onpopstate only tells you the "new" (to) value of location.href, and
// not the previous (from) value, we need to track the value of the current URL
// state ourselves
this._lastHref = to;
// Use only the path component of the URL if the URL matches the current
// document (almost all the time when using pushState)
if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host)
to = parsedTo.relative;
if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host)
from = parsedFrom.relative;
this.captureBreadcrumb({
category: 'navigation',
data: {
to: to,
from: from
}
});
},
_patchFunctionToString: function() {
var self = this;
self._originalFunctionToString = Function.prototype.toString;
// eslint-disable-next-line no-extend-native
Function.prototype.toString = function() {
if (typeof this === 'function' && this.__raven__) {
return self._originalFunctionToString.apply(this.__orig__, arguments);
}
return self._originalFunctionToString.apply(this, arguments);
};
},
_unpatchFunctionToString: function() {
if (this._originalFunctionToString) {
// eslint-disable-next-line no-extend-native
Function.prototype.toString = this._originalFunctionToString;
}
},
/**
* Wrap timer functions and event targets to catch errors and provide
* better metadata.
*/
_instrumentTryCatch: function() {
var self = this;
var wrappedBuiltIns = self._wrappedBuiltIns;
function wrapTimeFn(orig) {
return function(fn, t) {
// preserve arity
// Make a copy of the arguments to prevent deoptimization
// https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments
var args = new Array(arguments.length);
for (var i = 0; i < args.length; ++i) {
args[i] = arguments[i];
}
var originalCallback = args[0];
if (isFunction(originalCallback)) {
args[0] = self.wrap(originalCallback);
}
// IE < 9 doesn't support .call/.apply on setInterval/setTimeout, but it
// also supports only two arguments and doesn't care what this is, so we
// can just call the original function directly.
if (orig.apply) {
return orig.apply(this, args);
} else {
return orig(args[0], args[1]);
}
};
}
var autoBreadcrumbs = this._globalOptions.autoBreadcrumbs;
function wrapEventTarget(global) {
var proto = _window[global] && _window[global].prototype;
if (proto && proto.hasOwnProperty && proto.hasOwnProperty('addEventListener')) {
fill(
proto,
'addEventListener',
function(orig) {
return function(evtName, fn, capture, secure) {
// preserve arity
try {
if (fn && fn.handleEvent) {
fn.handleEvent = self.wrap(fn.handleEvent);
}
} catch (err) {
// can sometimes get 'Permission denied to access property "handle Event'
}
// More breadcrumb DOM capture ... done here and not in `_instrumentBreadcrumbs`
// so that we don't have more than one wrapper function
var before, clickHandler, keypressHandler;
if (
autoBreadcrumbs &&
autoBreadcrumbs.dom &&
(global === 'EventTarget' || global === 'Node')
) {
// NOTE: generating multiple handlers per addEventListener invocation, should
// revisit and verify we can just use one (almost certainly)
clickHandler = self._breadcrumbEventHandler('click');
keypressHandler = self._keypressEventHandler();
before = function(evt) {
// need to intercept every DOM event in `before` argument, in case that
// same wrapped method is re-used for different events (e.g. mousemove THEN click)
// see #724
if (!evt) return;
var eventType;
try {
eventType = evt.type;
} catch (e) {
// just accessing event properties can throw an exception in some rare circumstances
// see: https://github.com/getsentry/raven-js/issues/838
return;
}
if (eventType === 'click') return clickHandler(evt);
else if (eventType === 'keypress') return keypressHandler(evt);
};
}
return orig.call(
this,
evtName,
self.wrap(fn, undefined, before),
capture,
secure
);
};
},
wrappedBuiltIns
);
fill(
proto,
'removeEventListener',
function(orig) {
return function(evt, fn, capture, secure) {
try {
fn = fn && (fn.__raven_wrapper__ ? fn.__raven_wrapper__ : fn);
} catch (e) {
// ignore, accessing __raven_wrapper__ will throw in some Selenium environments
}
return orig.call(this, evt, fn, capture, secure);
};
},
wrappedBuiltIns
);
}
}
fill(_window, 'setTimeout', wrapTimeFn, wrappedBuiltIns);
fill(_window, 'setInterval', wrapTimeFn, wrappedBuiltIns);
if (_window.requestAnimationFrame) {
fill(
_window,
'requestAnimationFrame',
function(orig) {
return function(cb) {
return orig(self.wrap(cb));
};
},
wrappedBuiltIns
);
}
// event targets borrowed from bugsnag-js:
// https://github.com/bugsnag/bugsnag-js/blob/master/src/bugsnag.js#L666
var eventTargets = [
'EventTarget',
'Window',
'Node',
'ApplicationCache',
'AudioTrackList',
'ChannelMergerNode',
'CryptoOperation',
'EventSource',
'FileReader',
'HTMLUnknownElement',
'IDBDatabase',
'IDBRequest',
'IDBTransaction',
'KeyOperation',
'MediaController',
'MessagePort',
'ModalWindow',
'Notification',
'SVGElementInstance',
'Screen',
'TextTrack',
'TextTrackCue',
'TextTrackList',
'WebSocket',
'WebSocketWorker',
'Worker',
'XMLHttpRequest',
'XMLHttpRequestEventTarget',
'XMLHttpRequestUpload'
];
for (var i = 0; i < eventTargets.length; i++) {
wrapEventTarget(eventTargets[i]);
}
},
/**
* Instrument browser built-ins w/ breadcrumb capturing
* - XMLHttpRequests
* - DOM interactions (click/typing)
* - window.location changes
* - console
*
* Can be disabled or individually configured via the `autoBreadcrumbs` config option
*/
_instrumentBreadcrumbs: function() {
var self = this;
var autoBreadcrumbs = this._globalOptions.autoBreadcrumbs;
var wrappedBuiltIns = self._wrappedBuiltIns;
function wrapProp(prop, xhr) {
if (prop in xhr && isFunction(xhr[prop])) {
fill(xhr, prop, function(orig) {
return self.wrap(orig);
}); // intentionally don't track filled methods on XHR instances
}
}
if (autoBreadcrumbs.xhr && 'XMLHttpRequest' in _window) {
var xhrproto = _window.XMLHttpRequest && _window.XMLHttpRequest.prototype;
fill(
xhrproto,
'open',
function(origOpen) {
return function(method, url) {
// preserve arity
// if Sentry key appears in URL, don't capture
if (isString(url) && url.indexOf(self._globalKey) === -1) {
this.__raven_xhr = {
method: method,
url: url,
status_code: null
};
}
return origOpen.apply(this, arguments);
};
},
wrappedBuiltIns
);
fill(
xhrproto,
'send',
function(origSend) {
return function() {
// preserve arity
var xhr = this;
function onreadystatechangeHandler() {
if (xhr.__raven_xhr && xhr.readyState === 4) {
try {
// touching statusCode in some platforms throws
// an exception
xhr.__raven_xhr.status_code = xhr.status;
} catch (e) {
/* do nothing */
}
self.captureBreadcrumb({
type: 'http',
category: 'xhr',
data: xhr.__raven_xhr
});
}
}
var props = ['onload', 'onerror', 'onprogress'];
for (var j = 0; j < props.length; j++) {
wrapProp(props[j], xhr);
}
if ('onreadystatechange' in xhr && isFunction(xhr.onreadystatechange)) {
fill(
xhr,
'onreadystatechange',
function(orig) {
return self.wrap(orig, undefined, onreadystatechangeHandler);
} /* intentionally don't track this instrumentation */
);
} else {
// if onreadystatechange wasn't actually set by the page on this xhr, we
// are free to set our own and capture the breadcrumb
xhr.onreadystatechange = onreadystatechangeHandler;
}
return origSend.apply(this, arguments);
};
},
wrappedBuiltIns
);
}
if (autoBreadcrumbs.xhr && supportsFetch()) {
fill(
_window,
'fetch',
function(origFetch) {
return function() {
// preserve arity
// Make a copy of the arguments to prevent deoptimization
// https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments
var args = new Array(arguments.length);
for (var i = 0; i < args.length; ++i) {
args[i] = arguments[i];
}
var fetchInput = args[0];
var method = 'GET';
var url;
if (typeof fetchInput === 'string') {
url = fetchInput;
} else if ('Request' in _window && fetchInput instanceof _window.Request) {
url = fetchInput.url;
if (fetchInput.method) {
method = fetchInput.method;
}
} else {
url = '' + fetchInput;
}
// if Sentry key appears in URL, don't capture, as it's our own request
if (url.indexOf(self._globalKey) !== -1) {
return origFetch.apply(this, args);
}
if (args[1] && args[1].method) {
method = args[1].method;
}
var fetchData = {
method: method,
url: url,
status_code: null
};
return origFetch
.apply(this, args)
.then(function(response) {
fetchData.status_code = response.status;
self.captureBreadcrumb({
type: 'http',
category: 'fetch',
data: fetchData
});
return response;
})
['catch'](function(err) {
// if there is an error performing the request
self.captureBreadcrumb({
type: 'http',
category: 'fetch',
data: fetchData,
level: 'error'
});
throw err;
});
};
},
wrappedBuiltIns
);
}
// Capture breadcrumbs from any click that is unhandled / bubbled up all the way
// to the document. Do this before we instrument addEventListener.
if (autoBreadcrumbs.dom && this._hasDocument) {
if (_document.addEventListener) {
_document.addEventListener('click', self._breadcrumbEventHandler('click'), false);
_document.addEventListener('keypress', self._keypressEventHandler(), false);
} else if (_document.attachEvent) {
// IE8 Compatibility
_document.attachEvent('onclick', self._breadcrumbEventHandler('click'));
_document.attachEvent('onkeypress', self._keypressEventHandler());
}
}
// record navigation (URL) changes
// NOTE: in Chrome App environment, touching history.pushState, *even inside
// a try/catch block*, will cause Chrome to output an error to console.error
// borrowed from: https://github.com/angular/angular.js/pull/13945/files
var chrome = _window.chrome;
var isChromePackagedApp = chrome && chrome.app && chrome.app.runtime;
var hasPushAndReplaceState =
!isChromePackagedApp &&
_window.history &&
history.pushState &&
history.replaceState;
if (autoBreadcrumbs.location && hasPushAndReplaceState) {
// TODO: remove onpopstate handler on uninstall()
var oldOnPopState = _window.onpopstate;
_window.onpopstate = function() {
var currentHref = self._location.href;
self._captureUrlChange(self._lastHref, currentHref);
if (oldOnPopState) {
return oldOnPopState.apply(this, arguments);
}
};
var historyReplacementFunction = function(origHistFunction) {
// note history.pushState.length is 0; intentionally not declaring
// params to preserve 0 arity
return function(/* state, title, url */) {
var url = arguments.length > 2 ? arguments[2] : undefined;
// url argument is optional
if (url) {
// coerce to string (this is what pushState does)
self._captureUrlChange(self._lastHref, url + '');
}
return origHistFunction.apply(this, arguments);
};
};
fill(history, 'pushState', historyReplacementFunction, wrappedBuiltIns);
fill(history, 'replaceState', historyReplacementFunction, wrappedBuiltIns);
}
if (autoBreadcrumbs.console && 'console' in _window && console.log) {
// console
var consoleMethodCallback = function(msg, data) {
self.captureBreadcrumb({
message: msg,
level: data.level,
category: 'console'
});
};
each(['debug', 'info', 'warn', 'error', 'log'], function(_, level) {
wrapConsoleMethod(console, level, consoleMethodCallback);
});
}
},
_restoreBuiltIns: function() {
// restore any wrapped builtins
var builtin;
while (this._wrappedBuiltIns.length) {
builtin = this._wrappedBuiltIns.shift();
var obj = builtin[0],
name = builtin[1],
orig = builtin[2];
obj[name] = orig;
}
},
_restoreConsole: function() {
// eslint-disable-next-line guard-for-in
for (var method in this._originalConsoleMethods) {
this._originalConsole[method] = this._originalConsoleMethods[method];
}
},
_drainPlugins: function() {
var self = this;
// FIX ME TODO
each(this._plugins, function(_, plugin) {
var installer = plugin[0];
var args = plugin[1];
installer.apply(self, [self].concat(args));
});
},
_parseDSN: function(str) {
var m = dsnPattern.exec(str),
dsn = {},
i = 7;
try {
while (i--) dsn[dsnKeys[i]] = m[i] || '';
} catch (e) {
throw new RavenConfigError('Invalid DSN: ' + str);
}
if (dsn.pass && !this._globalOptions.allowSecretKey) {
throw new RavenConfigError(
'Do not specify your secret key in the DSN. See: http://bit.ly/raven-secret-key'
);
}
return dsn;
},
_getGlobalServer: function(uri) {
// assemble the endpoint from the uri pieces
var globalServer = '//' + uri.host + (uri.port ? ':' + uri.port : '');
if (uri.protocol) {
globalServer = uri.protocol + ':' + globalServer;
}
return globalServer;
},
_handleOnErrorStackInfo: function() {
// if we are intentionally ignoring errors via onerror, bail out
if (!this._ignoreOnError) {
this._handleStackInfo.apply(this, arguments);
}
},
_handleStackInfo: function(stackInfo, options) {
var frames = this._prepareFrames(stackInfo, options);
this._triggerEvent('handle', {
stackInfo: stackInfo,
options: options
});
this._processException(
stackInfo.name,
stackInfo.message,
stackInfo.url,
stackInfo.lineno,
frames,
options
);
},
_prepareFrames: function(stackInfo, options) {
var self = this;
var frames = [];
if (stackInfo.stack && stackInfo.stack.length) {
each(stackInfo.stack, function(i, stack) {
var frame = self._normalizeFrame(stack, stackInfo.url);
if (frame) {
frames.push(frame);
}
});
// e.g. frames captured via captureMessage throw
if (options && options.trimHeadFrames) {
for (var j = 0; j < options.trimHeadFrames && j < frames.length; j++) {
frames[j].in_app = false;
}
}
}
frames = frames.slice(0, this._globalOptions.stackTraceLimit);
return frames;
},
_normalizeFrame: function(frame, stackInfoUrl) {
// normalize the frames data
var normalized = {
filename: frame.url,
lineno: frame.line,
colno: frame.column,
function: frame.func || '?'
};
// Case when we don't have any information about the error
// E.g. throwing a string or raw object, instead of an `Error` in Firefox
// Generating synthetic error doesn't add any value here
//
// We should probably somehow let a user know that they should fix their code
if (!frame.url) {
normalized.filename = stackInfoUrl; // fallback to whole stacks url from onerror handler
}
normalized.in_app = !// determine if an exception came from outside of our app
// first we check the global includePaths list.
(
(!!this._globalOptions.includePaths.test &&
!this._globalOptions.includePaths.test(normalized.filename)) ||
// Now we check for fun, if the function name is Raven or TraceKit
/(Raven|TraceKit)\./.test(normalized['function']) ||
// finally, we do a last ditch effort and check for raven.min.js
/raven\.(min\.)?js$/.test(normalized.filename)
);
return normalized;
},
_processException: function(type, message, fileurl, lineno, frames, options) {
var prefixedMessage = (type ? type + ': ' : '') + (message || '');
if (
!!this._globalOptions.ignoreErrors.test &&
(this._globalOptions.ignoreErrors.test(message) ||
this._globalOptions.ignoreErrors.test(prefixedMessage))
) {
return;
}
var stacktrace;
if (frames && frames.length) {
fileurl = frames[0].filename || fileurl;
// Sentry expects frames oldest to newest
// and JS sends them as newest to oldest
frames.reverse();
stacktrace = {frames: frames};
} else if (fileurl) {
stacktrace = {
frames: [
{
filename: fileurl,
lineno: lineno,
in_app: true
}
]
};
}
if (
!!this._globalOptions.ignoreUrls.test &&
this._globalOptions.ignoreUrls.test(fileurl)
) {
return;
}
if (
!!this._globalOptions.whitelistUrls.test &&
!this._globalOptions.whitelistUrls.test(fileurl)
) {
return;
}
var data = objectMerge(
{
// sentry.interfaces.Exception
exception: {
values: [
{
type: type,
value: message,
stacktrace: stacktrace
}
]
},
culprit: fileurl
},
options
);
// Fire away!
this._send(data);
},
_trimPacket: function(data) {
// For now, we only want to truncate the two different messages
// but this could/should be expanded to just trim everything
var max = this._globalOptions.maxMessageLength;
if (data.message) {
data.message = truncate(data.message, max);
}
if (data.exception) {
var exception = data.exception.values[0];
exception.value = truncate(exception.value, max);
}
var request = data.request;
if (request) {
if (request.url) {
request.url = truncate(request.url, this._globalOptions.maxUrlLength);
}
if (request.Referer) {
request.Referer = truncate(request.Referer, this._globalOptions.maxUrlLength);
}
}
if (data.breadcrumbs && data.breadcrumbs.values)
this._trimBreadcrumbs(data.breadcrumbs);
return data;
},
/**
* Truncate breadcrumb values (right now just URLs)
*/
_trimBreadcrumbs: function(breadcrumbs) {
// known breadcrumb properties with urls
// TODO: also consider arbitrary prop values that start with (https?)?://
var urlProps = ['to', 'from', 'url'],
urlProp,
crumb,
data;
for (var i = 0; i < breadcrumbs.values.length; ++i) {
crumb = breadcrumbs.values[i];
if (
!crumb.hasOwnProperty('data') ||
!isObject(crumb.data) ||
objectFrozen(crumb.data)
)
continue;
data = objectMerge({}, crumb.data);
for (var j = 0; j < urlProps.length; ++j) {
urlProp = urlProps[j];
if (data.hasOwnProperty(urlProp) && data[urlProp]) {
data[urlProp] = truncate(data[urlProp], this._globalOptions.maxUrlLength);
}
}
breadcrumbs.values[i].data = data;
}
},
_getHttpData: function() {
if (!this._hasNavigator && !this._hasDocument) return;
var httpData = {};
if (this._hasNavigator && _navigator.userAgent) {
httpData.headers = {
'User-Agent': navigator.userAgent
};
}
// Check in `window` instead of `document`, as we may be in ServiceWorker environment
if (_window.location && _window.location.href) {
httpData.url = _window.location.href;
}
if (this._hasDocument && _document.referrer) {
if (!httpData.headers) httpData.headers = {};
httpData.headers.Referer = _document.referrer;
}
return httpData;
},
_resetBackoff: function() {
this._backoffDuration = 0;
this._backoffStart = null;
},
_shouldBackoff: function() {
return this._backoffDuration && now() - this._backoffStart < this._backoffDuration;
},
/**
* Returns true if the in-process data payload matches the signature
* of the previously-sent data
*
* NOTE: This has to be done at this level because TraceKit can generate
* data from window.onerror WITHOUT an exception object (IE8, IE9,
* other old browsers). This can take the form of an "exception"
* data object with a single frame (derived from the onerror args).
*/
_isRepeatData: function(current) {
var last = this._lastData;
if (
!last ||
current.message !== last.message || // defined for captureMessage
current.culprit !== last.culprit // defined for captureException/onerror
)
return false;
// Stacktrace interface (i.e. from captureMessage)
if (current.stacktrace || last.stacktrace) {
return isSameStacktrace(current.stacktrace, last.stacktrace);
} else if (current.exception || last.exception) {
// Exception interface (i.e. from captureException/onerror)
return isSameException(current.exception, last.exception);
}
return true;
},
_setBackoffState: function(request) {
// If we are already in a backoff state, don't change anything
if (this._shouldBackoff()) {
return;
}
var status = request.status;
// 400 - project_id doesn't exist or some other fatal
// 401 - invalid/revoked dsn
// 429 - too many requests
if (!(status === 400 || status === 401 || status === 429)) return;
var retry;
try {
// If Retry-After is not in Access-Control-Expose-Headers, most
// browsers will throw an exception trying to access it
if (supportsFetch()) {
retry = request.headers.get('Retry-After');
} else {
retry = request.getResponseHeader('Retry-After');
}
// Retry-After is returned in seconds
retry = parseInt(retry, 10) * 1000;
} catch (e) {
/* eslint no-empty:0 */
}
this._backoffDuration = retry
? // If Sentry server returned a Retry-After value, use it
retry
: // Otherwise, double the last backoff duration (starts at 1 sec)
this._backoffDuration * 2 || 1000;
this._backoffStart = now();
},
_send: function(data) {
var globalOptions = this._globalOptions;
var baseData = {
project: this._globalProject,
logger: globalOptions.logger,
platform: 'javascript'
},
httpData = this._getHttpData();
if (httpData) {
baseData.request = httpData;
}
// HACK: delete `trimHeadFrames` to prevent from appearing in outbound payload
if (data.trimHeadFrames) delete data.trimHeadFrames;
data = objectMerge(baseData, data);
// Merge in the tags and extra separately since objectMerge doesn't handle a deep merge
data.tags = objectMerge(objectMerge({}, this._globalContext.tags), data.tags);
data.extra = objectMerge(objectMerge({}, this._globalContext.extra), data.extra);
// Send along our own collected metadata with extra
data.extra['session:duration'] = now() - this._startTime;
if (this._breadcrumbs && this._breadcrumbs.length > 0) {
// intentionally make shallow copy so that additions
// to breadcrumbs aren't accidentally sent in this request
data.breadcrumbs = {
values: [].slice.call(this._breadcrumbs, 0)
};
}
if (this._globalContext.user) {
// sentry.interfaces.User
data.user = this._globalContext.user;
}
// Include the environment if it's defined in globalOptions
if (globalOptions.environment) data.environment = globalOptions.environment;
// Include the release if it's defined in globalOptions
if (globalOptions.release) data.release = globalOptions.release;
// Include server_name if it's defined in globalOptions
if (globalOptions.serverName) data.server_name = globalOptions.serverName;
data = this._sanitizeData(data);
// Cleanup empty properties before sending them to the server
Object.keys(data).forEach(function(key) {
if (data[key] == null || data[key] === '' || isEmptyObject(data[key])) {
delete data[key];
}
});
if (isFunction(globalOptions.dataCallback)) {
data = globalOptions.dataCallback(data) || data;
}
// Why??????????
if (!data || isEmptyObject(data)) {
return;
}
// Check if the request should be filtered or not
if (
isFunction(globalOptions.shouldSendCallback) &&
!globalOptions.shouldSendCallback(data)
) {
return;
}
// Backoff state: Sentry server previously responded w/ an error (e.g. 429 - too many requests),
// so drop requests until "cool-off" period has elapsed.
if (this._shouldBackoff()) {
this._logDebug('warn', 'Raven dropped error due to backoff: ', data);
return;
}
if (typeof globalOptions.sampleRate === 'number') {
if (Math.random() < globalOptions.sampleRate) {
this._sendProcessedPayload(data);
}
} else {
this._sendProcessedPayload(data);
}
},
_sanitizeData: function(data) {
return sanitize(data, this._globalOptions.sanitizeKeys);
},
_getUuid: function() {
return uuid4();
},
_sendProcessedPayload: function(data, callback) {
var self = this;
var globalOptions = this._globalOptions;
if (!this.isSetup()) return;
// Try and clean up the packet before sending by truncating long values
data = this._trimPacket(data);
// ideally duplicate error testing should occur *before* dataCallback/shouldSendCallback,
// but this would require copying an un-truncated copy of the data packet, which can be
// arbitrarily deep (extra_data) -- could be worthwhile? will revisit
if (!this._globalOptions.allowDuplicates && this._isRepeatData(data)) {
this._logDebug('warn', 'Raven dropped repeat event: ', data);
return;
}
// Send along an event_id if not explicitly passed.
// This event_id can be used to reference the error within Sentry itself.
// Set lastEventId after we know the error should actually be sent
this._lastEventId = data.event_id || (data.event_id = this._getUuid());
// Store outbound payload after trim
this._lastData = data;
this._logDebug('debug', 'Raven about to send:', data);
var auth = {
sentry_version: '7',
sentry_client: 'raven-js/' + this.VERSION,
sentry_key: this._globalKey
};
if (this._globalSecret) {
auth.sentry_secret = this._globalSecret;
}
var exception = data.exception && data.exception.values[0];
// only capture 'sentry' breadcrumb is autoBreadcrumbs is truthy
if (
this._globalOptions.autoBreadcrumbs &&
this._globalOptions.autoBreadcrumbs.sentry
) {
this.captureBreadcrumb({
category: 'sentry',
message: exception
? (exception.type ? exception.type + ': ' : '') + exception.value
: data.message,
event_id: data.event_id,
level: data.level || 'error' // presume error unless specified
});
}
var url = this._globalEndpoint;
(globalOptions.transport || this._makeRequest).call(this, {
url: url,
auth: auth,
data: data,
options: globalOptions,
onSuccess: function success() {
self._resetBackoff();
self._triggerEvent('success', {
data: data,
src: url
});
callback && callback();
},
onError: function failure(error) {
self._logDebug('error', 'Raven transport failed to send: ', error);
if (error.request) {
self._setBackoffState(error.request);
}
self._triggerEvent('failure', {
data: data,
src: url
});
error = error || new Error('Raven send failed (no additional details provided)');
callback && callback(error);
}
});
},
_makeRequest: function(opts) {
// Auth is intentionally sent as part of query string (NOT as custom HTTP header) to avoid preflight CORS requests
var url = opts.url + '?' + urlencode(opts.auth);
var evaluatedHeaders = null;
var evaluatedFetchParameters = {};
if (opts.options.headers) {
evaluatedHeaders = this._evaluateHash(opts.options.headers);
}
if (opts.options.fetchParameters) {
evaluatedFetchParameters = this._evaluateHash(opts.options.fetchParameters);
}
if (supportsFetch()) {
evaluatedFetchParameters.body = stringify(opts.data);
var defaultFetchOptions = objectMerge({}, this._fetchDefaults);
var fetchOptions = objectMerge(defaultFetchOptions, evaluatedFetchParameters);
if (evaluatedHeaders) {
fetchOptions.headers = evaluatedHeaders;
}
return _window
.fetch(url, fetchOptions)
.then(function(response) {
if (response.ok) {
opts.onSuccess && opts.onSuccess();
} else {
var error = new Error('Sentry error code: ' + response.status);
// It's called request only to keep compatibility with XHR interface
// and not add more redundant checks in setBackoffState method
error.request = response;
opts.onError && opts.onError(error);
}
})
['catch'](function() {
opts.onError &&
opts.onError(new Error('Sentry error code: network unavailable'));
});
}
var request = _window.XMLHttpRequest && new _window.XMLHttpRequest();
if (!request) return;
// if browser doesn't support CORS (e.g. IE7), we are out of luck
var hasCORS = 'withCredentials' in request || typeof XDomainRequest !== 'undefined';
if (!hasCORS) return;
if ('withCredentials' in request) {
request.onreadystatechange = function() {
if (request.readyState !== 4) {
return;
} else if (request.status === 200) {
opts.onSuccess && opts.onSuccess();
} else if (opts.onError) {
var err = new Error('Sentry error code: ' + request.status);
err.request = request;
opts.onError(err);
}
};
} else {
request = new XDomainRequest();
// xdomainrequest cannot go http -> https (or vice versa),
// so always use protocol relative
url = url.replace(/^https?:/, '');
// onreadystatechange not supported by XDomainRequest
if (opts.onSuccess) {
request.onload = opts.onSuccess;
}
if (opts.onError) {
request.onerror = function() {
var err = new Error('Sentry error code: XDomainRequest');
err.request = request;
opts.onError(err);
};
}
}
request.open('POST', url);
if (evaluatedHeaders) {
each(evaluatedHeaders, function(key, value) {
request.setRequestHeader(key, value);
});
}
request.send(stringify(opts.data));
},
_evaluateHash: function(hash) {
var evaluated = {};
for (var key in hash) {
if (hash.hasOwnProperty(key)) {
var value = hash[key];
evaluated[key] = typeof value === 'function' ? value() : value;
}
}
return evaluated;
},
_logDebug: function(level) {
// We allow `Raven.debug` and `Raven.config(DSN, { debug: true })` to not make backward incompatible API change
if (
this._originalConsoleMethods[level] &&
(this.debug || this._globalOptions.debug)
) {
// In IE<10 console methods do not have their own 'apply' method
Function.prototype.apply.call(
this._originalConsoleMethods[level],
this._originalConsole,
[].slice.call(arguments, 1)
);
}
},
_mergeContext: function(key, context) {
if (isUndefined(context)) {
delete this._globalContext[key];
} else {
this._globalContext[key] = objectMerge(this._globalContext[key] || {}, context);
}
}
};
// Deprecations
Raven.prototype.setUser = Raven.prototype.setUserContext;
Raven.prototype.setReleaseContext = Raven.prototype.setRelease;
module.exports = Raven;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"10":10,"11":11,"12":12,"5":5,"6":6,"9":9}],8:[function(_dereq_,module,exports){
(function (global){
/**
* Enforces a single instance of the Raven client, and the
* main entry point for Raven. If you are a consumer of the
* Raven library, you SHOULD load this file (vs raven.js).
**/
var RavenConstructor = _dereq_(7);
// This is to be defensive in environments where window does not exist (see https://github.com/getsentry/raven-js/pull/785)
var _window =
typeof window !== 'undefined'
? window
: typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
var _Raven = _window.Raven;
var Raven = new RavenConstructor();
/*
* Allow multiple versions of Raven to be installed.
* Strip Raven from the global context and returns the instance.
*
* @return {Raven}
*/
Raven.noConflict = function() {
_window.Raven = _Raven;
return Raven;
};
Raven.afterLoad();
module.exports = Raven;
/**
* DISCLAIMER:
*
* Expose `Client` constructor for cases where user want to track multiple "sub-applications" in one larger app.
* It's not meant to be used by a wide audience, so pleaaase make sure that you know what you're doing before using it.
* Accidentally calling `install` multiple times, may result in an unexpected behavior that's very hard to debug.
*
* It's called `Client' to be in-line with Raven Node implementation.
*
* HOWTO:
*
* import Raven from 'raven-js';
*
* const someAppReporter = new Raven.Client();
* const someOtherAppReporter = new Raven.Client();
*
* someAppReporter.config('__DSN__', {
* ...config goes here
* });
*
* someOtherAppReporter.config('__OTHER_DSN__', {
* ...config goes here
* });
*
* someAppReporter.captureMessage(...);
* someAppReporter.captureException(...);
* someAppReporter.captureBreadcrumb(...);
*
* someOtherAppReporter.captureMessage(...);
* someOtherAppReporter.captureException(...);
* someOtherAppReporter.captureBreadcrumb(...);
*
* It should "just work".
*/
module.exports.Client = RavenConstructor;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"7":7}],9:[function(_dereq_,module,exports){
(function (global){
var stringify = _dereq_(11);
var _window =
typeof window !== 'undefined'
? window
: typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function isObject(what) {
return typeof what === 'object' && what !== null;
}
// Yanked from https://git.io/vS8DV re-used under CC0
// with some tiny modifications
function isError(value) {
switch (Object.prototype.toString.call(value)) {
case '[object Error]':
return true;
case '[object Exception]':
return true;
case '[object DOMException]':
return true;
default:
return value instanceof Error;
}
}
function isErrorEvent(value) {
return Object.prototype.toString.call(value) === '[object ErrorEvent]';
}
function isDOMError(value) {
return Object.prototype.toString.call(value) === '[object DOMError]';
}
function isDOMException(value) {
return Object.prototype.toString.call(value) === '[object DOMException]';
}
function isUndefined(what) {
return what === void 0;
}
function isFunction(what) {
return typeof what === 'function';
}
function isPlainObject(what) {
return Object.prototype.toString.call(what) === '[object Object]';
}
function isString(what) {
return Object.prototype.toString.call(what) === '[object String]';
}
function isArray(what) {
return Object.prototype.toString.call(what) === '[object Array]';
}
function isEmptyObject(what) {
if (!isPlainObject(what)) return false;
for (var _ in what) {
if (what.hasOwnProperty(_)) {
return false;
}
}
return true;
}
function supportsErrorEvent() {
try {
new ErrorEvent(''); // eslint-disable-line no-new
return true;
} catch (e) {
return false;
}
}
function supportsDOMError() {
try {
new DOMError(''); // eslint-disable-line no-new
return true;
} catch (e) {
return false;
}
}
function supportsDOMException() {
try {
new DOMException(''); // eslint-disable-line no-new
return true;
} catch (e) {
return false;
}
}
function supportsFetch() {
if (!('fetch' in _window)) return false;
try {
new Headers(); // eslint-disable-line no-new
new Request(''); // eslint-disable-line no-new
new Response(); // eslint-disable-line no-new
return true;
} catch (e) {
return false;
}
}
// Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default
// https://caniuse.com/#feat=referrer-policy
// It doesn't. And it throw exception instead of ignoring this parameter...
// REF: https://github.com/getsentry/raven-js/issues/1233
function supportsReferrerPolicy() {
if (!supportsFetch()) return false;
try {
// eslint-disable-next-line no-new
new Request('pickleRick', {
referrerPolicy: 'origin'
});
return true;
} catch (e) {
return false;
}
}
function supportsPromiseRejectionEvent() {
return typeof PromiseRejectionEvent === 'function';
}
function wrappedCallback(callback) {
function dataCallback(data, original) {
var normalizedData = callback(data) || data;
if (original) {
return original(normalizedData) || normalizedData;
}
return normalizedData;
}
return dataCallback;
}
function each(obj, callback) {
var i, j;
if (isUndefined(obj.length)) {
for (i in obj) {
if (hasKey(obj, i)) {
callback.call(null, i, obj[i]);
}
}
} else {
j = obj.length;
if (j) {
for (i = 0; i < j; i++) {
callback.call(null, i, obj[i]);
}
}
}
}
function objectMerge(obj1, obj2) {
if (!obj2) {
return obj1;
}
each(obj2, function(key, value) {
obj1[key] = value;
});
return obj1;
}
/**
* This function is only used for react-native.
* react-native freezes object that have already been sent over the
* js bridge. We need this function in order to check if the object is frozen.
* So it's ok that objectFrozen returns false if Object.isFrozen is not
* supported because it's not relevant for other "platforms". See related issue:
* https://github.com/getsentry/react-native-sentry/issues/57
*/
function objectFrozen(obj) {
if (!Object.isFrozen) {
return false;
}
return Object.isFrozen(obj);
}
function truncate(str, max) {
if (typeof max !== 'number') {
throw new Error('2nd argument to `truncate` function should be a number');
}
if (typeof str !== 'string' || max === 0) {
return str;
}
return str.length <= max ? str : str.substr(0, max) + '\u2026';
}
/**
* hasKey, a better form of hasOwnProperty
* Example: hasKey(MainHostObject, property) === true/false
*
* @param {Object} host object to check property
* @param {string} key to check
*/
function hasKey(object, key) {
return Object.prototype.hasOwnProperty.call(object, key);
}
function joinRegExp(patterns) {
// Combine an array of regular expressions and strings into one large regexp
// Be mad.
var sources = [],
i = 0,
len = patterns.length,
pattern;
for (; i < len; i++) {
pattern = patterns[i];
if (isString(pattern)) {
// If it's a string, we need to escape it
// Taken from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
sources.push(pattern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'));
} else if (pattern && pattern.source) {
// If it's a regexp already, we want to extract the source
sources.push(pattern.source);
}
// Intentionally skip other cases
}
return new RegExp(sources.join('|'), 'i');
}
function urlencode(o) {
var pairs = [];
each(o, function(key, value) {
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
});
return pairs.join('&');
}
// borrowed from https://tools.ietf.org/html/rfc3986#appendix-B
// intentionally using regex and not <a/> href parsing trick because React Native and other
// environments where DOM might not be available
function parseUrl(url) {
if (typeof url !== 'string') return {};
var match = url.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);
// coerce to undefined values to empty string so we don't get 'undefined'
var query = match[6] || '';
var fragment = match[8] || '';
return {
protocol: match[2],
host: match[4],
path: match[5],
relative: match[5] + query + fragment // everything minus origin
};
}
function uuid4() {
var crypto = _window.crypto || _window.msCrypto;
if (!isUndefined(crypto) && crypto.getRandomValues) {
// Use window.crypto API if available
// eslint-disable-next-line no-undef
var arr = new Uint16Array(8);
crypto.getRandomValues(arr);
// set 4 in byte 7
arr[3] = (arr[3] & 0xfff) | 0x4000;
// set 2 most significant bits of byte 9 to '10'
arr[4] = (arr[4] & 0x3fff) | 0x8000;
var pad = function(num) {
var v = num.toString(16);
while (v.length < 4) {
v = '0' + v;
}
return v;
};
return (
pad(arr[0]) +
pad(arr[1]) +
pad(arr[2]) +
pad(arr[3]) +
pad(arr[4]) +
pad(arr[5]) +
pad(arr[6]) +
pad(arr[7])
);
} else {
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (Math.random() * 16) | 0,
v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
}
/**
* Given a child DOM element, returns a query-selector statement describing that
* and its ancestors
* e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]
* @param elem
* @returns {string}
*/
function htmlTreeAsString(elem) {
/* eslint no-extra-parens:0*/
var MAX_TRAVERSE_HEIGHT = 5,
MAX_OUTPUT_LEN = 80,
out = [],
height = 0,
len = 0,
separator = ' > ',
sepLength = separator.length,
nextStr;
while (elem && height++ < MAX_TRAVERSE_HEIGHT) {
nextStr = htmlElementAsString(elem);
// bail out if
// - nextStr is the 'html' element
// - the length of the string that would be created exceeds MAX_OUTPUT_LEN
// (ignore this limit if we are on the first iteration)
if (
nextStr === 'html' ||
(height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)
) {
break;
}
out.push(nextStr);
len += nextStr.length;
elem = elem.parentNode;
}
return out.reverse().join(separator);
}
/**
* Returns a simple, query-selector representation of a DOM element
* e.g. [HTMLElement] => input#foo.btn[name=baz]
* @param HTMLElement
* @returns {string}
*/
function htmlElementAsString(elem) {
var out = [],
className,
classes,
key,
attr,
i;
if (!elem || !elem.tagName) {
return '';
}
out.push(elem.tagName.toLowerCase());
if (elem.id) {
out.push('#' + elem.id);
}
className = elem.className;
if (className && isString(className)) {
classes = className.split(/\s+/);
for (i = 0; i < classes.length; i++) {
out.push('.' + classes[i]);
}
}
var attrWhitelist = ['type', 'name', 'title', 'alt'];
for (i = 0; i < attrWhitelist.length; i++) {
key = attrWhitelist[i];
attr = elem.getAttribute(key);
if (attr) {
out.push('[' + key + '="' + attr + '"]');
}
}
return out.join('');
}
/**
* Returns true if either a OR b is truthy, but not both
*/
function isOnlyOneTruthy(a, b) {
return !!(!!a ^ !!b);
}
/**
* Returns true if both parameters are undefined
*/
function isBothUndefined(a, b) {
return isUndefined(a) && isUndefined(b);
}
/**
* Returns true if the two input exception interfaces have the same content
*/
function isSameException(ex1, ex2) {
if (isOnlyOneTruthy(ex1, ex2)) return false;
ex1 = ex1.values[0];
ex2 = ex2.values[0];
if (ex1.type !== ex2.type || ex1.value !== ex2.value) return false;
// in case both stacktraces are undefined, we can't decide so default to false
if (isBothUndefined(ex1.stacktrace, ex2.stacktrace)) return false;
return isSameStacktrace(ex1.stacktrace, ex2.stacktrace);
}
/**
* Returns true if the two input stack trace interfaces have the same content
*/
function isSameStacktrace(stack1, stack2) {
if (isOnlyOneTruthy(stack1, stack2)) return false;
var frames1 = stack1.frames;
var frames2 = stack2.frames;
// Exit early if frame count differs
if (frames1.length !== frames2.length) return false;
// Iterate through every frame; bail out if anything differs
var a, b;
for (var i = 0; i < frames1.length; i++) {
a = frames1[i];
b = frames2[i];
if (
a.filename !== b.filename ||
a.lineno !== b.lineno ||
a.colno !== b.colno ||
a['function'] !== b['function']
)
return false;
}
return true;
}
/**
* Polyfill a method
* @param obj object e.g. `document`
* @param name method name present on object e.g. `addEventListener`
* @param replacement replacement function
* @param track {optional} record instrumentation to an array
*/
function fill(obj, name, replacement, track) {
if (obj == null) return;
var orig = obj[name];
obj[name] = replacement(orig);
obj[name].__raven__ = true;
obj[name].__orig__ = orig;
if (track) {
track.push([obj, name, orig]);
}
}
/**
* Join values in array
* @param input array of values to be joined together
* @param delimiter string to be placed in-between values
* @returns {string}
*/
function safeJoin(input, delimiter) {
if (!isArray(input)) return '';
var output = [];
for (var i = 0; i < input.length; i++) {
try {
output.push(String(input[i]));
} catch (e) {
output.push('[value cannot be serialized]');
}
}
return output.join(delimiter);
}
// Default Node.js REPL depth
var MAX_SERIALIZE_EXCEPTION_DEPTH = 3;
// 50kB, as 100kB is max payload size, so half sounds reasonable
var MAX_SERIALIZE_EXCEPTION_SIZE = 50 * 1024;
var MAX_SERIALIZE_KEYS_LENGTH = 40;
function utf8Length(value) {
return ~-encodeURI(value).split(/%..|./).length;
}
function jsonSize(value) {
return utf8Length(JSON.stringify(value));
}
function serializeValue(value) {
if (typeof value === 'string') {
var maxLength = 40;
return truncate(value, maxLength);
} else if (
typeof value === 'number' ||
typeof value === 'boolean' ||
typeof value === 'undefined'
) {
return value;
}
var type = Object.prototype.toString.call(value);
// Node.js REPL notation
if (type === '[object Object]') return '[Object]';
if (type === '[object Array]') return '[Array]';
if (type === '[object Function]')
return value.name ? '[Function: ' + value.name + ']' : '[Function]';
return value;
}
function serializeObject(value, depth) {
if (depth === 0) return serializeValue(value);
if (isPlainObject(value)) {
return Object.keys(value).reduce(function(acc, key) {
acc[key] = serializeObject(value[key], depth - 1);
return acc;
}, {});
} else if (Array.isArray(value)) {
return value.map(function(val) {
return serializeObject(val, depth - 1);
});
}
return serializeValue(value);
}
function serializeException(ex, depth, maxSize) {
if (!isPlainObject(ex)) return ex;
depth = typeof depth !== 'number' ? MAX_SERIALIZE_EXCEPTION_DEPTH : depth;
maxSize = typeof depth !== 'number' ? MAX_SERIALIZE_EXCEPTION_SIZE : maxSize;
var serialized = serializeObject(ex, depth);
if (jsonSize(stringify(serialized)) > maxSize) {
return serializeException(ex, depth - 1);
}
return serialized;
}
function serializeKeysForMessage(keys, maxLength) {
if (typeof keys === 'number' || typeof keys === 'string') return keys.toString();
if (!Array.isArray(keys)) return '';
keys = keys.filter(function(key) {
return typeof key === 'string';
});
if (keys.length === 0) return '[object has no keys]';
maxLength = typeof maxLength !== 'number' ? MAX_SERIALIZE_KEYS_LENGTH : maxLength;
if (keys[0].length >= maxLength) return keys[0];
for (var usedKeys = keys.length; usedKeys > 0; usedKeys--) {
var serialized = keys.slice(0, usedKeys).join(', ');
if (serialized.length > maxLength) continue;
if (usedKeys === keys.length) return serialized;
return serialized + '\u2026';
}
return '';
}
function sanitize(input, sanitizeKeys) {
if (!isArray(sanitizeKeys) || (isArray(sanitizeKeys) && sanitizeKeys.length === 0))
return input;
var sanitizeRegExp = joinRegExp(sanitizeKeys);
var sanitizeMask = '********';
var safeInput;
try {
safeInput = JSON.parse(stringify(input));
} catch (o_O) {
return input;
}
function sanitizeWorker(workerInput) {
if (isArray(workerInput)) {
return workerInput.map(function(val) {
return sanitizeWorker(val);
});
}
if (isPlainObject(workerInput)) {
return Object.keys(workerInput).reduce(function(acc, k) {
if (sanitizeRegExp.test(k)) {
acc[k] = sanitizeMask;
} else {
acc[k] = sanitizeWorker(workerInput[k]);
}
return acc;
}, {});
}
return workerInput;
}
return sanitizeWorker(safeInput);
}
module.exports = {
isObject: isObject,
isError: isError,
isErrorEvent: isErrorEvent,
isDOMError: isDOMError,
isDOMException: isDOMException,
isUndefined: isUndefined,
isFunction: isFunction,
isPlainObject: isPlainObject,
isString: isString,
isArray: isArray,
isEmptyObject: isEmptyObject,
supportsErrorEvent: supportsErrorEvent,
supportsDOMError: supportsDOMError,
supportsDOMException: supportsDOMException,
supportsFetch: supportsFetch,
supportsReferrerPolicy: supportsReferrerPolicy,
supportsPromiseRejectionEvent: supportsPromiseRejectionEvent,
wrappedCallback: wrappedCallback,
each: each,
objectMerge: objectMerge,
truncate: truncate,
objectFrozen: objectFrozen,
hasKey: hasKey,
joinRegExp: joinRegExp,
urlencode: urlencode,
uuid4: uuid4,
htmlTreeAsString: htmlTreeAsString,
htmlElementAsString: htmlElementAsString,
isSameException: isSameException,
isSameStacktrace: isSameStacktrace,
parseUrl: parseUrl,
fill: fill,
safeJoin: safeJoin,
serializeException: serializeException,
serializeKeysForMessage: serializeKeysForMessage,
sanitize: sanitize
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"11":11}],10:[function(_dereq_,module,exports){
(function (global){
var utils = _dereq_(9);
/*
TraceKit - Cross brower stack traces
This was originally forked from github.com/occ/TraceKit, but has since been
largely re-written and is now maintained as part of raven-js. Tests for
this are in test/vendor.
MIT license
*/
var TraceKit = {
collectWindowErrors: true,
debug: false
};
// This is to be defensive in environments where window does not exist (see https://github.com/getsentry/raven-js/pull/785)
var _window =
typeof window !== 'undefined'
? window
: typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
// global reference to slice
var _slice = [].slice;
var UNKNOWN_FUNCTION = '?';
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Error_types
var ERROR_TYPES_RE = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/;
function getLocationHref() {
if (typeof document === 'undefined' || document.location == null) return '';
return document.location.href;
}
function getLocationOrigin() {
if (typeof document === 'undefined' || document.location == null) return '';
return document.location.origin;
}
/**
* TraceKit.report: cross-browser processing of unhandled exceptions
*
* Syntax:
* TraceKit.report.subscribe(function(stackInfo) { ... })
* TraceKit.report.unsubscribe(function(stackInfo) { ... })
* TraceKit.report(exception)
* try { ...code... } catch(ex) { TraceKit.report(ex); }
*
* Supports:
* - Firefox: full stack trace with line numbers, plus column number
* on top frame; column number is not guaranteed
* - Opera: full stack trace with line and column numbers
* - Chrome: full stack trace with line and column numbers
* - Safari: line and column number for the top frame only; some frames
* may be missing, and column number is not guaranteed
* - IE: line and column number for the top frame only; some frames
* may be missing, and column number is not guaranteed
*
* In theory, TraceKit should work on all of the following versions:
* - IE5.5+ (only 8.0 tested)
* - Firefox 0.9+ (only 3.5+ tested)
* - Opera 7+ (only 10.50 tested; versions 9 and earlier may require
* Exceptions Have Stacktrace to be enabled in opera:config)
* - Safari 3+ (only 4+ tested)
* - Chrome 1+ (only 5+ tested)
* - Konqueror 3.5+ (untested)
*
* Requires TraceKit.computeStackTrace.
*
* Tries to catch all unhandled exceptions and report them to the
* subscribed handlers. Please note that TraceKit.report will rethrow the
* exception. This is REQUIRED in order to get a useful stack trace in IE.
* If the exception does not reach the top of the browser, you will only
* get a stack trace from the point where TraceKit.report was called.
*
* Handlers receive a stackInfo object as described in the
* TraceKit.computeStackTrace docs.
*/
TraceKit.report = (function reportModuleWrapper() {
var handlers = [],
lastArgs = null,
lastException = null,
lastExceptionStack = null;
/**
* Add a crash handler.
* @param {Function} handler
*/
function subscribe(handler) {
installGlobalHandler();
handlers.push(handler);
}
/**
* Remove a crash handler.
* @param {Function} handler
*/
function unsubscribe(handler) {
for (var i = handlers.length - 1; i >= 0; --i) {
if (handlers[i] === handler) {
handlers.splice(i, 1);
}
}
}
/**
* Remove all crash handlers.
*/
function unsubscribeAll() {
uninstallGlobalHandler();
handlers = [];
}
/**
* Dispatch stack information to all handlers.
* @param {Object.<string, *>} stack
*/
function notifyHandlers(stack, isWindowError) {
var exception = null;
if (isWindowError && !TraceKit.collectWindowErrors) {
return;
}
for (var i in handlers) {
if (handlers.hasOwnProperty(i)) {
try {
handlers[i].apply(null, [stack].concat(_slice.call(arguments, 2)));
} catch (inner) {
exception = inner;
}
}
}
if (exception) {
throw exception;
}
}
var _oldOnerrorHandler, _onErrorHandlerInstalled;
/**
* Ensures all global unhandled exceptions are recorded.
* Supported by Gecko and IE.
* @param {string} msg Error message.
* @param {string} url URL of script that generated the exception.
* @param {(number|string)} lineNo The line number at which the error
* occurred.
* @param {?(number|string)} colNo The column number at which the error
* occurred.
* @param {?Error} ex The actual Error object.
*/
function traceKitWindowOnError(msg, url, lineNo, colNo, ex) {
var stack = null;
// If 'ex' is ErrorEvent, get real Error from inside
var exception = utils.isErrorEvent(ex) ? ex.error : ex;
// If 'msg' is ErrorEvent, get real message from inside
var message = utils.isErrorEvent(msg) ? msg.message : msg;
if (lastExceptionStack) {
TraceKit.computeStackTrace.augmentStackTraceWithInitialElement(
lastExceptionStack,
url,
lineNo,
message
);
processLastException();
} else if (exception && utils.isError(exception)) {
// non-string `exception` arg; attempt to extract stack trace
// New chrome and blink send along a real error object
// Let's just report that like a normal error.
// See: https://mikewest.org/2013/08/debugging-runtime-errors-with-window-onerror
stack = TraceKit.computeStackTrace(exception);
notifyHandlers(stack, true);
} else {
var location = {
url: url,
line: lineNo,
column: colNo
};
var name = undefined;
var groups;
if ({}.toString.call(message) === '[object String]') {
var groups = message.match(ERROR_TYPES_RE);
if (groups) {
name = groups[1];
message = groups[2];
}
}
location.func = UNKNOWN_FUNCTION;
stack = {
name: name,
message: message,
url: getLocationHref(),
stack: [location]
};
notifyHandlers(stack, true);
}
if (_oldOnerrorHandler) {
return _oldOnerrorHandler.apply(this, arguments);
}
return false;
}
function installGlobalHandler() {
if (_onErrorHandlerInstalled) {
return;
}
_oldOnerrorHandler = _window.onerror;
_window.onerror = traceKitWindowOnError;
_onErrorHandlerInstalled = true;
}
function uninstallGlobalHandler() {
if (!_onErrorHandlerInstalled) {
return;
}
_window.onerror = _oldOnerrorHandler;
_onErrorHandlerInstalled = false;
_oldOnerrorHandler = undefined;
}
function processLastException() {
var _lastExceptionStack = lastExceptionStack,
_lastArgs = lastArgs;
lastArgs = null;
lastExceptionStack = null;
lastException = null;
notifyHandlers.apply(null, [_lastExceptionStack, false].concat(_lastArgs));
}
/**
* Reports an unhandled Error to TraceKit.
* @param {Error} ex
* @param {?boolean} rethrow If false, do not re-throw the exception.
* Only used for window.onerror to not cause an infinite loop of
* rethrowing.
*/
function report(ex, rethrow) {
var args = _slice.call(arguments, 1);
if (lastExceptionStack) {
if (lastException === ex) {
return; // already caught by an inner catch block, ignore
} else {
processLastException();
}
}
var stack = TraceKit.computeStackTrace(ex);
lastExceptionStack = stack;
lastException = ex;
lastArgs = args;
// If the stack trace is incomplete, wait for 2 seconds for
// slow slow IE to see if onerror occurs or not before reporting
// this exception; otherwise, we will end up with an incomplete
// stack trace
setTimeout(function() {
if (lastException === ex) {
processLastException();
}
}, stack.incomplete ? 2000 : 0);
if (rethrow !== false) {
throw ex; // re-throw to propagate to the top level (and cause window.onerror)
}
}
report.subscribe = subscribe;
report.unsubscribe = unsubscribe;
report.uninstall = unsubscribeAll;
return report;
})();
/**
* TraceKit.computeStackTrace: cross-browser stack traces in JavaScript
*
* Syntax:
* s = TraceKit.computeStackTrace(exception) // consider using TraceKit.report instead (see below)
* Returns:
* s.name - exception name
* s.message - exception message
* s.stack[i].url - JavaScript or HTML file URL
* s.stack[i].func - function name, or empty for anonymous functions (if guessing did not work)
* s.stack[i].args - arguments passed to the function, if known
* s.stack[i].line - line number, if known
* s.stack[i].column - column number, if known
*
* Supports:
* - Firefox: full stack trace with line numbers and unreliable column
* number on top frame
* - Opera 10: full stack trace with line and column numbers
* - Opera 9-: full stack trace with line numbers
* - Chrome: full stack trace with line and column numbers
* - Safari: line and column number for the topmost stacktrace element
* only
* - IE: no line numbers whatsoever
*
* Tries to guess names of anonymous functions by looking for assignments
* in the source code. In IE and Safari, we have to guess source file names
* by searching for function bodies inside all page scripts. This will not
* work for scripts that are loaded cross-domain.
* Here be dragons: some function names may be guessed incorrectly, and
* duplicate functions may be mismatched.
*
* TraceKit.computeStackTrace should only be used for tracing purposes.
* Logging of unhandled exceptions should be done with TraceKit.report,
* which builds on top of TraceKit.computeStackTrace and provides better
* IE support by utilizing the window.onerror event to retrieve information
* about the top of the stack.
*
* Note: In IE and Safari, no stack trace is recorded on the Error object,
* so computeStackTrace instead walks its *own* chain of callers.
* This means that:
* * in Safari, some methods may be missing from the stack trace;
* * in IE, the topmost function in the stack trace will always be the
* caller of computeStackTrace.
*
* This is okay for tracing (because you are likely to be calling
* computeStackTrace from the function you want to be the topmost element
* of the stack trace anyway), but not okay for logging unhandled
* exceptions (because your catch block will likely be far away from the
* inner function that actually caused the exception).
*
*/
TraceKit.computeStackTrace = (function computeStackTraceWrapper() {
// Contents of Exception in various browsers.
//
// SAFARI:
// ex.message = Can't find variable: qq
// ex.line = 59
// ex.sourceId = 580238192
// ex.sourceURL = http://...
// ex.expressionBeginOffset = 96
// ex.expressionCaretOffset = 98
// ex.expressionEndOffset = 98
// ex.name = ReferenceError
//
// FIREFOX:
// ex.message = qq is not defined
// ex.fileName = http://...
// ex.lineNumber = 59
// ex.columnNumber = 69
// ex.stack = ...stack trace... (see the example below)
// ex.name = ReferenceError
//
// CHROME:
// ex.message = qq is not defined
// ex.name = ReferenceError
// ex.type = not_defined
// ex.arguments = ['aa']
// ex.stack = ...stack trace...
//
// INTERNET EXPLORER:
// ex.message = ...
// ex.name = ReferenceError
//
// OPERA:
// ex.message = ...message... (see the example below)
// ex.name = ReferenceError
// ex.opera#sourceloc = 11 (pretty much useless, duplicates the info in ex.message)
// ex.stacktrace = n/a; see 'opera:config#UserPrefs|Exceptions Have Stacktrace'
/**
* Computes stack trace information from the stack property.
* Chrome and Gecko use this property.
* @param {Error} ex
* @return {?Object.<string, *>} Stack trace information.
*/
function computeStackTraceFromStackProp(ex) {
if (typeof ex.stack === 'undefined' || !ex.stack) return;
var chrome = /^\s*at (?:(.*?) ?\()?((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|[a-z]:|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
var winjs = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx(?:-web)|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
// NOTE: blob urls are now supposed to always have an origin, therefore it's format
// which is `blob:http://url/path/with-some-uuid`, is matched by `blob.*?:\/` as well
var gecko = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|moz-extension).*?:\/.*?|\[native code\]|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i;
// Used to additionally parse URL/line/column from eval frames
var geckoEval = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
var chromeEval = /\((\S*)(?::(\d+))(?::(\d+))\)/;
var lines = ex.stack.split('\n');
var stack = [];
var submatch;
var parts;
var element;
var reference = /^(.*) is undefined$/.exec(ex.message);
for (var i = 0, j = lines.length; i < j; ++i) {
if ((parts = chrome.exec(lines[i]))) {
var isNative = parts[2] && parts[2].indexOf('native') === 0; // start of line
var isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line
if (isEval && (submatch = chromeEval.exec(parts[2]))) {
// throw out eval line/column and use top-most line/column number
parts[2] = submatch[1]; // url
parts[3] = submatch[2]; // line
parts[4] = submatch[3]; // column
}
element = {
url: !isNative ? parts[2] : null,
func: parts[1] || UNKNOWN_FUNCTION,
args: isNative ? [parts[2]] : [],
line: parts[3] ? +parts[3] : null,
column: parts[4] ? +parts[4] : null
};
} else if ((parts = winjs.exec(lines[i]))) {
element = {
url: parts[2],
func: parts[1] || UNKNOWN_FUNCTION,
args: [],
line: +parts[3],
column: parts[4] ? +parts[4] : null
};
} else if ((parts = gecko.exec(lines[i]))) {
var isEval = parts[3] && parts[3].indexOf(' > eval') > -1;
if (isEval && (submatch = geckoEval.exec(parts[3]))) {
// throw out eval line/column and use top-most line number
parts[3] = submatch[1];
parts[4] = submatch[2];
parts[5] = null; // no column when eval
} else if (i === 0 && !parts[5] && typeof ex.columnNumber !== 'undefined') {
// FireFox uses this awesome columnNumber property for its top frame
// Also note, Firefox's column number is 0-based and everything else expects 1-based,
// so adding 1
// NOTE: this hack doesn't work if top-most frame is eval
stack[0].column = ex.columnNumber + 1;
}
element = {
url: parts[3],
func: parts[1] || UNKNOWN_FUNCTION,
args: parts[2] ? parts[2].split(',') : [],
line: parts[4] ? +parts[4] : null,
column: parts[5] ? +parts[5] : null
};
} else {
continue;
}
if (!element.func && element.line) {
element.func = UNKNOWN_FUNCTION;
}
if (element.url && element.url.substr(0, 5) === 'blob:') {
// Special case for handling JavaScript loaded into a blob.
// We use a synchronous AJAX request here as a blob is already in
// memory - it's not making a network request. This will generate a warning
// in the browser console, but there has already been an error so that's not
// that much of an issue.
var xhr = new XMLHttpRequest();
xhr.open('GET', element.url, false);
xhr.send(null);
// If we failed to download the source, skip this patch
if (xhr.status === 200) {
var source = xhr.responseText || '';
// We trim the source down to the last 300 characters as sourceMappingURL is always at the end of the file.
// Why 300? To be in line with: https://github.com/getsentry/sentry/blob/4af29e8f2350e20c28a6933354e4f42437b4ba42/src/sentry/lang/javascript/processor.py#L164-L175
source = source.slice(-300);
// Now we dig out the source map URL
var sourceMaps = source.match(/\/\/# sourceMappingURL=(.*)$/);
// If we don't find a source map comment or we find more than one, continue on to the next element.
if (sourceMaps) {
var sourceMapAddress = sourceMaps[1];
// Now we check to see if it's a relative URL.
// If it is, convert it to an absolute one.
if (sourceMapAddress.charAt(0) === '~') {
sourceMapAddress = getLocationOrigin() + sourceMapAddress.slice(1);
}
// Now we strip the '.map' off of the end of the URL and update the
// element so that Sentry can match the map to the blob.
element.url = sourceMapAddress.slice(0, -4);
}
}
}
stack.push(element);
}
if (!stack.length) {
return null;
}
return {
name: ex.name,
message: ex.message,
url: getLocationHref(),
stack: stack
};
}
/**
* Adds information about the first frame to incomplete stack traces.
* Safari and IE require this to get complete data on the first frame.
* @param {Object.<string, *>} stackInfo Stack trace information from
* one of the compute* methods.
* @param {string} url The URL of the script that caused an error.
* @param {(number|string)} lineNo The line number of the script that
* caused an error.
* @param {string=} message The error generated by the browser, which
* hopefully contains the name of the object that caused the error.
* @return {boolean} Whether or not the stack information was
* augmented.
*/
function augmentStackTraceWithInitialElement(stackInfo, url, lineNo, message) {
var initial = {
url: url,
line: lineNo
};
if (initial.url && initial.line) {
stackInfo.incomplete = false;
if (!initial.func) {
initial.func = UNKNOWN_FUNCTION;
}
if (stackInfo.stack.length > 0) {
if (stackInfo.stack[0].url === initial.url) {
if (stackInfo.stack[0].line === initial.line) {
return false; // already in stack trace
} else if (
!stackInfo.stack[0].line &&
stackInfo.stack[0].func === initial.func
) {
stackInfo.stack[0].line = initial.line;
return false;
}
}
}
stackInfo.stack.unshift(initial);
stackInfo.partial = true;
return true;
} else {
stackInfo.incomplete = true;
}
return false;
}
/**
* Computes stack trace information by walking the arguments.caller
* chain at the time the exception occurred. This will cause earlier
* frames to be missed but is the only way to get any stack trace in
* Safari and IE. The top frame is restored by
* {@link augmentStackTraceWithInitialElement}.
* @param {Error} ex
* @return {?Object.<string, *>} Stack trace information.
*/
function computeStackTraceByWalkingCallerChain(ex, depth) {
var functionName = /function\s+([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)?\s*\(/i,
stack = [],
funcs = {},
recursion = false,
parts,
item,
source;
for (
var curr = computeStackTraceByWalkingCallerChain.caller;
curr && !recursion;
curr = curr.caller
) {
if (curr === computeStackTrace || curr === TraceKit.report) {
// console.log('skipping internal function');
continue;
}
item = {
url: null,
func: UNKNOWN_FUNCTION,
line: null,
column: null
};
if (curr.name) {
item.func = curr.name;
} else if ((parts = functionName.exec(curr.toString()))) {
item.func = parts[1];
}
if (typeof item.func === 'undefined') {
try {
item.func = parts.input.substring(0, parts.input.indexOf('{'));
} catch (e) {}
}
if (funcs['' + curr]) {
recursion = true;
} else {
funcs['' + curr] = true;
}
stack.push(item);
}
if (depth) {
// console.log('depth is ' + depth);
// console.log('stack is ' + stack.length);
stack.splice(0, depth);
}
var result = {
name: ex.name,
message: ex.message,
url: getLocationHref(),
stack: stack
};
augmentStackTraceWithInitialElement(
result,
ex.sourceURL || ex.fileName,
ex.line || ex.lineNumber,
ex.message || ex.description
);
return result;
}
/**
* Computes a stack trace for an exception.
* @param {Error} ex
* @param {(string|number)=} depth
*/
function computeStackTrace(ex, depth) {
var stack = null;
depth = depth == null ? 0 : +depth;
try {
stack = computeStackTraceFromStackProp(ex);
if (stack) {
return stack;
}
} catch (e) {
if (TraceKit.debug) {
throw e;
}
}
try {
stack = computeStackTraceByWalkingCallerChain(ex, depth + 1);
if (stack) {
return stack;
}
} catch (e) {
if (TraceKit.debug) {
throw e;
}
}
return {
name: ex.name,
message: ex.message,
url: getLocationHref()
};
}
computeStackTrace.augmentStackTraceWithInitialElement = augmentStackTraceWithInitialElement;
computeStackTrace.computeStackTraceFromStackProp = computeStackTraceFromStackProp;
return computeStackTrace;
})();
module.exports = TraceKit;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"9":9}],11:[function(_dereq_,module,exports){
/*
json-stringify-safe
Like JSON.stringify, but doesn't throw on circular references.
Originally forked from https://github.com/isaacs/json-stringify-safe
version 5.0.1 on 3/8/2017 and modified to handle Errors serialization
and IE8 compatibility. Tests for this are in test/vendor.
ISC license: https://github.com/isaacs/json-stringify-safe/blob/master/LICENSE
*/
exports = module.exports = stringify;
exports.getSerialize = serializer;
function indexOf(haystack, needle) {
for (var i = 0; i < haystack.length; ++i) {
if (haystack[i] === needle) return i;
}
return -1;
}
function stringify(obj, replacer, spaces, cycleReplacer) {
return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces);
}
// https://github.com/ftlabs/js-abbreviate/blob/fa709e5f139e7770a71827b1893f22418097fbda/index.js#L95-L106
function stringifyError(value) {
var err = {
// These properties are implemented as magical getters and don't show up in for in
stack: value.stack,
message: value.message,
name: value.name
};
for (var i in value) {
if (Object.prototype.hasOwnProperty.call(value, i)) {
err[i] = value[i];
}
}
return err;
}
function serializer(replacer, cycleReplacer) {
var stack = [];
var keys = [];
if (cycleReplacer == null) {
cycleReplacer = function(key, value) {
if (stack[0] === value) {
return '[Circular ~]';
}
return '[Circular ~.' + keys.slice(0, indexOf(stack, value)).join('.') + ']';
};
}
return function(key, value) {
if (stack.length > 0) {
var thisPos = indexOf(stack, this);
~thisPos ? stack.splice(thisPos + 1) : stack.push(this);
~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);
if (~indexOf(stack, value)) {
value = cycleReplacer.call(this, key, value);
}
} else {
stack.push(value);
}
return replacer == null
? value instanceof Error ? stringifyError(value) : value
: replacer.call(this, key, value);
};
}
},{}],12:[function(_dereq_,module,exports){
/*
* JavaScript MD5
* https://github.com/blueimp/JavaScript-MD5
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*
* Based on
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safeAdd(x, y) {
var lsw = (x & 0xffff) + (y & 0xffff);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xffff);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bitRotateLeft(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5cmn(q, a, b, x, s, t) {
return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
}
function md5ff(a, b, c, d, x, s, t) {
return md5cmn((b & c) | (~b & d), a, b, x, s, t);
}
function md5gg(a, b, c, d, x, s, t) {
return md5cmn((b & d) | (c & ~d), a, b, x, s, t);
}
function md5hh(a, b, c, d, x, s, t) {
return md5cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5ii(a, b, c, d, x, s, t) {
return md5cmn(c ^ (b | ~d), a, b, x, s, t);
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length.
*/
function binlMD5(x, len) {
/* append padding */
x[len >> 5] |= 0x80 << (len % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var i;
var olda;
var oldb;
var oldc;
var oldd;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for (i = 0; i < x.length; i += 16) {
olda = a;
oldb = b;
oldc = c;
oldd = d;
a = md5ff(a, b, c, d, x[i], 7, -680876936);
d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
b = md5gg(b, c, d, a, x[i], 20, -373897302);
a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
d = md5hh(d, a, b, c, x[i], 11, -358537222);
c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
a = md5ii(a, b, c, d, x[i], 6, -198630844);
d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
a = safeAdd(a, olda);
b = safeAdd(b, oldb);
c = safeAdd(c, oldc);
d = safeAdd(d, oldd);
}
return [a, b, c, d];
}
/*
* Convert an array of little-endian words to a string
*/
function binl2rstr(input) {
var i;
var output = '';
var length32 = input.length * 32;
for (i = 0; i < length32; i += 8) {
output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xff);
}
return output;
}
/*
* Convert a raw string to an array of little-endian words
* Characters >255 have their high-byte silently ignored.
*/
function rstr2binl(input) {
var i;
var output = [];
output[(input.length >> 2) - 1] = undefined;
for (i = 0; i < output.length; i += 1) {
output[i] = 0;
}
var length8 = input.length * 8;
for (i = 0; i < length8; i += 8) {
output[i >> 5] |= (input.charCodeAt(i / 8) & 0xff) << (i % 32);
}
return output;
}
/*
* Calculate the MD5 of a raw string
*/
function rstrMD5(s) {
return binl2rstr(binlMD5(rstr2binl(s), s.length * 8));
}
/*
* Calculate the HMAC-MD5, of a key and some data (raw strings)
*/
function rstrHMACMD5(key, data) {
var i;
var bkey = rstr2binl(key);
var ipad = [];
var opad = [];
var hash;
ipad[15] = opad[15] = undefined;
if (bkey.length > 16) {
bkey = binlMD5(bkey, key.length * 8);
}
for (i = 0; i < 16; i += 1) {
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5c5c5c5c;
}
hash = binlMD5(ipad.concat(rstr2binl(data)), 512 + data.length * 8);
return binl2rstr(binlMD5(opad.concat(hash), 512 + 128));
}
/*
* Convert a raw string to a hex string
*/
function rstr2hex(input) {
var hexTab = '0123456789abcdef';
var output = '';
var x;
var i;
for (i = 0; i < input.length; i += 1) {
x = input.charCodeAt(i);
output += hexTab.charAt((x >>> 4) & 0x0f) + hexTab.charAt(x & 0x0f);
}
return output;
}
/*
* Encode a string as utf-8
*/
function str2rstrUTF8(input) {
return unescape(encodeURIComponent(input));
}
/*
* Take string arguments and return either raw or hex encoded strings
*/
function rawMD5(s) {
return rstrMD5(str2rstrUTF8(s));
}
function hexMD5(s) {
return rstr2hex(rawMD5(s));
}
function rawHMACMD5(k, d) {
return rstrHMACMD5(str2rstrUTF8(k), str2rstrUTF8(d));
}
function hexHMACMD5(k, d) {
return rstr2hex(rawHMACMD5(k, d));
}
function md5(string, key, raw) {
if (!key) {
if (!raw) {
return hexMD5(string);
}
return rawMD5(string);
}
if (!raw) {
return hexHMACMD5(key, string);
}
return rawHMACMD5(key, string);
}
module.exports = md5;
},{}]},{},[8,1,2,3,4])(8)
}); | joeyparrish/cdnjs | ajax/libs/raven.js/3.25.0/console,ember,require,vue/raven.js | JavaScript | mit | 124,023 |
import { __decorate, __extends } from 'tslib';
import { RuntimeConfig, Util, beta, mergeHeaders } from '@pnp/common';
import { BlobFileParser, BufferFileParser, ODataBatch, ODataQueryable, PipelineMethods } from '@pnp/odata';
import { LogLevel, Logger } from '@pnp/logging';
var NoGraphClientAvailableException = /** @class */ (function (_super) {
__extends(NoGraphClientAvailableException, _super);
function NoGraphClientAvailableException(msg) {
if (msg === void 0) { msg = "There is no Graph Client available, either set one using configuraiton or provide a valid SPFx Context using setup."; }
var _this = _super.call(this, msg) || this;
_this.name = "NoGraphClientAvailableException";
Logger.log({ data: null, level: LogLevel.Error, message: _this.message });
return _this;
}
return NoGraphClientAvailableException;
}(Error));
var GraphBatchParseException = /** @class */ (function (_super) {
__extends(GraphBatchParseException, _super);
function GraphBatchParseException(msg) {
var _this = _super.call(this, msg) || this;
_this.name = "GraphBatchParseException";
Logger.log({ data: {}, level: LogLevel.Error, message: "[" + _this.name + "]::" + _this.message });
return _this;
}
return GraphBatchParseException;
}(Error));
function setup(config) {
RuntimeConfig.extend(config);
}
var GraphRuntimeConfigImpl = /** @class */ (function () {
function GraphRuntimeConfigImpl() {
}
Object.defineProperty(GraphRuntimeConfigImpl.prototype, "headers", {
get: function () {
var graphPart = RuntimeConfig.get("graph");
if (typeof graphPart !== "undefined" && typeof graphPart.headers !== "undefined") {
return graphPart.headers;
}
return {};
},
enumerable: true,
configurable: true
});
Object.defineProperty(GraphRuntimeConfigImpl.prototype, "fetchClientFactory", {
get: function () {
var graphPart = RuntimeConfig.get("graph");
// use a configured factory firt
if (typeof graphPart !== "undefined" && typeof graphPart.fetchClientFactory !== "undefined") {
return graphPart.fetchClientFactory;
}
// then try and use spfx context if available
if (typeof RuntimeConfig.spfxContext !== "undefined") {
return function () { return RuntimeConfig.spfxContext.graphHttpClient; };
}
throw new NoGraphClientAvailableException();
},
enumerable: true,
configurable: true
});
return GraphRuntimeConfigImpl;
}());
var GraphRuntimeConfig = new GraphRuntimeConfigImpl();
// import { APIUrlException } from "../utils/exceptions";
var GraphHttpClient = /** @class */ (function () {
function GraphHttpClient() {
this._impl = GraphRuntimeConfig.fetchClientFactory();
}
GraphHttpClient.prototype.fetch = function (url, options) {
if (options === void 0) { options = {}; }
var headers = new Headers();
// first we add the global headers so they can be overwritten by any passed in locally to this call
mergeHeaders(headers, GraphRuntimeConfig.headers);
// second we add the local options so we can overwrite the globals
mergeHeaders(headers, options.headers);
var opts = Util.extend(options, { headers: headers });
// TODO: we could process auth here
return this.fetchRaw(url, opts);
};
GraphHttpClient.prototype.fetchRaw = function (url, options) {
var _this = this;
if (options === void 0) { options = {}; }
// here we need to normalize the headers
var rawHeaders = new Headers();
mergeHeaders(rawHeaders, options.headers);
options = Util.extend(options, { headers: rawHeaders });
var retry = function (ctx) {
_this._impl.fetch(url, {}, options).then(function (response) { return ctx.resolve(response); }).catch(function (response) {
// Check if request was throttled - http status code 429
// Check if request failed due to server unavailable - http status code 503
if (response.status !== 429 && response.status !== 503) {
ctx.reject(response);
}
// grab our current delay
var delay = ctx.delay;
// Increment our counters.
ctx.delay *= 2;
ctx.attempts++;
// If we have exceeded the retry count, reject.
if (ctx.retryCount <= ctx.attempts) {
ctx.reject(response);
}
// Set our retry timeout for {delay} milliseconds.
setTimeout(Util.getCtxCallback(_this, retry, ctx), delay);
});
};
return new Promise(function (resolve, reject) {
var retryContext = {
attempts: 0,
delay: 100,
reject: reject,
resolve: resolve,
retryCount: 7,
};
retry.call(_this, retryContext);
});
};
GraphHttpClient.prototype.get = function (url, options) {
if (options === void 0) { options = {}; }
var opts = Util.extend(options, { method: "GET" });
return this.fetch(url, opts);
};
GraphHttpClient.prototype.post = function (url, options) {
if (options === void 0) { options = {}; }
var opts = Util.extend(options, { method: "POST" });
return this.fetch(url, opts);
};
GraphHttpClient.prototype.patch = function (url, options) {
if (options === void 0) { options = {}; }
var opts = Util.extend(options, { method: "PATCH" });
return this.fetch(url, opts);
};
GraphHttpClient.prototype.delete = function (url, options) {
if (options === void 0) { options = {}; }
var opts = Util.extend(options, { method: "DELETE" });
return this.fetch(url, opts);
};
return GraphHttpClient;
}());
/**
* Queryable Base Class
*
*/
var GraphQueryable = /** @class */ (function (_super) {
__extends(GraphQueryable, _super);
/**
* Creates a new instance of the Queryable class
*
* @constructor
* @param baseUrl A string or Queryable that should form the base part of the url
*
*/
function GraphQueryable(baseUrl, path) {
var _this = _super.call(this) || this;
if (typeof baseUrl === "string") {
var urlStr = baseUrl;
_this._parentUrl = urlStr;
_this._url = Util.combinePaths(urlStr, path);
}
else {
var q = baseUrl;
_this._parentUrl = q._url;
_this._options = q._options;
_this._url = Util.combinePaths(_this._parentUrl, path);
}
return _this;
}
/**
* Creates a new instance of the supplied factory and extends this into that new instance
*
* @param factory constructor for the new queryable
*/
GraphQueryable.prototype.as = function (factory) {
var o = new factory(this._url, null);
return Util.extend(o, this, true);
};
/**
* Gets the full url with query information
*
*/
GraphQueryable.prototype.toUrlAndQuery = function () {
var _this = this;
return this.toUrl() + ("?" + this._query.getKeys().map(function (key) { return key + "=" + _this._query.get(key); }).join("&"));
};
/**
* Gets a parent for this instance as specified
*
* @param factory The contructor for the class to create
*/
GraphQueryable.prototype.getParent = function (factory, baseUrl, path) {
if (baseUrl === void 0) { baseUrl = this.parentUrl; }
return new factory(baseUrl, path);
};
/**
* Clones this queryable into a new queryable instance of T
* @param factory Constructor used to create the new instance
* @param additionalPath Any additional path to include in the clone
* @param includeBatch If true this instance's batch will be added to the cloned instance
*/
GraphQueryable.prototype.clone = function (factory, additionalPath, includeBatch) {
if (includeBatch === void 0) { includeBatch = true; }
// TODO:: include batching info in clone
if (includeBatch) {
return new factory(this, additionalPath);
}
return new factory(this, additionalPath);
};
/**
* Converts the current instance to a request context
*
* @param verb The request verb
* @param options The set of supplied request options
* @param parser The supplied ODataParser instance
* @param pipeline Optional request processing pipeline
*/
GraphQueryable.prototype.toRequestContext = function (verb, options, parser, pipeline) {
if (options === void 0) { options = {}; }
if (pipeline === void 0) { pipeline = PipelineMethods.default; }
// TODO:: add batch support
return Promise.resolve({
batch: this.batch,
batchDependency: function () { return void (0); },
cachingOptions: this._cachingOptions,
clientFactory: function () { return new GraphHttpClient(); },
isBatched: this.hasBatch,
isCached: this._useCaching,
options: options,
parser: parser,
pipeline: pipeline,
requestAbsoluteUrl: this.toUrlAndQuery(),
requestId: Util.getGUID(),
verb: verb,
});
};
return GraphQueryable;
}(ODataQueryable));
/**
* Represents a REST collection which can be filtered, paged, and selected
*
*/
var GraphQueryableCollection = /** @class */ (function (_super) {
__extends(GraphQueryableCollection, _super);
function GraphQueryableCollection() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
*
* @param filter The string representing the filter query
*/
GraphQueryableCollection.prototype.filter = function (filter) {
this._query.add("$filter", filter);
return this;
};
/**
* Choose which fields to return
*
* @param selects One or more fields to return
*/
GraphQueryableCollection.prototype.select = function () {
var selects = [];
for (var _i = 0; _i < arguments.length; _i++) {
selects[_i] = arguments[_i];
}
if (selects.length > 0) {
this._query.add("$select", selects.join(","));
}
return this;
};
/**
* Expands fields such as lookups to get additional data
*
* @param expands The Fields for which to expand the values
*/
GraphQueryableCollection.prototype.expand = function () {
var expands = [];
for (var _i = 0; _i < arguments.length; _i++) {
expands[_i] = arguments[_i];
}
if (expands.length > 0) {
this._query.add("$expand", expands.join(","));
}
return this;
};
/**
* Orders based on the supplied fields ascending
*
* @param orderby The name of the field to sort on
* @param ascending If false DESC is appended, otherwise ASC (default)
*/
GraphQueryableCollection.prototype.orderBy = function (orderBy, ascending) {
if (ascending === void 0) { ascending = true; }
var keys = this._query.getKeys();
var query = [];
var asc = ascending ? " asc" : " desc";
for (var i = 0; i < keys.length; i++) {
if (keys[i] === "$orderby") {
query.push(this._query.get("$orderby"));
break;
}
}
query.push("" + orderBy + asc);
this._query.add("$orderby", query.join(","));
return this;
};
/**
* Limits the query to only return the specified number of items
*
* @param top The query row limit
*/
GraphQueryableCollection.prototype.top = function (top) {
this._query.add("$top", top.toString());
return this;
};
/**
* Skips a set number of items in the return set
*
* @param num Number of items to skip
*/
GraphQueryableCollection.prototype.skip = function (num) {
this._query.add("$top", num.toString());
return this;
};
/**
* To request second and subsequent pages of Graph data
*/
GraphQueryableCollection.prototype.skipToken = function (token) {
this._query.add("$skiptoken", token);
return this;
};
Object.defineProperty(GraphQueryableCollection.prototype, "count", {
/**
* Retrieves the total count of matching resources
*/
get: function () {
this._query.add("$count", "true");
return this;
},
enumerable: true,
configurable: true
});
return GraphQueryableCollection;
}(GraphQueryable));
var GraphQueryableSearchableCollection = /** @class */ (function (_super) {
__extends(GraphQueryableSearchableCollection, _super);
function GraphQueryableSearchableCollection() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* To request second and subsequent pages of Graph data
*/
GraphQueryableSearchableCollection.prototype.search = function (query) {
this._query.add("$search", query);
return this;
};
return GraphQueryableSearchableCollection;
}(GraphQueryableCollection));
/**
* Represents an instance that can be selected
*
*/
var GraphQueryableInstance = /** @class */ (function (_super) {
__extends(GraphQueryableInstance, _super);
function GraphQueryableInstance() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Choose which fields to return
*
* @param selects One or more fields to return
*/
GraphQueryableInstance.prototype.select = function () {
var selects = [];
for (var _i = 0; _i < arguments.length; _i++) {
selects[_i] = arguments[_i];
}
if (selects.length > 0) {
this._query.add("$select", selects.join(","));
}
return this;
};
/**
* Expands fields such as lookups to get additional data
*
* @param expands The Fields for which to expand the values
*/
GraphQueryableInstance.prototype.expand = function () {
var expands = [];
for (var _i = 0; _i < arguments.length; _i++) {
expands[_i] = arguments[_i];
}
if (expands.length > 0) {
this._query.add("$expand", expands.join(","));
}
return this;
};
return GraphQueryableInstance;
}(GraphQueryable));
var Members = /** @class */ (function (_super) {
__extends(Members, _super);
function Members(baseUrl, path) {
if (path === void 0) { path = "members"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Use this API to add a member to an Office 365 group, a security group or a mail-enabled security group through
* the members navigation property. You can add users or other groups.
* Important: You can add only users to Office 365 groups.
*
* @param id Full @odata.id of the directoryObject, user, or group object you want to add (ex: https://graph.microsoft.com/v1.0/directoryObjects/${id})
*/
Members.prototype.add = function (id) {
return this.clone(Members, "$ref").postCore({
body: JSON.stringify({
"@odata.id": id,
}),
});
};
/**
* Gets a member of the group by id
*
* @param id Group member's id
*/
Members.prototype.getById = function (id) {
return new Member(this, id);
};
return Members;
}(GraphQueryableCollection));
var Member = /** @class */ (function (_super) {
__extends(Member, _super);
function Member() {
return _super !== null && _super.apply(this, arguments) || this;
}
return Member;
}(GraphQueryableInstance));
var Owners = /** @class */ (function (_super) {
__extends(Owners, _super);
function Owners(baseUrl, path) {
if (path === void 0) { path = "owners"; }
return _super.call(this, baseUrl, path) || this;
}
return Owners;
}(Members));
// import { Attachments } from "./attachments";
var Calendars = /** @class */ (function (_super) {
__extends(Calendars, _super);
function Calendars(baseUrl, path) {
if (path === void 0) { path = "calendars"; }
return _super.call(this, baseUrl, path) || this;
}
return Calendars;
}(GraphQueryableCollection));
var Calendar = /** @class */ (function (_super) {
__extends(Calendar, _super);
function Calendar() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(Calendar.prototype, "events", {
get: function () {
return new Events(this);
},
enumerable: true,
configurable: true
});
return Calendar;
}(GraphQueryableInstance));
var Events = /** @class */ (function (_super) {
__extends(Events, _super);
function Events(baseUrl, path) {
if (path === void 0) { path = "events"; }
return _super.call(this, baseUrl, path) || this;
}
Events.prototype.getById = function (id) {
return new Event(this, id);
};
/**
* Adds a new event to the collection
*
* @param properties The set of properties used to create the event
*/
Events.prototype.add = function (properties) {
var _this = this;
return this.postCore({
body: JSON.stringify(properties),
}).then(function (r) {
return {
data: r,
event: _this.getById(r.id),
};
});
};
return Events;
}(GraphQueryableCollection));
var Event = /** @class */ (function (_super) {
__extends(Event, _super);
function Event() {
return _super !== null && _super.apply(this, arguments) || this;
}
// TODO:: when supported
// /**
// * Gets the collection of attachments for this event
// */
// public get attachments(): Attachments {
// return new Attachments(this);
// }
/**
* Update the properties of an event object
*
* @param properties Set of properties of this event to update
*/
Event.prototype.update = function (properties) {
return this.patchCore({
body: JSON.stringify(properties),
});
};
/**
* Deletes this event
*/
Event.prototype.delete = function () {
return this.deleteCore();
};
return Event;
}(GraphQueryableInstance));
var Attachments = /** @class */ (function (_super) {
__extends(Attachments, _super);
function Attachments(baseUrl, path) {
if (path === void 0) { path = "attachments"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a member of the group by id
*
* @param id Attachment id
*/
Attachments.prototype.getById = function (id) {
return new Attachment(this, id);
};
/**
* Add attachment to this collection
*
* @param name Name given to the attachment file
* @param bytes File content
*/
Attachments.prototype.addFile = function (name, bytes) {
return this.postCore({
body: JSON.stringify({
"@odata.type": "#microsoft.graph.fileAttachment",
contentBytes: bytes,
name: name,
}),
});
};
return Attachments;
}(GraphQueryableCollection));
var Attachment = /** @class */ (function (_super) {
__extends(Attachment, _super);
function Attachment() {
return _super !== null && _super.apply(this, arguments) || this;
}
return Attachment;
}(GraphQueryableInstance));
var Conversations = /** @class */ (function (_super) {
__extends(Conversations, _super);
function Conversations(baseUrl, path) {
if (path === void 0) { path = "conversations"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Create a new conversation by including a thread and a post.
*
* @param properties Properties used to create the new conversation
*/
Conversations.prototype.add = function (properties) {
return this.postCore({
body: JSON.stringify(properties),
});
};
/**
* Gets a conversation from this collection by id
*
* @param id Group member's id
*/
Conversations.prototype.getById = function (id) {
return new Conversation(this, id);
};
return Conversations;
}(GraphQueryableCollection));
var Threads = /** @class */ (function (_super) {
__extends(Threads, _super);
function Threads(baseUrl, path) {
if (path === void 0) { path = "threads"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a thread from this collection by id
*
* @param id Group member's id
*/
Threads.prototype.getById = function (id) {
return new Thread(this, id);
};
/**
* Adds a new thread to this collection
*
* @param properties properties used to create the new thread
* @returns Id of the new thread
*/
Threads.prototype.add = function (properties) {
return this.postCore({
body: JSON.stringify(properties),
});
};
return Threads;
}(GraphQueryableCollection));
var Posts = /** @class */ (function (_super) {
__extends(Posts, _super);
function Posts(baseUrl, path) {
if (path === void 0) { path = "posts"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a thread from this collection by id
*
* @param id Group member's id
*/
Posts.prototype.getById = function (id) {
return new Post(this, id);
};
/**
* Adds a new thread to this collection
*
* @param properties properties used to create the new thread
* @returns Id of the new thread
*/
Posts.prototype.add = function (properties) {
return this.postCore({
body: JSON.stringify(properties),
});
};
return Posts;
}(GraphQueryableCollection));
var Conversation = /** @class */ (function (_super) {
__extends(Conversation, _super);
function Conversation() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(Conversation.prototype, "threads", {
/**
* Get all the threads in a group conversation.
*/
get: function () {
return new Threads(this);
},
enumerable: true,
configurable: true
});
/**
* Updates this conversation
*/
Conversation.prototype.update = function (properties) {
return this.patchCore({
body: JSON.stringify(properties),
});
};
/**
* Deletes this member from the group
*/
Conversation.prototype.delete = function () {
return this.deleteCore();
};
return Conversation;
}(GraphQueryableInstance));
var Thread = /** @class */ (function (_super) {
__extends(Thread, _super);
function Thread() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(Thread.prototype, "posts", {
/**
* Get all the threads in a group conversation.
*/
get: function () {
return new Posts(this);
},
enumerable: true,
configurable: true
});
/**
* Reply to a thread in a group conversation and add a new post to it
*
* @param post Contents of the post
*/
Thread.prototype.reply = function (post) {
return this.clone(Thread, "reply").postCore({
body: JSON.stringify({
post: post,
}),
});
};
/**
* Deletes this member from the group
*/
Thread.prototype.delete = function () {
return this.deleteCore();
};
return Thread;
}(GraphQueryableInstance));
var Post = /** @class */ (function (_super) {
__extends(Post, _super);
function Post() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(Post.prototype, "attachments", {
get: function () {
return new Attachments(this);
},
enumerable: true,
configurable: true
});
/**
* Deletes this post
*/
Post.prototype.delete = function () {
return this.deleteCore();
};
/**
* Forward a post to a recipient
*/
Post.prototype.forward = function (info) {
return this.clone(Post, "forward").postCore({
body: JSON.stringify(info),
});
};
/**
* Reply to a thread in a group conversation and add a new post to it
*
* @param post Contents of the post
*/
Post.prototype.reply = function (post) {
return this.clone(Post, "reply").postCore({
body: JSON.stringify({
post: post,
}),
});
};
return Post;
}(GraphQueryableInstance));
var Senders = /** @class */ (function (_super) {
__extends(Senders, _super);
function Senders(baseUrl, path) {
return _super.call(this, baseUrl, path) || this;
}
/**
* Add a new user or group to this senders collection
* @param id The full @odata.id value to add (ex: https://graph.microsoft.com/v1.0/users/user@contoso.com)
*/
Senders.prototype.add = function (id) {
return this.clone(Senders, "$ref").postCore({
body: JSON.stringify({
"@odata.id": id,
}),
});
};
/**
* Removes the entity from the collection
*
* @param id The full @odata.id value to remove (ex: https://graph.microsoft.com/v1.0/users/user@contoso.com)
*/
Senders.prototype.remove = function (id) {
var remover = this.clone(Senders, "$ref");
remover.query.add("$id", id);
return remover.deleteCore();
};
return Senders;
}(GraphQueryableCollection));
var Plans = /** @class */ (function (_super) {
__extends(Plans, _super);
function Plans(baseUrl, path) {
if (path === void 0) { path = "planner/plans"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a plan from this collection by id
*
* @param id Plan's id
*/
Plans.prototype.getById = function (id) {
return new Plan(this, id);
};
return Plans;
}(GraphQueryableCollection));
var Plan = /** @class */ (function (_super) {
__extends(Plan, _super);
function Plan() {
return _super !== null && _super.apply(this, arguments) || this;
}
return Plan;
}(GraphQueryableInstance));
var Photo = /** @class */ (function (_super) {
__extends(Photo, _super);
function Photo(baseUrl, path) {
if (path === void 0) { path = "photo"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets the image bytes as a blob (browser)
*/
Photo.prototype.getBlob = function () {
return this.clone(Photo, "$value", false).get(new BlobFileParser());
};
/**
* Gets the image file byets as a Buffer (node.js)
*/
Photo.prototype.getBuffer = function () {
return this.clone(Photo, "$value", false).get(new BufferFileParser());
};
/**
* Sets the file bytes
*
* @param content Image file contents, max 4 MB
*/
Photo.prototype.setContent = function (content) {
return this.clone(Photo, "$value", false).patchCore({
body: content,
});
};
return Photo;
}(GraphQueryableInstance));
var GroupType;
(function (GroupType) {
/**
* Office 365 (aka unified group)
*/
GroupType[GroupType["Office365"] = 0] = "Office365";
/**
* Dynamic membership
*/
GroupType[GroupType["Dynamic"] = 1] = "Dynamic";
/**
* Security
*/
GroupType[GroupType["Security"] = 2] = "Security";
})(GroupType || (GroupType = {}));
/**
* Describes a collection of Field objects
*
*/
var Groups = /** @class */ (function (_super) {
__extends(Groups, _super);
function Groups(baseUrl, path) {
if (path === void 0) { path = "groups"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a group from the collection using the specified id
*
* @param id Id of the group to get from this collection
*/
Groups.prototype.getById = function (id) {
return new Group(this, id);
};
/**
* Create a new group as specified in the request body.
*
* @param name Name to display in the address book for the group
* @param mailNickname Mail alias for the group
* @param groupType Type of group being created
* @param additionalProperties A plain object collection of additional properties you want to set on the new group
*/
Groups.prototype.add = function (name, mailNickname, groupType, additionalProperties) {
var _this = this;
if (additionalProperties === void 0) { additionalProperties = {}; }
var postBody = Util.extend({
displayName: name,
mailEnabled: groupType === GroupType.Office365,
mailNickname: mailNickname,
securityEnabled: groupType !== GroupType.Office365,
}, additionalProperties);
// include a group type if required
if (groupType !== GroupType.Security) {
postBody = Util.extend(postBody, {
groupTypes: [groupType === GroupType.Office365 ? "Unified" : "DynamicMembership"],
});
}
return this.postCore({
body: JSON.stringify(postBody),
}).then(function (r) {
return {
data: r,
group: _this.getById(r.id),
};
});
};
return Groups;
}(GraphQueryableCollection));
/**
* Represents a group entity
*/
var Group = /** @class */ (function (_super) {
__extends(Group, _super);
function Group() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(Group.prototype, "caldendar", {
/**
* The calendar associated with this group
*/
get: function () {
return new Calendar(this, "calendar");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Group.prototype, "events", {
/**
* Retrieve a list of event objects
*/
get: function () {
return new Events(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Group.prototype, "owners", {
/**
* Gets the collection of owners for this group
*/
get: function () {
return new Owners(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Group.prototype, "plans", {
/**
* The collection of plans for this group
*/
get: function () {
return new Plans(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Group.prototype, "members", {
/**
* Gets the collection of members for this group
*/
get: function () {
return new Members(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Group.prototype, "conversations", {
/**
* Gets the conversations collection for this group
*/
get: function () {
return new Conversations(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Group.prototype, "acceptedSenders", {
/**
* Gets the collection of accepted senders for this group
*/
get: function () {
return new Senders(this, "acceptedsenders");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Group.prototype, "rejectedSenders", {
/**
* Gets the collection of rejected senders for this group
*/
get: function () {
return new Senders(this, "rejectedsenders");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Group.prototype, "photo", {
/**
* The photo associated with the group
*/
get: function () {
return new Photo(this);
},
enumerable: true,
configurable: true
});
/**
* Add the group to the list of the current user's favorite groups. Supported for only Office 365 groups
*/
Group.prototype.addFavorite = function () {
return this.clone(Group, "addFavorite").postCore();
};
/**
* Return all the groups that the specified group is a member of. The check is transitive
*
* @param securityEnabledOnly
*/
Group.prototype.getMemberGroups = function (securityEnabledOnly) {
if (securityEnabledOnly === void 0) { securityEnabledOnly = false; }
return this.clone(Group, "getMemberGroups").postCore({
body: JSON.stringify({
securityEnabledOnly: securityEnabledOnly,
}),
});
};
/**
* Deletes this group
*/
Group.prototype.delete = function () {
return this.deleteCore();
};
/**
* Update the properties of a group object
*
* @param properties Set of properties of this group to update
*/
Group.prototype.update = function (properties) {
return this.patchCore({
body: JSON.stringify(properties),
});
};
/**
* Remove the group from the list of the current user's favorite groups. Supported for only Office 365 groups
*/
Group.prototype.removeFavorite = function () {
return this.clone(Group, "removeFavorite").postCore();
};
/**
* Reset the unseenCount of all the posts that the current user has not seen since their last visit
*/
Group.prototype.resetUnseenCount = function () {
return this.clone(Group, "resetUnseenCount").postCore();
};
/**
* Calling this method will enable the current user to receive email notifications for this group,
* about new posts, events, and files in that group. Supported for only Office 365 groups
*/
Group.prototype.subscribeByMail = function () {
return this.clone(Group, "subscribeByMail").postCore();
};
/**
* Calling this method will prevent the current user from receiving email notifications for this group
* about new posts, events, and files in that group. Supported for only Office 365 groups
*/
Group.prototype.unsubscribeByMail = function () {
return this.clone(Group, "unsubscribeByMail").postCore();
};
/**
* Get the occurrences, exceptions, and single instances of events in a calendar view defined by a time range, from the default calendar of a group
*
* @param start Start date and time of the time range
* @param end End date and time of the time range
*/
Group.prototype.getCalendarView = function (start, end) {
var view = this.clone(Group, "calendarView");
view.query.add("startDateTime", start.toISOString());
view.query.add("endDateTime", end.toISOString());
return view.get();
};
return Group;
}(GraphQueryableInstance));
// import { Me } from "./me";
/**
* Root object wrapping v1 functionality for MS Graph
*
*/
var V1 = /** @class */ (function (_super) {
__extends(V1, _super);
/**
* Creates a new instance of the V1 class
*
* @param baseUrl The url or Queryable which forms the parent of this fields collection
* @param path Optional additional path
*/
function V1(baseUrl, path) {
if (path === void 0) { path = "v1.0"; }
return _super.call(this, baseUrl, path) || this;
}
Object.defineProperty(V1.prototype, "groups", {
get: function () {
return new Groups(this);
},
enumerable: true,
configurable: true
});
return V1;
}(GraphQueryable));
var GraphRest = /** @class */ (function () {
function GraphRest() {
}
Object.defineProperty(GraphRest.prototype, "v1", {
get: function () {
return new V1("");
},
enumerable: true,
configurable: true
});
GraphRest.prototype.setup = function (config) {
setup(config);
};
return GraphRest;
}());
var graph = new GraphRest();
var GraphBatch = /** @class */ (function (_super) {
__extends(GraphBatch, _super);
function GraphBatch(batchUrl) {
if (batchUrl === void 0) { batchUrl = "https://graph.microsoft.com/beta/$batch"; }
var _this = _super.call(this) || this;
_this.batchUrl = batchUrl;
return _this;
}
GraphBatch.prototype.executeImpl = function () {
var _this = this;
Logger.write("[" + this.batchId + "] (" + (new Date()).getTime() + ") Executing batch with " + this.requests.length + " requests.", LogLevel.Info);
var client = new GraphHttpClient();
var batchRequest = {
requests: this.formatRequests(),
};
var batchOptions = {
"body": JSON.stringify(batchRequest),
"headers": {
"Accept": "application/json",
"Content-Type": "application/json",
},
"method": "POST",
};
Logger.write("[" + this.batchId + "] (" + (new Date()).getTime() + ") Sending batch request.", LogLevel.Info);
return client.fetch(this.batchUrl, batchOptions)
.then(function (r) { return r.json(); })
.then(this._parseResponse)
.then(function (parsedResponse) {
Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Resolving batched requests.", LogLevel.Info);
return parsedResponse.responses.reduce(function (chain, response, index) {
var request = _this.requests[index];
if (Util.objectDefinedNotNull(request)) {
Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Resolving batched request " + request.method + " " + request.url + ".", LogLevel.Verbose);
return chain.then(function (_) { return request.parser.parse(response).then(request.resolve).catch(request.reject); });
}
else {
// do we have a next url? if no this is an error
if (!Util.stringIsNullOrEmpty(parsedResponse.nextLink)) {
throw new GraphBatchParseException("Could not properly parse responses to match requests in batch.");
}
return chain;
}
}, Promise.resolve());
});
};
GraphBatch.prototype.formatRequests = function () {
return this.requests.map(function (reqInfo, index) {
var requestFragment = {
id: "" + ++index,
method: reqInfo.method,
url: reqInfo.url,
};
var headers = {};
// merge global config headers
if (typeof GraphRuntimeConfig.headers !== "undefined" && GraphRuntimeConfig.headers !== null) {
headers = Util.extend(headers, GraphRuntimeConfig.headers);
}
if (typeof reqInfo.options !== "undefined") {
// merge per request headers
if (typeof reqInfo.options.headers !== "undefined" && reqInfo.options.headers !== null) {
headers = Util.extend(headers, reqInfo.options.headers);
}
// add a request body
if (typeof reqInfo.options.body !== "undefined" && reqInfo.options.body !== null) {
requestFragment = Util.extend(requestFragment, {
body: reqInfo.options.body,
});
}
}
requestFragment = Util.extend(requestFragment, {
headers: headers,
});
return requestFragment;
});
};
GraphBatch.prototype._parseResponse = function (graphResponse) {
var _this = this;
return new Promise(function (resolve) {
var parsedResponses = new Array(_this.requests.length).fill(null);
for (var i = 0; i < graphResponse.responses.length; ++i) {
var response = graphResponse.responses[i];
// we create the request id by adding 1 to the index, so we place the response by subtracting one to match
// the array of requests and make it easier to map them by index
var responseId = parseInt(response.id, 10) - 1;
if (response.status === 204) {
parsedResponses[responseId] = new Response();
}
else {
parsedResponses[responseId] = new Response(null, {
headers: response.headers,
status: response.status,
});
}
}
resolve({
nextLink: graphResponse.nextLink,
responses: parsedResponses,
});
});
};
__decorate([
beta("Graph batching functionality is in beta.")
], GraphBatch.prototype, "executeImpl", null);
return GraphBatch;
}(ODataBatch));
export { graph, GraphRest, GraphBatch, GraphQueryable, GraphQueryableCollection, GraphQueryableInstance, GraphQueryableSearchableCollection };
//# sourceMappingURL=graph.es5.js.map
| joeyparrish/cdnjs | ajax/libs/pnp-graph/1.0.0-beta.3/graph.es5.js | JavaScript | mit | 43,547 |
/**
@license
* @pnp/odata v1.0.3 - pnp - provides shared odata functionality and base classes
* MIT (https://github.com/pnp/pnp/blob/master/LICENSE)
* Copyright (c) 2018 Microsoft
* docs: http://officedev.github.io/PnP-JS-Core
* source: https://github.com/pnp/pnp
* bugs: https://github.com/pnp/pnp/issues
*/
import { Dictionary, PnPClientStorage, RuntimeConfig, Util, mergeOptions } from '@pnp/common';
import { __decorate, __extends } from 'tslib';
import { Logger } from '@pnp/logging';
var CachingOptions = /** @class */ (function () {
function CachingOptions(key) {
this.key = key;
this.expiration = Util.dateAdd(new Date(), "second", RuntimeConfig.defaultCachingTimeoutSeconds);
this.storeName = RuntimeConfig.defaultCachingStore;
}
Object.defineProperty(CachingOptions.prototype, "store", {
get: function () {
if (this.storeName === "local") {
return CachingOptions.storage.local;
}
else {
return CachingOptions.storage.session;
}
},
enumerable: true,
configurable: true
});
CachingOptions.storage = new PnPClientStorage();
return CachingOptions;
}());
var CachingParserWrapper = /** @class */ (function () {
function CachingParserWrapper(_parser, _cacheOptions) {
this._parser = _parser;
this._cacheOptions = _cacheOptions;
}
CachingParserWrapper.prototype.parse = function (response) {
var _this = this;
// add this to the cache based on the options
return this._parser.parse(response).then(function (data) {
if (_this._cacheOptions.store !== null) {
_this._cacheOptions.store.put(_this._cacheOptions.key, data, _this._cacheOptions.expiration);
}
return data;
});
};
return CachingParserWrapper;
}());
/**
* Represents an exception with an HttpClient request
*
*/
var ProcessHttpClientResponseException = /** @class */ (function (_super) {
__extends(ProcessHttpClientResponseException, _super);
function ProcessHttpClientResponseException(status, statusText, data) {
var _this = _super.call(this, "Error making HttpClient request in queryable: [" + status + "] " + statusText) || this;
_this.status = status;
_this.statusText = statusText;
_this.data = data;
_this.name = "ProcessHttpClientResponseException";
Logger.log({ data: _this.data, level: 3 /* Error */, message: _this.message });
return _this;
}
return ProcessHttpClientResponseException;
}(Error));
var ODataParserBase = /** @class */ (function () {
function ODataParserBase() {
}
ODataParserBase.prototype.parse = function (r) {
var _this = this;
return new Promise(function (resolve, reject) {
if (_this.handleError(r, reject)) {
// handle all requests as text, then parse if they are not empty
r.text()
.then(function (txt) { return txt.replace(/\s/ig, "").length > 0 ? JSON.parse(txt) : {}; })
.then(function (json) { return resolve(_this.parseODataJSON(json)); })
.catch(function (e) { return reject(e); });
}
});
};
/**
* Handles a response with ok === false by parsing the body and creating a ProcessHttpClientResponseException
* which is passed to the reject delegate. This method returns true if there is no error, otherwise false
*
* @param r Current response object
* @param reject reject delegate for the surrounding promise
*/
ODataParserBase.prototype.handleError = function (r, reject) {
if (!r.ok) {
// read the response as text, it may not be valid json
r.json().then(function (json) {
// include the headers as they contain diagnostic information
var data = {
responseBody: json,
responseHeaders: r.headers,
};
reject(new ProcessHttpClientResponseException(r.status, r.statusText, data));
}).catch(function (e) {
// we failed to read the body - possibly it is empty. Let's report the original status that caused
// the request to fail and log the error without parsing the body if anyone needs it for debugging
Logger.log({
data: e,
level: 2 /* Warning */,
message: "There was an error parsing the error response body. See data for details.",
});
// include the headers as they contain diagnostic information
var data = {
responseBody: "[[body not available]]",
responseHeaders: r.headers,
};
reject(new ProcessHttpClientResponseException(r.status, r.statusText, data));
});
}
return r.ok;
};
/**
* Normalizes the json response by removing the various nested levels
*
* @param json json object to parse
*/
ODataParserBase.prototype.parseODataJSON = function (json) {
var result = json;
if (json.hasOwnProperty("d")) {
if (json.d.hasOwnProperty("results")) {
result = json.d.results;
}
else {
result = json.d;
}
}
else if (json.hasOwnProperty("value")) {
result = json.value;
}
return result;
};
return ODataParserBase;
}());
var ODataDefaultParser = /** @class */ (function (_super) {
__extends(ODataDefaultParser, _super);
function ODataDefaultParser() {
return _super !== null && _super.apply(this, arguments) || this;
}
return ODataDefaultParser;
}(ODataParserBase));
var TextParser = /** @class */ (function () {
function TextParser() {
}
TextParser.prototype.parse = function (r) {
return r.text();
};
return TextParser;
}());
var BlobParser = /** @class */ (function () {
function BlobParser() {
}
BlobParser.prototype.parse = function (r) {
return r.blob();
};
return BlobParser;
}());
var JSONParser = /** @class */ (function () {
function JSONParser() {
}
JSONParser.prototype.parse = function (r) {
return r.json();
};
return JSONParser;
}());
var BufferParser = /** @class */ (function () {
function BufferParser() {
}
BufferParser.prototype.parse = function (r) {
if (Util.isFunc(r.arrayBuffer)) {
return r.arrayBuffer();
}
return r.buffer();
};
return BufferParser;
}());
/**
* Resolves the context's result value
*
* @param context The current context
*/
function returnResult(context) {
Logger.log({
data: context.result,
level: 0 /* Verbose */,
message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Returning result, see data property for value.",
});
return Promise.resolve(context.result || null);
}
/**
* Sets the result on the context
*/
function setResult(context, value) {
return new Promise(function (resolve) {
context.result = value;
context.hasResult = true;
resolve(context);
});
}
/**
* Invokes the next method in the provided context's pipeline
*
* @param c The current request context
*/
function next(c) {
if (c.pipeline.length > 0) {
return c.pipeline.shift()(c);
}
else {
return Promise.resolve(c);
}
}
/**
* Executes the current request context's pipeline
*
* @param context Current context
*/
function pipe(context) {
if (context.pipeline.length < 1) {
Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Request pipeline contains no methods!", 2 /* Warning */);
}
return next(context)
.then(function (ctx) { return returnResult(ctx); })
.catch(function (e) {
Logger.error(e);
throw e;
});
}
/**
* decorator factory applied to methods in the pipeline to control behavior
*/
function requestPipelineMethod(alwaysRun) {
if (alwaysRun === void 0) { alwaysRun = false; }
return function (target, propertyKey, descriptor) {
var method = descriptor.value;
descriptor.value = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
// if we have a result already in the pipeline, pass it along and don't call the tagged method
if (!alwaysRun && args.length > 0 && args[0].hasOwnProperty("hasResult") && args[0].hasResult) {
Logger.write("[" + args[0].requestId + "] (" + (new Date()).getTime() + ") Skipping request pipeline method " + propertyKey + ", existing result in pipeline.", 0 /* Verbose */);
return Promise.resolve(args[0]);
}
// apply the tagged method
Logger.write("[" + args[0].requestId + "] (" + (new Date()).getTime() + ") Calling request pipeline method " + propertyKey + ".", 0 /* Verbose */);
// then chain the next method in the context's pipeline - allows for dynamic pipeline
return method.apply(target, args).then(function (ctx) { return next(ctx); });
};
};
}
/**
* Contains the methods used within the request pipeline
*/
var PipelineMethods = /** @class */ (function () {
function PipelineMethods() {
}
/**
* Logs the start of the request
*/
PipelineMethods.logStart = function (context) {
return new Promise(function (resolve) {
Logger.log({
data: Logger.activeLogLevel === 1 /* Info */ ? {} : context,
level: 1 /* Info */,
message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Beginning " + context.verb + " request (" + context.requestAbsoluteUrl + ")",
});
resolve(context);
});
};
/**
* Handles caching of the request
*/
PipelineMethods.caching = function (context) {
return new Promise(function (resolve) {
// handle caching, if applicable
if (context.verb === "GET" && context.isCached) {
Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Caching is enabled for request, checking cache...", 1 /* Info */);
var cacheOptions = new CachingOptions(context.requestAbsoluteUrl.toLowerCase());
if (typeof context.cachingOptions !== "undefined") {
cacheOptions = Util.extend(cacheOptions, context.cachingOptions);
}
// we may not have a valid store
if (cacheOptions.store !== null) {
// check if we have the data in cache and if so resolve the promise and return
var data = cacheOptions.store.get(cacheOptions.key);
if (data !== null) {
// ensure we clear any help batch dependency we are resolving from the cache
Logger.log({
data: Logger.activeLogLevel === 1 /* Info */ ? {} : data,
level: 1 /* Info */,
message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Value returned from cache.",
});
context.batchDependency();
// handle the case where a parser needs to take special actions with a cached result (such as getAs)
if (context.parser.hasOwnProperty("hydrate")) {
data = context.parser.hydrate(data);
}
return setResult(context, data).then(function (ctx) { return resolve(ctx); });
}
}
Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Value not found in cache.", 1 /* Info */);
// if we don't then wrap the supplied parser in the caching parser wrapper
// and send things on their way
context.parser = new CachingParserWrapper(context.parser, cacheOptions);
}
return resolve(context);
});
};
/**
* Sends the request
*/
PipelineMethods.send = function (context) {
return new Promise(function (resolve, reject) {
// send or batch the request
if (context.isBatched) {
// we are in a batch, so add to batch, remove dependency, and resolve with the batch's promise
var p = context.batch.add(context.requestAbsoluteUrl, context.verb, context.options, context.parser);
// we release the dependency here to ensure the batch does not execute until the request is added to the batch
context.batchDependency();
Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Batching request in batch " + context.batch.batchId + ".", 1 /* Info */);
// we set the result as the promise which will be resolved by the batch's execution
resolve(setResult(context, p));
}
else {
Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Sending request.", 1 /* Info */);
// we are not part of a batch, so proceed as normal
var client = context.clientFactory();
var opts = Util.extend(context.options || {}, { method: context.verb });
client.fetch(context.requestAbsoluteUrl, opts)
.then(function (response) { return context.parser.parse(response); })
.then(function (result) { return setResult(context, result); })
.then(function (ctx) { return resolve(ctx); })
.catch(function (e) { return reject(e); });
}
});
};
/**
* Logs the end of the request
*/
PipelineMethods.logEnd = function (context) {
return new Promise(function (resolve) {
if (context.isBatched) {
Logger.log({
data: Logger.activeLogLevel === 1 /* Info */ ? {} : context,
level: 1 /* Info */,
message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") " + context.verb + " request will complete in batch " + context.batch.batchId + ".",
});
}
else {
Logger.log({
data: Logger.activeLogLevel === 1 /* Info */ ? {} : context,
level: 1 /* Info */,
message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Completing " + context.verb + " request.",
});
}
resolve(context);
});
};
__decorate([
requestPipelineMethod(true)
], PipelineMethods, "logStart", null);
__decorate([
requestPipelineMethod()
], PipelineMethods, "caching", null);
__decorate([
requestPipelineMethod()
], PipelineMethods, "send", null);
__decorate([
requestPipelineMethod(true)
], PipelineMethods, "logEnd", null);
return PipelineMethods;
}());
function getDefaultPipeline() {
return [
PipelineMethods.logStart,
PipelineMethods.caching,
PipelineMethods.send,
PipelineMethods.logEnd,
].slice(0);
}
var AlreadyInBatchException = /** @class */ (function (_super) {
__extends(AlreadyInBatchException, _super);
function AlreadyInBatchException(msg) {
if (msg === void 0) { msg = "This query is already part of a batch."; }
var _this = _super.call(this, msg) || this;
_this.name = "AlreadyInBatchException";
Logger.error(_this);
return _this;
}
return AlreadyInBatchException;
}(Error));
var ODataQueryable = /** @class */ (function () {
function ODataQueryable() {
this._batch = null;
this._query = new Dictionary();
this._options = {};
this._url = "";
this._parentUrl = "";
this._useCaching = false;
this._cachingOptions = null;
}
/**
* Directly concatonates the supplied string to the current url, not normalizing "/" chars
*
* @param pathPart The string to concatonate to the url
*/
ODataQueryable.prototype.concat = function (pathPart) {
this._url += pathPart;
return this;
};
Object.defineProperty(ODataQueryable.prototype, "query", {
/**
* Provides access to the query builder for this url
*
*/
get: function () {
return this._query;
},
enumerable: true,
configurable: true
});
/**
* Sets custom options for current object and all derived objects accessible via chaining
*
* @param options custom options
*/
ODataQueryable.prototype.configure = function (options) {
mergeOptions(this._options, options);
return this;
};
/**
* Enables caching for this request
*
* @param options Defines the options used when caching this request
*/
ODataQueryable.prototype.usingCaching = function (options) {
if (!RuntimeConfig.globalCacheDisable) {
this._useCaching = true;
if (typeof options !== "undefined") {
this._cachingOptions = options;
}
}
return this;
};
/**
* Adds this query to the supplied batch
*
* @example
* ```
*
* let b = pnp.sp.createBatch();
* pnp.sp.web.inBatch(b).get().then(...);
* b.execute().then(...)
* ```
*/
ODataQueryable.prototype.inBatch = function (batch) {
if (this.batch !== null) {
throw new AlreadyInBatchException();
}
this._batch = batch;
return this;
};
/**
* Gets the currentl url
*
*/
ODataQueryable.prototype.toUrl = function () {
return this._url;
};
/**
* Executes the currently built request
*
* @param parser Allows you to specify a parser to handle the result
* @param getOptions The options used for this request
*/
ODataQueryable.prototype.get = function (parser, options) {
if (parser === void 0) { parser = new ODataDefaultParser(); }
if (options === void 0) { options = {}; }
return this.toRequestContext("GET", options, parser, getDefaultPipeline()).then(function (context) { return pipe(context); });
};
ODataQueryable.prototype.postCore = function (options, parser) {
if (options === void 0) { options = {}; }
if (parser === void 0) { parser = new ODataDefaultParser(); }
return this.toRequestContext("POST", options, parser, getDefaultPipeline()).then(function (context) { return pipe(context); });
};
ODataQueryable.prototype.patchCore = function (options, parser) {
if (options === void 0) { options = {}; }
if (parser === void 0) { parser = new ODataDefaultParser(); }
return this.toRequestContext("PATCH", options, parser, getDefaultPipeline()).then(function (context) { return pipe(context); });
};
ODataQueryable.prototype.deleteCore = function (options, parser) {
if (options === void 0) { options = {}; }
if (parser === void 0) { parser = new ODataDefaultParser(); }
return this.toRequestContext("DELETE", options, parser, getDefaultPipeline()).then(function (context) { return pipe(context); });
};
/**
* Blocks a batch call from occuring, MUST be cleared by calling the returned function
*/
ODataQueryable.prototype.addBatchDependency = function () {
if (this._batch !== null) {
return this._batch.addDependency();
}
return function () { return null; };
};
Object.defineProperty(ODataQueryable.prototype, "hasBatch", {
/**
* Indicates if the current query has a batch associated
*
*/
get: function () {
return Util.objectDefinedNotNull(this._batch);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ODataQueryable.prototype, "batch", {
/**
* The batch currently associated with this query or null
*
*/
get: function () {
return this.hasBatch ? this._batch : null;
},
enumerable: true,
configurable: true
});
/**
* Appends the given string and normalizes "/" chars
*
* @param pathPart The string to append
*/
ODataQueryable.prototype.append = function (pathPart) {
this._url = Util.combinePaths(this._url, pathPart);
};
Object.defineProperty(ODataQueryable.prototype, "parentUrl", {
/**
* Gets the parent url used when creating this instance
*
*/
get: function () {
return this._parentUrl;
},
enumerable: true,
configurable: true
});
return ODataQueryable;
}());
var ODataBatch = /** @class */ (function () {
function ODataBatch(_batchId) {
if (_batchId === void 0) { _batchId = Util.getGUID(); }
this._batchId = _batchId;
this._requests = [];
this._dependencies = [];
}
Object.defineProperty(ODataBatch.prototype, "batchId", {
get: function () {
return this._batchId;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ODataBatch.prototype, "requests", {
/**
* The requests contained in this batch
*/
get: function () {
return this._requests;
},
enumerable: true,
configurable: true
});
/**
*
* @param url Request url
* @param method Request method (GET, POST, etc)
* @param options Any request options
* @param parser The parser used to handle the eventual return from the query
*/
ODataBatch.prototype.add = function (url, method, options, parser) {
var info = {
method: method.toUpperCase(),
options: options,
parser: parser,
reject: null,
resolve: null,
url: url,
};
var p = new Promise(function (resolve, reject) {
info.resolve = resolve;
info.reject = reject;
});
this._requests.push(info);
return p;
};
/**
* Adds a dependency insuring that some set of actions will occur before a batch is processed.
* MUST be cleared using the returned resolve delegate to allow batches to run
*/
ODataBatch.prototype.addDependency = function () {
var resolver = function () { return void (0); };
var promise = new Promise(function (resolve) {
resolver = resolve;
});
this._dependencies.push(promise);
return resolver;
};
/**
* Execute the current batch and resolve the associated promises
*
* @returns A promise which will be resolved once all of the batch's child promises have resolved
*/
ODataBatch.prototype.execute = function () {
var _this = this;
// we need to check the dependencies twice due to how different engines handle things.
// We can get a second set of promises added during the first set resolving
return Promise.all(this._dependencies).then(function () { return Promise.all(_this._dependencies); }).then(function () { return _this.executeImpl(); });
};
return ODataBatch;
}());
export { CachingOptions, CachingParserWrapper, ProcessHttpClientResponseException, ODataParserBase, ODataDefaultParser, TextParser, BlobParser, JSONParser, BufferParser, setResult, pipe, requestPipelineMethod, PipelineMethods, getDefaultPipeline, AlreadyInBatchException, ODataQueryable, ODataBatch };
//# sourceMappingURL=odata.es5.js.map
| joeyparrish/cdnjs | ajax/libs/pnp-odata/1.0.3/odata.es5.js | JavaScript | mit | 24,930 |
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. 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 AJAX.ORG B.V. 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.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/plain_text', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/text_highlight_rules', 'ace/mode/behaviour'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var Behaviour = require("./behaviour").Behaviour;
var Mode = function() {
this.$tokenizer = new Tokenizer(new TextHighlightRules().getRules());
this.$behaviour = new Behaviour();
};
oop.inherits(Mode, TextMode);
(function() {
this.type = "text";
this.getNextLineIndent = function(state, line, tab) {
return '';
};
}).call(Mode.prototype);
exports.Mode = Mode;
}); | sqlviz/sqlviz | website/static/django_ace/ace/mode-plain_text.js | JavaScript | mit | 2,481 |
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v17.1.1
* @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 __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var selectCellEditor_1 = require("./selectCellEditor");
var PopupSelectCellEditor = (function (_super) {
__extends(PopupSelectCellEditor, _super);
function PopupSelectCellEditor() {
return _super !== null && _super.apply(this, arguments) || this;
}
PopupSelectCellEditor.prototype.isPopup = function () {
return true;
};
return PopupSelectCellEditor;
}(selectCellEditor_1.SelectCellEditor));
exports.PopupSelectCellEditor = PopupSelectCellEditor;
| seogi1004/cdnjs | ajax/libs/ag-grid/17.1.1/lib/rendering/cellEditors/popupSelectCellEditor.js | JavaScript | mit | 1,238 |
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { chainPropTypes, deepmerge } from '@material-ui/utils';
import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled';
import experimentalStyled from '../styles/experimentalStyled';
import useThemeProps from '../styles/useThemeProps';
import { alpha } from '../styles/colorManipulator';
import ButtonBase from '../ButtonBase';
import capitalize from '../utils/capitalize';
import iconButtonClasses, { getIconButtonUtilityClass } from './iconButtonClasses';
import { jsx as _jsx } from "react/jsx-runtime";
const overridesResolver = (props, styles) => {
const {
styleProps
} = props;
return deepmerge(_extends({}, styleProps.color !== 'default' && styles[`color${capitalize(styleProps.color)}`], styleProps.edge && styles[`edge${capitalize(styleProps.edge)}`], styles[`size${capitalize(styleProps.size)}`], {
[`& .${iconButtonClasses.label}`]: styles.label
}), styles.root || {});
};
const useUtilityClasses = styleProps => {
const {
classes,
disabled,
color,
edge,
size
} = styleProps;
const slots = {
root: ['root', disabled && 'disabled', color !== 'default' && `color${capitalize(color)}`, edge && `edge${capitalize(edge)}`, `size${capitalize(size)}`],
label: ['label']
};
return composeClasses(slots, getIconButtonUtilityClass, classes);
};
const IconButtonRoot = experimentalStyled(ButtonBase, {}, {
name: 'MuiIconButton',
slot: 'Root',
overridesResolver
})(({
theme,
styleProps
}) => _extends({
/* Styles applied to the root element. */
textAlign: 'center',
flex: '0 0 auto',
fontSize: theme.typography.pxToRem(24),
padding: 12,
borderRadius: '50%',
overflow: 'visible',
// Explicitly set the default value to solve a bug on IE11.
color: theme.palette.action.active,
transition: theme.transitions.create('background-color', {
duration: theme.transitions.duration.shortest
}),
'&:hover': {
backgroundColor: alpha(theme.palette.action.active, theme.palette.action.hoverOpacity),
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent'
}
}
}, styleProps.edge === 'start' && {
marginLeft: styleProps.size === 'small' ? -3 : -12
}, styleProps.edge === 'end' && {
marginRight: styleProps.size === 'small' ? -3 : -12
}), ({
theme,
styleProps
}) => _extends({}, styleProps.color === 'inherit' && {
color: 'inherit'
}, styleProps.color === 'primary' && {
color: theme.palette.primary.main,
'&:hover': {
backgroundColor: alpha(theme.palette.primary.main, theme.palette.action.hoverOpacity),
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent'
}
}
}, styleProps.color === 'secondary' && {
color: theme.palette.secondary.main,
'&:hover': {
backgroundColor: alpha(theme.palette.secondary.main, theme.palette.action.hoverOpacity),
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent'
}
}
}, styleProps.size === 'small' && {
padding: 3,
fontSize: theme.typography.pxToRem(18)
}, {
/* Styles applied to the root element if `disabled={true}`. */
[`&.${iconButtonClasses.disabled}`]: {
backgroundColor: 'transparent',
color: theme.palette.action.disabled
}
}));
const IconButtonLabel = experimentalStyled('span', {}, {
name: 'MuiIconButton',
slot: 'Label'
})({
/* Styles applied to the children container element. */
width: '100%',
display: 'flex',
alignItems: 'inherit',
justifyContent: 'inherit'
});
/**
* Refer to the [Icons](/components/icons/) section of the documentation
* regarding the available icon options.
*/
const IconButton = /*#__PURE__*/React.forwardRef(function IconButton(inProps, ref) {
const props = useThemeProps({
props: inProps,
name: 'MuiIconButton'
});
const {
edge = false,
children,
className,
color = 'default',
disabled = false,
disableFocusRipple = false,
size = 'medium'
} = props,
other = _objectWithoutPropertiesLoose(props, ["edge", "children", "className", "color", "disabled", "disableFocusRipple", "size"]);
const styleProps = _extends({}, props, {
edge,
color,
disabled,
disableFocusRipple,
size
});
const classes = useUtilityClasses(styleProps);
return /*#__PURE__*/_jsx(IconButtonRoot, _extends({
className: clsx(classes.root, className),
centerRipple: true,
focusRipple: !disableFocusRipple,
disabled: disabled,
ref: ref,
styleProps: styleProps
}, other, {
children: /*#__PURE__*/_jsx(IconButtonLabel, {
className: classes.label,
styleProps: styleProps,
children: children
})
}));
});
process.env.NODE_ENV !== "production" ? IconButton.propTypes
/* remove-proptypes */
= {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The icon to display.
*/
children: chainPropTypes(PropTypes.node, props => {
const found = React.Children.toArray(props.children).some(child => /*#__PURE__*/React.isValidElement(child) && child.props.onClick);
if (found) {
return new Error(['Material-UI: You are providing an onClick event listener to a child of a button element.', 'Prefer applying it to the IconButton directly.', 'This guarantees that the whole <button> will be responsive to click events.'].join('\n'));
}
return null;
}),
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The color of the component. It supports those theme colors that make sense for this component.
* @default 'default'
*/
color: PropTypes.oneOf(['default', 'inherit', 'primary', 'secondary']),
/**
* If `true`, the component is disabled.
* @default false
*/
disabled: PropTypes.bool,
/**
* If `true`, the keyboard focus ripple is disabled.
* @default false
*/
disableFocusRipple: PropTypes.bool,
/**
* If `true`, the ripple effect is disabled.
*
* ⚠️ Without a ripple there is no styling for :focus-visible by default. Be sure
* to highlight the element by applying separate styles with the `.Mui-focusedVisible` class.
* @default false
*/
disableRipple: PropTypes.bool,
/**
* If given, uses a negative margin to counteract the padding on one
* side (this is often helpful for aligning the left or right
* side of the icon with content above or below, without ruining the border
* size and shape).
* @default false
*/
edge: PropTypes.oneOf(['end', 'start', false]),
/**
* The size of the component.
* `small` is equivalent to the dense button styling.
* @default 'medium'
*/
size: PropTypes.oneOf(['medium', 'small']),
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.object
} : void 0;
export default IconButton; | cdnjs/cdnjs | ajax/libs/material-ui/5.0.0-alpha.31/modern/IconButton/IconButton.js | JavaScript | mit | 7,512 |
define(
//begin v1.x content
{
"field-tue-relative+-1": "el martes pasado",
"field-year": "año",
"dateFormatItem-Hm": "HH:mm",
"field-wed-relative+0": "este miércoles",
"field-wed-relative+1": "el próximo miércoles",
"dateFormatItem-ms": "mm:ss",
"field-minute": "minuto",
"field-month-narrow-relative+-1": "el mes pasado",
"field-tue-narrow-relative+0": "este MA",
"field-tue-narrow-relative+1": "el próximo MA",
"field-day-short-relative+-1": "ayer",
"field-thu-short-relative+0": "este jue.",
"dateTimeFormat-short": "{1} {0}",
"field-day-relative+0": "hoy",
"field-day-short-relative+-2": "anteayer",
"field-thu-short-relative+1": "el próximo jue.",
"field-day-relative+1": "mañana",
"field-week-narrow-relative+0": "esta sem.",
"field-day-relative+2": "pasado mañana",
"field-week-narrow-relative+1": "próx. sem.",
"dateFormatItem-EBhms": "E h:mm:ss B",
"field-wed-narrow-relative+-1": "el MI pasado",
"field-year-narrow": "a",
"field-era-short": "era",
"field-year-narrow-relative+0": "este año",
"field-tue-relative+0": "este martes",
"field-year-narrow-relative+1": "el próximo año",
"field-tue-relative+1": "el próximo martes",
"field-weekdayOfMonth": "día de la semana del mes",
"field-second-short": "s",
"dateFormatItem-MMMd": "d MMM",
"field-weekdayOfMonth-narrow": "día de sem. de mes",
"field-week-relative+0": "esta semana",
"field-month-relative+0": "este mes",
"field-week-relative+1": "la próxima semana",
"field-month-relative+1": "el próximo mes",
"field-sun-narrow-relative+0": "este DO",
"field-mon-short-relative+0": "este lun.",
"field-sun-narrow-relative+1": "el próximo DO",
"field-mon-short-relative+1": "el próximo lun.",
"field-second-relative+0": "ahora",
"dateFormatItem-yyyyQQQ": "QQQ y G",
"field-weekOfMonth": "semana del mes",
"field-month-short": "m",
"dateFormatItem-GyMMMM": "MMMM 'de' y G",
"dateFormatItem-GyMMMEd": "E, d MMM y G",
"dateFormatItem-yyyyMd": "d/M/y GGGGG",
"field-day": "día",
"field-dayOfYear-short": "día del a",
"field-year-relative+-1": "el año pasado",
"field-sat-short-relative+-1": "el sáb. pasado",
"dateFormatItem-yyyyMMMMd": "d 'de' MMMM 'de' y G",
"field-hour-relative+0": "esta hora",
"dateFormatItem-yyyyMEd": "E, d/M/y GGGGG",
"field-wed-relative+-1": "el miércoles pasado",
"dateTimeFormat-medium": "{1} {0}",
"field-sat-narrow-relative+-1": "el SA pasado",
"field-second": "segundo",
"dateFormatItem-Ehms": "E h:mm:ss a",
"dateFormat-long": "d 'de' MMMM 'de' y G",
"dateFormatItem-GyMMMd": "d MMM y G",
"field-quarter": "trimestre",
"field-week-short": "sem.",
"field-day-narrow-relative+0": "hoy",
"field-day-narrow-relative+1": "mañana",
"field-day-narrow-relative+2": "pasado mañana",
"dateFormatItem-yyyyMMMMEd": "EEE, d 'de' MMMM 'de' y G",
"field-tue-short-relative+0": "este mar.",
"field-tue-short-relative+1": "el próximo mar.",
"field-month-short-relative+-1": "el mes pasado",
"field-mon-relative+-1": "el lunes pasado",
"dateFormatItem-GyMMM": "MMM y G",
"field-month": "mes",
"field-day-narrow": "d",
"dateFormatItem-MMM": "LLL",
"field-minute-short": "min",
"field-dayperiod": "a. m./p. m.",
"field-sat-short-relative+0": "este sáb.",
"field-sat-short-relative+1": "el próximo sáb.",
"dateFormat-medium": "d/M/y G",
"dateFormatItem-yyyyMMMM": "MMMM 'de' y G",
"dateFormatItem-yyyyM": "M/y GGGGG",
"field-second-narrow": "s",
"field-mon-relative+0": "este lunes",
"field-mon-relative+1": "el próximo lunes",
"field-day-narrow-relative+-1": "ayer",
"field-year-short": "a",
"field-day-narrow-relative+-2": "anteayer",
"field-quarter-relative+-1": "el trimestre pasado",
"dateFormatItem-yyyyMMMd": "d MMM y G",
"field-dayperiod-narrow": "a. m./p. m.",
"field-week-narrow-relative+-1": "sem. ant.",
"field-dayOfYear": "día del año",
"field-sat-relative+-1": "el sábado pasado",
"dateTimeFormat-long": "{1}, {0}",
"dateFormatItem-Md": "d/M",
"field-hour": "hora",
"dateFormat-full": "EEEE, d 'de' MMMM 'de' y G",
"field-month-relative+-1": "el mes pasado",
"dateFormatItem-Hms": "HH:mm:ss",
"field-quarter-short": "trim.",
"field-sat-narrow-relative+0": "este SA",
"field-fri-relative+0": "este viernes",
"field-sat-narrow-relative+1": "el próximo SA",
"field-fri-relative+1": "el próximo viernes",
"dateFormatItem-EBhm": "E h:mm B",
"field-month-narrow-relative+0": "este mes",
"field-month-narrow-relative+1": "el próximo mes",
"field-sun-short-relative+0": "este dom.",
"field-sun-short-relative+1": "el próximo dom.",
"field-week-relative+-1": "la semana pasada",
"dateFormatItem-Ehm": "E h:mm a",
"field-quarter-relative+0": "este trimestre",
"field-minute-relative+0": "este minuto",
"field-quarter-relative+1": "el próximo trimestre",
"field-wed-short-relative+-1": "el mié. pasado",
"dateFormat-short": "d/M/yy G",
"dateFormatItem-Bh": "h B",
"field-year-narrow-relative+-1": "el año pasado",
"field-thu-short-relative+-1": "el jue. pasado",
"dateFormatItem-yyyyMMMEd": "EEE, d MMM y G",
"field-mon-narrow-relative+-1": "el LU pasado",
"dateFormatItem-MMMMd": "d 'de' MMMM",
"field-thu-narrow-relative+-1": "el JU pasado",
"dateFormatItem-E": "ccc",
"dateFormatItem-H": "HH",
"field-weekOfMonth-short": "sem. de mes",
"field-tue-narrow-relative+-1": "el MA pasado",
"dateFormatItem-yyyy": "y G",
"dateFormatItem-M": "L",
"field-wed-short-relative+0": "este mié.",
"field-wed-short-relative+1": "el próximo mié.",
"field-sun-relative+-1": "el domingo pasado",
"dateFormatItem-MMMMEd": "E, d 'de' MMMM",
"dateTimeFormat-full": "{1}, {0}",
"dateFormatItem-hm": "h:mm a",
"dateFormatItem-d": "d",
"field-weekday": "día de la semana",
"field-day-short-relative+0": "hoy",
"field-day-short-relative+1": "mañana",
"field-sat-relative+0": "este sábado",
"dateFormatItem-h": "h a",
"field-day-short-relative+2": "pasado mañana",
"field-sat-relative+1": "el próximo sábado",
"field-week-short-relative+0": "esta sem.",
"field-week-short-relative+1": "próx. sem.",
"dateFormatItem-GyMMMMEd": "E, d 'de' MMMM 'de' y G",
"field-dayOfYear-narrow": "día del a",
"field-month-short-relative+0": "este mes",
"field-month-short-relative+1": "el próximo mes",
"field-weekdayOfMonth-short": "día de sem. de mes",
"dateFormatItem-MEd": "E, d/M",
"field-zone-narrow": "zona",
"dateFormatItem-y": "y G",
"field-thu-narrow-relative+0": "este JU",
"field-sun-narrow-relative+-1": "el DO pasado",
"field-mon-short-relative+-1": "el lun. pasado",
"field-thu-narrow-relative+1": "el próximo JU",
"field-thu-relative+0": "este jueves",
"field-thu-relative+1": "el próximo jueves",
"dateFormatItem-hms": "h:mm:ss a",
"field-fri-short-relative+-1": "el vie. pasado",
"field-thu-relative+-1": "el jueves pasado",
"field-week": "semana",
"dateFormatItem-Ed": "E d",
"field-wed-narrow-relative+0": "este MI",
"field-wed-narrow-relative+1": "el próximo MI",
"field-year-short-relative+0": "este año",
"dateFormatItem-yyyyMMM": "MMM y G",
"field-dayperiod-short": "a. m./p. m.",
"field-year-short-relative+1": "el próximo año",
"field-fri-short-relative+0": "este vie.",
"field-fri-short-relative+1": "el próximo vie.",
"field-week-short-relative+-1": "sem. ant.",
"dateFormatItem-GyMMMMd": "d 'de' MMMM 'de' y G",
"dateFormatItem-yyyyQQQQ": "QQQQ 'de' y G",
"field-hour-short": "h",
"field-zone-short": "zona",
"field-month-narrow": "m",
"field-hour-narrow": "h",
"field-fri-narrow-relative+-1": "el VI pasado",
"field-year-relative+0": "este año",
"field-year-relative+1": "el próximo año",
"field-era-narrow": "era",
"field-fri-relative+-1": "el viernes pasado",
"dateFormatItem-Bhms": "h:mm:ss B",
"field-tue-short-relative+-1": "el mar. pasado",
"field-minute-narrow": "min",
"field-mon-narrow-relative+0": "este LU",
"dateFormatItem-EHm": "E HH:mm",
"field-mon-narrow-relative+1": "el próximo LU",
"field-year-short-relative+-1": "el año pasado",
"field-zone": "zona horaria",
"dateFormatItem-MMMEd": "E, d MMM",
"field-weekOfMonth-narrow": "sem. de mes",
"dateFormatItem-EHms": "E HH:mm:ss",
"field-weekday-narrow": "día de sem.",
"field-quarter-narrow": "trim.",
"field-sun-short-relative+-1": "el dom. pasado",
"field-day-relative+-1": "ayer",
"field-day-relative+-2": "anteayer",
"field-weekday-short": "día de sem.",
"dateFormatItem-Bhm": "h:mm B",
"field-sun-relative+0": "este domingo",
"field-sun-relative+1": "el próximo domingo",
"dateFormatItem-Gy": "y G",
"field-day-short": "d",
"field-week-narrow": "sem.",
"field-era": "era",
"field-fri-narrow-relative+0": "este VI",
"field-fri-narrow-relative+1": "el próximo VI"
}
//end v1.x content
); | cdnjs/cdnjs | ajax/libs/dojo/1.17.1/cldr/nls/es/generic.js | JavaScript | mit | 8,699 |
define(
//begin v1.x content
{
"field-quarter-short-relative+0": "هذا الربع",
"field-quarter-short-relative+1": "الربع القادم",
"field-tue-relative+-1": "الثلاثاء الماضي",
"field-year": "السنة",
"field-wed-relative+0": "الأربعاء الحالي",
"field-wed-relative+1": "الأربعاء القادم",
"field-minute": "الدقائق",
"field-tue-narrow-relative+0": "الثلاثاء الحالي",
"field-tue-narrow-relative+1": "الثلاثاء القادم",
"field-thu-short-relative+0": "الخميس الحالي",
"field-day-short-relative+-1": "أمس",
"field-thu-short-relative+1": "الخميس القادم",
"field-day-relative+0": "اليوم",
"field-day-short-relative+-2": "أول أمس",
"field-day-relative+1": "غدًا",
"field-day-relative+2": "بعد الغد",
"field-wed-narrow-relative+-1": "الأربعاء الماضي",
"field-year-narrow": "السنة",
"field-era-short": "العصر",
"field-tue-relative+0": "الثلاثاء الحالي",
"field-tue-relative+1": "الثلاثاء القادم",
"field-weekdayOfMonth": "يوم عمل من الشهر",
"field-second-short": "الثواني",
"field-weekdayOfMonth-narrow": "يوم عمل/شهر",
"field-week-relative+0": "هذا الأسبوع",
"field-month-relative+0": "هذا الشهر",
"field-week-relative+1": "الأسبوع القادم",
"field-month-relative+1": "الشهر القادم",
"field-sun-narrow-relative+0": "الأحد الحالي",
"field-mon-short-relative+0": "الإثنين الحالي",
"field-sun-narrow-relative+1": "الأحد القادم",
"field-mon-short-relative+1": "الإثنين القادم",
"field-second-relative+0": "الآن",
"field-weekOfMonth": "الأسبوع من الشهر",
"field-month-short": "الشهر",
"field-day": "يوم",
"field-dayOfYear-short": "يوم من سنة",
"field-year-relative+-1": "السنة الماضية",
"field-sat-short-relative+-1": "السبت الماضي",
"field-hour-relative+0": "الساعة الحالية",
"field-wed-relative+-1": "الأربعاء الماضي",
"field-sat-narrow-relative+-1": "السبت الماضي",
"field-second": "الثواني",
"field-quarter": "ربع السنة",
"field-week-short": "الأسبوع",
"field-day-narrow-relative+0": "اليوم",
"field-day-narrow-relative+1": "غدًا",
"field-day-narrow-relative+2": "بعد الغد",
"field-tue-short-relative+0": "الثلاثاء الحالي",
"field-tue-short-relative+1": "الثلاثاء القادم",
"field-mon-relative+-1": "الإثنين الماضي",
"field-month": "الشهر",
"field-day-narrow": "يوم",
"field-minute-short": "الدقائق",
"field-dayperiod": "ص/م",
"field-sat-short-relative+0": "السبت الحالي",
"field-sat-short-relative+1": "السبت القادم",
"eraAbbr": [
"تيكا",
"هاكتشي",
"هاكهو",
"شتشو",
"تيهو",
"كيين",
"وادو",
"رييكي",
"يورو",
"جينكي",
"تمبيو",
"تمبيو-كامبو",
"تمبيو-شوهو",
"تمبيو-هوجي",
"تمفو-جينجو",
"جينجو-كيين",
"هوكي",
"تن-أو",
"إنرياكو",
"ديدو",
"كونين",
"تنتشو",
"شووا (٨٣٤–٨٤٨)",
"كاجو",
"نينجو",
"سيكو",
"تنان",
"جوجان",
"جينكيي",
"نينا",
"كامبيو",
"شوتاي",
"انجي",
"انتشو",
"شوهيي",
"تنجيو",
"تنرياكو",
"تنتوكو",
"أووا",
"كوهو",
"آنا",
"تينروكو",
"تن-نن",
"جوجن",
"تنجن",
"إيكان",
"كانا",
"اي-ان",
"ايسو",
"شورياكو (٩٩٠–٩٩٥)",
"تشوتوكو",
"تشوهو",
"كانكو",
"تشووا",
"كانين",
"جاين",
"مانجو",
"تشوجين",
"تشورياكو",
"تشوكيو (١٠٤٠–١٠٤٤)",
"كانتوكو",
"ايشو (١٠٤٦–١٠٥٣)",
"تينجي",
"كوهيي",
"جيرياكو",
"انكيو (١٠٦٩–١٠٧٤)",
"شوهو (١٠٧٤–١٠٧٧)",
"شورياكو (١٠٧٧–١٠٨١)",
"ايهو",
"أوتوكو",
"كانجي",
"كاهو",
"ايتشو",
"شوتوكو",
"كووا (١٠٩٩–١١٠٤)",
"تشوجي",
"كاشو",
"تنين",
"تن-اي",
"ايكيو (١١١٣–١١١٨)",
"جن-اي",
"هوان",
"تنجي",
"ديجي",
"تنشو (١١٣١–١١٣٢)",
"تشوشو",
"هوين",
"ايجي",
"كوجي (١١٤٢–١١٤٤)",
"تنيو",
"كيوان",
"نينبيي",
"كيوجو",
"هجين",
"هيجي",
"ايرياكو",
"أوهو",
"تشوكان",
"ايمان",
"نين-ان",
"كاو",
"شون",
"أنجين",
"جيشو",
"يووا",
"جيي",
"جنريوكو",
"بنجي",
"كنكيو",
"شوجي",
"كنين",
"جنكيو (١٢٠٤–١٢٠٦)",
"كن-اي",
"شوجن (١٢٠٧–١٢١١)",
"كنرياكو",
"كنبو (١٢١٣–١٢١٩)",
"شوكيو",
"جو",
"جيننين",
"كروكو",
"أنتيي",
"كنكي",
"جويي",
"تمبكو",
"بنرياكو",
"كاتيي",
"رياكنين",
"ان-أو",
"نينجي",
"كنجين",
"هوجي",
"كنتشو",
"كوجن",
"شوكا",
"شوجن (١٢٥٩–١٢٦٠)",
"بن-أو",
"كوتشو",
"بن-اي",
"كنجي",
"كوان",
"شوو (١٢٨٨–١٢٩٣)",
"اينين",
"شوان",
"كنجن",
"كجن",
"توكجي",
"انكي",
"أوتشو",
"شووا (١٣١٢–١٣١٧)",
"بنبو",
"جنو",
"جنكيو (١٣٢١–١٣٢٤)",
"شوتشو (١٣٢٤–١٣٢٦)",
"كريكي",
"جنتكو",
"جنكو",
"كمو",
"إنجن",
"كوككو",
"شوهي",
"كنتكو",
"بنتشو",
"تنجو",
"كورياكو",
"كووا (١٣٨١–١٣٨٤)",
"جنتشو",
"مييتكو (١٣٨٤–١٣٨٧)",
"كاكي",
"كو",
"مييتكو (١٣٩٠–١٣٩٤)",
"أويي",
"شوتشو (١٤٢٨–١٤٢٩)",
"ايكيو (١٤٢٩–١٤٤١)",
"ككيتسو",
"بن-أن",
"هوتكو",
"كيوتكو",
"كوشو",
"تشوركو",
"كنشو",
"بنشو",
"أونين",
"بنمي",
"تشوكيو (١٤٨٧–١٤٨٩)",
"انتكو",
"ميو",
"بنكي",
"ايشو (١٥٠٤–١٥٢١)",
"تييي",
"كيوركو",
"تنمن",
"كوجي (١٥٥٥–١٥٥٨)",
"ايركو",
"جنكي",
"تنشو (١٥٧٣–١٥٩٢)",
"بنركو",
"كيتشو",
"جنوا",
"كان-اي",
"شوهو (١٦٤٤–١٦٤٨)",
"كيان",
"شوو (١٦٥٢–١٦٥٥)",
"ميرياكو",
"منجي",
"كنبن",
"انبو",
"تنوا",
"جوكيو",
"جنركو",
"هويي",
"شوتكو",
"كيوهو",
"جنبن",
"كنبو (١٧٤١–١٧٤٤)",
"انكيو (١٧٤٤–١٧٤٨)",
"كان-ان",
"هورياكو",
"مييوا",
"ان-اي",
"تنمي",
"كنسي",
"كيووا",
"بنكا",
"بنسي",
"تنبو",
"كوكا",
"كاي",
"أنسي",
"من-ان",
"بنكيو",
"جنجي",
"كيو",
"ميجي",
"تيشو",
"شووا",
"هيسي",
"ريوا"
],
"field-second-narrow": "الثواني",
"field-mon-relative+0": "الإثنين الحالي",
"field-mon-relative+1": "الإثنين القادم",
"field-day-narrow-relative+-1": "أمس",
"field-year-short": "السنة",
"field-day-narrow-relative+-2": "أول أمس",
"field-quarter-relative+-1": "الربع الأخير",
"field-dayperiod-narrow": "ص/م",
"field-dayOfYear": "يوم من السنة",
"field-sat-relative+-1": "السبت الماضي",
"field-hour": "الساعات",
"field-month-relative+-1": "الشهر الماضي",
"field-quarter-short": "ربع السنة",
"field-sat-narrow-relative+0": "السبت الحالي",
"field-fri-relative+0": "الجمعة الحالي",
"field-sat-narrow-relative+1": "السبت القادم",
"field-fri-relative+1": "الجمعة القادم",
"field-sun-short-relative+0": "الأحد الحالي",
"field-sun-short-relative+1": "الأحد القادم",
"field-week-relative+-1": "الأسبوع الماضي",
"field-quarter-short-relative+-1": "الربع الأخير",
"field-quarter-relative+0": "هذا الربع",
"field-minute-relative+0": "هذه الدقيقة",
"field-quarter-relative+1": "الربع القادم",
"field-wed-short-relative+-1": "الأربعاء الماضي",
"field-thu-short-relative+-1": "الخميس الماضي",
"field-mon-narrow-relative+-1": "الإثنين الماضي",
"field-thu-narrow-relative+-1": "الخميس الماضي",
"field-tue-narrow-relative+-1": "الثلاثاء الماضي",
"field-weekOfMonth-short": "أسبوع من شهر",
"field-wed-short-relative+0": "الأربعاء الحالي",
"field-wed-short-relative+1": "الأربعاء القادم",
"field-sun-relative+-1": "الأحد الماضي",
"field-weekday": "اليوم",
"field-day-short-relative+0": "اليوم",
"field-quarter-narrow-relative+0": "هذا الربع",
"field-sat-relative+0": "السبت الحالي",
"field-day-short-relative+1": "غدًا",
"field-quarter-narrow-relative+1": "الربع القادم",
"field-sat-relative+1": "السبت القادم",
"field-day-short-relative+2": "بعد الغد",
"field-dayOfYear-narrow": "يوم/سنة",
"field-weekdayOfMonth-short": "يوم عمل من شهر",
"field-zone-narrow": "توقيت",
"field-thu-narrow-relative+0": "الخميس الحالي",
"field-thu-narrow-relative+1": "الخميس القادم",
"field-sun-narrow-relative+-1": "الأحد الماضي",
"field-mon-short-relative+-1": "الإثنين الماضي",
"field-thu-relative+0": "الخميس الحالي",
"field-thu-relative+1": "الخميس القادم",
"field-fri-short-relative+-1": "الجمعة الماضي",
"field-thu-relative+-1": "الخميس الماضي",
"field-week": "الأسبوع",
"field-wed-narrow-relative+0": "الأربعاء الحالي",
"field-wed-narrow-relative+1": "الأربعاء القادم",
"field-quarter-narrow-relative+-1": "الربع الأخير",
"field-dayperiod-short": "ص/م",
"field-fri-short-relative+0": "الجمعة الحالي",
"field-fri-short-relative+1": "الجمعة القادم",
"field-hour-short": "الساعات",
"field-zone-short": "توقيت",
"field-month-narrow": "الشهر",
"field-hour-narrow": "الساعات",
"field-fri-narrow-relative+-1": "الجمعة الماضي",
"field-year-relative+0": "السنة الحالية",
"field-year-relative+1": "السنة القادمة",
"field-era-narrow": "العصر",
"field-fri-relative+-1": "الجمعة الماضي",
"field-tue-short-relative+-1": "الثلاثاء الماضي",
"field-minute-narrow": "الدقائق",
"field-mon-narrow-relative+0": "الإثنين الحالي",
"field-mon-narrow-relative+1": "الإثنين القادم",
"field-zone": "التوقيت",
"field-weekOfMonth-narrow": "أسبوع/شهر",
"field-weekday-narrow": "اليوم",
"field-quarter-narrow": "ربع السنة",
"field-sun-short-relative+-1": "الأحد الماضي",
"field-day-relative+-1": "أمس",
"field-day-relative+-2": "أول أمس",
"field-weekday-short": "اليوم",
"field-sun-relative+0": "الأحد الحالي",
"field-sun-relative+1": "الأحد القادم",
"field-day-short": "يوم",
"field-week-narrow": "الأسبوع",
"field-era": "العصر",
"field-fri-narrow-relative+0": "الجمعة الحالي",
"field-fri-narrow-relative+1": "الجمعة القادم"
}
//end v1.x content
); | cdnjs/cdnjs | ajax/libs/dojo/1.17.1/cldr/nls/ar/japanese.js | JavaScript | mit | 11,877 |
/* ========================================================================
* DOM-based Routing
* Based on http://goo.gl/EUTi53 by Paul Irish
*
* Only fires on body classes that match. If a body class contains a dash,
* replace the dash with an underscore when adding it to the object below.
* ======================================================================== */
var Roots = {
// All pages
common: {
init: function() {
// JavaScript to be fired on all pages
}
},
// Home page
home: {
init: function() {
// JavaScript to be fired on the home page
}
},
// About page
about: {
init: function() {
// JavaScript to be fired on the about page
}
}
};
var UTIL = {
fire: function(func, funcname, args) {
var namespace = Roots;
funcname = (funcname === undefined) ? 'init' : funcname;
if (func !== '' && namespace[func] && typeof namespace[func][funcname] === 'function') {
namespace[func][funcname](args);
}
},
loadEvents: function() {
UTIL.fire('common');
$.each(document.body.className.replace(/-/g, '_').split(/\s+/),function(i,classnm) {
UTIL.fire(classnm);
});
}
};
$(document).ready(UTIL.loadEvents);
| ajency/ascot-theme | wp-content/themes/shoestrap-3/assets/js/_main.js | JavaScript | gpl-2.0 | 1,224 |
define('app/routes/missing', ['ember'],
//
// Missing Route
//
// @returns Class
//
function () {
'use strict';
return App.MissingRoute = Ember.Route.extend({
documentTitle: 'mist.io - 404'
});
}
);
| DimensionDataCBUSydney/mist.io | src/mist/io/static/js/app/routes/missing.js | JavaScript | agpl-3.0 | 269 |
var SelectorTable = {
canReturnMultipleRecords: function () {
return true;
},
canHaveChildSelectors: function () {
return false;
},
canHaveLocalChildSelectors: function () {
return false;
},
canCreateNewJobs: function () {
return false;
},
willReturnElements: function () {
return false;
},
getTableHeaderColumns: function ($table) {
var columns = {};
var headerRowSelector = this.getTableHeaderRowSelector();
var $headerRow = $table.find(headerRowSelector);
if ($headerRow.length > 0) {
$headerRow.find("td,th").each(function (i) {
var header = $(this).text().trim();
columns[header] = {
index: i + 1
};
});
}
return columns;
},
_getData: function (parentElement) {
var dfd = $.Deferred();
var tables = this.getDataElements(parentElement);
var result = [];
$(tables).each(function (k, table) {
var columns = this.getTableHeaderColumns($(table));
var dataRowSelector = this.getTableDataRowSelector();
$(table).find(dataRowSelector).each(function (i, row) {
var data = {};
this.columns.forEach(function (column) {
if(column.extract === true) {
if (columns[column.header] === undefined) {
data[column.name] = null;
}
else {
var rowText = $(row).find(">:nth-child(" + columns[column.header].index + ")").text().trim();
data[column.name] = rowText;
}
}
});
result.push(data);
}.bind(this));
}.bind(this));
dfd.resolve(result);
return dfd.promise();
},
getDataColumns: function () {
var dataColumns = [];
this.columns.forEach(function (column) {
if (column.extract === true) {
dataColumns.push(column.name);
}
});
return dataColumns;
},
getFeatures: function () {
return ['multiple', 'columns', 'delay', 'tableDataRowSelector', 'tableHeaderRowSelector']
},
getItemCSSSelector: function () {
return "table";
},
getTableHeaderRowSelectorFromTableHTML: function(html) {
var $table = $(html);
if($table.find("thead tr:has(td:not(:empty)), thead tr:has(th:not(:empty))").length) {
if($table.find("thead tr").length === 1) {
return "thead tr";
}
else {
var $rows = $table.find("thead tr");
// first row with data
var rowIndex = $rows.index($rows.filter(":has(td:not(:empty)),:has(th:not(:empty))")[0]);
return "thead tr:nth-of-type("+(rowIndex+1)+")";
}
}
else if($table.find("tr td:not(:empty), tr th:not(:empty)").length) {
var $rows = $table.find("tr");
// first row with data
var rowIndex = $rows.index($rows.filter(":has(td:not(:empty)),:has(th:not(:empty))")[0]);
return "tr:nth-of-type("+(rowIndex+1)+")";
}
else {
return "";
}
},
getTableDataRowSelectorFromTableHTML: function(html) {
var $table = $(html);
if($table.find("thead tr:has(td:not(:empty)), thead tr:has(th:not(:empty))").length) {
return "tbody tr";
}
else if($table.find("tr td:not(:empty), tr th:not(:empty)").length) {
var $rows = $table.find("tr");
// first row with data
var rowIndex = $rows.index($rows.filter(":has(td:not(:empty)),:has(th:not(:empty))")[0]);
return "tr:nth-of-type(n+"+(rowIndex+2)+")";
}
else {
return "";
}
},
getTableHeaderRowSelector: function() {
// handle legacy selectors
if(this.tableHeaderRowSelector === undefined) {
return "thead tr";
}
else {
return this.tableHeaderRowSelector;
}
},
getTableDataRowSelector: function(){
// handle legacy selectors
if(this.tableDataRowSelector === undefined) {
return "tbody tr";
}
else {
return this.tableDataRowSelector;
}
},
/**
* Extract table header column info from html
* @param html
*/
getTableHeaderColumnsFromHTML: function(headerRowSelector, html) {
var $table = $(html);
var $headerRowColumns = $table.find(headerRowSelector).find("td,th");
var columns = [];
$headerRowColumns.each(function(i, columnEl) {
var header = $(columnEl).text().trim();
var name = header;
if(header.length !== 0) {
columns.push({
header: header,
name: name,
extract: true
});
}
});
return columns;
}
};
| kurtjcu/web-scraper-chrome-extension | extensionTest/scripts/Selector/SelectorTable.js | JavaScript | lgpl-3.0 | 4,123 |
/* Uncaught exception
* Output: None */
function throwsException() {
throw new Error();
}
try {
throwsException();
}
catch (e) { }
| qhanam/Pangor | js/test/input/error_handling/eh_fp_old.js | JavaScript | apache-2.0 | 137 |
/* The contents of this file are subject to the Netscape Public License
* Version 1.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.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is Mozilla Communicator client code, released March
* 31, 1998.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are Copyright (C) 1998
* Netscape Communications Corporation. All Rights Reserved.
*
*/
/**
File Name: 15.9.5.13.js
ECMA Section: 15.9.5.13
Description: Date.prototype.getUTCDay
1.Let t be this time value.
2.If t is NaN, return NaN.
3.Return WeekDay(t).
Author: christine@netscape.com
Date: 12 november 1997
*/
var SECTION = "15.9.5.13.js";
var VERSION = "ECMA_1";
startTest();
var TITLE = "Date.prototype.getUTCDay()";
writeHeaderToLog( SECTION + " "+ TITLE);
var testcases = new Array();
var TZ_ADJUST = TZ_DIFF * msPerHour;
addTestCase( TIME_1970 );
test();
function addTestCase( t ) {
for ( var m = 0; m < 12; m++ ) {
t += TimeInMonth(m);
for ( d = 0; d < TimeInMonth(m); d+= msPerDay*14 ) {
t += d;
testcases[tc++] = new TestCase( SECTION,
"(new Date("+t+")).getUTCDay()",
WeekDay((t)),
(new Date(t)).getUTCDay() );
}
}
}
function test() {
for ( tc=0; tc < testcases.length; tc++ ) {
testcases[tc].passed = writeTestCaseResult(
testcases[tc].expect,
testcases[tc].actual,
testcases[tc].description +" = "+
testcases[tc].actual );
testcases[tc].reason += ( testcases[tc].passed ) ? "" : "wrong value ";
}
stopTest();
return ( testcases );
}
| frivoal/presto-testo | core/standards/scripts/jstest-futhark/es-regression/imported-netscape/ecma/Date/15.9.5.13-3.js | JavaScript | bsd-3-clause | 2,280 |
// Copyright 2011 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Flags: --allow-natives-syntax
// Test that the arguments value is does not escape when it appears as
// an intermediate value in an expression.
function h() {}
function f() {
var a = null;
h(a = arguments);
};
%PrepareFunctionForOptimization(f);
f();
%OptimizeFunctionOnNextCall(f);
f();
| youtube/cobalt | third_party/v8/test/mjsunit/regress/regress-1351.js | JavaScript | bsd-3-clause | 1,896 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {assert} from 'chrome://resources/js/assert.m.js';
import {PromiseResolver} from 'chrome://resources/js/promise_resolver.m.js';
/**
* @fileoverview
* Implements a helper class for managing a fake API with async
* methods.
*/
/**
* Maintains a resolver and the return value of the fake method.
* @template T
*/
class FakeMethodState {
constructor() {
/** @private {T} */
this.result_ = undefined;
}
/**
* Resolve the method with the supplied result.
* @return {!Promise}
*/
resolveMethod() {
const resolver = new PromiseResolver();
resolver.resolve(this.result_);
return resolver.promise;
}
/**
* Resolve the method with the supplied result after delayMs.
* @param {number} delayMs
* @return {!Promise}
*/
resolveMethodWithDelay(delayMs) {
const resolver = new PromiseResolver();
setTimeout(() => {
resolver.resolve(this.result_);
}, delayMs);
return resolver.promise;
}
/**
* Set the result for this method.
* @param {T} result
*/
setResult(result) {
this.result_ = result;
}
}
/**
* Manages a map of fake async methods, their resolvers and the fake
* return value they will produce.
* @template T
**/
export class FakeMethodResolver {
constructor() {
/** @private {!Map<string, !FakeMethodState>} */
this.methodMap_ = new Map();
}
/**
* Registers methodName with the resolver. Calling other methods with a
* methodName that has not been registered will assert.
* @param {string} methodName
*/
register(methodName) {
this.methodMap_.set(methodName, new FakeMethodState());
}
/**
* Set the value that methodName will produce when it resolves.
* @param {string} methodName
* @param {T} result
*/
setResult(methodName, result) {
this.getState_(methodName).setResult(result);
}
/**
* Causes the promise for methodName to resolve.
* @param {string} methodName
* @return {!Promise}
*/
resolveMethod(methodName) {
return this.getState_(methodName).resolveMethod();
}
/**
* Causes the promise for methodName to resolve after delayMs.
* @param {string} methodName
* @param {number} delayMs
* @return {!Promise}
*/
resolveMethodWithDelay(methodName, delayMs) {
return this.getState_(methodName).resolveMethodWithDelay(delayMs);
}
/**
* Return the FakeMethodState for methodName.
* @param {string} methodName
* @return {!FakeMethodState}
* @private
*/
getState_(methodName) {
const state = this.methodMap_.get(methodName);
assert(!!state, `Method '${methodName}' not found.`);
return state;
}
}
| ric2b/Vivaldi-browser | chromium/ash/webui/common/resources/fake_method_resolver.js | JavaScript | bsd-3-clause | 2,819 |
version https://git-lfs.github.com/spec/v1
oid sha256:d988541e8ab30a2c074bc3c21478e898956b216d6ac33c9eda9dda5bc79345c3
size 927
| yogeshsaroya/new-cdnjs | ajax/libs/dojo/1.8.9/cldr/nls/th/currency.js | JavaScript | mit | 128 |
'use strict';
const AddonInstallTask = require('../../../lib/tasks/addon-install');
const expect = require('chai').expect;
const CoreObject = require('core-object');
const MockUi = require('console-ui/mock');
describe('addon install task', function () {
let ui;
let project;
beforeEach(function () {
ui = new MockUi();
project = {
reloadAddons() {},
};
});
afterEach(function () {
// ui.stopProgress();
ui = undefined;
project = undefined;
});
describe('when no save flag specified in blueprintOptions', function () {
it('calls npm install with --save-dev as a default', function (done) {
let MockNpmInstallTask = CoreObject.extend({
run(options) {
expect(options.save).to.not.be.true;
expect(options['save-dev']).to.be.true;
done();
return Promise.resolve();
},
});
let addonInstallTask = new AddonInstallTask({
ui,
project,
NpmInstallTask: MockNpmInstallTask,
});
addonInstallTask.run({});
});
});
describe('when save flag specified in blueprintOptions', function () {
it('calls npm install with --save', function (done) {
let MockNpmInstallTask = CoreObject.extend({
run(options) {
expect(options.save).to.be.true;
expect(options['save-dev']).to.not.be.true;
done();
return Promise.resolve();
},
});
let addonInstallTask = new AddonInstallTask({
ui,
project,
NpmInstallTask: MockNpmInstallTask,
});
addonInstallTask.run({
blueprintOptions: {
save: true,
},
});
});
});
describe('when saveDev flag specified in blueprintOptions', function () {
it('calls npm install with --save-dev', function (done) {
let MockNpmInstallTask = CoreObject.extend({
run(options) {
expect(options.save).to.not.be.true;
expect(options['save-dev']).to.be.true;
done();
return Promise.resolve();
},
});
let addonInstallTask = new AddonInstallTask({
ui,
project,
NpmInstallTask: MockNpmInstallTask,
});
addonInstallTask.run({
blueprintOptions: {
saveDev: true,
},
});
});
});
describe('when both save and saveDev flag specified in blueprintOptions', function () {
it('calls npm install with --save', function (done) {
let MockNpmInstallTask = CoreObject.extend({
run(options) {
expect(options.save).to.be.true;
expect(options['save-dev']).to.not.be.true;
done();
return Promise.resolve();
},
});
let addonInstallTask = new AddonInstallTask({
ui,
project,
NpmInstallTask: MockNpmInstallTask,
});
addonInstallTask.run({
blueprintOptions: {
save: true,
saveDev: true,
},
});
});
});
});
| ember-cli/ember-cli | tests/unit/tasks/addon-install-test.js | JavaScript | mit | 3,014 |
/*
* Copyright (c) 2012 Mathieu Turcotte
* Licensed under the MIT license.
*/
var sinon = require('sinon'),
util = require('util');
var BackoffStrategy = require('../lib/strategy/strategy');
function SampleBackoffStrategy(options) {
BackoffStrategy.call(this, options);
}
util.inherits(SampleBackoffStrategy, BackoffStrategy);
SampleBackoffStrategy.prototype.next_ = function() {
return this.getInitialDelay();
};
SampleBackoffStrategy.prototype.reset_ = function() {};
exports["BackoffStrategy"] = {
setUp: function(callback) {
this.random = sinon.stub(Math, 'random');
callback();
},
tearDown: function(callback) {
this.random.restore();
callback();
},
"the randomisation factor should be between 0 and 1": function(test) {
test.throws(function() {
new BackoffStrategy({
randomisationFactor: -0.1
});
});
test.throws(function() {
new BackoffStrategy({
randomisationFactor: 1.1
});
});
test.doesNotThrow(function() {
new BackoffStrategy({
randomisationFactor: 0.5
});
});
test.done();
},
"the raw delay should be randomized based on the randomisation factor": function(test) {
var strategy = new SampleBackoffStrategy({
randomisationFactor: 0.5,
initialDelay: 1000
});
this.random.returns(0.5);
var backoffDelay = strategy.next();
test.equals(backoffDelay, 1000 + (1000 * 0.5 * 0.5));
test.done();
},
"the initial backoff delay should be greater than 0": function(test) {
test.throws(function() {
new BackoffStrategy({
initialDelay: -1
});
});
test.throws(function() {
new BackoffStrategy({
initialDelay: 0
});
});
test.doesNotThrow(function() {
new BackoffStrategy({
initialDelay: 1
});
});
test.done();
},
"the maximal backoff delay should be greater than 0": function(test) {
test.throws(function() {
new BackoffStrategy({
maxDelay: -1
});
});
test.throws(function() {
new BackoffStrategy({
maxDelay: 0
});
});
test.done();
},
"the maximal backoff delay should be greater than the initial backoff delay": function(test) {
test.throws(function() {
new BackoffStrategy({
initialDelay: 10,
maxDelay: 10
});
});
test.doesNotThrow(function() {
new BackoffStrategy({
initialDelay: 10,
maxDelay: 11
});
});
test.done();
}
};
| githubUser919/ps-npm-as-a-build-tool | node_modules/live-reload/node_modules/reconnect/node_modules/backoff/tests/backoff_strategy.js | JavaScript | mit | 2,945 |
/**
All non-API related routes (e.g. route to Angular app).
*/
'use strict';
var express = require('express');
var app = module.exports = express();
module.exports = function(cfg){
var routes = {
index: function(req, res){
// check if last part of URL is a file reference by check if it contains a "."
var isFile = req.params[0].split('/').slice(-1)[0].indexOf('.') !== -1;
if(isFile){
// if file, then static middleware couldn't serve it since it doesn't exist
res.send(404);
} else {
// route all requests to Angular app
if(global.environment !==undefined && global.environment =='test') {
res.sendfile(req.app.get('staticFilePath') + '/index-test.html');
}
else {
res.sendfile(req.app.get('staticFilePath') + '/index.html');
}
}
}
};
// wildcard route: redirect all others to the index (HTML5 history)
app.get(cfg.server.appPath + '*', routes.index);
return app;
};
| notorii/generator-mean-seed | core-default-node/templates/app/routes/index.js | JavaScript | mit | 1,057 |
//ImageGallery2 Constructor
kony.ui.ImageGallery2 = function(bconfig, lconfig, pspconfig) {
if(arguments.length < 3)
bconfig = lconfig = pspconfig = $KU.mergeDefaults(bconfig, $KU.getAllDefaults("ImageGallery2"));
kony.ui.ImageGallery2.baseConstructor.call(this, bconfig, lconfig, pspconfig);
this.imageWhileDownloading = this.imagewhiledownloading = bconfig.imageWhileDownloading;
this.imageWhenFailed = this.imagewhenfailed = bconfig.imageWhenFailed;
this.spaceBetweenImages = this.spacebetweenimages = bconfig.spaceBetweenImages;
this.selectedindex = bconfig.selectedIndex || null;
this.onselection = bconfig.onSelection;
this.referencewidth = lconfig.referenceWidth;
this.referenceheight = lconfig.referenceHeight;
this.imagescalemode = lconfig.imageScaleMode;
//Internal Usage
this.wType = "IGallery";
this.name = "kony.ui.ImageGallery2";
this.canUpdateUI = true; //This flag is to prevent updating selectedIndex ui when changing it in event handler
this.selecteditem = null; //ReadOnly
var data = bconfig.data;
if (data) {
this.masterdata = data[0];
this.key = data[1];
}
defineGetter(this, "data", function() {
return data;
});
defineSetter(this, "data", function(val) {
data = val;
this.canUpdateUI && $KW[this.wType]["updateView"](this, "data" , val);
});
kony.ui.ImageGallery2.prototype.setGetterSetter.call(this);
};
kony.inherits(kony.ui.ImageGallery2, kony.ui.Widget);
kony.ui.ImageGallery2.prototype.setGetterSetter = function() {
defineGetter(this, "selectedIndex", function() {
return this.selectedindex;
});
defineSetter(this, "selectedIndex", function(val) {
this.selectedindex = val;
this.canUpdateUI && $KW[this.wType]["updateView"](this, "selectedindex" , val);
});
defineGetter(this, "onSelection", function() {
return this.onselection;
});
defineSetter(this, "onSelection", function(val) {
this.onselection = val;
});
defineGetter(this, "referenceWidth", function() {
return this.referencewidth;
});
defineSetter(this, "referenceWidth", function(val) {
this.referencewidth = val;
$KW[this.wType]["updateView"](this, "referencewidth", val);
});
defineGetter(this, "referenceHeight", function() {
return this.referenceheight;
});
defineSetter(this, "referenceHeight", function(val) {
this.referenceheight = val;
$KW[this.wType]["updateView"](this, "referenceheight" , val);
});
defineGetter(this, "imageScaleMode", function() {
return this.imagescalemode;
});
defineSetter(this, "imageScaleMode", function(val) {
this.imagescalemode = val;
$KW[this.wType]["updateView"](this, "imagescalemode", val);
});
defineGetter(this, "selectedItem", function() {
return this.selecteditem;
});
defineSetter(this, "selectedItem", function() {
//return this.selecteditem;
});
}
kony.ui.ImageGallery2.prototype.addAll = function(dataarray, key) {
$KW.IGallery.addAll(this, dataarray, key);
};
kony.ui.ImageGallery2.prototype.setData = function(dataarray, key) {
$KW.IGallery.setData(this, dataarray, key);
};
kony.ui.ImageGallery2.prototype.setDataAt = function(dataobj, index) {
$KW.IGallery.setDataAt(this, dataobj, index);
};
kony.ui.ImageGallery2.prototype.addDataAt = function(dataobj, index) {
$KW.IGallery.addDataAt(this, dataobj, index);
};
kony.ui.ImageGallery2.prototype.removeAt = function(index) {
$KW.IGallery.removeAt(this, index);
};
kony.ui.ImageGallery2.prototype.removeAll = function() {
$KW.IGallery.removeAll(this);
};
kony.ui.ImageGallery = function(bconfig, lconfig, pspconfig) {
kony.ui.ImageGallery.baseConstructor.call(this, bconfig, lconfig, pspconfig);
//For Backward compatibility
this.itemsperrow = pspconfig.itemsPerRow;
this.heightwidth = pspconfig.heightWidth;
this.name ="kony.ui.ImageGallery";
this.focuseditem = null; //ReadOnly
defineGetter(this, "focusedItem", function() {
return this.focuseditem;
});
this.focusedindex = bconfig.focusedIndex || null;
this.setGetterSetter();
}
kony.ui.ImageGallery.prototype.setGetterSetter = function() {
defineGetter(this, "focusedIndex", function() {
return this.focusedindex;
});
defineSetter(this, "focusedIndex", function(val) {
this.focusedindex = val;
$KW[this.wType]["updateView"](this, "focusedindex" , val);
});
defineGetter(this, "focusedItem", function() {
return this.focuseditem;
});
}
kony.inherits(kony.ui.ImageGallery, kony.ui.ImageGallery2); | backslash-f/paintcode-kony | Kony/webapps/KonyPaintCode/spawinphone8/jslib/konyJSLib/ui/konyuiImageGallery.js | JavaScript | mit | 4,446 |
/**
* @copyright (C) 2019 Open Source Matters, Inc. <https://www.joomla.org>
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
((customElements) => {
'use strict';
const KEYCODE = {
SPACE: 32,
ESC: 27,
ENTER: 13,
};
/**
* Helper for testing whether a selection modifier is pressed
* @param {Event} event
*
* @returns {boolean|*}
*/
function hasModifier(event) {
return (event.ctrlKey || event.metaKey || event.shiftKey);
}
class JoomlaFieldSubform extends HTMLElement {
// Attribute getters
get buttonAdd() { return this.getAttribute('button-add'); }
get buttonRemove() { return this.getAttribute('button-remove'); }
get buttonMove() { return this.getAttribute('button-move'); }
get rowsContainer() { return this.getAttribute('rows-container'); }
get repeatableElement() { return this.getAttribute('repeatable-element'); }
get minimum() { return this.getAttribute('minimum'); }
get maximum() { return this.getAttribute('maximum'); }
get name() { return this.getAttribute('name'); }
set name(value) {
// Update the template
this.template = this.template.replace(new RegExp(` name="${this.name.replace(/[[\]]/g, '\\$&')}`, 'g'), ` name="${value}`);
this.setAttribute('name', value);
}
constructor() {
super();
const that = this;
// Get the rows container
this.containerWithRows = this;
if (this.rowsContainer) {
const allContainers = this.querySelectorAll(this.rowsContainer);
// Find closest, and exclude nested
Array.from(allContainers).forEach((container) => {
if (container.closest('joomla-field-subform') === this) {
this.containerWithRows = container;
}
});
}
// Keep track of row index, this is important to avoid a name duplication
// Note: php side should reset the indexes each time, eg: $value = array_values($value);
this.lastRowIndex = this.getRows().length - 1;
// Template for the repeating group
this.template = '';
// Prepare a row template, and find available field names
this.prepareTemplate();
// Bind buttons
if (this.buttonAdd || this.buttonRemove) {
this.addEventListener('click', (event) => {
let btnAdd = null;
let btnRem = null;
if (that.buttonAdd) {
btnAdd = event.target.matches(that.buttonAdd)
? event.target
: event.target.closest(that.buttonAdd);
}
if (that.buttonRemove) {
btnRem = event.target.matches(that.buttonRemove)
? event.target
: event.target.closest(that.buttonRemove);
}
// Check active, with extra check for nested joomla-field-subform
if (btnAdd && btnAdd.closest('joomla-field-subform') === that) {
let row = btnAdd.closest(that.repeatableElement);
row = row && row.closest('joomla-field-subform') === that ? row : null;
that.addRow(row);
event.preventDefault();
} else if (btnRem && btnRem.closest('joomla-field-subform') === that) {
const row = btnRem.closest(that.repeatableElement);
that.removeRow(row);
event.preventDefault();
}
});
this.addEventListener('keydown', (event) => {
if (event.keyCode !== KEYCODE.SPACE) return;
const isAdd = that.buttonAdd && event.target.matches(that.buttonAdd);
const isRem = that.buttonRemove && event.target.matches(that.buttonRemove);
if ((isAdd || isRem) && event.target.closest('joomla-field-subform') === that) {
let row = event.target.closest(that.repeatableElement);
row = row && row.closest('joomla-field-subform') === that ? row : null;
if (isRem && row) {
that.removeRow(row);
} else if (isAdd) {
that.addRow(row);
}
event.preventDefault();
}
});
}
// Sorting
if (this.buttonMove) {
this.setUpDragSort();
}
}
/**
* Search for existing rows
* @returns {HTMLElement[]}
*/
getRows() {
const rows = Array.from(this.containerWithRows.children);
const result = [];
// Filter out the rows
rows.forEach((row) => {
if (row.matches(this.repeatableElement)) {
result.push(row);
}
});
return result;
}
/**
* Prepare a row template
*/
prepareTemplate() {
const tmplElement = [].slice.call(this.children).filter((el) => el.classList.contains('subform-repeatable-template-section'));
if (tmplElement[0]) {
this.template = tmplElement[0].innerHTML;
}
if (!this.template) {
throw new Error('The row template is required for the subform element to work');
}
}
/**
* Add new row
* @param {HTMLElement} after
* @returns {HTMLElement}
*/
addRow(after) {
// Count how many we already have
const count = this.getRows().length;
if (count >= this.maximum) {
return null;
}
// Make a new row from the template
let tmpEl;
if (this.containerWithRows.nodeName === 'TBODY' || this.containerWithRows.nodeName === 'TABLE') {
tmpEl = document.createElement('tbody');
} else {
tmpEl = document.createElement('div');
}
tmpEl.innerHTML = this.template;
const row = tmpEl.children[0];
// Add to container
if (after) {
after.parentNode.insertBefore(row, after.nextSibling);
} else {
this.containerWithRows.append(row);
}
// Add draggable attributes
if (this.buttonMove) {
row.setAttribute('draggable', 'false');
row.setAttribute('aria-grabbed', 'false');
row.setAttribute('tabindex', '0');
}
// Marker that it is new
row.setAttribute('data-new', '1');
// Fix names and ids, and reset values
this.fixUniqueAttributes(row, count);
// Tell about the new row
this.dispatchEvent(new CustomEvent('subform-row-add', {
detail: { row },
bubbles: true,
}));
row.dispatchEvent(new CustomEvent('joomla:updated', {
bubbles: true,
cancelable: true,
}));
return row;
}
/**
* Remove the row
* @param {HTMLElement} row
*/
removeRow(row) {
// Count how much we have
const count = this.getRows().length;
if (count <= this.minimum) {
return;
}
// Tell about the row will be removed
this.dispatchEvent(new CustomEvent('subform-row-remove', {
detail: { row },
bubbles: true,
}));
row.dispatchEvent(new CustomEvent('joomla:removed', {
bubbles: true,
cancelable: true,
}));
row.parentNode.removeChild(row);
}
/**
* Fix name and id for fields that are in the row
* @param {HTMLElement} row
* @param {Number} count
*/
fixUniqueAttributes(row, count) {
const countTmp = count || 0;
const group = row.getAttribute('data-group'); // current group name
const basename = row.getAttribute('data-base-name');
const countnew = Math.max(this.lastRowIndex, countTmp);
const groupnew = basename + countnew; // new group name
this.lastRowIndex = countnew + 1;
row.setAttribute('data-group', groupnew);
// Fix inputs that have a "name" attribute
let haveName = row.querySelectorAll('[name]');
const ids = {}; // Collect id for fix checkboxes and radio
// Filter out nested
haveName = [].slice.call(haveName).filter((el) => {
if (el.nodeName === 'JOOMLA-FIELD-SUBFORM') {
// Skip self in .closest() call
return el.parentElement.closest('joomla-field-subform') === this;
}
return el.closest('joomla-field-subform') === this;
});
haveName.forEach((elem) => {
const $el = elem;
const name = $el.getAttribute('name');
const aria = $el.getAttribute('aria-describedby');
const id = name
.replace(/(\[\]$)/g, '')
.replace(/(\]\[)/g, '__')
.replace(/\[/g, '_')
.replace(/\]/g, ''); // id from name
const nameNew = name.replace(`[${group}][`, `[${groupnew}][`); // New name
let idNew = id.replace(group, groupnew).replace(/\W/g, '_'); // Count new id
let countMulti = 0; // count for multiple radio/checkboxes
let forOldAttr = id; // Fix "for" in the labels
if ($el.type === 'checkbox' && name.match(/\[\]$/)) { // <input type="checkbox" name="name[]"> fix
// Recount id
countMulti = ids[id] ? ids[id].length : 0;
if (!countMulti) {
// Set the id for fieldset and group label
const fieldset = $el.closest('fieldset.checkboxes');
const elLbl = row.querySelector(`label[for="${id}"]`);
if (fieldset) {
fieldset.setAttribute('id', idNew);
}
if (elLbl) {
elLbl.setAttribute('for', idNew);
elLbl.setAttribute('id', `${idNew}-lbl`);
}
}
forOldAttr += countMulti;
idNew += countMulti;
} else if ($el.type === 'radio') { // <input type="radio"> fix
// Recount id
countMulti = ids[id] ? ids[id].length : 0;
if (!countMulti) {
// Set the id for fieldset and group label
const fieldset = $el.closest('fieldset.radio');
const elLbl = row.querySelector(`label[for="${id}"]`);
if (fieldset) {
fieldset.setAttribute('id', idNew);
}
if (elLbl) {
elLbl.setAttribute('for', idNew);
elLbl.setAttribute('id', `${idNew}-lbl`);
}
}
forOldAttr += countMulti;
idNew += countMulti;
}
// Cache already used id
if (ids[id]) {
ids[id].push(true);
} else {
ids[id] = [true];
}
// Replace the name to new one
$el.name = nameNew;
if ($el.id) {
$el.id = idNew;
}
if (aria) {
$el.setAttribute('aria-describedby', `${nameNew}-desc`);
}
// Check if there is a label for this input
const lbl = row.querySelector(`label[for="${forOldAttr}"]`);
if (lbl) {
lbl.setAttribute('for', idNew);
lbl.setAttribute('id', `${idNew}-lbl`);
}
});
}
/**
* Use of HTML Drag and Drop API
* https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API
* https://www.sitepoint.com/accessible-drag-drop/
*/
setUpDragSort() {
const that = this; // Self reference
let item = null; // Storing the selected item
let touched = false; // We have a touch events
// Find all existing rows and add draggable attributes
const rows = Array.from(this.getRows());
rows.forEach((row) => {
row.setAttribute('draggable', 'false');
row.setAttribute('aria-grabbed', 'false');
row.setAttribute('tabindex', '0');
});
// Helper method to test whether Handler was clicked
function getMoveHandler(element) {
return !element.form // This need to test whether the element is :input
&& element.matches(that.buttonMove) ? element : element.closest(that.buttonMove);
}
// Helper method to move row to selected position
function switchRowPositions(src, dest) {
let isRowBefore = false;
if (src.parentNode === dest.parentNode) {
for (let cur = src; cur; cur = cur.previousSibling) {
if (cur === dest) {
isRowBefore = true;
break;
}
}
}
if (isRowBefore) {
dest.parentNode.insertBefore(src, dest);
} else {
dest.parentNode.insertBefore(src, dest.nextSibling);
}
}
/**
* Touch interaction:
*
* - a touch of "move button" marks a row draggable / "selected",
* or deselect previous selected
*
* - a touch of "move button" in the destination row will move
* a selected row to a new position
*/
this.addEventListener('touchstart', (event) => {
touched = true;
// Check for .move button
const handler = getMoveHandler(event.target);
const row = handler ? handler.closest(that.repeatableElement) : null;
if (!row || row.closest('joomla-field-subform') !== that) {
return;
}
// First selection
if (!item) {
row.setAttribute('draggable', 'true');
row.setAttribute('aria-grabbed', 'true');
item = row;
} else { // Second selection
// Move to selected position
if (row !== item) {
switchRowPositions(item, row);
}
item.setAttribute('draggable', 'false');
item.setAttribute('aria-grabbed', 'false');
item = null;
}
event.preventDefault();
});
// Mouse interaction
// - mouse down, enable "draggable" and allow to drag the row,
// - mouse up, disable "draggable"
this.addEventListener('mousedown', ({ target }) => {
if (touched) return;
// Check for .move button
const handler = getMoveHandler(target);
const row = handler ? handler.closest(that.repeatableElement) : null;
if (!row || row.closest('joomla-field-subform') !== that) {
return;
}
row.setAttribute('draggable', 'true');
row.setAttribute('aria-grabbed', 'true');
item = row;
});
this.addEventListener('mouseup', () => {
if (item && !touched) {
item.setAttribute('draggable', 'false');
item.setAttribute('aria-grabbed', 'false');
item = null;
}
});
// Keyboard interaction
// - "tab" to navigate to needed row,
// - modifier (ctr,alt,shift) + "space" select the row,
// - "tab" to select destination,
// - "enter" to place selected row in to destination
// - "esc" to cancel selection
this.addEventListener('keydown', (event) => {
if ((event.keyCode !== KEYCODE.ESC
&& event.keyCode !== KEYCODE.SPACE
&& event.keyCode !== KEYCODE.ENTER) || event.target.form
|| !event.target.matches(that.repeatableElement)) {
return;
}
const row = event.target;
// Make sure we handle correct children
if (!row || row.closest('joomla-field-subform') !== that) {
return;
}
// Space is the selection or unselection keystroke
if (event.keyCode === KEYCODE.SPACE && hasModifier(event)) {
// Unselect previously selected
if (row.getAttribute('aria-grabbed') === 'true') {
row.setAttribute('draggable', 'false');
row.setAttribute('aria-grabbed', 'false');
item = null;
} else { // Select new
// If there was previously selected
if (item) {
item.setAttribute('draggable', 'false');
item.setAttribute('aria-grabbed', 'false');
item = null;
}
// Mark new selection
row.setAttribute('draggable', 'true');
row.setAttribute('aria-grabbed', 'true');
item = row;
}
// Prevent default to suppress any native actions
event.preventDefault();
}
// Escape is the abort keystroke (for any target element)
if (event.keyCode === KEYCODE.ESC && item) {
item.setAttribute('draggable', 'false');
item.setAttribute('aria-grabbed', 'false');
item = null;
}
// Enter, to place selected item in selected position
if (event.keyCode === KEYCODE.ENTER && item) {
item.setAttribute('draggable', 'false');
item.setAttribute('aria-grabbed', 'false');
// Do nothing here
if (row === item) {
item = null;
return;
}
// Move the item to selected position
switchRowPositions(item, row);
event.preventDefault();
item = null;
}
});
// dragstart event to initiate mouse dragging
this.addEventListener('dragstart', ({ dataTransfer }) => {
if (item) {
// We going to move the row
dataTransfer.effectAllowed = 'move';
// This need to work in Firefox and IE10+
dataTransfer.setData('text', '');
}
});
this.addEventListener('dragover', (event) => {
if (item) {
event.preventDefault();
}
});
// Handle drag action, move element to hovered position
this.addEventListener('dragenter', ({ target }) => {
// Make sure the target in the correct container
if (!item || target.parentElement.closest('joomla-field-subform') !== that) {
return;
}
// Find a hovered row
const row = target.closest(that.repeatableElement);
// One more check for correct parent
if (!row || row.closest('joomla-field-subform') !== that) return;
switchRowPositions(item, row);
});
// dragend event to clean-up after drop or abort
// which fires whether or not the drop target was valid
this.addEventListener('dragend', () => {
if (item) {
item.setAttribute('draggable', 'false');
item.setAttribute('aria-grabbed', 'false');
item = null;
}
});
}
}
customElements.define('joomla-field-subform', JoomlaFieldSubform);
})(customElements);
| richard67/joomla-cms | build/media_source/system/js/fields/joomla-field-subform.w-c.es6.js | JavaScript | gpl-2.0 | 18,121 |
/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Util.js
*/
/**
* Namespace: OpenLayers.Event
* Utility functions for event handling.
*/
OpenLayers.Event = {
/**
* Property: observers
* {Object} A hashtable cache of the event observers. Keyed by
* element._eventCacheID
*/
observers: false,
/**
* Constant: KEY_BACKSPACE
* {int}
*/
KEY_BACKSPACE: 8,
/**
* Constant: KEY_TAB
* {int}
*/
KEY_TAB: 9,
/**
* Constant: KEY_RETURN
* {int}
*/
KEY_RETURN: 13,
/**
* Constant: KEY_ESC
* {int}
*/
KEY_ESC: 27,
/**
* Constant: KEY_LEFT
* {int}
*/
KEY_LEFT: 37,
/**
* Constant: KEY_UP
* {int}
*/
KEY_UP: 38,
/**
* Constant: KEY_RIGHT
* {int}
*/
KEY_RIGHT: 39,
/**
* Constant: KEY_DOWN
* {int}
*/
KEY_DOWN: 40,
/**
* Constant: KEY_DELETE
* {int}
*/
KEY_DELETE: 46,
/**
* Method: element
* Cross browser event element detection.
*
* Parameters:
* event - {Event}
*
* Returns:
* {DOMElement} The element that caused the event
*/
element: function(event) {
return event.target || event.srcElement;
},
/**
* Method: isLeftClick
* Determine whether event was caused by a left click.
*
* Parameters:
* event - {Event}
*
* Returns:
* {Boolean}
*/
isLeftClick: function(event) {
return (((event.which) && (event.which == 1)) ||
((event.button) && (event.button == 1)));
},
/**
* Method: isRightClick
* Determine whether event was caused by a right mouse click.
*
* Parameters:
* event - {Event}
*
* Returns:
* {Boolean}
*/
isRightClick: function(event) {
return (((event.which) && (event.which == 3)) ||
((event.button) && (event.button == 2)));
},
/**
* Method: stop
* Stops an event from propagating.
*
* Parameters:
* event - {Event}
* allowDefault - {Boolean} If true, we stop the event chain but
* still allow the default browser
* behaviour (text selection, radio-button
* clicking, etc)
* Default false
*/
stop: function(event, allowDefault) {
if (!allowDefault) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
}
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
/**
* Method: findElement
*
* Parameters:
* event - {Event}
* tagName - {String}
*
* Returns:
* {DOMElement} The first node with the given tagName, starting from the
* node the event was triggered on and traversing the DOM upwards
*/
findElement: function(event, tagName) {
var element = OpenLayers.Event.element(event);
while (element.parentNode && (!element.tagName ||
(element.tagName.toUpperCase() != tagName.toUpperCase()))){
element = element.parentNode;
}
return element;
},
/**
* Method: observe
*
* Parameters:
* elementParam - {DOMElement || String}
* name - {String}
* observer - {function}
* useCapture - {Boolean}
*/
observe: function(elementParam, name, observer, useCapture) {
var element = OpenLayers.Util.getElement(elementParam);
useCapture = useCapture || false;
if (name == 'keypress' &&
(navigator.appVersion.match(/Konqueror|Safari|KHTML/)
|| element.attachEvent)) {
name = 'keydown';
}
//if observers cache has not yet been created, create it
if (!this.observers) {
this.observers = {};
}
//if not already assigned, make a new unique cache ID
if (!element._eventCacheID) {
var idPrefix = "eventCacheID_";
if (element.id) {
idPrefix = element.id + "_" + idPrefix;
}
element._eventCacheID = OpenLayers.Util.createUniqueID(idPrefix);
}
var cacheID = element._eventCacheID;
//if there is not yet a hash entry for this element, add one
if (!this.observers[cacheID]) {
this.observers[cacheID] = [];
}
//add a new observer to this element's list
this.observers[cacheID].push({
'element': element,
'name': name,
'observer': observer,
'useCapture': useCapture
});
//add the actual browser event listener
if (element.addEventListener) {
element.addEventListener(name, observer, useCapture);
} else if (element.attachEvent) {
element.attachEvent('on' + name, observer);
}
},
/**
* Method: stopObservingElement
* Given the id of an element to stop observing, cycle through the
* element's cached observers, calling stopObserving on each one,
* skipping those entries which can no longer be removed.
*
* parameters:
* elementParam - {DOMElement || String}
*/
stopObservingElement: function(elementParam) {
var element = OpenLayers.Util.getElement(elementParam);
var cacheID = element._eventCacheID;
this._removeElementObservers(OpenLayers.Event.observers[cacheID]);
},
/**
* Method: _removeElementObservers
*
* Parameters:
* elementObservers - {Array(Object)} Array of (element, name,
* observer, usecapture) objects,
* taken directly from hashtable
*/
_removeElementObservers: function(elementObservers) {
if (elementObservers) {
for(var i = elementObservers.length-1; i >= 0; i--) {
var entry = elementObservers[i];
var args = new Array(entry.element,
entry.name,
entry.observer,
entry.useCapture);
var removed = OpenLayers.Event.stopObserving.apply(this, args);
}
}
},
/**
* Method: stopObserving
*
* Parameters:
* elementParam - {DOMElement || String}
* name - {String}
* observer - {function}
* useCapture - {Boolean}
*
* Returns:
* {Boolean} Whether or not the event observer was removed
*/
stopObserving: function(elementParam, name, observer, useCapture) {
useCapture = useCapture || false;
var element = OpenLayers.Util.getElement(elementParam);
var cacheID = element._eventCacheID;
if (name == 'keypress') {
if ( navigator.appVersion.match(/Konqueror|Safari|KHTML/) ||
element.detachEvent) {
name = 'keydown';
}
}
// find element's entry in this.observers cache and remove it
var foundEntry = false;
var elementObservers = OpenLayers.Event.observers[cacheID];
if (elementObservers) {
// find the specific event type in the element's list
var i=0;
while(!foundEntry && i < elementObservers.length) {
var cacheEntry = elementObservers[i];
if ((cacheEntry.name == name) &&
(cacheEntry.observer == observer) &&
(cacheEntry.useCapture == useCapture)) {
elementObservers.splice(i, 1);
if (elementObservers.length == 0) {
delete OpenLayers.Event.observers[cacheID];
}
foundEntry = true;
break;
}
i++;
}
}
//actually remove the event listener from browser
if (foundEntry) {
if (element.removeEventListener) {
element.removeEventListener(name, observer, useCapture);
} else if (element && element.detachEvent) {
element.detachEvent('on' + name, observer);
}
}
return foundEntry;
},
/**
* Method: unloadCache
* Cycle through all the element entries in the events cache and call
* stopObservingElement on each.
*/
unloadCache: function() {
// check for OpenLayers.Event before checking for observers, because
// OpenLayers.Event may be undefined in IE if no map instance was
// created
if (OpenLayers.Event && OpenLayers.Event.observers) {
for (var cacheID in OpenLayers.Event.observers) {
var elementObservers = OpenLayers.Event.observers[cacheID];
OpenLayers.Event._removeElementObservers.apply(this,
[elementObservers]);
}
OpenLayers.Event.observers = false;
}
},
CLASS_NAME: "OpenLayers.Event"
};
/* prevent memory leaks in IE */
OpenLayers.Event.observe(window, 'unload', OpenLayers.Event.unloadCache, false);
// FIXME: Remove this in 3.0. In 3.0, Event.stop will no longer be provided
// by OpenLayers.
if (window.Event) {
OpenLayers.Util.applyDefaults(window.Event, OpenLayers.Event);
} else {
var Event = OpenLayers.Event;
}
/**
* Class: OpenLayers.Events
*/
OpenLayers.Events = OpenLayers.Class({
/**
* Constant: BROWSER_EVENTS
* {Array(String)} supported events
*/
BROWSER_EVENTS: [
"mouseover", "mouseout",
"mousedown", "mouseup", "mousemove",
"click", "dblclick", "rightclick", "dblrightclick",
"resize", "focus", "blur"
],
/**
* Property: listeners
* {Object} Hashtable of Array(Function): events listener functions
*/
listeners: null,
/**
* Property: object
* {Object} the code object issuing application events
*/
object: null,
/**
* Property: element
* {DOMElement} the DOM element receiving browser events
*/
element: null,
/**
* Property: eventTypes
* {Array(String)} list of support application events
*/
eventTypes: null,
/**
* Property: eventHandler
* {Function} bound event handler attached to elements
*/
eventHandler: null,
/**
* APIProperty: fallThrough
* {Boolean}
*/
fallThrough: null,
/**
* APIProperty: includeXY
* {Boolean} Should the .xy property automatically be created for browser
* mouse events? In general, this should be false. If it is true, then
* mouse events will automatically generate a '.xy' property on the
* event object that is passed. (Prior to OpenLayers 2.7, this was true
* by default.) Otherwise, you can call the getMousePosition on the
* relevant events handler on the object available via the 'evt.object'
* property of the evt object. So, for most events, you can call:
* function named(evt) {
* this.xy = this.object.events.getMousePosition(evt)
* }
*
* This option typically defaults to false for performance reasons:
* when creating an events object whose primary purpose is to manage
* relatively positioned mouse events within a div, it may make
* sense to set it to true.
*
* This option is also used to control whether the events object caches
* offsets. If this is false, it will not: the reason for this is that
* it is only expected to be called many times if the includeXY property
* is set to true. If you set this to true, you are expected to clear
* the offset cache manually (using this.clearMouseCache()) if:
* the border of the element changes
* the location of the element in the page changes
*/
includeXY: false,
/**
* Method: clearMouseListener
* A version of <clearMouseCache> that is bound to this instance so that
* it can be used with <OpenLayers.Event.observe> and
* <OpenLayers.Event.stopObserving>.
*/
clearMouseListener: null,
/**
* Constructor: OpenLayers.Events
* Construct an OpenLayers.Events object.
*
* Parameters:
* object - {Object} The js object to which this Events object is being
* added element - {DOMElement} A dom element to respond to browser events
* eventTypes - {Array(String)} Array of custom application events
* fallThrough - {Boolean} Allow events to fall through after these have
* been handled?
* options - {Object} Options for the events object.
*/
initialize: function (object, element, eventTypes, fallThrough, options) {
OpenLayers.Util.extend(this, options);
this.object = object;
this.fallThrough = fallThrough;
this.listeners = {};
// keep a bound copy of handleBrowserEvent() so that we can
// pass the same function to both Event.observe() and .stopObserving()
this.eventHandler = OpenLayers.Function.bindAsEventListener(
this.handleBrowserEvent, this
);
// to be used with observe and stopObserving
this.clearMouseListener = OpenLayers.Function.bind(
this.clearMouseCache, this
);
// if eventTypes is specified, create a listeners list for each
// custom application event.
this.eventTypes = [];
if (eventTypes != null) {
for (var i=0, len=eventTypes.length; i<len; i++) {
this.addEventType(eventTypes[i]);
}
}
// if a dom element is specified, add a listeners list
// for browser events on the element and register them
if (element != null) {
this.attachToElement(element);
}
},
/**
* APIMethod: destroy
*/
destroy: function () {
if (this.element) {
OpenLayers.Event.stopObservingElement(this.element);
if(this.element.hasScrollEvent) {
OpenLayers.Event.stopObserving(
window, "scroll", this.clearMouseListener
);
}
}
this.element = null;
this.listeners = null;
this.object = null;
this.eventTypes = null;
this.fallThrough = null;
this.eventHandler = null;
},
/**
* APIMethod: addEventType
* Add a new event type to this events object.
* If the event type has already been added, do nothing.
*
* Parameters:
* eventName - {String}
*/
addEventType: function(eventName) {
if (!this.listeners[eventName]) {
this.eventTypes.push(eventName);
this.listeners[eventName] = [];
}
},
/**
* Method: attachToElement
*
* Parameters:
* element - {HTMLDOMElement} a DOM element to attach browser events to
*/
attachToElement: function (element) {
if(this.element) {
OpenLayers.Event.stopObservingElement(this.element);
}
this.element = element;
for (var i=0, len=this.BROWSER_EVENTS.length; i<len; i++) {
var eventType = this.BROWSER_EVENTS[i];
// every browser event has a corresponding application event
// (whether it's listened for or not).
this.addEventType(eventType);
// use Prototype to register the event cross-browser
OpenLayers.Event.observe(element, eventType, this.eventHandler);
}
// disable dragstart in IE so that mousedown/move/up works normally
OpenLayers.Event.observe(element, "dragstart", OpenLayers.Event.stop);
},
/**
* APIMethod: on
* Convenience method for registering listeners with a common scope.
* Internally, this method calls <register> as shown in the examples
* below.
*
* Example use:
* (code)
* // register a single listener for the "loadstart" event
* events.on({"loadstart", loadStartListener});
*
* // this is equivalent to the following
* events.register("loadstart", undefined, loadStartListener);
*
* // register multiple listeners to be called with the same `this` object
* events.on({
* "loadstart": loadStartListener,
* "loadend": loadEndListener,
* scope: object
* });
*
* // this is equivalent to the following
* events.register("loadstart", object, loadStartListener);
* events.register("loadstart", object, loadEndListener);
* (end)
*/
on: function(object) {
for(var type in object) {
if(type != "scope") {
this.register(type, object.scope, object[type]);
}
}
},
/**
* APIMethod: register
* Register an event on the events object.
*
* When the event is triggered, the 'func' function will be called, in the
* context of 'obj'. Imagine we were to register an event, specifying an
* OpenLayers.Bounds Object as 'obj'. When the event is triggered, the
* context in the callback function will be our Bounds object. This means
* that within our callback function, we can access the properties and
* methods of the Bounds object through the "this" variable. So our
* callback could execute something like:
* : leftStr = "Left: " + this.left;
*
* or
*
* : centerStr = "Center: " + this.getCenterLonLat();
*
* Parameters:
* type - {String} Name of the event to register
* obj - {Object} The object to bind the context to for the callback#.
* If no object is specified, default is the Events's
* 'object' property.
* func - {Function} The callback function. If no callback is
* specified, this function does nothing.
*
*
*/
register: function (type, obj, func) {
if ( (func != null) &&
(OpenLayers.Util.indexOf(this.eventTypes, type) != -1) ) {
if (obj == null) {
obj = this.object;
}
var listeners = this.listeners[type];
listeners.push( {obj: obj, func: func} );
}
},
/**
* APIMethod: registerPriority
* Same as register() but adds the new listener to the *front* of the
* events queue instead of to the end.
*
* TODO: get rid of this in 3.0 - Decide whether listeners should be
* called in the order they were registered or in reverse order.
*
*
* Parameters:
* type - {String} Name of the event to register
* obj - {Object} The object to bind the context to for the callback#.
* If no object is specified, default is the Events's
* 'object' property.
* func - {Function} The callback function. If no callback is
* specified, this function does nothing.
*/
registerPriority: function (type, obj, func) {
if (func != null) {
if (obj == null) {
obj = this.object;
}
var listeners = this.listeners[type];
if (listeners != null) {
listeners.unshift( {obj: obj, func: func} );
}
}
},
/**
* APIMethod: un
* Convenience method for unregistering listeners with a common scope.
* Internally, this method calls <unregister> as shown in the examples
* below.
*
* Example use:
* (code)
* // unregister a single listener for the "loadstart" event
* events.un({"loadstart", loadStartListener});
*
* // this is equivalent to the following
* events.unregister("loadstart", undefined, loadStartListener);
*
* // unregister multiple listeners with the same `this` object
* events.un({
* "loadstart": loadStartListener,
* "loadend": loadEndListener,
* scope: object
* });
*
* // this is equivalent to the following
* events.unregister("loadstart", object, loadStartListener);
* events.unregister("loadstart", object, loadEndListener);
* (end)
*/
un: function(object) {
for(var type in object) {
if(type != "scope") {
this.unregister(type, object.scope, object[type]);
}
}
},
/**
* APIMethod: unregister
*
* Parameters:
* type - {String}
* obj - {Object} If none specified, defaults to this.object
* func - {Function}
*/
unregister: function (type, obj, func) {
if (obj == null) {
obj = this.object;
}
var listeners = this.listeners[type];
if (listeners != null) {
for (var i=0, len=listeners.length; i<len; i++) {
if (listeners[i].obj == obj && listeners[i].func == func) {
listeners.splice(i, 1);
break;
}
}
}
},
/**
* Method: remove
* Remove all listeners for a given event type. If type is not registered,
* does nothing.
*
* Parameters:
* type - {String}
*/
remove: function(type) {
if (this.listeners[type] != null) {
this.listeners[type] = [];
}
},
/**
* APIMethod: triggerEvent
* Trigger a specified registered event.
*
* Parameters:
* type - {String}
* evt - {Event}
*
* Returns:
* {Boolean} The last listener return. If a listener returns false, the
* chain of listeners will stop getting called.
*/
triggerEvent: function (type, evt) {
var listeners = this.listeners[type];
// fast path
if(!listeners || listeners.length == 0) {
return;
}
// prep evt object with object & div references
if (evt == null) {
evt = {};
}
evt.object = this.object;
evt.element = this.element;
if(!evt.type) {
evt.type = type;
}
// execute all callbacks registered for specified type
// get a clone of the listeners array to
// allow for splicing during callbacks
var listeners = listeners.slice(), continueChain;
for (var i=0, len=listeners.length; i<len; i++) {
var callback = listeners[i];
// bind the context to callback.obj
continueChain = callback.func.apply(callback.obj, [evt]);
if ((continueChain != undefined) && (continueChain == false)) {
// if callback returns false, execute no more callbacks.
break;
}
}
// don't fall through to other DOM elements
if (!this.fallThrough) {
OpenLayers.Event.stop(evt, true);
}
return continueChain;
},
/**
* Method: handleBrowserEvent
* Basically just a wrapper to the triggerEvent() function, but takes
* care to set a property 'xy' on the event with the current mouse
* position.
*
* Parameters:
* evt - {Event}
*/
handleBrowserEvent: function (evt) {
if (this.includeXY) {
evt.xy = this.getMousePosition(evt);
}
this.triggerEvent(evt.type, evt);
},
/**
* APIMethod: clearMouseCache
* Clear cached data about the mouse position. This should be called any
* time the element that events are registered on changes position
* within the page.
*/
clearMouseCache: function() {
this.element.scrolls = null;
this.element.lefttop = null;
this.element.offsets = null;
},
/**
* Method: getMousePosition
*
* Parameters:
* evt - {Event}
*
* Returns:
* {<OpenLayers.Pixel>} The current xy coordinate of the mouse, adjusted
* for offsets
*/
getMousePosition: function (evt) {
if (!this.includeXY) {
this.clearMouseCache();
} else if (!this.element.hasScrollEvent) {
OpenLayers.Event.observe(window, "scroll", this.clearMouseListener);
this.element.hasScrollEvent = true;
}
if (!this.element.scrolls) {
this.element.scrolls = [
(document.documentElement.scrollLeft
|| document.body.scrollLeft),
(document.documentElement.scrollTop
|| document.body.scrollTop)
];
}
if (!this.element.lefttop) {
this.element.lefttop = [
(document.documentElement.clientLeft || 0),
(document.documentElement.clientTop || 0)
];
}
if (!this.element.offsets) {
this.element.offsets = OpenLayers.Util.pagePosition(this.element);
this.element.offsets[0] += this.element.scrolls[0];
this.element.offsets[1] += this.element.scrolls[1];
}
return new OpenLayers.Pixel(
(evt.clientX + this.element.scrolls[0]) - this.element.offsets[0]
- this.element.lefttop[0],
(evt.clientY + this.element.scrolls[1]) - this.element.offsets[1]
- this.element.lefttop[1]
);
},
CLASS_NAME: "OpenLayers.Events"
});
| guolivar/totus-niwa | web/js/libs/openlayers/lib/OpenLayers/Events.js | JavaScript | gpl-3.0 | 26,459 |
/**
* UI/Components/PetInformations/PetInformations.js
*
* Display pet informations
*
* This file is part of ROBrowser, Ragnarok Online in the Web Browser (http://www.robrowser.com/).
*
* @author Vincent Thibault
*/
define(function(require)
{
'use strict';
/**
* Dependencies
*/
var DB = require('DB/DBManager');
var Client = require('Core/Client');
var Preferences = require('Core/Preferences');
var Renderer = require('Renderer/Renderer');
var UIManager = require('UI/UIManager');
var UIComponent = require('UI/UIComponent');
var htmlText = require('text!./PetInformations.html');
var cssText = require('text!./PetInformations.css');
/**
* Create Component
*/
var PetInformations = new UIComponent( 'PetInformations', htmlText, cssText );
/**
* @var {Preferences} Window preferences
*/
var _preferences = Preferences.get('PetInformations', {
x: 100,
y: 200,
show: true,
}, 1.0);
/**
* Initialize component
*/
PetInformations.init = function init()
{
this.draggable(this.ui.find('.titlebar'));
this.ui.find('.base').mousedown(stopPropagation);
this.ui.find('.close').click(onClose);
this.ui.find('.modify').click(onChangeName);
this.ui.find('.command').change(onCommandSelected);
if (!_preferences.show) {
this.ui.hide();
}
this.ui.css({
top: Math.min( Math.max( 0, _preferences.y), Renderer.height - this.ui.height()),
left: Math.min( Math.max( 0, _preferences.x), Renderer.width - this.ui.width())
});
};
/**
* Once remove from body, save user preferences
*/
PetInformations.onRemove = function onRemove()
{
// Save preferences
_preferences.show = this.ui.is(':visible');
_preferences.y = parseInt(this.ui.css('top'), 10);
_preferences.x = parseInt(this.ui.css('left'), 10);
_preferences.save();
};
/**
* Process shortcut
*
* @param {object} key
*/
PetInformations.onShortCut = function onShortCut( key )
{
// Not in body
if (!this.ui) {
return;
}
switch (key.cmd) {
case 'TOGGLE':
this.ui.toggle();
if (this.ui.is(':visible')) {
this.focus();
}
break;
}
};
/**
* Update UI
*
* @param {object} pet info
*/
PetInformations.setInformations = function setInformations(info)
{
this.ui.find('.name').val(info.szName);
this.ui.find('.level').text(info.nLevel);
this.setHunger(info.nFullness);
this.setIntimacy(info.nRelationship);
this.ui.find('.accessory').text(DB.getMessage(info.ITID ? 598 : 600));
Client.loadFile( DB.getPetIllustPath(info.job), function(data){
this.ui.find('.content').css('backgroundImage', 'url('+ data +')');
}.bind(this));
if (!info.bModified) {
this.ui.find('.name, .modify').removeClass('disabled').attr('disabled', false);
}
else {
this.ui.find('.name, .modify').addClass('disabled').attr('disabled', true);
}
};
/**
* Set intimacy
*
* @param {number} intimacy
*/
PetInformations.setIntimacy = function setIntimacy(val)
{
this.ui.find('.intimacy').text(DB.getMessage(
val < 100 ? 672 :
val < 250 ? 673 :
val < 600 ? 669 :
val < 900 ? 674 :
675
));
};
/**
* Set hunger value
*
* @param {number} hunger
*/
PetInformations.setHunger = function setHunger(val)
{
this.ui.find('.hunger').text(DB.getMessage(
val < 10 ? 667 :
val < 25 ? 668 :
val < 75 ? 669 :
val < 90 ? 670 :
671
));
};
/**
* User just execute a command
*/
function onCommandSelected()
{
switch (this.value) {
case 'feed':
PetInformations.reqPetFeed();
break;
case 'action':
PetInformations.reqPetAction();
break;
case 'release':
PetInformations.reqBackToEgg();
break;
case 'unequip':
PetInformations.reqUnEquipPet();
break;
default:
}
this.value = 'default';
}
/**
* Request to modify pet's name
*/
function onChangeName()
{
var input = PetInformations.ui.find('.name');
PetInformations.reqNameEdit( input.val() );
}
/**
* Closing window
*/
function onClose()
{
PetInformations.ui.hide();
}
/**
* Stop event propagation
*/
function stopPropagation( event )
{
event.stopImmediatePropagation();
return false;
}
/**
* Functions defined in Engine/MapEngine/Pet.js
*/
PetInformations.reqPetFeed = function reqPetFeed(){};
PetInformations.reqPetAction = function reqPetAction(){};
PetInformations.reqNameEdit = function reqNameEdit(){};
PetInformations.reqUnEquipPet = function reqUnEquipPet(){};
PetInformations.reqBackToEgg = function reqBackToEgg(){};
/**
* Create component and export it
*/
return UIManager.addComponent(PetInformations);
}); | kontownik/roBrowser | src/UI/Components/PetInformations/PetInformations.js | JavaScript | gpl-3.0 | 4,771 |
import { OpaqueToken } from '@angular/core';
import { isArray, isBlank, isPresent } from '../util/util';
/**
* @hidden
*/
var UrlSerializer = (function () {
/**
* @param {?} _app
* @param {?} config
*/
function UrlSerializer(_app, config) {
this._app = _app;
if (config && isArray(config.links)) {
this.links = normalizeLinks(config.links);
}
else {
this.links = [];
}
}
/**
* Parse the URL into a Path, which is made up of multiple NavSegments.
* Match which components belong to each segment.
* @param {?} browserUrl
* @return {?}
*/
UrlSerializer.prototype.parse = function (browserUrl) {
if (browserUrl.charAt(0) === '/') {
browserUrl = browserUrl.substr(1);
}
// trim off data after ? and #
browserUrl = browserUrl.split('?')[0].split('#')[0];
return convertUrlToSegments(this._app, browserUrl, this.links);
};
/**
* @param {?} navContainer
* @param {?} nameOrComponent
* @return {?}
*/
UrlSerializer.prototype.createSegmentFromName = function (navContainer, nameOrComponent) {
var /** @type {?} */ configLink = this.getLinkFromName(nameOrComponent);
if (configLink) {
return this._createSegment(this._app, navContainer, configLink, null);
}
return null;
};
/**
* @param {?} nameOrComponent
* @return {?}
*/
UrlSerializer.prototype.getLinkFromName = function (nameOrComponent) {
return this.links.find(function (link) {
return (link.component === nameOrComponent) ||
(link.name === nameOrComponent);
});
};
/**
* Serialize a path, which is made up of multiple NavSegments,
* into a URL string. Turn each segment into a string and concat them to a URL.
* @param {?} segments
* @return {?}
*/
UrlSerializer.prototype.serialize = function (segments) {
if (!segments || !segments.length) {
return '/';
}
var /** @type {?} */ sections = segments.map(function (segment) {
if (segment.type === 'tabs') {
if (segment.requiresExplicitNavPrefix) {
return "/" + segment.type + "/" + segment.navId + "/" + segment.secondaryId + "/" + segment.id;
}
return "/" + segment.secondaryId + "/" + segment.id;
}
// it's a nav
if (segment.requiresExplicitNavPrefix) {
return "/" + segment.type + "/" + segment.navId + "/" + segment.id;
}
return "/" + segment.id;
});
return sections.join('');
};
/**
* Serializes a component and its data into a NavSegment.
* @param {?} navContainer
* @param {?} component
* @param {?} data
* @return {?}
*/
UrlSerializer.prototype.serializeComponent = function (navContainer, component, data) {
if (component) {
var /** @type {?} */ link = findLinkByComponentData(this.links, component, data);
if (link) {
return this._createSegment(this._app, navContainer, link, data);
}
}
return null;
};
/**
* \@internal
* @param {?} app
* @param {?} navContainer
* @param {?} configLink
* @param {?} data
* @return {?}
*/
UrlSerializer.prototype._createSegment = function (app, navContainer, configLink, data) {
var /** @type {?} */ urlParts = configLink.segmentParts;
if (isPresent(data)) {
// create a copy of the original parts in the link config
urlParts = urlParts.slice();
// loop through all the data and convert it to a string
var /** @type {?} */ keys = Object.keys(data);
var /** @type {?} */ keysLength = keys.length;
if (keysLength) {
for (var /** @type {?} */ i = 0; i < urlParts.length; i++) {
if (urlParts[i].charAt(0) === ':') {
for (var /** @type {?} */ j = 0; j < keysLength; j++) {
if (urlParts[i] === ":" + keys[j]) {
// this data goes into the URL part (between slashes)
urlParts[i] = encodeURIComponent(data[keys[j]]);
break;
}
}
}
}
}
}
var /** @type {?} */ requiresExplicitPrefix = true;
if (navContainer.parent) {
requiresExplicitPrefix = navContainer.parent && navContainer.parent.getAllChildNavs().length > 1;
}
else {
// if it's a root nav, and there are multiple root navs, we need an explicit prefix
requiresExplicitPrefix = app.getRootNavById(navContainer.id) && app.getRootNavs().length > 1;
}
return {
id: urlParts.join('/'),
name: configLink.name,
component: configLink.component,
loadChildren: configLink.loadChildren,
data: data,
defaultHistory: configLink.defaultHistory,
navId: navContainer.name || navContainer.id,
type: navContainer.getType(),
secondaryId: navContainer.getSecondaryIdentifier(),
requiresExplicitNavPrefix: requiresExplicitPrefix
};
};
return UrlSerializer;
}());
export { UrlSerializer };
function UrlSerializer_tsickle_Closure_declarations() {
/** @type {?} */
UrlSerializer.prototype.links;
/** @type {?} */
UrlSerializer.prototype._app;
}
/**
* @param {?} name
* @return {?}
*/
export function formatUrlPart(name) {
name = name.replace(URL_REPLACE_REG, '-');
name = name.charAt(0).toLowerCase() + name.substring(1).replace(/[A-Z]/g, function (match) {
return '-' + match.toLowerCase();
});
while (name.indexOf('--') > -1) {
name = name.replace('--', '-');
}
if (name.charAt(0) === '-') {
name = name.substring(1);
}
if (name.substring(name.length - 1) === '-') {
name = name.substring(0, name.length - 1);
}
return encodeURIComponent(name);
}
export var /** @type {?} */ isPartMatch = function (urlPart, configLinkPart) {
if (isPresent(urlPart) && isPresent(configLinkPart)) {
if (configLinkPart.charAt(0) === ':') {
return true;
}
return (urlPart === configLinkPart);
}
return false;
};
export var /** @type {?} */ createMatchedData = function (matchedUrlParts, link) {
var /** @type {?} */ data = null;
for (var /** @type {?} */ i = 0; i < link.segmentPartsLen; i++) {
if (link.segmentParts[i].charAt(0) === ':') {
data = data || {};
data[link.segmentParts[i].substring(1)] = decodeURIComponent(matchedUrlParts[i]);
}
}
return data;
};
export var /** @type {?} */ findLinkByComponentData = function (links, component, instanceData) {
var /** @type {?} */ foundLink = null;
var /** @type {?} */ foundLinkDataMatches = -1;
for (var /** @type {?} */ i = 0; i < links.length; i++) {
var /** @type {?} */ link = links[i];
if (link.component === component) {
// ok, so the component matched, but multiple links can point
// to the same component, so let's make sure this is the right link
var /** @type {?} */ dataMatches = 0;
if (instanceData) {
var /** @type {?} */ instanceDataKeys = Object.keys(instanceData);
// this link has data
for (var /** @type {?} */ j = 0; j < instanceDataKeys.length; j++) {
if (isPresent(link.dataKeys[instanceDataKeys[j]])) {
dataMatches++;
}
}
}
else if (link.dataLen) {
// this component does not have data but the link does
continue;
}
if (dataMatches >= foundLinkDataMatches) {
foundLink = link;
foundLinkDataMatches = dataMatches;
}
}
}
return foundLink;
};
export var /** @type {?} */ normalizeLinks = function (links) {
for (var /** @type {?} */ i = 0, /** @type {?} */ ilen = links.length; i < ilen; i++) {
var /** @type {?} */ link = links[i];
if (isBlank(link.segment)) {
link.segment = link.name;
}
link.dataKeys = {};
link.segmentParts = link.segment.split('/');
link.segmentPartsLen = link.segmentParts.length;
// used for sorting
link.staticLen = link.dataLen = 0;
var /** @type {?} */ stillCountingStatic = true;
for (var /** @type {?} */ j = 0; j < link.segmentPartsLen; j++) {
if (link.segmentParts[j].charAt(0) === ':') {
link.dataLen++;
stillCountingStatic = false;
link.dataKeys[link.segmentParts[j].substring(1)] = true;
}
else if (stillCountingStatic) {
link.staticLen++;
}
}
}
// sort by the number of parts, with the links
// with the most parts first
return links.sort(sortConfigLinks);
};
/**
* @param {?} a
* @param {?} b
* @return {?}
*/
function sortConfigLinks(a, b) {
// sort by the number of parts
if (a.segmentPartsLen > b.segmentPartsLen) {
return -1;
}
if (a.segmentPartsLen < b.segmentPartsLen) {
return 1;
}
// sort by the number of static parts in a row
if (a.staticLen > b.staticLen) {
return -1;
}
if (a.staticLen < b.staticLen) {
return 1;
}
// sort by the number of total data parts
if (a.dataLen < b.dataLen) {
return -1;
}
if (a.dataLen > b.dataLen) {
return 1;
}
return 0;
}
var /** @type {?} */ URL_REPLACE_REG = /\s+|\?|\!|\$|\,|\.|\+|\"|\'|\*|\^|\||\/|\\|\[|\]|#|%|`|>|<|;|:|@|&|=/g;
/**
* @hidden
*/
export var DeepLinkConfigToken = new OpaqueToken('USERLINKS');
/**
* @param {?} app
* @param {?} userDeepLinkConfig
* @return {?}
*/
export function setupUrlSerializer(app, userDeepLinkConfig) {
return new UrlSerializer(app, userDeepLinkConfig);
}
/**
* @param {?} navGroupStrings
* @return {?}
*/
export function navGroupStringtoObjects(navGroupStrings) {
// each string has a known format-ish, convert it to it
return navGroupStrings.map(function (navGroupString) {
var /** @type {?} */ sections = navGroupString.split('/');
if (sections[0] === 'nav') {
return {
type: 'nav',
navId: sections[1],
niceId: sections[1],
secondaryId: null,
segmentPieces: sections.splice(2)
};
}
else if (sections[0] === 'tabs') {
return {
type: 'tabs',
navId: sections[1],
niceId: sections[1],
secondaryId: sections[2],
segmentPieces: sections.splice(3)
};
}
return {
type: null,
navId: null,
niceId: null,
secondaryId: null,
segmentPieces: sections
};
});
}
/**
* @param {?} url
* @return {?}
*/
export function urlToNavGroupStrings(url) {
var /** @type {?} */ tokens = url.split('/');
var /** @type {?} */ keywordIndexes = [];
for (var /** @type {?} */ i = 0; i < tokens.length; i++) {
if (i !== 0 && (tokens[i] === 'nav' || tokens[i] === 'tabs')) {
keywordIndexes.push(i);
}
}
// append the last index + 1 to the list no matter what
keywordIndexes.push(tokens.length);
var /** @type {?} */ groupings = [];
var /** @type {?} */ activeKeywordIndex = 0;
var /** @type {?} */ tmpArray = [];
for (var /** @type {?} */ i = 0; i < tokens.length; i++) {
if (i >= keywordIndexes[activeKeywordIndex]) {
groupings.push(tmpArray.join('/'));
tmpArray = [];
activeKeywordIndex++;
}
tmpArray.push(tokens[i]);
}
// okay, after the loop we've gotta push one more time just to be safe
groupings.push(tmpArray.join('/'));
return groupings;
}
/**
* @param {?} app
* @param {?} url
* @param {?} navLinks
* @return {?}
*/
export function convertUrlToSegments(app, url, navLinks) {
var /** @type {?} */ pairs = convertUrlToDehydratedSegments(url, navLinks);
return hydrateSegmentsWithNav(app, pairs);
}
/**
* @param {?} url
* @param {?} navLinks
* @return {?}
*/
export function convertUrlToDehydratedSegments(url, navLinks) {
var /** @type {?} */ navGroupStrings = urlToNavGroupStrings(url);
var /** @type {?} */ navGroups = navGroupStringtoObjects(navGroupStrings);
return getSegmentsFromNavGroups(navGroups, navLinks);
}
/**
* @param {?} app
* @param {?} dehydratedSegmentPairs
* @return {?}
*/
export function hydrateSegmentsWithNav(app, dehydratedSegmentPairs) {
var /** @type {?} */ segments = [];
for (var /** @type {?} */ i = 0; i < dehydratedSegmentPairs.length; i++) {
var /** @type {?} */ navs = getNavFromNavGroup(dehydratedSegmentPairs[i].navGroup, app);
// okay, cool, let's walk through the segments and hydrate them
for (var _i = 0, _a = dehydratedSegmentPairs[i].segments; _i < _a.length; _i++) {
var dehydratedSegment = _a[_i];
if (navs.length === 1) {
segments.push(hydrateSegment(dehydratedSegment, navs[0]));
navs = navs[0].getActiveChildNavs();
}
else if (navs.length > 1) {
// this is almost certainly an async race condition bug in userland
// if you're in this state, it would be nice to just bail here
// but alas we must perservere and handle the issue
// the simple solution is to just use the last child
// because that is probably what the user wants anyway
// remember, do not harm, even if it makes our shizzle ugly
segments.push(hydrateSegment(dehydratedSegment, navs[navs.length - 1]));
navs = navs[navs.length - 1].getActiveChildNavs();
}
else {
break;
}
}
}
return segments;
}
/**
* @param {?} navGroup
* @param {?} app
* @return {?}
*/
export function getNavFromNavGroup(navGroup, app) {
if (navGroup.navId) {
var /** @type {?} */ rootNav = app.getNavByIdOrName(navGroup.navId);
if (rootNav) {
return [rootNav];
}
return [];
}
// we don't know what nav to use, so just use the root nav.
// if there is more than one root nav, throw an error
return app.getRootNavs();
}
/**
* @param {?} navGroups
* @param {?} navLinks
* @return {?}
*/
export function getSegmentsFromNavGroups(navGroups, navLinks) {
var /** @type {?} */ pairs = [];
var /** @type {?} */ usedNavLinks = new Set();
for (var _i = 0, navGroups_1 = navGroups; _i < navGroups_1.length; _i++) {
var navGroup = navGroups_1[_i];
var /** @type {?} */ segments = [];
var /** @type {?} */ segmentPieces = navGroup.segmentPieces.concat([]);
for (var /** @type {?} */ i = segmentPieces.length; i >= 0; i--) {
var /** @type {?} */ created = false;
for (var /** @type {?} */ j = 0; j < i; j++) {
var /** @type {?} */ startIndex = i - j - 1;
var /** @type {?} */ endIndex = i;
var /** @type {?} */ subsetOfUrl = segmentPieces.slice(startIndex, endIndex);
for (var _a = 0, navLinks_1 = navLinks; _a < navLinks_1.length; _a++) {
var navLink = navLinks_1[_a];
if (!usedNavLinks.has(navLink.name)) {
var /** @type {?} */ segment = getSegmentsFromUrlPieces(subsetOfUrl, navLink);
if (segment) {
i = startIndex + 1;
usedNavLinks.add(navLink.name);
created = true;
// sweet, we found a segment
segments.push(segment);
// now we want to null out the url subsection in the segmentPieces
for (var /** @type {?} */ k = startIndex; k < endIndex; k++) {
segmentPieces[k] = null;
}
break;
}
}
}
if (created) {
break;
}
}
if (!created && segmentPieces[i - 1]) {
// this is very likely a tab's secondary identifier
segments.push({
id: null,
name: null,
secondaryId: segmentPieces[i - 1],
component: null,
loadChildren: null,
data: null,
defaultHistory: null
});
}
}
// since we're getting segments in from right-to-left in the url, reverse them
// so they're in the correct order. Also filter out and bogus segments
var /** @type {?} */ orderedSegments = segments.reverse();
// okay, this is the lazy persons approach here.
// so here's the deal! Right now if section of the url is not a part of a segment
// it is almost certainly the secondaryId for a tabs component
// basically, knowing the segment for the `tab` itself is good, but we also need to know
// which tab is selected, so we have an identifer in the url that is associated with the tabs component
// telling us which tab is selected. With that in mind, we are going to go through and find the segments with only secondary identifiers,
// and simply add the secondaryId to the next segment, and then remove the empty segment from the list
for (var /** @type {?} */ i = 0; i < orderedSegments.length; i++) {
if (orderedSegments[i].secondaryId && !orderedSegments[i].id && ((i + 1) <= orderedSegments.length - 1)) {
orderedSegments[i + 1].secondaryId = orderedSegments[i].secondaryId;
orderedSegments[i] = null;
}
}
var /** @type {?} */ cleanedSegments = segments.filter(function (segment) { return !!segment; });
// if the nav group has a secondary id, make sure the first segment also has it set
if (navGroup.secondaryId && segments.length) {
cleanedSegments[0].secondaryId = navGroup.secondaryId;
}
pairs.push({
navGroup: navGroup,
segments: cleanedSegments
});
}
return pairs;
}
/**
* @param {?} urlSections
* @param {?} navLink
* @return {?}
*/
export function getSegmentsFromUrlPieces(urlSections, navLink) {
if (navLink.segmentPartsLen !== urlSections.length) {
return null;
}
for (var /** @type {?} */ i = 0; i < urlSections.length; i++) {
if (!isPartMatch(urlSections[i], navLink.segmentParts[i])) {
// just return an empty array if the part doesn't match
return null;
}
}
return {
id: urlSections.join('/'),
name: navLink.name,
component: navLink.component,
loadChildren: navLink.loadChildren,
data: createMatchedData(urlSections, navLink),
defaultHistory: navLink.defaultHistory
};
}
/**
* @param {?} segment
* @param {?} nav
* @return {?}
*/
export function hydrateSegment(segment, nav) {
var /** @type {?} */ hydratedSegment = (Object.assign({}, segment));
hydratedSegment.type = nav.getType();
hydratedSegment.navId = nav.name || nav.id;
// secondaryId is set on an empty dehydrated segment in the case of tabs to identify which tab is selected
hydratedSegment.secondaryId = segment.secondaryId;
return hydratedSegment;
}
/**
* @param {?} urlChunks
* @param {?} navLink
* @return {?}
*/
export function getNonHydratedSegmentIfLinkAndUrlMatch(urlChunks, navLink) {
var /** @type {?} */ allSegmentsMatch = true;
for (var /** @type {?} */ i = 0; i < urlChunks.length; i++) {
if (!isPartMatch(urlChunks[i], navLink.segmentParts[i])) {
allSegmentsMatch = false;
break;
}
}
if (allSegmentsMatch) {
return {
id: navLink.segmentParts.join('/'),
name: navLink.name,
component: navLink.component,
loadChildren: navLink.loadChildren,
data: createMatchedData(urlChunks, navLink),
defaultHistory: navLink.defaultHistory
};
}
return null;
}
//# sourceMappingURL=url-serializer.js.map | raisinbit/RaisinLearning | node_modules/ionic-angular/navigation/url-serializer.js | JavaScript | gpl-3.0 | 21,150 |
var attribution = new ol.Attribution({
html: 'Copyright:© 2013 ESRI, i-cubed, GeoEye'
});
var projection = ol.proj.get('EPSG:4326');
var projectionExtent = projection.getExtent();
// The tile size supported by the ArcGIS tile service.
var tileSize = 512;
// Calculate the resolutions supported by the ArcGIS tile service.
// There are 16 resolutions, with a factor of 2 between successive
// resolutions. The max resolution is such that the world (360°)
// fits into two (512x512 px) tiles.
var maxResolution = ol.extent.getWidth(projectionExtent) / (tileSize * 2);
var resolutions = new Array(16);
var z;
for (z = 0; z < 16; ++z) {
resolutions[z] = maxResolution / Math.pow(2, z);
}
var urlTemplate = 'http://services.arcgisonline.com/arcgis/rest/services/' +
'ESRI_Imagery_World_2D/MapServer/tile/{z}/{y}/{x}';
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
/* ol.source.XYZ and ol.tilegrid.XYZ have no resolutions config */
source: new ol.source.TileImage({
attributions: [attribution],
tileUrlFunction: function(tileCoord, pixelRatio, projection) {
var z = tileCoord[0];
var x = tileCoord[1];
var y = -tileCoord[2] - 1;
// wrap the world on the X axis
var n = Math.pow(2, z + 1); // 2 tiles at z=0
x = x % n;
if (x * n < 0) {
// x and n differ in sign so add n to wrap the result
// to the correct sign
x = x + n;
}
return urlTemplate.replace('{z}', z.toString())
.replace('{y}', y.toString())
.replace('{x}', x.toString());
},
projection: projection,
tileGrid: new ol.tilegrid.TileGrid({
origin: ol.extent.getTopLeft(projectionExtent),
resolutions: resolutions,
tileSize: 512
})
})
})
],
view: new ol.View({
center: [0, 0],
projection: projection,
zoom: 2,
minZoom: 2
})
});
| MilletPu/airvis | src/main/webapp/js/ol3/v3.1.1/examples/xyz-esri-4326-512.js | JavaScript | agpl-3.0 | 2,004 |
/*
* Ze importer.
*
* == Dependencies ==
* * jQuery <http://jquery.com>
* * the jQuery Form Plugin <http://malsup.com/jquery/form/#code-samples>
*
* == The order of things ==
*
* 1. User enters an identifier (username or email address)
* into an input field.
*
* 2. When the user exits the input field, we grab as much
* data as we can about that identifier.
* (In the future.)
* (This code is handled in Preparation below.)
*
* 3. When the user clicks the submit button, we ask the server
* to enqueue background tasks that import data from sources
* 'round the web.
* (This code is handled in Submission below.)
*
* 4. When the server responds, we show some progress bars to
* the user, to let them know we're working behind the
* scenes.
* (This code is also handled in Submission below.)
*
* 5. We ping the server repeatedly, asking
* "How's the import going? Are you done yet?"
*
* 6. On each ping the server responds with a JSONified Python list comprising:
* - the Citations we've found so far
*
*/
if (typeof want_importer == 'undefined') {
/* do nothing. */
} else {
$.fn.hoverClass = function(className) {
// {{{
mouseoverHandler = function() { $(this).addClass(className); };
mouseoutHandler = function() { $(this).removeClass(className); };
return this.hover(mouseoverHandler, mouseoutHandler);
// }}}
};
$.fn.debug = function() {
// {{{
console.debug(this);
return this;
// }}}
};
var lastUniqueNumber = 0;
function generateUniqueID() {
lastUniqueNumber++;
return 'element_'+lastUniqueNumber;
}
makeNewInput = function() {
// {{{
// }}}
};
keydownHandler = function() {
// {{{
$input = $(this);
var oneInputIsBlank = function() {
var ret = false;
$("form input[type='text']").each(function () {
var thisInputIsBlank = (
$(this).val().replace(/\s/g,'') == '' );
if (thisInputIsBlank) ret = true;
});
return ret;
}();
if (!oneInputIsBlank) {
makeNewInput();
bindHandlers();
}
// }}}
};
bindHandlers = function() {
// {{{
$("form .data_source").hoverClass('hover');
// }}}
};
$.fn.setThrobberStatus = function(theStatus) {
// {{{
var $throbber = this;
mapStatusToImage = {
'working': '/static/images/snake.gif',
'succeeded': '/static/images/icons/finished-successfully.png',
'failed': '/static/images/icons/finished-unsuccessfully.png',
}
src = mapStatusToImage[theStatus];
if ($throbber.attr('src') != src) {
$throbber.attr('src', src);
}
// }}}
};
Preparation = {
// {{{
'init': function () {
Preparation.$inputs = $('#importer form input[type="text"]');
Preparation.bindHandler();
},
'$inputs': null,
'handler': function () {
var url = '/people/portfolio/import/prepare_data_import_attempts_do';
var query = $(this).val();
fireunit.ok(typeof query != 'undefined', "query: " + query);
var data = {'format': 'success_code'};
// About the below; the old POST handler used to expect
// a digit instead of "x", but I don't think it will matter.
data['commit_username_x'] = query;
$.post(url, data, Preparation.callback);
},
'bindHandler': function () {
Preparation.$inputs.blur(Preparation.handler);
},
'callback': function (response) {
}
// }}}
};
Submission = {
// {{{
'init': function () {
Submission.$form = $('#importer form');
Submission.bindHandler();
},
'$form': null,
'handler': function () {
$(this).ajaxSubmit({'success': Submission.callback});
return false; // Bypass the form's native Submission logic.
},
'bindHandler': function () {
Submission.$form.submit(Submission.handler);
},
'callback': function (response) {
$('input', Submission.$form).attr('disabled', 'disabled');
}
// }}}
};
init = function () {
makeNewInput(); // Create first blank row of input table.
Preparation.init();
Submission.init();
};
$(init);
$(function() { $('.hide_on_doc_ready').hide(); });
tests = {
'Preparation': function () {
$('form input[type="text"]').val('paulproteus').blur();
fireunit.testDone();
}
};
runTests = function () {
for (t in tests) {
fireunit.ok(true, "test: " + t);
tests[t]();
}
};
mockedPortfolioResponse = null;
askServerForPortfolio_wasCalled = false;
function askServerForPortfolio() {
if (testJS) {
updatePortfolio(mockedPortfolioResponse);
return;
}
var ajaxOptions = {
'type': 'GET',
'url': '/profile/views/gimme_json_for_portfolio',
'dataType': 'json',
'success': updatePortfolio,
'error': errorWhileAskingForPortfolio
};
$.ajax(ajaxOptions);
askServerForPortfolio_wasCalled = true;
}
if (typeof testJS == 'undefined') { testJS = false; }
if (testJS) {
// do nothing
} else {
$(askServerForPortfolio);
}
function errorWhileAskingForPortfolio() {
console.log('Error while asking for portfolio.');
}
$.fn.textSmart = function(text) {
// Only replace text if text is different.
if (this.text() != text) { this.text(text); }
};
$.fn.attrSmart = function(attr, text) {
// Only replace attribute if attribute is different.
if (this.attr(attr) != text) { this.attr(attr, text) };
};
$.fn.htmlSmart = function(html) {
// Only replace html if html is different.
if (this.html() != html) { this.html(html); }
};
/*
* Perhaps we should talk more explicitly with the server about whose portfolio we want.
* Otherwise somebody might do this:
* Log in as Alice
* Load portfolio
* In a different window, log out; log in as Bob
* Return to Alice's portfolio window
* Notice the portfolio are mixed together in an unholy UNION. Yow.
*/
function updatePortfolio(response) {
/* Input: A whole bunch of (decoded) JSON data containing
* all of the user's Citations, PortfolioEntries, and Projects,
* summaries for those Citations,
* Output: Nothing.
* Side-effect: Update the page's DOM to display these data.
* (FIXME: Right now we just add, not "update" :-)
*/
var portfolio_entry_html = $('#portfolio_entry_building_block').html();
var citation_html = $('#citation_building_block').html();
$('#portfolio_entries .loading_message').hide();
/* Now fill in the template */
if (response.portfolio_entries.length === 0) {
$('#portfolio_entries .apologies').show();
}
$('#reorder_projects_wrapper')[(response.portfolio_entries.length > 1) ? "show" : "hide"]();
var are_we_printing_archived_projects_yet = false;
for (var i = 0; i < response.portfolio_entries.length; i++) {
var portfolioEntry = response.portfolio_entries[i];
/* portfolioEntry is something like: {'pk': 0, 'fields': {'project': 0}}
* (a JSONified PortfolioEntry)
*/
var id = 'portfolio_entry_' + portfolioEntry.pk;
$new_portfolio_entry = $('#' + id);
if ($new_portfolio_entry.size() == 0) {
// The HTML must be customized a bit for this portfolio entry so
// that labels know which descriptions to point to.
var html = portfolio_entry_html.replace(/\$PORTFOLIO_ENTRY_ID/g, portfolioEntry.pk);
var $new_portfolio_entry = $(html);
$('#portfolio_entries').append($new_portfolio_entry);
$new_portfolio_entry.attr('id', id);
$new_portfolio_entry.attr('portfolio_entry__pk', portfolioEntry.pk);
}
// if the last one wasn't archived but this one is, add a heading
if (! are_we_printing_archived_projects_yet && portfolioEntry.fields.is_archived) {
var heading = $('#archived_projects_heading');
if (heading.size() == 0) {
heading = $('<h5 id=\'archived_projects_heading\'>Archived projects</h5>');
}
$new_portfolio_entry.before(heading);
are_we_printing_archived_projects_yet = true;
}
// published/unpublished status
if (portfolioEntry.fields.is_published) {
var $actionListItem = $new_portfolio_entry.find('.actions li.publish_portfolio_entry');
var $maybeSpan = $actionListItem.find('span');
$new_portfolio_entry.removeClass("unpublished");
}
/* Find the project this PortfolioElement refers to */
var project_id = portfolioEntry.fields.project;
var project_we_refer_to = null;
$(response.projects).each( function() {
if (this.pk == project_id) {
project_we_refer_to = this;
}
});
/* project_description */
$(".project_description", $new_portfolio_entry).textSmart(portfolioEntry.fields.project_description);
/* receive_maintainer_updates */
$('.receive_maintainer_updates',
$new_portfolio_entry).attr('checked', portfolioEntry.fields.receive_maintainer_updates);
/* project_icon */
if (project_we_refer_to.fields.icon_for_profile == '') {
$new_portfolio_entry.find('.icon_flagger').hide();
}
else {
/* So, the object we select is a DIV whose CSS background-image
* is what causes the browser to display the icon. We store a
* copy of the URL JavaScript gave us in a totally made-up "src"
* attribute of the DIV to make life easier for us.
*/
var $icon = $new_portfolio_entry.find(".project_icon");
var current_src = $icon.attr('src');
var response_src = ("/static/" +
project_we_refer_to.fields.icon_for_profile);
var response_src_for_css = 'url(' + response_src + ')';
if (current_src != response_src) {
$icon.attr('src', response_src); /* just for us */
$icon.css('background-image', response_src_for_css);
$new_portfolio_entry.find('.icon_flagger').show();
}
}
/* project_name */
var $pname = $(".project_name", $new_portfolio_entry);
var $addto = $pname;
var $link = $('a', $pname);
if ($link && $link.length) {
$link.attrSmart('href', '/projects/' + project_we_refer_to.fields.name);
$addto = $link;
}
$addto.textSmart(project_we_refer_to.fields.name);
/* experience_description */
$(".experience_description", $new_portfolio_entry).textSmart(
portfolioEntry.fields.experience_description);
/* Add the appropriate citations to this portfolio entry. */
var addMemberCitations = function() {
var citation = this;
// "this" is an object in response.citations
if ("portfolio_entry_"+citation.fields.portfolio_entry ==
$new_portfolio_entry.attr('id')) {
// Does this exist? If not, then create it.
var id = 'citation_' + citation.pk;
var $citation_existing_or_not = $('#'+id);
var already_exists = ($citation_existing_or_not.size() != 0);
if (already_exists) {
var $citation = $citation_existing_or_not;
} else {
// Then we have a citation that we're gonna add the DOM.
var $citation = $(citation_html);
$citation.attr('id', id);
$('.citations', $new_portfolio_entry).append($citation);
}
// Update the css class of this citation to reflect its
// published/unpublished status.
if (citation.fields.is_published == '1') {
$citation.removeClass("unpublished");
} else {
// Citation is unpublished
$new_portfolio_entry.addClass('unsaved');
}
var summaryHTML = response.summaries[citation.pk]
$summary = $citation.find('.summary');
$summary.htmlSmart(summaryHTML);
}
};
$(response.citations).each(addMemberCitations);
}
if (response['import'].running) {
Importer.ProgressBar.showWithValue(response['import'].progress_percentage);
window.setTimeout(askServerForPortfolio, 1500);
}
else {
// If import's not running, bump to 100.
// If no import was running in the first place, then the progress bar will remain invisible.
// If there had been an import running, then the progress bar, now visible, will
// stand at 100%, to indicate that the import is done.
Importer.ProgressBar.bumpTo100();
}
bindEventHandlers();
SaveAllButton.updateDisplay();
var conditions = PortfolioEntry.Save.stopCheckingForNewIconsWhenWeAllReturnTrue;
var all_are_true = true;
for (var c = 0; c < conditions.length; c++) {
if (!conditions[c](response)) { all_are_true = false; break; }
}
if (!all_are_true) {
window.setTimeout(askServerForPortfolio, 1500);
}
else {
PortfolioEntry.Save.stopCheckingForNewIconsWhenWeAllReturnTrue = [];
}
};
Citation = {};
Citation.$get = function(id) {
var selector = '#citation_'+id;
var matching = $(selector);
return matching;
};
Citation.get = function(id) {
citation = Citation.$get(id).get(0);
return citation;
};
Citation.$getDeleteLink = function(id) {
$link = Citation.$get(id).find('a.delete_citation');
return $link;
};
deleteCitationByID = function(id) {
deleteCitation(Citation.$get(id));
};
deleteCitation = function($citation) {
$citation.addClass('deleted').fadeOut('slow', function () {
$(this).remove();
});
/*removeClass('unpublished')
.removeClass('published')
.addClass('deleted');*/
var pk = $citation[0].id.split('_')[1];
var ajaxOptions = {
'type': 'POST',
'url': '/profile/views/delete_citation_do',
'data': {'citation__pk': pk},
'success': deleteCitationCallback,
'error': deleteCitationErrorCallback,
};
$.ajax(ajaxOptions);
};
deleteCitationCallback = function (response) {
// No need to do anything. We already
// removed the citation element.
};
deleteCitationErrorCallback = function (request) {
Notifier.displayMessage('Whoops! There was an error ' +
'communicating with the server when trying to ' +
'delete a citation. The page may be out of date. ' +
'Please reload. ');
};
drawAddCitationForm = function() {
console.log("draw 'Add a citation' form");
};
Notifier = {};
Notifier.displayMessage = function(message) {
$.jGrowl($('<div/>').text(message).html(), {'life': 5000});
};
/******************
* Event handlers *
******************/
deleteCitationForThisLink = function () {
if (!confirm('are you sure?')) return false;
var deleteLink = this;
var $citation = $(this).closest('.citations > li');
deleteCitation($citation);
return false;
};
drawAddCitationFormNearThisButton = function () {
var button = this;
var $citationForms = $(this).closest('.citations-wrapper').find('ul.citation-forms');
var buildingBlockHTML = $('#citation_form_building_block').html();
var $form_container = $(buildingBlockHTML);
// Set element ID
$form_container.attr('id', generateUniqueID());
if ($citationForms.find('form').length >= 1 ){
return false;
}
$citationForm = $form_container.find('form');
$citationForms.append($form_container);
// console.log($citationForm);
// console.log($citationForm.parents('.portfolio_entry'));
// Set field: portfolio entry ID
var portfolioEntryID = $citationForm.closest('.portfolio_entry')
.attr('portfolio_entry__pk');
$citationForm.find('[name="portfolio_entry"]').attr('lang', 'your-mom');
$citationForm.find('[name="portfolio_entry"]').attr('value', portfolioEntryID);
// console.log('hi');
// console.log($citationForm.find('[name="portfolio_entry"]'));
// Set field: form container element ID
var formContainerElementID = $citationForm.closest('.citation-forms li').attr('id');
$citationForm.find('[name="form_container_element_id"]').val(formContainerElementID);
var ajaxOptions = {
'success': handleServerResponseToNewRecordSubmission,
'error': handleServerErrorInResponseToNewRecordSubmission,
'dataType': 'json'
};
$citationForm.submit(function() {
$(this).ajaxSubmit(ajaxOptions);
$(this).find('input').attr('disabled','disabled');
return false;});
return false; // FIXME: Test this.
}
handleServerResponseToNewRecordSubmission = function(response) {
askServerForPortfolio();
$form_container = $('#'+response.form_container_element_id);
$form_container.remove();
};
handleServerErrorInResponseToNewRecordSubmission = function(xhr) {
responseObj = $.secureEvalJSON(xhr.responseText);
var msg = 'There was at least one problem submitting your citation: <ul>';
for (var i = 0; i < responseObj.error_msgs.length; i++) {
msg += "<li class='error-message'>"
+ responseObj.error_msgs[i]
+ "</li>";
}
msg += "</ul>";
$citationFormContainer = $('#'+responseObj.form_container_element_id);
$citationFormContainer.find('input').removeAttr('disabled');
// FIXME: XSS vulnerability? This will work:
// msg += "<script>alert('injection');</script>";
Notifier.displayMessage(msg);
};
FlagIcon = {};
FlagIcon.postOptions = {
'url': '/profile/views/replace_icon_with_default',
'type': 'POST',
'dataType': 'json',
};
FlagIcon.postOptions.success = function (response) {
$portfolioEntry = $('#portfolio_entry_'+response['portfolio_entry__pk']);
var defaultIconCssAttr = $('#portfolio_entry_building_block .project_icon').css('background-image');
var defaultIconUrl = defaultIconCssAttr.replace(/^url[(]/, '').replace(/[)]$/, ''); /* remove url() */
var relative_path = defaultIconUrl.replace(/^.*?:[/][/].*?[/]/, '/'); /* remove http://domain or https://domain */
// we change the image url as the icon div understands it twice
// this is a hack that allows us to change fewer tests (the icon used to be an img)
$portfolioEntry.find('.project_icon').attr('src', relative_path);
$portfolioEntry.find('.project_icon').css('background-image', defaultIconCssAttr);
// the text() function will remove all children, including the link.
$portfolioEntry.find('.icon_flagger').text('Using default icon.');
};
FlagIcon.postOptions.error = function (response) {
alert('error');
};
FlagIcon.post = function () {
if (!confirm("Flag icon as incorrect: This will remove the icon - are you sure?"))
{ return false; }
$.ajax(FlagIcon.postOptions);
};
FlagIcon.flag = function () {
var $flaggerLink = $(this);
FlagIcon.postOptions.data = {
'csrfmiddlewaretoken': $.cookie('csrftoken'),
'portfolio_entry__pk': $flaggerLink.closest('.portfolio_entry')
.attr('portfolio_entry__pk')
};
FlagIcon.post();
return false;
};
FlagIcon.bindEventHandlers = function() {
$('.icon_flagger a').click(FlagIcon.flag);
};
// Despite the name, this is actually the Importer
// FIXME: Rename this "Importer"
HowTo = {
'init': function () {
HowTo.$element = $('#portfolio_entries .howto');
HowTo.$hideLink = $('#portfolio_entries .howto .hide-link');
HowTo.$showLink = $('#portfolio_entries .show-howto-link');
var tests = ["HowTo.$element.size() == 1",
"HowTo.$hideLink.size() == 1",
"HowTo.$showLink.size() == 1"];
for (var i = 0; i < tests.length; i++) {
// fireunit.ok(eval(tests[i]), tests[i]);
}
for (var e in HowTo.events) {
HowTo.events[e].bind();
}
},
'$element': null,
'$hideLink': null,
'$showLink': null,
'events': {
'hide': {
'go': function () {
HowTo.$element.fadeOut('slow');
HowTo.$showLink.fadeIn('slow');
return false;
},
'bind': function () {
HowTo.$hideLink.click(HowTo.events.hide.go);
},
},
'show': {
'go': function () {
HowTo.$element.fadeIn('slow');
return false;
},
'bind': function () {
HowTo.$showLink.click(HowTo.events.show.go);
},
}
}
};
$(HowTo.init);
PortfolioEntry = {};
PortfolioEntry.bindEventHandlers = function() {
PortfolioEntry.Save.bindEventHandlers();
PortfolioEntry.Delete.bindEventHandlers();
$('#portfolio_entries .portfolio_entry textarea').keydown(pfEntryFieldKeydownHandler);
$('#portfolio_entries .portfolio_entry input').change(pfEntryFieldKeydownHandler);
};
pfEntryFieldKeydownHandler = function () {
var $textarea = $(this);
$textarea.closest('.portfolio_entry').not('.unpublished, .unsaved').addClass('unsaved');
SaveAllButton.updateDisplay();
};
pfCheckboxChangeHandler = function () {
var $checkbox = $(this);
$checkbox.closest('.portfolio_entry').not('.unpublished, .unsaved').addClass('unsaved');
SaveAllButton.updateDisplay();
};
PortfolioEntry.Save = {};
PortfolioEntry.Save.postOptions = {
'url': '/profile/views/save_portfolio_entry_do',
'type': 'POST',
'dataType': 'json',
};
PortfolioEntry.Save.stopCheckingForNewIconsWhenWeAllReturnTrue = [];
PortfolioEntry.Save.postOptions.success = function (response) {
if (typeof response.pf_entry_element_id != 'undefined') {
// This was an INSERT aka an "Add"
var $new_pf_entry = $('#'+response.pf_entry_element_id);
$new_pf_entry.attr('id', "portfolio_entry_"+response.portfolio_entry__pk);
$new_pf_entry.attr('portfolio_entry__pk', response.portfolio_entry__pk);
$old_project_name_field = $new_pf_entry.find('input:text.project_name');
var project_name = $old_project_name_field.val()
$new_project_name_span = $('<span></span>').addClass('project_name')
.text(project_name);
$old_project_name_field.replaceWith($new_project_name_span);
}
var $entry = $('#portfolio_entry_'+response.portfolio_entry__pk);
$entry.removeClass('unsaved').removeClass('adding').removeClass('unpublished');
var $newupdateIcon = $entry.find('.actions li#update_icon');
$newupdateIcon.toggle();
var project_name = $entry.find('.project_name').text();
Notifier.displayMessage('Saved entry for '+project_name+'.');
// Poll until we stop looking for an icon
var iconChecker = PerProjectIconRefresher(response.project__pk,
response.portfolio_entry__pk);
iconChecker.startPolling();
};
PortfolioEntry.Save.postOptions.error = function (response) {
Notifier.displayMessage('Oh dear! There was an error saving this entry in your portfolio. '
+ 'A pox on the programmers.');
};
PortfolioEntry.Save.post = function () {
$.ajax(PortfolioEntry.Save.postOptions);
};
PortfolioEntry.Save.save = function () {
$saveLink = $(this);
$pfEntry = $saveLink.closest('.portfolio_entry');
Notifier.displayMessage('Saving, please wait!');
var $updateIcon = $pfEntry.find('.actions li#update_icon');
$updateIcon.toggle();
if ($pfEntry.find('.actions li.save_and_publish_button')) {
var $savePublishButton = $pfEntry.find('.actions li.save_and_publish_button');
$savePublishButton.remove();
}
// Do some client-side validation.
$projectName = $pfEntry.find('input.project_name');
if ($projectName.size() === 1) {
if ($projectName.val() === $projectName.attr('title')) {
alert("Couldn't save one of your projects. Did you forget to type a project name?");
return false;
}
}
PortfolioEntry.Save.postOptions.data = {
'csrfmiddlewaretoken': $.cookie('csrftoken'),
'portfolio_entry__pk': $pfEntry.attr('portfolio_entry__pk'),
'project_name': $pfEntry.find('.project_name').val(),
'project_description': $pfEntry.find('.project_description').val(),
'experience_description': $pfEntry.find('.experience_description').val(),
'receive_maintainer_updates': $pfEntry.find('.receive_maintainer_updates').is(':checked'),
// Send this always, but really it's only used when the pf entry has no pk yet.
'pf_entry_element_id': $pfEntry.attr('id'),
};
PortfolioEntry.Save.post();
return false;
}
PortfolioEntry.Save.bindEventHandlers = function() {
$('.portfolio_entry li.publish_portfolio_entry a').click(PortfolioEntry.Save.save);
$('.citations-wrapper .add').click(drawAddCitationFormNearThisButton);
};
PortfolioEntry.Delete = {};
PortfolioEntry.Delete.postOptions = {
'url': '/profile/views/delete_portfolio_entry_do',
'type': 'POST',
'dataType': 'json',
};
PortfolioEntry.Delete.postOptions.success = function (response) {
if (!response.success) {
PortfolioEntry.Delete.postOptions.error(response);
return;
}
/* Find the portfolio entry section of the page, and make it disappear. */
var pk = response.portfolio_entry__pk;
$portfolioEntry = $('#portfolio_entry_'+pk);
project_name = $portfolioEntry.find('.project_name').text();
$portfolioEntry.hide();
Notifier.displayMessage('Deleted entry for '+project_name+'.');
SaveAllButton.updateDisplay();
};
PortfolioEntry.Delete.postOptions.error = function (response) {
Notifier.displayMessage('Something went awry. We failed to remove that project from your profile.');
};
PortfolioEntry.Delete.post = function () {
$.ajax(PortfolioEntry.Delete.postOptions);
};
PortfolioEntry.Delete.deleteIt = function (deleteLink) {
$deleteLink = $(deleteLink);
$pfEntry = $deleteLink.closest('.portfolio_entry');
if ($pfEntry.hasClass('adding')) {
// If this pfEntry element is in adding mode,
// then there is no corresponding record in the db to delete,
// so let's just remove the element and say no more.
$pfEntry.remove();
}
else {
PortfolioEntry.Delete.postOptions.data = {
'csrfmiddlewaretoken': $.cookie('csrftoken'),
'portfolio_entry__pk': $pfEntry.attr('portfolio_entry__pk'),
};
PortfolioEntry.Delete.post();
}
return false;
}
// NB: Keeping event handlers in a named variable like this appears to prevent
// them from being bound more than once. This prevents bugs where a single
// click will cause the event handler to be executed more than once.
PortfolioEntry.Delete.deleteButtonClickHandler = function(){
var deleteLink = this;
var $projectNameElement = $(deleteLink).closest('.portfolio_entry').find('.project_name')
var projectName = $projectNameElement.text() ? $projectNameElement.text() : $projectNameElement.val();
if (projectName == '' || projectName == $projectNameElement.attr('title')) {
projectName = 'this unnamed project';
}
else {
projectName = '\'' + projectName + '\''; /* put in quotes */
}
keep_going = confirm('Are you sure you want to remove ' + projectName + ' from your profile?');
if (keep_going){
PortfolioEntry.Delete.deleteIt(deleteLink);
}
return false;
};
PortfolioEntry.Delete.bindEventHandlers = function() {
$('.portfolio_entry .actions li.delete_portfolio_entry a').click(
PortfolioEntry.Delete.deleteButtonClickHandler);
};
bindEventHandlers = function() {
$('a.delete_citation').hover(
function () { $(this).closest('.citations > li').addClass('to_be_deleted'); },
function () { $(this).closest('.citations > li').removeClass('to_be_deleted'); }
);
$('a.delete_citation').click(deleteCitationForThisLink);
$('.citations-wrapper .add').click(drawAddCitationFormNearThisButton);
FlagIcon.bindEventHandlers();
PortfolioEntry.bindEventHandlers();
};
$(bindEventHandlers);
Importer = {};
Importer.Inputs = {};
Importer.Inputs.getInputs = function () {
return $("form#importer input[type='text']");
};
Importer.Inputs.init = function () {
Importer.Inputs.makeNew();
Importer.Inputs.makeNew();
Importer.Inputs.getInputs().eq(0).attr('title',
"Type a repository username here");
Importer.Inputs.getInputs().eq(1).attr('title',
"Type an email address here");
};
Importer.Inputs.makeNew = function () {
// Don't make more than three. FIXME: Make this work for n > 3.
//if ($('#importer .query').size() > 2) return;
var $inputs_go_here = $('form#importer .body');
var index = $inputs_go_here.find('.query').size();
var extraClass = (index % 2 == 0) ? "" : " odd";
var html = ""
+ "<div id='query_$INDEX' class='query"+ extraClass +"'>"
// FIXME: Use $EXTRA_CLASS to include this in the string.
+ " <div class='who'>"
+ " <input type='text' "
+ " name='identifier_$INDEX' />"
+ " </div>"
+ "</div>";
html = html.replace(/\$INDEX/g, index);
$input_container = $(html);
$('#importer-form-footer').before($input_container);
Importer.Inputs.bindEventHandlers();
return false;
};
Importer.Inputs.keydownHandler = function () {
$input = $(this);
var oneInputIsBlank = function() {
var ret = false;
$("form#importer input[type='text']").each(function () {
var thisInputIsBlank = (
$(this).val().replace(/\s/g,'') == ''
|| $(this).val() == $(this).attr('title'));
if (thisInputIsBlank) ret = true;
});
return ret;
}();
if (!oneInputIsBlank) {
Importer.Inputs.makeNew();
Importer.Inputs.bindEventHandlers();
}
};
Importer.Inputs.bindEventHandlers = function () {
$("form#importer input[type='text']").keydown(Importer.Inputs.keydownHandler);
};
$(Importer.Inputs.init);
Importer.Submission = {
'init': function () {
Importer.Submission.$form = $('form#importer');
Importer.Submission.bindEventHandlers();
},
'$form': null,
'postOptions': {
'success': function () {
askServerForPortfolio();
},
'error': function () {
Notifier.displayMessage("Apologies—there was an error starting this import.");
}
},
'submitHandler': function () {
$(this).ajaxSubmit(Importer.Submission.postOptions);
return false; // Bypass the form's native submission logic.
},
'bindEventHandlers': function () {
Importer.Submission.$form.submit(Importer.Submission.submitHandler);
},
};
$(Importer.Submission.init);
Importer.ProgressBar = {};
Importer.ProgressBar.showWithValue = function(value) {
$bar = $('#importer #progressbar');
if (value < 10 ) { value = 10; } // Always show a smidgen of progress.
$bar.addClass('working');
if (value == 100) { Importer.ProgressBar.bumpTo100(); }
else { $bar.show().progressbar('option', 'value', value); }
};
Importer.ProgressBar.bumpTo100 = function() {
$('#importer #progressbar').removeClass('working').progressbar('option', 'value', 100);
};
PortfolioEntry.Add = {};
PortfolioEntry.Add.$link = null;
PortfolioEntry.Add.$projectNames = null;
PortfolioEntry.Add.init = function () {
console.info('console me');
PortfolioEntry.Add.$link = $('#add_pf_entry');
PortfolioEntry.Add.bindEventHandlers();
};
// We do this so that this particular method can be monkeypatched in testDeleteAdderWidget.
PortfolioEntry.Add.whenDoneAnimating = function () { SaveAllButton.updateDisplay(); };
PortfolioEntry.Add.clickHandler = function (project_name) {
// Draw a widget for adding pf entries.
var html = $('#add_a_portfolio_entry_building_block').html();
$add_a_pf_entry = $(html);
$add_a_pf_entry.attr('id', generateUniqueID());
$('#portfolio_entries').prepend($add_a_pf_entry);
if (typeof project_name == 'string') {
// Fill the project name
$add_a_pf_entry.find('.project_name').eq(0).val(project_name);
$add_a_pf_entry.show(PortfolioEntry.Add.whenDoneAnimating);
}
else {
// project_name not specified or is an event
$add_a_pf_entry.hide().fadeIn(PortfolioEntry.Add.whenDoneAnimating);
}
PortfolioEntry.bindEventHandlers();
return false;
};
PortfolioEntry.Add.bindEventHandlers = function () {
PortfolioEntry.Add.$link.click(PortfolioEntry.Add.clickHandler);
};
$(PortfolioEntry.Add.init);
/*
* Re-order projects
*-------------------------*/
PortfolioEntry.Reorder = {
'$list': null,
'$done_reordering': null,
'$hideUsWhenSorting': null,
'init': function () {
PortfolioEntry.Reorder.$hideUsWhenSorting = $('#add_pf_entry,'
+ 'h4 .separator, .apologies, #back_to_profile, #import_links_heading, '
+ '#importer, #back_to_profile, #portfolio_entries,'
+ '#save_all_projects');
$('a#reorder_projects').click(function () {
if ($('#portfolio .unsaved, #portfolio .unpublished').size() > 0) {
alert('Please save all of your projects before you sort or archive them.');
return false;
}
$reorder_projects_link = $(this);
// print a list of project names
PortfolioEntry.Reorder.$list = $list = $('<ul id="projects_to_be_reordered">');
var have_we_created_the_fold_yet = false;
var create_the_fold = function () {
$list.append("<li id='sortable_portfolio_entry_FOLD' class='fold'>(To archive your work on a project, put it below this line.)</li>");
};
$('#portfolio .portfolio_entry:visible, #archived_projects_heading').each(function () {
if (this.id == 'archived_projects_heading') {
have_we_created_the_fold_yet = true;
create_the_fold();
}
else {
var project_name = $(this).find('.project_name').html();
var $item = $('<li>').html(project_name).attr('id', 'sortable_'+this.id);
$list.append($item);
}
});
if (!have_we_created_the_fold_yet) { create_the_fold(); }
$('#portfolio_entries').before($list);
PortfolioEntry.Reorder.$hideUsWhenSorting.hide();
// Make list sortable using jQuery UI
$list.sortable({'axis': 'y'});
$reorder_projects_link.hide();
$('#projects_heading span:eq(0)').text('Sort and archive projects');
$('#done_reordering').text('Save this ordering').removeAttr('disabled').show();
$('#done_reordering').click(function () {
/* Save the new ordering.
* ---------------------- */
query_string = PortfolioEntry.Reorder.$list.sortable('serialize');
$(this).text('Working...').attr('disabled','disabled');
PortfolioEntry.Reorder.$done_reordering = $(this);
var options = {
'type': 'POST',
'url': '/+do/save_portfolio_entry_ordering_do',
'data': query_string,
'success': function () {
PortfolioEntry.Reorder.$list.remove();
$('#portfolio_entries *').not('.loading_message').remove();
PortfolioEntry.Reorder.$hideUsWhenSorting.show();
$('#done_reordering').hide();
$('#projects_heading span:eq(0)').text('Projects');
$('a#reorder_projects').show();
$('#portfolio_entries .loading_message').show();
askServerForPortfolio();
},
'error': function () {
alert('Merde, there was an error saving your ordering.');
},
};
$.ajax(options);
});
return false;
});
}
}
$(PortfolioEntry.Reorder.init);
$.fn.getHandler = function(handler) {
var real_obj = this[0];
var handler_meta_array = $.data(real_obj, "events");
for (var key in handler_meta_array) {
if (key == handler) {
return handler_meta_array[key];
}
}
return false;
}
SaveAllButton = {};
SaveAllButton.updateDisplay = function () {
$saveAllButton = $('button#save_all_projects');
if ($('#portfolio .portfolio_entry:visible').size() === 0) {
$saveAllButton.hide();
}
else {
$saveAllButton.show();
}
if (SaveAllButton.getAllProjects().size() === 0) {
$saveAllButton.attr('disabled', 'disabled');
}
else {
$saveAllButton.removeAttr('disabled');
}
if (!$saveAllButton.getHandler('click')) {
$saveAllButton.click(SaveAllButton.saveAll);
}
};
SaveAllButton.getAllProjects = function() {
return $('#portfolio .portfolio_entry.unsaved, #portfolio .portfolio_entry.unpublished');
};
SaveAllButton.saveAll = function() {
SaveAllButton.getAllProjects().each(function () {
$(this).find('.publish_portfolio_entry:visible a').trigger('click');
});
};
AutoSaucepan = {
'init': function () {
// This query string prefix triggers the automatic saucepan
qs_pref = /^\?add_project_name=/;
if (location.search.match(qs_pref) === null) return;
// Check in the query string if there is anything
var project_name = decodeURIComponent(location.search.replace(qs_pref,''));
if (project_name) {
// If so, simulate a click
PortfolioEntry.Add.clickHandler(project_name);
}
}
};
$(function () {
$('#importer .howto h5 a').click(function() {
var $imp = $('#importer');
$imp.toggleClass('expanded');
return false;
});
});
}
// vim: set nu:
/* Icon refresher class.
*/
// neo-classical constructor, attempting to clone from
// javascript the good parts.
var PerProjectIconRefresher = function(project_id, portfolio_entry_id) {
var instance = {}; // empty object
// private members
var projectId = project_id;
var portfolioEntryId = portfolio_entry_id;
var doNothing = function() {};
var delayBetweenPolls = 1500; /* Unit: milliseconds */
var enqueueNextPoll = function() {
window.setTimeout(
function() {
var ajaxOptions = {
'type': 'GET',
'url': '/profile/views/gimme_json_for_portfolio',
'dataType': 'json',
'success': ajaxResponseHandler,
'error': doNothing
};
$.ajax(ajaxOptions);
console.debug("Enqueuing a JSON GET.");
}, delayBetweenPolls);
};
var getPortfolioEntryOnPage = function() {
var id = 'portfolio_entry_' + portfolioEntryId;
$portfolio_entry = $('#' + id);
return $portfolio_entry;
};
var updatePageWithIcon = function(project_data) {
/* So, the object we select is a DIV whose CSS background-image
* is what causes the browser to display the icon. We store a
* copy of the URL JavaScript gave us in a totally made-up "src"
* attribute of the DIV to make life easier for us.
*/
var $pfeOnPage = getPortfolioEntryOnPage();
if ($pfeOnPage.size() == 0) {
/* Well, for some reason, we are trying to update a portfolio entry
we cannot find.
Bailing.
*/
console.warn("Mysteriously, we could not find a matching PFE box on the page.");
return;
}
var $icon = $pfeOnPage.find(".project_icon");
var current_src = $icon.attr('src');
var response_src = ("/static/" +
project_data.fields.icon_for_profile);
var response_src_for_css = 'url(' + response_src + ')';
if (current_src != response_src) {
$icon.attr('src', response_src); /* just for us */
$icon.css('background-image', response_src_for_css);
$pfeOnPage.find('.icon_flagger').show();
}
console.debug("Successfully updated page with icon.");
};
var findMyPortfolioEntry = function(portfolio_json) {
/* This function looks for the individual PortfolioEntry that
corresponds to our project. */
var project_id = null;
for (var i = 0; i < portfolio_json.projects.length; i++) {
var project = portfolio_json.projects[i];
if (project.pk === projectId) {
return project;
}
}
return null; /* if it is not found */
};
var ajaxResponseHandler = function(response) {
console.debug("ajaxResponseHandler started.");
myPortfolioEntry = findMyPortfolioEntry(response);
if (myPortfolioEntry === null) {
// if we could not find it, then we bail immediately.
return;
}
if (myPortfolioEntry.fields.date_icon_was_fetched_from_ohloh === null) {
enqueueNextPoll();
} else {
updatePageWithIcon(myPortfolioEntry);
}
console.debug("ajaxResponseHandler finished.");
};
// public members
instance.startPolling = function() {
enqueueNextPoll();
};
instance.toString = function(){
return "<PerProjectIconRefresher for project_id=" + private_project_id + ">";
};
return instance;
}
| nirmeshk/oh-mainline | mysite/static/js/importer.js | JavaScript | agpl-3.0 | 41,965 |
/*
Copyright 2008-2015 Clipperz Srl
This file is part of Clipperz, the online password manager.
For further information about its features and functionalities please
refer to http://www.clipperz.com.
* Clipperz is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
* Clipperz is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public
License along with Clipperz. If not, see http://www.gnu.org/licenses/.
*/
Clipperz.Base.module('Clipperz.PM.UI.Web.Components');
Clipperz.PM.UI.Common.Components.SimpleMessagePanel = function(args) {
args = args || {};
Clipperz.PM.UI.Common.Components.SimpleMessagePanel.superclass.constructor.apply(this, arguments);
this._title = args.title || Clipperz.Base.exception.raise('MandatoryParameter');
this._text = args.text || Clipperz.Base.exception.raise('MandatoryParameter');
this._type = args.type || Clipperz.Base.exception.raise('MandatoryParameter'); // ALERT, INFO, ERROR
this._buttons = args.buttons || Clipperz.Base.exception.raise('MandatoryParameter');
this._buttonComponents = [];
this._deferred = null;
this.renderModalMask();
return this;
}
//=============================================================================
Clipperz.Base.extend(Clipperz.PM.UI.Common.Components.SimpleMessagePanel, Clipperz.PM.UI.Common.Components.BaseComponent, {
//-------------------------------------------------------------------------
'toString': function () {
return "Clipperz.PM.UI.Common.Components.SimpleMessagePanel component";
},
//-------------------------------------------------------------------------
'deferred': function() {
if (this._deferred == null) {
this._deferred = new Clipperz.Async.Deferred("SimpleMessagePanel.deferred", {trace:false});
}
return this._deferred;
},
//-------------------------------------------------------------------------
'title': function () {
return this._title;
},
'setTitle': function (aValue) {
this._title = aValue;
if (this.getElement('title') != null) {
this.getElement('title').innerHTML = aValue;
}
},
//-------------------------------------------------------------------------
'text': function () {
return this._text;
},
'setText': function (aValue) {
this._text = aValue;
if (this.getElement('text') != null) {
this.getElement('text').innerHTML = aValue;
}
},
//-------------------------------------------------------------------------
'type': function () {
return this._type;
},
'setType': function (aValue) {
// if (this.getElement('icon') != null) {
// MochiKit.DOM.removeElementClass(this.getId('icon'), this._type);
// MochiKit.DOM.addElementClass(this.getId('icon'), aValue);
// }
this._type = aValue;
},
'icon': function () {
var type = this.type();
var result;
if (type == 'ALERT') {
result = '!';
} else if (type == 'INFO') {
result = 'i';
} else if (type == 'ERROR') {
result = '!';
}
return result;
},
//-------------------------------------------------------------------------
'buttons': function () {
return this._buttons;
},
'setButtons': function (someValues) {
MochiKit.Iter.forEach(this.buttonComponents(), MochiKit.Base.methodcaller('clear'));
this._buttons = someValues;
if (this.getElement('buttonArea') != null) {
this.renderButtons();
}
},
//.........................................................................
'buttonComponents': function () {
return this._buttonComponents;
},
//-------------------------------------------------------------------------
'renderSelf': function() {
this.append(this.element(), {tag:'div', cls:'SimpleMessagePanel', id:this.getId('panel'), children: [
// {tag:'div', cls:'header', children:[]},
{tag:'div', cls:'body', children:[
// {tag:'div', id:this.getId('icon'), cls:'img ' + this.type(), children:[{tag:'div'}]},
{tag:'div', /*id:this.getId('icon'),*/ cls:'img ' + this.type(), children:[{tag:'canvas', id:this.getId('icon')}]},
{tag:'h3', id:this.getId('title'), html:this.title()},
{tag:'p', id:this.getId('text'), html:this.text()},
{tag:'div', id:this.getId('container')},
{tag:'div', id:this.getId('buttonArea'), cls:'buttonArea', children:[]}
]}
// {tag:'div', cls:'footer', children:[]}
]});
Clipperz.PM.UI.Canvas.marks[this.icon()](this.getElement('icon'), "#ffffff");
MochiKit.Signal.connect(this.getId('panel'), 'onkeydown', this, 'keyDownHandler');
this.renderButtons();
},
//-------------------------------------------------------------------------
'renderButtons': function () {
this.getElement('buttonArea').innerHTML = '';
MochiKit.Base.map(MochiKit.Base.bind(function (aButton) {
var buttonElement;
var buttonComponent;
// element = this.append(this.getElement('buttonArea'), {tag:'div', cls:'button' + (aButton['isDefault'] === true ? ' default' : ''), children:[
// {tag:'a', href:'#'/*, id:this.getId('buttonLink')*/, html:aButton['text']}
// ]});
buttonElement = this.append(this.getElement('buttonArea'), {tag:'div'});
buttonComponent = new Clipperz.PM.UI.Common.Components.Button({'element':buttonElement, 'text':aButton['text'], 'isDefault':aButton['isDefault']});
this.buttonComponents().push(buttonComponent);
MochiKit.Signal.connect(buttonComponent, 'onclick', MochiKit.Base.method(this, 'buttonEventHandler', aButton));
}, this), MochiKit.Iter.reversed(this.buttons()));
},
//-------------------------------------------------------------------------
'displayElement': function() {
return this.getElement('panel');
},
//-------------------------------------------------------------------------
'closeOk': function () {
this.deferred().callback();
this._deferred = null;
},
'closeCancel': function () {
this.deferred().cancel();
this._deferred = null;
},
'closeError': function () {
this.deferred().errback();
this._deferred = null;
},
//-------------------------------------------------------------------------
'buttonEventHandler': function(aButton, anEvent) {
anEvent.preventDefault();
// MochiKit.Signal.signal(this, 'cancelEvent');
switch (aButton['result']) {
case 'OK':
this.closeOk();
break;
case 'CANCEL':
this.closeCancel();
break;
default:
this.closeError();
break;
}
},
//-------------------------------------------------------------------------
'deferredShow': function (someArgs, aResult) {
this.deferredShowModal(someArgs);
this.deferred().addMethod(this, 'deferredHideModal', {closeToElement:someArgs.onOkCloseToElement });
this.deferred().addErrback (MochiKit.Base.method(this, 'deferredHideModal', {closeToElement:someArgs.onCancelCloseToElement }));
this.deferred().addCallback(MochiKit.Async.succeed, aResult);
return this.deferred();
},
//-------------------------------------------------------------------------
'modalDialogMask': function () {
return this.getId('modalDialogMask');
},
'modalDialog': function () {
return this.getId('modalDialog');
},
'modalDialogFrame': function() {
return this.getId('modalDialogFrame');
},
//-------------------------------------------------------------------------
'renderModalMask': function () {
Clipperz.DOM.Helper.append(MochiKit.DOM.currentDocument().body,
{tag:'div', id:this.getId('modalDialogWrapper'), cls:'modalDialogWrapper simpleMessagePanelMask', children:[
{tag:'div', id:this.getId('modalDialogMask'), cls:'modalDialogMask simpleMessagePanelMask'},
{tag:'div', id:this.getId('modalDialogFrame'), cls:'modalDialogFrame simpleMessagePanelMask'},
{tag:'div', id:this.getId('modalDialog'), cls:'modalDialog simpleMessagePanelMask'}
]}
);
MochiKit.Style.hideElement(this.getId('modalDialogMask'));
MochiKit.Style.hideElement(this.getId('modalDialogFrame'));
},
//-------------------------------------------------------------------------
'keyDownHandler': function (anEvent) {
if (anEvent.key().string == 'KEY_ENTER') {
anEvent.preventDefault();
this.closeOk();
}
if (anEvent.key().string == 'KEY_ESCAPE') {
anEvent.preventDefault();
this.closeCancel();
}
},
//-------------------------------------------------------------------------
__syntaxFix__: "syntax fix"
});
| gcsolaroli/password-manager | frontend/gamma/js/Clipperz/PM/UI/Common/Components/SimpleMessagePanel.js | JavaScript | agpl-3.0 | 8,697 |
import { ListWrapper, StringMapWrapper } from '../facade/collection';
import { BaseException } from '../facade/exceptions';
import { NumberWrapper, RegExpWrapper, isPresent } from '../facade/lang';
import { HtmlAttrAst, HtmlElementAst, HtmlTextAst, htmlVisitAll } from '../html_ast';
import { HtmlParseTreeResult } from '../html_parser';
import { DEFAULT_INTERPOLATION_CONFIG } from '../interpolation_config';
import { expandNodes } from './expander';
import { id } from './message';
import { I18N_ATTR, I18N_ATTR_PREFIX, I18nError, dedupePhName, getPhNameFromBinding, messageFromAttribute, messageFromI18nAttribute, partition } from './shared';
const _PLACEHOLDER_ELEMENT = 'ph';
const _NAME_ATTR = 'name';
let _PLACEHOLDER_EXPANDED_REGEXP = /<ph(\s)+name=("(\w)+")><\/ph>/gi;
/**
* Creates an i18n-ed version of the parsed template.
*
* Algorithm:
*
* See `message_extractor.ts` for details on the partitioning algorithm.
*
* This is how the merging works:
*
* 1. Use the stringify function to get the message id. Look up the message in the map.
* 2. Get the translated message. At this point we have two trees: the original tree
* and the translated tree, where all the elements are replaced with placeholders.
* 3. Use the original tree to create a mapping Index:number -> HtmlAst.
* 4. Walk the translated tree.
* 5. If we encounter a placeholder element, get its name property.
* 6. Get the type and the index of the node using the name property.
* 7. If the type is 'e', which means element, then:
* - translate the attributes of the original element
* - recurse to merge the children
* - create a new element using the original element name, original position,
* and translated children and attributes
* 8. If the type if 't', which means text, then:
* - get the list of expressions from the original node.
* - get the string version of the interpolation subtree
* - find all the placeholders in the translated message, and replace them with the
* corresponding original expressions
*/
export class I18nHtmlParser {
constructor(_htmlParser, _parser, _messagesContent, _messages, _implicitTags, _implicitAttrs) {
this._htmlParser = _htmlParser;
this._parser = _parser;
this._messagesContent = _messagesContent;
this._messages = _messages;
this._implicitTags = _implicitTags;
this._implicitAttrs = _implicitAttrs;
}
parse(sourceContent, sourceUrl, parseExpansionForms = false, interpolationConfig = DEFAULT_INTERPOLATION_CONFIG) {
this.errors = [];
this._interpolationConfig = interpolationConfig;
let res = this._htmlParser.parse(sourceContent, sourceUrl, true);
if (res.errors.length > 0) {
return res;
}
else {
let expanded = expandNodes(res.rootNodes);
let nodes = this._recurse(expanded.nodes);
this.errors.push(...expanded.errors);
return this.errors.length > 0 ? new HtmlParseTreeResult([], this.errors) :
new HtmlParseTreeResult(nodes, []);
}
}
_processI18nPart(part) {
try {
return part.hasI18n ? this._mergeI18Part(part) : this._recurseIntoI18nPart(part);
}
catch (e) {
if (e instanceof I18nError) {
this.errors.push(e);
return [];
}
else {
throw e;
}
}
}
_mergeI18Part(part) {
let message = part.createMessage(this._parser, this._interpolationConfig);
let messageId = id(message);
if (!StringMapWrapper.contains(this._messages, messageId)) {
throw new I18nError(part.sourceSpan, `Cannot find message for id '${messageId}', content '${message.content}'.`);
}
let parsedMessage = this._messages[messageId];
return this._mergeTrees(part, parsedMessage, part.children);
}
_recurseIntoI18nPart(p) {
// we found an element without an i18n attribute
// we need to recurse in cause its children may have i18n set
// we also need to translate its attributes
if (isPresent(p.rootElement)) {
let root = p.rootElement;
let children = this._recurse(p.children);
let attrs = this._i18nAttributes(root);
return [new HtmlElementAst(root.name, attrs, children, root.sourceSpan, root.startSourceSpan, root.endSourceSpan)];
}
else if (isPresent(p.rootTextNode)) {
return [p.rootTextNode];
}
else {
return this._recurse(p.children);
}
}
_recurse(nodes) {
let parts = partition(nodes, this.errors, this._implicitTags);
return ListWrapper.flatten(parts.map(p => this._processI18nPart(p)));
}
_mergeTrees(p, translated, original) {
let l = new _CreateNodeMapping();
htmlVisitAll(l, original);
// merge the translated tree with the original tree.
// we do it by preserving the source code position of the original tree
let merged = this._mergeTreesHelper(translated, l.mapping);
// if the root element is present, we need to create a new root element with its attributes
// translated
if (isPresent(p.rootElement)) {
let root = p.rootElement;
let attrs = this._i18nAttributes(root);
return [new HtmlElementAst(root.name, attrs, merged, root.sourceSpan, root.startSourceSpan, root.endSourceSpan)];
}
else if (isPresent(p.rootTextNode)) {
throw new BaseException('should not be reached');
}
else {
return merged;
}
}
_mergeTreesHelper(translated, mapping) {
return translated.map(t => {
if (t instanceof HtmlElementAst) {
return this._mergeElementOrInterpolation(t, translated, mapping);
}
else if (t instanceof HtmlTextAst) {
return t;
}
else {
throw new BaseException('should not be reached');
}
});
}
_mergeElementOrInterpolation(t, translated, mapping) {
let name = this._getName(t);
let type = name[0];
let index = NumberWrapper.parseInt(name.substring(1), 10);
let originalNode = mapping[index];
if (type == 't') {
return this._mergeTextInterpolation(t, originalNode);
}
else if (type == 'e') {
return this._mergeElement(t, originalNode, mapping);
}
else {
throw new BaseException('should not be reached');
}
}
_getName(t) {
if (t.name != _PLACEHOLDER_ELEMENT) {
throw new I18nError(t.sourceSpan, `Unexpected tag "${t.name}". Only "${_PLACEHOLDER_ELEMENT}" tags are allowed.`);
}
let names = t.attrs.filter(a => a.name == _NAME_ATTR);
if (names.length == 0) {
throw new I18nError(t.sourceSpan, `Missing "${_NAME_ATTR}" attribute.`);
}
return names[0].value;
}
_mergeTextInterpolation(t, originalNode) {
let split = this._parser.splitInterpolation(originalNode.value, originalNode.sourceSpan.toString(), this._interpolationConfig);
let exps = isPresent(split) ? split.expressions : [];
let messageSubstring = this._messagesContent.substring(t.startSourceSpan.end.offset, t.endSourceSpan.start.offset);
let translated = this._replacePlaceholdersWithExpressions(messageSubstring, exps, originalNode.sourceSpan);
return new HtmlTextAst(translated, originalNode.sourceSpan);
}
_mergeElement(t, originalNode, mapping) {
let children = this._mergeTreesHelper(t.children, mapping);
return new HtmlElementAst(originalNode.name, this._i18nAttributes(originalNode), children, originalNode.sourceSpan, originalNode.startSourceSpan, originalNode.endSourceSpan);
}
_i18nAttributes(el) {
let res = [];
let implicitAttrs = isPresent(this._implicitAttrs[el.name]) ? this._implicitAttrs[el.name] : [];
el.attrs.forEach(attr => {
if (attr.name.startsWith(I18N_ATTR_PREFIX) || attr.name == I18N_ATTR)
return;
let message;
let i18ns = el.attrs.filter(a => a.name == `${I18N_ATTR_PREFIX}${attr.name}`);
if (i18ns.length == 0) {
if (implicitAttrs.indexOf(attr.name) == -1) {
res.push(attr);
return;
}
message = messageFromAttribute(this._parser, this._interpolationConfig, attr);
}
else {
message = messageFromI18nAttribute(this._parser, this._interpolationConfig, el, i18ns[0]);
}
let messageId = id(message);
if (StringMapWrapper.contains(this._messages, messageId)) {
let updatedMessage = this._replaceInterpolationInAttr(attr, this._messages[messageId]);
res.push(new HtmlAttrAst(attr.name, updatedMessage, attr.sourceSpan));
}
else {
throw new I18nError(attr.sourceSpan, `Cannot find message for id '${messageId}', content '${message.content}'.`);
}
});
return res;
}
_replaceInterpolationInAttr(attr, msg) {
let split = this._parser.splitInterpolation(attr.value, attr.sourceSpan.toString(), this._interpolationConfig);
let exps = isPresent(split) ? split.expressions : [];
let first = msg[0];
let last = msg[msg.length - 1];
let start = first.sourceSpan.start.offset;
let end = last instanceof HtmlElementAst ? last.endSourceSpan.end.offset : last.sourceSpan.end.offset;
let messageSubstring = this._messagesContent.substring(start, end);
return this._replacePlaceholdersWithExpressions(messageSubstring, exps, attr.sourceSpan);
}
;
_replacePlaceholdersWithExpressions(message, exps, sourceSpan) {
let expMap = this._buildExprMap(exps);
return RegExpWrapper.replaceAll(_PLACEHOLDER_EXPANDED_REGEXP, message, (match) => {
let nameWithQuotes = match[2];
let name = nameWithQuotes.substring(1, nameWithQuotes.length - 1);
return this._convertIntoExpression(name, expMap, sourceSpan);
});
}
_buildExprMap(exps) {
let expMap = new Map();
let usedNames = new Map();
for (var i = 0; i < exps.length; i++) {
let phName = getPhNameFromBinding(exps[i], i);
expMap.set(dedupePhName(usedNames, phName), exps[i]);
}
return expMap;
}
_convertIntoExpression(name, expMap, sourceSpan) {
if (expMap.has(name)) {
return `${this._interpolationConfig.start}${expMap.get(name)}${this._interpolationConfig.end}`;
}
else {
throw new I18nError(sourceSpan, `Invalid interpolation name '${name}'`);
}
}
}
class _CreateNodeMapping {
constructor() {
this.mapping = [];
}
visitElement(ast, context) {
this.mapping.push(ast);
htmlVisitAll(this, ast.children);
return null;
}
visitAttr(ast, context) { return null; }
visitText(ast, context) {
this.mapping.push(ast);
return null;
}
visitExpansion(ast, context) { return null; }
visitExpansionCase(ast, context) { return null; }
visitComment(ast, context) { return ''; }
}
//# sourceMappingURL=i18n_html_parser.js.map | evandor/skysail-webconsole | webconsole.client/client/dist/lib/@angular/compiler/esm/src/i18n/i18n_html_parser.js | JavaScript | apache-2.0 | 11,582 |
/* =========================================================
* bootstrap-datepicker.js
* Repo: https://github.com/eternicode/bootstrap-datepicker/
* Demo: http://eternicode.github.io/bootstrap-datepicker/
* Docs: http://bootstrap-datepicker.readthedocs.org/
* Forked from http://www.eyecon.ro/bootstrap-datepicker
* =========================================================
* Started by Stefan Petre; improvements by Andrew Rowls + contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================= */
(function($, undefined){
var $date_prev_icon = '«';//ACE
var $date_next_icon = '»';//ACE
var $window = $(window);
function UTCDate(){
return new Date(Date.UTC.apply(Date, arguments));
}
function UTCToday(){
var today = new Date();
return UTCDate(today.getFullYear(), today.getMonth(), today.getDate());
}
function alias(method){
return function(){
return this[method].apply(this, arguments);
};
}
var DateArray = (function(){
var extras = {
get: function(i){
return this.slice(i)[0];
},
contains: function(d){
// Array.indexOf is not cross-browser;
// $.inArray doesn't work with Dates
var val = d && d.valueOf();
for (var i=0, l=this.length; i < l; i++)
if (this[i].valueOf() === val)
return i;
return -1;
},
remove: function(i){
this.splice(i,1);
},
replace: function(new_array){
if (!new_array)
return;
if (!$.isArray(new_array))
new_array = [new_array];
this.clear();
this.push.apply(this, new_array);
},
clear: function(){
this.length = 0;
},
copy: function(){
var a = new DateArray();
a.replace(this);
return a;
}
};
return function(){
var a = [];
a.push.apply(a, arguments);
$.extend(a, extras);
return a;
};
})();
var Datepicker = function(element, options){
this.dates = new DateArray();
this.viewDate = UTCToday();
this.focusDate = null;
this._process_options(options);
this.element = $(element);
this.isInline = false;
this.isInput = this.element.is('input');
this.component = this.element.is('.date') ? this.element.find('.add-on, .input-group-addon, .btn') : false;
this.hasInput = this.component && this.element.find('input').length;
if (this.component && this.component.length === 0)
this.component = false;
this.picker = $(DPGlobal.template);
this._buildEvents();
this._attachEvents();
if (this.isInline){
this.picker.addClass('datepicker-inline').appendTo(this.element);
}
else {
this.picker.addClass('datepicker-dropdown dropdown-menu');
}
if (this.o.rtl){
this.picker.addClass('datepicker-rtl');
}
this.viewMode = this.o.startView;
if (this.o.calendarWeeks)
this.picker.find('tfoot th.today')
.attr('colspan', function(i, val){
return parseInt(val) + 1;
});
this._allow_update = false;
this.setStartDate(this._o.startDate);
this.setEndDate(this._o.endDate);
this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled);
this.fillDow();
this.fillMonths();
this._allow_update = true;
this.update();
this.showMode();
if (this.isInline){
this.show();
}
};
Datepicker.prototype = {
constructor: Datepicker,
_process_options: function(opts){
// Store raw options for reference
this._o = $.extend({}, this._o, opts);
// Processed options
var o = this.o = $.extend({}, this._o);
// Check if "de-DE" style date is available, if not language should
// fallback to 2 letter code eg "de"
var lang = o.language;
if (!dates[lang]){
lang = lang.split('-')[0];
if (!dates[lang])
lang = defaults.language;
}
o.language = lang;
switch (o.startView){
case 2:
case 'decade':
o.startView = 2;
break;
case 1:
case 'year':
o.startView = 1;
break;
default:
o.startView = 0;
}
switch (o.minViewMode){
case 1:
case 'months':
o.minViewMode = 1;
break;
case 2:
case 'years':
o.minViewMode = 2;
break;
default:
o.minViewMode = 0;
}
o.startView = Math.max(o.startView, o.minViewMode);
// true, false, or Number > 0
if (o.multidate !== true){
o.multidate = Number(o.multidate) || false;
if (o.multidate !== false)
o.multidate = Math.max(0, o.multidate);
else
o.multidate = 1;
}
o.multidateSeparator = String(o.multidateSeparator);
o.weekStart %= 7;
o.weekEnd = ((o.weekStart + 6) % 7);
var format = DPGlobal.parseFormat(o.format);
if (o.startDate !== -Infinity){
if (!!o.startDate){
if (o.startDate instanceof Date)
o.startDate = this._local_to_utc(this._zero_time(o.startDate));
else
o.startDate = DPGlobal.parseDate(o.startDate, format, o.language);
}
else {
o.startDate = -Infinity;
}
}
if (o.endDate !== Infinity){
if (!!o.endDate){
if (o.endDate instanceof Date)
o.endDate = this._local_to_utc(this._zero_time(o.endDate));
else
o.endDate = DPGlobal.parseDate(o.endDate, format, o.language);
}
else {
o.endDate = Infinity;
}
}
o.daysOfWeekDisabled = o.daysOfWeekDisabled||[];
if (!$.isArray(o.daysOfWeekDisabled))
o.daysOfWeekDisabled = o.daysOfWeekDisabled.split(/[,\s]*/);
o.daysOfWeekDisabled = $.map(o.daysOfWeekDisabled, function(d){
return parseInt(d, 10);
});
var plc = String(o.orientation).toLowerCase().split(/\s+/g),
_plc = o.orientation.toLowerCase();
plc = $.grep(plc, function(word){
return (/^auto|left|right|top|bottom$/).test(word);
});
o.orientation = {x: 'auto', y: 'auto'};
if (!_plc || _plc === 'auto')
; // no action
else if (plc.length === 1){
switch (plc[0]){
case 'top':
case 'bottom':
o.orientation.y = plc[0];
break;
case 'left':
case 'right':
o.orientation.x = plc[0];
break;
}
}
else {
_plc = $.grep(plc, function(word){
return (/^left|right$/).test(word);
});
o.orientation.x = _plc[0] || 'auto';
_plc = $.grep(plc, function(word){
return (/^top|bottom$/).test(word);
});
o.orientation.y = _plc[0] || 'auto';
}
},
_events: [],
_secondaryEvents: [],
_applyEvents: function(evs){
for (var i=0, el, ch, ev; i < evs.length; i++){
el = evs[i][0];
if (evs[i].length === 2){
ch = undefined;
ev = evs[i][1];
}
else if (evs[i].length === 3){
ch = evs[i][1];
ev = evs[i][2];
}
el.on(ev, ch);
}
},
_unapplyEvents: function(evs){
for (var i=0, el, ev, ch; i < evs.length; i++){
el = evs[i][0];
if (evs[i].length === 2){
ch = undefined;
ev = evs[i][1];
}
else if (evs[i].length === 3){
ch = evs[i][1];
ev = evs[i][2];
}
el.off(ev, ch);
}
},
_buildEvents: function(){
if (this.isInput){ // single input
this._events = [
[this.element, {
focus: $.proxy(this.show, this),
keyup: $.proxy(function(e){
if ($.inArray(e.keyCode, [27,37,39,38,40,32,13,9]) === -1)
this.update();
}, this),
keydown: $.proxy(this.keydown, this)
}]
];
}
else if (this.component && this.hasInput){ // component: input + button
this._events = [
// For components that are not readonly, allow keyboard nav
[this.element.find('input'), {
focus: $.proxy(this.show, this),
keyup: $.proxy(function(e){
if ($.inArray(e.keyCode, [27,37,39,38,40,32,13,9]) === -1)
this.update();
}, this),
keydown: $.proxy(this.keydown, this)
}],
[this.component, {
click: $.proxy(this.show, this)
}]
];
}
else if (this.element.is('div')){ // inline datepicker
this.isInline = true;
}
else {
this._events = [
[this.element, {
click: $.proxy(this.show, this)
}]
];
}
this._events.push(
// Component: listen for blur on element descendants
[this.element, '*', {
blur: $.proxy(function(e){
this._focused_from = e.target;
}, this)
}],
// Input: listen for blur on element
[this.element, {
blur: $.proxy(function(e){
this._focused_from = e.target;
}, this)
}]
);
this._secondaryEvents = [
[this.picker, {
click: $.proxy(this.click, this)
}],
[$(window), {
resize: $.proxy(this.place, this)
}],
[$(document), {
'mousedown touchstart': $.proxy(function(e){
// Clicked outside the datepicker, hide it
if (!(
this.element.is(e.target) ||
this.element.find(e.target).length ||
this.picker.is(e.target) ||
this.picker.find(e.target).length
)){
this.hide();
}
}, this)
}]
];
},
_attachEvents: function(){
this._detachEvents();
this._applyEvents(this._events);
},
_detachEvents: function(){
this._unapplyEvents(this._events);
},
_attachSecondaryEvents: function(){
this._detachSecondaryEvents();
this._applyEvents(this._secondaryEvents);
},
_detachSecondaryEvents: function(){
this._unapplyEvents(this._secondaryEvents);
},
_trigger: function(event, altdate){
var date = altdate || this.dates.get(-1),
local_date = this._utc_to_local(date);
this.element.trigger({
type: event,
date: local_date,
dates: $.map(this.dates, this._utc_to_local),
format: $.proxy(function(ix, format){
if (arguments.length === 0){
ix = this.dates.length - 1;
format = this.o.format;
}
else if (typeof ix === 'string'){
format = ix;
ix = this.dates.length - 1;
}
format = format || this.o.format;
var date = this.dates.get(ix);
return DPGlobal.formatDate(date, format, this.o.language);
}, this)
});
},
show: function(){
if (!this.isInline)
this.picker.appendTo('body');
this.picker.show();
this.place();
this._attachSecondaryEvents();
this._trigger('show');
},
hide: function(){
if (this.isInline)
return;
if (!this.picker.is(':visible'))
return;
this.focusDate = null;
this.picker.hide().detach();
this._detachSecondaryEvents();
this.viewMode = this.o.startView;
this.showMode();
if (
this.o.forceParse &&
(
this.isInput && this.element.val() ||
this.hasInput && this.element.find('input').val()
)
)
this.setValue();
this._trigger('hide');
},
remove: function(){
this.hide();
this._detachEvents();
this._detachSecondaryEvents();
this.picker.remove();
delete this.element.data().datepicker;
if (!this.isInput){
delete this.element.data().date;
}
},
_utc_to_local: function(utc){
return utc && new Date(utc.getTime() + (utc.getTimezoneOffset()*60000));
},
_local_to_utc: function(local){
return local && new Date(local.getTime() - (local.getTimezoneOffset()*60000));
},
_zero_time: function(local){
return local && new Date(local.getFullYear(), local.getMonth(), local.getDate());
},
_zero_utc_time: function(utc){
return utc && new Date(Date.UTC(utc.getUTCFullYear(), utc.getUTCMonth(), utc.getUTCDate()));
},
getDates: function(){
return $.map(this.dates, this._utc_to_local);
},
getUTCDates: function(){
return $.map(this.dates, function(d){
return new Date(d);
});
},
getDate: function(){
return this._utc_to_local(this.getUTCDate());
},
getUTCDate: function(){
return new Date(this.dates.get(-1));
},
setDates: function(){
var args = $.isArray(arguments[0]) ? arguments[0] : arguments;
this.update.apply(this, args);
this._trigger('changeDate');
this.setValue();
},
setUTCDates: function(){
var args = $.isArray(arguments[0]) ? arguments[0] : arguments;
this.update.apply(this, $.map(args, this._utc_to_local));
this._trigger('changeDate');
this.setValue();
},
setDate: alias('setDates'),
setUTCDate: alias('setUTCDates'),
setValue: function(){
var formatted = this.getFormattedDate();
if (!this.isInput){
if (this.component){
this.element.find('input').val(formatted).change();
}
}
else {
this.element.val(formatted).change();
}
},
getFormattedDate: function(format){
if (format === undefined)
format = this.o.format;
var lang = this.o.language;
return $.map(this.dates, function(d){
return DPGlobal.formatDate(d, format, lang);
}).join(this.o.multidateSeparator);
},
setStartDate: function(startDate){
this._process_options({startDate: startDate});
this.update();
this.updateNavArrows();
},
setEndDate: function(endDate){
this._process_options({endDate: endDate});
this.update();
this.updateNavArrows();
},
setDaysOfWeekDisabled: function(daysOfWeekDisabled){
this._process_options({daysOfWeekDisabled: daysOfWeekDisabled});
this.update();
this.updateNavArrows();
},
place: function(){
if (this.isInline)
return;
var calendarWidth = this.picker.outerWidth(),
calendarHeight = this.picker.outerHeight(),
visualPadding = 10,
windowWidth = $window.width(),
windowHeight = $window.height(),
scrollTop = $window.scrollTop();
var zIndex = parseInt(this.element.parents().filter(function(){
return $(this).css('z-index') !== 'auto';
}).first().css('z-index'))+10;
var offset = this.component ? this.component.parent().offset() : this.element.offset();
var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(false);
var width = this.component ? this.component.outerWidth(true) : this.element.outerWidth(false);
var left = offset.left,
top = offset.top;
this.picker.removeClass(
'datepicker-orient-top datepicker-orient-bottom '+
'datepicker-orient-right datepicker-orient-left'
);
if (this.o.orientation.x !== 'auto'){
this.picker.addClass('datepicker-orient-' + this.o.orientation.x);
if (this.o.orientation.x === 'right')
left -= calendarWidth - width;
}
// auto x orientation is best-placement: if it crosses a window
// edge, fudge it sideways
else {
// Default to left
this.picker.addClass('datepicker-orient-left');
if (offset.left < 0)
left -= offset.left - visualPadding;
else if (offset.left + calendarWidth > windowWidth)
left = windowWidth - calendarWidth - visualPadding;
}
// auto y orientation is best-situation: top or bottom, no fudging,
// decision based on which shows more of the calendar
var yorient = this.o.orientation.y,
top_overflow, bottom_overflow;
if (yorient === 'auto'){
top_overflow = -scrollTop + offset.top - calendarHeight;
bottom_overflow = scrollTop + windowHeight - (offset.top + height + calendarHeight);
if (Math.max(top_overflow, bottom_overflow) === bottom_overflow)
yorient = 'top';
else
yorient = 'bottom';
}
this.picker.addClass('datepicker-orient-' + yorient);
if (yorient === 'top')
top += height;
else
top -= calendarHeight + parseInt(this.picker.css('padding-top'));
this.picker.css({
top: top,
left: left,
zIndex: zIndex
});
},
_allow_update: true,
update: function(){
if (!this._allow_update)
return;
var oldDates = this.dates.copy(),
dates = [],
fromArgs = false;
if (arguments.length){
$.each(arguments, $.proxy(function(i, date){
if (date instanceof Date)
date = this._local_to_utc(date);
dates.push(date);
}, this));
fromArgs = true;
}
else {
dates = this.isInput
? this.element.val()
: this.element.data('date') || this.element.find('input').val();
if (dates && this.o.multidate)
dates = dates.split(this.o.multidateSeparator);
else
dates = [dates];
delete this.element.data().date;
}
dates = $.map(dates, $.proxy(function(date){
return DPGlobal.parseDate(date, this.o.format, this.o.language);
}, this));
dates = $.grep(dates, $.proxy(function(date){
return (
date < this.o.startDate ||
date > this.o.endDate ||
!date
);
}, this), true);
this.dates.replace(dates);
if (this.dates.length)
this.viewDate = new Date(this.dates.get(-1));
else if (this.viewDate < this.o.startDate)
this.viewDate = new Date(this.o.startDate);
else if (this.viewDate > this.o.endDate)
this.viewDate = new Date(this.o.endDate);
if (fromArgs){
// setting date by clicking
this.setValue();
}
else if (dates.length){
// setting date by typing
if (String(oldDates) !== String(this.dates))
this._trigger('changeDate');
}
if (!this.dates.length && oldDates.length)
this._trigger('clearDate');
this.fill();
},
fillDow: function(){
var dowCnt = this.o.weekStart,
html = '<tr>';
if (this.o.calendarWeeks){
var cell = '<th class="cw"> </th>';
html += cell;
this.picker.find('.datepicker-days thead tr:first-child').prepend(cell);
}
while (dowCnt < this.o.weekStart + 7){
html += '<th class="dow">'+dates[this.o.language].daysMin[(dowCnt++)%7]+'</th>';
}
html += '</tr>';
this.picker.find('.datepicker-days thead').append(html);
},
fillMonths: function(){
var html = '',
i = 0;
while (i < 12){
html += '<span class="month">'+dates[this.o.language].monthsShort[i++]+'</span>';
}
this.picker.find('.datepicker-months td').html(html);
},
setRange: function(range){
if (!range || !range.length)
delete this.range;
else
this.range = $.map(range, function(d){
return d.valueOf();
});
this.fill();
},
getClassNames: function(date){
var cls = [],
year = this.viewDate.getUTCFullYear(),
month = this.viewDate.getUTCMonth(),
today = new Date();
if (date.getUTCFullYear() < year || (date.getUTCFullYear() === year && date.getUTCMonth() < month)){
cls.push('old');
}
else if (date.getUTCFullYear() > year || (date.getUTCFullYear() === year && date.getUTCMonth() > month)){
cls.push('new');
}
if (this.focusDate && date.valueOf() === this.focusDate.valueOf())
cls.push('focused');
// Compare internal UTC date with local today, not UTC today
if (this.o.todayHighlight &&
date.getUTCFullYear() === today.getFullYear() &&
date.getUTCMonth() === today.getMonth() &&
date.getUTCDate() === today.getDate()){
cls.push('today');
}
if (this.dates.contains(date) !== -1)
cls.push('active');
if (date.valueOf() < this.o.startDate || date.valueOf() > this.o.endDate ||
$.inArray(date.getUTCDay(), this.o.daysOfWeekDisabled) !== -1){
cls.push('disabled');
}
if (this.range){
if (date > this.range[0] && date < this.range[this.range.length-1]){
cls.push('range');
}
if ($.inArray(date.valueOf(), this.range) !== -1){
cls.push('selected');
}
}
return cls;
},
fill: function(){
var d = new Date(this.viewDate),
year = d.getUTCFullYear(),
month = d.getUTCMonth(),
startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity,
startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity,
endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity,
endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity,
todaytxt = dates[this.o.language].today || dates['en'].today || '',
cleartxt = dates[this.o.language].clear || dates['en'].clear || '',
tooltip;
this.picker.find('.datepicker-days thead th.datepicker-switch')
.text(dates[this.o.language].months[month]+' '+year);
this.picker.find('tfoot th.today')
.text(todaytxt)
.toggle(this.o.todayBtn !== false);
this.picker.find('tfoot th.clear')
.text(cleartxt)
.toggle(this.o.clearBtn !== false);
this.updateNavArrows();
this.fillMonths();
var prevMonth = UTCDate(year, month-1, 28),
day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth());
prevMonth.setUTCDate(day);
prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.o.weekStart + 7)%7);
var nextMonth = new Date(prevMonth);
nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
nextMonth = nextMonth.valueOf();
var html = [];
var clsName;
while (prevMonth.valueOf() < nextMonth){
if (prevMonth.getUTCDay() === this.o.weekStart){
html.push('<tr>');
if (this.o.calendarWeeks){
// ISO 8601: First week contains first thursday.
// ISO also states week starts on Monday, but we can be more abstract here.
var
// Start of current week: based on weekstart/current date
ws = new Date(+prevMonth + (this.o.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5),
// Thursday of this week
th = new Date(Number(ws) + (7 + 4 - ws.getUTCDay()) % 7 * 864e5),
// First Thursday of year, year from thursday
yth = new Date(Number(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay())%7*864e5),
// Calendar week: ms between thursdays, div ms per day, div 7 days
calWeek = (th - yth) / 864e5 / 7 + 1;
html.push('<td class="cw">'+ calWeek +'</td>');
}
}
clsName = this.getClassNames(prevMonth);
clsName.push('day');
if (this.o.beforeShowDay !== $.noop){
var before = this.o.beforeShowDay(this._utc_to_local(prevMonth));
if (before === undefined)
before = {};
else if (typeof(before) === 'boolean')
before = {enabled: before};
else if (typeof(before) === 'string')
before = {classes: before};
if (before.enabled === false)
clsName.push('disabled');
if (before.classes)
clsName = clsName.concat(before.classes.split(/\s+/));
if (before.tooltip)
tooltip = before.tooltip;
}
clsName = $.unique(clsName);
html.push('<td class="'+clsName.join(' ')+'"' + (tooltip ? ' title="'+tooltip+'"' : '') + '>'+prevMonth.getUTCDate() + '</td>');
if (prevMonth.getUTCDay() === this.o.weekEnd){
html.push('</tr>');
}
prevMonth.setUTCDate(prevMonth.getUTCDate()+1);
}
this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
var months = this.picker.find('.datepicker-months')
.find('th:eq(1)')
.text(year)
.end()
.find('span').removeClass('active');
$.each(this.dates, function(i, d){
if (d.getUTCFullYear() === year)
months.eq(d.getUTCMonth()).addClass('active');
});
if (year < startYear || year > endYear){
months.addClass('disabled');
}
if (year === startYear){
months.slice(0, startMonth).addClass('disabled');
}
if (year === endYear){
months.slice(endMonth+1).addClass('disabled');
}
html = '';
year = parseInt(year/10, 10) * 10;
var yearCont = this.picker.find('.datepicker-years')
.find('th:eq(1)')
.text(year + '-' + (year + 9))
.end()
.find('td');
year -= 1;
var years = $.map(this.dates, function(d){
return d.getUTCFullYear();
}),
classes;
for (var i = -1; i < 11; i++){
classes = ['year'];
if (i === -1)
classes.push('old');
else if (i === 10)
classes.push('new');
if ($.inArray(year, years) !== -1)
classes.push('active');
if (year < startYear || year > endYear)
classes.push('disabled');
html += '<span class="' + classes.join(' ') + '">'+year+'</span>';
year += 1;
}
yearCont.html(html);
},
updateNavArrows: function(){
if (!this._allow_update)
return;
var d = new Date(this.viewDate),
year = d.getUTCFullYear(),
month = d.getUTCMonth();
switch (this.viewMode){
case 0:
if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear() && month <= this.o.startDate.getUTCMonth()){
this.picker.find('.prev').css({visibility: 'hidden'});
}
else {
this.picker.find('.prev').css({visibility: 'visible'});
}
if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear() && month >= this.o.endDate.getUTCMonth()){
this.picker.find('.next').css({visibility: 'hidden'});
}
else {
this.picker.find('.next').css({visibility: 'visible'});
}
break;
case 1:
case 2:
if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear()){
this.picker.find('.prev').css({visibility: 'hidden'});
}
else {
this.picker.find('.prev').css({visibility: 'visible'});
}
if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear()){
this.picker.find('.next').css({visibility: 'hidden'});
}
else {
this.picker.find('.next').css({visibility: 'visible'});
}
break;
}
},
click: function(e){
e.preventDefault();
var target = $(e.target).closest('span, td, th'),
year, month, day;
if (target.length === 1){
switch (target[0].nodeName.toLowerCase()){
case 'th':
switch (target[0].className){
case 'datepicker-switch':
this.showMode(1);
break;
case 'prev':
case 'next':
var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1);
switch (this.viewMode){
case 0:
this.viewDate = this.moveMonth(this.viewDate, dir);
this._trigger('changeMonth', this.viewDate);
break;
case 1:
case 2:
this.viewDate = this.moveYear(this.viewDate, dir);
if (this.viewMode === 1)
this._trigger('changeYear', this.viewDate);
break;
}
this.fill();
break;
case 'today':
var date = new Date();
date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
this.showMode(-2);
var which = this.o.todayBtn === 'linked' ? null : 'view';
this._setDate(date, which);
break;
case 'clear':
var element;
if (this.isInput)
element = this.element;
else if (this.component)
element = this.element.find('input');
if (element)
element.val("").change();
this.update();
this._trigger('changeDate');
if (this.o.autoclose)
this.hide();
break;
}
break;
case 'span':
if (!target.is('.disabled')){
this.viewDate.setUTCDate(1);
if (target.is('.month')){
day = 1;
month = target.parent().find('span').index(target);
year = this.viewDate.getUTCFullYear();
this.viewDate.setUTCMonth(month);
this._trigger('changeMonth', this.viewDate);
if (this.o.minViewMode === 1){
this._setDate(UTCDate(year, month, day));
}
}
else {
day = 1;
month = 0;
year = parseInt(target.text(), 10)||0;
this.viewDate.setUTCFullYear(year);
this._trigger('changeYear', this.viewDate);
if (this.o.minViewMode === 2){
this._setDate(UTCDate(year, month, day));
}
}
this.showMode(-1);
this.fill();
}
break;
case 'td':
if (target.is('.day') && !target.is('.disabled')){
day = parseInt(target.text(), 10)||1;
year = this.viewDate.getUTCFullYear();
month = this.viewDate.getUTCMonth();
if (target.is('.old')){
if (month === 0){
month = 11;
year -= 1;
}
else {
month -= 1;
}
}
else if (target.is('.new')){
if (month === 11){
month = 0;
year += 1;
}
else {
month += 1;
}
}
this._setDate(UTCDate(year, month, day));
}
break;
}
}
if (this.picker.is(':visible') && this._focused_from){
$(this._focused_from).focus();
}
delete this._focused_from;
},
_toggle_multidate: function(date){
var ix = this.dates.contains(date);
if (!date){
this.dates.clear();
}
else if (ix !== -1){
this.dates.remove(ix);
}
else {
this.dates.push(date);
}
if (typeof this.o.multidate === 'number')
while (this.dates.length > this.o.multidate)
this.dates.remove(0);
},
_setDate: function(date, which){
if (!which || which === 'date')
this._toggle_multidate(date && new Date(date));
if (!which || which === 'view')
this.viewDate = date && new Date(date);
this.fill();
this.setValue();
this._trigger('changeDate');
var element;
if (this.isInput){
element = this.element;
}
else if (this.component){
element = this.element.find('input');
}
if (element){
element.change();
}
if (this.o.autoclose && (!which || which === 'date')){
this.hide();
}
},
moveMonth: function(date, dir){
if (!date)
return undefined;
if (!dir)
return date;
var new_date = new Date(date.valueOf()),
day = new_date.getUTCDate(),
month = new_date.getUTCMonth(),
mag = Math.abs(dir),
new_month, test;
dir = dir > 0 ? 1 : -1;
if (mag === 1){
test = dir === -1
// If going back one month, make sure month is not current month
// (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02)
? function(){
return new_date.getUTCMonth() === month;
}
// If going forward one month, make sure month is as expected
// (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02)
: function(){
return new_date.getUTCMonth() !== new_month;
};
new_month = month + dir;
new_date.setUTCMonth(new_month);
// Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11
if (new_month < 0 || new_month > 11)
new_month = (new_month + 12) % 12;
}
else {
// For magnitudes >1, move one month at a time...
for (var i=0; i < mag; i++)
// ...which might decrease the day (eg, Jan 31 to Feb 28, etc)...
new_date = this.moveMonth(new_date, dir);
// ...then reset the day, keeping it in the new month
new_month = new_date.getUTCMonth();
new_date.setUTCDate(day);
test = function(){
return new_month !== new_date.getUTCMonth();
};
}
// Common date-resetting loop -- if date is beyond end of month, make it
// end of month
while (test()){
new_date.setUTCDate(--day);
new_date.setUTCMonth(new_month);
}
return new_date;
},
moveYear: function(date, dir){
return this.moveMonth(date, dir*12);
},
dateWithinRange: function(date){
return date >= this.o.startDate && date <= this.o.endDate;
},
keydown: function(e){
if (this.picker.is(':not(:visible)')){
if (e.keyCode === 27) // allow escape to hide and re-show picker
this.show();
return;
}
var dateChanged = false,
dir, newDate, newViewDate,
focusDate = this.focusDate || this.viewDate;
switch (e.keyCode){
case 27: // escape
if (this.focusDate){
this.focusDate = null;
this.viewDate = this.dates.get(-1) || this.viewDate;
this.fill();
}
else
this.hide();
e.preventDefault();
break;
case 37: // left
case 39: // right
if (!this.o.keyboardNavigation)
break;
dir = e.keyCode === 37 ? -1 : 1;
if (e.ctrlKey){
newDate = this.moveYear(this.dates.get(-1) || UTCToday(), dir);
newViewDate = this.moveYear(focusDate, dir);
this._trigger('changeYear', this.viewDate);
}
else if (e.shiftKey){
newDate = this.moveMonth(this.dates.get(-1) || UTCToday(), dir);
newViewDate = this.moveMonth(focusDate, dir);
this._trigger('changeMonth', this.viewDate);
}
else {
newDate = new Date(this.dates.get(-1) || UTCToday());
newDate.setUTCDate(newDate.getUTCDate() + dir);
newViewDate = new Date(focusDate);
newViewDate.setUTCDate(focusDate.getUTCDate() + dir);
}
if (this.dateWithinRange(newDate)){
this.focusDate = this.viewDate = newViewDate;
this.setValue();
this.fill();
e.preventDefault();
}
break;
case 38: // up
case 40: // down
if (!this.o.keyboardNavigation)
break;
dir = e.keyCode === 38 ? -1 : 1;
if (e.ctrlKey){
newDate = this.moveYear(this.dates.get(-1) || UTCToday(), dir);
newViewDate = this.moveYear(focusDate, dir);
this._trigger('changeYear', this.viewDate);
}
else if (e.shiftKey){
newDate = this.moveMonth(this.dates.get(-1) || UTCToday(), dir);
newViewDate = this.moveMonth(focusDate, dir);
this._trigger('changeMonth', this.viewDate);
}
else {
newDate = new Date(this.dates.get(-1) || UTCToday());
newDate.setUTCDate(newDate.getUTCDate() + dir * 7);
newViewDate = new Date(focusDate);
newViewDate.setUTCDate(focusDate.getUTCDate() + dir * 7);
}
if (this.dateWithinRange(newDate)){
this.focusDate = this.viewDate = newViewDate;
this.setValue();
this.fill();
e.preventDefault();
}
break;
case 32: // spacebar
// Spacebar is used in manually typing dates in some formats.
// As such, its behavior should not be hijacked.
break;
case 13: // enter
focusDate = this.focusDate || this.dates.get(-1) || this.viewDate;
this._toggle_multidate(focusDate);
dateChanged = true;
this.focusDate = null;
this.viewDate = this.dates.get(-1) || this.viewDate;
this.setValue();
this.fill();
if (this.picker.is(':visible')){
e.preventDefault();
if (this.o.autoclose)
this.hide();
}
break;
case 9: // tab
this.focusDate = null;
this.viewDate = this.dates.get(-1) || this.viewDate;
this.fill();
this.hide();
break;
}
if (dateChanged){
if (this.dates.length)
this._trigger('changeDate');
else
this._trigger('clearDate');
var element;
if (this.isInput){
element = this.element;
}
else if (this.component){
element = this.element.find('input');
}
if (element){
element.change();
}
}
},
showMode: function(dir){
if (dir){
this.viewMode = Math.max(this.o.minViewMode, Math.min(2, this.viewMode + dir));
}
this.picker
.find('>div')
.hide()
.filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName)
.css('display', 'block');
this.updateNavArrows();
}
};
var DateRangePicker = function(element, options){
this.element = $(element);
this.inputs = $.map(options.inputs, function(i){
return i.jquery ? i[0] : i;
});
delete options.inputs;
$(this.inputs)
.datepicker(options)
.bind('changeDate', $.proxy(this.dateUpdated, this));
this.pickers = $.map(this.inputs, function(i){
return $(i).data('datepicker');
});
this.updateDates();
};
DateRangePicker.prototype = {
updateDates: function(){
this.dates = $.map(this.pickers, function(i){
return i.getUTCDate();
});
this.updateRanges();
},
updateRanges: function(){
var range = $.map(this.dates, function(d){
return d.valueOf();
});
$.each(this.pickers, function(i, p){
p.setRange(range);
});
},
dateUpdated: function(e){
// `this.updating` is a workaround for preventing infinite recursion
// between `changeDate` triggering and `setUTCDate` calling. Until
// there is a better mechanism.
if (this.updating)
return;
this.updating = true;
var dp = $(e.target).data('datepicker'),
new_date = dp.getUTCDate(),
i = $.inArray(e.target, this.inputs),
l = this.inputs.length;
if (i === -1)
return;
$.each(this.pickers, function(i, p){
if (!p.getUTCDate())
p.setUTCDate(new_date);
});
if (new_date < this.dates[i]){
// Date being moved earlier/left
while (i >= 0 && new_date < this.dates[i]){
this.pickers[i--].setUTCDate(new_date);
}
}
else if (new_date > this.dates[i]){
// Date being moved later/right
while (i < l && new_date > this.dates[i]){
this.pickers[i++].setUTCDate(new_date);
}
}
this.updateDates();
delete this.updating;
},
remove: function(){
$.map(this.pickers, function(p){ p.remove(); });
delete this.element.data().datepicker;
}
};
function opts_from_el(el, prefix){
// Derive options from element data-attrs
var data = $(el).data(),
out = {}, inkey,
replace = new RegExp('^' + prefix.toLowerCase() + '([A-Z])');
prefix = new RegExp('^' + prefix.toLowerCase());
function re_lower(_,a){
return a.toLowerCase();
}
for (var key in data)
if (prefix.test(key)){
inkey = key.replace(replace, re_lower);
out[inkey] = data[key];
}
return out;
}
function opts_from_locale(lang){
// Derive options from locale plugins
var out = {};
// Check if "de-DE" style date is available, if not language should
// fallback to 2 letter code eg "de"
if (!dates[lang]){
lang = lang.split('-')[0];
if (!dates[lang])
return;
}
var d = dates[lang];
$.each(locale_opts, function(i,k){
if (k in d)
out[k] = d[k];
});
return out;
}
var old = $.fn.datepicker;
$.fn.datepicker = function(option){
var args = Array.apply(null, arguments);
args.shift();
var internal_return;
this.each(function(){
var $this = $(this),
data = $this.data('datepicker'),
options = typeof option === 'object' && option;
if (!data){
var elopts = opts_from_el(this, 'date'),
// Preliminary otions
xopts = $.extend({}, defaults, elopts, options),
locopts = opts_from_locale(xopts.language),
// Options priority: js args, data-attrs, locales, defaults
opts = $.extend({}, defaults, locopts, elopts, options);
if ($this.is('.input-daterange') || opts.inputs){
var ropts = {
inputs: opts.inputs || $this.find('input').toArray()
};
$this.data('datepicker', (data = new DateRangePicker(this, $.extend(opts, ropts))));
}
else {
$this.data('datepicker', (data = new Datepicker(this, opts)));
}
}
if (typeof option === 'string' && typeof data[option] === 'function'){
internal_return = data[option].apply(data, args);
if (internal_return !== undefined)
return false;
}
});
if (internal_return !== undefined)
return internal_return;
else
return this;
};
var defaults = $.fn.datepicker.defaults = {
autoclose: false,
beforeShowDay: $.noop,
calendarWeeks: false,
clearBtn: false,
daysOfWeekDisabled: [],
endDate: Infinity,
forceParse: true,
format: 'mm/dd/yyyy',
keyboardNavigation: true,
language: 'en',
minViewMode: 0,
multidate: false,
multidateSeparator: ',',
orientation: "auto",
rtl: false,
startDate: -Infinity,
startView: 0,
todayBtn: false,
todayHighlight: false,
weekStart: 0
};
var locale_opts = $.fn.datepicker.locale_opts = [
'format',
'rtl',
'weekStart'
];
$.fn.datepicker.Constructor = Datepicker;
var dates = $.fn.datepicker.dates = {
en: {
days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
today: "Today",
clear: "Clear"
},
cn: {
days: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
daysShort: ["日", "一", "二", "三", "四", "五", "六", "七"],
daysMin: ["日", "一", "二", "三", "四", "五", "六", "七"],
months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
today: "今天",
clear: "清除"
}
};
var DPGlobal = {
modes: [
{
clsName: 'days',
navFnc: 'Month',
navStep: 1
},
{
clsName: 'months',
navFnc: 'FullYear',
navStep: 1
},
{
clsName: 'years',
navFnc: 'FullYear',
navStep: 10
}],
isLeapYear: function(year){
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
},
getDaysInMonth: function(year, month){
return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
},
validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g,
parseFormat: function(format){
// IE treats \0 as a string end in inputs (truncating the value),
// so it's a bad format delimiter, anyway
var separators = format.replace(this.validParts, '\0').split('\0'),
parts = format.match(this.validParts);
if (!separators || !separators.length || !parts || parts.length === 0){
throw new Error("Invalid date format.");
}
return {separators: separators, parts: parts};
},
parseDate: function(date, format, language){
if (!date)
return undefined;
if (date instanceof Date)
return date;
if (typeof format === 'string')
format = DPGlobal.parseFormat(format);
var part_re = /([\-+]\d+)([dmwy])/,
parts = date.match(/([\-+]\d+)([dmwy])/g),
part, dir, i;
if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)){
date = new Date();
for (i=0; i < parts.length; i++){
part = part_re.exec(parts[i]);
dir = parseInt(part[1]);
switch (part[2]){
case 'd':
date.setUTCDate(date.getUTCDate() + dir);
break;
case 'm':
date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir);
break;
case 'w':
date.setUTCDate(date.getUTCDate() + dir * 7);
break;
case 'y':
date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir);
break;
}
}
return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0);
}
parts = date && date.match(this.nonpunctuation) || [];
date = new Date();
var parsed = {},
setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'],
setters_map = {
yyyy: function(d,v){
return d.setUTCFullYear(v);
},
yy: function(d,v){
return d.setUTCFullYear(2000+v);
},
m: function(d,v){
if (isNaN(d))
return d;
v -= 1;
while (v < 0) v += 12;
v %= 12;
d.setUTCMonth(v);
while (d.getUTCMonth() !== v)
d.setUTCDate(d.getUTCDate()-1);
return d;
},
d: function(d,v){
return d.setUTCDate(v);
}
},
val, filtered;
setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m'];
setters_map['dd'] = setters_map['d'];
date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
var fparts = format.parts.slice();
// Remove noop parts
if (parts.length !== fparts.length){
fparts = $(fparts).filter(function(i,p){
return $.inArray(p, setters_order) !== -1;
}).toArray();
}
// Process remainder
function match_part(){
var m = this.slice(0, parts[i].length),
p = parts[i].slice(0, m.length);
return m === p;
}
if (parts.length === fparts.length){
var cnt;
for (i=0, cnt = fparts.length; i < cnt; i++){
val = parseInt(parts[i], 10);
part = fparts[i];
if (isNaN(val)){
switch (part){
case 'MM':
filtered = $(dates[language].months).filter(match_part);
val = $.inArray(filtered[0], dates[language].months) + 1;
break;
case 'M':
filtered = $(dates[language].monthsShort).filter(match_part);
val = $.inArray(filtered[0], dates[language].monthsShort) + 1;
break;
}
}
parsed[part] = val;
}
var _date, s;
for (i=0; i < setters_order.length; i++){
s = setters_order[i];
if (s in parsed && !isNaN(parsed[s])){
_date = new Date(date);
setters_map[s](_date, parsed[s]);
if (!isNaN(_date))
date = _date;
}
}
}
return date;
},
formatDate: function(date, format, language){
if (!date)
return '';
if (typeof format === 'string')
format = DPGlobal.parseFormat(format);
var val = {
d: date.getUTCDate(),
D: dates[language].daysShort[date.getUTCDay()],
DD: dates[language].days[date.getUTCDay()],
m: date.getUTCMonth() + 1,
M: dates[language].monthsShort[date.getUTCMonth()],
MM: dates[language].months[date.getUTCMonth()],
yy: date.getUTCFullYear().toString().substring(2),
yyyy: date.getUTCFullYear()
};
val.dd = (val.d < 10 ? '0' : '') + val.d;
val.mm = (val.m < 10 ? '0' : '') + val.m;
date = [];
var seps = $.extend([], format.separators);
for (var i=0, cnt = format.parts.length; i <= cnt; i++){
if (seps.length)
date.push(seps.shift());
date.push(val[format.parts[i]]);
}
return date.join('');
},
headTemplate: '<thead>'+
'<tr>'+
'<th class="prev">'+$date_prev_icon+'</th>'+//ACE
'<th colspan="5" class="datepicker-switch"></th>'+
'<th class="next">'+$date_next_icon+'</th>'+//ACE
'</tr>'+
'</thead>',
contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
footTemplate: '<tfoot>'+
'<tr>'+
'<th colspan="7" class="today"></th>'+
'</tr>'+
'<tr>'+
'<th colspan="7" class="clear"></th>'+
'</tr>'+
'</tfoot>'
};
DPGlobal.template = '<div class="datepicker">'+
'<div class="datepicker-days">'+
'<table class=" table-condensed">'+
DPGlobal.headTemplate+
'<tbody></tbody>'+
DPGlobal.footTemplate+
'</table>'+
'</div>'+
'<div class="datepicker-months">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
DPGlobal.footTemplate+
'</table>'+
'</div>'+
'<div class="datepicker-years">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
DPGlobal.footTemplate+
'</table>'+
'</div>'+
'</div>';
$.fn.datepicker.DPGlobal = DPGlobal;
/* DATEPICKER NO CONFLICT
* =================== */
$.fn.datepicker.noConflict = function(){
$.fn.datepicker = old;
return this;
};
/* DATEPICKER DATA-API
* ================== */
$(document).on(
'focus.datepicker.data-api click.datepicker.data-api',
'[data-provide="datepicker"]',
function(e){
var $this = $(this);
if ($this.data('datepicker'))
return;
e.preventDefault();
// component click requires us to explicitly show it
$this.datepicker('show');
}
);
$(function(){
$('[data-provide="datepicker-inline"]').datepicker();
});
}(window.jQuery));
| shuoguoa/fastadmin | Public/qwadmin/js/date-time/bootstrap-datepicker.js | JavaScript | apache-2.0 | 47,484 |
const debug = require('ghost-ignition').debug('api:v2:utils:serializers:output:pages');
const mapper = require('./utils/mapper');
module.exports = {
all(models, apiConfig, frame) {
debug('all');
// CASE: e.g. destroy returns null
if (!models) {
return;
}
if (models.meta) {
frame.response = {
pages: models.data.map(model => mapper.mapPost(model, frame)),
meta: models.meta
};
return;
}
frame.response = {
pages: [mapper.mapPost(models, frame)]
};
}
};
| dingotiles/ghost-for-cloudfoundry | versions/3.3.0/core/server/api/v2/utils/serializers/output/pages.js | JavaScript | mit | 622 |
var config = require('../config');
if (typeof ot === 'undefined') {
var ot = {};
}
ot.Server = (function (global) {
'use strict';
// Constructor. Takes the current document as a string and optionally the array
// of all operations.
function Server (document, operations) {
this.document = document;
this.operations = operations || [];
}
// Call this method whenever you receive an operation from a client.
Server.prototype.receiveOperation = function (revision, operation) {
if (revision < 0 || this.operations.length < revision) {
throw new Error("operation revision not in history");
}
// Find all operations that the client didn't know of when it sent the
// operation ...
var concurrentOperations = this.operations.slice(revision);
// ... and transform the operation against all these operations ...
var transform = operation.constructor.transform;
for (var i = 0; i < concurrentOperations.length; i++) {
operation = transform(operation, concurrentOperations[i])[0];
}
// ... and apply that on the document.
var newDocument = operation.apply(this.document);
// ignore if exceed the max length of document
if(newDocument.length > config.documentmaxlength && newDocument.length > this.document.length)
return;
this.document = newDocument;
// Store operation in history.
this.operations.push(operation);
// It's the caller's responsibility to send the operation to all connected
// clients and an acknowledgement to the creator.
return operation;
};
return Server;
}(this));
if (typeof module === 'object') {
module.exports = ot.Server;
} | xnum/hackmd | lib/ot/server.js | JavaScript | mit | 1,675 |
Ext.define('ExtThemeNeptune.Component', {
override: 'Ext.Component',
initComponent: function() {
this.callParent();
if (this.dock && this.border === undefined) {
this.border = false;
}
},
privates: {
initStyles: function () {
var me = this,
hasOwnBorder = me.hasOwnProperty('border'),
border = me.border;
if (me.dock) {
// prevent the superclass method from setting the border style. We want to
// allow dock layout to decide which borders to suppress.
me.border = null;
}
me.callParent(arguments);
if (hasOwnBorder) {
me.border = border;
} else {
delete me.border;
}
}
}
});
Ext.define('ExtThemeNeptune.resizer.Splitter', {
override: 'Ext.resizer.Splitter',
size: 8
});
Ext.define('Ext.touch.sizing.resizer.Splitter', {
override: 'Ext.resizer.Splitter',
size: 16
});
Ext.define('ExtThemeNeptune.toolbar.Toolbar', {
override: 'Ext.toolbar.Toolbar',
usePlainButtons: false,
border: false
});
Ext.define('ExtThemeNeptune.layout.component.Dock', {
override: 'Ext.layout.component.Dock',
/**
* This table contains the border removal classes indexed by the sum of the edges to
* remove. Each edge is assigned a value:
*
* * `left` = 1
* * `bottom` = 2
* * `right` = 4
* * `top` = 8
*
* @private
*/
noBorderClassTable: [
0, // TRBL
Ext.baseCSSPrefix + 'noborder-l', // 0001 = 1
Ext.baseCSSPrefix + 'noborder-b', // 0010 = 2
Ext.baseCSSPrefix + 'noborder-bl', // 0011 = 3
Ext.baseCSSPrefix + 'noborder-r', // 0100 = 4
Ext.baseCSSPrefix + 'noborder-rl', // 0101 = 5
Ext.baseCSSPrefix + 'noborder-rb', // 0110 = 6
Ext.baseCSSPrefix + 'noborder-rbl', // 0111 = 7
Ext.baseCSSPrefix + 'noborder-t', // 1000 = 8
Ext.baseCSSPrefix + 'noborder-tl', // 1001 = 9
Ext.baseCSSPrefix + 'noborder-tb', // 1010 = 10
Ext.baseCSSPrefix + 'noborder-tbl', // 1011 = 11
Ext.baseCSSPrefix + 'noborder-tr', // 1100 = 12
Ext.baseCSSPrefix + 'noborder-trl', // 1101 = 13
Ext.baseCSSPrefix + 'noborder-trb', // 1110 = 14
Ext.baseCSSPrefix + 'noborder-trbl' // 1111 = 15
],
/**
* The numeric values assigned to each edge indexed by the `dock` config value.
* @private
*/
edgeMasks: {
top: 8,
right: 4,
bottom: 2,
left: 1
},
handleItemBorders: function() {
var me = this,
edges = 0,
maskT = 8,
maskR = 4,
maskB = 2,
maskL = 1,
owner = me.owner,
bodyBorder = owner.bodyBorder,
ownerBorder = owner.border,
collapsed = me.collapsed,
edgeMasks = me.edgeMasks,
noBorderCls = me.noBorderClassTable,
dockedItemsGen = owner.dockedItems.generation,
b, borderCls, docked, edgesTouched, i, ln, item, dock, lastValue, mask,
addCls, removeCls;
if (me.initializedBorders === dockedItemsGen) {
return;
}
addCls = [];
removeCls = [];
borderCls = me.getBorderCollapseTable();
noBorderCls = me.getBorderClassTable ? me.getBorderClassTable() : noBorderCls;
me.initializedBorders = dockedItemsGen;
// Borders have to be calculated using expanded docked item collection.
me.collapsed = false;
docked = me.getDockedItems();
me.collapsed = collapsed;
for (i = 0, ln = docked.length; i < ln; i++) {
item = docked[i];
if (item.ignoreBorderManagement) {
// headers in framed panels ignore border management, so we do not want
// to set "satisfied" on the edge in question
continue;
}
dock = item.dock;
mask = edgesTouched = 0;
addCls.length = 0;
removeCls.length = 0;
if (dock !== 'bottom') {
if (edges & maskT) { // if (not touching the top edge)
b = item.border;
} else {
b = ownerBorder;
if (b !== false) {
edgesTouched += maskT;
}
}
if (b === false) {
mask += maskT;
}
}
if (dock !== 'left') {
if (edges & maskR) { // if (not touching the right edge)
b = item.border;
} else {
b = ownerBorder;
if (b !== false) {
edgesTouched += maskR;
}
}
if (b === false) {
mask += maskR;
}
}
if (dock !== 'top') {
if (edges & maskB) { // if (not touching the bottom edge)
b = item.border;
} else {
b = ownerBorder;
if (b !== false) {
edgesTouched += maskB;
}
}
if (b === false) {
mask += maskB;
}
}
if (dock !== 'right') {
if (edges & maskL) { // if (not touching the left edge)
b = item.border;
} else {
b = ownerBorder;
if (b !== false) {
edgesTouched += maskL;
}
}
if (b === false) {
mask += maskL;
}
}
if ((lastValue = item.lastBorderMask) !== mask) {
item.lastBorderMask = mask;
if (lastValue) {
removeCls[0] = noBorderCls[lastValue];
}
if (mask) {
addCls[0] = noBorderCls[mask];
}
}
if ((lastValue = item.lastBorderCollapse) !== edgesTouched) {
item.lastBorderCollapse = edgesTouched;
if (lastValue) {
removeCls[removeCls.length] = borderCls[lastValue];
}
if (edgesTouched) {
addCls[addCls.length] = borderCls[edgesTouched];
}
}
if (removeCls.length) {
item.removeCls(removeCls);
}
if (addCls.length) {
item.addCls(addCls);
}
// mask can use += but edges must use |= because there can be multiple items
// on an edge but the mask is reset per item
edges |= edgeMasks[dock]; // = T, R, B or L (8, 4, 2 or 1)
}
mask = edgesTouched = 0;
addCls.length = 0;
removeCls.length = 0;
if (edges & maskT) { // if (not touching the top edge)
b = bodyBorder;
} else {
b = ownerBorder;
if (b !== false) {
edgesTouched += maskT;
}
}
if (b === false) {
mask += maskT;
}
if (edges & maskR) { // if (not touching the right edge)
b = bodyBorder;
} else {
b = ownerBorder;
if (b !== false) {
edgesTouched += maskR;
}
}
if (b === false) {
mask += maskR;
}
if (edges & maskB) { // if (not touching the bottom edge)
b = bodyBorder;
} else {
b = ownerBorder;
if (b !== false) {
edgesTouched += maskB;
}
}
if (b === false) {
mask += maskB;
}
if (edges & maskL) { // if (not touching the left edge)
b = bodyBorder;
} else {
b = ownerBorder;
if (b !== false) {
edgesTouched += maskL;
}
}
if (b === false) {
mask += maskL;
}
if ((lastValue = me.lastBodyBorderMask) !== mask) {
me.lastBodyBorderMask = mask;
if (lastValue) {
removeCls[0] = noBorderCls[lastValue];
}
if (mask) {
addCls[0] = noBorderCls[mask];
}
}
if ((lastValue = me.lastBodyBorderCollapse) !== edgesTouched) {
me.lastBodyBorderCollapse = edgesTouched;
if (lastValue) {
removeCls[removeCls.length] = borderCls[lastValue];
}
if (edgesTouched) {
addCls[addCls.length] = borderCls[edgesTouched];
}
}
if (removeCls.length) {
owner.removeBodyCls(removeCls);
}
if (addCls.length) {
owner.addBodyCls(addCls);
}
},
onRemove: function (item) {
var lastBorderMask = item.lastBorderMask;
if (!item.isDestroyed && !item.ignoreBorderManagement && lastBorderMask) {
item.lastBorderMask = 0;
item.removeCls(this.noBorderClassTable[lastBorderMask]);
}
this.callParent([item]);
}
});
Ext.define('ExtThemeNeptune.panel.Panel', {
override: 'Ext.panel.Panel',
border: false,
bodyBorder: false,
initBorderProps: Ext.emptyFn,
initBodyBorder: function() {
// The superclass method converts a truthy bodyBorder into a number and sets
// an inline border-width style on the body element. This prevents that from
// happening if borderBody === true so that the body will get its border-width
// the stylesheet.
if (this.bodyBorder !== true) {
this.callParent();
}
}
});
Ext.define('ExtThemeNeptune.panel.Table', {
override: 'Ext.panel.Table',
initComponent: function() {
var me = this;
if (!me.hasOwnProperty('bodyBorder') && !me.hideHeaders) {
me.bodyBorder = true;
}
me.callParent();
}
});
Ext.define('ExtThemeNeptune.container.ButtonGroup', {
override: 'Ext.container.ButtonGroup',
usePlainButtons: false
});
Ext.define('Ext.touch.sizing.form.trigger.Spinner', {
override: 'Ext.form.trigger.Spinner',
vertical: false
});
Ext.define('ExtThemeNeptune.toolbar.Paging', {
override: 'Ext.toolbar.Paging',
defaultButtonUI: 'plain-toolbar',
inputItemWidth: 40
});
Ext.define('ExtThemeNeptune.picker.Month', {
override: 'Ext.picker.Month',
// Monthpicker contains logic that reduces the margins of the month items if it detects
// that the text has wrapped. This can happen in the classic theme in certain
// locales such as zh_TW. In order to work around this, Month picker measures
// the month items to see if the height is greater than "measureMaxHeight".
// In neptune the height of the items is larger, so we must increase this value.
// While the actual height of the month items in neptune is 24px, we will only
// determine that the text has wrapped if the height of the item exceeds 36px.
// this allows theme developers some leeway to increase the month item size in
// a neptune-derived theme.
measureMaxHeight: 36
});
Ext.define('ExtThemeNeptune.form.field.HtmlEditor', {
override: 'Ext.form.field.HtmlEditor',
defaultButtonUI: 'plain-toolbar'
});
Ext.define('ExtThemeNeptune.grid.RowEditor', {
override: 'Ext.grid.RowEditor',
buttonUI: 'default-toolbar'
});
Ext.define('ExtThemeNeptune.grid.column.RowNumberer', {
override: 'Ext.grid.column.RowNumberer',
width: 25
});
Ext.define('ExtThemeNeptune.menu.Separator', {
override: 'Ext.menu.Separator',
border: true
});
Ext.define('ExtThemeNeptune.menu.Menu', {
override: 'Ext.menu.Menu',
showSeparator: false
});
Ext.define('Ext.touch.sizing.grid.plugin.RowExpander', {
override: 'Ext.grid.plugin.RowExpander',
headerWidth: 32
});
Ext.define('Ext.touch.sizing.selection.CheckboxModel', {
override: 'Ext.selection.CheckboxModel',
headerWidth: 32
});
| ybbkd2/publicweb | web/ext/packages/ext-theme-neptune-touch/build/ext-theme-neptune-touch-debug.js | JavaScript | gpl-2.0 | 12,553 |
var searchData=
[
['queue_2ec',['queue.c',['../queue_8c.html',1,'']]],
['queue_2eh',['queue.h',['../queue_8h.html',1,'']]]
];
| eduardocrn/tp1HellFireOs | usr/doc/doxygen/html/search/files_71.js | JavaScript | gpl-2.0 | 130 |
define(['app'], function (app) {
app.controller('FloorplanController', ['$scope', '$rootScope', '$location', '$window', '$http', '$interval', '$timeout', '$compile', 'permissions', function ($scope, $rootScope, $location, $window, $http, $interval, $timeout, $compile, permissions) {
$scope.debug = 0;
$scope.floorPlans;
$scope.FloorplanCount;
$scope.actFloorplan;
$scope.browser = "unknown";
$scope.lastUpdateTime = 0;
$scope.isScrolling = false; // used on tablets & phones
$scope.pendingScroll = false; // used on tablets & phones
$scope.lastTouch = 0; // used on tablets & phones
$scope.makeHTMLnode = function (tag, attrs) {
var el = document.createElement(tag);
for (var k in attrs) el.setAttribute(k, attrs[k]);
return el;
}
function FPtouchstart(e) { $scope.isScrolling = false; };
function FPtouchmove(e) { $scope.isScrolling = true; };
function FPtouchend(e) {
// Handle events on navigation elements
if (e.target.getAttribute('related') != null) {
$("#BulletImages").children().css({ 'display': 'none' });
if ($scope.debug > 0) $.cachenoty = generate_noty('info', '<b>Scrolling to: ' + e.target.getAttribute('related') + '</b>', 1000);
e.preventDefault();
ScrollFloorplans(e.target.getAttribute('related'));
}
else
// otherwise do scrolling stuff
{
if ($scope.isScrolling == true) {
$scope.isScrolling = false;
$scope.pendingScroll = true;
$timeout(function () {
if (($scope.isScrolling == false) && ($scope.pendingScroll == true)) {
if ($scope.debug > 0) $.cachenoty = generate_noty('info', '<b>Scrolled to: ' + window.pageXOffset + '</b>', 1000);
$scope.pendingScroll = false;
var nearestFP = $('.imageparent:first');
$('.imageparent').each(function () {
var offset = Math.abs(window.pageXOffset - $(this).offset().left);
if (offset < Math.abs(window.pageXOffset - nearestFP.offset().left)) {
nearestFP = $(this);
}
});
if ($scope.debug > 0) $.cachenoty = generate_noty('info', '<b>Closest is: ' + nearestFP.attr('id') + '</b>', 1000);
ScrollFloorplans(nearestFP.attr('id'), true);
}
}, 50);
}
else // if not scrolling look for double tap
{
var delta = (new Date()).getTime() - $scope.lastTouch;
var delay = 500;
if ($scope.debug > 0) $.cachenoty = generate_noty('info', '<b>Tap Delta: ' + delta + '</b>', 1000);
if (delta < delay && delta > 0) {
$scope.doubleClick();
}
$scope.lastTouch = (new Date()).getTime();
}
}
};
ScrollFloorplans = function (tagName, animate) {
if ($scope.debug > 0) $.cachenoty = generate_noty('info', '<b>Scrolling to: ' + tagName + '</b>', 1000);
var allowAnimation = $.myglobals.AnimateTransitions;
if (arguments.length > 1) {
allowAnimation = animate;
}
var target = document.getElementById(tagName);
if (target != null) {
for (var i = 0, len = $scope.floorPlans.length; i < len; i++) {
if ($scope.floorPlans[i].idx == target.getAttribute("index")) {
if (allowAnimation == false) {
window.scrollTo($("#floorplancontent").width() * i, 0);
} else {
var from = { property: window.pageXOffset }; // starting position is current scrolled amount
var to = { property: $("#floorplancontent").width() * i };
jQuery(from).animate(to, { duration: 500, easing: 'easeOutQuint', step: function (val) { window.scrollTo(val, 0); } });
}
$(".bulletSelected").attr('class', 'bullet');
var bullet = $(".bullet")[i];
if (bullet !== undefined) {
bullet.setAttribute('class', 'bulletSelected');
}
$scope.actFloorplan = i;
break;
}
}
}
$("#copyright").attr("style", "position:fixed");
}
ImgLoaded = function (tagName) {
var target = document.getElementById(tagName + '_img');
if (target != null) {
for (var i = 0, len = $scope.floorPlans.length; i < len; i++) {
if ($scope.floorPlans[i].idx == target.parentNode.getAttribute("index")) {
$scope.floorPlans[i].xImageSize = target.naturalWidth;
$scope.floorPlans[i].yImageSize = target.naturalHeight;
$scope.floorPlans[i].Loaded = true;
// Image has loaded, now load it into SVG
var svgCont = document.getElementById(tagName + '_svg');
svgCont.setAttribute("viewBox", "0 0 " + target.naturalWidth + " " + target.naturalHeight);
svgCont.appendChild(makeSVGnode('g', { id: tagName + '_grp', transform: 'translate(0,0) scale(1)', style: "", zoomed: "false" }, ''));
svgCont.childNodes[0].appendChild(makeSVGnode('image', { width: "100%", height: "100%", "xlink:href": $scope.floorPlans[i].Image }, ''));
svgCont.childNodes[0].appendChild(makeSVGnode('g', { id: tagName + '_Content', 'class': 'FloorContent' }, ''));
svgCont.childNodes[0].appendChild(makeSVGnode('g', { id: tagName + '_Rooms', 'class': 'FloorRooms' }, ''));
svgCont.childNodes[0].appendChild(makeSVGnode('g', { id: tagName + '_Devices', transform: 'scale(1)' }, ''));
svgCont.setAttribute("style", "display:inline; position: relative;");
target.parentNode.removeChild(target);
$scope.ShowRooms(i);
break;
}
}
// kick off periodic refresh once all images have loaded
var AllLoaded = true;
for (var i = 0, len = $scope.floorPlans.length; i < len; i++) {
if ($scope.floorPlans[i].Loaded != true) {
AllLoaded = false;
break;
}
}
if (AllLoaded == true) {
Device.checkDefs();
$(".FloorRooms").click(function (event) { $scope.RoomClick(event) });
$scope.mytimer = $interval(function () { RefreshFPDevices(false); }, 10000);
$scope.FloorplanResize();
}
}
else generate_noty('error', '<b>ImageLoaded Error</b><br>Element not found: ' + tagName, false);
}
$scope.FloorplanResize = function () {
if (typeof $("#floorplancontent") != 'undefined') {
var wrpHeight = $window.innerHeight;
// when the small menu bar is displayed main-view jumps to the top so force it down
if ($(".navbar").css('display') != 'none') {
$("#floorplancontent").offset({ top: $(".navbar").height() });
wrpHeight = $window.innerHeight - $("#floorplancontent").offset().top - (($("#copyright").css('display') == 'none') ? 0 : $("#copyright").height()) - 52;
}
else {
$("#floorplancontent").offset({ top: 0 });
}
$("#floorplancontent").width($("#main-view").width()).height(wrpHeight);
if ($scope.debug > 0) $.cachenoty = generate_noty('info', '<b>Window: ' + $window.innerWidth + 'x' + $window.innerHeight + '</b><br/><b>View: ' + $("#floorplancontent").width() + 'x' + wrpHeight + '</b>', 10000);
$(".imageparent").each(function (i) { $("#" + $(this).attr('id') + '_svg').width($("#floorplancontent").width()).height(wrpHeight); });
if ($scope.FloorplanCount > 1) {
$("#BulletGroup:first").css("left", ($window.innerWidth - $("#BulletGroup:first").width()) / 2)
.css("bottom", ($("#copyright").css('display') == 'none') ? 10 : $("#copyright").height() + 10)
.css("display", "inline");
}
if (typeof $scope.actFloorplan != 'undefined') ScrollFloorplans($scope.floorPlans[$scope.actFloorplan].tagName, false);
}
}
$scope.animateMove = function (svgFloor) {
var element = $("#" + svgFloor)[0];
var oTransform = new Transform(element);
if (element.style.paddingLeft != '') {
oTransform.xOffset = parseInt(element.style.paddingLeft.replace("px", "").replace(";", "")) * -1;
}
if (element.style.paddingTop != '') {
oTransform.yOffset = parseInt(element.style.paddingTop.replace("px", "").replace(";", "")) * -1;
}
if (element.style.paddingRight != '') {
oTransform.scale = parseFloat(element.style.paddingRight.replace("px", "").replace(";", ""));
}
$("#" + svgFloor)[0].setAttribute('transform', oTransform.toString());
}
$scope.doubleClick = function () {
if ($.myglobals.FullscreenMode == true) {
if ($("#fpwrapper").attr('fullscreen') != 'true') {
if ($scope.debug > 1) $.cachenoty = generate_noty('info', '<b>Double Click -> Fullscreen!!</b>', 1000);
$('#copyright').css({ display: 'none' });
$('.navbar').css({ display: 'none' });
$("#fpwrapper").css({ position: 'absolute', top: 0, left: 0 }).attr('fullscreen', 'true');
} else {
if ($scope.debug > 1) $.cachenoty = generate_noty('info', '<b>Double Click <- Fullscreen!!</b>', 1000);
$('#copyright').css({ display: 'block' });
$('.navbar').css({ display: 'block' });
$("#fpwrapper").css({ position: 'relative' }).attr('fullscreen', 'false');
}
$scope.FloorplanResize();
}
else {
$.cachenoty = generate_noty('warning', '<b>' + $.t('Fullscreen mode is disabled') + '</b>', 3000);
}
}
$scope.RoomClick = function (click) {
$('.DeviceDetails').css('display', 'none'); // hide all popups
var borderRect = click.target.getBBox(); // polygon bounding box
var margin = 0.1; // 10% margin around polygon
var marginX = borderRect.width * margin;
var marginY = borderRect.height * margin;
var scaleX = $scope.floorPlans[$scope.actFloorplan].xImageSize / (borderRect.width + (marginX * 2));
var scaleY = $scope.floorPlans[$scope.actFloorplan].yImageSize / (borderRect.height + (marginY * 2));
var scale = ((scaleX > scaleY) ? scaleY : scaleX);
var svgFloor = click.target.parentNode.parentNode.getAttribute("id");
if ($("#" + svgFloor).attr('zoomed') == "true") {
if ($.myglobals.AnimateTransitions) {
$("#" + svgFloor).css('paddingTop', (borderRect.y - marginY)).css('paddingLeft', (borderRect.x - marginX)).css('paddingRight', scale)
.animate({
paddingTop: 0,
paddingLeft: 0,
paddingRight: 1.0
},
{
duration: 300,
progress: function (animation, progress, remainingMs) { $scope.animateMove(svgFloor); },
always: function () {
$("#" + svgFloor).attr("zoomed", "false")
.css('paddingTop', '').css('paddingLeft', '').css('paddingRight', '')
.attr("transform", 'translate(0,0) scale(1)');
}
});
}
else {
$("#" + svgFloor).attr('zoomed', 'false')
.css('paddingTop', '').css('paddingLeft', '').css('paddingRight', '')
.attr("transform", "translate(0,0) scale(1)");
}
}
else {
var attr = 'scale(' + scale + ')' + ' translate(' + (borderRect.x - marginX) * -1 + ',' + (borderRect.y - marginY) * -1 + ')';
if ($.myglobals.AnimateTransitions) {
$("#" + svgFloor).css('paddingTop', 0).css('paddingLeft', 0).css('paddingRight', 1)
.animate({
paddingTop: (borderRect.y - marginY),
paddingLeft: (borderRect.x - marginX),
paddingRight: scale
},
{
duration: 300,
progress: function (animation, progress, remainingMs) { $scope.animateMove(svgFloor); },
always: function () {
$("#" + svgFloor).attr("zoomed", "true")
.css('paddingTop', '').css('paddingLeft', '').css('paddingRight', '')
.attr("transform", attr);
}
});
}
else {
// this actually needs to centre in the direction its not scaling but close enough for v1.0
$("#" + svgFloor)[0].setAttribute("transform", attr);
$("#" + svgFloor).attr("zoomed", "true");
}
}
}
RefreshFPDevices = function (pOneOff) {
var bOneOff = true;
if (arguments.length > 1) {
bOneOff = pOneOff;
}
if ((bOneOff != true) && (typeof $scope.mytimer != 'undefined')) {
$interval.cancel($scope.mytimer);
$scope.mytimer = undefined;
}
$http({
url: "json.htm?type=devices&filter=all&used=true&order=Name&lastupdate=" + $scope.lastUpdateTime
}).then(function successCallback(response) {
var data = response.data;
if (typeof data.ActTime != 'undefined') {
$scope.lastUpdateTime = data.ActTime;
}
// update devices that already exist in the DOM
if (typeof data.result != 'undefined') {
$.each(data.result, function (i, item) {
var compoundDevice = (item.Type.indexOf('+') >= 0);
item.Scale = $scope.floorPlans[$scope.actFloorplan].scaleFactor;
$(".Device_" + item.idx).each(function () {
var aSplit = $(this).attr("id").split("_");
item.FloorID = aSplit[1];
item.PlanID = aSplit[2];
if (compoundDevice) {
item.Type = aSplit[0]; // handle multi value sensors (Baro, Humidity, Temp etc)
item.CustomImage = 1;
item.Image = aSplit[0].toLowerCase();
}
try {
var dev = Device.create(item);
var existing = document.getElementById(dev.uniquename);
if (existing != undefined) {
if ($scope.debug > 2) $.cachenoty = generate_noty('info', '<b>Refreshing Device ' + dev.name + ((compoundDevice) ? ' - ' + item.Type : '') + '</b>', 2000);
dev.htmlMinimum(existing.parentNode);
}
}
catch (err) {
$.cachenoty = generate_noty('error', '<b>Device refresh error</b> ' + dev.name + '<br>' + err, 5000);
}
});
});
}
if (bOneOff != true) {
$scope.mytimer = $interval(function () { RefreshFPDevices(false); }, 10000);
}
}, function errorCallback(response) {
if (bOneOff != true) {
$scope.mytimer = $interval(function () { RefreshFPDevices(false); }, 10000);
}
});
}
$scope.ShowFPDevices = function (floorIdx) {
$http({
url: "json.htm?type=devices&filter=all&used=true&order=Name&floor=" + $scope.floorPlans[floorIdx].idx
}).then(function successCallback(response) {
var data = response.data;
if ((typeof data.ActTime != 'undefined') && ($scope.lastUpdateTime == 0)) {
$scope.lastUpdateTime = data.ActTime;
}
// insert devices into the document
var dev;
if (typeof data.result != 'undefined') {
var elDevices = document.getElementById($scope.floorPlans[floorIdx].tagName + '_Devices');
var elIcons = makeSVGnode('g', { id: 'DeviceIcons' }, '');
elDevices.appendChild(elIcons);
var elDetails = makeSVGnode('g', { id: 'DeviceDetails' }, '');
elDevices.appendChild(elDetails);
$.each(data.result, function (i, item) {
item.Scale = $scope.floorPlans[floorIdx].scaleFactor;
item.FloorID = $scope.floorPlans[floorIdx].floorID;
if (item.Type.indexOf('+') >= 0) {
var aDev = item.Type.split('+');
var k;
for (k = 0; k < aDev.length; k++) {
var sDev = aDev[k].trim();
item.Name = ((k == 0) ? item.Name : sDev);
item.Type = sDev;
item.CustomImage = 1;
item.Image = sDev.toLowerCase();
item.XOffset = Math.abs(item.XOffset) + ((k == 0) ? 0 : (50 * $scope.floorPlans[floorIdx].scaleFactor));
dev = Device.create(item);
if (dev.onFloorplan == true) {
try {
dev.htmlMinimum(elDevices);
}
catch (err) {
generate_noty('error', '<b>Device draw error</b><br>' + err, false);
}
}
}
}
else {
dev = Device.create(item);
if (dev.onFloorplan == true) {
try {
dev.htmlMinimum(elDevices);
}
catch (err) {
generate_noty('error', '<b>Device draw error</b><br>' + err, false);
}
}
}
});
elIcons.setAttribute("id", $scope.floorPlans[floorIdx].tagName + '_Icons');
elDetails.setAttribute("id", $scope.floorPlans[floorIdx].tagName + '_Details');
}
});
}
$scope.ShowRooms = function (floorIdx) {
$http({
url: "json.htm?type=command¶m=getfloorplanplans&idx=" + $scope.floorPlans[floorIdx].idx
}).then(function successCallback(response) {
var data = response.data;
if (typeof data.result != 'undefined') {
$.each(data.result, function (i, item) {
$("#" + $scope.floorPlans[floorIdx].tagName + '_Rooms').append(makeSVGnode('polygon', { id: item.Name, 'class': 'hoverable', points: item.Area }, item.Name));
});
if ((typeof $.myglobals.RoomColour != 'undefined') &&
(typeof $.myglobals.InactiveRoomOpacity != 'undefined')) {
$(".hoverable").css({ 'fill': $.myglobals.RoomColour, 'fill-opacity': $.myglobals.InactiveRoomOpacity / 100 });
}
if (typeof $.myglobals.ActiveRoomOpacity != 'undefined') {
$(".hoverable").hover(function () { $(this).css({ 'fill-opacity': $.myglobals.ActiveRoomOpacity / 100 }) },
function () { $(this).css({ 'fill-opacity': $.myglobals.InactiveRoomOpacity / 100 }) });
}
}
});
$scope.ShowFPDevices(floorIdx);
}
ShowFloorplans = function (floorIdx) {
if (typeof $scope.mytimer != 'undefined') {
$interval.cancel($scope.mytimer);
$scope.mytimer = undefined;
}
var htmlcontent = "";
htmlcontent += $('#fphtmlcontent').html();
$('#floorplancontent').html($compile(htmlcontent)($scope));
$('#floorplancontent').i18n();
Device.useSVGtags = true;
Device.backFunction = 'ShowFloorplans';
Device.switchFunction = 'RefreshFPDevices';
Device.contentTag = 'floorplancontent';
Device.xImageSize = 1280;
Device.yImageSize = 720;
Device.checkDefs();
//Get initial floorplans
$http({
url: "json.htm?type=floorplans", async: false
}).then(function successCallback(response) {
var data = response.data;
if (typeof data.result != 'undefined') {
if (typeof $scope.actFloorplan == "undefined") {
$scope.FloorplanCount = data.result.length;
$scope.floorPlans = data.result;
$scope.actFloorplan = 0;
$scope.browser = "unknown";
} else {
if ($scope.debug > 0) $.cachenoty = generate_noty('info', '<b>Floorplan already set to: ' + $scope.actFloorplan + '</b>', 5000);
}
// handle settings
if (typeof data.AnimateZoom != 'undefined') {
$.myglobals.AnimateTransitions = (data.AnimateZoom != 0);
}
if (typeof data.FullscreenMode != 'undefined') {
$.myglobals.FullscreenMode = (data.FullscreenMode != 0);
}
if (typeof data.RoomColour != 'undefined') {
$.myglobals.RoomColour = data.RoomColour;
}
if (typeof data.ActiveRoomOpacity != 'undefined') {
$.myglobals.ActiveRoomOpacity = data.ActiveRoomOpacity;
}
if (typeof data.InactiveRoomOpacity != 'undefined') {
$.myglobals.InactiveRoomOpacity = data.InactiveRoomOpacity;
}
if (typeof data.PopupDelay != 'undefined') {
Device.popupDelay = data.PopupDelay;
}
if (typeof data.ShowSensorValues != 'undefined') {
Device.showSensorValues = (data.ShowSensorValues == 1);
}
if (typeof data.ShowSwitchValues != 'undefined') {
Device.showSwitchValues = (data.ShowSwitchValues == 1);
}
if (typeof data.ShowSceneNames != 'undefined') {
Device.showSceneNames = (data.ShowSceneNames == 1);
}
//Lets start
$.each(data.result, function (i, item) {
var tagName = item.Name.replace(/\s/g, '_') + "_" + item.idx;
$scope.floorPlans[i].floorID = item.idx;
$scope.floorPlans[i].xImageSize = 0;
$scope.floorPlans[i].yImageSize = 0;
$scope.floorPlans[i].scaleFactor = item.ScaleFactor;
$scope.floorPlans[i].Name = item.Name;
$scope.floorPlans[i].tagName = tagName;
$scope.floorPlans[i].Image = item.Image;
$scope.floorPlans[i].Loaded = false;
var thisFP = $scope.makeHTMLnode('div', { id: $scope.floorPlans[i].tagName, index: item.idx, order: item.Order, style: 'display:inline;', 'class': 'imageparent' })
$("#fpwrapper").append(thisFP);
thisFP.appendChild($scope.makeHTMLnode('img', { id: $scope.floorPlans[i].tagName + '_img', 'src': item.Image, align: 'top', 'onload': "ImgLoaded('" + $scope.floorPlans[i].tagName + "');", class: 'floorplan', style: "display:none" }));
thisFP.appendChild(makeSVGnode('svg', { id: tagName + '_svg', width: "100%", height: "100%", version: "1.1", xmlns: "http://www.w3.org/2000/svg", 'xmlns:xlink': "http://www.w3.org/1999/xlink", viewBox: "0 0 0 0", preserveAspectRatio: "xMidYMid meet", overflow: "hidden", style: "display:none" }, ''));
if ($scope.FloorplanCount > 1) {
var bulletTd = $scope.makeHTMLnode('td', { 'class': "bulletcell", "width": 100 / $scope.FloorplanCount + "%" });
$("#BulletRow:first").append(bulletTd);
bulletTd.appendChild($scope.makeHTMLnode('div', { 'class': "bullet", title: item.Name, related: $scope.floorPlans[i].tagName }));
$("#BulletImages").append($scope.makeHTMLnode('img', { id: $scope.floorPlans[i].tagName + '_bullet', 'src': item.Image, related: $scope.floorPlans[i].tagName }));
}
});
}
$(".bulletcell").hover(function () {
$(this).children().css({ 'background': $.myglobals.RoomColour });
$("#" + $(this).children().attr('related') + "_bullet").css({ 'display': 'inline' });
},
function () {
$(this).children().css({ 'background': '' });
$("#" + $(this).children().attr('related') + "_bullet").css({ 'display': 'none' });
})
.mouseup(function () {
$("#BulletImages").children().css({ 'display': 'none' });
ScrollFloorplans($(this).children().attr('related'));
});
if ((typeof $.myglobals.RoomColour != 'undefined') &&
(typeof $.myglobals.InactiveRoomOpacity != 'undefined')) {
$(".hoverable").css({ 'fill': $.myglobals.RoomColour, 'fill-opacity': $.myglobals.InactiveRoomOpacity / 100 });
}
if (typeof $.myglobals.ActiveRoomOpacity != 'undefined') {
$(".hoverable").hover(function () { $(this).css({ 'fill-opacity': $.myglobals.ActiveRoomOpacity / 100 }) },
function () { $(this).css({ 'fill-opacity': $.myglobals.InactiveRoomOpacity / 100 }) });
}
// Hide menus if query string contains 'fullscreen'
if (window.location.href.search("fullscreen") > 0) {
$scope.doubleClick();
}
$("#fpwrapper").dblclick(function () { $scope.doubleClick(); })
.attr('fullscreen', ($(".navbar").css('display') == 'none') ? 'true' : 'false');
});
$(window).resize(function () { $scope.FloorplanResize(); });
document.addEventListener('touchstart', FPtouchstart, false);
document.addEventListener('touchmove', FPtouchmove, false);
document.addEventListener('touchend', FPtouchend, false);
$("body").css('overflow', 'hidden')
.on('pageexit', function () {
document.removeEventListener('touchstart', FPtouchstart);
document.removeEventListener('touchmove', FPtouchmove);
document.removeEventListener('touchend', FPtouchend);
$(window).off('resize');
$("body").off('pageexit').css('overflow', '');
//Make vertical scrollbar disappear
$("#fpwrapper").attr("style", "display:none;");
$("#floorplancontent").addClass("container ng-scope").attr("style", "");
//Move nav bar with Back and Report button down
if ($(".navbar").css('display') != 'none') {
$("#floorplancontent").offset({ top: $(".navbar").height() });
}
else {
$("#floorplancontent").offset({ top: 0 });
}
$("#copyright").attr("style", "position:absolute");
if ($scope.debug > 0) $.cachenoty = generate_noty('info', '<b>PageExit code executed</b>', 2000);
});
}
init();
function init() {
try {
$scope.MakeGlobalConfig();
ShowFloorplans();
}
catch (err) {
generate_noty('error', '<b>Error Initialising Page</b><br>' + err, false);
}
};
$scope.$on('$destroy', function () {
if (typeof $scope.mytimer != 'undefined') {
$interval.cancel($scope.mytimer);
$scope.mytimer = undefined;
}
$("body").trigger("pageexit");
});
}]);
}); | jjalling/domoticz | www/app/FloorplanController.js | JavaScript | gpl-3.0 | 23,614 |
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'justify', 'zh-cn', {
block: '两端对齐',
center: '居中',
left: '左对齐',
right: '右对齐'
} );
| gmuro/dolibarr | htdocs/includes/ckeditor/ckeditor/_source/plugins/justify/lang/zh-cn.js | JavaScript | gpl-3.0 | 279 |
// DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py.
// OffscreenCanvas test in a worker:2d.shadow.attributes.shadowBlur.initial
// Description:
// Note:
importScripts("/resources/testharness.js");
importScripts("/html/canvas/resources/canvas-tests.js");
var t = async_test("");
var t_pass = t.done.bind(t);
var t_fail = t.step_func(function(reason) {
throw reason;
});
t.step(function() {
var offscreenCanvas = new OffscreenCanvas(100, 50);
var ctx = offscreenCanvas.getContext('2d');
_assertSame(ctx.shadowBlur, 0, "ctx.shadowBlur", "0");
t.done();
});
done();
| scheib/chromium | third_party/blink/web_tests/external/wpt/html/canvas/offscreen/shadows/2d.shadow.attributes.shadowBlur.initial.worker.js | JavaScript | bsd-3-clause | 598 |
(function($) {
"use strict"; // Start of use strict
// jQuery for page scrolling feature - requires jQuery Easing plugin
$(document).on('click', 'a.page-scroll', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: ($($anchor.attr('href')).offset().top - 50)
}, 1250, 'easeInOutExpo');
event.preventDefault();
});
// Highlight the top nav as scrolling occurs
$('body').scrollspy({
target: '#mainNav',
offset: 54
});
// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse>ul>li>a').click(function() {
$('.navbar-collapse').collapse('hide');
});
// jQuery to collapse the navbar on scroll
$(window).scroll(function() {
if ($("#mainNav").offset().top > 100) {
$("#mainNav").addClass("navbar-shrink");
} else {
$("#mainNav").removeClass("navbar-shrink");
}
});
// Initialize and Configure Scroll Reveal Animation
window.sr = ScrollReveal();
sr.reveal('.sr-icons', {
duration: 600,
scale: 0.3,
distance: '0px'
}, 200);
sr.reveal('.sr-button', {
duration: 1000,
delay: 200
});
sr.reveal('.sr-contact', {
duration: 600,
scale: 0.3,
distance: '0px'
}, 300);
// Initialize and Configure Magnific Popup Lightbox Plugin
$('.popup-gallery').magnificPopup({
delegate: 'a',
type: 'image',
tLoading: 'Loading image #%curr%...',
mainClass: 'mfp-img-mobile',
gallery: {
enabled: true,
navigateByImgClick: true,
preload: [0, 1] // Will preload 0 - before current, and 1 after the current image
},
image: {
tError: '<a href="%url%">The image #%curr%</a> could not be loaded.'
}
});
})(jQuery); // End of use strict
| GCebria/AulaEspill2.0 | js/creative.js | JavaScript | mit | 1,937 |
'use strict';
var levels = require('../levels');
var times = require('../times');
var calcData = require('../data/calcdelta');
var ObjectID = require('mongodb').ObjectID;
function init (env, ctx, server) {
function websocket ( ) {
return websocket;
}
//var log_yellow = '\x1B[33m';
var log_green = '\x1B[32m';
var log_magenta = '\x1B[35m';
var log_reset = '\x1B[0m';
var LOG_WS = log_green + 'WS: ' + log_reset;
var LOG_DEDUP = log_magenta + 'DEDUPE: ' + log_reset;
var io;
var watchers = 0;
var lastData = {};
var lastProfileSwitch = null;
// TODO: this would be better to have somehow integrated/improved
var supportedCollections = {
'treatments' : env.treatments_collection,
'entries': env.entries_collection,
'devicestatus': env.devicestatus_collection,
'profile': env.profile_collection,
'food': env.food_collection,
'activity': env.activity_collection
};
// This is little ugly copy but I was unable to pass testa after making module from status and share with /api/v1/status
function status () {
var versionNum = 0;
var verParse = /(\d+)\.(\d+)\.(\d+)*/.exec(env.version);
if (verParse) {
versionNum = 10000 * parseInt(verParse[1]) + 100 * parseInt(verParse[2]) + 1 * parseInt(verParse[3]) ;
}
var apiEnabled = env.api_secret ? true : false;
var activeProfile = ctx.ddata.lastProfileFromSwitch;
var info = {
status: 'ok'
, name: env.name
, version: env.version
, versionNum: versionNum
, serverTime: new Date().toISOString()
, apiEnabled: apiEnabled
, careportalEnabled: apiEnabled && env.settings.enable.indexOf('careportal') > -1
, boluscalcEnabled: apiEnabled && env.settings.enable.indexOf('boluscalc') > -1
, settings: env.settings
, extendedSettings: ctx.plugins && ctx.plugins.extendedClientSettings ? ctx.plugins.extendedClientSettings(env.extendedSettings) : {}
};
if (activeProfile) {
info.activeProfile = activeProfile;
}
return info;
}
function start ( ) {
io = require('socket.io')({
'transports': ['xhr-polling'], 'log level': 0
}).listen(server, {
//these only effect the socket.io.js file that is sent to the client, but better than nothing
'browser client minification': true,
'browser client etag': true,
'browser client gzip': false
});
ctx.bus.on('teardown', function serverTeardown () {
Object.keys(io.sockets.sockets).forEach(function(s) {
io.sockets.sockets[s].disconnect(true);
});
io.close();
});
}
function verifyAuthorization (message, callback) {
ctx.authorization.resolve({ api_secret: message.secret, token: message.token }, function resolved (err, result) {
if (err) {
return callback( err, {
read: false
, write: false
, write_treatment: false
, error: true
});
}
return callback(null, {
read: ctx.authorization.checkMultiple('api:*:read', result.shiros)
, write: ctx.authorization.checkMultiple('api:*:create,update,delete', result.shiros)
, write_treatment: ctx.authorization.checkMultiple('api:treatments:create,update,delete', result.shiros)
});
});
}
function emitData (delta) {
if (lastData.cals) {
// console.log(LOG_WS + 'running websocket.emitData', ctx.ddata.lastUpdated);
if (lastProfileSwitch !== ctx.ddata.lastProfileFromSwitch) {
// console.log(LOG_WS + 'profile switch detected OLD: ' + lastProfileSwitch + ' NEW: ' + ctx.ddata.lastProfileFromSwitch);
delta.status = status(ctx.ddata.profiles);
lastProfileSwitch = ctx.ddata.lastProfileFromSwitch;
}
io.to('DataReceivers').emit('dataUpdate', delta);
}
}
function listeners ( ) {
io.sockets.on('connection', function onConnection (socket) {
var socketAuthorization = null;
var clientType = null;
var timeDiff;
var history;
var remoteIP = socket.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
console.log(LOG_WS + 'Connection from client ID: ', socket.client.id, ' IP: ', remoteIP);
io.emit('clients', ++watchers);
socket.on('ack', function onAck(level, group, silenceTime) {
ctx.notifications.ack(level, group, silenceTime, true);
});
socket.on('disconnect', function onDisconnect ( ) {
io.emit('clients', --watchers);
console.log(LOG_WS + 'Disconnected client ID: ',socket.client.id);
});
function checkConditions (action, data) {
var collection = supportedCollections[data.collection];
if (!collection) {
console.log('WS dbUpdate/dbAdd call: ', 'Wrong collection', data);
return { result: 'Wrong collection' };
}
if (!socketAuthorization) {
console.log('WS dbUpdate/dbAdd call: ', 'Not authorized', data);
return { result: 'Not authorized' };
}
if (data.collection === 'treatments') {
if (!socketAuthorization.write_treatment) {
console.log('WS dbUpdate/dbAdd call: ', 'Not permitted', data);
return { result: 'Not permitted' };
}
} else {
if (!socketAuthorization.write) {
console.log('WS dbUpdate call: ', 'Not permitted', data);
return { result: 'Not permitted' };
}
}
if (action === 'dbUpdate' && !data._id) {
console.log('WS dbUpdate/dbAddnot sure abou documentati call: ', 'Missing _id', data);
return { result: 'Missing _id' };
}
return null;
}
socket.on('loadRetro', function loadRetro (opts, callback) {
if (callback) {
callback( { result: 'success' } );
}
//TODO: use opts to only send delta for retro data
socket.emit('retroUpdate', {devicestatus: lastData.devicestatus});
console.info('sent retroUpdate', opts);
});
// dbUpdate message
// {
// collection: treatments
// _id: 'some mongo record id'
// data: {
// field_1: new_value,
// field_2: another_value
// }
// }
socket.on('dbUpdate', function dbUpdate (data, callback) {
console.log(LOG_WS + 'dbUpdate client ID: ', socket.client.id, ' data: ', data);
var collection = supportedCollections[data.collection];
var check = checkConditions('dbUpdate', data);
if (check) {
if (callback) {
callback( check );
}
return;
}
var id ;
try {
id = new ObjectID(data._id);
} catch (err){
console.error(err);
id = new ObjectID();
}
ctx.store.collection(collection).update(
{ '_id': id },
{ $set: data.data }
);
if (callback) {
callback( { result: 'success' } );
}
ctx.bus.emit('data-received');
});
// dbUpdateUnset message
// {
// collection: treatments
// _id: 'some mongo record id'
// data: {
// field_1: 1,
// field_2: 1
// }
// }
socket.on('dbUpdateUnset', function dbUpdateUnset (data, callback) {
console.log(LOG_WS + 'dbUpdateUnset client ID: ', socket.client.id, ' data: ', data);
var collection = supportedCollections[data.collection];
var check = checkConditions('dbUpdate', data);
if (check) {
if (callback) {
callback( check );
}
return;
}
var objId = new ObjectID(data._id);
ctx.store.collection(collection).update(
{ '_id': objId },
{ $unset: data.data }
);
if (callback) {
callback( { result: 'success' } );
}
ctx.bus.emit('data-received');
});
// dbAdd message
// {
// collection: treatments
// data: {
// field_1: new_value,
// field_2: another_value
// }
// }
socket.on('dbAdd', function dbAdd (data, callback) {
console.log(LOG_WS + 'dbAdd client ID: ', socket.client.id, ' data: ', data);
var collection = supportedCollections[data.collection];
var maxtimediff = times.mins(1).msecs;
var check = checkConditions('dbAdd', data);
if (check) {
if (callback) {
callback( check );
}
return;
}
if (data.collection === 'treatments' && !('eventType' in data.data)) {
data.data.eventType = '<none>';
}
if (!('created_at' in data.data)) {
data.data.created_at = new Date().toISOString();
}
// treatments deduping
if (data.collection === 'treatments') {
var query;
if (data.data.NSCLIENT_ID) {
query = { NSCLIENT_ID: data.data.NSCLIENT_ID };
} else {
query = {
created_at: data.data.created_at
, eventType: data.data.eventType
};
}
// try to find exact match
ctx.store.collection(collection).find(query).toArray(function findResult (err, array) {
if (err || array.length > 0) {
console.log(LOG_DEDUP + 'Exact match');
if (callback) {
callback([array[0]]);
}
return;
}
var selected = false;
var query_similiar = {
created_at: {$gte: new Date(new Date(data.data.created_at).getTime() - maxtimediff).toISOString(), $lte: new Date(new Date(data.data.created_at).getTime() + maxtimediff).toISOString()}
};
if (data.data.insulin) {
query_similiar.insulin = data.data.insulin;
selected = true;
}
if (data.data.carbs) {
query_similiar.carbs = data.data.carbs;
selected = true;
}
if (data.data.percent) {
query_similiar.percent = data.data.percent;
selected = true;
}
if (data.data.absolute) {
query_similiar.absolute = data.data.absolute;
selected = true;
}
if (data.data.duration) {
query_similiar.duration = data.data.duration;
selected = true;
}
if (data.data.NSCLIENT_ID) {
query_similiar.NSCLIENT_ID = data.data.NSCLIENT_ID;
selected = true;
}
// if none assigned add at least eventType
if (!selected) {
query_similiar.eventType = data.data.eventType;
}
// try to find similiar
ctx.store.collection(collection).find(query_similiar).toArray(function findSimiliarResult (err, array) {
// if found similiar just update date. next time it will match exactly
if (err || array.length > 0) {
console.log(LOG_DEDUP + 'Found similiar', array[0]);
array[0].created_at = data.data.created_at;
var objId = new ObjectID(array[0]._id);
ctx.store.collection(collection).update(
{ '_id': objId },
{ $set: {created_at: data.data.created_at} }
);
if (callback) {
callback([array[0]]);
}
ctx.bus.emit('data-received');
return;
}
// if not found create new record
console.log(LOG_DEDUP + 'Adding new record');
ctx.store.collection(collection).insert(data.data, function insertResult (err, doc) {
if (err != null && err.message) {
console.log('treatments data insertion error: ', err.message);
return;
}
if (callback) {
callback(doc.ops);
}
ctx.bus.emit('data-received');
});
});
});
// devicestatus deduping
} else if (data.collection === 'devicestatus') {
var queryDev;
if (data.data.NSCLIENT_ID) {
queryDev = { NSCLIENT_ID: data.data.NSCLIENT_ID };
} else {
queryDev = {
created_at: data.data.created_at
};
}
// try to find exact match
ctx.store.collection(collection).find(queryDev).toArray(function findResult (err, array) {
if (err || array.length > 0) {
console.log(LOG_DEDUP + 'Devicestatus exact match');
if (callback) {
callback([array[0]]);
}
return;
}
});
ctx.store.collection(collection).insert(data.data, function insertResult (err, doc) {
if (err != null && err.message) {
console.log('devicestatus insertion error: ', err.message);
return;
}
if (callback) {
callback(doc.ops);
}
ctx.bus.emit('data-received');
});
} else {
ctx.store.collection(collection).insert(data.data, function insertResult (err, doc) {
if (err != null && err.message) {
console.log(data.collection + ' insertion error: ', err.message);
return;
}
if (callback) {
callback(doc.ops);
}
ctx.bus.emit('data-received');
});
}
});
// dbRemove message
// {
// collection: treatments
// _id: 'some mongo record id'
// }
socket.on('dbRemove', function dbRemove (data, callback) {
console.log(LOG_WS + 'dbRemove client ID: ', socket.client.id, ' data: ', data);
var collection = supportedCollections[data.collection];
var check = checkConditions('dbUpdate', data);
if (check) {
if (callback) {
callback( check );
}
return;
}
var objId = new ObjectID(data._id);
ctx.store.collection(collection).remove(
{ '_id': objId }
);
if (callback) {
callback( { result: 'success' } );
}
ctx.bus.emit('data-received');
});
// Authorization message
// {
// client: 'web' | 'phone' | 'pump'
// , secret: 'secret_hash'
// [, history : history_in_hours ]
// [, status : true ]
// }
socket.on('authorize', function authorize (message, callback) {
verifyAuthorization(message, function verified (err, authorization) {
socketAuthorization = authorization;
clientType = message.client;
history = message.history || 48; //default history is 48 hours
if (socketAuthorization.read) {
socket.join('DataReceivers');
if (lastData && lastData.dataWithRecentStatuses) {
let data = lastData.dataWithRecentStatuses();
if (message.status) {
data.status = status(data.profiles);
}
socket.emit('dataUpdate', data);
}
}
// console.log(LOG_WS + 'Authetication ID: ', socket.client.id, ' client: ', clientType, ' history: ' + history);
if (callback) {
callback(socketAuthorization);
}
});
});
// Pind message
// {
// mills: <local_time_in_milliseconds>
// }
socket.on('nsping', function ping (message, callback) {
var clientTime = message.mills;
timeDiff = new Date().getTime() - clientTime;
// console.log(LOG_WS + 'Ping from client ID: ',socket.client.id, ' client: ', clientType, ' timeDiff: ', (timeDiff/1000).toFixed(1) + 'sec');
if (callback) {
callback({ result: 'pong', mills: new Date().getTime(), authorization: socketAuthorization });
}
});
});
}
websocket.update = function update ( ) {
// console.log(LOG_WS + 'running websocket.update');
if (lastData.sgvs) {
var delta = calcData(lastData, ctx.ddata);
if (delta.delta) {
// console.log('lastData full size', JSON.stringify(lastData).length,'bytes');
// if (delta.sgvs) { console.log('patientData update size', JSON.stringify(delta).length,'bytes'); }
emitData(delta);
}; // else { console.log('delta calculation indicates no new data is present'); }
}
lastData = ctx.ddata.clone();
};
websocket.emitNotification = function emitNotification (notify) {
if (notify.clear) {
io.emit('clear_alarm', notify);
console.info(LOG_WS + 'emitted clear_alarm to all clients');
} else if (notify.level === levels.WARN) {
io.emit('alarm', notify);
console.info(LOG_WS + 'emitted alarm to all clients');
} else if (notify.level === levels.URGENT) {
io.emit('urgent_alarm', notify);
console.info(LOG_WS + 'emitted urgent_alarm to all clients');
} else if (notify.isAnnouncement) {
io.emit('announcement', notify);
console.info(LOG_WS + 'emitted announcement to all clients');
} else {
io.emit('notification', notify);
console.info(LOG_WS + 'emitted notification to all clients');
}
};
start( );
listeners( );
if (ctx.storageSocket) {
ctx.storageSocket.init(io);
}
return websocket();
}
module.exports = init;
| simigit/cgm-remote-monitor | lib/server/websocket.js | JavaScript | agpl-3.0 | 17,691 |
/*
* Copyright 2015 The Closure Compiler Authors.
*
* 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 Extra externs for Jasmine when using Angular.
*
* Depends on both the angular-1.x-mocks.js and Jasmine 2.0 externs.
*
* @externs
*/
/**
* Provided by angular-mocks.js.
* @type {angular.$injector}
*/
jasmine.Spec.prototype.$injector;
/**
* Provided by angular-mocks.js.
* @param {...(Function|Array<string|Function>)} var_args
*/
function inject(var_args) {}
/**
* Provided by angular-mocks.js.
* @param {...(string|Function|Array<string|Function>|Object<string, *>)}
* var_args
* @suppress {checkTypes}
*/
function module(var_args) {}
| GoogleChromeLabs/chromeos_smart_card_connector | third_party/closure-compiler/src/contrib/externs/jasmine-angular.js | JavaScript | apache-2.0 | 1,196 |
/**
* @license
* Copyright The Closure Library Authors.
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview A utility to write alltests.js for Closure Library.
*/
const {promises: fs} = require('fs');
const CLOSURE_PATH = 'closure/goog';
const THIRD_PARTY_PATH = 'third_party/closure/goog';
const HEADER = `
/**
* @license
* Copyright The Closure Library Authors.
* SPDX-License-Identifier: Apache-2.0
*/
// This file has been auto-generated, please do not edit.
// To regenerate, run \`npm run gen_alltests_js\` in the root directory of the
// Closure Library git repository.
`.trim();
const FOOTER = `
// If we're running in a nodejs context, export tests. Used when running tests
// externally on Travis.
if (typeof module !== 'undefined' && module.exports) {
module.exports = _allTests;
}
`.trim();
/**
* Calls fs.readdir recursively on the given path and subdirectories.
* Returns only the list of files.
* @param {string} path The path to read.
* @return {!Array<string>} A list of files.
*/
async function readdirRecursive(path) {
const filesAndDirectories =
(await fs.readdir(path))
.map(fileOrDirectory => `${path}/${fileOrDirectory}`)
.sort();
const files = [];
for (const fileOrDirectory of filesAndDirectories) {
const fileStat = await fs.stat(fileOrDirectory);
if (fileStat.isDirectory()) {
files.push(...await readdirRecursive(fileOrDirectory));
} else {
files.push(fileOrDirectory);
}
}
return files;
}
/**
* Prints the generated alltests.js contents.
* @return {!Promise<number>} The exit code.
*/
async function main() {
try {
// Get a list of all *_test.html files.
const allTestHtmls = [
...await readdirRecursive(CLOSURE_PATH),
...await readdirRecursive(THIRD_PARTY_PATH),
].filter(f => f.endsWith('_test.html'));
if (allTestHtmls.length === 0) {
throw new Error(
'No *_test.html files found. Did you run `npm run gen_test_htmls`?');
}
const output = [
HEADER, '', 'var _allTests = [', ...allTestHtmls.map(f => ` '${f}',`),
'];', '', FOOTER
];
console.log(output.join('\n'));
return 0;
} catch (e) {
console.error(e);
return 1;
}
}
main().then(code => process.exit(code));
| scheib/chromium | third_party/google-closure-library/scripts/generate_alltests_js.js | JavaScript | bsd-3-clause | 2,287 |
/**
* @license
* Copyright 2018 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.
*/
const {SourceError} = require('./sourceerror');
const depGraph = require('./depgraph');
const fs = require('fs');
const {gjd} = require('./jsfile_parser');
const path = require('path');
class ParseResult {
/**
* @param {!Array<!depGraph.Dependency>} dependencies
* @param {!Array<!ParseError>} errors
* @param {!ParseResult.Source} source
*/
constructor(dependencies, errors, source) {
/** @const */
this.dependencies = dependencies;
/** @const */
this.errors = errors;
/** @const */
this.source = source;
/** @const */
this.isFromDepsFile = source === ParseResult.Source.GOOG_ADD_DEPENDENCY;
/** @const {boolean} */
this.hasFatalError = errors.some(e => e.fatal);
}
}
exports.ParseResult = ParseResult;
/**
* @enum {string}
*/
ParseResult.Source = {
/**
* Scanned from an actual source file.
*/
SOURCE_FILE: 'f',
/**
* A goog.addDependency statement.
*/
GOOG_ADD_DEPENDENCY: 'd',
};
class ParseError {
/**
* @param {boolean} fatal
* @param {string} message
* @param {string} sourceName
* @param {number} line
* @param {number} lineOffset
*/
constructor(fatal, message, sourceName, line, lineOffset) {
/** @const */
this.fatal = fatal;
/** @const */
this.message = message;
/** @const */
this.sourceName = sourceName;
/** @const */
this.line = line;
/** @const */
this.lineOffset = lineOffset;
}
/** @override */
toString() {
return `${this.fatal ? 'ERROR' : 'WARNING'} in ${this.sourceName} at ${
this.line}, ${this.lineOffset}: ${this.message}`;
}
}
exports.ParseError = ParseError;
/**
* @param {string} path
* @return {!ParseResult}
*/
const parseFile = exports.parseFile = function(path) {
return parseText(fs.readFileSync(path, 'utf8'), path);
};
/**
* @param {string} path
* @return {!Promise<!ParseResult>}
*/
const parseFileAsync = exports.parseFileAsync = async function(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf8', (err, data) => {
if (err) {
reject(err);
return;
}
try {
resolve(parseText(data, path));
} catch (e) {
reject(e);
}
});
});
};
const MultipleSymbolsInClosureModuleError =
exports.MultipleSymbolsInClosureModuleError = class extends SourceError {
/**
* @param {string} filePath
*/
constructor(filePath) {
super('Closure modules cannot contain more than one namespace.', filePath);
}
};
const MultipleSymbolsInEs6ModuleError =
exports.MultipleSymbolsInEs6ModuleError = class extends SourceError {
/**
* @param {string} filePath
*/
constructor(filePath) {
super('ES6 modules cannot contain more than one namespace.', filePath);
}
};
/**
* @return {!RegExp} A fresh regular expression object to test for
* goog.addDependnecy statements.
*/
function googAddDependency() {
return /^goog\.addDependency\('(.*?)', (\[.*?\]), (\[.*?\])(?:, ({.*}|true|false))?\);$/mg;
}
/**
* @param {string} fileContent
* @return {boolean}
*/
function isDepFile(fileContent) {
return googAddDependency().test(fileContent);
}
/**
* @param {string} closureRelativePath
* @param {string} providesText
* @param {string} requiresText
* @param {string} optionsText
* @return {!depGraph.Dependency}
*/
const parseDependencyResult = function(
closureRelativePath, providesText, requiresText, optionsText) {
const provides = JSON.parse(providesText.replace(/'/g, '"'));
const requires = JSON.parse(requiresText.replace(/'/g, '"'));
const options = optionsText ? JSON.parse(optionsText.replace(/'/g, '"')) : {};
let type = depGraph.DependencyType.SCRIPT;
if (provides.length) {
type = depGraph.DependencyType.CLOSURE_PROVIDE;
}
// true and false are legacy flags that mean a goog.module or not.
if (options === true) {
type = depGraph.DependencyType.CLOSURE_MODULE;
} else if (options !== false) {
switch (options.module) {
case 'es6':
type = depGraph.DependencyType.ES6_MODULE;
break;
case 'goog':
type = depGraph.DependencyType.CLOSURE_MODULE;
break;
default:
break;
}
}
const imports = requires.map(
// Assume if there is a slash it is an ES import, otherwise
// goog.require. Any import should have a slash, except for those inside
// the root of Closure Library (so just goog.js, which we also need to
// check for). Admittedly not 100% accurate.
(require) => require.indexOf('/') > -1 || require === 'goog.js' ?
new depGraph.Es6Import(require) :
new depGraph.GoogRequire(require));
return new depGraph.ParsedDependency(
type, closureRelativePath, provides, imports, options.lang);
};
/**
* Parses a file that contains only goog.addDependency statements. This is regex
* based to be lightweight and avoid addtional dependencies.
*
* @param {string} text
* @param {string} filePath
* @return {!ParseResult}
*/
const parseDependencyFile = function(text, filePath) {
const dependencies = [];
const errors = [];
let regexResult;
const regex = googAddDependency();
while (regexResult = regex.exec(text)) {
try {
dependencies.push(parseDependencyResult(
regexResult[1], regexResult[2], regexResult[3], regexResult[4]));
} catch (e) {
errors.push(new SourceError(e.toString(), filePath));
}
}
return new ParseResult(
dependencies, errors, ParseResult.Source.GOOG_ADD_DEPENDENCY);
};
exports.parseDependencyFile = parseDependencyFile;
/**
* @param {string} text
* @param {string} filePath
* @return {!ParseResult}
*/
const parseText = exports.parseText = function(text, filePath) {
const errors = [];
/**
* @param {boolean} fatal
* @param {string} message
* @param {string} sourceName
* @param {number} line
* @param {number} lineOffset
*/
function report(fatal, message, sourceName, line, lineOffset) {
errors.push(new ParseError(fatal, message, sourceName, line, lineOffset));
}
if (isDepFile(text)) {
return parseDependencyFile(text, filePath, report);
}
const data = gjd(text, filePath, report);
if (errors.some(e => e.fatal)) {
return new ParseResult(
[new depGraph.Dependency(
depGraph.DependencyType.SCRIPT, filePath, [], [])],
errors, ParseResult.Source.SOURCE_FILE);
}
function getLoadFlag(key, defaultValue) {
if (data.load_flags) {
for (const [k, v] of data.load_flags) {
if (key === k) {
return v;
}
}
}
return defaultValue;
}
const loadFlags = new Map(data.load_flags || []);
const module = loadFlags.get('module');
const language = loadFlags.get('lang') || 'es3';
const imports = [];
if (data.imported_modules) {
data.imported_modules.forEach(r => imports.push(new depGraph.Es6Import(r)));
}
// The special `goog` symbol is implicitly required by files that use
// goog primitives, and implicitly provided by base.js (in the output
// produced by jsfile_parser). However, it should be omitted from
// deps.js files, since the debug loader should never load base.js.
if (data.requires) {
data.requires.filter(r => r != 'goog')
.forEach(r => imports.push(new depGraph.GoogRequire(r)));
}
const provides = (data.provides || []).filter(p => p != 'goog');
let dependency;
if (module == 'es6') {
if (provides.length > 1) {
throw new MultipleSymbolsInEs6ModuleError(filePath);
}
dependency = new depGraph.Dependency(
depGraph.DependencyType.ES6_MODULE, filePath, provides, imports,
language);
} else if (module == 'goog') {
if (provides.length > 1) {
throw new MultipleSymbolsInClosureModuleError(filePath);
}
dependency = new depGraph.Dependency(
depGraph.DependencyType.CLOSURE_MODULE, filePath, provides, imports,
language);
} else if (provides.length) {
dependency = new depGraph.Dependency(
depGraph.DependencyType.CLOSURE_PROVIDE, filePath, provides, imports,
language);
} else {
dependency = new depGraph.Dependency(
depGraph.DependencyType.SCRIPT, filePath, provides, imports, language);
}
return new ParseResult([dependency], errors, ParseResult.Source.SOURCE_FILE);
};
| scheib/chromium | third_party/google-closure-library/closure-deps/lib/parser.js | JavaScript | bsd-3-clause | 9,011 |
'use strict';
exports.__esModule = true;
exports.locationShape = exports.routerShape = undefined;
var _propTypes = require('prop-types');
var routerShape = exports.routerShape = (0, _propTypes.shape)({
push: _propTypes.func.isRequired,
replace: _propTypes.func.isRequired,
go: _propTypes.func.isRequired,
goBack: _propTypes.func.isRequired,
goForward: _propTypes.func.isRequired,
setRouteLeaveHook: _propTypes.func.isRequired,
isActive: _propTypes.func.isRequired
});
var locationShape = exports.locationShape = (0, _propTypes.shape)({
pathname: _propTypes.string.isRequired,
search: _propTypes.string.isRequired,
state: _propTypes.object,
action: _propTypes.string.isRequired,
key: _propTypes.string
}); | NickingMeSpace/questionnaire | node_modules/react-router/lib/PropTypes.js | JavaScript | mit | 732 |
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var fname = process.cwd().match(/cocotte-(.*)$/)[1];
gulp.task('build', function () {
browserify('lib/' + fname + '.js')
.bundle()
.pipe(source(fname + '.min.js'))
.pipe(buffer())
.pipe(uglify({preserveComments: 'some'}))
.pipe(gulp.dest('public'));
});
gulp.task('watch', function() {
gulp.watch('lib/**/*.js', ['build']);
});
gulp.task('default', ['build', 'watch']); | yukik/cocotte-flow | gulpfile.js | JavaScript | mit | 585 |
import { tryInvoke } from 'ember-metal/utils';
var obj;
QUnit.module("Ember.tryInvoke", {
setup() {
obj = {
aMethodThatExists() { return true; },
aMethodThatTakesArguments(arg1, arg2) { return arg1 === arg2; }
};
},
teardown() {
obj = undefined;
}
});
QUnit.test("should return undefined when the object doesn't exist", function() {
equal(tryInvoke(undefined, 'aMethodThatDoesNotExist'), undefined);
});
QUnit.test("should return undefined when asked to perform a method that doesn't exist on the object", function() {
equal(tryInvoke(obj, 'aMethodThatDoesNotExist'), undefined);
});
QUnit.test("should return what the method returns when asked to perform a method that exists on the object", function() {
equal(tryInvoke(obj, 'aMethodThatExists'), true);
});
QUnit.test("should return what the method returns when asked to perform a method that takes arguments and exists on the object", function() {
equal(tryInvoke(obj, 'aMethodThatTakesArguments', [true, true]), true);
});
| mitchlloyd/ember.js | packages/ember-metal/tests/utils/try_invoke_test.js | JavaScript | mit | 1,025 |
/*!
* Copyright 2002 - 2015 Webdetails, a Pentaho company. All rights reserved.
*
* This software was developed by Webdetails and is provided under the terms
* of the Mozilla Public License, Version 2.0, or any later version. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails.
*
* Software distributed under the Mozilla Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
/*==================================================
* Common localization strings
*==================================================
*/
Timeline.strings["cs"] = {
wikiLinkLabel: "Diskuze"
};
| SteveSchafer-Innovent/innovent-pentaho-birt-plugin | js-lib/expanded/cdf/js/lib/simile/timeline/scripts/l10n/cs/timeline.js | JavaScript | epl-1.0 | 876 |
'use strict';
var TestRunner = require('test-runner');
var cliArgs = require('../../');
var a = require('core-assert');
var runner = new TestRunner();
runner.test('defaultOption: string', function () {
var optionDefinitions = [{ name: 'files', defaultOption: true }];
var argv = ['file1', 'file2'];
a.deepStrictEqual(cliArgs(optionDefinitions, argv), {
files: 'file2'
});
});
runner.test('defaultOption: multiple string', function () {
var optionDefinitions = [{ name: 'files', defaultOption: true, multiple: true }];
var argv = ['file1', 'file2'];
a.deepStrictEqual(cliArgs(optionDefinitions, argv), {
files: ['file1', 'file2']
});
});
runner.test('defaultOption: after a boolean', function () {
var definitions = [{ name: 'one', type: Boolean }, { name: 'two', defaultOption: true }];
a.deepStrictEqual(cliArgs(definitions, ['--one', 'sfsgf']), { one: true, two: 'sfsgf' });
});
runner.test('defaultOption: multiple defaultOption values between other arg/value pairs', function () {
var optionDefinitions = [{ name: 'one' }, { name: 'two' }, { name: 'files', defaultOption: true, multiple: true }];
var argv = ['--one', '1', 'file1', 'file2', '--two', '2'];
a.deepStrictEqual(cliArgs(optionDefinitions, argv), {
one: '1',
two: '2',
files: ['file1', 'file2']
});
});
runner.test('defaultOption: multiple defaultOption values between other arg/value pairs 2', function () {
var optionDefinitions = [{ name: 'one', type: Boolean }, { name: 'two' }, { name: 'files', defaultOption: true, multiple: true }];
var argv = ['file0', '--one', 'file1', '--files', 'file2', '--two', '2', 'file3'];
a.deepStrictEqual(cliArgs(optionDefinitions, argv), {
one: true,
two: '2',
files: ['file0', 'file1', 'file2', 'file3']
});
});
runner.test('defaultOption: floating args present but no defaultOption', function () {
var definitions = [{ name: 'one', type: Boolean }];
a.deepStrictEqual(cliArgs(definitions, ['aaa', '--one', 'aaa', 'aaa']), { one: true });
}); | mrkmvd/Agent21 | src/node_modules/command-line-args/es5/test/default-option.js | JavaScript | apache-2.0 | 2,025 |
var render = function (theme, data, meta, require) {
if(data.error.length == 0 ){
theme('index', {
config: [{
context: {
gadgetsUrlBase: data.config.gadgetsUrlBase
}
}],
title: [{
context:{
page_title:'AS Dashboard'
}
}],
appname: [{
context:data.appname
}],
header: [
{
partial: 'header',
context:{
user_name: 'dakshika@wso2.com ',
user_avatar:'dakshika'
}
}
],
'sub-header': [
{
partial: 'sub-header',
context:{
appname : data.appname,
aspect: data.aspect
}
}
],
left_side:[
{
partial: 'left_side',
context: {
nav: data.nav,
user_name: 'dakshika@wso2.com ',
user_avatar:'dakshika',
breadcrumb:'Service Cluster System Statistics'
}
}
],
right_side: [
{
partial: 'location',
context:{
aspect:'Location' ,
appname : data.appname,
user_name: 'dakshika@wso2.com ',
user_avatar:'dakshika',
data: data.panels,
updateInterval: data.updateInterval
}
}
]
});
}else{
theme('index', {
title: [
],
header:[
{
partial: 'header_login'
}
],
body: [
{
partial: 'error',
context:{
error: data.error
}
}
]
});
}
};
| jsdjayanga/as_bam_dashboard | themes/theme0/renderers/location.js | JavaScript | apache-2.0 | 2,282 |
define([
"jQuery",
"utils/storage",
"utils/sharing",
"utils/dropdown",
"core/events",
"core/font-settings",
"core/state",
"core/keyboard",
"core/navigation",
"core/progress",
"core/sidebar",
"core/search",
"core/glossary"
], function($, storage, sharing, dropdown, events, fontSettings, state, keyboard, navigation, progress, sidebar, search, glossary){
var start = function(config) {
var $book;
$book = state.$book;
// Init sidebar
sidebar.init();
// Load search
search.init();
// Load glossary
glossary.init();
// Init keyboard
keyboard.init();
// Bind sharing button
sharing.init();
// Bind dropdown
dropdown.init();
// Init navigation
navigation.init();
//Init font settings
fontSettings.init(config.fontSettings || {});
events.trigger("start", config);
}
return {
start: start,
events: events,
state: state
};
});
| bjlxj2008/gitbook | theme/javascript/gitbook.js | JavaScript | apache-2.0 | 1,074 |
(function($)
{
$.Redactor.prototype.table = function()
{
return {
getTemplate: function()
{
return String()
+ '<section id="redactor-modal-table-insert">'
+ '<label>' + this.lang.get('rows') + '</label>'
+ '<input type="text" size="5" value="2" id="redactor-table-rows" />'
+ '<label>' + this.lang.get('columns') + '</label>'
+ '<input type="text" size="5" value="3" id="redactor-table-columns" />'
+ '</section>';
},
init: function()
{
var dropdown = {};
dropdown.insert_table = {
title: this.lang.get('insert_table'),
func: this.table.show,
observe: {
element: 'table',
in: {
attr: {
'class': 'redactor-dropdown-link-inactive',
'aria-disabled': true,
}
}
}
};
dropdown.insert_row_above = {
title: this.lang.get('insert_row_above'),
func: this.table.addRowAbove,
observe: {
element: 'table',
out: {
attr: {
'class': 'redactor-dropdown-link-inactive',
'aria-disabled': true,
}
}
}
};
dropdown.insert_row_below = {
title: this.lang.get('insert_row_below'),
func: this.table.addRowBelow,
observe: {
element: 'table',
out: {
attr: {
'class': 'redactor-dropdown-link-inactive',
'aria-disabled': true,
}
}
}
};
dropdown.insert_row_below = {
title: this.lang.get('insert_row_below'),
func: this.table.addRowBelow,
observe: {
element: 'table',
out: {
attr: {
'class': 'redactor-dropdown-link-inactive',
'aria-disabled': true,
}
}
}
};
dropdown.insert_column_left = {
title: this.lang.get('insert_column_left'),
func: this.table.addColumnLeft,
observe: {
element: 'table',
out: {
attr: {
'class': 'redactor-dropdown-link-inactive',
'aria-disabled': true,
}
}
}
};
dropdown.insert_column_right = {
title: this.lang.get('insert_column_right'),
func: this.table.addColumnRight,
observe: {
element: 'table',
out: {
attr: {
'class': 'redactor-dropdown-link-inactive',
'aria-disabled': true,
}
}
}
};
dropdown.add_head = {
title: this.lang.get('add_head'),
func: this.table.addHead,
observe: {
element: 'table',
out: {
attr: {
'class': 'redactor-dropdown-link-inactive',
'aria-disabled': true,
}
}
}
};
dropdown.delete_head = {
title: this.lang.get('delete_head'),
func: this.table.deleteHead,
observe: {
element: 'table',
out: {
attr: {
'class': 'redactor-dropdown-link-inactive',
'aria-disabled': true,
}
}
}
};
dropdown.delete_column = {
title: this.lang.get('delete_column'),
func: this.table.deleteColumn,
observe: {
element: 'table',
out: {
attr: {
'class': 'redactor-dropdown-link-inactive',
'aria-disabled': true,
}
}
}
};
dropdown.delete_row = {
title: this.lang.get('delete_row'),
func: this.table.deleteRow,
observe: {
element: 'table',
out: {
attr: {
'class': 'redactor-dropdown-link-inactive',
'aria-disabled': true,
}
}
}
};
dropdown.delete_row = {
title: this.lang.get('delete_table'),
func: this.table.deleteTable,
observe: {
element: 'table',
out: {
attr: {
'class': 'redactor-dropdown-link-inactive',
'aria-disabled': true,
}
}
}
};
this.observe.addButton('td', 'table');
this.observe.addButton('th', 'table');
var button = this.button.addBefore('link', 'table', this.lang.get('table'));
this.button.addDropdown(button, dropdown);
},
show: function()
{
this.modal.addTemplate('table', this.table.getTemplate());
this.modal.load('table', this.lang.get('insert_table'), 300);
this.modal.createCancelButton();
var button = this.modal.createActionButton(this.lang.get('insert'));
button.on('click', this.table.insert);
this.selection.save();
this.modal.show();
$('#redactor-table-rows').focus();
},
insert: function()
{
this.placeholder.remove();
var rows = $('#redactor-table-rows').val(),
columns = $('#redactor-table-columns').val(),
$tableBox = $('<div>'),
tableId = Math.floor(Math.random() * 99999),
$table = $('<table id="table' + tableId + '"><tbody></tbody></table>'),
i, $row, z, $column;
for (i = 0; i < rows; i++)
{
$row = $('<tr>');
for (z = 0; z < columns; z++)
{
$column = $('<td>' + this.opts.invisibleSpace + '</td>');
// set the focus to the first td
if (i === 0 && z === 0)
{
$column.append(this.selection.getMarker());
}
$($row).append($column);
}
$table.append($row);
}
$tableBox.append($table);
var html = $tableBox.html();
this.modal.close();
this.selection.restore();
if (this.table.getTable()) return;
this.buffer.set();
var current = this.selection.getBlock() || this.selection.getCurrent();
if (current && current.tagName != 'BODY')
{
if (current.tagName == 'LI') current = $(current).closest('ul, ol');
$(current).after(html);
}
else
{
this.insert.html(html, false);
}
this.selection.restore();
var table = this.$editor.find('#table' + tableId);
var p = table.prev("p");
if (p.length > 0 && this.utils.isEmpty(p.html()))
{
p.remove();
}
if (!this.opts.linebreaks && (this.utils.browser('mozilla') || this.utils.browser('msie')))
{
var $next = table.next();
if ($next.length === 0)
{
table.after(this.opts.emptyHtml);
}
}
this.observe.buttons();
table.find('span.redactor-selection-marker').remove();
table.removeAttr('id');
this.code.sync();
this.core.setCallback('insertedTable', table);
},
getTable: function()
{
var $table = $(this.selection.getParent()).closest('table');
if (!this.utils.isRedactorParent($table)) return false;
if ($table.size() === 0) return false;
return $table;
},
restoreAfterDelete: function($table)
{
this.selection.restore();
$table.find('span.redactor-selection-marker').remove();
this.code.sync();
},
deleteTable: function()
{
var $table = this.table.getTable();
if (!$table) return;
this.buffer.set();
var $next = $table.next();
if (!this.opts.linebreaks && $next.length !== 0)
{
this.caret.setStart($next);
}
else
{
this.caret.setAfter($table);
}
$table.remove();
this.code.sync();
},
deleteRow: function()
{
var $table = this.table.getTable();
if (!$table) return;
var $current = $(this.selection.getCurrent());
this.buffer.set();
var $current_tr = $current.closest('tr');
var $focus_tr = $current_tr.prev().length ? $current_tr.prev() : $current_tr.next();
if ($focus_tr.length)
{
var $focus_td = $focus_tr.children('td, th').first();
if ($focus_td.length) $focus_td.prepend(this.selection.getMarker());
}
$current_tr.remove();
this.table.restoreAfterDelete($table);
},
deleteColumn: function()
{
var $table = this.table.getTable();
if (!$table) return;
this.buffer.set();
var $current = $(this.selection.getCurrent());
var $current_td = $current.closest('td, th');
var index = $current_td[0].cellIndex;
$table.find('tr').each($.proxy(function(i, elem)
{
var $elem = $(elem);
var focusIndex = index - 1 < 0 ? index + 1 : index - 1;
if (i === 0) $elem.find('td, th').eq(focusIndex).prepend(this.selection.getMarker());
$elem.find('td, th').eq(index).remove();
}, this));
this.table.restoreAfterDelete($table);
},
addHead: function()
{
var $table = this.table.getTable();
if (!$table) return;
this.buffer.set();
if ($table.find('thead').size() !== 0)
{
this.table.deleteHead();
return;
}
var tr = $table.find('tr').first().clone();
tr.find('td').replaceWith($.proxy(function()
{
return $('<th>').html(this.opts.invisibleSpace);
}, this));
$thead = $('<thead></thead>').append(tr);
$table.prepend($thead);
this.code.sync();
},
deleteHead: function()
{
var $table = this.table.getTable();
if (!$table) return;
var $thead = $table.find('thead');
if ($thead.size() === 0) return;
this.buffer.set();
$thead.remove();
this.code.sync();
},
addRowAbove: function()
{
this.table.addRow('before');
},
addRowBelow: function()
{
this.table.addRow('after');
},
addColumnLeft: function()
{
this.table.addColumn('before');
},
addColumnRight: function()
{
this.table.addColumn('after');
},
addRow: function(type)
{
var $table = this.table.getTable();
if (!$table) return;
this.buffer.set();
var $current = $(this.selection.getCurrent());
var $current_tr = $current.closest('tr');
var new_tr = $current_tr.clone();
new_tr.find('th').replaceWith(function()
{
var $td = $('<td>');
$td[0].attributes = this.attributes;
return $td.append($(this).contents());
});
new_tr.find('td').html(this.opts.invisibleSpace);
if (type == 'after')
{
$current_tr.after(new_tr);
}
else
{
$current_tr.before(new_tr);
}
this.code.sync();
},
addColumn: function (type)
{
var $table = this.table.getTable();
if (!$table) return;
var index = 0;
var current = $(this.selection.getCurrent());
this.buffer.set();
var $current_tr = current.closest('tr');
var $current_td = current.closest('td, th');
$current_tr.find('td, th').each($.proxy(function(i, elem)
{
if ($(elem)[0] === $current_td[0]) index = i;
}, this));
$table.find('tr').each($.proxy(function(i, elem)
{
var $current = $(elem).find('td, th').eq(index);
var td = $current.clone();
td.html(this.opts.invisibleSpace);
if (type == 'after')
{
$current.after(td);
}
else
{
$current.before(td);
}
}, this));
this.code.sync();
}
};
};
})(jQuery); | u4aew/tdtaliru | vendor/yiiext/imperavi-redactor-widget/assets/plugins/table/table.js | JavaScript | bsd-3-clause | 11,066 |
// namespace for dataset sources
// API for sources is
//
// dw.datasource.delimited(opts).dataset();
//
dw.datasource = {};
| datafunk/datawrapper | dw.js/src/dw.datasource.js | JavaScript | mit | 127 |
function shouldMatchTokens(result, tokens) {
for (var index = 0; index < result.length; index++) {
equals(result[index].name, tokens[index]);
}
}
function shouldBeToken(result, name, text) {
equals(result.name, name);
equals(result.text, text);
}
describe('Tokenizer', function() {
if (!Handlebars.Parser) {
return;
}
function tokenize(template) {
var parser = Handlebars.Parser,
lexer = parser.lexer;
lexer.setInput(template);
var out = [],
token;
while ((token = lexer.lex())) {
var result = parser.terminals_[token] || token;
if (!result || result === 'EOF' || result === 'INVALID') {
break;
}
out.push({name: result, text: lexer.yytext});
}
return out;
}
it('tokenizes a simple mustache as "OPEN ID CLOSE"', function() {
var result = tokenize('{{foo}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE']);
shouldBeToken(result[1], 'ID', 'foo');
});
it('supports unescaping with &', function() {
var result = tokenize('{{&bar}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE']);
shouldBeToken(result[0], 'OPEN', '{{&');
shouldBeToken(result[1], 'ID', 'bar');
});
it('supports unescaping with {{{', function() {
var result = tokenize('{{{bar}}}');
shouldMatchTokens(result, ['OPEN_UNESCAPED', 'ID', 'CLOSE_UNESCAPED']);
shouldBeToken(result[1], 'ID', 'bar');
});
it('supports escaping delimiters', function() {
var result = tokenize('{{foo}} \\{{bar}} {{baz}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE', 'CONTENT', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
shouldBeToken(result[3], 'CONTENT', ' ');
shouldBeToken(result[4], 'CONTENT', '{{bar}} ');
});
it('supports escaping multiple delimiters', function() {
var result = tokenize('{{foo}} \\{{bar}} \\{{baz}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE', 'CONTENT', 'CONTENT', 'CONTENT']);
shouldBeToken(result[3], 'CONTENT', ' ');
shouldBeToken(result[4], 'CONTENT', '{{bar}} ');
shouldBeToken(result[5], 'CONTENT', '{{baz}}');
});
it('supports escaping a triple stash', function() {
var result = tokenize('{{foo}} \\{{{bar}}} {{baz}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE', 'CONTENT', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
shouldBeToken(result[4], 'CONTENT', '{{{bar}}} ');
});
it('supports escaping escape character', function() {
var result = tokenize('{{foo}} \\\\{{bar}} {{baz}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE', 'CONTENT', 'OPEN', 'ID', 'CLOSE', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
shouldBeToken(result[3], 'CONTENT', ' \\');
shouldBeToken(result[5], 'ID', 'bar');
});
it('supports escaping multiple escape characters', function() {
var result = tokenize('{{foo}} \\\\{{bar}} \\\\{{baz}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE', 'CONTENT', 'OPEN', 'ID', 'CLOSE', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
shouldBeToken(result[3], 'CONTENT', ' \\');
shouldBeToken(result[5], 'ID', 'bar');
shouldBeToken(result[7], 'CONTENT', ' \\');
shouldBeToken(result[9], 'ID', 'baz');
});
it('supports escaped mustaches after escaped escape characters', function() {
var result = tokenize('{{foo}} \\\\{{bar}} \\{{baz}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE', 'CONTENT', 'OPEN', 'ID', 'CLOSE', 'CONTENT', 'CONTENT', 'CONTENT']);
shouldBeToken(result[3], 'CONTENT', ' \\');
shouldBeToken(result[4], 'OPEN', '{{');
shouldBeToken(result[5], 'ID', 'bar');
shouldBeToken(result[7], 'CONTENT', ' ');
shouldBeToken(result[8], 'CONTENT', '{{baz}}');
});
it('supports escaped escape characters after escaped mustaches', function() {
var result = tokenize('{{foo}} \\{{bar}} \\\\{{baz}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE', 'CONTENT', 'CONTENT', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
shouldBeToken(result[4], 'CONTENT', '{{bar}} ');
shouldBeToken(result[5], 'CONTENT', '\\');
shouldBeToken(result[6], 'OPEN', '{{');
shouldBeToken(result[7], 'ID', 'baz');
});
it('supports escaped escape character on a triple stash', function() {
var result = tokenize('{{foo}} \\\\{{{bar}}} {{baz}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE', 'CONTENT', 'OPEN_UNESCAPED', 'ID', 'CLOSE_UNESCAPED', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
shouldBeToken(result[3], 'CONTENT', ' \\');
shouldBeToken(result[5], 'ID', 'bar');
});
it('tokenizes a simple path', function() {
var result = tokenize('{{foo/bar}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'SEP', 'ID', 'CLOSE']);
});
it('allows dot notation', function() {
var result = tokenize('{{foo.bar}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'SEP', 'ID', 'CLOSE']);
shouldMatchTokens(tokenize('{{foo.bar.baz}}'), ['OPEN', 'ID', 'SEP', 'ID', 'SEP', 'ID', 'CLOSE']);
});
it('allows path literals with []', function() {
var result = tokenize('{{foo.[bar]}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'SEP', 'ID', 'CLOSE']);
});
it('allows multiple path literals on a line with []', function() {
var result = tokenize('{{foo.[bar]}}{{foo.[baz]}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'SEP', 'ID', 'CLOSE', 'OPEN', 'ID', 'SEP', 'ID', 'CLOSE']);
});
it('allows escaped literals in []', function() {
var result = tokenize('{{foo.[bar\\]]}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'SEP', 'ID', 'CLOSE']);
});
it('tokenizes {{.}} as OPEN ID CLOSE', function() {
var result = tokenize('{{.}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE']);
});
it('tokenizes a path as "OPEN (ID SEP)* ID CLOSE"', function() {
var result = tokenize('{{../foo/bar}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'SEP', 'ID', 'SEP', 'ID', 'CLOSE']);
shouldBeToken(result[1], 'ID', '..');
});
it('tokenizes a path with .. as a parent path', function() {
var result = tokenize('{{../foo.bar}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'SEP', 'ID', 'SEP', 'ID', 'CLOSE']);
shouldBeToken(result[1], 'ID', '..');
});
it('tokenizes a path with this/foo as OPEN ID SEP ID CLOSE', function() {
var result = tokenize('{{this/foo}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'SEP', 'ID', 'CLOSE']);
shouldBeToken(result[1], 'ID', 'this');
shouldBeToken(result[3], 'ID', 'foo');
});
it('tokenizes a simple mustache with spaces as "OPEN ID CLOSE"', function() {
var result = tokenize('{{ foo }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE']);
shouldBeToken(result[1], 'ID', 'foo');
});
it('tokenizes a simple mustache with line breaks as "OPEN ID ID CLOSE"', function() {
var result = tokenize('{{ foo \n bar }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'CLOSE']);
shouldBeToken(result[1], 'ID', 'foo');
});
it('tokenizes raw content as "CONTENT"', function() {
var result = tokenize('foo {{ bar }} baz');
shouldMatchTokens(result, ['CONTENT', 'OPEN', 'ID', 'CLOSE', 'CONTENT']);
shouldBeToken(result[0], 'CONTENT', 'foo ');
shouldBeToken(result[4], 'CONTENT', ' baz');
});
it('tokenizes a partial as "OPEN_PARTIAL ID CLOSE"', function() {
var result = tokenize('{{> foo}}');
shouldMatchTokens(result, ['OPEN_PARTIAL', 'ID', 'CLOSE']);
});
it('tokenizes a partial with context as "OPEN_PARTIAL ID ID CLOSE"', function() {
var result = tokenize('{{> foo bar }}');
shouldMatchTokens(result, ['OPEN_PARTIAL', 'ID', 'ID', 'CLOSE']);
});
it('tokenizes a partial without spaces as "OPEN_PARTIAL ID CLOSE"', function() {
var result = tokenize('{{>foo}}');
shouldMatchTokens(result, ['OPEN_PARTIAL', 'ID', 'CLOSE']);
});
it('tokenizes a partial space at the }); as "OPEN_PARTIAL ID CLOSE"', function() {
var result = tokenize('{{>foo }}');
shouldMatchTokens(result, ['OPEN_PARTIAL', 'ID', 'CLOSE']);
});
it('tokenizes a partial space at the }); as "OPEN_PARTIAL ID CLOSE"', function() {
var result = tokenize('{{>foo/bar.baz }}');
shouldMatchTokens(result, ['OPEN_PARTIAL', 'ID', 'SEP', 'ID', 'SEP', 'ID', 'CLOSE']);
});
it('tokenizes partial block declarations', function() {
var result = tokenize('{{#> foo}}');
shouldMatchTokens(result, ['OPEN_PARTIAL_BLOCK', 'ID', 'CLOSE']);
});
it('tokenizes a comment as "COMMENT"', function() {
var result = tokenize('foo {{! this is a comment }} bar {{ baz }}');
shouldMatchTokens(result, ['CONTENT', 'COMMENT', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
shouldBeToken(result[1], 'COMMENT', '{{! this is a comment }}');
});
it('tokenizes a block comment as "COMMENT"', function() {
var result = tokenize('foo {{!-- this is a {{comment}} --}} bar {{ baz }}');
shouldMatchTokens(result, ['CONTENT', 'COMMENT', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
shouldBeToken(result[1], 'COMMENT', '{{!-- this is a {{comment}} --}}');
});
it('tokenizes a block comment with whitespace as "COMMENT"', function() {
var result = tokenize('foo {{!-- this is a\n{{comment}}\n--}} bar {{ baz }}');
shouldMatchTokens(result, ['CONTENT', 'COMMENT', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
shouldBeToken(result[1], 'COMMENT', '{{!-- this is a\n{{comment}}\n--}}');
});
it('tokenizes open and closing blocks as OPEN_BLOCK, ID, CLOSE ..., OPEN_ENDBLOCK ID CLOSE', function() {
var result = tokenize('{{#foo}}content{{/foo}}');
shouldMatchTokens(result, ['OPEN_BLOCK', 'ID', 'CLOSE', 'CONTENT', 'OPEN_ENDBLOCK', 'ID', 'CLOSE']);
});
it('tokenizes directives', function() {
shouldMatchTokens(
tokenize('{{#*foo}}content{{/foo}}'),
['OPEN_BLOCK', 'ID', 'CLOSE', 'CONTENT', 'OPEN_ENDBLOCK', 'ID', 'CLOSE']);
shouldMatchTokens(
tokenize('{{*foo}}'),
['OPEN', 'ID', 'CLOSE']);
});
it('tokenizes inverse sections as "INVERSE"', function() {
shouldMatchTokens(tokenize('{{^}}'), ['INVERSE']);
shouldMatchTokens(tokenize('{{else}}'), ['INVERSE']);
shouldMatchTokens(tokenize('{{ else }}'), ['INVERSE']);
});
it('tokenizes inverse sections with ID as "OPEN_INVERSE ID CLOSE"', function() {
var result = tokenize('{{^foo}}');
shouldMatchTokens(result, ['OPEN_INVERSE', 'ID', 'CLOSE']);
shouldBeToken(result[1], 'ID', 'foo');
});
it('tokenizes inverse sections with ID and spaces as "OPEN_INVERSE ID CLOSE"', function() {
var result = tokenize('{{^ foo }}');
shouldMatchTokens(result, ['OPEN_INVERSE', 'ID', 'CLOSE']);
shouldBeToken(result[1], 'ID', 'foo');
});
it('tokenizes mustaches with params as "OPEN ID ID ID CLOSE"', function() {
var result = tokenize('{{ foo bar baz }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'ID', 'CLOSE']);
shouldBeToken(result[1], 'ID', 'foo');
shouldBeToken(result[2], 'ID', 'bar');
shouldBeToken(result[3], 'ID', 'baz');
});
it('tokenizes mustaches with String params as "OPEN ID ID STRING CLOSE"', function() {
var result = tokenize('{{ foo bar \"baz\" }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'STRING', 'CLOSE']);
shouldBeToken(result[3], 'STRING', 'baz');
});
it('tokenizes mustaches with String params using single quotes as "OPEN ID ID STRING CLOSE"', function() {
var result = tokenize("{{ foo bar \'baz\' }}");
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'STRING', 'CLOSE']);
shouldBeToken(result[3], 'STRING', 'baz');
});
it('tokenizes String params with spaces inside as "STRING"', function() {
var result = tokenize('{{ foo bar "baz bat" }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'STRING', 'CLOSE']);
shouldBeToken(result[3], 'STRING', 'baz bat');
});
it('tokenizes String params with escapes quotes as STRING', function() {
var result = tokenize('{{ foo "bar\\"baz" }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'STRING', 'CLOSE']);
shouldBeToken(result[2], 'STRING', 'bar"baz');
});
it('tokenizes String params using single quotes with escapes quotes as STRING', function() {
var result = tokenize("{{ foo 'bar\\'baz' }}");
shouldMatchTokens(result, ['OPEN', 'ID', 'STRING', 'CLOSE']);
shouldBeToken(result[2], 'STRING', "bar'baz");
});
it('tokenizes numbers', function() {
var result = tokenize('{{ foo 1 }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'NUMBER', 'CLOSE']);
shouldBeToken(result[2], 'NUMBER', '1');
result = tokenize('{{ foo 1.1 }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'NUMBER', 'CLOSE']);
shouldBeToken(result[2], 'NUMBER', '1.1');
result = tokenize('{{ foo -1 }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'NUMBER', 'CLOSE']);
shouldBeToken(result[2], 'NUMBER', '-1');
result = tokenize('{{ foo -1.1 }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'NUMBER', 'CLOSE']);
shouldBeToken(result[2], 'NUMBER', '-1.1');
});
it('tokenizes booleans', function() {
var result = tokenize('{{ foo true }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'BOOLEAN', 'CLOSE']);
shouldBeToken(result[2], 'BOOLEAN', 'true');
result = tokenize('{{ foo false }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'BOOLEAN', 'CLOSE']);
shouldBeToken(result[2], 'BOOLEAN', 'false');
});
it('tokenizes undefined and null', function() {
var result = tokenize('{{ foo undefined null }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'UNDEFINED', 'NULL', 'CLOSE']);
shouldBeToken(result[2], 'UNDEFINED', 'undefined');
shouldBeToken(result[3], 'NULL', 'null');
});
it('tokenizes hash arguments', function() {
var result = tokenize('{{ foo bar=baz }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'EQUALS', 'ID', 'CLOSE']);
result = tokenize('{{ foo bar baz=bat }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'ID', 'CLOSE']);
result = tokenize('{{ foo bar baz=1 }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'NUMBER', 'CLOSE']);
result = tokenize('{{ foo bar baz=true }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'BOOLEAN', 'CLOSE']);
result = tokenize('{{ foo bar baz=false }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'BOOLEAN', 'CLOSE']);
result = tokenize('{{ foo bar\n baz=bat }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'ID', 'CLOSE']);
result = tokenize('{{ foo bar baz=\"bat\" }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'STRING', 'CLOSE']);
result = tokenize('{{ foo bar baz=\"bat\" bam=wot }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'STRING', 'ID', 'EQUALS', 'ID', 'CLOSE']);
result = tokenize('{{foo omg bar=baz bat=\"bam\"}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'ID', 'ID', 'EQUALS', 'STRING', 'CLOSE']);
shouldBeToken(result[2], 'ID', 'omg');
});
it('tokenizes special @ identifiers', function() {
var result = tokenize('{{ @foo }}');
shouldMatchTokens(result, ['OPEN', 'DATA', 'ID', 'CLOSE']);
shouldBeToken(result[2], 'ID', 'foo');
result = tokenize('{{ foo @bar }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'DATA', 'ID', 'CLOSE']);
shouldBeToken(result[3], 'ID', 'bar');
result = tokenize('{{ foo bar=@baz }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'EQUALS', 'DATA', 'ID', 'CLOSE']);
shouldBeToken(result[5], 'ID', 'baz');
});
it('does not time out in a mustache with a single } followed by EOF', function() {
shouldMatchTokens(tokenize('{{foo}'), ['OPEN', 'ID']);
});
it('does not time out in a mustache when invalid ID characters are used', function() {
shouldMatchTokens(tokenize('{{foo & }}'), ['OPEN', 'ID']);
});
it('tokenizes subexpressions', function() {
var result = tokenize('{{foo (bar)}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'OPEN_SEXPR', 'ID', 'CLOSE_SEXPR', 'CLOSE']);
shouldBeToken(result[1], 'ID', 'foo');
shouldBeToken(result[3], 'ID', 'bar');
result = tokenize('{{foo (a-x b-y)}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'OPEN_SEXPR', 'ID', 'ID', 'CLOSE_SEXPR', 'CLOSE']);
shouldBeToken(result[1], 'ID', 'foo');
shouldBeToken(result[3], 'ID', 'a-x');
shouldBeToken(result[4], 'ID', 'b-y');
});
it('tokenizes nested subexpressions', function() {
var result = tokenize('{{foo (bar (lol rofl)) (baz)}}');
shouldMatchTokens(result, ['OPEN', 'ID', 'OPEN_SEXPR', 'ID', 'OPEN_SEXPR', 'ID', 'ID', 'CLOSE_SEXPR', 'CLOSE_SEXPR', 'OPEN_SEXPR', 'ID', 'CLOSE_SEXPR', 'CLOSE']);
shouldBeToken(result[3], 'ID', 'bar');
shouldBeToken(result[5], 'ID', 'lol');
shouldBeToken(result[6], 'ID', 'rofl');
shouldBeToken(result[10], 'ID', 'baz');
});
it('tokenizes nested subexpressions: literals', function() {
var result = tokenize("{{foo (bar (lol true) false) (baz 1) (blah 'b') (blorg \"c\")}}");
shouldMatchTokens(result, ['OPEN', 'ID', 'OPEN_SEXPR', 'ID', 'OPEN_SEXPR', 'ID', 'BOOLEAN', 'CLOSE_SEXPR', 'BOOLEAN', 'CLOSE_SEXPR', 'OPEN_SEXPR', 'ID', 'NUMBER', 'CLOSE_SEXPR', 'OPEN_SEXPR', 'ID', 'STRING', 'CLOSE_SEXPR', 'OPEN_SEXPR', 'ID', 'STRING', 'CLOSE_SEXPR', 'CLOSE']);
});
it('tokenizes block params', function() {
var result = tokenize('{{#foo as |bar|}}');
shouldMatchTokens(result, ['OPEN_BLOCK', 'ID', 'OPEN_BLOCK_PARAMS', 'ID', 'CLOSE_BLOCK_PARAMS', 'CLOSE']);
result = tokenize('{{#foo as |bar baz|}}');
shouldMatchTokens(result, ['OPEN_BLOCK', 'ID', 'OPEN_BLOCK_PARAMS', 'ID', 'ID', 'CLOSE_BLOCK_PARAMS', 'CLOSE']);
result = tokenize('{{#foo as | bar baz |}}');
shouldMatchTokens(result, ['OPEN_BLOCK', 'ID', 'OPEN_BLOCK_PARAMS', 'ID', 'ID', 'CLOSE_BLOCK_PARAMS', 'CLOSE']);
result = tokenize('{{#foo as as | bar baz |}}');
shouldMatchTokens(result, ['OPEN_BLOCK', 'ID', 'ID', 'OPEN_BLOCK_PARAMS', 'ID', 'ID', 'CLOSE_BLOCK_PARAMS', 'CLOSE']);
result = tokenize('{{else foo as |bar baz|}}');
shouldMatchTokens(result, ['OPEN_INVERSE_CHAIN', 'ID', 'OPEN_BLOCK_PARAMS', 'ID', 'ID', 'CLOSE_BLOCK_PARAMS', 'CLOSE']);
});
});
| jackhummah/bootles | vendor/handlebars/handlebars.js-4.0.10/spec/tokenizer.js | JavaScript | mit | 18,167 |
/* This Source Code Form is subject to the terms of the MIT license
* If a copy of the MIT license was not distributed with this file, you can
* obtain one at https://raw.github.com/mozilla/butter/master/LICENSE */
define( [ "util/lang", "./logo-spinner", "./resizeHandler", "./toggler", "localized",
"text!layouts/tray.html",
"l10n!/layouts/status-area.html", "text!layouts/timeline-area.html" ],
function( LangUtils, LogoSpinner, ResizeHandler, Toggler, Localized,
TRAY_LAYOUT,
STATUS_AREA_LAYOUT, TIMELINE_AREA_LAYOUT ) {
return function( butter ){
var _toggler,
statusAreaFragment = LangUtils.domFragment( STATUS_AREA_LAYOUT, ".media-status-container" ),
timelineAreaFragment = LangUtils.domFragment( TIMELINE_AREA_LAYOUT, ".butter-timeline" ),
trayRoot = LangUtils.domFragment( TRAY_LAYOUT, ".butter-tray" ),
timelineArea = trayRoot.querySelector( ".butter-timeline-area" ),
trayHandle = trayRoot.querySelector( ".butter-tray-resize-handle" ),
bodyWrapper = document.querySelector( ".body-wrapper" ),
stageWrapper = document.querySelector( ".stage-wrapper" ),
addTrackButton = statusAreaFragment.querySelector( "button.add-track" ),
loadingContainer = trayRoot.querySelector( ".butter-loading-container" ),
resizeHandler = new ResizeHandler( { margin: 26, border: 15 } ),
trayHeight = 205,
minHeight = 50,
minimized = true,
logoSpinner = new LogoSpinner( loadingContainer );
this.statusArea = trayRoot.querySelector( ".butter-status-area" );
this.timelineArea = timelineArea;
trayRoot.setAttribute( "dir", document.querySelector( "html" ).dir );
this.rootElement = trayRoot;
this.statusArea.appendChild( statusAreaFragment );
this.timelineArea.appendChild( timelineAreaFragment );
LangUtils.applyTransitionEndListener( trayRoot, resizeHandler.resize );
addTrackButton.addEventListener( "click", function() {
butter.currentMedia.addTrack( null, true );
} );
this.attachToDOM = function() {
bodyWrapper.appendChild( trayRoot );
};
function onTrayHandleMousedown( e ) {
e.preventDefault();
trayRoot.classList.remove( "butter-tray-transitions" );
trayHandle.removeEventListener( "mousedown", onTrayHandleMousedown, false );
window.addEventListener( "mousemove", onTrayHandleMousemove );
window.addEventListener( "mouseup", onTrayHandleMouseup );
}
function onTrayHandleMousemove( e ) {
var height = window.innerHeight - e.pageY;
// If it is dragged to be smaller than the min,
// instead minimize it.
if ( height <= minHeight ) {
minimize( true );
return;
} else if ( minimized ) {
minimize( false );
}
if ( e.pageY < stageWrapper.offsetTop ) {
height = window.innerHeight - stageWrapper.offsetTop;
}
trayRoot.style.height = height + "px";
stageWrapper.style.bottom = height + "px";
resizeHandler.resize();
butter.timeline.media.verticalResize();
}
function onTrayHandleMouseup( e ) {
var height = window.innerHeight - e.pageY;
if ( e.pageY < stageWrapper.offsetTop ) {
height = window.innerHeight - stageWrapper.offsetTop;
}
// If we have a valid height, store it incase the panel is maximized.
if ( height > minHeight ) {
trayHeight = height;
}
trayRoot.classList.add( "butter-tray-transitions" );
trayHandle.addEventListener( "mousedown", onTrayHandleMousedown );
window.removeEventListener( "mousemove", onTrayHandleMousemove, false );
window.removeEventListener( "mouseup", onTrayHandleMouseup, false );
}
trayHandle.addEventListener( "mousedown", onTrayHandleMousedown );
this.setMediaInstance = function( mediaInstanceRootElement ) {
var timelineContainer = timelineArea.querySelector( ".butter-timeline" );
LangUtils.applyTransitionEndListener( trayRoot, butter.timeline.media.verticalResize );
stageWrapper.style.bottom = trayHeight + "px";
timelineContainer.innerHTML = "";
timelineContainer.appendChild( mediaInstanceRootElement );
};
function toggleLoadingSpinner( state ) {
if ( state ) {
logoSpinner.start();
loadingContainer.style.display = "block";
} else {
logoSpinner.stop( function() {
loadingContainer.style.display = "none";
});
}
}
toggleLoadingSpinner( true );
function minimize( state ) {
_toggler.state = state;
minimized = state;
if ( state ) {
document.body.classList.add( "tray-minimized" );
trayRoot.style.height = minHeight + "px";
stageWrapper.style.bottom = minHeight + "px";
} else {
document.body.classList.remove( "tray-minimized" );
trayRoot.style.height = trayHeight + "px";
stageWrapper.style.bottom = trayHeight + "px";
}
}
_toggler = new Toggler( trayRoot.querySelector( ".butter-toggle-button" ), function () {
minimize( !_toggler.state );
}, Localized.get( "Show/Hide Timeline" ) );
minimize( true );
butter.listen( "mediaready", function onMediaReady() {
// This function's only purpose is to avoid having
// transitions on the tray while it's attached to the DOM,
// since Chrome doesn't display the element where it should be on load.
trayRoot.classList.add( "butter-tray-transitions" );
butter.unlisten( "mediaready", onMediaReady );
toggleLoadingSpinner( false );
minimize( false );
_toggler.visible = true;
});
};
});
| cadecairos/popcorn.webmaker.org | public/src/ui/tray.js | JavaScript | mit | 5,718 |
var class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_get_account_id_by_party_type_id_procedure =
[
[ "GetAccountIdByPartyTypeIdProcedure", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_get_account_id_by_party_type_id_procedure.html#a176b5c6e8a45127d46ae14330b6574df", null ],
[ "GetAccountIdByPartyTypeIdProcedure", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_get_account_id_by_party_type_id_procedure.html#aaeba35ce94c31f448c1db56c4c3548b9", null ],
[ "Execute", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_get_account_id_by_party_type_id_procedure.html#a76a5f119d9391898423472609a80209d", null ],
[ "ObjectName", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_get_account_id_by_party_type_id_procedure.html#aff5e1c4b6e5563f41956493f074a8c64", null ],
[ "ObjectNamespace", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_get_account_id_by_party_type_id_procedure.html#a109f7c5c5007a6531c848f589246e699", null ],
[ "_LoginId", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_get_account_id_by_party_type_id_procedure.html#aa78c6bb1e57cabfd278488578bf8f6f1", null ],
[ "_UserId", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_get_account_id_by_party_type_id_procedure.html#adc9321f2581843d7bb644f54db8778b5", null ],
[ "Catalog", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_get_account_id_by_party_type_id_procedure.html#a883747eb149106aa96548f0a145211e2", null ],
[ "PartyTypeId", "class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_get_account_id_by_party_type_id_procedure.html#ae54c40237c32fa25064e1324a1af18ac", null ]
]; | mixerp6/mixerp | docs/api/class_mix_e_r_p_1_1_net_1_1_schemas_1_1_core_1_1_data_1_1_get_account_id_by_party_type_id_procedure.js | JavaScript | gpl-2.0 | 1,682 |
/* eslint-env mocha */
import expect from 'expect';
import JSXAttributeMock from '../../../../__mocks__/JSXAttributeMock';
import getImplicitRoleForMenu from '../../../../src/util/implicitRoles/menu';
describe('isAbstractRole', () => {
it('works for toolbars', () => {
expect(getImplicitRoleForMenu([JSXAttributeMock('type', 'toolbar')])).toBe('toolbar');
});
it('works for non-toolbars', () => {
expect(getImplicitRoleForMenu([JSXAttributeMock('type', '')])).toBe('');
});
});
| BigBoss424/portfolio | v8/development/node_modules/eslint-plugin-jsx-a11y/__tests__/src/util/implicitRoles/menu-test.js | JavaScript | apache-2.0 | 495 |
(function (enyo, scope) {
/**
* {@link enyo.ContextualLayout} provides the base positioning logic for a contextual
* layout strategy. This layout strategy is intended for use with a popup in a
* decorator/activator scenario, in which the popup is positioned relative to
* the activator, e.g.:
*
* ```
* {kind: 'onyx.ContextualPopupDecorator', components: [
* {content: 'Show Popup'},
* {kind: 'onyx.ContextualPopup',
* title: 'Sample Popup',
* actionButtons: [
* {content: 'Button 1', classes: 'onyx-button-warning'},
* {content: 'Button 2'}
* ],
* components: [
* {content: 'Sample component in popup'}
* ]
* }
* ]}
* ```
*
* The decorator contains the popup and activator, with the activator being the
* first child component (i.e., the "Show Popup" button). The contextual layout
* strategy is applied because, in the definition of `onyx.ContextualPopup`,
* its `layoutKind` property is set to `enyo.ContextualLayout`.
*
* Note that a popup using ContextualLayout as its `layoutKind` is expected to
* declare several specific properties:
*
* - `vertFlushMargin` - The vertical flush layout margin, i.e., how close the
* popup's edge may come to the vertical screen edge (in pixels) before
* being laid out "flush" style.
* - `horizFlushMargin` - The horizontal flush layout margin, i.e., how close
* the popup's edge may come to the horizontal screen edge (in pixels)
* before being laid out "flush" style.
* - `widePopup` - A popup wider than this value (in pixels) is considered wide
* for layout calculation purposes.
* - `longPopup` - A popup longer than this value (in pixels) is considered long
* for layout calculation purposes.
* - `horizBuffer` - Horizontal flush popups are not allowed within this buffer
* area (in pixels) on the left or right screen edge.
* - `activatorOffset` - The popup activator's offset on the page (in pixels);
* this should be calculated whenever the popup is to be shown.
*
* @typedef {Object} enyo.ContextualLayout
*
* @ui
* @class enyo.ContextualLayout
* @extends enyo.Layout
* @public
*/
enyo.kind(
/** @lends enyo.ContextualLayout.prototype */ {
/**
* @private
*/
name: 'enyo.ContextualLayout',
/**
* @private
*/
kind: 'Layout',
/**
* Adjusts the popup's position, as well as the nub location and direction.
*
* @public
*/
adjustPosition: function() {
if (this.container.showing && this.container.hasNode()) {
/****ContextualPopup positioning rules:
1. Activator Location:
a. If activator is located in a corner then position using a flush style.
i. Attempt vertical first.
ii. Horizontal if vertical doesn't fit.
b. If not in a corner then check if the activator is located in one of the 4 "edges" of the view & position the
following way if so:
i. Activator is in top edge, position popup below it.
ii. Activator is in bottom edge, position popup above it.
iii. Activator is in left edge, position popup to the right of it.
iv. Activator is in right edge, position popup to the left of it.
2. Screen Size - the pop-up should generally extend in the direction where there’s room for it.
Note: no specific logic below for this rule since it is built into the positioning functions, ie we attempt to never
position a popup where there isn't enough room for it.
3. Popup Size:
i. If popup content is wide, use top or bottom positioning.
ii. If popup content is long, use horizontal positioning.
4. Favor top or bottom:
If all the above rules have been followed and location can still vary then favor top or bottom positioning.
5. If top or bottom will work, favor bottom.
Note: no specific logic below for this rule since it is built into the vertical position functions, ie we attempt to
use a bottom position for the popup as much possible. Additionally within the vetical position function we center the
popup if the activator is at the vertical center of the view.
****/
this.resetPositioning();
var innerWidth = this.getViewWidth();
var innerHeight = this.getViewHeight();
//These are the view "flush boundaries"
var topFlushPt = this.container.vertFlushMargin;
var bottomFlushPt = innerHeight - this.container.vertFlushMargin;
var leftFlushPt = this.container.horizFlushMargin;
var rightFlushPt = innerWidth - this.container.horizFlushMargin;
//Rule 1 - Activator Location based positioning
//if the activator is in the top or bottom edges of the view, check if the popup needs flush positioning
if ((this.offset.top + this.offset.height) < topFlushPt || this.offset.top > bottomFlushPt) {
//check/try vertical flush positioning (rule 1.a.i)
if (this.applyVerticalFlushPositioning(leftFlushPt, rightFlushPt)) {
return;
}
//if vertical doesn't fit then check/try horizontal flush (rule 1.a.ii)
if (this.applyHorizontalFlushPositioning(leftFlushPt, rightFlushPt)) {
return;
}
//if flush positioning didn't work then try just positioning vertically (rule 1.b.i & rule 1.b.ii)
if (this.applyVerticalPositioning()){
return;
}
//otherwise check if the activator is in the left or right edges of the view & if so try horizontal positioning
} else if ((this.offset.left + this.offset.width) < leftFlushPt || this.offset.left > rightFlushPt) {
//if flush positioning didn't work then try just positioning horizontally (rule 1.b.iii & rule 1.b.iv)
if (this.applyHorizontalPositioning()){
return;
}
}
//Rule 2 - no specific logic below for this rule since it is inheritent to the positioning functions, ie we attempt to never
//position a popup where there isn't enough room for it.
//Rule 3 - Popup Size based positioning
var clientRect = this.getBoundingRect(this.container.node);
//if the popup is wide then use vertical positioning
if (clientRect.width > this.container.widePopup) {
if (this.applyVerticalPositioning()){
return;
}
}
//if the popup is long then use horizontal positioning
else if (clientRect.height > this.container.longPopup) {
if (this.applyHorizontalPositioning()){
return;
}
}
//Rule 4 - Favor top or bottom positioning
if (this.applyVerticalPositioning()) {
return;
}
//but if thats not possible try horizontal
else if (this.applyHorizontalPositioning()){
return;
}
//Rule 5 - no specific logic below for this rule since it is built into the vertical position functions, ie we attempt to
// use a bottom position for the popup as much possible.
}
},
//
/**
* Determines whether the popup will fit onscreen if moved below or above the activator.
*
* @return {Boolean} `true` if popup will fit onscreen; otherwise, `false`.
* @public
*/
initVerticalPositioning: function() {
this.resetPositioning();
this.container.addClass('vertical');
var clientRect = this.getBoundingRect(this.container.node);
var innerHeight = this.getViewHeight();
if (this.container.floating){
if (this.offset.top < (innerHeight / 2)) {
this.applyPosition({top: this.offset.top + this.offset.height, bottom: 'auto'});
this.container.addClass('below');
} else {
this.applyPosition({top: this.offset.top - clientRect.height, bottom: 'auto'});
this.container.addClass('above');
}
} else {
//if the popup's bottom goes off the screen then put it on the top of the invoking control
if ((clientRect.top + clientRect.height > innerHeight) && ((innerHeight - clientRect.bottom) < (clientRect.top - clientRect.height))){
this.container.addClass('above');
} else {
this.container.addClass('below');
}
}
//if moving the popup above or below the activator puts it past the edge of the screen then vertical doesn't work
clientRect = this.getBoundingRect(this.container.node);
if ((clientRect.top + clientRect.height) > innerHeight || clientRect.top < 0){
return false;
}
return true;
},
/**
* Moves the popup below or above the activating control.
*
* @return {Boolean} `false` if popup was not moved because it would not fit onscreen
* in the new position; otherwise, `true`.
* @public
*/
applyVerticalPositioning: function() {
//if we can't fit the popup above or below the activator then forget vertical positioning
if (!this.initVerticalPositioning()) {
return false;
}
var clientRect = this.getBoundingRect(this.container.node);
var innerWidth = this.getViewWidth();
if (this.container.floating){
//Get the left edge delta to horizontally center the popup
var centeredLeft = this.offset.left + this.offset.width/2 - clientRect.width/2;
if (centeredLeft + clientRect.width > innerWidth) {//popup goes off right edge of the screen if centered
this.applyPosition({left: this.offset.left + this.offset.width - clientRect.width});
this.container.addClass('left');
} else if (centeredLeft < 0) {//popup goes off left edge of the screen if centered
this.applyPosition({left:this.offset.left});
this.container.addClass('right');
} else {//center the popup
this.applyPosition({left: centeredLeft});
}
} else {
//Get the left edge delta to horizontally center the popup
var centeredLeftDelta = this.offset.left + this.offset.width/2 - clientRect.left - clientRect.width/2;
if (clientRect.right + centeredLeftDelta > innerWidth) {//popup goes off right edge of the screen if centered
this.applyPosition({left: this.offset.left + this.offset.width - clientRect.right});
this.container.addRemoveClass('left', true);
} else if (clientRect.left + centeredLeftDelta < 0) {//popup goes off left edge of the screen if centered
this.container.addRemoveClass('right', true);
} else {//center the popup
this.applyPosition({left: centeredLeftDelta});
}
}
return true;
},
/**
* Positions the popup vertically flush with the activating control.
*
* @param {Number} leftFlushPt - Left side cutoff.
* @param {Number} rightFlushPt - Right side cutoff.
* @return {Boolean} `false` if popup will not fit onscreen in new position;
* otherwise, `true`.
* @public
*/
applyVerticalFlushPositioning: function(leftFlushPt, rightFlushPt) {
//if we can't fit the popup above or below the activator then forget vertical positioning
if (!this.initVerticalPositioning()) {
return false;
}
var clientRect = this.getBoundingRect(this.container.node);
var innerWidth = this.getViewWidth();
//If the activator's right side is within our left side cut off use flush positioning
if ((this.offset.left + this.offset.width/2) < leftFlushPt){
//if the activator's left edge is too close or past the screen left edge
if (this.offset.left + this.offset.width/2 < this.container.horizBuffer){
this.applyPosition({left:this.container.horizBuffer + (this.container.floating ? 0 : -clientRect.left)});
} else {
this.applyPosition({left:this.offset.width/2 + (this.container.floating ? this.offset.left : 0)});
}
this.container.addClass('right');
this.container.addClass('corner');
return true;
}
//If the activator's left side is within our right side cut off use flush positioning
else if (this.offset.left + this.offset.width/2 > rightFlushPt) {
if ((this.offset.left+this.offset.width/2) > (innerWidth-this.container.horizBuffer)){
this.applyPosition({left:innerWidth - this.container.horizBuffer - clientRect.right});
} else {
this.applyPosition({left: (this.offset.left + this.offset.width/2) - clientRect.right});
}
this.container.addClass('left');
this.container.addClass('corner');
return true;
}
return false;
},
/**
* Determines whether popup will fit onscreen if moved to the left or right of the
* activator.
*
* @return {Boolean} `true` if the popup will fit onscreen; otherwise, `false`.
* @public
*/
initHorizontalPositioning: function() {
this.resetPositioning();
var clientRect = this.getBoundingRect(this.container.node);
var innerWidth = this.getViewWidth();
//adjust horizontal positioning of the popup & nub vertical positioning
if (this.container.floating){
if ((this.offset.left + this.offset.width) < innerWidth/2) {
this.applyPosition({left: this.offset.left + this.offset.width});
this.container.addRemoveClass('left', true);
} else {
this.applyPosition({left: this.offset.left - clientRect.width});
this.container.addRemoveClass('right', true);
}
} else {
if (this.offset.left - clientRect.width > 0) {
this.applyPosition({left: this.offset.left - clientRect.left - clientRect.width});
this.container.addRemoveClass('right', true);
} else {
this.applyPosition({left: this.offset.width});
this.container.addRemoveClass('left', true);
}
}
this.container.addRemoveClass('horizontal', true);
//if moving the popup left or right of the activator puts it past the edge of the screen then horizontal won't work
clientRect = this.getBoundingRect(this.container.node);
if (clientRect.left < 0 || (clientRect.left + clientRect.width) > innerWidth){
return false;
}
return true;
},
/**
* Moves the popup to the left or right of the activating control.
*
* @return {Boolean} `false` if popup was not moved because it would not fit onscreen
* in the new position; otherwise, `true`.
* @public
*/
applyHorizontalPositioning: function() {
//if we can't fit the popup left or right of the activator then forget horizontal positioning
if (!this.initHorizontalPositioning()) {
return false;
}
var clientRect = this.getBoundingRect(this.container.node);
var innerHeight = this.getViewHeight();
var activatorCenter = this.offset.top + this.offset.height/2;
if (this.container.floating){
//if the activator's center is within 10% of the center of the view, vertically center the popup
if ((activatorCenter >= (innerHeight/2 - 0.05 * innerHeight)) && (activatorCenter <= (innerHeight/2 + 0.05 * innerHeight))) {
this.applyPosition({top: this.offset.top + this.offset.height/2 - clientRect.height/2, bottom: 'auto'});
} else if (this.offset.top + this.offset.height < innerHeight/2) { //the activator is in the top 1/2 of the screen
this.applyPosition({top: this.offset.top, bottom: 'auto'});
this.container.addRemoveClass('high', true);
} else { //otherwise the popup will be positioned in the bottom 1/2 of the screen
this.applyPosition({top: this.offset.top - clientRect.height + this.offset.height*2, bottom: 'auto'});
this.container.addRemoveClass('low', true);
}
} else {
//if the activator's center is within 10% of the center of the view, vertically center the popup
if ((activatorCenter >= (innerHeight/2 - 0.05 * innerHeight)) && (activatorCenter <= (innerHeight/2 + 0.05 * innerHeight))) {
this.applyPosition({top: (this.offset.height - clientRect.height)/2});
} else if (this.offset.top + this.offset.height < innerHeight/2) { //the activator is in the top 1/2 of the screen
this.applyPosition({top: -this.offset.height});
this.container.addRemoveClass('high', true);
} else { //otherwise the popup will be positioned in the bottom 1/2 of the screen
this.applyPosition({top: clientRect.top - clientRect.height - this.offset.top + this.offset.height});
this.container.addRemoveClass('low', true);
}
}
return true;
},
/**
* Positions the popup horizontally flush with the activating control.
*
* @param {Number} leftFlushPt - Left side cutoff.
* @param {Number} rightFlushPt - Right side cutoff.
* @return {Boolean} `false` if popup will not fit onscreen in new position;
* otherwise, `true`.
* @public
*/
applyHorizontalFlushPositioning: function(leftFlushPt, rightFlushPt) {
//if we can't fit the popup left or right of the activator then forget horizontal positioning
if (!this.initHorizontalPositioning()) {
return false;
}
var clientRect = this.getBoundingRect(this.container.node);
var innerHeight = this.getViewHeight();
//adjust vertical positioning (high or low nub & popup position)
if (this.container.floating){
if (this.offset.top < (innerHeight/2)){
this.applyPosition({top: this.offset.top + this.offset.height/2});
this.container.addRemoveClass('high', true);
} else {
this.applyPosition({top:this.offset.top + this.offset.height/2 - clientRect.height});
this.container.addRemoveClass('low', true);
}
} else {
if (((clientRect.top + clientRect.height) > innerHeight) && ((innerHeight - clientRect.bottom) < (clientRect.top - clientRect.height))) {
this.applyPosition({top: clientRect.top - clientRect.height - this.offset.top - this.offset.height/2});
this.container.addRemoveClass('low', true);
} else {
this.applyPosition({top: this.offset.height/2});
this.container.addRemoveClass('high', true);
}
}
//If the activator's right side is within our left side cut off use flush positioning
if ((this.offset.left + this.offset.width) < leftFlushPt){
this.container.addClass('left');
this.container.addClass('corner');
return true;
}
//If the activator's left side is within our right side cut off use flush positioning
else if (this.offset.left > rightFlushPt) {
this.container.addClass('right');
this.container.addClass('corner');
return true;
}
return false;
},
/**
* Retrieves an object with properties describing the bounding rectangle for the
* passed-in DOM node.
*
* @param {String} inNode - DOM node for which to retrieve the bounding rectangle.
* @return {Object} Object with properties describing the DOM node's bounding rectangle.
* @private
*/
getBoundingRect: function(inNode){
// getBoundingClientRect returns top/left values which are relative to the viewport and not absolute
var o = inNode.getBoundingClientRect();
if (!o.width || !o.height) {
return {
left: o.left,
right: o.right,
top: o.top,
bottom: o.bottom,
width: o.right - o.left,
height: o.bottom - o.top
};
}
return o;
},
/**
* @private
*/
getViewHeight: function() {
return (window.innerHeight === undefined) ? document.documentElement.clientHeight : window.innerHeight;
},
/**
* @private
*/
getViewWidth: function() {
return (window.innerWidth === undefined) ? document.documentElement.clientWidth : window.innerWidth;
},
/**
* @private
*/
applyPosition: function(inRect) {
var s = '';
for (var n in inRect) {
s += (n + ':' + inRect[n] + (isNaN(inRect[n]) ? '; ' : 'px; '));
}
this.container.addStyles(s);
},
/**
* @private
*/
resetPositioning: function() {
this.container.removeClass('right');
this.container.removeClass('left');
this.container.removeClass('high');
this.container.removeClass('low');
this.container.removeClass("corner");
this.container.removeClass('below');
this.container.removeClass('above');
this.container.removeClass('vertical');
this.container.removeClass('horizontal');
this.applyPosition({left: 'auto'});
this.applyPosition({top: 'auto'});
},
/**
* @private
*/
reflow: function() {
this.offset = this.container.activatorOffset;
this.adjustPosition();
}
});
})(enyo, this); | Herrie82/org.webosports.app.settings | lib/layout/contextual/source/ContextualLayout.js | JavaScript | apache-2.0 | 24,159 |
$(function() { alert("Hello.2"); });
| LeArNalytics/LeArNalytics | vendor/cache/gems/sinatra-assetpack-0.3.3/test/app/app/js/hello.2.js | JavaScript | mit | 37 |
/*
SystemJS map support
Provides map configuration through
System.map['jquery'] = 'some/module/map'
As well as contextual map config through
System.map['bootstrap'] = {
jquery: 'some/module/map2'
}
Note that this applies for subpaths, just like RequireJS
jquery -> 'some/module/map'
jquery/path -> 'some/module/map/path'
bootstrap -> 'bootstrap'
Inside any module name of the form 'bootstrap' or 'bootstrap/*'
jquery -> 'some/module/map2'
jquery/p -> 'some/module/map2/p'
Maps are carefully applied from most specific contextual map, to least specific global map
*/
function map(loader) {
loader.map = loader.map || {};
loader._extensions.push(map);
// return if prefix parts (separated by '/') match the name
// eg prefixMatch('jquery/some/thing', 'jquery') -> true
// prefixMatch('jqueryhere/', 'jquery') -> false
function prefixMatch(name, prefix) {
if (name.length < prefix.length)
return false;
if (name.substr(0, prefix.length) != prefix)
return false;
if (name[prefix.length] && name[prefix.length] != '/')
return false;
return true;
}
// get the depth of a given path
// eg pathLen('some/name') -> 2
function pathLen(name) {
var len = 1;
for (var i = 0, l = name.length; i < l; i++)
if (name[i] === '/')
len++;
return len;
}
function doMap(name, matchLen, map) {
return map + name.substr(matchLen);
}
// given a relative-resolved module name and normalized parent name,
// apply the map configuration
function applyMap(name, parentName, loader) {
var curMatch, curMatchLength = 0;
var curParent, curParentMatchLength = 0;
var tmpParentLength, tmpPrefixLength;
var subPath;
var nameParts;
// first find most specific contextual match
if (parentName) {
for (var p in loader.map) {
var curMap = loader.map[p];
if (typeof curMap != 'object')
continue;
// most specific parent match wins first
if (!prefixMatch(parentName, p))
continue;
tmpParentLength = pathLen(p);
if (tmpParentLength <= curParentMatchLength)
continue;
for (var q in curMap) {
// most specific name match wins
if (!prefixMatch(name, q))
continue;
tmpPrefixLength = pathLen(q);
if (tmpPrefixLength <= curMatchLength)
continue;
curMatch = q;
curMatchLength = tmpPrefixLength;
curParent = p;
curParentMatchLength = tmpParentLength;
}
}
}
// if we found a contextual match, apply it now
if (curMatch)
return doMap(name, curMatch.length, loader.map[curParent][curMatch]);
// now do the global map
for (var p in loader.map) {
var curMap = loader.map[p];
if (typeof curMap != 'string')
continue;
if (!prefixMatch(name, p))
continue;
var tmpPrefixLength = pathLen(p);
if (tmpPrefixLength <= curMatchLength)
continue;
curMatch = p;
curMatchLength = tmpPrefixLength;
}
if (curMatch)
return doMap(name, curMatch.length, loader.map[curMatch]);
return name;
}
var loaderNormalize = loader.normalize;
loader.normalize = function(name, parentName, parentAddress) {
var loader = this;
if (!loader.map)
loader.map = {};
var isPackage = false;
if (name.substr(name.length - 1, 1) == '/') {
isPackage = true;
name += '#';
}
return Promise.resolve(loaderNormalize.call(loader, name, parentName, parentAddress))
.then(function(name) {
name = applyMap(name, parentName, loader);
// Normalize "module/" into "module/module"
// Convenient for packages
if (isPackage) {
var nameParts = name.split('/');
nameParts.pop();
var pkgName = nameParts.pop();
nameParts.push(pkgName);
nameParts.push(pkgName);
name = nameParts.join('/');
}
return name;
});
}
}
| AbdulBasitBashir/learn-angular2 | step9_gulp_router/node_modules/systemjs/lib/extension-map.js | JavaScript | mit | 4,078 |
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["Hls"] = factory();
else
root["Hls"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = 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;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/dist/";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 8);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return enableLogs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return logger; });
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function noop() {}
var fakeLogger = {
trace: noop,
debug: noop,
log: noop,
warn: noop,
info: noop,
error: noop
};
var exportedLogger = fakeLogger;
/*globals self: false */
//let lastCallTime;
// function formatMsgWithTimeInfo(type, msg) {
// const now = Date.now();
// const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
// lastCallTime = now;
// msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
// return msg;
// }
function formatMsg(type, msg) {
msg = '[' + type + '] > ' + msg;
return msg;
}
function consolePrintFn(type) {
var func = self.console[type];
if (func) {
return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (args[0]) {
args[0] = formatMsg(type, args[0]);
}
func.apply(self.console, args);
};
}
return noop;
}
function exportLoggerFunctions(debugConfig) {
for (var _len2 = arguments.length, functions = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
functions[_key2 - 1] = arguments[_key2];
}
functions.forEach(function (type) {
exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);
});
}
var enableLogs = function enableLogs(debugConfig) {
if (debugConfig === true || (typeof debugConfig === 'undefined' ? 'undefined' : _typeof(debugConfig)) === 'object') {
exportLoggerFunctions(debugConfig,
// Remove out from list here to hard-disable a log-level
//'trace',
'debug', 'log', 'info', 'warn', 'error');
// Some browsers don't allow to use bind on console object anyway
// fallback to default if needed
try {
exportedLogger.log();
} catch (e) {
exportedLogger = fakeLogger;
}
} else {
exportedLogger = fakeLogger;
}
};
var logger = exportedLogger;
/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony default export */ __webpack_exports__["a"] = ({
// fired before MediaSource is attaching to media element - data: { media }
MEDIA_ATTACHING: 'hlsMediaAttaching',
// fired when MediaSource has been succesfully attached to media element - data: { }
MEDIA_ATTACHED: 'hlsMediaAttached',
// fired before detaching MediaSource from media element - data: { }
MEDIA_DETACHING: 'hlsMediaDetaching',
// fired when MediaSource has been detached from media element - data: { }
MEDIA_DETACHED: 'hlsMediaDetached',
// fired when we buffer is going to be reset - data: { }
BUFFER_RESET: 'hlsBufferReset',
// fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}
BUFFER_CODECS: 'hlsBufferCodecs',
// fired when sourcebuffers have been created - data: { tracks : tracks }
BUFFER_CREATED: 'hlsBufferCreated',
// fired when we append a segment to the buffer - data: { segment: segment object }
BUFFER_APPENDING: 'hlsBufferAppending',
// fired when we are done with appending a media segment to the buffer - data : { parent : segment parent that triggered BUFFER_APPENDING, pending : nb of segments waiting for appending for this segment parent}
BUFFER_APPENDED: 'hlsBufferAppended',
// fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { }
BUFFER_EOS: 'hlsBufferEos',
// fired when the media buffer should be flushed - data { startOffset, endOffset }
BUFFER_FLUSHING: 'hlsBufferFlushing',
// fired when the media buffer has been flushed - data: { }
BUFFER_FLUSHED: 'hlsBufferFlushed',
// fired to signal that a manifest loading starts - data: { url : manifestURL}
MANIFEST_LOADING: 'hlsManifestLoading',
// fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks], url : manifestURL, stats : { trequest, tfirst, tload, mtime}}
MANIFEST_LOADED: 'hlsManifestLoaded',
// fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest}
MANIFEST_PARSED: 'hlsManifestParsed',
// fired when a level switch is requested - data: { level : id of new level } // deprecated in favor LEVEL_SWITCHING
LEVEL_SWITCH: 'hlsLevelSwitch',
// fired when a level switch is requested - data: { level : id of new level }
LEVEL_SWITCHING: 'hlsLevelSwitching',
// fired when a level switch is effective - data: { level : id of new level }
LEVEL_SWITCHED: 'hlsLevelSwitched',
// fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded}
LEVEL_LOADING: 'hlsLevelLoading',
// fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : { trequest, tfirst, tload, mtime} }
LEVEL_LOADED: 'hlsLevelLoaded',
// fired when a level's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, level : id of updated level }
LEVEL_UPDATED: 'hlsLevelUpdated',
// fired when a level's PTS information has been updated after parsing a fragment - data: { details : levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment }
LEVEL_PTS_UPDATED: 'hlsLevelPtsUpdated',
// fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }
AUDIO_TRACKS_UPDATED: 'hlsAudioTracksUpdated',
// fired when an audio track switch occurs - data: { id : audio track id } // deprecated in favor AUDIO_TRACK_SWITCHING
AUDIO_TRACK_SWITCH: 'hlsAudioTrackSwitch',
// fired when an audio track switching is requested - data: { id : audio track id }
AUDIO_TRACK_SWITCHING: 'hlsAudioTrackSwitching',
// fired when an audio track switch actually occurs - data: { id : audio track id }
AUDIO_TRACK_SWITCHED: 'hlsAudioTrackSwitched',
// fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }
AUDIO_TRACK_LOADING: 'hlsAudioTrackLoading',
// fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime } }
AUDIO_TRACK_LOADED: 'hlsAudioTrackLoaded',
// fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }
SUBTITLE_TRACKS_UPDATED: 'hlsSubtitleTracksUpdated',
// fired when an subtitle track switch occurs - data: { id : subtitle track id }
SUBTITLE_TRACK_SWITCH: 'hlsSubtitleTrackSwitch',
// fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }
SUBTITLE_TRACK_LOADING: 'hlsSubtitleTrackLoading',
// fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime } }
SUBTITLE_TRACK_LOADED: 'hlsSubtitleTrackLoaded',
// fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }
SUBTITLE_FRAG_PROCESSED: 'hlsSubtitleFragProcessed',
// fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, frag : fragment object }
INIT_PTS_FOUND: 'hlsInitPtsFound',
// fired when a fragment loading starts - data: { frag : fragment object }
FRAG_LOADING: 'hlsFragLoading',
// fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }
FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress',
// Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }
FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted',
// fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length } }
FRAG_LOADED: 'hlsFragLoaded',
// fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }
FRAG_DECRYPTED: 'hlsFragDecrypted',
// fired when Init Segment has been extracted from fragment - data: { id : demuxer id, frag: fragment object, moov : moov MP4 box, codecs : codecs found while parsing fragment }
FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment',
// fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }
FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata',
// fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }
FRAG_PARSING_METADATA: 'hlsFragParsingMetadata',
// fired when data have been extracted from fragment - data: { id : demuxer id, frag: fragment object, data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null}
FRAG_PARSING_DATA: 'hlsFragParsingData',
// fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }
FRAG_PARSED: 'hlsFragParsed',
// fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tbuffered, length, bwEstimate } }
FRAG_BUFFERED: 'hlsFragBuffered',
// fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }
FRAG_CHANGED: 'hlsFragChanged',
// Identifier for a FPS drop event - data: { curentDropped, currentDecoded, totalDroppedFrames }
FPS_DROP: 'hlsFpsDrop',
//triggered when FPS drop triggers auto level capping - data: { level, droppedlevel }
FPS_DROP_LEVEL_CAPPING: 'hlsFpsDropLevelCapping',
// Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data }
ERROR: 'hlsError',
// fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example - data: { }
DESTROYING: 'hlsDestroying',
// fired when a decrypt key loading starts - data: { frag : fragment object }
KEY_LOADING: 'hlsKeyLoading',
// fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length } }
KEY_LOADED: 'hlsKeyLoaded',
// fired upon stream controller state transitions - data: { previousState, nextState }
STREAM_STATE_TRANSITION: 'hlsStreamStateTransition'
});
/***/ }),
/* 2 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return ErrorTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ErrorDetails; });
var ErrorTypes = {
// Identifier for a network error (loading error / timeout ...)
NETWORK_ERROR: 'networkError',
// Identifier for a media Error (video/parsing/mediasource error)
MEDIA_ERROR: 'mediaError',
// Identifier for a mux Error (demuxing/remuxing)
MUX_ERROR: 'muxError',
// Identifier for all other errors
OTHER_ERROR: 'otherError'
};
var ErrorDetails = {
// Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }}
MANIFEST_LOAD_ERROR: 'manifestLoadError',
// Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
MANIFEST_LOAD_TIMEOUT: 'manifestLoadTimeOut',
// Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}
MANIFEST_PARSING_ERROR: 'manifestParsingError',
// Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}
MANIFEST_INCOMPATIBLE_CODECS_ERROR: 'manifestIncompatibleCodecsError',
// Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }}
LEVEL_LOAD_ERROR: 'levelLoadError',
// Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
LEVEL_LOAD_TIMEOUT: 'levelLoadTimeOut',
// Identifier for a level switch error - data: { level : faulty level Id, event : error description}
LEVEL_SWITCH_ERROR: 'levelSwitchError',
// Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }}
AUDIO_TRACK_LOAD_ERROR: 'audioTrackLoadError',
// Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
AUDIO_TRACK_LOAD_TIMEOUT: 'audioTrackLoadTimeOut',
// Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }}
FRAG_LOAD_ERROR: 'fragLoadError',
// Identifier for fragment loop loading error - data: { frag : fragment object}
FRAG_LOOP_LOADING_ERROR: 'fragLoopLoadingError',
// Identifier for fragment load timeout error - data: { frag : fragment object}
FRAG_LOAD_TIMEOUT: 'fragLoadTimeOut',
// Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description }
FRAG_DECRYPT_ERROR: 'fragDecryptError',
// Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description }
// will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release
FRAG_PARSING_ERROR: 'fragParsingError',
// Identifier for a remux alloc error event - data: { id : demuxer Id, frag : fragment object, bytes : nb of bytes on which allocation failed , reason : error text }
REMUX_ALLOC_ERROR: 'remuxAllocError',
// Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }}
KEY_LOAD_ERROR: 'keyLoadError',
// Identifier for decrypt key load timeout error - data: { frag : fragment object}
KEY_LOAD_TIMEOUT: 'keyLoadTimeOut',
// Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { err : exception , mimeType : mimeType }
BUFFER_ADD_CODEC_ERROR: 'bufferAddCodecError',
// Identifier for a buffer append error - data: append error description
BUFFER_APPEND_ERROR: 'bufferAppendError',
// Identifier for a buffer appending error event - data: appending error description
BUFFER_APPENDING_ERROR: 'bufferAppendingError',
// Identifier for a buffer stalled error event
BUFFER_STALLED_ERROR: 'bufferStalledError',
// Identifier for a buffer full event
BUFFER_FULL_ERROR: 'bufferFullError',
// Identifier for a buffer seek over hole event
BUFFER_SEEK_OVER_HOLE: 'bufferSeekOverHole',
// Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area)
BUFFER_NUDGE_ON_STALL: 'bufferNudgeOnStall',
// Identifier for an internal exception happening inside hls.js while handling an event
INTERNAL_EXCEPTION: 'internalException'
};
/***/ }),
/* 3 */
/***/ (function(module, exports) {
// A blank file used to build the "light" configurations
// This file replaces modules which we do not want to build
// This replacement is done in the "resolve" section of the webpack config
/***/ }),
/* 4 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* ID3 parser
*/
var ID3 = function () {
function ID3() {
_classCallCheck(this, ID3);
}
/**
* Returns true if an ID3 header can be found at offset in data
* @param {Uint8Array} data - The data to search in
* @param {number} offset - The offset at which to start searching
* @return {boolean} - True if an ID3 header is found
*/
ID3.isHeader = function isHeader(data, offset) {
/*
* http://id3.org/id3v2.3.0
* [0] = 'I'
* [1] = 'D'
* [2] = '3'
* [3,4] = {Version}
* [5] = {Flags}
* [6-9] = {ID3 Size}
*
* An ID3v2 tag can be detected with the following pattern:
* $49 44 33 yy yy xx zz zz zz zz
* Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80
*/
if (offset + 10 <= data.length) {
//look for 'ID3' identifier
if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {
//check version is within range
if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {
//check size is within range
if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
return true;
}
}
}
}
return false;
};
/**
* Returns true if an ID3 footer can be found at offset in data
* @param {Uint8Array} data - The data to search in
* @param {number} offset - The offset at which to start searching
* @return {boolean} - True if an ID3 footer is found
*/
ID3.isFooter = function isFooter(data, offset) {
/*
* The footer is a copy of the header, but with a different identifier
*/
if (offset + 10 <= data.length) {
//look for '3DI' identifier
if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {
//check version is within range
if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {
//check size is within range
if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
return true;
}
}
}
}
return false;
};
/**
* Returns any adjacent ID3 tags found in data starting at offset, as one block of data
* @param {Uint8Array} data - The data to search in
* @param {number} offset - The offset at which to start searching
* @return {Uint8Array} - The block of data containing any ID3 tags found
*/
ID3.getID3Data = function getID3Data(data, offset) {
var front = offset;
var length = 0;
while (ID3.isHeader(data, offset)) {
//ID3 header is 10 bytes
length += 10;
var size = ID3._readSize(data, offset + 6);
length += size;
if (ID3.isFooter(data, offset + 10)) {
//ID3 footer is 10 bytes
length += 10;
}
offset += length;
}
if (length > 0) {
return data.subarray(front, front + length);
}
return undefined;
};
ID3._readSize = function _readSize(data, offset) {
var size = 0;
size = (data[offset] & 0x7f) << 21;
size |= (data[offset + 1] & 0x7f) << 14;
size |= (data[offset + 2] & 0x7f) << 7;
size |= data[offset + 3] & 0x7f;
return size;
};
/**
* Searches for the Elementary Stream timestamp found in the ID3 data chunk
* @param {Uint8Array} data - Block of data containing one or more ID3 tags
* @return {number} - The timestamp
*/
ID3.getTimeStamp = function getTimeStamp(data) {
var frames = ID3.getID3Frames(data);
for (var i = 0; i < frames.length; i++) {
var frame = frames[i];
if (ID3.isTimeStampFrame(frame)) {
return ID3._readTimeStamp(frame);
}
}
return undefined;
};
/**
* Returns true if the ID3 frame is an Elementary Stream timestamp frame
* @param {ID3 frame} frame
*/
ID3.isTimeStampFrame = function isTimeStampFrame(frame) {
return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';
};
ID3._getFrameData = function _getFrameData(data) {
/*
Frame ID $xx xx xx xx (four characters)
Size $xx xx xx xx
Flags $xx xx
*/
var type = String.fromCharCode(data[0], data[1], data[2], data[3]);
var size = ID3._readSize(data, 4);
//skip frame id, size, and flags
var offset = 10;
return { type: type, size: size, data: data.subarray(offset, offset + size) };
};
/**
* Returns an array of ID3 frames found in all the ID3 tags in the id3Data
* @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags
* @return {ID3 frame[]} - Array of ID3 frame objects
*/
ID3.getID3Frames = function getID3Frames(id3Data) {
var offset = 0;
var frames = [];
while (ID3.isHeader(id3Data, offset)) {
var size = ID3._readSize(id3Data, offset + 6);
//skip past ID3 header
offset += 10;
var end = offset + size;
//loop through frames in the ID3 tag
while (offset + 8 < end) {
var frameData = ID3._getFrameData(id3Data.subarray(offset));
var frame = ID3._decodeFrame(frameData);
if (frame) {
frames.push(frame);
}
//skip frame header and frame data
offset += frameData.size + 10;
}
if (ID3.isFooter(id3Data, offset)) {
offset += 10;
}
}
return frames;
};
ID3._decodeFrame = function _decodeFrame(frame) {
if (frame.type === 'PRIV') {
return ID3._decodePrivFrame(frame);
} else if (frame.type[0] === 'T') {
return ID3._decodeTextFrame(frame);
} else if (frame.type[0] === 'W') {
return ID3._decodeURLFrame(frame);
}
return undefined;
};
ID3._readTimeStamp = function _readTimeStamp(timeStampFrame) {
if (timeStampFrame.data.byteLength === 8) {
var data = new Uint8Array(timeStampFrame.data);
// timestamp is 33 bit expressed as a big-endian eight-octet number,
// with the upper 31 bits set to zero.
var pts33Bit = data[3] & 0x1;
var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
timestamp /= 45;
if (pts33Bit) {
timestamp += 47721858.84; // 2^32 / 90
}
return Math.round(timestamp);
}
return undefined;
};
ID3._decodePrivFrame = function _decodePrivFrame(frame) {
/*
Format: <text string>\0<binary data>
*/
if (frame.size < 2) {
return undefined;
}
var owner = ID3._utf8ArrayToStr(frame.data);
var privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
return { key: frame.type, info: owner, data: privateData.buffer };
};
ID3._decodeTextFrame = function _decodeTextFrame(frame) {
if (frame.size < 2) {
return undefined;
}
if (frame.type === 'TXXX') {
/*
Format:
[0] = {Text Encoding}
[1-?] = {Description}\0{Value}
*/
var index = 1;
var description = ID3._utf8ArrayToStr(frame.data.subarray(index));
index += description.length + 1;
var value = ID3._utf8ArrayToStr(frame.data.subarray(index));
return { key: frame.type, info: description, data: value };
} else {
/*
Format:
[0] = {Text Encoding}
[1-?] = {Value}
*/
var text = ID3._utf8ArrayToStr(frame.data.subarray(1));
return { key: frame.type, data: text };
}
};
ID3._decodeURLFrame = function _decodeURLFrame(frame) {
if (frame.type === 'WXXX') {
/*
Format:
[0] = {Text Encoding}
[1-?] = {Description}\0{URL}
*/
if (frame.size < 2) {
return undefined;
}
var index = 1;
var description = ID3._utf8ArrayToStr(frame.data.subarray(index));
index += description.length + 1;
var value = ID3._utf8ArrayToStr(frame.data.subarray(index));
return { key: frame.type, info: description, data: value };
} else {
/*
Format:
[0-?] = {URL}
*/
var url = ID3._utf8ArrayToStr(frame.data);
return { key: frame.type, data: url };
}
};
// http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
/* utf.js - UTF-8 <=> UTF-16 convertion
*
* Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
* Version: 1.0
* LastModified: Dec 25 1999
* This library is free. You can redistribute it and/or modify it.
*/
ID3._utf8ArrayToStr = function _utf8ArrayToStr(array) {
var char2 = void 0;
var char3 = void 0;
var out = '';
var i = 0;
var length = array.length;
while (i < length) {
var c = array[i++];
switch (c >> 4) {
case 0:
return out;
case 1:case 2:case 3:case 4:case 5:case 6:case 7:
// 0xxxxxxx
out += String.fromCharCode(c);
break;
case 12:case 13:
// 110x xxxx 10xx xxxx
char2 = array[i++];
out += String.fromCharCode((c & 0x1F) << 6 | char2 & 0x3F);
break;
case 14:
// 1110 xxxx 10xx xxxx 10xx xxxx
char2 = array[i++];
char3 = array[i++];
out += String.fromCharCode((c & 0x0F) << 12 | (char2 & 0x3F) << 6 | (char3 & 0x3F) << 0);
break;
}
}
return out;
};
return ID3;
}();
/* harmony default export */ __webpack_exports__["a"] = (ID3);
/***/ }),
/* 5 */
/***/ (function(module, exports) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
// see https://tools.ietf.org/html/rfc1808
/* jshint ignore:start */
(function(root) {
/* jshint ignore:end */
var URL_REGEX = /^((?:[^\/;?#]+:)?)(\/\/[^\/\;?#]*)?(.*?)??(;.*?)?(\?.*?)?(#.*?)?$/;
var FIRST_SEGMENT_REGEX = /^([^\/;?#]*)(.*)$/;
var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/).*?(?=\/)/g;
var URLToolkit = { // jshint ignore:line
// If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
// E.g
// With opts.alwaysNormalize = false (default, spec compliant)
// http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
// With opts.alwaysNormalize = true (default, not spec compliant)
// http://a.com/b/cd + /e/f/../g => http://a.com/e/g
buildAbsoluteURL: function(baseURL, relativeURL, opts) {
opts = opts || {};
// remove any remaining space and CRLF
baseURL = baseURL.trim();
relativeURL = relativeURL.trim();
if (!relativeURL) {
// 2a) If the embedded URL is entirely empty, it inherits the
// entire base URL (i.e., is set equal to the base URL)
// and we are done.
if (!opts.alwaysNormalize) {
return baseURL;
}
var basePartsForNormalise = this.parseURL(baseURL);
if (!baseParts) {
throw new Error('Error trying to parse base URL.');
}
basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);
return URLToolkit.buildURLFromParts(basePartsForNormalise);
}
var relativeParts = this.parseURL(relativeURL);
if (!relativeParts) {
throw new Error('Error trying to parse relative URL.');
}
if (relativeParts.scheme) {
// 2b) If the embedded URL starts with a scheme name, it is
// interpreted as an absolute URL and we are done.
if (!opts.alwaysNormalize) {
return relativeURL;
}
relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
return URLToolkit.buildURLFromParts(relativeParts);
}
var baseParts = this.parseURL(baseURL);
if (!baseParts) {
throw new Error('Error trying to parse base URL.');
}
if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
// If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
// This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
baseParts.netLoc = pathParts[1];
baseParts.path = pathParts[2];
}
if (baseParts.netLoc && !baseParts.path) {
baseParts.path = '/';
}
var builtParts = {
// 2c) Otherwise, the embedded URL inherits the scheme of
// the base URL.
scheme: baseParts.scheme,
netLoc: relativeParts.netLoc,
path: null,
params: relativeParts.params,
query: relativeParts.query,
fragment: relativeParts.fragment
};
if (!relativeParts.netLoc) {
// 3) If the embedded URL's <net_loc> is non-empty, we skip to
// Step 7. Otherwise, the embedded URL inherits the <net_loc>
// (if any) of the base URL.
builtParts.netLoc = baseParts.netLoc;
// 4) If the embedded URL path is preceded by a slash "/", the
// path is not relative and we skip to Step 7.
if (relativeParts.path[0] !== '/') {
if (!relativeParts.path) {
// 5) If the embedded URL path is empty (and not preceded by a
// slash), then the embedded URL inherits the base URL path
builtParts.path = baseParts.path;
// 5a) if the embedded URL's <params> is non-empty, we skip to
// step 7; otherwise, it inherits the <params> of the base
// URL (if any) and
if (!relativeParts.params) {
builtParts.params = baseParts.params;
// 5b) if the embedded URL's <query> is non-empty, we skip to
// step 7; otherwise, it inherits the <query> of the base
// URL (if any) and we skip to step 7.
if (!relativeParts.query) {
builtParts.query = baseParts.query;
}
}
} else {
// 6) The last segment of the base URL's path (anything
// following the rightmost slash "/", or the entire path if no
// slash is present) is removed and the embedded URL's path is
// appended in its place.
var baseURLPath = baseParts.path;
var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path;
builtParts.path = URLToolkit.normalizePath(newPath);
}
}
}
if (builtParts.path === null) {
builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;
}
return URLToolkit.buildURLFromParts(builtParts);
},
parseURL: function(url) {
var parts = URL_REGEX.exec(url);
if (!parts) {
return null;
}
return {
scheme: parts[1] || '',
netLoc: parts[2] || '',
path: parts[3] || '',
params: parts[4] || '',
query: parts[5] || '',
fragment: parts[6] || ''
};
},
normalizePath: function(path) {
// The following operations are
// then applied, in order, to the new path:
// 6a) All occurrences of "./", where "." is a complete path
// segment, are removed.
// 6b) If the path ends with "." as a complete path segment,
// that "." is removed.
path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
// 6c) All occurrences of "<segment>/../", where <segment> is a
// complete path segment not equal to "..", are removed.
// Removal of these path segments is performed iteratively,
// removing the leftmost matching pattern on each iteration,
// until no matching pattern remains.
// 6d) If the path ends with "<segment>/..", where <segment> is a
// complete path segment not equal to "..", that
// "<segment>/.." is removed.
while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {} // jshint ignore:line
return path.split('').reverse().join('');
},
buildURLFromParts: function(parts) {
return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
}
};
/* jshint ignore:start */
if(true)
module.exports = URLToolkit;
else if(typeof define === 'function' && define.amd)
define([], function() { return URLToolkit; });
else if(typeof exports === 'object')
exports["URLToolkit"] = URLToolkit;
else
root["URLToolkit"] = URLToolkit;
})(this);
/* jshint ignore:end */
/***/ }),
/* 7 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXTERNAL MODULE: ./src/events.js
var events = __webpack_require__(1);
// EXTERNAL MODULE: ./src/errors.js
var errors = __webpack_require__(2);
// CONCATENATED MODULE: ./src/crypt/aes-crypto.js
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var AESCrypto = function () {
function AESCrypto(subtle, iv) {
_classCallCheck(this, AESCrypto);
this.subtle = subtle;
this.aesIV = iv;
}
AESCrypto.prototype.decrypt = function decrypt(data, key) {
return this.subtle.decrypt({ name: 'AES-CBC', iv: this.aesIV }, key, data);
};
return AESCrypto;
}();
/* harmony default export */ var aes_crypto = (AESCrypto);
// CONCATENATED MODULE: ./src/crypt/fast-aes-key.js
function fast_aes_key__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var FastAESKey = function () {
function FastAESKey(subtle, key) {
fast_aes_key__classCallCheck(this, FastAESKey);
this.subtle = subtle;
this.key = key;
}
FastAESKey.prototype.expandKey = function expandKey() {
return this.subtle.importKey('raw', this.key, { name: 'AES-CBC' }, false, ['encrypt', 'decrypt']);
};
return FastAESKey;
}();
/* harmony default export */ var fast_aes_key = (FastAESKey);
// CONCATENATED MODULE: ./src/crypt/aes-decryptor.js
function aes_decryptor__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var AESDecryptor = function () {
function AESDecryptor() {
aes_decryptor__classCallCheck(this, AESDecryptor);
// Static after running initTable
this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
this.sBox = new Uint32Array(256);
this.invSBox = new Uint32Array(256);
// Changes during runtime
this.key = new Uint32Array(0);
this.initTable();
}
// Using view.getUint32() also swaps the byte order.
AESDecryptor.prototype.uint8ArrayToUint32Array_ = function uint8ArrayToUint32Array_(arrayBuffer) {
var view = new DataView(arrayBuffer);
var newArray = new Uint32Array(4);
for (var i = 0; i < 4; i++) {
newArray[i] = view.getUint32(i * 4);
}
return newArray;
};
AESDecryptor.prototype.initTable = function initTable() {
var sBox = this.sBox;
var invSBox = this.invSBox;
var subMix = this.subMix;
var subMix0 = subMix[0];
var subMix1 = subMix[1];
var subMix2 = subMix[2];
var subMix3 = subMix[3];
var invSubMix = this.invSubMix;
var invSubMix0 = invSubMix[0];
var invSubMix1 = invSubMix[1];
var invSubMix2 = invSubMix[2];
var invSubMix3 = invSubMix[3];
var d = new Uint32Array(256);
var x = 0;
var xi = 0;
var i = 0;
for (i = 0; i < 256; i++) {
if (i < 128) {
d[i] = i << 1;
} else {
d[i] = i << 1 ^ 0x11b;
}
}
for (i = 0; i < 256; i++) {
var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
sBox[x] = sx;
invSBox[sx] = x;
// Compute multiplication
var x2 = d[x];
var x4 = d[x2];
var x8 = d[x4];
// Compute sub/invSub bytes, mix columns tables
var t = d[sx] * 0x101 ^ sx * 0x1010100;
subMix0[x] = t << 24 | t >>> 8;
subMix1[x] = t << 16 | t >>> 16;
subMix2[x] = t << 8 | t >>> 24;
subMix3[x] = t;
// Compute inv sub bytes, inv mix columns tables
t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
invSubMix0[sx] = t << 24 | t >>> 8;
invSubMix1[sx] = t << 16 | t >>> 16;
invSubMix2[sx] = t << 8 | t >>> 24;
invSubMix3[sx] = t;
// Compute next counter
if (!x) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
};
AESDecryptor.prototype.expandKey = function expandKey(keyBuffer) {
// convert keyBuffer to Uint32Array
var key = this.uint8ArrayToUint32Array_(keyBuffer);
var sameKey = true;
var offset = 0;
while (offset < key.length && sameKey) {
sameKey = key[offset] === this.key[offset];
offset++;
}
if (sameKey) {
return;
}
this.key = key;
var keySize = this.keySize = key.length;
if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
throw new Error('Invalid aes key size=' + keySize);
}
var ksRows = this.ksRows = (keySize + 6 + 1) * 4;
var ksRow = void 0;
var invKsRow = void 0;
var keySchedule = this.keySchedule = new Uint32Array(ksRows);
var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
var sbox = this.sBox;
var rcon = this.rcon;
var invSubMix = this.invSubMix;
var invSubMix0 = invSubMix[0];
var invSubMix1 = invSubMix[1];
var invSubMix2 = invSubMix[2];
var invSubMix3 = invSubMix[3];
var prev = void 0;
var t = void 0;
for (ksRow = 0; ksRow < ksRows; ksRow++) {
if (ksRow < keySize) {
prev = keySchedule[ksRow] = key[ksRow];
continue;
}
t = prev;
if (ksRow % keySize === 0) {
// Rot word
t = t << 8 | t >>> 24;
// Sub word
t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
// Mix Rcon
t ^= rcon[ksRow / keySize | 0] << 24;
} else if (keySize > 6 && ksRow % keySize === 4) {
// Sub word
t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
}
keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
}
for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
ksRow = ksRows - invKsRow;
if (invKsRow & 3) {
t = keySchedule[ksRow];
} else {
t = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t;
} else {
invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
}
invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
}
};
// Adding this as a method greatly improves performance.
AESDecryptor.prototype.networkToHostOrderSwap = function networkToHostOrderSwap(word) {
return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
};
AESDecryptor.prototype.decrypt = function decrypt(inputArrayBuffer, offset, aesIV) {
var nRounds = this.keySize + 6;
var invKeySchedule = this.invKeySchedule;
var invSBOX = this.invSBox;
var invSubMix = this.invSubMix;
var invSubMix0 = invSubMix[0];
var invSubMix1 = invSubMix[1];
var invSubMix2 = invSubMix[2];
var invSubMix3 = invSubMix[3];
var initVector = this.uint8ArrayToUint32Array_(aesIV);
var initVector0 = initVector[0];
var initVector1 = initVector[1];
var initVector2 = initVector[2];
var initVector3 = initVector[3];
var inputInt32 = new Int32Array(inputArrayBuffer);
var outputInt32 = new Int32Array(inputInt32.length);
var t0 = void 0,
t1 = void 0,
t2 = void 0,
t3 = void 0;
var s0 = void 0,
s1 = void 0,
s2 = void 0,
s3 = void 0;
var inputWords0 = void 0,
inputWords1 = void 0,
inputWords2 = void 0,
inputWords3 = void 0;
var ksRow, i;
var swapWord = this.networkToHostOrderSwap;
while (offset < inputInt32.length) {
inputWords0 = swapWord(inputInt32[offset]);
inputWords1 = swapWord(inputInt32[offset + 1]);
inputWords2 = swapWord(inputInt32[offset + 2]);
inputWords3 = swapWord(inputInt32[offset + 3]);
s0 = inputWords0 ^ invKeySchedule[0];
s1 = inputWords3 ^ invKeySchedule[1];
s2 = inputWords2 ^ invKeySchedule[2];
s3 = inputWords1 ^ invKeySchedule[3];
ksRow = 4;
// Iterate through the rounds of decryption
for (i = 1; i < nRounds; i++) {
t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
// Update state
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
ksRow = ksRow + 4;
}
// Shift rows, sub bytes, add round key
t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
ksRow = ksRow + 3;
// Write
outputInt32[offset] = swapWord(t0 ^ initVector0);
outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
// reset initVector to last 4 unsigned int
initVector0 = inputWords0;
initVector1 = inputWords1;
initVector2 = inputWords2;
initVector3 = inputWords3;
offset = offset + 4;
}
return outputInt32.buffer;
};
AESDecryptor.prototype.destroy = function destroy() {
this.key = undefined;
this.keySize = undefined;
this.ksRows = undefined;
this.sBox = undefined;
this.invSBox = undefined;
this.subMix = undefined;
this.invSubMix = undefined;
this.keySchedule = undefined;
this.invKeySchedule = undefined;
this.rcon = undefined;
};
return AESDecryptor;
}();
/* harmony default export */ var aes_decryptor = (AESDecryptor);
// EXTERNAL MODULE: ./src/utils/logger.js
var logger = __webpack_require__(0);
// CONCATENATED MODULE: ./src/crypt/decrypter.js
function decrypter__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/*globals self: false */
var decrypter_Decrypter = function () {
function Decrypter(observer, config) {
decrypter__classCallCheck(this, Decrypter);
this.observer = observer;
this.config = config;
this.logEnabled = true;
try {
var browserCrypto = crypto ? crypto : self.crypto;
this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
} catch (e) {}
this.disableWebCrypto = !this.subtle;
}
Decrypter.prototype.isSync = function isSync() {
return this.disableWebCrypto && this.config.enableSoftwareAES;
};
Decrypter.prototype.decrypt = function decrypt(data, key, iv, callback) {
var _this = this;
if (this.disableWebCrypto && this.config.enableSoftwareAES) {
if (this.logEnabled) {
logger["b" /* logger */].log('JS AES decrypt');
this.logEnabled = false;
}
var decryptor = this.decryptor;
if (!decryptor) {
this.decryptor = decryptor = new aes_decryptor();
}
decryptor.expandKey(key);
callback(decryptor.decrypt(data, 0, iv));
} else {
if (this.logEnabled) {
logger["b" /* logger */].log('WebCrypto AES decrypt');
this.logEnabled = false;
}
var subtle = this.subtle;
if (this.key !== key) {
this.key = key;
this.fastAesKey = new fast_aes_key(subtle, key);
}
this.fastAesKey.expandKey().then(function (aesKey) {
// decrypt using web crypto
var crypto = new aes_crypto(subtle, iv);
crypto.decrypt(data, aesKey).catch(function (err) {
_this.onWebCryptoError(err, data, key, iv, callback);
}).then(function (result) {
callback(result);
});
}).catch(function (err) {
_this.onWebCryptoError(err, data, key, iv, callback);
});
}
};
Decrypter.prototype.onWebCryptoError = function onWebCryptoError(err, data, key, iv, callback) {
if (this.config.enableSoftwareAES) {
logger["b" /* logger */].log('WebCrypto Error, disable WebCrypto API');
this.disableWebCrypto = true;
this.logEnabled = true;
this.decrypt(data, key, iv, callback);
} else {
logger["b" /* logger */].error('decrypting error : ' + err.message);
this.observer.trigger(Event.ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_DECRYPT_ERROR, fatal: true, reason: err.message });
}
};
Decrypter.prototype.destroy = function destroy() {
var decryptor = this.decryptor;
if (decryptor) {
decryptor.destroy();
this.decryptor = undefined;
}
};
return Decrypter;
}();
/* harmony default export */ var crypt_decrypter = (decrypter_Decrypter);
// CONCATENATED MODULE: ./src/demux/adts.js
/**
* ADTS parser helper
*/
function getAudioConfig(observer, data, offset, audioCodec) {
var adtsObjectType,
// :int
adtsSampleingIndex,
// :int
adtsExtensionSampleingIndex,
// :int
adtsChanelConfig,
// :int
config,
userAgent = navigator.userAgent.toLowerCase(),
manifestCodec = audioCodec,
adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
// byte 2
adtsObjectType = ((data[offset + 2] & 0xC0) >>> 6) + 1;
adtsSampleingIndex = (data[offset + 2] & 0x3C) >>> 2;
if (adtsSampleingIndex > adtsSampleingRates.length - 1) {
observer.trigger(Event.ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: true, reason: 'invalid ADTS sampling index:' + adtsSampleingIndex });
return;
}
adtsChanelConfig = (data[offset + 2] & 0x01) << 2;
// byte 3
adtsChanelConfig |= (data[offset + 3] & 0xC0) >>> 6;
logger["b" /* logger */].log('manifest codec:' + audioCodec + ',ADTS data:type:' + adtsObjectType + ',sampleingIndex:' + adtsSampleingIndex + '[' + adtsSampleingRates[adtsSampleingIndex] + 'Hz],channelConfig:' + adtsChanelConfig);
// firefox: freq less than 24kHz = AAC SBR (HE-AAC)
if (/firefox/i.test(userAgent)) {
if (adtsSampleingIndex >= 6) {
adtsObjectType = 5;
config = new Array(4);
// HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
// there is a factor 2 between frame sample rate and output sample rate
// multiply frequency by 2 (see table below, equivalent to substract 3)
adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
} else {
adtsObjectType = 2;
config = new Array(2);
adtsExtensionSampleingIndex = adtsSampleingIndex;
}
// Android : always use AAC
} else if (userAgent.indexOf('android') !== -1) {
adtsObjectType = 2;
config = new Array(2);
adtsExtensionSampleingIndex = adtsSampleingIndex;
} else {
/* for other browsers (Chrome/Vivaldi/Opera ...)
always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
*/
adtsObjectType = 5;
config = new Array(4);
// if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSampleingIndex >= 6) {
// HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
// there is a factor 2 between frame sample rate and output sample rate
// multiply frequency by 2 (see table below, equivalent to substract 3)
adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
} else {
// if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)
// Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.
if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && (adtsSampleingIndex >= 6 && adtsChanelConfig === 1 || /vivaldi/i.test(userAgent)) || !audioCodec && adtsChanelConfig === 1) {
adtsObjectType = 2;
config = new Array(2);
}
adtsExtensionSampleingIndex = adtsSampleingIndex;
}
}
/* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()
Audio Profile / Audio Object Type
0: Null
1: AAC Main
2: AAC LC (Low Complexity)
3: AAC SSR (Scalable Sample Rate)
4: AAC LTP (Long Term Prediction)
5: SBR (Spectral Band Replication)
6: AAC Scalable
sampling freq
0: 96000 Hz
1: 88200 Hz
2: 64000 Hz
3: 48000 Hz
4: 44100 Hz
5: 32000 Hz
6: 24000 Hz
7: 22050 Hz
8: 16000 Hz
9: 12000 Hz
10: 11025 Hz
11: 8000 Hz
12: 7350 Hz
13: Reserved
14: Reserved
15: frequency is written explictly
Channel Configurations
These are the channel configurations:
0: Defined in AOT Specifc Config
1: 1 channel: front-center
2: 2 channels: front-left, front-right
*/
// audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
config[0] = adtsObjectType << 3;
// samplingFrequencyIndex
config[0] |= (adtsSampleingIndex & 0x0E) >> 1;
config[1] |= (adtsSampleingIndex & 0x01) << 7;
// channelConfiguration
config[1] |= adtsChanelConfig << 3;
if (adtsObjectType === 5) {
// adtsExtensionSampleingIndex
config[1] |= (adtsExtensionSampleingIndex & 0x0E) >> 1;
config[2] = (adtsExtensionSampleingIndex & 0x01) << 7;
// adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???
// https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc
config[2] |= 2 << 2;
config[3] = 0;
}
return { config: config, samplerate: adtsSampleingRates[adtsSampleingIndex], channelCount: adtsChanelConfig, codec: 'mp4a.40.' + adtsObjectType, manifestCodec: manifestCodec };
}
function isHeaderPattern(data, offset) {
return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
}
function getHeaderLength(data, offset) {
return !!(data[offset + 1] & 0x01) ? 7 : 9;
}
function getFullFrameLength(data, offset) {
return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5;
}
function isHeader(data, offset) {
// Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
// Layer bits (position 14 and 15) in header should be always 0 for ADTS
// More info https://wiki.multimedia.cx/index.php?title=ADTS
if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
return true;
}
return false;
}
function adts_probe(data, offset) {
// same as isHeader but we also check that ADTS frame follows last ADTS frame
// or end of data is reached
if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
// ADTS header Length
var headerLength = getHeaderLength(data, offset);
// ADTS frame Length
var frameLength = headerLength;
if (offset + 5 < data.length) {
frameLength = getFullFrameLength(data, offset);
}
var newOffset = offset + frameLength;
if (newOffset === data.length || newOffset + 1 < data.length && isHeaderPattern(data, newOffset)) {
return true;
}
}
return false;
}
function initTrackConfig(track, observer, data, offset, audioCodec) {
if (!track.samplerate) {
var config = getAudioConfig(observer, data, offset, audioCodec);
track.config = config.config;
track.samplerate = config.samplerate;
track.channelCount = config.channelCount;
track.codec = config.codec;
track.manifestCodec = config.manifestCodec;
logger["b" /* logger */].log('parsed codec:' + track.codec + ',rate:' + config.samplerate + ',nb channel:' + config.channelCount);
}
}
function getFrameDuration(samplerate) {
return 1024 * 90000 / samplerate;
}
function parseFrameHeader(data, offset, pts, frameIndex, frameDuration) {
var headerLength, frameLength, stamp;
var length = data.length;
// The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
headerLength = getHeaderLength(data, offset);
// retrieve frame size
frameLength = getFullFrameLength(data, offset);
frameLength -= headerLength;
if (frameLength > 0 && offset + headerLength + frameLength <= length) {
stamp = pts + frameIndex * frameDuration;
//logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
return { headerLength: headerLength, frameLength: frameLength, stamp: stamp };
}
return undefined;
}
function appendFrame(track, data, offset, pts, frameIndex) {
var frameDuration = getFrameDuration(track.samplerate);
var header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);
if (header) {
var stamp = header.stamp;
var headerLength = header.headerLength;
var frameLength = header.frameLength;
//logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
var aacSample = {
unit: data.subarray(offset + headerLength, offset + headerLength + frameLength),
pts: stamp,
dts: stamp
};
track.samples.push(aacSample);
track.len += frameLength;
return { sample: aacSample, length: frameLength + headerLength };
}
return undefined;
}
// EXTERNAL MODULE: ./src/demux/id3.js
var id3 = __webpack_require__(4);
// CONCATENATED MODULE: ./src/demux/aacdemuxer.js
function aacdemuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* AAC demuxer
*/
var aacdemuxer_AACDemuxer = function () {
function AACDemuxer(observer, remuxer, config) {
aacdemuxer__classCallCheck(this, AACDemuxer);
this.observer = observer;
this.config = config;
this.remuxer = remuxer;
}
AACDemuxer.prototype.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
this._audioTrack = { container: 'audio/adts', type: 'audio', id: 0, sequenceNumber: 0, isAAC: true, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };
};
AACDemuxer.prototype.resetTimeStamp = function resetTimeStamp() {};
AACDemuxer.probe = function probe(data) {
if (!data) {
return false;
}
// Check for the ADTS sync word
// Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
// Layer bits (position 14 and 15) in header should be always 0 for ADTS
// More info https://wiki.multimedia.cx/index.php?title=ADTS
var id3Data = id3["a" /* default */].getID3Data(data, 0) || [];
var offset = id3Data.length;
for (var length = data.length; offset < length; offset++) {
if (adts_probe(data, offset)) {
logger["b" /* logger */].log('ADTS sync word found !');
return true;
}
}
return false;
};
// feed incoming data to the front of the parsing pipeline
AACDemuxer.prototype.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {
var track = this._audioTrack;
var id3Data = id3["a" /* default */].getID3Data(data, 0) || [];
var timestamp = id3["a" /* default */].getTimeStamp(id3Data);
var pts = timestamp ? 90 * timestamp : timeOffset * 90000;
var frameIndex = 0;
var stamp = pts;
var length = data.length;
var offset = id3Data.length;
var id3Samples = [{ pts: stamp, dts: stamp, data: id3Data }];
while (offset < length - 1) {
if (isHeader(data, offset) && offset + 5 < length) {
initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
var frame = appendFrame(track, data, offset, pts, frameIndex);
if (frame) {
offset += frame.length;
stamp = frame.sample.pts;
frameIndex++;
} else {
logger["b" /* logger */].log('Unable to parse AAC frame');
break;
}
} else if (id3["a" /* default */].isHeader(data, offset)) {
id3Data = id3["a" /* default */].getID3Data(data, offset);
id3Samples.push({ pts: stamp, dts: stamp, data: id3Data });
offset += id3Data.length;
} else {
//nothing found, keep looking
offset++;
}
}
this.remuxer.remux(track, { samples: [] }, { samples: id3Samples, inputTimeScale: 90000 }, { samples: [] }, timeOffset, contiguous, accurateTimeOffset);
};
AACDemuxer.prototype.destroy = function destroy() {};
return AACDemuxer;
}();
/* harmony default export */ var aacdemuxer = (aacdemuxer_AACDemuxer);
// CONCATENATED MODULE: ./src/demux/mp4demuxer.js
function mp4demuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* MP4 demuxer
*/
var UINT32_MAX = Math.pow(2, 32) - 1;
var mp4demuxer_MP4Demuxer = function () {
function MP4Demuxer(observer, remuxer) {
mp4demuxer__classCallCheck(this, MP4Demuxer);
this.observer = observer;
this.remuxer = remuxer;
}
MP4Demuxer.prototype.resetTimeStamp = function resetTimeStamp(initPTS) {
this.initPTS = initPTS;
};
MP4Demuxer.prototype.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
//jshint unused:false
if (initSegment && initSegment.byteLength) {
var initData = this.initData = MP4Demuxer.parseInitSegment(initSegment);
// default audio codec if nothing specified
// TODO : extract that from initsegment
if (audioCodec == null) {
audioCodec = 'mp4a.40.5';
}
if (videoCodec == null) {
videoCodec = 'avc1.42e01e';
}
var tracks = {};
if (initData.audio && initData.video) {
tracks.audiovideo = { container: 'video/mp4', codec: audioCodec + ',' + videoCodec, initSegment: duration ? initSegment : null };
} else {
if (initData.audio) {
tracks.audio = { container: 'audio/mp4', codec: audioCodec, initSegment: duration ? initSegment : null };
}
if (initData.video) {
tracks.video = { container: 'video/mp4', codec: videoCodec, initSegment: duration ? initSegment : null };
}
}
this.observer.trigger(events["a" /* default */].FRAG_PARSING_INIT_SEGMENT, { tracks: tracks });
} else {
if (audioCodec) {
this.audioCodec = audioCodec;
}
if (videoCodec) {
this.videoCodec = videoCodec;
}
}
};
MP4Demuxer.probe = function probe(data) {
// ensure we find a moof box in the first 16 kB
return MP4Demuxer.findBox({ data: data, start: 0, end: Math.min(data.length, 16384) }, ['moof']).length > 0;
};
MP4Demuxer.bin2str = function bin2str(buffer) {
return String.fromCharCode.apply(null, buffer);
};
MP4Demuxer.readUint32 = function readUint32(buffer, offset) {
if (buffer.data) {
offset += buffer.start;
buffer = buffer.data;
}
var val = buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
return val < 0 ? 4294967296 + val : val;
};
MP4Demuxer.writeUint32 = function writeUint32(buffer, offset, value) {
if (buffer.data) {
offset += buffer.start;
buffer = buffer.data;
}
buffer[offset] = value >> 24;
buffer[offset + 1] = value >> 16 & 0xff;
buffer[offset + 2] = value >> 8 & 0xff;
buffer[offset + 3] = value & 0xff;
};
// Find the data for a box specified by its path
MP4Demuxer.findBox = function findBox(data, path) {
var results = [],
i,
size,
type,
end,
subresults,
start,
endbox;
if (data.data) {
start = data.start;
end = data.end;
data = data.data;
} else {
start = 0;
end = data.byteLength;
}
if (!path.length) {
// short-circuit the search for empty paths
return null;
}
for (i = start; i < end;) {
size = MP4Demuxer.readUint32(data, i);
type = MP4Demuxer.bin2str(data.subarray(i + 4, i + 8));
endbox = size > 1 ? i + size : end;
if (type === path[0]) {
if (path.length === 1) {
// this is the end of the path and we've found the box we were
// looking for
results.push({ data: data, start: i + 8, end: endbox });
} else {
// recursively search for the next box along the path
subresults = MP4Demuxer.findBox({ data: data, start: i + 8, end: endbox }, path.slice(1));
if (subresults.length) {
results = results.concat(subresults);
}
}
}
i = endbox;
}
// we've finished searching all of data
return results;
};
/**
* Parses an MP4 initialization segment and extracts stream type and
* timescale values for any declared tracks. Timescale values indicate the
* number of clock ticks per second to assume for time-based values
* elsewhere in the MP4.
*
* To determine the start time of an MP4, you need two pieces of
* information: the timescale unit and the earliest base media decode
* time. Multiple timescales can be specified within an MP4 but the
* base media decode time is always expressed in the timescale from
* the media header box for the track:
* ```
* moov > trak > mdia > mdhd.timescale
* moov > trak > mdia > hdlr
* ```
* @param init {Uint8Array} the bytes of the init segment
* @return {object} a hash of track type to timescale values or null if
* the init segment is malformed.
*/
MP4Demuxer.parseInitSegment = function parseInitSegment(initSegment) {
var result = [];
var traks = MP4Demuxer.findBox(initSegment, ['moov', 'trak']);
traks.forEach(function (trak) {
var tkhd = MP4Demuxer.findBox(trak, ['tkhd'])[0];
if (tkhd) {
var version = tkhd.data[tkhd.start];
var index = version === 0 ? 12 : 20;
var trackId = MP4Demuxer.readUint32(tkhd, index);
var mdhd = MP4Demuxer.findBox(trak, ['mdia', 'mdhd'])[0];
if (mdhd) {
version = mdhd.data[mdhd.start];
index = version === 0 ? 12 : 20;
var timescale = MP4Demuxer.readUint32(mdhd, index);
var hdlr = MP4Demuxer.findBox(trak, ['mdia', 'hdlr'])[0];
if (hdlr) {
var hdlrType = MP4Demuxer.bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12));
var type = { 'soun': 'audio', 'vide': 'video' }[hdlrType];
if (type) {
// extract codec info. TODO : parse codec details to be able to build MIME type
var codecBox = MP4Demuxer.findBox(trak, ['mdia', 'minf', 'stbl', 'stsd']);
if (codecBox.length) {
codecBox = codecBox[0];
var codecType = MP4Demuxer.bin2str(codecBox.data.subarray(codecBox.start + 12, codecBox.start + 16));
logger["b" /* logger */].log('MP4Demuxer:' + type + ':' + codecType + ' found');
}
result[trackId] = { timescale: timescale, type: type };
result[type] = { timescale: timescale, id: trackId };
}
}
}
}
});
return result;
};
/**
* Determine the base media decode start time, in seconds, for an MP4
* fragment. If multiple fragments are specified, the earliest time is
* returned.
*
* The base media decode time can be parsed from track fragment
* metadata:
* ```
* moof > traf > tfdt.baseMediaDecodeTime
* ```
* It requires the timescale value from the mdhd to interpret.
*
* @param timescale {object} a hash of track ids to timescale values.
* @return {number} the earliest base media decode start time for the
* fragment, in seconds
*/
MP4Demuxer.getStartDTS = function getStartDTS(initData, fragment) {
var trafs, baseTimes, result;
// we need info from two childrend of each track fragment box
trafs = MP4Demuxer.findBox(fragment, ['moof', 'traf']);
// determine the start times for each track
baseTimes = [].concat.apply([], trafs.map(function (traf) {
return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {
var id, scale, baseTime;
// get the track id from the tfhd
id = MP4Demuxer.readUint32(tfhd, 4);
// assume a 90kHz clock if no timescale was specified
scale = initData[id].timescale || 90e3;
// get the base media decode time from the tfdt
baseTime = MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {
var version, result;
version = tfdt.data[tfdt.start];
result = MP4Demuxer.readUint32(tfdt, 4);
if (version === 1) {
result *= Math.pow(2, 32);
result += MP4Demuxer.readUint32(tfdt, 8);
}
return result;
})[0];
// convert base time to seconds
return baseTime / scale;
});
}));
// return the minimum
result = Math.min.apply(null, baseTimes);
return isFinite(result) ? result : 0;
};
MP4Demuxer.offsetStartDTS = function offsetStartDTS(initData, fragment, timeOffset) {
MP4Demuxer.findBox(fragment, ['moof', 'traf']).map(function (traf) {
return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {
// get the track id from the tfhd
var id = MP4Demuxer.readUint32(tfhd, 4);
// assume a 90kHz clock if no timescale was specified
var timescale = initData[id].timescale || 90e3;
// get the base media decode time from the tfdt
MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {
var version = tfdt.data[tfdt.start];
var baseMediaDecodeTime = MP4Demuxer.readUint32(tfdt, 4);
if (version === 0) {
MP4Demuxer.writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset * timescale);
} else {
baseMediaDecodeTime *= Math.pow(2, 32);
baseMediaDecodeTime += MP4Demuxer.readUint32(tfdt, 8);
baseMediaDecodeTime -= timeOffset * timescale;
baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
var lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
MP4Demuxer.writeUint32(tfdt, 4, upper);
MP4Demuxer.writeUint32(tfdt, 8, lower);
}
});
});
});
};
// feed incoming data to the front of the parsing pipeline
MP4Demuxer.prototype.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {
var initData = this.initData;
if (!initData) {
this.resetInitSegment(data, this.audioCodec, this.videoCodec);
initData = this.initData;
}
var startDTS = void 0,
initPTS = this.initPTS;
if (initPTS === undefined) {
var _startDTS = MP4Demuxer.getStartDTS(initData, data);
this.initPTS = initPTS = _startDTS - timeOffset;
this.observer.trigger(events["a" /* default */].INIT_PTS_FOUND, { initPTS: initPTS });
}
MP4Demuxer.offsetStartDTS(initData, data, initPTS);
startDTS = MP4Demuxer.getStartDTS(initData, data);
this.remuxer.remux(initData.audio, initData.video, null, null, startDTS, contiguous, accurateTimeOffset, data);
};
MP4Demuxer.prototype.destroy = function destroy() {};
return MP4Demuxer;
}();
/* harmony default export */ var mp4demuxer = (mp4demuxer_MP4Demuxer);
// CONCATENATED MODULE: ./src/demux/mpegaudio.js
/**
* MPEG parser helper
*/
var MpegAudio = {
BitratesMap: [32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],
SamplingRateMap: [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000],
appendFrame: function appendFrame(track, data, offset, pts, frameIndex) {
// Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
if (offset + 24 > data.length) {
return undefined;
}
var header = this.parseHeader(data, offset);
if (header && offset + header.frameLength <= data.length) {
var frameDuration = 1152 * 90000 / header.sampleRate;
var stamp = pts + frameIndex * frameDuration;
var sample = { unit: data.subarray(offset, offset + header.frameLength), pts: stamp, dts: stamp };
track.config = [];
track.channelCount = header.channelCount;
track.samplerate = header.sampleRate;
track.samples.push(sample);
track.len += header.frameLength;
return { sample: sample, length: header.frameLength };
}
return undefined;
},
parseHeader: function parseHeader(data, offset) {
var headerB = data[offset + 1] >> 3 & 3;
var headerC = data[offset + 1] >> 1 & 3;
var headerE = data[offset + 2] >> 4 & 15;
var headerF = data[offset + 2] >> 2 & 3;
var headerG = !!(data[offset + 2] & 2);
if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) {
var columnInBitrates = headerB === 3 ? 3 - headerC : headerC === 3 ? 3 : 4;
var bitRate = MpegAudio.BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;
var columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;
var sampleRate = MpegAudio.SamplingRateMap[columnInSampleRates * 3 + headerF];
var padding = headerG ? 1 : 0;
var channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
var frameLength = headerC === 3 ? (headerB === 3 ? 12 : 6) * bitRate / sampleRate + padding << 2 : (headerB === 3 ? 144 : 72) * bitRate / sampleRate + padding | 0;
return { sampleRate: sampleRate, channelCount: channelCount, frameLength: frameLength };
}
return undefined;
},
isHeaderPattern: function isHeaderPattern(data, offset) {
return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
},
isHeader: function isHeader(data, offset) {
// Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
// Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
// More info http://www.mp3-tech.org/programmer/frame_header.html
if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {
return true;
}
return false;
},
probe: function probe(data, offset) {
// same as isHeader but we also check that MPEG frame follows last MPEG frame
// or end of data is reached
if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {
// MPEG header Length
var headerLength = 4;
// MPEG frame Length
var header = this.parseHeader(data, offset);
var frameLength = headerLength;
if (header && header.frameLength) {
frameLength = header.frameLength;
}
var newOffset = offset + frameLength;
if (newOffset === data.length || newOffset + 1 < data.length && this.isHeaderPattern(data, newOffset)) {
return true;
}
}
return false;
}
};
/* harmony default export */ var mpegaudio = (MpegAudio);
// CONCATENATED MODULE: ./src/demux/exp-golomb.js
function exp_golomb__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
*/
var exp_golomb_ExpGolomb = function () {
function ExpGolomb(data) {
exp_golomb__classCallCheck(this, ExpGolomb);
this.data = data;
// the number of bytes left to examine in this.data
this.bytesAvailable = data.byteLength;
// the current word being examined
this.word = 0; // :uint
// the number of bits left to examine in the current word
this.bitsAvailable = 0; // :uint
}
// ():void
ExpGolomb.prototype.loadWord = function loadWord() {
var data = this.data,
bytesAvailable = this.bytesAvailable,
position = data.byteLength - bytesAvailable,
workingBytes = new Uint8Array(4),
availableBytes = Math.min(4, bytesAvailable);
if (availableBytes === 0) {
throw new Error('no bytes available');
}
workingBytes.set(data.subarray(position, position + availableBytes));
this.word = new DataView(workingBytes.buffer).getUint32(0);
// track the amount of this.data that has been processed
this.bitsAvailable = availableBytes * 8;
this.bytesAvailable -= availableBytes;
};
// (count:int):void
ExpGolomb.prototype.skipBits = function skipBits(count) {
var skipBytes; // :int
if (this.bitsAvailable > count) {
this.word <<= count;
this.bitsAvailable -= count;
} else {
count -= this.bitsAvailable;
skipBytes = count >> 3;
count -= skipBytes >> 3;
this.bytesAvailable -= skipBytes;
this.loadWord();
this.word <<= count;
this.bitsAvailable -= count;
}
};
// (size:int):uint
ExpGolomb.prototype.readBits = function readBits(size) {
var bits = Math.min(this.bitsAvailable, size),
// :uint
valu = this.word >>> 32 - bits; // :uint
if (size > 32) {
logger["b" /* logger */].error('Cannot read more than 32 bits at a time');
}
this.bitsAvailable -= bits;
if (this.bitsAvailable > 0) {
this.word <<= bits;
} else if (this.bytesAvailable > 0) {
this.loadWord();
}
bits = size - bits;
if (bits > 0 && this.bitsAvailable) {
return valu << bits | this.readBits(bits);
} else {
return valu;
}
};
// ():uint
ExpGolomb.prototype.skipLZ = function skipLZ() {
var leadingZeroCount; // :uint
for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
if (0 !== (this.word & 0x80000000 >>> leadingZeroCount)) {
// the first bit of working word is 1
this.word <<= leadingZeroCount;
this.bitsAvailable -= leadingZeroCount;
return leadingZeroCount;
}
}
// we exhausted word and still have not found a 1
this.loadWord();
return leadingZeroCount + this.skipLZ();
};
// ():void
ExpGolomb.prototype.skipUEG = function skipUEG() {
this.skipBits(1 + this.skipLZ());
};
// ():void
ExpGolomb.prototype.skipEG = function skipEG() {
this.skipBits(1 + this.skipLZ());
};
// ():uint
ExpGolomb.prototype.readUEG = function readUEG() {
var clz = this.skipLZ(); // :uint
return this.readBits(clz + 1) - 1;
};
// ():int
ExpGolomb.prototype.readEG = function readEG() {
var valu = this.readUEG(); // :int
if (0x01 & valu) {
// the number is odd if the low order bit is set
return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
} else {
return -1 * (valu >>> 1); // divide by two then make it negative
}
};
// Some convenience functions
// :Boolean
ExpGolomb.prototype.readBoolean = function readBoolean() {
return 1 === this.readBits(1);
};
// ():int
ExpGolomb.prototype.readUByte = function readUByte() {
return this.readBits(8);
};
// ():int
ExpGolomb.prototype.readUShort = function readUShort() {
return this.readBits(16);
};
// ():int
ExpGolomb.prototype.readUInt = function readUInt() {
return this.readBits(32);
};
/**
* Advance the ExpGolomb decoder past a scaling list. The scaling
* list is optionally transmitted as part of a sequence parameter
* set and is not relevant to transmuxing.
* @param count {number} the number of entries in this scaling list
* @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
*/
ExpGolomb.prototype.skipScalingList = function skipScalingList(count) {
var lastScale = 8,
nextScale = 8,
j,
deltaScale;
for (j = 0; j < count; j++) {
if (nextScale !== 0) {
deltaScale = this.readEG();
nextScale = (lastScale + deltaScale + 256) % 256;
}
lastScale = nextScale === 0 ? lastScale : nextScale;
}
};
/**
* Read a sequence parameter set and return some interesting video
* properties. A sequence parameter set is the H264 metadata that
* describes the properties of upcoming video frames.
* @param data {Uint8Array} the bytes of a sequence parameter set
* @return {object} an object with configuration parsed from the
* sequence parameter set, including the dimensions of the
* associated video frames.
*/
ExpGolomb.prototype.readSPS = function readSPS() {
var frameCropLeftOffset = 0,
frameCropRightOffset = 0,
frameCropTopOffset = 0,
frameCropBottomOffset = 0,
profileIdc,
profileCompat,
levelIdc,
numRefFramesInPicOrderCntCycle,
picWidthInMbsMinus1,
picHeightInMapUnitsMinus1,
frameMbsOnlyFlag,
scalingListCount,
i,
readUByte = this.readUByte.bind(this),
readBits = this.readBits.bind(this),
readUEG = this.readUEG.bind(this),
readBoolean = this.readBoolean.bind(this),
skipBits = this.skipBits.bind(this),
skipEG = this.skipEG.bind(this),
skipUEG = this.skipUEG.bind(this),
skipScalingList = this.skipScalingList.bind(this);
readUByte();
profileIdc = readUByte(); // profile_idc
profileCompat = readBits(5); // constraint_set[0-4]_flag, u(5)
skipBits(3); // reserved_zero_3bits u(3),
levelIdc = readUByte(); //level_idc u(8)
skipUEG(); // seq_parameter_set_id
// some profiles have more optional data we don't need
if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
var chromaFormatIdc = readUEG();
if (chromaFormatIdc === 3) {
skipBits(1); // separate_colour_plane_flag
}
skipUEG(); // bit_depth_luma_minus8
skipUEG(); // bit_depth_chroma_minus8
skipBits(1); // qpprime_y_zero_transform_bypass_flag
if (readBoolean()) {
// seq_scaling_matrix_present_flag
scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
for (i = 0; i < scalingListCount; i++) {
if (readBoolean()) {
// seq_scaling_list_present_flag[ i ]
if (i < 6) {
skipScalingList(16);
} else {
skipScalingList(64);
}
}
}
}
}
skipUEG(); // log2_max_frame_num_minus4
var picOrderCntType = readUEG();
if (picOrderCntType === 0) {
readUEG(); //log2_max_pic_order_cnt_lsb_minus4
} else if (picOrderCntType === 1) {
skipBits(1); // delta_pic_order_always_zero_flag
skipEG(); // offset_for_non_ref_pic
skipEG(); // offset_for_top_to_bottom_field
numRefFramesInPicOrderCntCycle = readUEG();
for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
skipEG(); // offset_for_ref_frame[ i ]
}
}
skipUEG(); // max_num_ref_frames
skipBits(1); // gaps_in_frame_num_value_allowed_flag
picWidthInMbsMinus1 = readUEG();
picHeightInMapUnitsMinus1 = readUEG();
frameMbsOnlyFlag = readBits(1);
if (frameMbsOnlyFlag === 0) {
skipBits(1); // mb_adaptive_frame_field_flag
}
skipBits(1); // direct_8x8_inference_flag
if (readBoolean()) {
// frame_cropping_flag
frameCropLeftOffset = readUEG();
frameCropRightOffset = readUEG();
frameCropTopOffset = readUEG();
frameCropBottomOffset = readUEG();
}
var pixelRatio = [1, 1];
if (readBoolean()) {
// vui_parameters_present_flag
if (readBoolean()) {
// aspect_ratio_info_present_flag
var aspectRatioIdc = readUByte();
switch (aspectRatioIdc) {
case 1:
pixelRatio = [1, 1];break;
case 2:
pixelRatio = [12, 11];break;
case 3:
pixelRatio = [10, 11];break;
case 4:
pixelRatio = [16, 11];break;
case 5:
pixelRatio = [40, 33];break;
case 6:
pixelRatio = [24, 11];break;
case 7:
pixelRatio = [20, 11];break;
case 8:
pixelRatio = [32, 11];break;
case 9:
pixelRatio = [80, 33];break;
case 10:
pixelRatio = [18, 11];break;
case 11:
pixelRatio = [15, 11];break;
case 12:
pixelRatio = [64, 33];break;
case 13:
pixelRatio = [160, 99];break;
case 14:
pixelRatio = [4, 3];break;
case 15:
pixelRatio = [3, 2];break;
case 16:
pixelRatio = [2, 1];break;
case 255:
{
pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
break;
}
}
}
}
return {
width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
pixelRatio: pixelRatio
};
};
ExpGolomb.prototype.readSliceType = function readSliceType() {
// skip NALu type
this.readUByte();
// discard first_mb_in_slice
this.readUEG();
// return slice_type
return this.readUEG();
};
return ExpGolomb;
}();
/* harmony default export */ var exp_golomb = (exp_golomb_ExpGolomb);
// CONCATENATED MODULE: ./src/demux/sample-aes.js
function sample_aes__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* SAMPLE-AES decrypter
*/
var sample_aes_SampleAesDecrypter = function () {
function SampleAesDecrypter(observer, config, decryptdata, discardEPB) {
sample_aes__classCallCheck(this, SampleAesDecrypter);
this.decryptdata = decryptdata;
this.discardEPB = discardEPB;
this.decrypter = new crypt_decrypter(observer, config);
}
SampleAesDecrypter.prototype.decryptBuffer = function decryptBuffer(encryptedData, callback) {
this.decrypter.decrypt(encryptedData, this.decryptdata.key.buffer, this.decryptdata.iv.buffer, callback);
};
// AAC - encrypt all full 16 bytes blocks starting from offset 16
SampleAesDecrypter.prototype.decryptAacSample = function decryptAacSample(samples, sampleIndex, callback, sync) {
var curUnit = samples[sampleIndex].unit;
var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
var localthis = this;
this.decryptBuffer(encryptedBuffer, function (decryptedData) {
decryptedData = new Uint8Array(decryptedData);
curUnit.set(decryptedData, 16);
if (!sync) {
localthis.decryptAacSamples(samples, sampleIndex + 1, callback);
}
});
};
SampleAesDecrypter.prototype.decryptAacSamples = function decryptAacSamples(samples, sampleIndex, callback) {
for (;; sampleIndex++) {
if (sampleIndex >= samples.length) {
callback();
return;
}
if (samples[sampleIndex].unit.length < 32) {
continue;
}
var sync = this.decrypter.isSync();
this.decryptAacSample(samples, sampleIndex, callback, sync);
if (!sync) {
return;
}
}
};
// AVC - encrypt one 16 bytes block out of ten, starting from offset 32
SampleAesDecrypter.prototype.getAvcEncryptedData = function getAvcEncryptedData(decodedData) {
var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
var encryptedData = new Int8Array(encryptedDataLen);
var outputPos = 0;
for (var inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) {
encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
}
return encryptedData;
};
SampleAesDecrypter.prototype.getAvcDecryptedUnit = function getAvcDecryptedUnit(decodedData, decryptedData) {
decryptedData = new Uint8Array(decryptedData);
var inputPos = 0;
for (var outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {
decodedData.set(decryptedData.subarray(inputPos, inputPos + 16), outputPos);
}
return decodedData;
};
SampleAesDecrypter.prototype.decryptAvcSample = function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) {
var decodedData = this.discardEPB(curUnit.data);
var encryptedData = this.getAvcEncryptedData(decodedData);
var localthis = this;
this.decryptBuffer(encryptedData.buffer, function (decryptedData) {
curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedData);
if (!sync) {
localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
}
});
};
SampleAesDecrypter.prototype.decryptAvcSamples = function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
for (;; sampleIndex++, unitIndex = 0) {
if (sampleIndex >= samples.length) {
callback();
return;
}
var curUnits = samples[sampleIndex].units;
for (;; unitIndex++) {
if (unitIndex >= curUnits.length) {
break;
}
var curUnit = curUnits[unitIndex];
if (curUnit.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
continue;
}
var sync = this.decrypter.isSync();
this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync);
if (!sync) {
return;
}
}
}
};
return SampleAesDecrypter;
}();
/* harmony default export */ var sample_aes = (sample_aes_SampleAesDecrypter);
// CONCATENATED MODULE: ./src/demux/tsdemuxer.js
function tsdemuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* highly optimized TS demuxer:
* parse PAT, PMT
* extract PES packet from audio and video PIDs
* extract AVC/H264 NAL units and AAC/ADTS samples from PES packet
* trigger the remuxer upon parsing completion
* it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource.
* it also controls the remuxing process :
* upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.
*/
// import Hex from '../utils/hex';
var tsdemuxer_TSDemuxer = function () {
function TSDemuxer(observer, remuxer, config, typeSupported) {
tsdemuxer__classCallCheck(this, TSDemuxer);
this.observer = observer;
this.config = config;
this.typeSupported = typeSupported;
this.remuxer = remuxer;
this.sampleAes = null;
}
TSDemuxer.prototype.setDecryptData = function setDecryptData(decryptdata) {
if (decryptdata != null && decryptdata.key != null && decryptdata.method === 'SAMPLE-AES') {
this.sampleAes = new sample_aes(this.observer, this.config, decryptdata, this.discardEPB);
} else {
this.sampleAes = null;
}
};
TSDemuxer.probe = function probe(data) {
var syncOffset = TSDemuxer._syncOffset(data);
if (syncOffset < 0) {
return false;
} else {
if (syncOffset) {
logger["b" /* logger */].warn('MPEG2-TS detected but first sync word found @ offset ' + syncOffset + ', junk ahead ?');
}
return true;
}
};
TSDemuxer._syncOffset = function _syncOffset(data) {
// scan 1000 first bytes
var scanwindow = Math.min(1000, data.length - 3 * 188);
var i = 0;
while (i < scanwindow) {
// a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47
if (data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) {
return i;
} else {
i++;
}
}
return -1;
};
TSDemuxer.prototype.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
this.pmtParsed = false;
this._pmtId = -1;
this._avcTrack = { container: 'video/mp2t', type: 'video', id: -1, inputTimeScale: 90000, sequenceNumber: 0, samples: [], len: 0, dropped: 0 };
this._audioTrack = { container: 'video/mp2t', type: 'audio', id: -1, inputTimeScale: 90000, duration: duration, sequenceNumber: 0, samples: [], len: 0, isAAC: true };
this._id3Track = { type: 'id3', id: -1, inputTimeScale: 90000, sequenceNumber: 0, samples: [], len: 0 };
this._txtTrack = { type: 'text', id: -1, inputTimeScale: 90000, sequenceNumber: 0, samples: [], len: 0 };
// flush any partial content
this.aacOverFlow = null;
this.aacLastPTS = null;
this.avcSample = null;
this.audioCodec = audioCodec;
this.videoCodec = videoCodec;
this._duration = duration;
};
TSDemuxer.prototype.resetTimeStamp = function resetTimeStamp() {};
// feed incoming data to the front of the parsing pipeline
TSDemuxer.prototype.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {
var start,
len = data.length,
stt,
pid,
atf,
offset,
pes,
unknownPIDs = false;
this.contiguous = contiguous;
var pmtParsed = this.pmtParsed,
avcTrack = this._avcTrack,
audioTrack = this._audioTrack,
id3Track = this._id3Track,
avcId = avcTrack.id,
audioId = audioTrack.id,
id3Id = id3Track.id,
pmtId = this._pmtId,
avcData = avcTrack.pesData,
audioData = audioTrack.pesData,
id3Data = id3Track.pesData,
parsePAT = this._parsePAT,
parsePMT = this._parsePMT,
parsePES = this._parsePES,
parseAVCPES = this._parseAVCPES.bind(this),
parseAACPES = this._parseAACPES.bind(this),
parseMPEGPES = this._parseMPEGPES.bind(this),
parseID3PES = this._parseID3PES.bind(this);
var syncOffset = TSDemuxer._syncOffset(data);
// don't parse last TS packet if incomplete
len -= (len + syncOffset) % 188;
// loop through TS packets
for (start = syncOffset; start < len; start += 188) {
if (data[start] === 0x47) {
stt = !!(data[start + 1] & 0x40);
// pid is a 13-bit field starting at the last bit of TS[1]
pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];
atf = (data[start + 3] & 0x30) >> 4;
// if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
if (atf > 1) {
offset = start + 5 + data[start + 4];
// continue if there is only adaptation field
if (offset === start + 188) {
continue;
}
} else {
offset = start + 4;
}
switch (pid) {
case avcId:
if (stt) {
if (avcData && (pes = parsePES(avcData))) {
parseAVCPES(pes, false);
}
avcData = { data: [], size: 0 };
}
if (avcData) {
avcData.data.push(data.subarray(offset, start + 188));
avcData.size += start + 188 - offset;
}
break;
case audioId:
if (stt) {
if (audioData && (pes = parsePES(audioData))) {
if (audioTrack.isAAC) {
parseAACPES(pes);
} else {
parseMPEGPES(pes);
}
}
audioData = { data: [], size: 0 };
}
if (audioData) {
audioData.data.push(data.subarray(offset, start + 188));
audioData.size += start + 188 - offset;
}
break;
case id3Id:
if (stt) {
if (id3Data && (pes = parsePES(id3Data))) {
parseID3PES(pes);
}
id3Data = { data: [], size: 0 };
}
if (id3Data) {
id3Data.data.push(data.subarray(offset, start + 188));
id3Data.size += start + 188 - offset;
}
break;
case 0:
if (stt) {
offset += data[offset] + 1;
}
pmtId = this._pmtId = parsePAT(data, offset);
break;
case pmtId:
if (stt) {
offset += data[offset] + 1;
}
var parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, this.sampleAes != null);
// only update track id if track PID found while parsing PMT
// this is to avoid resetting the PID to -1 in case
// track PID transiently disappears from the stream
// this could happen in case of transient missing audio samples for example
avcId = parsedPIDs.avc;
if (avcId > 0) {
avcTrack.id = avcId;
}
audioId = parsedPIDs.audio;
if (audioId > 0) {
audioTrack.id = audioId;
audioTrack.isAAC = parsedPIDs.isAAC;
}
id3Id = parsedPIDs.id3;
if (id3Id > 0) {
id3Track.id = id3Id;
}
if (unknownPIDs && !pmtParsed) {
logger["b" /* logger */].log('reparse from beginning');
unknownPIDs = false;
// we set it to -188, the += 188 in the for loop will reset start to 0
start = syncOffset - 188;
}
pmtParsed = this.pmtParsed = true;
break;
case 17:
case 0x1fff:
break;
default:
unknownPIDs = true;
break;
}
} else {
this.observer.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: false, reason: 'TS packet did not start with 0x47' });
}
}
// try to parse last PES packets
if (avcData && (pes = parsePES(avcData))) {
parseAVCPES(pes, true);
avcTrack.pesData = null;
} else {
// either avcData null or PES truncated, keep it for next frag parsing
avcTrack.pesData = avcData;
}
if (audioData && (pes = parsePES(audioData))) {
if (audioTrack.isAAC) {
parseAACPES(pes);
} else {
parseMPEGPES(pes);
}
audioTrack.pesData = null;
} else {
if (audioData && audioData.size) {
logger["b" /* logger */].log('last AAC PES packet truncated,might overlap between fragments');
}
// either audioData null or PES truncated, keep it for next frag parsing
audioTrack.pesData = audioData;
}
if (id3Data && (pes = parsePES(id3Data))) {
parseID3PES(pes);
id3Track.pesData = null;
} else {
// either id3Data null or PES truncated, keep it for next frag parsing
id3Track.pesData = id3Data;
}
if (this.sampleAes == null) {
this.remuxer.remux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);
} else {
this.decryptAndRemux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);
}
};
TSDemuxer.prototype.decryptAndRemux = function decryptAndRemux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
if (audioTrack.samples && audioTrack.isAAC) {
var localthis = this;
this.sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {
localthis.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
});
} else {
this.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
}
};
TSDemuxer.prototype.decryptAndRemuxAvc = function decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
if (videoTrack.samples) {
var localthis = this;
this.sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {
localthis.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
});
} else {
this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
}
};
TSDemuxer.prototype.destroy = function destroy() {
this._initPTS = this._initDTS = undefined;
this._duration = 0;
};
TSDemuxer.prototype._parsePAT = function _parsePAT(data, offset) {
// skip the PSI header and parse the first PMT entry
return (data[offset + 10] & 0x1F) << 8 | data[offset + 11];
//logger.log('PMT PID:' + this._pmtId);
};
TSDemuxer.prototype._parsePMT = function _parsePMT(data, offset, mpegSupported, isSampleAes) {
var sectionLength,
tableEnd,
programInfoLength,
pid,
result = { audio: -1, avc: -1, id3: -1, isAAC: true };
sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
tableEnd = offset + 3 + sectionLength - 4;
// to determine where the table is, we have to figure out how
// long the program info descriptors are
programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];
// advance the offset to the first entry in the mapping table
offset += 12 + programInfoLength;
while (offset < tableEnd) {
pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2];
switch (data[offset]) {
case 0xcf:
// SAMPLE-AES AAC
if (!isSampleAes) {
logger["b" /* logger */].log('unkown stream type:' + data[offset]);
break;
}
/* falls through */
// ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
case 0x0f:
//logger.log('AAC PID:' + pid);
if (result.audio === -1) {
result.audio = pid;
}
break;
// Packetized metadata (ID3)
case 0x15:
//logger.log('ID3 PID:' + pid);
if (result.id3 === -1) {
result.id3 = pid;
}
break;
case 0xdb:
// SAMPLE-AES AVC
if (!isSampleAes) {
logger["b" /* logger */].log('unkown stream type:' + data[offset]);
break;
}
/* falls through */
// ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
case 0x1b:
//logger.log('AVC PID:' + pid);
if (result.avc === -1) {
result.avc = pid;
}
break;
// ISO/IEC 11172-3 (MPEG-1 audio)
// or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
case 0x03:
case 0x04:
//logger.log('MPEG PID:' + pid);
if (!mpegSupported) {
logger["b" /* logger */].log('MPEG audio found, not supported in this browser for now');
} else if (result.audio === -1) {
result.audio = pid;
result.isAAC = false;
}
break;
case 0x24:
logger["b" /* logger */].warn('HEVC stream type found, not supported for now');
break;
default:
logger["b" /* logger */].log('unkown stream type:' + data[offset]);
break;
}
// move to the next table entry
// skip past the elementary stream descriptors, if present
offset += ((data[offset + 3] & 0x0F) << 8 | data[offset + 4]) + 5;
}
return result;
};
TSDemuxer.prototype._parsePES = function _parsePES(stream) {
var i = 0,
frag,
pesFlags,
pesPrefix,
pesLen,
pesHdrLen,
pesData,
pesPts,
pesDts,
payloadStartOffset,
data = stream.data;
// safety check
if (!stream || stream.size === 0) {
return null;
}
// we might need up to 19 bytes to read PES header
// if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
// usually only one merge is needed (and this is rare ...)
while (data[0].length < 19 && data.length > 1) {
var newData = new Uint8Array(data[0].length + data[1].length);
newData.set(data[0]);
newData.set(data[1], data[0].length);
data[0] = newData;
data.splice(1, 1);
}
//retrieve PTS/DTS from first fragment
frag = data[0];
pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
if (pesPrefix === 1) {
pesLen = (frag[4] << 8) + frag[5];
// if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
// minus 6 : PES header size
if (pesLen && pesLen > stream.size - 6) {
return null;
}
pesFlags = frag[7];
if (pesFlags & 0xC0) {
/* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
as Bitwise operators treat their operands as a sequence of 32 bits */
pesPts = (frag[9] & 0x0E) * 536870912 + // 1 << 29
(frag[10] & 0xFF) * 4194304 + // 1 << 22
(frag[11] & 0xFE) * 16384 + // 1 << 14
(frag[12] & 0xFF) * 128 + // 1 << 7
(frag[13] & 0xFE) / 2;
// check if greater than 2^32 -1
if (pesPts > 4294967295) {
// decrement 2^33
pesPts -= 8589934592;
}
if (pesFlags & 0x40) {
pesDts = (frag[14] & 0x0E) * 536870912 + // 1 << 29
(frag[15] & 0xFF) * 4194304 + // 1 << 22
(frag[16] & 0xFE) * 16384 + // 1 << 14
(frag[17] & 0xFF) * 128 + // 1 << 7
(frag[18] & 0xFE) / 2;
// check if greater than 2^32 -1
if (pesDts > 4294967295) {
// decrement 2^33
pesDts -= 8589934592;
}
if (pesPts - pesDts > 60 * 90000) {
logger["b" /* logger */].warn(Math.round((pesPts - pesDts) / 90000) + 's delta between PTS and DTS, align them');
pesPts = pesDts;
}
} else {
pesDts = pesPts;
}
}
pesHdrLen = frag[8];
// 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
payloadStartOffset = pesHdrLen + 9;
stream.size -= payloadStartOffset;
//reassemble PES packet
pesData = new Uint8Array(stream.size);
for (var j = 0, dataLen = data.length; j < dataLen; j++) {
frag = data[j];
var len = frag.byteLength;
if (payloadStartOffset) {
if (payloadStartOffset > len) {
// trim full frag if PES header bigger than frag
payloadStartOffset -= len;
continue;
} else {
// trim partial frag if PES header smaller than frag
frag = frag.subarray(payloadStartOffset);
len -= payloadStartOffset;
payloadStartOffset = 0;
}
}
pesData.set(frag, i);
i += len;
}
if (pesLen) {
// payload size : remove PES header + PES extension
pesLen -= pesHdrLen + 3;
}
return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen };
} else {
return null;
}
};
TSDemuxer.prototype.pushAccesUnit = function pushAccesUnit(avcSample, avcTrack) {
if (avcSample.units.length && avcSample.frame) {
var samples = avcTrack.samples;
var nbSamples = samples.length;
// only push AVC sample if starting with a keyframe is not mandatory OR
// if keyframe already found in this fragment OR
// keyframe found in last fragment (track.sps) AND
// samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous
if (!this.config.forceKeyFrameOnDiscontinuity || avcSample.key === true || avcTrack.sps && (nbSamples || this.contiguous)) {
avcSample.id = nbSamples;
samples.push(avcSample);
} else {
// dropped samples, track it
avcTrack.dropped++;
}
}
if (avcSample.debug.length) {
logger["b" /* logger */].log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);
}
};
TSDemuxer.prototype._parseAVCPES = function _parseAVCPES(pes, last) {
var _this = this;
//logger.log('parse new PES');
var track = this._avcTrack,
units = this._parseAVCNALu(pes.data),
debug = false,
expGolombDecoder,
avcSample = this.avcSample,
push,
spsfound = false,
i,
pushAccesUnit = this.pushAccesUnit.bind(this),
createAVCSample = function createAVCSample(key, pts, dts, debug) {
return { key: key, pts: pts, dts: dts, units: [], debug: debug };
};
//free pes.data to save up some memory
pes.data = null;
// if new NAL units found and last sample still there, let's push ...
// this helps parsing streams with missing AUD (only do this if AUD never found)
if (avcSample && units.length && !track.audFound) {
pushAccesUnit(avcSample, track);
avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, '');
}
units.forEach(function (unit) {
switch (unit.type) {
//NDR
case 1:
push = true;
if (!avcSample) {
avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
}
if (debug) {
avcSample.debug += 'NDR ';
}
avcSample.frame = true;
var data = unit.data;
// only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
if (spsfound && data.length > 4) {
// retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
var sliceType = new exp_golomb(data).readSliceType();
// 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
// SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
// An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
// I slice: A slice that is not an SI slice that is decoded using intra prediction only.
//if (sliceType === 2 || sliceType === 7) {
if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
avcSample.key = true;
}
}
break;
//IDR
case 5:
push = true;
// handle PES not starting with AUD
if (!avcSample) {
avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
}
if (debug) {
avcSample.debug += 'IDR ';
}
avcSample.key = true;
avcSample.frame = true;
break;
//SEI
case 6:
push = true;
if (debug && avcSample) {
avcSample.debug += 'SEI ';
}
expGolombDecoder = new exp_golomb(_this.discardEPB(unit.data));
// skip frameType
expGolombDecoder.readUByte();
var payloadType = 0;
var payloadSize = 0;
var endOfCaptions = false;
var b = 0;
while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {
payloadType = 0;
do {
b = expGolombDecoder.readUByte();
payloadType += b;
} while (b === 0xFF);
// Parse payload size.
payloadSize = 0;
do {
b = expGolombDecoder.readUByte();
payloadSize += b;
} while (b === 0xFF);
// TODO: there can be more than one payload in an SEI packet...
// TODO: need to read type and size in a while loop to get them all
if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {
endOfCaptions = true;
var countryCode = expGolombDecoder.readUByte();
if (countryCode === 181) {
var providerCode = expGolombDecoder.readUShort();
if (providerCode === 49) {
var userStructure = expGolombDecoder.readUInt();
if (userStructure === 0x47413934) {
var userDataType = expGolombDecoder.readUByte();
// Raw CEA-608 bytes wrapped in CEA-708 packet
if (userDataType === 3) {
var firstByte = expGolombDecoder.readUByte();
var secondByte = expGolombDecoder.readUByte();
var totalCCs = 31 & firstByte;
var byteArray = [firstByte, secondByte];
for (i = 0; i < totalCCs; i++) {
// 3 bytes per CC
byteArray.push(expGolombDecoder.readUByte());
byteArray.push(expGolombDecoder.readUByte());
byteArray.push(expGolombDecoder.readUByte());
}
_this._insertSampleInOrder(_this._txtTrack.samples, { type: 3, pts: pes.pts, bytes: byteArray });
}
}
}
}
} else if (payloadSize < expGolombDecoder.bytesAvailable) {
for (i = 0; i < payloadSize; i++) {
expGolombDecoder.readUByte();
}
}
}
break;
//SPS
case 7:
push = true;
spsfound = true;
if (debug && avcSample) {
avcSample.debug += 'SPS ';
}
if (!track.sps) {
expGolombDecoder = new exp_golomb(unit.data);
var config = expGolombDecoder.readSPS();
track.width = config.width;
track.height = config.height;
track.pixelRatio = config.pixelRatio;
track.sps = [unit.data];
track.duration = _this._duration;
var codecarray = unit.data.subarray(1, 4);
var codecstring = 'avc1.';
for (i = 0; i < 3; i++) {
var h = codecarray[i].toString(16);
if (h.length < 2) {
h = '0' + h;
}
codecstring += h;
}
track.codec = codecstring;
}
break;
//PPS
case 8:
push = true;
if (debug && avcSample) {
avcSample.debug += 'PPS ';
}
if (!track.pps) {
track.pps = [unit.data];
}
break;
// AUD
case 9:
push = false;
track.audFound = true;
if (avcSample) {
pushAccesUnit(avcSample, track);
}
avcSample = _this.avcSample = createAVCSample(false, pes.pts, pes.dts, debug ? 'AUD ' : '');
break;
// Filler Data
case 12:
push = false;
break;
default:
push = false;
if (avcSample) {
avcSample.debug += 'unknown NAL ' + unit.type + ' ';
}
break;
}
if (avcSample && push) {
var _units = avcSample.units;
_units.push(unit);
}
});
// if last PES packet, push samples
if (last && avcSample) {
pushAccesUnit(avcSample, track);
this.avcSample = null;
}
};
TSDemuxer.prototype._insertSampleInOrder = function _insertSampleInOrder(arr, data) {
var len = arr.length;
if (len > 0) {
if (data.pts >= arr[len - 1].pts) {
arr.push(data);
} else {
for (var pos = len - 1; pos >= 0; pos--) {
if (data.pts < arr[pos].pts) {
arr.splice(pos, 0, data);
break;
}
}
}
} else {
arr.push(data);
}
};
TSDemuxer.prototype._getLastNalUnit = function _getLastNalUnit() {
var avcSample = this.avcSample,
lastUnit = void 0;
// try to fallback to previous sample if current one is empty
if (!avcSample || avcSample.units.length === 0) {
var track = this._avcTrack,
samples = track.samples;
avcSample = samples[samples.length - 1];
}
if (avcSample) {
var units = avcSample.units;
lastUnit = units[units.length - 1];
}
return lastUnit;
};
TSDemuxer.prototype._parseAVCNALu = function _parseAVCNALu(array) {
var i = 0,
len = array.byteLength,
value,
overflow,
track = this._avcTrack,
state = track.naluState || 0,
lastState = state;
var units = [],
unit,
unitType,
lastUnitStart = -1,
lastUnitType;
//logger.log('PES:' + Hex.hexDump(array));
if (state === -1) {
// special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
lastUnitStart = 0;
// NALu type is value read from offset 0
lastUnitType = array[0] & 0x1f;
state = 0;
i = 1;
}
while (i < len) {
value = array[i++];
// optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
if (!state) {
state = value ? 0 : 1;
continue;
}
if (state === 1) {
state = value ? 0 : 2;
continue;
}
// here we have state either equal to 2 or 3
if (!value) {
state = 3;
} else if (value === 1) {
if (lastUnitStart >= 0) {
unit = { data: array.subarray(lastUnitStart, i - state - 1), type: lastUnitType };
//logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
units.push(unit);
} else {
// lastUnitStart is undefined => this is the first start code found in this PES packet
// first check if start code delimiter is overlapping between 2 PES packets,
// ie it started in last packet (lastState not zero)
// and ended at the beginning of this PES packet (i <= 4 - lastState)
var lastUnit = this._getLastNalUnit();
if (lastUnit) {
if (lastState && i <= 4 - lastState) {
// start delimiter overlapping between PES packets
// strip start delimiter bytes from the end of last NAL unit
// check if lastUnit had a state different from zero
if (lastUnit.state) {
// strip last bytes
lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
}
}
// If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
overflow = i - state - 1;
if (overflow > 0) {
//logger.log('first NALU found with overflow:' + overflow);
var tmp = new Uint8Array(lastUnit.data.byteLength + overflow);
tmp.set(lastUnit.data, 0);
tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);
lastUnit.data = tmp;
}
}
}
// check if we can read unit type
if (i < len) {
unitType = array[i] & 0x1f;
//logger.log('find NALU @ offset:' + i + ',type:' + unitType);
lastUnitStart = i;
lastUnitType = unitType;
state = 0;
} else {
// not enough byte to read unit type. let's read it on next PES parsing
state = -1;
}
} else {
state = 0;
}
}
if (lastUnitStart >= 0 && state >= 0) {
unit = { data: array.subarray(lastUnitStart, len), type: lastUnitType, state: state };
units.push(unit);
//logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
}
// no NALu found
if (units.length === 0) {
// append pes.data to previous NAL unit
var _lastUnit = this._getLastNalUnit();
if (_lastUnit) {
var _tmp = new Uint8Array(_lastUnit.data.byteLength + array.byteLength);
_tmp.set(_lastUnit.data, 0);
_tmp.set(array, _lastUnit.data.byteLength);
_lastUnit.data = _tmp;
}
}
track.naluState = state;
return units;
};
/**
* remove Emulation Prevention bytes from a RBSP
*/
TSDemuxer.prototype.discardEPB = function discardEPB(data) {
var length = data.byteLength,
EPBPositions = [],
i = 1,
newLength,
newData;
// Find all `Emulation Prevention Bytes`
while (i < length - 2) {
if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
EPBPositions.push(i + 2);
i += 2;
} else {
i++;
}
}
// If no Emulation Prevention Bytes were found just return the original
// array
if (EPBPositions.length === 0) {
return data;
}
// Create a new array to hold the NAL unit data
newLength = length - EPBPositions.length;
newData = new Uint8Array(newLength);
var sourceIndex = 0;
for (i = 0; i < newLength; sourceIndex++, i++) {
if (sourceIndex === EPBPositions[0]) {
// Skip this byte
sourceIndex++;
// Remove this position index
EPBPositions.shift();
}
newData[i] = data[sourceIndex];
}
return newData;
};
TSDemuxer.prototype._parseAACPES = function _parseAACPES(pes) {
var track = this._audioTrack,
data = pes.data,
pts = pes.pts,
startOffset = 0,
aacOverFlow = this.aacOverFlow,
aacLastPTS = this.aacLastPTS,
frameDuration,
frameIndex,
offset,
stamp,
len;
if (aacOverFlow) {
var tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength);
tmp.set(aacOverFlow, 0);
tmp.set(data, aacOverFlow.byteLength);
//logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`);
data = tmp;
}
// look for ADTS header (0xFFFx)
for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
if (isHeader(data, offset)) {
break;
}
}
// if ADTS header does not start straight from the beginning of the PES payload, raise an error
if (offset) {
var reason, fatal;
if (offset < len - 1) {
reason = 'AAC PES did not start with ADTS header,offset:' + offset;
fatal = false;
} else {
reason = 'no ADTS header found in AAC PES';
fatal = true;
}
logger["b" /* logger */].warn('parsing error:' + reason);
this.observer.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: fatal, reason: reason });
if (fatal) {
return;
}
}
initTrackConfig(track, this.observer, data, offset, this.audioCodec);
frameIndex = 0;
frameDuration = getFrameDuration(track.samplerate);
// if last AAC frame is overflowing, we should ensure timestamps are contiguous:
// first sample PTS should be equal to last sample PTS + frameDuration
if (aacOverFlow && aacLastPTS) {
var newPTS = aacLastPTS + frameDuration;
if (Math.abs(newPTS - pts) > 1) {
logger["b" /* logger */].log('AAC: align PTS for overlapping frames by ' + Math.round((newPTS - pts) / 90));
pts = newPTS;
}
}
//scan for aac samples
while (offset < len) {
if (isHeader(data, offset) && offset + 5 < len) {
var frame = appendFrame(track, data, offset, pts, frameIndex);
if (frame) {
//logger.log(`${Math.round(frame.sample.pts)} : AAC`);
offset += frame.length;
stamp = frame.sample.pts;
frameIndex++;
} else {
//logger.log('Unable to parse AAC frame');
break;
}
} else {
//nothing found, keep looking
offset++;
}
}
if (offset < len) {
aacOverFlow = data.subarray(offset, len);
//logger.log(`AAC: overflow detected:${len-offset}`);
} else {
aacOverFlow = null;
}
this.aacOverFlow = aacOverFlow;
this.aacLastPTS = stamp;
};
TSDemuxer.prototype._parseMPEGPES = function _parseMPEGPES(pes) {
var data = pes.data;
var length = data.length;
var frameIndex = 0;
var offset = 0;
var pts = pes.pts;
while (offset < length) {
if (mpegaudio.isHeader(data, offset)) {
var frame = mpegaudio.appendFrame(this._audioTrack, data, offset, pts, frameIndex);
if (frame) {
offset += frame.length;
frameIndex++;
} else {
//logger.log('Unable to parse Mpeg audio frame');
break;
}
} else {
//nothing found, keep looking
offset++;
}
}
};
TSDemuxer.prototype._parseID3PES = function _parseID3PES(pes) {
this._id3Track.samples.push(pes);
};
return TSDemuxer;
}();
/* harmony default export */ var tsdemuxer = (tsdemuxer_TSDemuxer);
// CONCATENATED MODULE: ./src/demux/mp3demuxer.js
function mp3demuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* MP3 demuxer
*/
var mp3demuxer_MP3Demuxer = function () {
function MP3Demuxer(observer, remuxer, config) {
mp3demuxer__classCallCheck(this, MP3Demuxer);
this.observer = observer;
this.config = config;
this.remuxer = remuxer;
}
MP3Demuxer.prototype.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
this._audioTrack = { container: 'audio/mpeg', type: 'audio', id: -1, sequenceNumber: 0, isAAC: false, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };
};
MP3Demuxer.prototype.resetTimeStamp = function resetTimeStamp() {};
MP3Demuxer.probe = function probe(data) {
// check if data contains ID3 timestamp and MPEG sync word
var offset, length;
var id3Data = id3["a" /* default */].getID3Data(data, 0);
if (id3Data && id3["a" /* default */].getTimeStamp(id3Data) !== undefined) {
// Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
// Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
// More info http://www.mp3-tech.org/programmer/frame_header.html
for (offset = id3Data.length, length = Math.min(data.length - 1, offset + 100); offset < length; offset++) {
if (mpegaudio.probe(data, offset)) {
logger["b" /* logger */].log('MPEG Audio sync word found !');
return true;
}
}
}
return false;
};
// feed incoming data to the front of the parsing pipeline
MP3Demuxer.prototype.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {
var id3Data = id3["a" /* default */].getID3Data(data, 0);
var pts = 90 * id3["a" /* default */].getTimeStamp(id3Data);
var offset = id3Data.length;
var length = data.length;
var frameIndex = 0,
stamp = 0;
var track = this._audioTrack;
var id3Samples = [{ pts: pts, dts: pts, data: id3Data }];
while (offset < length) {
if (mpegaudio.isHeader(data, offset)) {
var frame = mpegaudio.appendFrame(track, data, offset, pts, frameIndex);
if (frame) {
offset += frame.length;
stamp = frame.sample.pts;
frameIndex++;
} else {
//logger.log('Unable to parse Mpeg audio frame');
break;
}
} else if (id3["a" /* default */].isHeader(data, offset)) {
id3Data = id3["a" /* default */].getID3Data(data, offset);
id3Samples.push({ pts: stamp, dts: stamp, data: id3Data });
offset += id3Data.length;
} else {
//nothing found, keep looking
offset++;
}
}
this.remuxer.remux(track, { samples: [] }, { samples: id3Samples, inputTimeScale: 90000 }, { samples: [] }, timeOffset, contiguous, accurateTimeOffset);
};
MP3Demuxer.prototype.destroy = function destroy() {};
return MP3Demuxer;
}();
/* harmony default export */ var mp3demuxer = (mp3demuxer_MP3Demuxer);
// CONCATENATED MODULE: ./src/helper/aac.js
function aac__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* AAC helper
*/
var AAC = function () {
function AAC() {
aac__classCallCheck(this, AAC);
}
AAC.getSilentFrame = function getSilentFrame(codec, channelCount) {
switch (codec) {
case 'mp4a.40.2':
if (channelCount === 1) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
} else if (channelCount === 2) {
return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
} else if (channelCount === 3) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
} else if (channelCount === 4) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
} else if (channelCount === 5) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
} else if (channelCount === 6) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]);
}
break;
// handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
default:
if (channelCount === 1) {
// ffmpeg -y -f lavfi -i "aevalsrc=0:d=0.05" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
} else if (channelCount === 2) {
// ffmpeg -y -f lavfi -i "aevalsrc=0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
} else if (channelCount === 3) {
// ffmpeg -y -f lavfi -i "aevalsrc=0|0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
}
break;
}
return null;
};
return AAC;
}();
/* harmony default export */ var aac = (AAC);
// CONCATENATED MODULE: ./src/remux/mp4-generator.js
function mp4_generator__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Generate MP4 Box
*/
//import Hex from '../utils/hex';
var mp4_generator_UINT32_MAX = Math.pow(2, 32) - 1;
var MP4 = function () {
function MP4() {
mp4_generator__classCallCheck(this, MP4);
}
MP4.init = function init() {
MP4.types = {
avc1: [], // codingname
avcC: [],
btrt: [],
dinf: [],
dref: [],
esds: [],
ftyp: [],
hdlr: [],
mdat: [],
mdhd: [],
mdia: [],
mfhd: [],
minf: [],
moof: [],
moov: [],
mp4a: [],
'.mp3': [],
mvex: [],
mvhd: [],
pasp: [],
sdtp: [],
stbl: [],
stco: [],
stsc: [],
stsd: [],
stsz: [],
stts: [],
tfdt: [],
tfhd: [],
traf: [],
trak: [],
trun: [],
trex: [],
tkhd: [],
vmhd: [],
smhd: []
};
var i;
for (i in MP4.types) {
if (MP4.types.hasOwnProperty(i)) {
MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
}
}
var videoHdlr = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // pre_defined
0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
]);
var audioHdlr = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // pre_defined
0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
]);
MP4.HDLR_TYPES = {
'video': videoHdlr,
'audio': audioHdlr
};
var dref = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x01, // entry_count
0x00, 0x00, 0x00, 0x0c, // entry_size
0x75, 0x72, 0x6c, 0x20, // 'url' type
0x00, // version 0
0x00, 0x00, 0x01 // entry_flags
]);
var stco = new Uint8Array([0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00 // entry_count
]);
MP4.STTS = MP4.STSC = MP4.STCO = stco;
MP4.STSZ = new Uint8Array([0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // sample_size
0x00, 0x00, 0x00, 0x00]);
MP4.VMHD = new Uint8Array([0x00, // version
0x00, 0x00, 0x01, // flags
0x00, 0x00, // graphicsmode
0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
]);
MP4.SMHD = new Uint8Array([0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, // balance
0x00, 0x00 // reserved
]);
MP4.STSD = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x01]); // entry_count
var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
var minorVersion = new Uint8Array([0, 0, 0, 1]);
MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
};
MP4.box = function box(type) {
var payload = Array.prototype.slice.call(arguments, 1),
size = 8,
i = payload.length,
len = i,
result;
// calculate the total size we need to allocate
while (i--) {
size += payload[i].byteLength;
}
result = new Uint8Array(size);
result[0] = size >> 24 & 0xff;
result[1] = size >> 16 & 0xff;
result[2] = size >> 8 & 0xff;
result[3] = size & 0xff;
result.set(type, 4);
// copy the payload into the result
for (i = 0, size = 8; i < len; i++) {
// copy payload[i] array @ offset size
result.set(payload[i], size);
size += payload[i].byteLength;
}
return result;
};
MP4.hdlr = function hdlr(type) {
return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
};
MP4.mdat = function mdat(data) {
return MP4.box(MP4.types.mdat, data);
};
MP4.mdhd = function mdhd(timescale, duration) {
duration *= timescale;
var upperWordDuration = Math.floor(duration / (mp4_generator_UINT32_MAX + 1));
var lowerWordDuration = Math.floor(duration % (mp4_generator_UINT32_MAX + 1));
return MP4.box(MP4.types.mdhd, new Uint8Array([0x01, // version 1
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
upperWordDuration >> 24, upperWordDuration >> 16 & 0xFF, upperWordDuration >> 8 & 0xFF, upperWordDuration & 0xFF, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xFF, lowerWordDuration >> 8 & 0xFF, lowerWordDuration & 0xFF, 0x55, 0xc4, // 'und' language (undetermined)
0x00, 0x00]));
};
MP4.mdia = function mdia(track) {
return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
};
MP4.mfhd = function mfhd(sequenceNumber) {
return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
sequenceNumber >> 24, sequenceNumber >> 16 & 0xFF, sequenceNumber >> 8 & 0xFF, sequenceNumber & 0xFF]) // sequence_number
);
};
MP4.minf = function minf(track) {
if (track.type === 'audio') {
return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
} else {
return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
}
};
MP4.moof = function moof(sn, baseMediaDecodeTime, track) {
return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
};
/**
* @param tracks... (optional) {array} the tracks associated with this movie
*/
MP4.moov = function moov(tracks) {
var i = tracks.length,
boxes = [];
while (i--) {
boxes[i] = MP4.trak(tracks[i]);
}
return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));
};
MP4.mvex = function mvex(tracks) {
var i = tracks.length,
boxes = [];
while (i--) {
boxes[i] = MP4.trex(tracks[i]);
}
return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
};
MP4.mvhd = function mvhd(timescale, duration) {
duration *= timescale;
var upperWordDuration = Math.floor(duration / (mp4_generator_UINT32_MAX + 1));
var lowerWordDuration = Math.floor(duration % (mp4_generator_UINT32_MAX + 1));
var bytes = new Uint8Array([0x01, // version 1
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
upperWordDuration >> 24, upperWordDuration >> 16 & 0xFF, upperWordDuration >> 8 & 0xFF, upperWordDuration & 0xFF, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xFF, lowerWordDuration >> 8 & 0xFF, lowerWordDuration & 0xFF, 0x00, 0x01, 0x00, 0x00, // 1.0 rate
0x01, 0x00, // 1.0 volume
0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
0xff, 0xff, 0xff, 0xff // next_track_ID
]);
return MP4.box(MP4.types.mvhd, bytes);
};
MP4.sdtp = function sdtp(track) {
var samples = track.samples || [],
bytes = new Uint8Array(4 + samples.length),
flags,
i;
// leave the full box header (4 bytes) all zero
// write the sample table
for (i = 0; i < samples.length; i++) {
flags = samples[i].flags;
bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
}
return MP4.box(MP4.types.sdtp, bytes);
};
MP4.stbl = function stbl(track) {
return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO));
};
MP4.avc1 = function avc1(track) {
var sps = [],
pps = [],
i,
data,
len;
// assemble the SPSs
for (i = 0; i < track.sps.length; i++) {
data = track.sps[i];
len = data.byteLength;
sps.push(len >>> 8 & 0xFF);
sps.push(len & 0xFF);
sps = sps.concat(Array.prototype.slice.call(data)); // SPS
}
// assemble the PPSs
for (i = 0; i < track.pps.length; i++) {
data = track.pps[i];
len = data.byteLength;
pps.push(len >>> 8 & 0xFF);
pps.push(len & 0xFF);
pps = pps.concat(Array.prototype.slice.call(data));
}
var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01, // version
sps[3], // profile
sps[4], // profile compat
sps[5], // level
0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes
0xE0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
].concat(sps).concat([track.pps.length // numOfPictureParameterSets
]).concat(pps))),
// "PPS"
width = track.width,
height = track.height,
hSpacing = track.pixelRatio[0],
vSpacing = track.pixelRatio[1];
//console.log('avcc:' + Hex.hexDump(avcc));
return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, // reserved
0x00, 0x01, // data_reference_index
0x00, 0x00, // pre_defined
0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
width >> 8 & 0xFF, width & 0xff, // width
height >> 8 & 0xFF, height & 0xff, // height
0x00, 0x48, 0x00, 0x00, // horizresolution
0x00, 0x48, 0x00, 0x00, // vertresolution
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x01, // frame_count
0x12, 0x64, 0x61, 0x69, 0x6C, //dailymotion/hls.js
0x79, 0x6D, 0x6F, 0x74, 0x69, 0x6F, 0x6E, 0x2F, 0x68, 0x6C, 0x73, 0x2E, 0x6A, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname
0x00, 0x18, // depth = 24
0x11, 0x11]), // pre_defined = -1
avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
0x00, 0x2d, 0xc6, 0xc0])), // avgBitrate
MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24, // hSpacing
hSpacing >> 16 & 0xFF, hSpacing >> 8 & 0xFF, hSpacing & 0xFF, vSpacing >> 24, // vSpacing
vSpacing >> 16 & 0xFF, vSpacing >> 8 & 0xFF, vSpacing & 0xFF])));
};
MP4.esds = function esds(track) {
var configlen = track.config.length;
return new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x03, // descriptor_type
0x17 + configlen, // length
0x00, 0x01, //es_id
0x00, // stream_priority
0x04, // descriptor_type
0x0f + configlen, // length
0x40, //codec : mpeg4_audio
0x15, // stream_type
0x00, 0x00, 0x00, // buffer_size
0x00, 0x00, 0x00, 0x00, // maxBitrate
0x00, 0x00, 0x00, 0x00, // avgBitrate
0x05 // descriptor_type
].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
};
MP4.mp4a = function mp4a(track) {
var samplerate = track.samplerate;
return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, // reserved
0x00, 0x01, // data_reference_index
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
0x00, track.channelCount, // channelcount
0x00, 0x10, // sampleSize:16bits
0x00, 0x00, 0x00, 0x00, // reserved2
samplerate >> 8 & 0xFF, samplerate & 0xff, //
0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track)));
};
MP4.mp3 = function mp3(track) {
var samplerate = track.samplerate;
return MP4.box(MP4.types['.mp3'], new Uint8Array([0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, // reserved
0x00, 0x01, // data_reference_index
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
0x00, track.channelCount, // channelcount
0x00, 0x10, // sampleSize:16bits
0x00, 0x00, 0x00, 0x00, // reserved2
samplerate >> 8 & 0xFF, samplerate & 0xff, //
0x00, 0x00]));
};
MP4.stsd = function stsd(track) {
if (track.type === 'audio') {
if (!track.isAAC && track.codec === 'mp3') {
return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
}
return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
} else {
return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
}
};
MP4.tkhd = function tkhd(track) {
var id = track.id,
duration = track.duration * track.timescale,
width = track.width,
height = track.height,
upperWordDuration = Math.floor(duration / (mp4_generator_UINT32_MAX + 1)),
lowerWordDuration = Math.floor(duration % (mp4_generator_UINT32_MAX + 1));
return MP4.box(MP4.types.tkhd, new Uint8Array([0x01, // version 1
0x00, 0x00, 0x07, // flags
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
id >> 24 & 0xFF, id >> 16 & 0xFF, id >> 8 & 0xFF, id & 0xFF, // track_ID
0x00, 0x00, 0x00, 0x00, // reserved
upperWordDuration >> 24, upperWordDuration >> 16 & 0xFF, upperWordDuration >> 8 & 0xFF, upperWordDuration & 0xFF, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xFF, lowerWordDuration >> 8 & 0xFF, lowerWordDuration & 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, // layer
0x00, 0x00, // alternate_group
0x00, 0x00, // non-audio track volume
0x00, 0x00, // reserved
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
width >> 8 & 0xFF, width & 0xFF, 0x00, 0x00, // width
height >> 8 & 0xFF, height & 0xFF, 0x00, 0x00 // height
]));
};
MP4.traf = function traf(track, baseMediaDecodeTime) {
var sampleDependencyTable = MP4.sdtp(track),
id = track.id,
upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (mp4_generator_UINT32_MAX + 1)),
lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (mp4_generator_UINT32_MAX + 1));
return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF]) // track_ID
), MP4.box(MP4.types.tfdt, new Uint8Array([0x01, // version 1
0x00, 0x00, 0x00, // flags
upperWordBaseMediaDecodeTime >> 24, upperWordBaseMediaDecodeTime >> 16 & 0XFF, upperWordBaseMediaDecodeTime >> 8 & 0XFF, upperWordBaseMediaDecodeTime & 0xFF, lowerWordBaseMediaDecodeTime >> 24, lowerWordBaseMediaDecodeTime >> 16 & 0XFF, lowerWordBaseMediaDecodeTime >> 8 & 0XFF, lowerWordBaseMediaDecodeTime & 0xFF])), MP4.trun(track, sampleDependencyTable.length + 16 + // tfhd
20 + // tfdt
8 + // traf header
16 + // mfhd
8 + // moof header
8), // mdat header
sampleDependencyTable);
};
/**
* Generate a track box.
* @param track {object} a track definition
* @return {Uint8Array} the track box
*/
MP4.trak = function trak(track) {
track.duration = track.duration || 0xffffffff;
return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
};
MP4.trex = function trex(track) {
var id = track.id;
return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF, // track_ID
0x00, 0x00, 0x00, 0x01, // default_sample_description_index
0x00, 0x00, 0x00, 0x00, // default_sample_duration
0x00, 0x00, 0x00, 0x00, // default_sample_size
0x00, 0x01, 0x00, 0x01 // default_sample_flags
]));
};
MP4.trun = function trun(track, offset) {
var samples = track.samples || [],
len = samples.length,
arraylen = 12 + 16 * len,
array = new Uint8Array(arraylen),
i,
sample,
duration,
size,
flags,
cts;
offset += 8 + arraylen;
array.set([0x00, // version 0
0x00, 0x0f, 0x01, // flags
len >>> 24 & 0xFF, len >>> 16 & 0xFF, len >>> 8 & 0xFF, len & 0xFF, // sample_count
offset >>> 24 & 0xFF, offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, offset & 0xFF // data_offset
], 0);
for (i = 0; i < len; i++) {
sample = samples[i];
duration = sample.duration;
size = sample.size;
flags = sample.flags;
cts = sample.cts;
array.set([duration >>> 24 & 0xFF, duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, // sample_duration
size >>> 24 & 0xFF, size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, // sample_size
flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xF0 << 8, flags.degradPrio & 0x0F, // sample_flags
cts >>> 24 & 0xFF, cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF // sample_composition_time_offset
], 12 + 16 * i);
}
return MP4.box(MP4.types.trun, array);
};
MP4.initSegment = function initSegment(tracks) {
if (!MP4.types) {
MP4.init();
}
var movie = MP4.moov(tracks),
result;
result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);
result.set(MP4.FTYP);
result.set(movie, MP4.FTYP.byteLength);
return result;
};
return MP4;
}();
/* harmony default export */ var mp4_generator = (MP4);
// CONCATENATED MODULE: ./src/remux/mp4-remuxer.js
function mp4_remuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* fMP4 remuxer
*/
// 10 seconds
var MAX_SILENT_FRAME_DURATION = 10 * 1000;
var mp4_remuxer_MP4Remuxer = function () {
function MP4Remuxer(observer, config, typeSupported, vendor) {
mp4_remuxer__classCallCheck(this, MP4Remuxer);
this.observer = observer;
this.config = config;
this.typeSupported = typeSupported;
var userAgent = navigator.userAgent;
this.isSafari = vendor && vendor.indexOf('Apple') > -1 && userAgent && !userAgent.match('CriOS');
this.ISGenerated = false;
}
MP4Remuxer.prototype.destroy = function destroy() {};
MP4Remuxer.prototype.resetTimeStamp = function resetTimeStamp(defaultTimeStamp) {
this._initPTS = this._initDTS = defaultTimeStamp;
};
MP4Remuxer.prototype.resetInitSegment = function resetInitSegment() {
this.ISGenerated = false;
};
MP4Remuxer.prototype.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
// generate Init Segment if needed
if (!this.ISGenerated) {
this.generateIS(audioTrack, videoTrack, timeOffset);
}
if (this.ISGenerated) {
var nbAudioSamples = audioTrack.samples.length;
var nbVideoSamples = videoTrack.samples.length;
var audioTimeOffset = timeOffset;
var videoTimeOffset = timeOffset;
if (nbAudioSamples && nbVideoSamples) {
// timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
// if first audio DTS is not aligned with first video DTS then we need to take that into account
// when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
// drift between audio and video streams
var audiovideoDeltaDts = (audioTrack.samples[0].dts - videoTrack.samples[0].dts) / videoTrack.inputTimeScale;
audioTimeOffset += Math.max(0, audiovideoDeltaDts);
videoTimeOffset += Math.max(0, -audiovideoDeltaDts);
}
// Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is
// calculated in remuxAudio.
//logger.log('nb AAC samples:' + audioTrack.samples.length);
if (nbAudioSamples) {
// if initSegment was generated without video samples, regenerate it again
if (!audioTrack.timescale) {
logger["b" /* logger */].warn('regenerate InitSegment as audio detected');
this.generateIS(audioTrack, videoTrack, timeOffset);
}
var audioData = this.remuxAudio(audioTrack, audioTimeOffset, contiguous, accurateTimeOffset);
//logger.log('nb AVC samples:' + videoTrack.samples.length);
if (nbVideoSamples) {
var audioTrackLength = void 0;
if (audioData) {
audioTrackLength = audioData.endPTS - audioData.startPTS;
}
// if initSegment was generated without video samples, regenerate it again
if (!videoTrack.timescale) {
logger["b" /* logger */].warn('regenerate InitSegment as video detected');
this.generateIS(audioTrack, videoTrack, timeOffset);
}
this.remuxVideo(videoTrack, videoTimeOffset, contiguous, audioTrackLength, accurateTimeOffset);
}
} else {
var videoData = void 0;
//logger.log('nb AVC samples:' + videoTrack.samples.length);
if (nbVideoSamples) {
videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, accurateTimeOffset);
}
if (videoData && audioTrack.codec) {
this.remuxEmptyAudio(audioTrack, audioTimeOffset, contiguous, videoData);
}
}
}
//logger.log('nb ID3 samples:' + audioTrack.samples.length);
if (id3Track.samples.length) {
this.remuxID3(id3Track, timeOffset);
}
//logger.log('nb ID3 samples:' + audioTrack.samples.length);
if (textTrack.samples.length) {
this.remuxText(textTrack, timeOffset);
}
//notify end of parsing
this.observer.trigger(events["a" /* default */].FRAG_PARSED);
};
MP4Remuxer.prototype.generateIS = function generateIS(audioTrack, videoTrack, timeOffset) {
var observer = this.observer,
audioSamples = audioTrack.samples,
videoSamples = videoTrack.samples,
typeSupported = this.typeSupported,
container = 'audio/mp4',
tracks = {},
data = { tracks: tracks },
computePTSDTS = this._initPTS === undefined,
initPTS,
initDTS;
if (computePTSDTS) {
initPTS = initDTS = Infinity;
}
if (audioTrack.config && audioSamples.length) {
// let's use audio sampling rate as MP4 time scale.
// rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
// using audio sampling rate here helps having an integer MP4 frame duration
// this avoids potential rounding issue and AV sync issue
audioTrack.timescale = audioTrack.samplerate;
logger["b" /* logger */].log('audio sampling rate : ' + audioTrack.samplerate);
if (!audioTrack.isAAC) {
if (typeSupported.mpeg) {
// Chrome and Safari
container = 'audio/mpeg';
audioTrack.codec = '';
} else if (typeSupported.mp3) {
// Firefox
audioTrack.codec = 'mp3';
}
}
tracks.audio = {
container: container,
codec: audioTrack.codec,
initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array() : mp4_generator.initSegment([audioTrack]),
metadata: {
channelCount: audioTrack.channelCount
}
};
if (computePTSDTS) {
// remember first PTS of this demuxing context. for audio, PTS = DTS
initPTS = initDTS = audioSamples[0].pts - audioTrack.inputTimeScale * timeOffset;
}
}
if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
// let's use input time scale as MP4 video timescale
// we use input time scale straight away to avoid rounding issues on frame duration / cts computation
var inputTimeScale = videoTrack.inputTimeScale;
videoTrack.timescale = inputTimeScale;
tracks.video = {
container: 'video/mp4',
codec: videoTrack.codec,
initSegment: mp4_generator.initSegment([videoTrack]),
metadata: {
width: videoTrack.width,
height: videoTrack.height
}
};
if (computePTSDTS) {
initPTS = Math.min(initPTS, videoSamples[0].pts - inputTimeScale * timeOffset);
initDTS = Math.min(initDTS, videoSamples[0].dts - inputTimeScale * timeOffset);
this.observer.trigger(events["a" /* default */].INIT_PTS_FOUND, { initPTS: initPTS });
}
}
if (Object.keys(tracks).length) {
observer.trigger(events["a" /* default */].FRAG_PARSING_INIT_SEGMENT, data);
this.ISGenerated = true;
if (computePTSDTS) {
this._initPTS = initPTS;
this._initDTS = initDTS;
}
} else {
observer.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found' });
}
};
MP4Remuxer.prototype.remuxVideo = function remuxVideo(track, timeOffset, contiguous, audioTrackLength, accurateTimeOffset) {
var offset = 8,
timeScale = track.timescale,
mp4SampleDuration,
mdat,
moof,
firstPTS,
firstDTS,
nextDTS,
lastPTS,
lastDTS,
inputSamples = track.samples,
outputSamples = [],
nbSamples = inputSamples.length,
ptsNormalize = this._PTSNormalize,
initDTS = this._initDTS;
// for (let i = 0; i < track.samples.length; i++) {
// let avcSample = track.samples[i];
// let units = avcSample.units;
// let unitsString = '';
// for (let j = 0; j < units.length ; j++) {
// unitsString += units[j].type + ',';
// if (units[j].data.length < 500) {
// unitsString += Hex.hexDump(units[j].data);
// }
// }
// logger.log(avcSample.pts + '/' + avcSample.dts + ',' + unitsString + avcSample.units.length);
// }
// if parsed fragment is contiguous with last one, let's use last DTS value as reference
var nextAvcDts = this.nextAvcDts;
var isSafari = this.isSafari;
// Safari does not like overlapping DTS on consecutive fragments. let's use nextAvcDts to overcome this if fragments are consecutive
if (isSafari) {
// also consider consecutive fragments as being contiguous (even if a level switch occurs),
// for sake of clarity:
// consecutive fragments are frags with
// - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
// - less than 200 ms PTS gaps (timeScale/5)
contiguous |= inputSamples.length && nextAvcDts && (accurateTimeOffset && Math.abs(timeOffset - nextAvcDts / timeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAvcDts - initDTS) < timeScale / 5);
}
if (!contiguous) {
// if not contiguous, let's use target timeOffset
nextAvcDts = timeOffset * timeScale;
}
// PTS is coded on 33bits, and can loop from -2^32 to 2^32
// ptsNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
inputSamples.forEach(function (sample) {
sample.pts = ptsNormalize(sample.pts - initDTS, nextAvcDts);
sample.dts = ptsNormalize(sample.dts - initDTS, nextAvcDts);
});
// sort video samples by DTS then PTS then demux id order
inputSamples.sort(function (a, b) {
var deltadts = a.dts - b.dts;
var deltapts = a.pts - b.pts;
return deltadts ? deltadts : deltapts ? deltapts : a.id - b.id;
});
// handle broken streams with PTS < DTS, tolerance up 200ms (18000 in 90kHz timescale)
var PTSDTSshift = inputSamples.reduce(function (prev, curr) {
return Math.max(Math.min(prev, curr.pts - curr.dts), -18000);
}, 0);
if (PTSDTSshift < 0) {
logger["b" /* logger */].warn('PTS < DTS detected in video samples, shifting DTS by ' + Math.round(PTSDTSshift / 90) + ' ms to overcome this issue');
for (var i = 0; i < inputSamples.length; i++) {
inputSamples[i].dts += PTSDTSshift;
}
}
// compute first DTS and last DTS, normalize them against reference value
var sample = inputSamples[0];
firstDTS = Math.max(sample.dts, 0);
firstPTS = Math.max(sample.pts, 0);
// check timestamp continuity accross consecutive fragments (this is to remove inter-fragment gap/hole)
var delta = Math.round((firstDTS - nextAvcDts) / 90);
// if fragment are contiguous, detect hole/overlapping between fragments
if (contiguous) {
if (delta) {
if (delta > 1) {
logger["b" /* logger */].log('AVC:' + delta + ' ms hole between fragments detected,filling it');
} else if (delta < -1) {
logger["b" /* logger */].log('AVC:' + -delta + ' ms overlapping between fragments detected');
}
// remove hole/gap : set DTS to next expected DTS
firstDTS = nextAvcDts;
inputSamples[0].dts = firstDTS;
// offset PTS as well, ensure that PTS is smaller or equal than new DTS
firstPTS = Math.max(firstPTS - delta, nextAvcDts);
inputSamples[0].pts = firstPTS;
logger["b" /* logger */].log('Video/PTS/DTS adjusted: ' + Math.round(firstPTS / 90) + '/' + Math.round(firstDTS / 90) + ',delta:' + delta + ' ms');
}
}
nextDTS = firstDTS;
// compute lastPTS/lastDTS
sample = inputSamples[inputSamples.length - 1];
lastDTS = Math.max(sample.dts, 0);
lastPTS = Math.max(sample.pts, 0, lastDTS);
// on Safari let's signal the same sample duration for all samples
// sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
// set this constant duration as being the avg delta between consecutive DTS.
if (isSafari) {
mp4SampleDuration = Math.round((lastDTS - firstDTS) / (inputSamples.length - 1));
}
var nbNalu = 0,
naluLen = 0;
for (var _i = 0; _i < nbSamples; _i++) {
// compute total/avc sample length and nb of NAL units
var _sample = inputSamples[_i],
units = _sample.units,
nbUnits = units.length,
sampleLen = 0;
for (var j = 0; j < nbUnits; j++) {
sampleLen += units[j].data.length;
}
naluLen += sampleLen;
nbNalu += nbUnits;
_sample.length = sampleLen;
// normalize PTS/DTS
if (isSafari) {
// sample DTS is computed using a constant decoding offset (mp4SampleDuration) between samples
_sample.dts = firstDTS + _i * mp4SampleDuration;
} else {
// ensure sample monotonic DTS
_sample.dts = Math.max(_sample.dts, firstDTS);
}
// ensure that computed value is greater or equal than sample DTS
_sample.pts = Math.max(_sample.pts, _sample.dts);
}
/* concatenate the video data and construct the mdat in place
(need 8 more bytes to fill length and mpdat type) */
var mdatSize = naluLen + 4 * nbNalu + 8;
try {
mdat = new Uint8Array(mdatSize);
} catch (err) {
this.observer.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MUX_ERROR, details: errors["a" /* ErrorDetails */].REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: 'fail allocating video mdat ' + mdatSize });
return;
}
var view = new DataView(mdat.buffer);
view.setUint32(0, mdatSize);
mdat.set(mp4_generator.types.mdat, 4);
for (var _i2 = 0; _i2 < nbSamples; _i2++) {
var avcSample = inputSamples[_i2],
avcSampleUnits = avcSample.units,
mp4SampleLength = 0,
compositionTimeOffset = void 0;
// convert NALU bitstream to MP4 format (prepend NALU with size field)
for (var _j = 0, _nbUnits = avcSampleUnits.length; _j < _nbUnits; _j++) {
var unit = avcSampleUnits[_j],
unitData = unit.data,
unitDataLen = unit.data.byteLength;
view.setUint32(offset, unitDataLen);
offset += 4;
mdat.set(unitData, offset);
offset += unitDataLen;
mp4SampleLength += 4 + unitDataLen;
}
if (!isSafari) {
// expected sample duration is the Decoding Timestamp diff of consecutive samples
if (_i2 < nbSamples - 1) {
mp4SampleDuration = inputSamples[_i2 + 1].dts - avcSample.dts;
} else {
var config = this.config,
lastFrameDuration = avcSample.dts - inputSamples[_i2 > 0 ? _i2 - 1 : _i2].dts;
if (config.stretchShortVideoTrack) {
// In some cases, a segment's audio track duration may exceed the video track duration.
// Since we've already remuxed audio, and we know how long the audio track is, we look to
// see if the delta to the next segment is longer than the minimum of maxBufferHole and
// maxSeekHole. If so, playback would potentially get stuck, so we artificially inflate
// the duration of the last frame to minimize any potential gap between segments.
var maxBufferHole = config.maxBufferHole,
maxSeekHole = config.maxSeekHole,
gapTolerance = Math.floor(Math.min(maxBufferHole, maxSeekHole) * timeScale),
deltaToFrameEnd = (audioTrackLength ? firstPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;
if (deltaToFrameEnd > gapTolerance) {
// We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
// frame overlap. maxBufferHole/maxSeekHole should be >> lastFrameDuration anyway.
mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
if (mp4SampleDuration < 0) {
mp4SampleDuration = lastFrameDuration;
}
logger["b" /* logger */].log('It is approximately ' + deltaToFrameEnd / 90 + ' ms to the next segment; using duration ' + mp4SampleDuration / 90 + ' ms for the last video frame.');
} else {
mp4SampleDuration = lastFrameDuration;
}
} else {
mp4SampleDuration = lastFrameDuration;
}
}
compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts);
} else {
compositionTimeOffset = Math.max(0, mp4SampleDuration * Math.round((avcSample.pts - avcSample.dts) / mp4SampleDuration));
}
//console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${avcSample.pts}/${avcSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(avcSample.pts/4294967296).toFixed(3)}');
outputSamples.push({
size: mp4SampleLength,
// constant duration
duration: mp4SampleDuration,
cts: compositionTimeOffset,
flags: {
isLeading: 0,
isDependedOn: 0,
hasRedundancy: 0,
degradPrio: 0,
dependsOn: avcSample.key ? 2 : 1,
isNonSync: avcSample.key ? 0 : 1
}
});
}
// next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
this.nextAvcDts = lastDTS + mp4SampleDuration;
var dropped = track.dropped;
track.len = 0;
track.nbNalu = 0;
track.dropped = 0;
if (outputSamples.length && navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
var flags = outputSamples[0].flags;
// chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue
// https://code.google.com/p/chromium/issues/detail?id=229412
flags.dependsOn = 2;
flags.isNonSync = 0;
}
track.samples = outputSamples;
moof = mp4_generator.moof(track.sequenceNumber++, firstDTS, track);
track.samples = [];
var data = {
data1: moof,
data2: mdat,
startPTS: firstPTS / timeScale,
endPTS: (lastPTS + mp4SampleDuration) / timeScale,
startDTS: firstDTS / timeScale,
endDTS: this.nextAvcDts / timeScale,
type: 'video',
nb: outputSamples.length,
dropped: dropped
};
this.observer.trigger(events["a" /* default */].FRAG_PARSING_DATA, data);
return data;
};
MP4Remuxer.prototype.remuxAudio = function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset) {
var inputTimeScale = track.inputTimeScale,
mp4timeScale = track.timescale,
scaleFactor = inputTimeScale / mp4timeScale,
mp4SampleDuration = track.isAAC ? 1024 : 1152,
inputSampleDuration = mp4SampleDuration * scaleFactor,
ptsNormalize = this._PTSNormalize,
initDTS = this._initDTS,
rawMPEG = !track.isAAC && this.typeSupported.mpeg;
var offset,
mp4Sample,
fillFrame,
mdat,
moof,
firstPTS,
lastPTS,
inputSamples = track.samples,
outputSamples = [],
nextAudioPts = this.nextAudioPts;
// for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
// for sake of clarity:
// consecutive fragments are frags with
// - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
// - less than 20 audio frames distance
// contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
// this helps ensuring audio continuity
// and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
contiguous |= inputSamples.length && nextAudioPts && (accurateTimeOffset && Math.abs(timeOffset - nextAudioPts / inputTimeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAudioPts - initDTS) < 20 * inputSampleDuration);
if (!contiguous) {
// if fragments are not contiguous, let's use timeOffset to compute next Audio PTS
nextAudioPts = timeOffset * inputTimeScale;
}
// compute normalized PTS
inputSamples.forEach(function (sample) {
sample.pts = sample.dts = ptsNormalize(sample.pts - initDTS, nextAudioPts);
});
// sort based on normalized PTS (this is to avoid sorting issues in case timestamp
// reloop in the middle of our samples array)
inputSamples.sort(function (a, b) {
return a.pts - b.pts;
});
// If the audio track is missing samples, the frames seem to get "left-shifted" within the
// resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
// In an effort to prevent this from happening, we inject frames here where there are gaps.
// When possible, we inject a silent frame; when that's not possible, we duplicate the last
// frame.
// only inject/drop audio frames in case time offset is accurate
if (accurateTimeOffset && track.isAAC) {
var maxAudioFramesDrift = this.config.maxAudioFramesDrift;
for (var i = 0, nextPts = nextAudioPts; i < inputSamples.length;) {
// First, let's see how far off this frame is from where we expect it to be
var sample = inputSamples[i],
delta;
var pts = sample.pts;
delta = pts - nextPts;
//console.log(Math.round(pts) + '/' + Math.round(nextPts) + '/' + Math.round(delta));
var duration = Math.abs(1000 * delta / inputTimeScale);
// If we're overlapping by more than a duration, drop this sample
if (delta <= -maxAudioFramesDrift * inputSampleDuration) {
logger["b" /* logger */].warn('Dropping 1 audio frame @ ' + (nextPts / inputTimeScale).toFixed(3) + 's due to ' + Math.round(duration) + ' ms overlap.');
inputSamples.splice(i, 1);
track.len -= sample.unit.length;
// Don't touch nextPtsNorm or i
}
// Insert missing frames if:
// 1: We're more than maxAudioFramesDrift frame away
// 2: Not more than MAX_SILENT_FRAME_DURATION away
// 3: currentTime (aka nextPtsNorm) is not 0
else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && nextPts) {
var missing = Math.round(delta / inputSampleDuration);
logger["b" /* logger */].warn('Injecting ' + missing + ' audio frame @ ' + (nextPts / inputTimeScale).toFixed(3) + 's due to ' + Math.round(1000 * delta / inputTimeScale) + ' ms gap.');
for (var j = 0; j < missing; j++) {
var newStamp = Math.max(nextPts, 0);
fillFrame = aac.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
if (!fillFrame) {
logger["b" /* logger */].log('Unable to get silent frame for given audio codec; duplicating last frame instead.');
fillFrame = sample.unit.subarray();
}
inputSamples.splice(i, 0, { unit: fillFrame, pts: newStamp, dts: newStamp });
track.len += fillFrame.length;
nextPts += inputSampleDuration;
i++;
}
// Adjust sample to next expected pts
sample.pts = sample.dts = nextPts;
nextPts += inputSampleDuration;
i++;
} else {
// Otherwise, just adjust pts
if (Math.abs(delta) > 0.1 * inputSampleDuration) {
//logger.log(`Invalid frame delta ${Math.round(delta + inputSampleDuration)} at PTS ${Math.round(pts / 90)} (should be ${Math.round(inputSampleDuration)}).`);
}
sample.pts = sample.dts = nextPts;
nextPts += inputSampleDuration;
i++;
}
}
}
for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) {
var audioSample = inputSamples[_j2];
var unit = audioSample.unit;
var _pts = audioSample.pts;
//logger.log(`Audio/PTS:${Math.round(pts/90)}`);
// if not first sample
if (lastPTS !== undefined) {
mp4Sample.duration = Math.round((_pts - lastPTS) / scaleFactor);
} else {
var _delta = Math.round(1000 * (_pts - nextAudioPts) / inputTimeScale),
numMissingFrames = 0;
// if fragment are contiguous, detect hole/overlapping between fragments
// contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
if (contiguous && track.isAAC) {
// log delta
if (_delta) {
if (_delta > 0 && _delta < MAX_SILENT_FRAME_DURATION) {
numMissingFrames = Math.round((_pts - nextAudioPts) / inputSampleDuration);
logger["b" /* logger */].log(_delta + ' ms hole between AAC samples detected,filling it');
if (numMissingFrames > 0) {
fillFrame = aac.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
if (!fillFrame) {
fillFrame = unit.subarray();
}
track.len += numMissingFrames * fillFrame.length;
}
// if we have frame overlap, overlapping for more than half a frame duraion
} else if (_delta < -12) {
// drop overlapping audio frames... browser will deal with it
logger["b" /* logger */].log('drop overlapping AAC sample, expected/parsed/delta:' + (nextAudioPts / inputTimeScale).toFixed(3) + 's/' + (_pts / inputTimeScale).toFixed(3) + 's/' + -_delta + 'ms');
track.len -= unit.byteLength;
continue;
}
// set PTS/DTS to expected PTS/DTS
_pts = nextAudioPts;
}
}
// remember first PTS of our audioSamples, ensure value is positive
firstPTS = Math.max(0, _pts);
if (track.len > 0) {
/* concatenate the audio data and construct the mdat in place
(need 8 more bytes to fill length and mdat type) */
var mdatSize = rawMPEG ? track.len : track.len + 8;
offset = rawMPEG ? 0 : 8;
try {
mdat = new Uint8Array(mdatSize);
} catch (err) {
this.observer.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MUX_ERROR, details: errors["a" /* ErrorDetails */].REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: 'fail allocating audio mdat ' + mdatSize });
return;
}
if (!rawMPEG) {
var view = new DataView(mdat.buffer);
view.setUint32(0, mdatSize);
mdat.set(mp4_generator.types.mdat, 4);
}
} else {
// no audio samples
return;
}
for (var _i3 = 0; _i3 < numMissingFrames; _i3++) {
fillFrame = aac.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
if (!fillFrame) {
logger["b" /* logger */].log('Unable to get silent frame for given audio codec; duplicating this frame instead.');
fillFrame = unit.subarray();
}
mdat.set(fillFrame, offset);
offset += fillFrame.byteLength;
mp4Sample = {
size: fillFrame.byteLength,
cts: 0,
duration: 1024,
flags: {
isLeading: 0,
isDependedOn: 0,
hasRedundancy: 0,
degradPrio: 0,
dependsOn: 1
}
};
outputSamples.push(mp4Sample);
}
}
mdat.set(unit, offset);
var unitLen = unit.byteLength;
offset += unitLen;
//console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${audioSample.pts}/${audioSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(audioSample.pts/4294967296).toFixed(3)}');
mp4Sample = {
size: unitLen,
cts: 0,
duration: 0,
flags: {
isLeading: 0,
isDependedOn: 0,
hasRedundancy: 0,
degradPrio: 0,
dependsOn: 1
}
};
outputSamples.push(mp4Sample);
lastPTS = _pts;
}
var lastSampleDuration = 0;
var nbSamples = outputSamples.length;
//set last sample duration as being identical to previous sample
if (nbSamples >= 2) {
lastSampleDuration = outputSamples[nbSamples - 2].duration;
mp4Sample.duration = lastSampleDuration;
}
if (nbSamples) {
// next audio sample PTS should be equal to last sample PTS + duration
this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSampleDuration;
//logger.log('Audio/PTS/PTSend:' + audioSample.pts.toFixed(0) + '/' + this.nextAacDts.toFixed(0));
track.len = 0;
track.samples = outputSamples;
if (rawMPEG) {
moof = new Uint8Array();
} else {
moof = mp4_generator.moof(track.sequenceNumber++, firstPTS / scaleFactor, track);
}
track.samples = [];
var start = firstPTS / inputTimeScale;
var end = nextAudioPts / inputTimeScale;
var audioData = {
data1: moof,
data2: mdat,
startPTS: start,
endPTS: end,
startDTS: start,
endDTS: end,
type: 'audio',
nb: nbSamples
};
this.observer.trigger(events["a" /* default */].FRAG_PARSING_DATA, audioData);
return audioData;
}
return null;
};
MP4Remuxer.prototype.remuxEmptyAudio = function remuxEmptyAudio(track, timeOffset, contiguous, videoData) {
var inputTimeScale = track.inputTimeScale,
mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale,
scaleFactor = inputTimeScale / mp4timeScale,
nextAudioPts = this.nextAudioPts,
// sync with video's timestamp
startDTS = (nextAudioPts !== undefined ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS,
endDTS = videoData.endDTS * inputTimeScale + this._initDTS,
// one sample's duration value
sampleDuration = 1024,
frameDuration = scaleFactor * sampleDuration,
// samples count of this segment's duration
nbSamples = Math.ceil((endDTS - startDTS) / frameDuration),
// silent frame
silentFrame = aac.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
logger["b" /* logger */].warn('remux empty Audio');
// Can't remux if we can't generate a silent frame...
if (!silentFrame) {
logger["b" /* logger */].trace('Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!');
return;
}
var samples = [];
for (var i = 0; i < nbSamples; i++) {
var stamp = startDTS + i * frameDuration;
samples.push({ unit: silentFrame, pts: stamp, dts: stamp });
track.len += silentFrame.length;
}
track.samples = samples;
this.remuxAudio(track, timeOffset, contiguous);
};
MP4Remuxer.prototype.remuxID3 = function remuxID3(track, timeOffset) {
var length = track.samples.length,
sample;
var inputTimeScale = track.inputTimeScale;
var initPTS = this._initPTS;
var initDTS = this._initDTS;
// consume samples
if (length) {
for (var index = 0; index < length; index++) {
sample = track.samples[index];
// setting id3 pts, dts to relative time
// using this._initPTS and this._initDTS to calculate relative time
sample.pts = (sample.pts - initPTS) / inputTimeScale;
sample.dts = (sample.dts - initDTS) / inputTimeScale;
}
this.observer.trigger(events["a" /* default */].FRAG_PARSING_METADATA, {
samples: track.samples
});
}
track.samples = [];
timeOffset = timeOffset;
};
MP4Remuxer.prototype.remuxText = function remuxText(track, timeOffset) {
track.samples.sort(function (a, b) {
return a.pts - b.pts;
});
var length = track.samples.length,
sample;
var inputTimeScale = track.inputTimeScale;
var initPTS = this._initPTS;
// consume samples
if (length) {
for (var index = 0; index < length; index++) {
sample = track.samples[index];
// setting text pts, dts to relative time
// using this._initPTS and this._initDTS to calculate relative time
sample.pts = (sample.pts - initPTS) / inputTimeScale;
}
this.observer.trigger(events["a" /* default */].FRAG_PARSING_USERDATA, {
samples: track.samples
});
}
track.samples = [];
timeOffset = timeOffset;
};
MP4Remuxer.prototype._PTSNormalize = function _PTSNormalize(value, reference) {
var offset;
if (reference === undefined) {
return value;
}
if (reference < value) {
// - 2^33
offset = -8589934592;
} else {
// + 2^33
offset = 8589934592;
}
/* PTS is 33bit (from 0 to 2^33 -1)
if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
PTS looping occured. fill the gap */
while (Math.abs(value - reference) > 4294967296) {
value += offset;
}
return value;
};
return MP4Remuxer;
}();
/* harmony default export */ var mp4_remuxer = (mp4_remuxer_MP4Remuxer);
// CONCATENATED MODULE: ./src/remux/passthrough-remuxer.js
function passthrough_remuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* passthrough remuxer
*/
var passthrough_remuxer_PassThroughRemuxer = function () {
function PassThroughRemuxer(observer) {
passthrough_remuxer__classCallCheck(this, PassThroughRemuxer);
this.observer = observer;
}
PassThroughRemuxer.prototype.destroy = function destroy() {};
PassThroughRemuxer.prototype.resetTimeStamp = function resetTimeStamp() {};
PassThroughRemuxer.prototype.resetInitSegment = function resetInitSegment() {};
PassThroughRemuxer.prototype.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset, rawData) {
var observer = this.observer;
var streamType = '';
if (audioTrack) {
streamType += 'audio';
}
if (videoTrack) {
streamType += 'video';
}
observer.trigger(events["a" /* default */].FRAG_PARSING_DATA, {
data1: rawData,
startPTS: timeOffset,
startDTS: timeOffset,
type: streamType,
nb: 1,
dropped: 0
});
//notify end of parsing
observer.trigger(events["a" /* default */].FRAG_PARSED);
};
return PassThroughRemuxer;
}();
/* harmony default export */ var passthrough_remuxer = (passthrough_remuxer_PassThroughRemuxer);
// CONCATENATED MODULE: ./src/demux/demuxer-inline.js
function demuxer_inline__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/* inline demuxer.
* probe fragments and instantiate appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)
*/
var demuxer_inline_DemuxerInline = function () {
function DemuxerInline(observer, typeSupported, config, vendor) {
demuxer_inline__classCallCheck(this, DemuxerInline);
this.observer = observer;
this.typeSupported = typeSupported;
this.config = config;
this.vendor = vendor;
}
DemuxerInline.prototype.destroy = function destroy() {
var demuxer = this.demuxer;
if (demuxer) {
demuxer.destroy();
}
};
DemuxerInline.prototype.push = function push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {
if (data.byteLength > 0 && decryptdata != null && decryptdata.key != null && decryptdata.method === 'AES-128') {
var decrypter = this.decrypter;
if (decrypter == null) {
decrypter = this.decrypter = new crypt_decrypter(this.observer, this.config);
}
var localthis = this;
// performance.now() not available on WebWorker, at least on Safari Desktop
var startTime;
try {
startTime = performance.now();
} catch (error) {
startTime = Date.now();
}
decrypter.decrypt(data, decryptdata.key.buffer, decryptdata.iv.buffer, function (decryptedData) {
var endTime;
try {
endTime = performance.now();
} catch (error) {
endTime = Date.now();
}
localthis.observer.trigger(events["a" /* default */].FRAG_DECRYPTED, { stats: { tstart: startTime, tdecrypt: endTime } });
localthis.pushDecrypted(new Uint8Array(decryptedData), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
});
} else {
this.pushDecrypted(new Uint8Array(data), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
}
};
DemuxerInline.prototype.pushDecrypted = function pushDecrypted(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {
var demuxer = this.demuxer;
if (!demuxer ||
// in case of continuity change, we might switch from content type (AAC container to TS container for example)
// so let's check that current demuxer is still valid
discontinuity && !this.probe(data)) {
var observer = this.observer;
var typeSupported = this.typeSupported;
var config = this.config;
// probing order is TS/AAC/MP3/MP4
var muxConfig = [{ demux: tsdemuxer, remux: mp4_remuxer }, { demux: aacdemuxer, remux: mp4_remuxer }, { demux: mp3demuxer, remux: mp4_remuxer }, { demux: mp4demuxer, remux: passthrough_remuxer }];
// probe for content type
for (var i = 0, len = muxConfig.length; i < len; i++) {
var mux = muxConfig[i];
var probe = mux.demux.probe;
if (probe(data)) {
var _remuxer = this.remuxer = new mux.remux(observer, config, typeSupported, this.vendor);
demuxer = new mux.demux(observer, _remuxer, config, typeSupported);
this.probe = probe;
break;
}
}
if (!demuxer) {
observer.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: true, reason: 'no demux matching with content found' });
return;
}
this.demuxer = demuxer;
}
var remuxer = this.remuxer;
if (discontinuity || trackSwitch) {
demuxer.resetInitSegment(initSegment, audioCodec, videoCodec, duration);
remuxer.resetInitSegment();
}
if (discontinuity) {
demuxer.resetTimeStamp(defaultInitPTS);
remuxer.resetTimeStamp(defaultInitPTS);
}
if (typeof demuxer.setDecryptData === 'function') {
demuxer.setDecryptData(decryptdata);
}
demuxer.append(data, timeOffset, contiguous, accurateTimeOffset);
};
return DemuxerInline;
}();
/* harmony default export */ var demuxer_inline = __webpack_exports__["a"] = (demuxer_inline_DemuxerInline);
/***/ }),
/* 8 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
// EXTERNAL MODULE: ./node_modules/url-toolkit/src/url-toolkit.js
var url_toolkit = __webpack_require__(6);
var url_toolkit_default = /*#__PURE__*/__webpack_require__.n(url_toolkit);
// EXTERNAL MODULE: ./src/events.js
var events = __webpack_require__(1);
// EXTERNAL MODULE: ./src/errors.js
var errors = __webpack_require__(2);
// EXTERNAL MODULE: ./src/utils/logger.js
var logger = __webpack_require__(0);
// CONCATENATED MODULE: ./src/event-handler.js
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/*
*
* All objects in the event handling chain should inherit from this class
*
*/
var event_handler_EventHandler = function () {
function EventHandler(hls) {
_classCallCheck(this, EventHandler);
this.hls = hls;
this.onEvent = this.onEvent.bind(this);
for (var _len = arguments.length, events = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
events[_key - 1] = arguments[_key];
}
this.handledEvents = events;
this.useGenericHandler = true;
this.registerListeners();
}
EventHandler.prototype.destroy = function destroy() {
this.unregisterListeners();
};
EventHandler.prototype.isEventHandler = function isEventHandler() {
return _typeof(this.handledEvents) === 'object' && this.handledEvents.length && typeof this.onEvent === 'function';
};
EventHandler.prototype.registerListeners = function registerListeners() {
if (this.isEventHandler()) {
this.handledEvents.forEach(function (event) {
if (event === 'hlsEventGeneric') {
throw new Error('Forbidden event name: ' + event);
}
this.hls.on(event, this.onEvent);
}, this);
}
};
EventHandler.prototype.unregisterListeners = function unregisterListeners() {
if (this.isEventHandler()) {
this.handledEvents.forEach(function (event) {
this.hls.off(event, this.onEvent);
}, this);
}
};
/**
* arguments: event (string), data (any)
*/
EventHandler.prototype.onEvent = function onEvent(event, data) {
this.onEventGeneric(event, data);
};
EventHandler.prototype.onEventGeneric = function onEventGeneric(event, data) {
var eventToFunction = function eventToFunction(event, data) {
var funcName = 'on' + event.replace('hls', '');
if (typeof this[funcName] !== 'function') {
throw new Error('Event ' + event + ' has no generic handler in this ' + this.constructor.name + ' class (tried ' + funcName + ')');
}
return this[funcName].bind(this, data);
};
try {
eventToFunction.call(this, event, data).call();
} catch (err) {
logger["b" /* logger */].error('internal error happened while processing ' + event + ':' + err.message);
this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].OTHER_ERROR, details: errors["a" /* ErrorDetails */].INTERNAL_EXCEPTION, fatal: false, event: event, err: err });
}
};
return EventHandler;
}();
/* harmony default export */ var event_handler = (event_handler_EventHandler);
// CONCATENATED MODULE: ./src/utils/attr-list.js
function attr_list__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/;
var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g;
// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
var AttrList = function () {
function AttrList(attrs) {
attr_list__classCallCheck(this, AttrList);
if (typeof attrs === 'string') {
attrs = AttrList.parseAttrList(attrs);
}
for (var attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
this[attr] = attrs[attr];
}
}
}
AttrList.prototype.decimalInteger = function decimalInteger(attrName) {
var intValue = parseInt(this[attrName], 10);
if (intValue > Number.MAX_SAFE_INTEGER) {
return Infinity;
}
return intValue;
};
AttrList.prototype.hexadecimalInteger = function hexadecimalInteger(attrName) {
if (this[attrName]) {
var stringValue = (this[attrName] || '0x').slice(2);
stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
var value = new Uint8Array(stringValue.length / 2);
for (var i = 0; i < stringValue.length / 2; i++) {
value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
}
return value;
} else {
return null;
}
};
AttrList.prototype.hexadecimalIntegerAsNumber = function hexadecimalIntegerAsNumber(attrName) {
var intValue = parseInt(this[attrName], 16);
if (intValue > Number.MAX_SAFE_INTEGER) {
return Infinity;
}
return intValue;
};
AttrList.prototype.decimalFloatingPoint = function decimalFloatingPoint(attrName) {
return parseFloat(this[attrName]);
};
AttrList.prototype.enumeratedString = function enumeratedString(attrName) {
return this[attrName];
};
AttrList.prototype.decimalResolution = function decimalResolution(attrName) {
var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
if (res === null) {
return undefined;
}
return {
width: parseInt(res[1], 10),
height: parseInt(res[2], 10)
};
};
AttrList.parseAttrList = function parseAttrList(input) {
var match,
attrs = {};
ATTR_LIST_REGEX.lastIndex = 0;
while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
var value = match[2],
quote = '"';
if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {
value = value.slice(1, -1);
}
attrs[match[1]] = value;
}
return attrs;
};
return AttrList;
}();
/* harmony default export */ var attr_list = (AttrList);
// CONCATENATED MODULE: ./src/utils/codecs.js
// from http://mp4ra.org/codecs.html
var sampleEntryCodesISO = {
audio: {
'a3ds': true,
'ac-3': true,
'ac-4': true,
'alac': true,
'alaw': true,
'dra1': true,
'dts+': true,
'dts-': true,
'dtsc': true,
'dtse': true,
'dtsh': true,
'ec-3': true,
'enca': true,
'g719': true,
'g726': true,
'm4ae': true,
'mha1': true,
'mha2': true,
'mhm1': true,
'mhm2': true,
'mlpa': true,
'mp4a': true,
'raw ': true,
'Opus': true,
'samr': true,
'sawb': true,
'sawp': true,
'sevc': true,
'sqcp': true,
'ssmv': true,
'twos': true,
'ulaw': true
},
video: {
'avc1': true,
'avc2': true,
'avc3': true,
'avc4': true,
'avcp': true,
'drac': true,
'dvav': true,
'dvhe': true,
'encv': true,
'hev1': true,
'hvc1': true,
'mjp2': true,
'mp4v': true,
'mvc1': true,
'mvc2': true,
'mvc3': true,
'mvc4': true,
'resv': true,
'rv60': true,
's263': true,
'svc1': true,
'svc2': true,
'vc-1': true,
'vp08': true,
'vp09': true
}
};
function isCodecType(codec, type) {
var typeCodes = sampleEntryCodesISO[type];
return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;
}
function isCodecSupportedInMp4(codec) {
return MediaSource.isTypeSupported('video/mp4;codecs="' + codec + '"');
}
// CONCATENATED MODULE: ./src/loader/playlist-loader.js
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function playlist_loader__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Playlist Loader
*/
// https://regex101.com is your friend
var MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g;
var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
/|(?!#)(\S+)/.source, // segment URI, group 3 => the URI (note newline is not eaten)
/|#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)
/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec
/|#.*/.source // All other non-segment oriented tags will match with all groups empty
].join(''), 'g');
var LEVEL_PLAYLIST_REGEX_SLOW = /(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\d+))|(?:#EXT-X-(TARGETDURATION): *(\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\d+))|(?:#EXT-X-(MAP):(.+))|(?:(#)(.*):(.*))|(?:(#)(.*))(?:.*)\r?\n?/;
var playlist_loader_LevelKey = function () {
function LevelKey() {
playlist_loader__classCallCheck(this, LevelKey);
this.method = null;
this.key = null;
this.iv = null;
this._uri = null;
}
_createClass(LevelKey, [{
key: 'uri',
get: function get() {
if (!this._uri && this.reluri) {
this._uri = url_toolkit_default.a.buildAbsoluteURL(this.baseuri, this.reluri, { alwaysNormalize: true });
}
return this._uri;
}
}]);
return LevelKey;
}();
var playlist_loader_Fragment = function () {
function Fragment() {
playlist_loader__classCallCheck(this, Fragment);
this._url = null;
this._byteRange = null;
this._decryptdata = null;
this.tagList = [];
}
/**
* Utility method for parseLevelPlaylist to create an initialization vector for a given segment
* @returns {Uint8Array}
*/
Fragment.prototype.createInitializationVector = function createInitializationVector(segmentNumber) {
var uint8View = new Uint8Array(16);
for (var i = 12; i < 16; i++) {
uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
}
return uint8View;
};
/**
* Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data
* @param levelkey - a playlist's encryption info
* @param segmentNumber - the fragment's segment number
* @returns {*} - an object to be applied as a fragment's decryptdata
*/
Fragment.prototype.fragmentDecryptdataFromLevelkey = function fragmentDecryptdataFromLevelkey(levelkey, segmentNumber) {
var decryptdata = levelkey;
if (levelkey && levelkey.method && levelkey.uri && !levelkey.iv) {
decryptdata = new playlist_loader_LevelKey();
decryptdata.method = levelkey.method;
decryptdata.baseuri = levelkey.baseuri;
decryptdata.reluri = levelkey.reluri;
decryptdata.iv = this.createInitializationVector(segmentNumber);
}
return decryptdata;
};
Fragment.prototype.cloneObj = function cloneObj(obj) {
return JSON.parse(JSON.stringify(obj));
};
_createClass(Fragment, [{
key: 'url',
get: function get() {
if (!this._url && this.relurl) {
this._url = url_toolkit_default.a.buildAbsoluteURL(this.baseurl, this.relurl, { alwaysNormalize: true });
}
return this._url;
},
set: function set(value) {
this._url = value;
}
}, {
key: 'programDateTime',
get: function get() {
if (!this._programDateTime && this.rawProgramDateTime) {
this._programDateTime = new Date(Date.parse(this.rawProgramDateTime));
}
return this._programDateTime;
}
}, {
key: 'byteRange',
get: function get() {
if (!this._byteRange) {
var byteRange = this._byteRange = [];
if (this.rawByteRange) {
var params = this.rawByteRange.split('@', 2);
if (params.length === 1) {
var lastByteRangeEndOffset = this.lastByteRangeEndOffset;
byteRange[0] = lastByteRangeEndOffset ? lastByteRangeEndOffset : 0;
} else {
byteRange[0] = parseInt(params[1]);
}
byteRange[1] = parseInt(params[0]) + byteRange[0];
}
}
return this._byteRange;
}
}, {
key: 'byteRangeStartOffset',
get: function get() {
return this.byteRange[0];
}
}, {
key: 'byteRangeEndOffset',
get: function get() {
return this.byteRange[1];
}
}, {
key: 'decryptdata',
get: function get() {
if (!this._decryptdata) {
this._decryptdata = this.fragmentDecryptdataFromLevelkey(this.levelkey, this.sn);
}
return this._decryptdata;
}
}]);
return Fragment;
}();
var playlist_loader_PlaylistLoader = function (_EventHandler) {
_inherits(PlaylistLoader, _EventHandler);
function PlaylistLoader(hls) {
playlist_loader__classCallCheck(this, PlaylistLoader);
var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MANIFEST_LOADING, events["a" /* default */].LEVEL_LOADING, events["a" /* default */].AUDIO_TRACK_LOADING, events["a" /* default */].SUBTITLE_TRACK_LOADING));
_this.loaders = {};
return _this;
}
PlaylistLoader.prototype.destroy = function destroy() {
for (var loaderName in this.loaders) {
var loader = this.loaders[loaderName];
if (loader) {
loader.destroy();
}
}
this.loaders = {};
event_handler.prototype.destroy.call(this);
};
PlaylistLoader.prototype.onManifestLoading = function onManifestLoading(data) {
this.load(data.url, { type: 'manifest' });
};
PlaylistLoader.prototype.onLevelLoading = function onLevelLoading(data) {
this.load(data.url, { type: 'level', level: data.level, id: data.id });
};
PlaylistLoader.prototype.onAudioTrackLoading = function onAudioTrackLoading(data) {
this.load(data.url, { type: 'audioTrack', id: data.id });
};
PlaylistLoader.prototype.onSubtitleTrackLoading = function onSubtitleTrackLoading(data) {
this.load(data.url, { type: 'subtitleTrack', id: data.id });
};
PlaylistLoader.prototype.load = function load(url, context) {
var loader = this.loaders[context.type];
if (loader) {
var loaderContext = loader.context;
if (loaderContext && loaderContext.url === url) {
logger["b" /* logger */].trace('playlist request ongoing');
return;
} else {
logger["b" /* logger */].warn('abort previous loader for type:' + context.type);
loader.abort();
}
}
var config = this.hls.config,
retry = void 0,
timeout = void 0,
retryDelay = void 0,
maxRetryDelay = void 0;
if (context.type === 'manifest') {
retry = config.manifestLoadingMaxRetry;
timeout = config.manifestLoadingTimeOut;
retryDelay = config.manifestLoadingRetryDelay;
maxRetryDelay = config.manifestLoadingMaxRetryTimeout;
} else {
retry = config.levelLoadingMaxRetry;
timeout = config.levelLoadingTimeOut;
retryDelay = config.levelLoadingRetryDelay;
maxRetryDelay = config.levelLoadingMaxRetryTimeout;
logger["b" /* logger */].log('loading playlist for ' + context.type + ' ' + (context.level || context.id));
}
loader = this.loaders[context.type] = context.loader = typeof config.pLoader !== 'undefined' ? new config.pLoader(config) : new config.loader(config);
context.url = url;
context.responseType = '';
var loaderConfig = void 0,
loaderCallbacks = void 0;
loaderConfig = { timeout: timeout, maxRetry: retry, retryDelay: retryDelay, maxRetryDelay: maxRetryDelay };
loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this) };
loader.load(context, loaderConfig, loaderCallbacks);
};
PlaylistLoader.prototype.resolve = function resolve(url, baseUrl) {
return url_toolkit_default.a.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true });
};
PlaylistLoader.prototype.parseMasterPlaylist = function parseMasterPlaylist(string, baseurl) {
var levels = [],
result = void 0;
MASTER_PLAYLIST_REGEX.lastIndex = 0;
function setCodecs(codecs, level) {
['video', 'audio'].forEach(function (type) {
var filtered = codecs.filter(function (codec) {
return isCodecType(codec, type);
});
if (filtered.length) {
var preferred = filtered.filter(function (codec) {
return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0;
});
level[type + 'Codec'] = preferred.length > 0 ? preferred[0] : filtered[0];
// remove from list
codecs = codecs.filter(function (codec) {
return filtered.indexOf(codec) === -1;
});
}
});
level.unknownCodecs = codecs;
}
while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
var level = {};
var attrs = level.attrs = new attr_list(result[1]);
level.url = this.resolve(result[2], baseurl);
var resolution = attrs.decimalResolution('RESOLUTION');
if (resolution) {
level.width = resolution.width;
level.height = resolution.height;
}
level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH');
level.name = attrs.NAME;
setCodecs([].concat((attrs.CODECS || '').split(/[ ,]+/)), level);
if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {
level.videoCodec = this.avc1toavcoti(level.videoCodec);
}
levels.push(level);
}
return levels;
};
PlaylistLoader.prototype.parseMasterPlaylistMedia = function parseMasterPlaylistMedia(string, baseurl, type) {
var audioCodec = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var result = void 0,
medias = [],
id = 0;
MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) != null) {
var media = {};
var attrs = new attr_list(result[1]);
if (attrs.TYPE === type) {
media.groupId = attrs['GROUP-ID'];
media.name = attrs.NAME;
media.type = type;
media.default = attrs.DEFAULT === 'YES';
media.autoselect = attrs.AUTOSELECT === 'YES';
media.forced = attrs.FORCED === 'YES';
if (attrs.URI) {
media.url = this.resolve(attrs.URI, baseurl);
}
media.lang = attrs.LANGUAGE;
if (!media.name) {
media.name = media.lang;
}
if (audioCodec) {
media.audioCodec = audioCodec;
}
media.id = id++;
medias.push(media);
}
}
return medias;
};
PlaylistLoader.prototype.avc1toavcoti = function avc1toavcoti(codec) {
var result,
avcdata = codec.split('.');
if (avcdata.length > 2) {
result = avcdata.shift() + '.';
result += parseInt(avcdata.shift()).toString(16);
result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);
} else {
result = codec;
}
return result;
};
PlaylistLoader.prototype.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type) {
var currentSN = 0,
totalduration = 0,
level = { type: null, version: null, url: baseurl, fragments: [], live: true, startSN: 0 },
levelkey = new playlist_loader_LevelKey(),
cc = 0,
prevFrag = null,
frag = new playlist_loader_Fragment(),
result,
i;
LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
var duration = result[1];
if (duration) {
// INF
frag.duration = parseFloat(duration);
// avoid sliced strings https://github.com/video-dev/hls.js/issues/939
var title = (' ' + result[2]).slice(1);
frag.title = title ? title : null;
frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
} else if (result[3]) {
// url
if (!isNaN(frag.duration)) {
var sn = currentSN++;
frag.type = type;
frag.start = totalduration;
frag.levelkey = levelkey;
frag.sn = sn;
frag.level = id;
frag.cc = cc;
frag.baseurl = baseurl;
// avoid sliced strings https://github.com/video-dev/hls.js/issues/939
frag.relurl = (' ' + result[3]).slice(1);
level.fragments.push(frag);
prevFrag = frag;
totalduration += frag.duration;
frag = new playlist_loader_Fragment();
}
} else if (result[4]) {
// X-BYTERANGE
frag.rawByteRange = (' ' + result[4]).slice(1);
if (prevFrag) {
var lastByteRangeEndOffset = prevFrag.byteRangeEndOffset;
if (lastByteRangeEndOffset) {
frag.lastByteRangeEndOffset = lastByteRangeEndOffset;
}
}
} else if (result[5]) {
// PROGRAM-DATE-TIME
// avoid sliced strings https://github.com/video-dev/hls.js/issues/939
frag.rawProgramDateTime = (' ' + result[5]).slice(1);
frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);
if (level.programDateTime === undefined) {
level.programDateTime = new Date(new Date(Date.parse(result[5])) - 1000 * totalduration);
}
} else {
result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
for (i = 1; i < result.length; i++) {
if (result[i] !== undefined) {
break;
}
}
// avoid sliced strings https://github.com/video-dev/hls.js/issues/939
var value1 = (' ' + result[i + 1]).slice(1);
var value2 = (' ' + result[i + 2]).slice(1);
switch (result[i]) {
case '#':
frag.tagList.push(value2 ? [value1, value2] : [value1]);
break;
case 'PLAYLIST-TYPE':
level.type = value1.toUpperCase();
break;
case 'MEDIA-SEQUENCE':
currentSN = level.startSN = parseInt(value1);
break;
case 'TARGETDURATION':
level.targetduration = parseFloat(value1);
break;
case 'VERSION':
level.version = parseInt(value1);
break;
case 'EXTM3U':
break;
case 'ENDLIST':
level.live = false;
break;
case 'DIS':
cc++;
frag.tagList.push(['DIS']);
break;
case 'DISCONTINUITY-SEQ':
cc = parseInt(value1);
break;
case 'KEY':
// https://tools.ietf.org/html/draft-pantos-http-live-streaming-08#section-3.4.4
var decryptparams = value1;
var keyAttrs = new attr_list(decryptparams);
var decryptmethod = keyAttrs.enumeratedString('METHOD'),
decrypturi = keyAttrs.URI,
decryptiv = keyAttrs.hexadecimalInteger('IV');
if (decryptmethod) {
levelkey = new playlist_loader_LevelKey();
if (decrypturi && ['AES-128', 'SAMPLE-AES'].indexOf(decryptmethod) >= 0) {
levelkey.method = decryptmethod;
// URI to get the key
levelkey.baseuri = baseurl;
levelkey.reluri = decrypturi;
levelkey.key = null;
// Initialization Vector (IV)
levelkey.iv = decryptiv;
}
}
break;
case 'START':
var startParams = value1;
var startAttrs = new attr_list(startParams);
var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');
//TIME-OFFSET can be 0
if (!isNaN(startTimeOffset)) {
level.startTimeOffset = startTimeOffset;
}
break;
case 'MAP':
var mapAttrs = new attr_list(value1);
frag.relurl = mapAttrs.URI;
frag.rawByteRange = mapAttrs.BYTERANGE;
frag.baseurl = baseurl;
frag.level = id;
frag.type = type;
frag.sn = 'initSegment';
level.initSegment = frag;
frag = new playlist_loader_Fragment();
break;
default:
logger["b" /* logger */].warn('line parsed but not handled: ' + result);
break;
}
}
}
frag = prevFrag;
//logger.log('found ' + level.fragments.length + ' fragments');
if (frag && !frag.relurl) {
level.fragments.pop();
totalduration -= frag.duration;
}
level.totalduration = totalduration;
level.averagetargetduration = totalduration / level.fragments.length;
level.endSN = currentSN - 1;
level.startCC = level.fragments[0] ? level.fragments[0].cc : 0;
level.endCC = cc;
return level;
};
PlaylistLoader.prototype.loadsuccess = function loadsuccess(response, stats, context) {
var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var string = response.data,
url = response.url,
type = context.type,
id = context.id,
level = context.level,
hls = this.hls;
this.loaders[type] = undefined;
// responseURL not supported on some browsers (it is used to detect URL redirection)
// data-uri mode also not supported (but no need to detect redirection)
if (url === undefined || url.indexOf('data:') === 0) {
// fallback to initial URL
url = context.url;
}
stats.tload = performance.now();
//stats.mtime = new Date(target.getResponseHeader('Last-Modified'));
if (string.indexOf('#EXTM3U') === 0) {
if (string.indexOf('#EXTINF:') > 0) {
var isLevel = type !== 'audioTrack' && type !== 'subtitleTrack',
levelId = !isNaN(level) ? level : !isNaN(id) ? id : 0,
levelDetails = this.parseLevelPlaylist(string, url, levelId, type === 'audioTrack' ? 'audio' : type === 'subtitleTrack' ? 'subtitle' : 'main');
levelDetails.tload = stats.tload;
if (type === 'manifest') {
// first request, stream manifest (no master playlist), fire manifest loaded event with level details
hls.trigger(events["a" /* default */].MANIFEST_LOADED, { levels: [{ url: url, details: levelDetails }], audioTracks: [], url: url, stats: stats, networkDetails: networkDetails });
}
stats.tparsed = performance.now();
if (levelDetails.targetduration) {
if (isLevel) {
hls.trigger(events["a" /* default */].LEVEL_LOADED, { details: levelDetails, level: level || 0, id: id || 0, stats: stats, networkDetails: networkDetails });
} else {
if (type === 'audioTrack') {
hls.trigger(events["a" /* default */].AUDIO_TRACK_LOADED, { details: levelDetails, id: id, stats: stats, networkDetails: networkDetails });
} else if (type === 'subtitleTrack') {
hls.trigger(events["a" /* default */].SUBTITLE_TRACK_LOADED, { details: levelDetails, id: id, stats: stats, networkDetails: networkDetails });
}
}
} else {
hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'invalid targetduration', networkDetails: networkDetails });
}
} else {
var levels = this.parseMasterPlaylist(string, url);
// multi level playlist, parse level info
if (levels.length) {
var audioTracks = this.parseMasterPlaylistMedia(string, url, 'AUDIO', levels[0].audioCodec);
var subtitles = this.parseMasterPlaylistMedia(string, url, 'SUBTITLES');
if (audioTracks.length) {
// check if we have found an audio track embedded in main playlist (audio track without URI attribute)
var embeddedAudioFound = false;
audioTracks.forEach(function (audioTrack) {
if (!audioTrack.url) {
embeddedAudioFound = true;
}
});
// if no embedded audio track defined, but audio codec signaled in quality level, we need to signal this main audio track
// this could happen with playlists with alt audio rendition in which quality levels (main) contains both audio+video. but with mixed audio track not signaled
if (embeddedAudioFound === false && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
logger["b" /* logger */].log('audio codec signaled in quality level, but no embedded audio track signaled, create one');
audioTracks.unshift({ type: 'main', name: 'main' });
}
}
hls.trigger(events["a" /* default */].MANIFEST_LOADED, { levels: levels, audioTracks: audioTracks, subtitles: subtitles, url: url, stats: stats, networkDetails: networkDetails });
} else {
hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no level found in manifest', networkDetails: networkDetails });
}
}
} else {
hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no EXTM3U delimiter', networkDetails: networkDetails });
}
};
PlaylistLoader.prototype.loaderror = function loaderror(response, context) {
var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var details,
fatal,
loader = context.loader;
switch (context.type) {
case 'manifest':
details = errors["a" /* ErrorDetails */].MANIFEST_LOAD_ERROR;
fatal = true;
break;
case 'level':
details = errors["a" /* ErrorDetails */].LEVEL_LOAD_ERROR;
fatal = false;
break;
case 'audioTrack':
details = errors["a" /* ErrorDetails */].AUDIO_TRACK_LOAD_ERROR;
fatal = false;
break;
}
if (loader) {
loader.abort();
this.loaders[context.type] = undefined;
}
this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: details, fatal: fatal, url: loader.url, loader: loader, response: response, context: context, networkDetails: networkDetails });
};
PlaylistLoader.prototype.loadtimeout = function loadtimeout(stats, context) {
var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var details,
fatal,
loader = context.loader;
switch (context.type) {
case 'manifest':
details = errors["a" /* ErrorDetails */].MANIFEST_LOAD_TIMEOUT;
fatal = true;
break;
case 'level':
details = errors["a" /* ErrorDetails */].LEVEL_LOAD_TIMEOUT;
fatal = false;
break;
case 'audioTrack':
details = errors["a" /* ErrorDetails */].AUDIO_TRACK_LOAD_TIMEOUT;
fatal = false;
break;
}
if (loader) {
loader.abort();
this.loaders[context.type] = undefined;
}
this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: details, fatal: fatal, url: loader.url, loader: loader, context: context, networkDetails: networkDetails });
};
return PlaylistLoader;
}(event_handler);
/* harmony default export */ var playlist_loader = (playlist_loader_PlaylistLoader);
// CONCATENATED MODULE: ./src/loader/fragment-loader.js
function fragment_loader__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function fragment_loader__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 fragment_loader__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; }
/*
* Fragment Loader
*/
var fragment_loader_FragmentLoader = function (_EventHandler) {
fragment_loader__inherits(FragmentLoader, _EventHandler);
function FragmentLoader(hls) {
fragment_loader__classCallCheck(this, FragmentLoader);
var _this = fragment_loader__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].FRAG_LOADING));
_this.loaders = {};
return _this;
}
FragmentLoader.prototype.destroy = function destroy() {
var loaders = this.loaders;
for (var loaderName in loaders) {
var loader = loaders[loaderName];
if (loader) {
loader.destroy();
}
}
this.loaders = {};
event_handler.prototype.destroy.call(this);
};
FragmentLoader.prototype.onFragLoading = function onFragLoading(data) {
var frag = data.frag,
type = frag.type,
loader = this.loaders[type],
config = this.hls.config;
frag.loaded = 0;
if (loader) {
logger["b" /* logger */].warn('abort previous fragment loader for type:' + type);
loader.abort();
}
loader = this.loaders[type] = frag.loader = typeof config.fLoader !== 'undefined' ? new config.fLoader(config) : new config.loader(config);
var loaderContext = void 0,
loaderConfig = void 0,
loaderCallbacks = void 0;
loaderContext = { url: frag.url, frag: frag, responseType: 'arraybuffer', progressData: false };
var start = frag.byteRangeStartOffset,
end = frag.byteRangeEndOffset;
if (!isNaN(start) && !isNaN(end)) {
loaderContext.rangeStart = start;
loaderContext.rangeEnd = end;
}
loaderConfig = { timeout: config.fragLoadingTimeOut, maxRetry: 0, retryDelay: 0, maxRetryDelay: config.fragLoadingMaxRetryTimeout };
loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this), onProgress: this.loadprogress.bind(this) };
loader.load(loaderContext, loaderConfig, loaderCallbacks);
};
FragmentLoader.prototype.loadsuccess = function loadsuccess(response, stats, context) {
var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var payload = response.data,
frag = context.frag;
// detach fragment loader on load success
frag.loader = undefined;
this.loaders[frag.type] = undefined;
this.hls.trigger(events["a" /* default */].FRAG_LOADED, { payload: payload, frag: frag, stats: stats, networkDetails: networkDetails });
};
FragmentLoader.prototype.loaderror = function loaderror(response, context) {
var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var loader = context.loader;
if (loader) {
loader.abort();
}
this.loaders[context.type] = undefined;
this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR, fatal: false, frag: context.frag, response: response, networkDetails: networkDetails });
};
FragmentLoader.prototype.loadtimeout = function loadtimeout(stats, context) {
var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var loader = context.loader;
if (loader) {
loader.abort();
}
this.loaders[context.type] = undefined;
this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT, fatal: false, frag: context.frag, networkDetails: networkDetails });
};
// data will be used for progressive parsing
FragmentLoader.prototype.loadprogress = function loadprogress(stats, context, data) {
var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
// jshint ignore:line
var frag = context.frag;
frag.loaded = stats.loaded;
this.hls.trigger(events["a" /* default */].FRAG_LOAD_PROGRESS, { frag: frag, stats: stats, networkDetails: networkDetails });
};
return FragmentLoader;
}(event_handler);
/* harmony default export */ var fragment_loader = (fragment_loader_FragmentLoader);
// CONCATENATED MODULE: ./src/loader/key-loader.js
function key_loader__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function key_loader__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 key_loader__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; }
/*
* Decrypt key Loader
*/
var key_loader_KeyLoader = function (_EventHandler) {
key_loader__inherits(KeyLoader, _EventHandler);
function KeyLoader(hls) {
key_loader__classCallCheck(this, KeyLoader);
var _this = key_loader__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].KEY_LOADING));
_this.loaders = {};
_this.decryptkey = null;
_this.decrypturl = null;
return _this;
}
KeyLoader.prototype.destroy = function destroy() {
for (var loaderName in this.loaders) {
var loader = this.loaders[loaderName];
if (loader) {
loader.destroy();
}
}
this.loaders = {};
event_handler.prototype.destroy.call(this);
};
KeyLoader.prototype.onKeyLoading = function onKeyLoading(data) {
var frag = data.frag,
type = frag.type,
loader = this.loaders[type],
decryptdata = frag.decryptdata,
uri = decryptdata.uri;
// if uri is different from previous one or if decrypt key not retrieved yet
if (uri !== this.decrypturl || this.decryptkey === null) {
var config = this.hls.config;
if (loader) {
logger["b" /* logger */].warn('abort previous key loader for type:' + type);
loader.abort();
}
frag.loader = this.loaders[type] = new config.loader(config);
this.decrypturl = uri;
this.decryptkey = null;
var loaderContext = void 0,
loaderConfig = void 0,
loaderCallbacks = void 0;
loaderContext = { url: uri, frag: frag, responseType: 'arraybuffer' };
loaderConfig = { timeout: config.fragLoadingTimeOut, maxRetry: config.fragLoadingMaxRetry, retryDelay: config.fragLoadingRetryDelay, maxRetryDelay: config.fragLoadingMaxRetryTimeout };
loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this) };
frag.loader.load(loaderContext, loaderConfig, loaderCallbacks);
} else if (this.decryptkey) {
// we already loaded this key, return it
decryptdata.key = this.decryptkey;
this.hls.trigger(events["a" /* default */].KEY_LOADED, { frag: frag });
}
};
KeyLoader.prototype.loadsuccess = function loadsuccess(response, stats, context) {
var frag = context.frag;
this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data);
// detach fragment loader on load success
frag.loader = undefined;
this.loaders[frag.type] = undefined;
this.hls.trigger(events["a" /* default */].KEY_LOADED, { frag: frag });
};
KeyLoader.prototype.loaderror = function loaderror(response, context) {
var frag = context.frag,
loader = frag.loader;
if (loader) {
loader.abort();
}
this.loaders[context.type] = undefined;
this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].KEY_LOAD_ERROR, fatal: false, frag: frag, response: response });
};
KeyLoader.prototype.loadtimeout = function loadtimeout(stats, context) {
var frag = context.frag,
loader = frag.loader;
if (loader) {
loader.abort();
}
this.loaders[context.type] = undefined;
this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].KEY_LOAD_TIMEOUT, fatal: false, frag: frag });
};
return KeyLoader;
}(event_handler);
/* harmony default export */ var key_loader = (key_loader_KeyLoader);
// CONCATENATED MODULE: ./src/utils/binary-search.js
var BinarySearch = {
/**
* Searches for an item in an array which matches a certain condition.
* This requires the condition to only match one item in the array,
* and for the array to be ordered.
*
* @param {Array} list The array to search.
* @param {Function} comparisonFunction
* Called and provided a candidate item as the first argument.
* Should return:
* > -1 if the item should be located at a lower index than the provided item.
* > 1 if the item should be located at a higher index than the provided item.
* > 0 if the item is the item you're looking for.
*
* @return {*} The object if it is found or null otherwise.
*/
search: function search(list, comparisonFunction) {
var minIndex = 0;
var maxIndex = list.length - 1;
var currentIndex = null;
var currentElement = null;
while (minIndex <= maxIndex) {
currentIndex = (minIndex + maxIndex) / 2 | 0;
currentElement = list[currentIndex];
var comparisonResult = comparisonFunction(currentElement);
if (comparisonResult > 0) {
minIndex = currentIndex + 1;
} else if (comparisonResult < 0) {
maxIndex = currentIndex - 1;
} else {
return currentElement;
}
}
return null;
}
};
/* harmony default export */ var binary_search = (BinarySearch);
// CONCATENATED MODULE: ./src/helper/buffer-helper.js
/**
* Buffer Helper utils, providing methods dealing buffer length retrieval
*/
var BufferHelper = {
isBuffered: function isBuffered(media, position) {
if (media) {
var buffered = media.buffered;
for (var i = 0; i < buffered.length; i++) {
if (position >= buffered.start(i) && position <= buffered.end(i)) {
return true;
}
}
}
return false;
},
bufferInfo: function bufferInfo(media, pos, maxHoleDuration) {
if (media) {
var vbuffered = media.buffered,
buffered = [],
i;
for (i = 0; i < vbuffered.length; i++) {
buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) });
}
return this.bufferedInfo(buffered, pos, maxHoleDuration);
} else {
return { len: 0, start: pos, end: pos, nextStart: undefined };
}
},
bufferedInfo: function bufferedInfo(buffered, pos, maxHoleDuration) {
var buffered2 = [],
// bufferStart and bufferEnd are buffer boundaries around current video position
bufferLen,
bufferStart,
bufferEnd,
bufferStartNext,
i;
// sort on buffer.start/smaller end (IE does not always return sorted buffered range)
buffered.sort(function (a, b) {
var diff = a.start - b.start;
if (diff) {
return diff;
} else {
return b.end - a.end;
}
});
// there might be some small holes between buffer time range
// consider that holes smaller than maxHoleDuration are irrelevant and build another
// buffer time range representations that discards those holes
for (i = 0; i < buffered.length; i++) {
var buf2len = buffered2.length;
if (buf2len) {
var buf2end = buffered2[buf2len - 1].end;
// if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
if (buffered[i].start - buf2end < maxHoleDuration) {
// merge overlapping time ranges
// update lastRange.end only if smaller than item.end
// e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
// whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
if (buffered[i].end > buf2end) {
buffered2[buf2len - 1].end = buffered[i].end;
}
} else {
// big hole
buffered2.push(buffered[i]);
}
} else {
// first value
buffered2.push(buffered[i]);
}
}
for (i = 0, bufferLen = 0, bufferStart = bufferEnd = pos; i < buffered2.length; i++) {
var start = buffered2[i].start,
end = buffered2[i].end;
//logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
if (pos + maxHoleDuration >= start && pos < end) {
// play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
bufferStart = start;
bufferEnd = end;
bufferLen = bufferEnd - pos;
} else if (pos + maxHoleDuration < start) {
bufferStartNext = start;
break;
}
}
return { len: bufferLen, start: bufferStart, end: bufferEnd, nextStart: bufferStartNext };
}
};
/* harmony default export */ var buffer_helper = (BufferHelper);
// EXTERNAL MODULE: ./src/demux/demuxer-inline.js + 16 modules
var demuxer_inline = __webpack_require__(7);
// EXTERNAL MODULE: ./node_modules/events/events.js
var events_events = __webpack_require__(5);
var events_default = /*#__PURE__*/__webpack_require__.n(events_events);
// EXTERNAL MODULE: ./node_modules/webworkify-webpack/index.js
var webworkify_webpack = __webpack_require__(9);
var webworkify_webpack_default = /*#__PURE__*/__webpack_require__.n(webworkify_webpack);
// CONCATENATED MODULE: ./src/helper/mediasource-helper.js
/**
* MediaSource helper
*/
function getMediaSource() {
if (typeof window !== 'undefined') {
return window.MediaSource || window.WebKitMediaSource;
}
}
// CONCATENATED MODULE: ./src/demux/demuxer.js
function demuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var demuxer_MediaSource = getMediaSource();
var demuxer_Demuxer = function () {
function Demuxer(hls, id) {
demuxer__classCallCheck(this, Demuxer);
this.hls = hls;
this.id = id;
// observer setup
var observer = this.observer = new events_default.a();
var config = hls.config;
observer.trigger = function trigger(event) {
for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
data[_key - 1] = arguments[_key];
}
observer.emit.apply(observer, [event, event].concat(data));
};
observer.off = function off(event) {
for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
data[_key2 - 1] = arguments[_key2];
}
observer.removeListener.apply(observer, [event].concat(data));
};
var forwardMessage = function (ev, data) {
data = data || {};
data.frag = this.frag;
data.id = this.id;
hls.trigger(ev, data);
}.bind(this);
// forward events to main thread
observer.on(events["a" /* default */].FRAG_DECRYPTED, forwardMessage);
observer.on(events["a" /* default */].FRAG_PARSING_INIT_SEGMENT, forwardMessage);
observer.on(events["a" /* default */].FRAG_PARSING_DATA, forwardMessage);
observer.on(events["a" /* default */].FRAG_PARSED, forwardMessage);
observer.on(events["a" /* default */].ERROR, forwardMessage);
observer.on(events["a" /* default */].FRAG_PARSING_METADATA, forwardMessage);
observer.on(events["a" /* default */].FRAG_PARSING_USERDATA, forwardMessage);
observer.on(events["a" /* default */].INIT_PTS_FOUND, forwardMessage);
var typeSupported = {
mp4: demuxer_MediaSource.isTypeSupported('video/mp4'),
mpeg: demuxer_MediaSource.isTypeSupported('audio/mpeg'),
mp3: demuxer_MediaSource.isTypeSupported('audio/mp4; codecs="mp3"')
};
// navigator.vendor is not always available in Web Worker
// refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator
var vendor = navigator.vendor;
if (config.enableWorker && typeof Worker !== 'undefined') {
logger["b" /* logger */].log('demuxing in webworker');
var w = void 0;
try {
w = this.w = webworkify_webpack_default()(/*require.resolve*/(10));
this.onwmsg = this.onWorkerMessage.bind(this);
w.addEventListener('message', this.onwmsg);
w.onerror = function (event) {
hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].OTHER_ERROR, details: errors["a" /* ErrorDetails */].INTERNAL_EXCEPTION, fatal: true, event: 'demuxerWorker', err: { message: event.message + ' (' + event.filename + ':' + event.lineno + ')' } });
};
w.postMessage({ cmd: 'init', typeSupported: typeSupported, vendor: vendor, id: id, config: JSON.stringify(config) });
} catch (err) {
logger["b" /* logger */].error('error while initializing DemuxerWorker, fallback on DemuxerInline');
if (w) {
// revoke the Object URL that was used to create demuxer worker, so as not to leak it
URL.revokeObjectURL(w.objectURL);
}
this.demuxer = new demuxer_inline["a" /* default */](observer, typeSupported, config, vendor);
this.w = undefined;
}
} else {
this.demuxer = new demuxer_inline["a" /* default */](observer, typeSupported, config, vendor);
}
}
Demuxer.prototype.destroy = function destroy() {
var w = this.w;
if (w) {
w.removeEventListener('message', this.onwmsg);
w.terminate();
this.w = null;
} else {
var demuxer = this.demuxer;
if (demuxer) {
demuxer.destroy();
this.demuxer = null;
}
}
var observer = this.observer;
if (observer) {
observer.removeAllListeners();
this.observer = null;
}
};
Demuxer.prototype.push = function push(data, initSegment, audioCodec, videoCodec, frag, duration, accurateTimeOffset, defaultInitPTS) {
var w = this.w;
var timeOffset = !isNaN(frag.startDTS) ? frag.startDTS : frag.start;
var decryptdata = frag.decryptdata;
var lastFrag = this.frag;
var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
var trackSwitch = !(lastFrag && frag.level === lastFrag.level);
var nextSN = lastFrag && frag.sn === lastFrag.sn + 1;
var contiguous = !trackSwitch && nextSN;
if (discontinuity) {
logger["b" /* logger */].log(this.id + ':discontinuity detected');
}
if (trackSwitch) {
logger["b" /* logger */].log(this.id + ':switch detected');
}
this.frag = frag;
if (w) {
// post fragment payload as transferable objects for ArrayBuffer (no copy)
w.postMessage({ cmd: 'demux', data: data, decryptdata: decryptdata, initSegment: initSegment, audioCodec: audioCodec, videoCodec: videoCodec, timeOffset: timeOffset, discontinuity: discontinuity, trackSwitch: trackSwitch, contiguous: contiguous, duration: duration, accurateTimeOffset: accurateTimeOffset, defaultInitPTS: defaultInitPTS }, data instanceof ArrayBuffer ? [data] : []);
} else {
var demuxer = this.demuxer;
if (demuxer) {
demuxer.push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
}
}
};
Demuxer.prototype.onWorkerMessage = function onWorkerMessage(ev) {
var data = ev.data,
hls = this.hls;
//console.log('onWorkerMessage:' + data.event);
switch (data.event) {
case 'init':
// revoke the Object URL that was used to create demuxer worker, so as not to leak it
URL.revokeObjectURL(this.w.objectURL);
break;
// special case for FRAG_PARSING_DATA: data1 and data2 are transferable objects
case events["a" /* default */].FRAG_PARSING_DATA:
data.data.data1 = new Uint8Array(data.data1);
if (data.data2) {
data.data.data2 = new Uint8Array(data.data2);
}
/* falls through */
default:
data.data = data.data || {};
data.data.frag = this.frag;
data.data.id = this.id;
hls.trigger(data.event, data.data);
break;
}
};
return Demuxer;
}();
/* harmony default export */ var demux_demuxer = (demuxer_Demuxer);
// CONCATENATED MODULE: ./src/helper/level-helper.js
/**
* Level Helper class, providing methods dealing with playlist sliding and drift
*/
function updatePTS(fragments, fromIdx, toIdx) {
var fragFrom = fragments[fromIdx],
fragTo = fragments[toIdx],
fragToPTS = fragTo.startPTS;
// if we know startPTS[toIdx]
if (!isNaN(fragToPTS)) {
// update fragment duration.
// it helps to fix drifts between playlist reported duration and fragment real duration
if (toIdx > fromIdx) {
fragFrom.duration = fragToPTS - fragFrom.start;
if (fragFrom.duration < 0) {
logger["b" /* logger */].warn('negative duration computed for frag ' + fragFrom.sn + ',level ' + fragFrom.level + ', there should be some duration drift between playlist and fragment!');
}
} else {
fragTo.duration = fragFrom.start - fragToPTS;
if (fragTo.duration < 0) {
logger["b" /* logger */].warn('negative duration computed for frag ' + fragTo.sn + ',level ' + fragTo.level + ', there should be some duration drift between playlist and fragment!');
}
}
} else {
// we dont know startPTS[toIdx]
if (toIdx > fromIdx) {
fragTo.start = fragFrom.start + fragFrom.duration;
} else {
fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);
}
}
}
function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
// update frag PTS/DTS
var maxStartPTS = startPTS;
if (!isNaN(frag.startPTS)) {
// delta PTS between audio and video
var deltaPTS = Math.abs(frag.startPTS - startPTS);
if (isNaN(frag.deltaPTS)) {
frag.deltaPTS = deltaPTS;
} else {
frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
}
maxStartPTS = Math.max(startPTS, frag.startPTS);
startPTS = Math.min(startPTS, frag.startPTS);
endPTS = Math.max(endPTS, frag.endPTS);
startDTS = Math.min(startDTS, frag.startDTS);
endDTS = Math.max(endDTS, frag.endDTS);
}
var drift = startPTS - frag.start;
frag.start = frag.startPTS = startPTS;
frag.maxStartPTS = maxStartPTS;
frag.endPTS = endPTS;
frag.startDTS = startDTS;
frag.endDTS = endDTS;
frag.duration = endPTS - startPTS;
var sn = frag.sn;
// exit if sn out of range
if (!details || sn < details.startSN || sn > details.endSN) {
return 0;
}
var fragIdx, fragments, i;
fragIdx = sn - details.startSN;
fragments = details.fragments;
// update frag reference in fragments array
// rationale is that fragments array might not contain this frag object.
// this will happpen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
// if we don't update frag, we won't be able to propagate PTS info on the playlist
// resulting in invalid sliding computation
fragments[fragIdx] = frag;
// adjust fragment PTS/duration from seqnum-1 to frag 0
for (i = fragIdx; i > 0; i--) {
updatePTS(fragments, i, i - 1);
}
// adjust fragment PTS/duration from seqnum to last frag
for (i = fragIdx; i < fragments.length - 1; i++) {
updatePTS(fragments, i, i + 1);
}
details.PTSKnown = true;
//logger.log(` frag start/end:${startPTS.toFixed(3)}/${endPTS.toFixed(3)}`);
return drift;
}
function mergeDetails(oldDetails, newDetails) {
var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN,
end = Math.min(oldDetails.endSN, newDetails.endSN) - newDetails.startSN,
delta = newDetails.startSN - oldDetails.startSN,
oldfragments = oldDetails.fragments,
newfragments = newDetails.fragments,
ccOffset = 0,
PTSFrag;
// check if old/new playlists have fragments in common
if (end < start) {
newDetails.PTSKnown = false;
return;
}
// loop through overlapping SN and update startPTS , cc, and duration if any found
for (var i = start; i <= end; i++) {
var oldFrag = oldfragments[delta + i],
newFrag = newfragments[i];
if (newFrag && oldFrag) {
ccOffset = oldFrag.cc - newFrag.cc;
if (!isNaN(oldFrag.startPTS)) {
newFrag.start = newFrag.startPTS = oldFrag.startPTS;
newFrag.endPTS = oldFrag.endPTS;
newFrag.duration = oldFrag.duration;
newFrag.backtracked = oldFrag.backtracked;
newFrag.dropped = oldFrag.dropped;
PTSFrag = newFrag;
}
}
}
if (ccOffset) {
logger["b" /* logger */].log('discontinuity sliding from playlist, take drift into account');
for (i = 0; i < newfragments.length; i++) {
newfragments[i].cc += ccOffset;
}
}
// if at least one fragment contains PTS info, recompute PTS information for all fragments
if (PTSFrag) {
updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
} else {
// ensure that delta is within oldfragments range
// also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
// in that case we also need to adjust start offset of all fragments
if (delta >= 0 && delta < oldfragments.length) {
// adjust start by sliding offset
var sliding = oldfragments[delta].start;
for (i = 0; i < newfragments.length; i++) {
newfragments[i].start += sliding;
}
}
}
// if we are here, it means we have fragments overlapping between
// old and new level. reliable PTS info is thus relying on old level
newDetails.PTSKnown = oldDetails.PTSKnown;
}
// CONCATENATED MODULE: ./src/utils/timeRanges.js
/**
* TimeRanges to string helper
*/
var TimeRanges = {
toString: function toString(r) {
var log = '',
len = r.length;
for (var i = 0; i < len; i++) {
log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';
}
return log;
}
};
/* harmony default export */ var timeRanges = (TimeRanges);
// CONCATENATED MODULE: ./src/utils/discontinuities.js
function findFirstFragWithCC(fragments, cc) {
var firstFrag = null;
for (var i = 0; i < fragments.length; i += 1) {
var currentFrag = fragments[i];
if (currentFrag && currentFrag.cc === cc) {
firstFrag = currentFrag;
break;
}
}
return firstFrag;
}
function findFragWithCC(fragments, CC) {
return binary_search.search(fragments, function (candidate) {
if (candidate.cc < CC) {
return 1;
} else if (candidate.cc > CC) {
return -1;
} else {
return 0;
}
});
}
function shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) {
var shouldAlign = false;
if (lastLevel && lastLevel.details && details) {
if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) {
shouldAlign = true;
}
}
return shouldAlign;
}
// Find the first frag in the previous level which matches the CC of the first frag of the new level
function findDiscontinuousReferenceFrag(prevDetails, curDetails) {
var prevFrags = prevDetails.fragments;
var curFrags = curDetails.fragments;
if (!curFrags.length || !prevFrags.length) {
logger["b" /* logger */].log('No fragments to align');
return;
}
var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);
if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) {
logger["b" /* logger */].log('No frag in previous level to align on');
return;
}
return prevStartFrag;
}
function adjustPts(sliding, details) {
details.fragments.forEach(function (frag) {
if (frag) {
var start = frag.start + sliding;
frag.start = frag.startPTS = start;
frag.endPTS = start + frag.duration;
}
});
details.PTSKnown = true;
}
// If a change in CC is detected, the PTS can no longer be relied upon
// Attempt to align the level by using the last level - find the last frag matching the current CC and use it's PTS
// as a reference
function alignDiscontinuities(lastFrag, lastLevel, details) {
if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {
var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);
if (referenceFrag) {
logger["b" /* logger */].log('Adjusting PTS using last level due to CC increase within current level');
adjustPts(referenceFrag.start, details);
}
}
// try to align using programDateTime attribute (if available)
if (details.PTSKnown === false && lastLevel && lastLevel.details) {
// if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM
// and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM
// then we can deduce that playlist B sliding is 1000+8 = 1008s
var lastPDT = lastLevel.details.programDateTime;
var newPDT = details.programDateTime;
// date diff is in ms. frag.start is in seconds
var sliding = (newPDT - lastPDT) / 1000 + lastLevel.details.fragments[0].start;
if (!isNaN(sliding)) {
logger["b" /* logger */].log('adjusting PTS using programDateTime delta, sliding:' + sliding.toFixed(3));
adjustPts(sliding, details);
}
}
}
// CONCATENATED MODULE: ./src/controller/stream-controller.js
var stream_controller__createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function stream_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function stream_controller__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 stream_controller__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; }
/*
* Stream Controller
*/
var State = {
STOPPED: 'STOPPED',
IDLE: 'IDLE',
KEY_LOADING: 'KEY_LOADING',
FRAG_LOADING: 'FRAG_LOADING',
FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
WAITING_LEVEL: 'WAITING_LEVEL',
PARSING: 'PARSING',
PARSED: 'PARSED',
BUFFER_FLUSHING: 'BUFFER_FLUSHING',
ENDED: 'ENDED',
ERROR: 'ERROR'
};
var stream_controller_StreamController = function (_EventHandler) {
stream_controller__inherits(StreamController, _EventHandler);
function StreamController(hls) {
stream_controller__classCallCheck(this, StreamController);
var _this = stream_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHED, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].MANIFEST_LOADING, events["a" /* default */].MANIFEST_PARSED, events["a" /* default */].LEVEL_LOADED, events["a" /* default */].KEY_LOADED, events["a" /* default */].FRAG_LOADED, events["a" /* default */].FRAG_LOAD_EMERGENCY_ABORTED, events["a" /* default */].FRAG_PARSING_INIT_SEGMENT, events["a" /* default */].FRAG_PARSING_DATA, events["a" /* default */].FRAG_PARSED, events["a" /* default */].ERROR, events["a" /* default */].AUDIO_TRACK_SWITCHING, events["a" /* default */].AUDIO_TRACK_SWITCHED, events["a" /* default */].BUFFER_CREATED, events["a" /* default */].BUFFER_APPENDED, events["a" /* default */].BUFFER_FLUSHED));
_this.config = hls.config;
_this.audioCodecSwap = false;
_this.ticks = 0;
_this._state = State.STOPPED;
_this.ontick = _this.tick.bind(_this);
return _this;
}
StreamController.prototype.destroy = function destroy() {
this.stopLoad();
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
event_handler.prototype.destroy.call(this);
this.state = State.STOPPED;
};
StreamController.prototype.startLoad = function startLoad(startPosition) {
if (this.levels) {
var lastCurrentTime = this.lastCurrentTime,
hls = this.hls;
this.stopLoad();
if (!this.timer) {
this.timer = setInterval(this.ontick, 100);
}
this.level = -1;
this.fragLoadError = 0;
if (!this.startFragRequested) {
// determine load level
var startLevel = hls.startLevel;
if (startLevel === -1) {
// -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
startLevel = 0;
this.bitrateTest = true;
}
// set new level to playlist loader : this will trigger start level load
// hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
this.level = hls.nextLoadLevel = startLevel;
this.loadedmetadata = false;
}
// if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
if (lastCurrentTime > 0 && startPosition === -1) {
logger["b" /* logger */].log('override startPosition with lastCurrentTime @' + lastCurrentTime.toFixed(3));
startPosition = lastCurrentTime;
}
this.state = State.IDLE;
this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
this.tick();
} else {
this.forceStartLoad = true;
this.state = State.STOPPED;
}
};
StreamController.prototype.stopLoad = function stopLoad() {
var frag = this.fragCurrent;
if (frag) {
if (frag.loader) {
frag.loader.abort();
}
this.fragCurrent = null;
}
this.fragPrevious = null;
if (this.demuxer) {
this.demuxer.destroy();
this.demuxer = null;
}
this.state = State.STOPPED;
this.forceStartLoad = false;
};
StreamController.prototype.tick = function tick() {
this.ticks++;
if (this.ticks === 1) {
this.doTick();
if (this.ticks > 1) {
setTimeout(this.tick, 1);
}
this.ticks = 0;
}
};
StreamController.prototype.doTick = function doTick() {
switch (this.state) {
case State.ERROR:
//don't do anything in error state to avoid breaking further ...
break;
case State.BUFFER_FLUSHING:
// in buffer flushing state, reset fragLoadError counter
this.fragLoadError = 0;
break;
case State.IDLE:
this._doTickIdle();
break;
case State.WAITING_LEVEL:
var level = this.levels[this.level];
// check if playlist is already loaded
if (level && level.details) {
this.state = State.IDLE;
}
break;
case State.FRAG_LOADING_WAITING_RETRY:
var now = performance.now();
var retryDate = this.retryDate;
// if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
if (!retryDate || now >= retryDate || this.media && this.media.seeking) {
logger["b" /* logger */].log('mediaController: retryDate reached, switch back to IDLE state');
this.state = State.IDLE;
}
break;
case State.ERROR:
case State.STOPPED:
case State.FRAG_LOADING:
case State.PARSING:
case State.PARSED:
case State.ENDED:
break;
default:
break;
}
// check buffer
this._checkBuffer();
// check/update current fragment
this._checkFragmentChanged();
};
// Ironically the "idle" state is the on we do the most logic in it seems ....
// NOTE: Maybe we could rather schedule a check for buffer length after half of the currently
// played segment, or on pause/play/seek instead of naively checking every 100ms?
StreamController.prototype._doTickIdle = function _doTickIdle() {
var hls = this.hls,
config = hls.config,
media = this.media;
// if start level not parsed yet OR
// if video not attached AND start fragment already requested OR start frag prefetch disable
// exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
if (this.levelLastLoaded === undefined || !media && (this.startFragRequested || !config.startFragPrefetch)) {
return;
}
// if we have not yet loaded any fragment, start loading from start position
var pos = void 0;
if (this.loadedmetadata) {
pos = media.currentTime;
} else {
pos = this.nextLoadPosition;
}
// determine next load level
var level = hls.nextLoadLevel,
levelInfo = this.levels[level];
if (!levelInfo) {
return;
}
var levelBitrate = levelInfo.bitrate,
maxBufLen = void 0;
// compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s
if (levelBitrate) {
maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
} else {
maxBufLen = config.maxBufferLength;
}
maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength);
// determine next candidate fragment to be loaded, based on current position and end of buffer position
// ensure up to `config.maxMaxBufferLength` of buffer upfront
var bufferInfo = buffer_helper.bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, config.maxBufferHole),
bufferLen = bufferInfo.len;
// Stay idle if we are still with buffer margins
if (bufferLen >= maxBufLen) {
return;
}
// if buffer length is less than maxBufLen try to load a new fragment ...
logger["b" /* logger */].trace('buffer length of ' + bufferLen.toFixed(3) + ' is below max of ' + maxBufLen.toFixed(3) + '. checking for more payload ...');
// set next load level : this will trigger a playlist load if needed
this.level = hls.nextLoadLevel = level;
var levelDetails = levelInfo.details;
// if level info not retrieved yet, switch state and wait for level retrieval
// if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
// a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
if (typeof levelDetails === 'undefined' || levelDetails.live && this.levelLastLoaded !== level) {
this.state = State.WAITING_LEVEL;
return;
}
// we just got done loading the final fragment and there is no other buffered range after ...
// rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between
// so we should not switch to ENDED in that case, to be able to buffer them
// dont switch to ENDED if we need to backtrack last fragment
var fragPrevious = this.fragPrevious;
if (!levelDetails.live && fragPrevious && !fragPrevious.backtracked && fragPrevious.sn === levelDetails.endSN && !bufferInfo.nextStart) {
// fragPrevious is last fragment. retrieve level duration using last frag start offset + duration
// real duration might be lower than initial duration if there are drifts between real frag duration and playlist signaling
var duration = Math.min(media.duration, fragPrevious.start + fragPrevious.duration);
// if everything (almost) til the end is buffered, let's signal eos
// we don't compare exactly media.duration === bufferInfo.end as there could be some subtle media duration difference (audio/video offsets...)
// tolerate up to one frag duration to cope with these cases.
// also cope with almost zero last frag duration (max last frag duration with 200ms) refer to https://github.com/video-dev/hls.js/pull/657
if (duration - Math.max(bufferInfo.end, fragPrevious.start) <= Math.max(0.2, fragPrevious.duration)) {
// Finalize the media stream
var data = {};
if (this.altAudio) {
data.type = 'video';
}
this.hls.trigger(events["a" /* default */].BUFFER_EOS, data);
this.state = State.ENDED;
return;
}
}
// if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..)
this._fetchPayloadOrEos(pos, bufferInfo, levelDetails);
};
StreamController.prototype._fetchPayloadOrEos = function _fetchPayloadOrEos(pos, bufferInfo, levelDetails) {
var fragPrevious = this.fragPrevious,
level = this.level,
fragments = levelDetails.fragments,
fragLen = fragments.length;
// empty playlist
if (fragLen === 0) {
return;
}
// find fragment index, contiguous with end of buffer position
var start = fragments[0].start,
end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,
bufferEnd = bufferInfo.end,
frag = void 0;
if (levelDetails.initSegment && !levelDetails.initSegment.data) {
frag = levelDetails.initSegment;
} else {
// in case of live playlist we need to ensure that requested position is not located before playlist start
if (levelDetails.live) {
var initialLiveManifestSize = this.config.initialLiveManifestSize;
if (fragLen < initialLiveManifestSize) {
logger["b" /* logger */].warn('Can not start playback of a level, reason: not enough fragments ' + fragLen + ' < ' + initialLiveManifestSize);
return;
}
frag = this._ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen);
// if it explicitely returns null don't load any fragment and exit function now
if (frag === null) {
return;
}
} else {
// VoD playlist: if bufferEnd before start of playlist, load first fragment
if (bufferEnd < start) {
frag = fragments[0];
}
}
}
if (!frag) {
frag = this._findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails);
}
if (frag) {
this._loadFragmentOrKey(frag, level, levelDetails, pos, bufferEnd);
}
return;
};
StreamController.prototype._ensureFragmentAtLivePoint = function _ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen) {
var config = this.hls.config,
media = this.media;
var frag = void 0;
// check if requested position is within seekable boundaries :
//logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`);
var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) {
var liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails);
logger["b" /* logger */].log('buffer end: ' + bufferEnd.toFixed(3) + ' is located too far from the end of live sliding playlist, reset currentTime to : ' + liveSyncPosition.toFixed(3));
bufferEnd = liveSyncPosition;
if (media && media.readyState && media.duration > liveSyncPosition) {
media.currentTime = liveSyncPosition;
}
this.nextLoadPosition = liveSyncPosition;
}
// if end of buffer greater than live edge, don't load any fragment
// this could happen if live playlist intermittently slides in the past.
// level 1 loaded [182580161,182580167]
// level 1 loaded [182580162,182580169]
// Loading 182580168 of [182580162 ,182580169],level 1 ..
// Loading 182580169 of [182580162 ,182580169],level 1 ..
// level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168
// level 1 loaded [182580164,182580171]
//
// don't return null in case media not loaded yet (readystate === 0)
if (levelDetails.PTSKnown && bufferEnd > end && media && media.readyState) {
return null;
}
if (this.startFragRequested && !levelDetails.PTSKnown) {
/* we are switching level on live playlist, but we don't have any PTS info for that quality level ...
try to load frag matching with next SN.
even if SN are not synchronized between playlists, loading this frag will help us
compute playlist sliding and find the right one after in case it was not the right consecutive one */
if (fragPrevious) {
var targetSN = fragPrevious.sn + 1;
if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
var fragNext = fragments[targetSN - levelDetails.startSN];
if (fragPrevious.cc === fragNext.cc) {
frag = fragNext;
logger["b" /* logger */].log('live playlist, switching playlist, load frag with next SN: ' + frag.sn);
}
}
// next frag SN not available (or not with same continuity counter)
// look for a frag sharing the same CC
if (!frag) {
frag = binary_search.search(fragments, function (frag) {
return fragPrevious.cc - frag.cc;
});
if (frag) {
logger["b" /* logger */].log('live playlist, switching playlist, load frag with same CC: ' + frag.sn);
}
}
}
if (!frag) {
/* we have no idea about which fragment should be loaded.
so let's load mid fragment. it will help computing playlist sliding and find the right one
*/
frag = fragments[Math.min(fragLen - 1, Math.round(fragLen / 2))];
logger["b" /* logger */].log('live playlist, switching playlist, unknown, load middle frag : ' + frag.sn);
}
}
return frag;
};
StreamController.prototype._findFragment = function _findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails) {
var config = this.hls.config;
var frag = void 0;
var foundFrag = void 0;
var maxFragLookUpTolerance = config.maxFragLookUpTolerance;
var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined;
var fragmentWithinToleranceTest = function fragmentWithinToleranceTest(candidate) {
// offset should be within fragment boundary - config.maxFragLookUpTolerance
// this is to cope with situations like
// bufferEnd = 9.991
// frag[Ø] : [0,10]
// frag[1] : [10,20]
// bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
// frag start frag start+duration
// |-----------------------------|
// <---> <--->
// ...--------><-----------------------------><---------....
// previous frag matching fragment next frag
// return -1 return 0 return 1
//logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
// Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
return 1;
} // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
return -1;
}
return 0;
};
if (bufferEnd < end) {
if (bufferEnd > end - maxFragLookUpTolerance) {
maxFragLookUpTolerance = 0;
}
// Prefer the next fragment if it's within tolerance
if (fragNext && !fragmentWithinToleranceTest(fragNext)) {
foundFrag = fragNext;
} else {
foundFrag = binary_search.search(fragments, fragmentWithinToleranceTest);
}
} else {
// reach end of playlist
foundFrag = fragments[fragLen - 1];
}
if (foundFrag) {
frag = foundFrag;
var curSNIdx = frag.sn - levelDetails.startSN;
var sameLevel = fragPrevious && frag.level === fragPrevious.level;
var prevFrag = fragments[curSNIdx - 1];
var nextFrag = fragments[curSNIdx + 1];
//logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
if (fragPrevious && frag.sn === fragPrevious.sn) {
if (sameLevel && !frag.backtracked) {
if (frag.sn < levelDetails.endSN) {
var deltaPTS = fragPrevious.deltaPTS;
// if there is a significant delta between audio and video, larger than max allowed hole,
// and if previous remuxed fragment did not start with a keyframe. (fragPrevious.dropped)
// let's try to load previous fragment again to get last keyframe
// then we will reload again current fragment (that way we should be able to fill the buffer hole ...)
if (deltaPTS && deltaPTS > config.maxBufferHole && fragPrevious.dropped && curSNIdx) {
frag = prevFrag;
logger["b" /* logger */].warn('SN just loaded, with large PTS gap between audio and video, maybe frag is not starting with a keyframe ? load previous one to try to overcome this');
// decrement previous frag load counter to avoid frag loop loading error when next fragment will get reloaded
fragPrevious.loadCounter--;
} else {
frag = nextFrag;
logger["b" /* logger */].log('SN just loaded, load next one: ' + frag.sn);
}
} else {
frag = null;
}
} else if (frag.backtracked) {
// Only backtrack a max of 1 consecutive fragment to prevent sliding back too far when little or no frags start with keyframes
if (nextFrag && nextFrag.backtracked) {
logger["b" /* logger */].warn('Already backtracked from fragment ' + nextFrag.sn + ', will not backtrack to fragment ' + frag.sn + '. Loading fragment ' + nextFrag.sn);
frag = nextFrag;
} else {
// If a fragment has dropped frames and it's in a same level/sequence, load the previous fragment to try and find the keyframe
// Reset the dropped count now since it won't be reset until we parse the fragment again, which prevents infinite backtracking on the same segment
logger["b" /* logger */].warn('Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe');
frag.dropped = 0;
if (prevFrag) {
if (prevFrag.loadCounter) {
prevFrag.loadCounter--;
}
frag = prevFrag;
frag.backtracked = true;
} else if (curSNIdx) {
// can't backtrack on very first fragment
frag = null;
}
}
}
}
}
return frag;
};
StreamController.prototype._loadFragmentOrKey = function _loadFragmentOrKey(frag, level, levelDetails, pos, bufferEnd) {
var hls = this.hls,
config = hls.config;
//logger.log('loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3));
if (frag.decryptdata && frag.decryptdata.uri != null && frag.decryptdata.key == null) {
logger["b" /* logger */].log('Loading key for ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level);
this.state = State.KEY_LOADING;
hls.trigger(events["a" /* default */].KEY_LOADING, { frag: frag });
} else {
logger["b" /* logger */].log('Loading ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level + ', currentTime:' + pos.toFixed(3) + ',bufferEnd:' + bufferEnd.toFixed(3));
// ensure that we are not reloading the same fragments in loop ...
if (this.fragLoadIdx !== undefined) {
this.fragLoadIdx++;
} else {
this.fragLoadIdx = 0;
}
if (frag.loadCounter) {
frag.loadCounter++;
var maxThreshold = config.fragLoadingLoopThreshold;
// if this frag has already been loaded 3 times, and if it has been reloaded recently
if (frag.loadCounter > maxThreshold && Math.abs(this.fragLoadIdx - frag.loadIdx) < maxThreshold) {
hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_LOOP_LOADING_ERROR, fatal: false, frag: frag });
return;
}
} else {
frag.loadCounter = 1;
}
frag.loadIdx = this.fragLoadIdx;
frag.autoLevel = hls.autoLevelEnabled;
frag.bitrateTest = this.bitrateTest;
this.fragCurrent = frag;
this.startFragRequested = true;
// Don't update nextLoadPosition for fragments which are not buffered
if (!isNaN(frag.sn) && !frag.bitrateTest) {
this.nextLoadPosition = frag.start + frag.duration;
}
hls.trigger(events["a" /* default */].FRAG_LOADING, { frag: frag });
// lazy demuxer init, as this could take some time ... do it during frag loading
if (!this.demuxer) {
this.demuxer = new demux_demuxer(hls, 'main');
}
this.state = State.FRAG_LOADING;
return;
}
};
StreamController.prototype.getBufferedFrag = function getBufferedFrag(position) {
return binary_search.search(this._bufferedFrags, function (frag) {
if (position < frag.startPTS) {
return -1;
} else if (position > frag.endPTS) {
return 1;
}
return 0;
});
};
StreamController.prototype.followingBufferedFrag = function followingBufferedFrag(frag) {
if (frag) {
// try to get range of next fragment (500ms after this range)
return this.getBufferedFrag(frag.endPTS + 0.5);
}
return null;
};
StreamController.prototype._checkFragmentChanged = function _checkFragmentChanged() {
var fragPlayingCurrent,
currentTime,
video = this.media;
if (video && video.readyState && video.seeking === false) {
currentTime = video.currentTime;
/* if video element is in seeked state, currentTime can only increase.
(assuming that playback rate is positive ...)
As sometimes currentTime jumps back to zero after a
media decode error, check this, to avoid seeking back to
wrong position after a media decode error
*/
if (currentTime > video.playbackRate * this.lastCurrentTime) {
this.lastCurrentTime = currentTime;
}
if (buffer_helper.isBuffered(video, currentTime)) {
fragPlayingCurrent = this.getBufferedFrag(currentTime);
} else if (buffer_helper.isBuffered(video, currentTime + 0.1)) {
/* ensure that FRAG_CHANGED event is triggered at startup,
when first video frame is displayed and playback is paused.
add a tolerance of 100ms, in case current position is not buffered,
check if current pos+100ms is buffered and use that buffer range
for FRAG_CHANGED event reporting */
fragPlayingCurrent = this.getBufferedFrag(currentTime + 0.1);
}
if (fragPlayingCurrent) {
var fragPlaying = fragPlayingCurrent;
if (fragPlaying !== this.fragPlaying) {
this.hls.trigger(events["a" /* default */].FRAG_CHANGED, { frag: fragPlaying });
var fragPlayingLevel = fragPlaying.level;
if (!this.fragPlaying || this.fragPlaying.level !== fragPlayingLevel) {
this.hls.trigger(events["a" /* default */].LEVEL_SWITCHED, { level: fragPlayingLevel });
}
this.fragPlaying = fragPlaying;
}
}
}
};
/*
on immediate level switch :
- pause playback if playing
- cancel any pending load request
- and trigger a buffer flush
*/
StreamController.prototype.immediateLevelSwitch = function immediateLevelSwitch() {
logger["b" /* logger */].log('immediateLevelSwitch');
if (!this.immediateSwitch) {
this.immediateSwitch = true;
var media = this.media,
previouslyPaused = void 0;
if (media) {
previouslyPaused = media.paused;
media.pause();
} else {
// don't restart playback after instant level switch in case media not attached
previouslyPaused = true;
}
this.previouslyPaused = previouslyPaused;
}
var fragCurrent = this.fragCurrent;
if (fragCurrent && fragCurrent.loader) {
fragCurrent.loader.abort();
}
this.fragCurrent = null;
// increase fragment load Index to avoid frag loop loading error after buffer flush
if (this.fragLoadIdx !== undefined) {
this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;
}
// flush everything
this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
};
/*
on immediate level switch end, after new fragment has been buffered :
- nudge video decoder by slightly adjusting video currentTime (if currentTime buffered)
- resume the playback if needed
*/
StreamController.prototype.immediateLevelSwitchEnd = function immediateLevelSwitchEnd() {
var media = this.media;
if (media && media.buffered.length) {
this.immediateSwitch = false;
if (buffer_helper.isBuffered(media, media.currentTime)) {
// only nudge if currentTime is buffered
media.currentTime -= 0.0001;
}
if (!this.previouslyPaused) {
media.play();
}
}
};
StreamController.prototype.nextLevelSwitch = function nextLevelSwitch() {
/* try to switch ASAP without breaking video playback :
in order to ensure smooth but quick level switching,
we need to find the next flushable buffer range
we should take into account new segment fetch time
*/
var media = this.media;
// ensure that media is defined and that metadata are available (to retrieve currentTime)
if (media && media.readyState) {
var fetchdelay = void 0,
fragPlayingCurrent = void 0,
nextBufferedFrag = void 0;
if (this.fragLoadIdx !== undefined) {
// increase fragment load Index to avoid frag loop loading error after buffer flush
this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;
}
fragPlayingCurrent = this.getBufferedFrag(media.currentTime);
if (fragPlayingCurrent && fragPlayingCurrent.startPTS > 1) {
// flush buffer preceding current fragment (flush until current fragment start offset)
// minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
this.flushMainBuffer(0, fragPlayingCurrent.startPTS - 1);
}
if (!media.paused) {
// add a safety delay of 1s
var nextLevelId = this.hls.nextLoadLevel,
nextLevel = this.levels[nextLevelId],
fragLastKbps = this.fragLastKbps;
if (fragLastKbps && this.fragCurrent) {
fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1;
} else {
fetchdelay = 0;
}
} else {
fetchdelay = 0;
}
//logger.log('fetchdelay:'+fetchdelay);
// find buffer range that will be reached once new fragment will be fetched
nextBufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
if (nextBufferedFrag) {
// we can flush buffer range following this one without stalling playback
nextBufferedFrag = this.followingBufferedFrag(nextBufferedFrag);
if (nextBufferedFrag) {
// if we are here, we can also cancel any loading/demuxing in progress, as they are useless
var fragCurrent = this.fragCurrent;
if (fragCurrent && fragCurrent.loader) {
fragCurrent.loader.abort();
}
this.fragCurrent = null;
// start flush position is the start PTS of next buffered frag.
// we use frag.naxStartPTS which is max(audio startPTS, video startPTS).
// in case there is a small PTS Delta between audio and video, using maxStartPTS avoids flushing last samples from current fragment
this.flushMainBuffer(nextBufferedFrag.maxStartPTS, Number.POSITIVE_INFINITY);
}
}
}
};
StreamController.prototype.flushMainBuffer = function flushMainBuffer(startOffset, endOffset) {
this.state = State.BUFFER_FLUSHING;
var flushScope = { startOffset: startOffset, endOffset: endOffset };
// if alternate audio tracks are used, only flush video, otherwise flush everything
if (this.altAudio) {
flushScope.type = 'video';
}
this.hls.trigger(events["a" /* default */].BUFFER_FLUSHING, flushScope);
};
StreamController.prototype.onMediaAttached = function onMediaAttached(data) {
var media = this.media = this.mediaBuffer = data.media;
this.onvseeking = this.onMediaSeeking.bind(this);
this.onvseeked = this.onMediaSeeked.bind(this);
this.onvended = this.onMediaEnded.bind(this);
media.addEventListener('seeking', this.onvseeking);
media.addEventListener('seeked', this.onvseeked);
media.addEventListener('ended', this.onvended);
var config = this.config;
if (this.levels && config.autoStartLoad) {
this.hls.startLoad(config.startPosition);
}
};
StreamController.prototype.onMediaDetaching = function onMediaDetaching() {
var media = this.media;
if (media && media.ended) {
logger["b" /* logger */].log('MSE detaching and video ended, reset startPosition');
this.startPosition = this.lastCurrentTime = 0;
}
// reset fragment loading counter on MSE detaching to avoid reporting FRAG_LOOP_LOADING_ERROR after error recovery
var levels = this.levels;
if (levels) {
// reset fragment load counter
levels.forEach(function (level) {
if (level.details) {
level.details.fragments.forEach(function (fragment) {
fragment.loadCounter = undefined;
fragment.backtracked = undefined;
});
}
});
}
// remove video listeners
if (media) {
media.removeEventListener('seeking', this.onvseeking);
media.removeEventListener('seeked', this.onvseeked);
media.removeEventListener('ended', this.onvended);
this.onvseeking = this.onvseeked = this.onvended = null;
}
this.media = this.mediaBuffer = null;
this.loadedmetadata = false;
this.stopLoad();
};
StreamController.prototype.onMediaSeeking = function onMediaSeeking() {
var media = this.media,
currentTime = media ? media.currentTime : undefined,
config = this.config;
if (!isNaN(currentTime)) {
logger["b" /* logger */].log('media seeking to ' + currentTime.toFixed(3));
}
var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;
var bufferInfo = buffer_helper.bufferInfo(mediaBuffer, currentTime, this.config.maxBufferHole);
if (this.state === State.FRAG_LOADING) {
var fragCurrent = this.fragCurrent;
// check if we are seeking to a unbuffered area AND if frag loading is in progress
if (bufferInfo.len === 0 && fragCurrent) {
var tolerance = config.maxFragLookUpTolerance,
fragStartOffset = fragCurrent.start - tolerance,
fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
// check if we seek position will be out of currently loaded frag range : if out cancel frag load, if in, don't do anything
if (currentTime < fragStartOffset || currentTime > fragEndOffset) {
if (fragCurrent.loader) {
logger["b" /* logger */].log('seeking outside of buffer while fragment load in progress, cancel fragment load');
fragCurrent.loader.abort();
}
this.fragCurrent = null;
this.fragPrevious = null;
// switch to IDLE state to load new fragment
this.state = State.IDLE;
} else {
logger["b" /* logger */].log('seeking outside of buffer but within currently loaded fragment range');
}
}
} else if (this.state === State.ENDED) {
// if seeking to unbuffered area, clean up fragPrevious
if (bufferInfo.len === 0) {
this.fragPrevious = 0;
}
// switch to IDLE state to check for potential new fragment
this.state = State.IDLE;
}
if (media) {
this.lastCurrentTime = currentTime;
}
// avoid reporting fragment loop loading error in case user is seeking several times on same position
if (this.state !== State.FRAG_LOADING && this.fragLoadIdx !== undefined) {
this.fragLoadIdx += 2 * config.fragLoadingLoopThreshold;
}
// in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
if (!this.loadedmetadata) {
this.nextLoadPosition = this.startPosition = currentTime;
}
// tick to speed up processing
this.tick();
};
StreamController.prototype.onMediaSeeked = function onMediaSeeked() {
var media = this.media,
currentTime = media ? media.currentTime : undefined;
if (!isNaN(currentTime)) {
logger["b" /* logger */].log('media seeked to ' + currentTime.toFixed(3));
}
// tick to speed up FRAGMENT_PLAYING triggering
this.tick();
};
StreamController.prototype.onMediaEnded = function onMediaEnded() {
logger["b" /* logger */].log('media ended');
// reset startPosition and lastCurrentTime to restart playback @ stream beginning
this.startPosition = this.lastCurrentTime = 0;
};
StreamController.prototype.onManifestLoading = function onManifestLoading() {
// reset buffer on manifest loading
logger["b" /* logger */].log('trigger BUFFER_RESET');
this.hls.trigger(events["a" /* default */].BUFFER_RESET);
this._bufferedFrags = [];
this.stalled = false;
this.startPosition = this.lastCurrentTime = 0;
};
StreamController.prototype.onManifestParsed = function onManifestParsed(data) {
var aac = false,
heaac = false,
codec;
data.levels.forEach(function (level) {
// detect if we have different kind of audio codecs used amongst playlists
codec = level.audioCodec;
if (codec) {
if (codec.indexOf('mp4a.40.2') !== -1) {
aac = true;
}
if (codec.indexOf('mp4a.40.5') !== -1) {
heaac = true;
}
}
});
this.audioCodecSwitch = aac && heaac;
if (this.audioCodecSwitch) {
logger["b" /* logger */].log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
}
this.levels = data.levels;
this.startFragRequested = false;
var config = this.config;
if (config.autoStartLoad || this.forceStartLoad) {
this.hls.startLoad(config.startPosition);
}
};
StreamController.prototype.onLevelLoaded = function onLevelLoaded(data) {
var newDetails = data.details;
var newLevelId = data.level;
var lastLevel = this.levels[this.levelLastLoaded];
var curLevel = this.levels[newLevelId];
var duration = newDetails.totalduration;
var sliding = 0;
logger["b" /* logger */].log('level ' + newLevelId + ' loaded [' + newDetails.startSN + ',' + newDetails.endSN + '],duration:' + duration);
if (newDetails.live) {
var curDetails = curLevel.details;
if (curDetails && newDetails.fragments.length > 0) {
// we already have details for that level, merge them
mergeDetails(curDetails, newDetails);
sliding = newDetails.fragments[0].start;
this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);
if (newDetails.PTSKnown && !isNaN(sliding)) {
logger["b" /* logger */].log('live playlist sliding:' + sliding.toFixed(3));
} else {
logger["b" /* logger */].log('live playlist - outdated PTS, unknown sliding');
alignDiscontinuities(this.fragPrevious, lastLevel, newDetails);
}
} else {
logger["b" /* logger */].log('live playlist - first load, unknown sliding');
newDetails.PTSKnown = false;
alignDiscontinuities(this.fragPrevious, lastLevel, newDetails);
}
} else {
newDetails.PTSKnown = false;
}
// override level info
curLevel.details = newDetails;
this.levelLastLoaded = newLevelId;
this.hls.trigger(events["a" /* default */].LEVEL_UPDATED, { details: newDetails, level: newLevelId });
if (this.startFragRequested === false) {
// compute start position if set to -1. use it straight away if value is defined
if (this.startPosition === -1 || this.lastCurrentTime === -1) {
// first, check if start time offset has been set in playlist, if yes, use this value
var startTimeOffset = newDetails.startTimeOffset;
if (!isNaN(startTimeOffset)) {
if (startTimeOffset < 0) {
logger["b" /* logger */].log('negative start time offset ' + startTimeOffset + ', count from end of last fragment');
startTimeOffset = sliding + duration + startTimeOffset;
}
logger["b" /* logger */].log('start time offset found in playlist, adjust startPosition to ' + startTimeOffset);
this.startPosition = startTimeOffset;
} else {
// if live playlist, set start position to be fragment N-this.config.liveSyncDurationCount (usually 3)
if (newDetails.live) {
this.startPosition = this.computeLivePosition(sliding, newDetails);
logger["b" /* logger */].log('configure startPosition to ' + this.startPosition);
} else {
this.startPosition = 0;
}
}
this.lastCurrentTime = this.startPosition;
}
this.nextLoadPosition = this.startPosition;
}
// only switch batck to IDLE state if we were waiting for level to start downloading a new fragment
if (this.state === State.WAITING_LEVEL) {
this.state = State.IDLE;
}
//trigger handler right now
this.tick();
};
StreamController.prototype.onKeyLoaded = function onKeyLoaded() {
if (this.state === State.KEY_LOADING) {
this.state = State.IDLE;
this.tick();
}
};
StreamController.prototype.onFragLoaded = function onFragLoaded(data) {
var fragCurrent = this.fragCurrent,
fragLoaded = data.frag;
if (this.state === State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'main' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) {
var stats = data.stats,
currentLevel = this.levels[fragCurrent.level],
details = currentLevel.details;
logger["b" /* logger */].log('Loaded ' + fragCurrent.sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + fragCurrent.level);
// reset frag bitrate test in any case after frag loaded event
this.bitrateTest = false;
this.stats = stats;
// if this frag was loaded to perform a bitrate test AND if hls.nextLoadLevel is greater than 0
// then this means that we should be able to load a fragment at a higher quality level
if (fragLoaded.bitrateTest === true && this.hls.nextLoadLevel) {
// switch back to IDLE state ... we just loaded a fragment to determine adequate start bitrate and initialize autoswitch algo
this.state = State.IDLE;
this.startFragRequested = false;
stats.tparsed = stats.tbuffered = performance.now();
this.hls.trigger(events["a" /* default */].FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });
this.tick();
} else if (fragLoaded.sn === 'initSegment') {
this.state = State.IDLE;
stats.tparsed = stats.tbuffered = performance.now();
details.initSegment.data = data.payload;
this.hls.trigger(events["a" /* default */].FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });
this.tick();
} else {
this.state = State.PARSING;
// transmux the MPEG-TS data to ISO-BMFF segments
var duration = details.totalduration,
level = fragCurrent.level,
sn = fragCurrent.sn,
audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
if (this.audioCodecSwap) {
logger["b" /* logger */].log('swapping playlist audio codec');
if (audioCodec === undefined) {
audioCodec = this.lastAudioCodec;
}
if (audioCodec) {
if (audioCodec.indexOf('mp4a.40.5') !== -1) {
audioCodec = 'mp4a.40.2';
} else {
audioCodec = 'mp4a.40.5';
}
}
}
this.pendingBuffering = true;
this.appended = false;
logger["b" /* logger */].log('Parsing ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + level + ', cc ' + fragCurrent.cc);
var demuxer = this.demuxer;
if (!demuxer) {
demuxer = this.demuxer = new demux_demuxer(this.hls, 'main');
}
// time Offset is accurate if level PTS is known, or if playlist is not sliding (not live) and if media is not seeking (this is to overcome potential timestamp drifts between playlists and fragments)
var media = this.media;
var mediaSeeking = media && media.seeking;
var accurateTimeOffset = !mediaSeeking && (details.PTSKnown || !details.live);
var initSegmentData = details.initSegment ? details.initSegment.data : [];
demuxer.push(data.payload, initSegmentData, audioCodec, currentLevel.videoCodec, fragCurrent, duration, accurateTimeOffset, undefined);
}
}
this.fragLoadError = 0;
};
StreamController.prototype.onFragParsingInitSegment = function onFragParsingInitSegment(data) {
var fragCurrent = this.fragCurrent;
var fragNew = data.frag;
if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
var tracks = data.tracks,
trackName,
track;
// if audio track is expected to come from audio stream controller, discard any coming from main
if (tracks.audio && this.altAudio) {
delete tracks.audio;
}
// include levelCodec in audio and video tracks
track = tracks.audio;
if (track) {
var audioCodec = this.levels[this.level].audioCodec,
ua = navigator.userAgent.toLowerCase();
if (audioCodec && this.audioCodecSwap) {
logger["b" /* logger */].log('swapping playlist audio codec');
if (audioCodec.indexOf('mp4a.40.5') !== -1) {
audioCodec = 'mp4a.40.2';
} else {
audioCodec = 'mp4a.40.5';
}
}
// in case AAC and HE-AAC audio codecs are signalled in manifest
// force HE-AAC , as it seems that most browsers prefers that way,
// except for mono streams OR on FF
// these conditions might need to be reviewed ...
if (this.audioCodecSwitch) {
// don't force HE-AAC if mono stream
if (track.metadata.channelCount !== 1 &&
// don't force HE-AAC if firefox
ua.indexOf('firefox') === -1) {
audioCodec = 'mp4a.40.5';
}
}
// HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
if (ua.indexOf('android') !== -1 && track.container !== 'audio/mpeg') {
// Exclude mpeg audio
audioCodec = 'mp4a.40.2';
logger["b" /* logger */].log('Android: force audio codec to ' + audioCodec);
}
track.levelCodec = audioCodec;
track.id = data.id;
}
track = tracks.video;
if (track) {
track.levelCodec = this.levels[this.level].videoCodec;
track.id = data.id;
}
this.hls.trigger(events["a" /* default */].BUFFER_CODECS, tracks);
// loop through tracks that are going to be provided to bufferController
for (trackName in tracks) {
track = tracks[trackName];
logger["b" /* logger */].log('main track:' + trackName + ',container:' + track.container + ',codecs[level/parsed]=[' + track.levelCodec + '/' + track.codec + ']');
var initSegment = track.initSegment;
if (initSegment) {
this.appended = true;
// arm pending Buffering flag before appending a segment
this.pendingBuffering = true;
this.hls.trigger(events["a" /* default */].BUFFER_APPENDING, { type: trackName, data: initSegment, parent: 'main', content: 'initSegment' });
}
}
//trigger handler right now
this.tick();
}
};
StreamController.prototype.onFragParsingData = function onFragParsingData(data) {
var _this2 = this;
var fragCurrent = this.fragCurrent;
var fragNew = data.frag;
if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && !(data.type === 'audio' && this.altAudio) && // filter out main audio if audio track is loaded through audio stream controller
this.state === State.PARSING) {
var level = this.levels[this.level],
frag = fragCurrent;
if (isNaN(data.endPTS)) {
data.endPTS = data.startPTS + fragCurrent.duration;
data.endDTS = data.startDTS + fragCurrent.duration;
}
logger["b" /* logger */].log('Parsed ' + data.type + ',PTS:[' + data.startPTS.toFixed(3) + ',' + data.endPTS.toFixed(3) + '],DTS:[' + data.startDTS.toFixed(3) + '/' + data.endDTS.toFixed(3) + '],nb:' + data.nb + ',dropped:' + (data.dropped || 0));
// Detect gaps in a fragment and try to fix it by finding a keyframe in the previous fragment (see _findFragments)
if (data.type === 'video') {
frag.dropped = data.dropped;
if (frag.dropped) {
if (!frag.backtracked) {
var levelDetails = level.details;
if (levelDetails && frag.sn === levelDetails.startSN) {
logger["b" /* logger */].warn('missing video frame(s) on first frag, appending with gap');
} else {
logger["b" /* logger */].warn('missing video frame(s), backtracking fragment');
// Return back to the IDLE state without appending to buffer
// Causes findFragments to backtrack a segment and find the keyframe
// Audio fragments arriving before video sets the nextLoadPosition, causing _findFragments to skip the backtracked fragment
frag.backtracked = true;
this.nextLoadPosition = data.startPTS;
this.state = State.IDLE;
this.fragPrevious = frag;
this.tick();
return;
}
} else {
logger["b" /* logger */].warn('Already backtracked on this fragment, appending with the gap');
}
} else {
// Only reset the backtracked flag if we've loaded the frag without any dropped frames
frag.backtracked = false;
}
}
var drift = updateFragPTSDTS(level.details, frag, data.startPTS, data.endPTS, data.startDTS, data.endDTS),
hls = this.hls;
hls.trigger(events["a" /* default */].LEVEL_PTS_UPDATED, { details: level.details, level: this.level, drift: drift, type: data.type, start: data.startPTS, end: data.endPTS });
// has remuxer dropped video frames located before first keyframe ?
[data.data1, data.data2].forEach(function (buffer) {
// only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)
// in that case it is useless to append following segments
if (buffer && buffer.length && _this2.state === State.PARSING) {
_this2.appended = true;
// arm pending Buffering flag before appending a segment
_this2.pendingBuffering = true;
hls.trigger(events["a" /* default */].BUFFER_APPENDING, { type: data.type, data: buffer, parent: 'main', content: 'data' });
}
});
//trigger handler right now
this.tick();
}
};
StreamController.prototype.onFragParsed = function onFragParsed(data) {
var fragCurrent = this.fragCurrent;
var fragNew = data.frag;
if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
this.stats.tparsed = performance.now();
this.state = State.PARSED;
this._checkAppendedParsed();
}
};
StreamController.prototype.onAudioTrackSwitching = function onAudioTrackSwitching(data) {
// if any URL found on new audio track, it is an alternate audio track
var altAudio = !!data.url,
trackId = data.id;
// if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
// don't do anything if we switch to alt audio: audio stream controller is handling it.
// we will just have to change buffer scheduling on audioTrackSwitched
if (!altAudio) {
if (this.mediaBuffer !== this.media) {
logger["b" /* logger */].log('switching on main audio, use media.buffered to schedule main fragment loading');
this.mediaBuffer = this.media;
var fragCurrent = this.fragCurrent;
// we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
if (fragCurrent.loader) {
logger["b" /* logger */].log('switching to main audio track, cancel main fragment load');
fragCurrent.loader.abort();
}
this.fragCurrent = null;
this.fragPrevious = null;
// destroy demuxer to force init segment generation (following audio switch)
if (this.demuxer) {
this.demuxer.destroy();
this.demuxer = null;
}
// switch to IDLE state to load new fragment
this.state = State.IDLE;
}
var hls = this.hls;
// switching to main audio, flush all audio and trigger track switched
hls.trigger(events["a" /* default */].BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });
hls.trigger(events["a" /* default */].AUDIO_TRACK_SWITCHED, { id: trackId });
this.altAudio = false;
}
};
StreamController.prototype.onAudioTrackSwitched = function onAudioTrackSwitched(data) {
var trackId = data.id,
altAudio = !!this.hls.audioTracks[trackId].url;
if (altAudio) {
var videoBuffer = this.videoBuffer;
// if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
if (videoBuffer && this.mediaBuffer !== videoBuffer) {
logger["b" /* logger */].log('switching on alternate audio, use video.buffered to schedule main fragment loading');
this.mediaBuffer = videoBuffer;
}
}
this.altAudio = altAudio;
this.tick();
};
StreamController.prototype.onBufferCreated = function onBufferCreated(data) {
var tracks = data.tracks,
mediaTrack = void 0,
name = void 0,
alternate = false;
for (var type in tracks) {
var track = tracks[type];
if (track.id === 'main') {
name = type;
mediaTrack = track;
// keep video source buffer reference
if (type === 'video') {
this.videoBuffer = tracks[type].buffer;
}
} else {
alternate = true;
}
}
if (alternate && mediaTrack) {
logger["b" /* logger */].log('alternate track found, use ' + name + '.buffered to schedule main fragment loading');
this.mediaBuffer = mediaTrack.buffer;
} else {
this.mediaBuffer = this.media;
}
};
StreamController.prototype.onBufferAppended = function onBufferAppended(data) {
if (data.parent === 'main') {
var state = this.state;
if (state === State.PARSING || state === State.PARSED) {
// check if all buffers have been appended
this.pendingBuffering = data.pending > 0;
this._checkAppendedParsed();
}
}
};
StreamController.prototype._checkAppendedParsed = function _checkAppendedParsed() {
//trigger handler right now
if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {
var frag = this.fragCurrent;
if (frag) {
var media = this.mediaBuffer ? this.mediaBuffer : this.media;
logger["b" /* logger */].log('main buffered : ' + timeRanges.toString(media.buffered));
// filter fragments potentially evicted from buffer. this is to avoid memleak on live streams
var bufferedFrags = this._bufferedFrags.filter(function (frag) {
return buffer_helper.isBuffered(media, (frag.startPTS + frag.endPTS) / 2);
});
// push new range
bufferedFrags.push(frag);
// sort frags, as we use BinarySearch for lookup in getBufferedFrag ...
this._bufferedFrags = bufferedFrags.sort(function (a, b) {
return a.startPTS - b.startPTS;
});
this.fragPrevious = frag;
var stats = this.stats;
stats.tbuffered = performance.now();
// we should get rid of this.fragLastKbps
this.fragLastKbps = Math.round(8 * stats.total / (stats.tbuffered - stats.tfirst));
this.hls.trigger(events["a" /* default */].FRAG_BUFFERED, { stats: stats, frag: frag, id: 'main' });
this.state = State.IDLE;
}
this.tick();
}
};
StreamController.prototype.onError = function onError(data) {
var frag = data.frag || this.fragCurrent;
// don't handle frag error not related to main fragment
if (frag && frag.type !== 'main') {
return;
}
// 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
var mediaBuffered = !!this.media && buffer_helper.isBuffered(this.media, this.media.currentTime) && buffer_helper.isBuffered(this.media, this.media.currentTime + 0.5);
switch (data.details) {
case errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR:
case errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT:
case errors["a" /* ErrorDetails */].KEY_LOAD_ERROR:
case errors["a" /* ErrorDetails */].KEY_LOAD_TIMEOUT:
if (!data.fatal) {
// keep retrying until the limit will be reached
if (this.fragLoadError + 1 <= this.config.fragLoadingMaxRetry) {
// exponential backoff capped to config.fragLoadingMaxRetryTimeout
var delay = Math.min(Math.pow(2, this.fragLoadError) * this.config.fragLoadingRetryDelay, this.config.fragLoadingMaxRetryTimeout);
// reset load counter to avoid frag loop loading error
frag.loadCounter = 0;
logger["b" /* logger */].warn('mediaController: frag loading failed, retry in ' + delay + ' ms');
this.retryDate = performance.now() + delay;
// retry loading state
// if loadedmetadata is not set, it means that we are emergency switch down on first frag
// in that case, reset startFragRequested flag
if (!this.loadedmetadata) {
this.startFragRequested = false;
this.nextLoadPosition = this.startPosition;
}
this.fragLoadError++;
this.state = State.FRAG_LOADING_WAITING_RETRY;
} else {
logger["b" /* logger */].error('mediaController: ' + data.details + ' reaches max retry, redispatch as fatal ...');
// switch error to fatal
data.fatal = true;
this.state = State.ERROR;
}
}
break;
case errors["a" /* ErrorDetails */].FRAG_LOOP_LOADING_ERROR:
if (!data.fatal) {
// if buffer is not empty
if (mediaBuffered) {
// try to reduce max buffer length : rationale is that we could get
// frag loop loading error because of buffer eviction
this._reduceMaxBufferLength(frag.duration);
this.state = State.IDLE;
} else {
// buffer empty. report as fatal if in manual mode or if lowest level.
// level controller takes care of emergency switch down logic
if (!frag.autoLevel || frag.level === 0) {
// switch error to fatal
data.fatal = true;
this.state = State.ERROR;
}
}
}
break;
case errors["a" /* ErrorDetails */].LEVEL_LOAD_ERROR:
case errors["a" /* ErrorDetails */].LEVEL_LOAD_TIMEOUT:
if (this.state !== State.ERROR) {
if (data.fatal) {
// if fatal error, stop processing
this.state = State.ERROR;
logger["b" /* logger */].warn('streamController: ' + data.details + ',switch to ' + this.state + ' state ...');
} else {
// in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE
if (!data.levelRetry && this.state === State.WAITING_LEVEL) {
this.state = State.IDLE;
}
}
}
break;
case errors["a" /* ErrorDetails */].BUFFER_FULL_ERROR:
// if in appending state
if (data.parent === 'main' && (this.state === State.PARSING || this.state === State.PARSED)) {
// reduce max buf len if current position is buffered
if (mediaBuffered) {
this._reduceMaxBufferLength(this.config.maxBufferLength);
this.state = State.IDLE;
} else {
// current position is not buffered, but browser is still complaining about buffer full error
// this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
// in that case flush the whole buffer to recover
logger["b" /* logger */].warn('buffer full error also media.currentTime is not buffered, flush everything');
this.fragCurrent = null;
// flush everything
this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
}
}
break;
default:
break;
}
};
StreamController.prototype._reduceMaxBufferLength = function _reduceMaxBufferLength(minLength) {
var config = this.config;
if (config.maxMaxBufferLength >= minLength) {
// reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
config.maxMaxBufferLength /= 2;
logger["b" /* logger */].warn('main:reduce max buffer length to ' + config.maxMaxBufferLength + 's');
if (this.fragLoadIdx !== undefined) {
// increase fragment load Index to avoid frag loop loading error after buffer flush
this.fragLoadIdx += 2 * config.fragLoadingLoopThreshold;
}
}
};
StreamController.prototype._checkBuffer = function _checkBuffer() {
var media = this.media,
config = this.config;
// if ready state different from HAVE_NOTHING (numeric value 0), we are allowed to seek
if (media && media.readyState) {
var currentTime = media.currentTime,
mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media,
buffered = mediaBuffer.buffered;
// adjust currentTime to start position on loaded metadata
if (!this.loadedmetadata && buffered.length) {
this.loadedmetadata = true;
// only adjust currentTime if different from startPosition or if startPosition not buffered
// at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
var startPosition = media.seeking ? currentTime : this.startPosition,
startPositionBuffered = buffer_helper.isBuffered(mediaBuffer, startPosition),
firstbufferedPosition = buffered.start(0),
startNotBufferedButClose = !startPositionBuffered && Math.abs(startPosition - firstbufferedPosition) < config.maxSeekHole;
// if currentTime not matching with expected startPosition or startPosition not buffered but close to first buffered
if (currentTime !== startPosition || startNotBufferedButClose) {
logger["b" /* logger */].log('target start position:' + startPosition);
// if startPosition not buffered, let's seek to buffered.start(0)
if (startNotBufferedButClose) {
startPosition = firstbufferedPosition;
logger["b" /* logger */].log('target start position not buffered, seek to buffered.start(0) ' + startPosition);
}
logger["b" /* logger */].log('adjust currentTime from ' + currentTime + ' to ' + startPosition);
media.currentTime = startPosition;
}
} else if (this.immediateSwitch) {
this.immediateLevelSwitchEnd();
} else {
var bufferInfo = buffer_helper.bufferInfo(media, currentTime, 0),
expectedPlaying = !(media.paused || // not playing when media is paused
media.ended || // not playing when media is ended
media.buffered.length === 0),
// not playing if nothing buffered
jumpThreshold = 0.5,
// tolerance needed as some browsers stalls playback before reaching buffered range end
playheadMoving = currentTime !== this.lastCurrentTime;
if (playheadMoving) {
// played moving, but was previously stalled => now not stuck anymore
if (this.stallReported) {
logger["b" /* logger */].warn('playback not stuck anymore @' + currentTime + ', after ' + Math.round(performance.now() - this.stalled) + 'ms');
this.stallReported = false;
}
this.stalled = undefined;
this.nudgeRetry = 0;
} else {
// playhead not moving
if (expectedPlaying) {
// playhead not moving BUT media expected to play
var tnow = performance.now();
var hls = this.hls;
if (!this.stalled) {
// stall just detected, store current time
this.stalled = tnow;
this.stallReported = false;
} else {
// playback already stalled, check stalling duration
// if stalling for more than a given threshold, let's try to recover
var stalledDuration = tnow - this.stalled;
var bufferLen = bufferInfo.len;
var nudgeRetry = this.nudgeRetry || 0;
// have we reached stall deadline ?
if (bufferLen <= jumpThreshold && stalledDuration > config.lowBufferWatchdogPeriod * 1000) {
// report stalled error once
if (!this.stallReported) {
this.stallReported = true;
logger["b" /* logger */].warn('playback stalling in low buffer @' + currentTime);
hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_STALLED_ERROR, fatal: false, buffer: bufferLen });
}
// if buffer len is below threshold, try to jump to start of next buffer range if close
// no buffer available @ currentTime, check if next buffer is close (within a config.maxSeekHole second range)
var nextBufferStart = bufferInfo.nextStart,
delta = nextBufferStart - currentTime;
if (nextBufferStart && delta < config.maxSeekHole && delta > 0) {
this.nudgeRetry = ++nudgeRetry;
var nudgeOffset = nudgeRetry * config.nudgeOffset;
// next buffer is close ! adjust currentTime to nextBufferStart
// this will ensure effective video decoding
logger["b" /* logger */].log('adjust currentTime from ' + media.currentTime + ' to next buffered @ ' + nextBufferStart + ' + nudge ' + nudgeOffset);
media.currentTime = nextBufferStart + nudgeOffset;
// reset stalled so to rearm watchdog timer
this.stalled = undefined;
hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_SEEK_OVER_HOLE, fatal: false, hole: nextBufferStart + nudgeOffset - currentTime });
}
} else if (bufferLen > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) {
// report stalled error once
if (!this.stallReported) {
this.stallReported = true;
logger["b" /* logger */].warn('playback stalling in high buffer @' + currentTime);
hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_STALLED_ERROR, fatal: false, buffer: bufferLen });
}
// reset stalled so to rearm watchdog timer
this.stalled = undefined;
this.nudgeRetry = ++nudgeRetry;
if (nudgeRetry < config.nudgeMaxRetry) {
var _currentTime = media.currentTime;
var targetTime = _currentTime + nudgeRetry * config.nudgeOffset;
logger["b" /* logger */].log('adjust currentTime from ' + _currentTime + ' to ' + targetTime);
// playback stalled in buffered area ... let's nudge currentTime to try to overcome this
media.currentTime = targetTime;
hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_NUDGE_ON_STALL, fatal: false });
} else {
logger["b" /* logger */].error('still stuck in high buffer @' + currentTime + ' after ' + config.nudgeMaxRetry + ', raise fatal error');
hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_STALLED_ERROR, fatal: true });
}
}
}
}
}
}
}
};
StreamController.prototype.onFragLoadEmergencyAborted = function onFragLoadEmergencyAborted() {
this.state = State.IDLE;
// if loadedmetadata is not set, it means that we are emergency switch down on first frag
// in that case, reset startFragRequested flag
if (!this.loadedmetadata) {
this.startFragRequested = false;
this.nextLoadPosition = this.startPosition;
}
this.tick();
};
StreamController.prototype.onBufferFlushed = function onBufferFlushed() {
/* after successful buffer flushing, filter flushed fragments from bufferedFrags
use mediaBuffered instead of media (so that we will check against video.buffered ranges in case of alt audio track)
*/
var media = this.mediaBuffer ? this.mediaBuffer : this.media;
this._bufferedFrags = this._bufferedFrags.filter(function (frag) {
return buffer_helper.isBuffered(media, (frag.startPTS + frag.endPTS) / 2);
});
if (this.fragLoadIdx !== undefined) {
// increase fragment load Index to avoid frag loop loading error after buffer flush
this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;
}
// move to IDLE once flush complete. this should trigger new fragment loading
this.state = State.IDLE;
// reset reference to frag
this.fragPrevious = null;
};
StreamController.prototype.swapAudioCodec = function swapAudioCodec() {
this.audioCodecSwap = !this.audioCodecSwap;
};
StreamController.prototype.computeLivePosition = function computeLivePosition(sliding, levelDetails) {
var targetLatency = this.config.liveSyncDuration !== undefined ? this.config.liveSyncDuration : this.config.liveSyncDurationCount * levelDetails.targetduration;
return sliding + Math.max(0, levelDetails.totalduration - targetLatency);
};
stream_controller__createClass(StreamController, [{
key: 'state',
set: function set(nextState) {
if (this.state !== nextState) {
var previousState = this.state;
this._state = nextState;
logger["b" /* logger */].log('main stream:' + previousState + '->' + nextState);
this.hls.trigger(events["a" /* default */].STREAM_STATE_TRANSITION, { previousState: previousState, nextState: nextState });
}
},
get: function get() {
return this._state;
}
}, {
key: 'currentLevel',
get: function get() {
var media = this.media;
if (media) {
var frag = this.getBufferedFrag(media.currentTime);
if (frag) {
return frag.level;
}
}
return -1;
}
}, {
key: 'nextBufferedFrag',
get: function get() {
var media = this.media;
if (media) {
// first get end range of current fragment
return this.followingBufferedFrag(this.getBufferedFrag(media.currentTime));
} else {
return null;
}
}
}, {
key: 'nextLevel',
get: function get() {
var frag = this.nextBufferedFrag;
if (frag) {
return frag.level;
} else {
return -1;
}
}
}, {
key: 'liveSyncPosition',
get: function get() {
return this._liveSyncPosition;
},
set: function set(value) {
this._liveSyncPosition = value;
}
}]);
return StreamController;
}(event_handler);
/* harmony default export */ var stream_controller = (stream_controller_StreamController);
// CONCATENATED MODULE: ./src/controller/level-controller.js
var level_controller__createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function level_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function level_controller__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 level_controller__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; }
/*
* Level Controller
*/
var level_controller_LevelController = function (_EventHandler) {
level_controller__inherits(LevelController, _EventHandler);
function LevelController(hls) {
level_controller__classCallCheck(this, LevelController);
var _this = level_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MANIFEST_LOADED, events["a" /* default */].LEVEL_LOADED, events["a" /* default */].FRAG_LOADED, events["a" /* default */].ERROR));
_this._manualLevel = -1;
_this.timer = null;
return _this;
}
LevelController.prototype.destroy = function destroy() {
this.cleanTimer();
this._manualLevel = -1;
};
LevelController.prototype.cleanTimer = function cleanTimer() {
if (this.timer !== null) {
clearTimeout(this.timer);
this.timer = null;
}
};
LevelController.prototype.startLoad = function startLoad() {
var levels = this._levels;
this.canload = true;
this.levelRetryCount = 0;
// clean up live level details to force reload them, and reset load errors
if (levels) {
levels.forEach(function (level) {
level.loadError = 0;
var levelDetails = level.details;
if (levelDetails && levelDetails.live) {
level.details = undefined;
}
});
}
// speed up live playlist refresh if timer exists
if (this.timer) {
this.tick();
}
};
LevelController.prototype.stopLoad = function stopLoad() {
this.canload = false;
};
LevelController.prototype.onManifestLoaded = function onManifestLoaded(data) {
var levels = [],
bitrateStart = void 0,
levelSet = {},
levelFromSet = null,
videoCodecFound = false,
audioCodecFound = false,
chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());
// regroup redundant levels together
data.levels.forEach(function (level) {
level.loadError = 0;
level.fragmentError = false;
videoCodecFound = videoCodecFound || !!level.videoCodec;
audioCodecFound = audioCodecFound || !!level.audioCodec || !!(level.attrs && level.attrs.AUDIO);
// erase audio codec info if browser does not support mp4a.40.34.
// demuxer will autodetect codec and fallback to mpeg/audio
if (chromeOrFirefox === true && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {
level.audioCodec = undefined;
}
levelFromSet = levelSet[level.bitrate];
if (levelFromSet === undefined) {
level.url = [level.url];
level.urlId = 0;
levelSet[level.bitrate] = level;
levels.push(level);
} else {
levelFromSet.url.push(level.url);
}
});
// remove audio-only level if we also have levels with audio+video codecs signalled
if (videoCodecFound === true && audioCodecFound === true) {
levels = levels.filter(function (_ref) {
var videoCodec = _ref.videoCodec;
return !!videoCodec;
});
}
// only keep levels with supported audio/video codecs
levels = levels.filter(function (_ref2) {
var audioCodec = _ref2.audioCodec,
videoCodec = _ref2.videoCodec;
return (!audioCodec || isCodecSupportedInMp4(audioCodec)) && (!videoCodec || isCodecSupportedInMp4(videoCodec));
});
if (levels.length > 0) {
// start bitrate is the first bitrate of the manifest
bitrateStart = levels[0].bitrate;
// sort level on bitrate
levels.sort(function (a, b) {
return a.bitrate - b.bitrate;
});
this._levels = levels;
// find index of first level in sorted levels
for (var i = 0; i < levels.length; i++) {
if (levels[i].bitrate === bitrateStart) {
this._firstLevel = i;
logger["b" /* logger */].log('manifest loaded,' + levels.length + ' level(s) found, first bitrate:' + bitrateStart);
break;
}
}
this.hls.trigger(events["a" /* default */].MANIFEST_PARSED, {
levels: levels,
firstLevel: this._firstLevel,
stats: data.stats,
audio: audioCodecFound,
video: videoCodecFound,
altAudio: data.audioTracks.length > 0
});
} else {
this.hls.trigger(events["a" /* default */].ERROR, {
type: errors["b" /* ErrorTypes */].MEDIA_ERROR,
details: errors["a" /* ErrorDetails */].MANIFEST_INCOMPATIBLE_CODECS_ERROR,
fatal: true,
url: this.hls.url,
reason: 'no level with compatible codecs found in manifest'
});
}
};
LevelController.prototype.setLevelInternal = function setLevelInternal(newLevel) {
var levels = this._levels;
var hls = this.hls;
// check if level idx is valid
if (newLevel >= 0 && newLevel < levels.length) {
// stopping live reloading timer if any
this.cleanTimer();
if (this._level !== newLevel) {
logger["b" /* logger */].log('switching to level ' + newLevel);
this._level = newLevel;
var levelProperties = levels[newLevel];
levelProperties.level = newLevel;
// LEVEL_SWITCH to be deprecated in next major release
hls.trigger(events["a" /* default */].LEVEL_SWITCH, levelProperties);
hls.trigger(events["a" /* default */].LEVEL_SWITCHING, levelProperties);
}
var level = levels[newLevel],
levelDetails = level.details;
// check if we need to load playlist for this level
if (!levelDetails || levelDetails.live === true) {
// level not retrieved yet, or live playlist we need to (re)load it
var urlId = level.urlId;
hls.trigger(events["a" /* default */].LEVEL_LOADING, { url: level.url[urlId], level: newLevel, id: urlId });
}
} else {
// invalid level id given, trigger error
hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].OTHER_ERROR, details: errors["a" /* ErrorDetails */].LEVEL_SWITCH_ERROR, level: newLevel, fatal: false, reason: 'invalid level idx' });
}
};
LevelController.prototype.onError = function onError(data) {
var _this2 = this;
if (data.fatal === true) {
if (data.type === errors["b" /* ErrorTypes */].NETWORK_ERROR) {
this.cleanTimer();
}
return;
}
var details = data.details,
levelError = false,
fragmentError = false;
var levelIndex = void 0,
level = void 0;
var config = this.hls.config;
// try to recover not fatal errors
switch (details) {
case errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR:
case errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT:
case errors["a" /* ErrorDetails */].FRAG_LOOP_LOADING_ERROR:
case errors["a" /* ErrorDetails */].KEY_LOAD_ERROR:
case errors["a" /* ErrorDetails */].KEY_LOAD_TIMEOUT:
levelIndex = data.frag.level;
fragmentError = true;
break;
case errors["a" /* ErrorDetails */].LEVEL_LOAD_ERROR:
case errors["a" /* ErrorDetails */].LEVEL_LOAD_TIMEOUT:
levelIndex = data.context.level;
levelError = true;
break;
case errors["a" /* ErrorDetails */].REMUX_ALLOC_ERROR:
levelIndex = data.level;
break;
}
/* try to switch to a redundant stream if any available.
* if no redundant stream available, emergency switch down (if in auto mode and current level not 0)
* otherwise, we cannot recover this network error ...
*/
if (levelIndex !== undefined) {
level = this._levels[levelIndex];
level.loadError++;
level.fragmentError = fragmentError;
// Allow fragment retry as long as configuration allows.
// Since fragment retry logic could depend on the levels, we should not enforce retry limits when there is an issue with fragments
// FIXME Find a better abstraction where fragment/level retry management is well decoupled
if (fragmentError === true) {
// if any redundant streams available and if we haven't try them all (level.loadError is reseted on successful frag/level load.
// if level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down
var redundantLevels = level.url.length;
if (redundantLevels > 1 && level.loadError < redundantLevels) {
level.urlId = (level.urlId + 1) % redundantLevels;
level.details = undefined;
logger["b" /* logger */].warn('level controller,' + details + ' for level ' + levelIndex + ': switching to redundant stream id ' + level.urlId);
} else {
// we could try to recover if in auto mode and current level not lowest level (0)
if (this._manualLevel === -1 && levelIndex !== 0) {
logger["b" /* logger */].warn('level controller,' + details + ': switch-down for next fragment');
this.hls.nextAutoLevel = levelIndex - 1;
} else {
logger["b" /* logger */].warn('level controller, ' + details + ': reload a fragment');
// reset this._level so that another call to set level() will trigger again a frag load
this._level = undefined;
}
}
} else if (levelError === true) {
if (this.levelRetryCount + 1 <= config.levelLoadingMaxRetry) {
// exponential backoff capped to max retry timeout
var delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout);
// reset load counter to avoid frag loop loading error
this.timer = setTimeout(function () {
return _this2.tick();
}, delay);
// boolean used to inform stream controller not to switch back to IDLE on non fatal error
data.levelRetry = true;
this.levelRetryCount++;
logger["b" /* logger */].warn('level controller,' + details + ', retry in ' + delay + ' ms, current retry count is ' + this.levelRetryCount);
} else {
logger["b" /* logger */].error('cannot recover ' + details + ' error');
this._level = undefined;
// stopping live reloading timer if any
this.cleanTimer();
// switch error to fatal
data.fatal = true;
}
}
}
};
// reset errors on the successful load of a fragment
LevelController.prototype.onFragLoaded = function onFragLoaded(_ref3) {
var frag = _ref3.frag;
if (frag !== undefined && frag.type === 'main') {
var level = this._levels[frag.level];
if (level !== undefined) {
level.fragmentError = false;
level.loadError = 0;
this.levelRetryCount = 0;
}
}
};
LevelController.prototype.onLevelLoaded = function onLevelLoaded(data) {
var _this3 = this;
var levelId = data.level;
// only process level loaded events matching with expected level
if (levelId === this._level) {
var curLevel = this._levels[levelId];
// reset level load error counter on successful level loaded only if there is no issues with fragments
if (curLevel.fragmentError === false) {
curLevel.loadError = 0;
this.levelRetryCount = 0;
}
var newDetails = data.details;
// if current playlist is a live playlist, arm a timer to reload it
if (newDetails.live) {
var reloadInterval = 1000 * (newDetails.averagetargetduration ? newDetails.averagetargetduration : newDetails.targetduration),
curDetails = curLevel.details;
if (curDetails && newDetails.endSN === curDetails.endSN) {
// follow HLS Spec, If the client reloads a Playlist file and finds that it has not
// changed then it MUST wait for a period of one-half the target
// duration before retrying.
reloadInterval /= 2;
logger["b" /* logger */].log('same live playlist, reload twice faster');
}
// decrement reloadInterval with level loading delay
reloadInterval -= performance.now() - data.stats.trequest;
// in any case, don't reload more than every second
reloadInterval = Math.max(1000, Math.round(reloadInterval));
logger["b" /* logger */].log('live playlist, reload in ' + reloadInterval + ' ms');
this.timer = setTimeout(function () {
return _this3.tick();
}, reloadInterval);
} else {
this.cleanTimer();
}
}
};
LevelController.prototype.tick = function tick() {
var levelId = this._level;
if (levelId !== undefined && this.canload) {
var level = this._levels[levelId];
if (level && level.url) {
var urlId = level.urlId;
this.hls.trigger(events["a" /* default */].LEVEL_LOADING, { url: level.url[urlId], level: levelId, id: urlId });
}
}
};
level_controller__createClass(LevelController, [{
key: 'levels',
get: function get() {
return this._levels;
}
}, {
key: 'level',
get: function get() {
return this._level;
},
set: function set(newLevel) {
var levels = this._levels;
if (levels) {
newLevel = Math.min(newLevel, levels.length - 1);
if (this._level !== newLevel || levels[newLevel].details === undefined) {
this.setLevelInternal(newLevel);
}
}
}
}, {
key: 'manualLevel',
get: function get() {
return this._manualLevel;
},
set: function set(newLevel) {
this._manualLevel = newLevel;
if (this._startLevel === undefined) {
this._startLevel = newLevel;
}
if (newLevel !== -1) {
this.level = newLevel;
}
}
}, {
key: 'firstLevel',
get: function get() {
return this._firstLevel;
},
set: function set(newLevel) {
this._firstLevel = newLevel;
}
}, {
key: 'startLevel',
get: function get() {
// hls.startLevel takes precedence over config.startLevel
// if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)
if (this._startLevel === undefined) {
var configStartLevel = this.hls.config.startLevel;
if (configStartLevel !== undefined) {
return configStartLevel;
} else {
return this._firstLevel;
}
} else {
return this._startLevel;
}
},
set: function set(newLevel) {
this._startLevel = newLevel;
}
}, {
key: 'nextLoadLevel',
get: function get() {
if (this._manualLevel !== -1) {
return this._manualLevel;
} else {
return this.hls.nextAutoLevel;
}
},
set: function set(nextLevel) {
this.level = nextLevel;
if (this._manualLevel === -1) {
this.hls.nextAutoLevel = nextLevel;
}
}
}]);
return LevelController;
}(event_handler);
/* harmony default export */ var level_controller = (level_controller_LevelController);
// EXTERNAL MODULE: ./src/demux/id3.js
var id3 = __webpack_require__(4);
// CONCATENATED MODULE: ./src/controller/id3-track-controller.js
function id3_track_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function id3_track_controller__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 id3_track_controller__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; }
/*
* id3 metadata track controller
*/
var id3_track_controller_ID3TrackController = function (_EventHandler) {
id3_track_controller__inherits(ID3TrackController, _EventHandler);
function ID3TrackController(hls) {
id3_track_controller__classCallCheck(this, ID3TrackController);
var _this = id3_track_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHED, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].FRAG_PARSING_METADATA));
_this.id3Track = undefined;
_this.media = undefined;
return _this;
}
ID3TrackController.prototype.destroy = function destroy() {
event_handler.prototype.destroy.call(this);
};
// Add ID3 metatadata text track.
ID3TrackController.prototype.onMediaAttached = function onMediaAttached(data) {
this.media = data.media;
if (!this.media) {
return;
}
};
ID3TrackController.prototype.onMediaDetaching = function onMediaDetaching() {
this.media = undefined;
};
ID3TrackController.prototype.onFragParsingMetadata = function onFragParsingMetadata(data) {
var fragment = data.frag;
var samples = data.samples;
// create track dynamically
if (!this.id3Track) {
this.id3Track = this.media.addTextTrack('metadata', 'id3');
this.id3Track.mode = 'hidden';
}
// Attempt to recreate Safari functionality by creating
// WebKitDataCue objects when available and store the decoded
// ID3 data in the value property of the cue
var Cue = window.WebKitDataCue || window.VTTCue || window.TextTrackCue;
for (var i = 0; i < samples.length; i++) {
var frames = id3["a" /* default */].getID3Frames(samples[i].data);
if (frames) {
var startTime = samples[i].pts;
var endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.endPTS;
// Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE
if (startTime === endTime) {
endTime += 0.0001;
}
for (var j = 0; j < frames.length; j++) {
var frame = frames[j];
// Safari doesn't put the timestamp frame in the TextTrack
if (!id3["a" /* default */].isTimeStampFrame(frame)) {
var cue = new Cue(startTime, endTime, '');
cue.value = frame;
this.id3Track.addCue(cue);
}
}
}
}
};
return ID3TrackController;
}(event_handler);
/* harmony default export */ var id3_track_controller = (id3_track_controller_ID3TrackController);
// CONCATENATED MODULE: ./src/utils/ewma.js
function ewma__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/*
* compute an Exponential Weighted moving average
* - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
* - heavily inspired from shaka-player
*/
var EWMA = function () {
// About half of the estimated value will be from the last |halfLife| samples by weight.
function EWMA(halfLife) {
ewma__classCallCheck(this, EWMA);
// Larger values of alpha expire historical data more slowly.
this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
this.estimate_ = 0;
this.totalWeight_ = 0;
}
EWMA.prototype.sample = function sample(weight, value) {
var adjAlpha = Math.pow(this.alpha_, weight);
this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
this.totalWeight_ += weight;
};
EWMA.prototype.getTotalWeight = function getTotalWeight() {
return this.totalWeight_;
};
EWMA.prototype.getEstimate = function getEstimate() {
if (this.alpha_) {
var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
return this.estimate_ / zeroFactor;
} else {
return this.estimate_;
}
};
return EWMA;
}();
/* harmony default export */ var ewma = (EWMA);
// CONCATENATED MODULE: ./src/utils/ewma-bandwidth-estimator.js
function ewma_bandwidth_estimator__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/*
* EWMA Bandwidth Estimator
* - heavily inspired from shaka-player
* Tracks bandwidth samples and estimates available bandwidth.
* Based on the minimum of two exponentially-weighted moving averages with
* different half-lives.
*/
var ewma_bandwidth_estimator_EwmaBandWidthEstimator = function () {
function EwmaBandWidthEstimator(hls, slow, fast, defaultEstimate) {
ewma_bandwidth_estimator__classCallCheck(this, EwmaBandWidthEstimator);
this.hls = hls;
this.defaultEstimate_ = defaultEstimate;
this.minWeight_ = 0.001;
this.minDelayMs_ = 50;
this.slow_ = new ewma(slow);
this.fast_ = new ewma(fast);
}
EwmaBandWidthEstimator.prototype.sample = function sample(durationMs, numBytes) {
durationMs = Math.max(durationMs, this.minDelayMs_);
var bandwidth = 8000 * numBytes / durationMs,
//console.log('instant bw:'+ Math.round(bandwidth));
// we weight sample using loading duration....
weight = durationMs / 1000;
this.fast_.sample(weight, bandwidth);
this.slow_.sample(weight, bandwidth);
};
EwmaBandWidthEstimator.prototype.canEstimate = function canEstimate() {
var fast = this.fast_;
return fast && fast.getTotalWeight() >= this.minWeight_;
};
EwmaBandWidthEstimator.prototype.getEstimate = function getEstimate() {
if (this.canEstimate()) {
//console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
//console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
// Take the minimum of these two estimates. This should have the effect of
// adapting down quickly, but up more slowly.
return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
} else {
return this.defaultEstimate_;
}
};
EwmaBandWidthEstimator.prototype.destroy = function destroy() {};
return EwmaBandWidthEstimator;
}();
/* harmony default export */ var ewma_bandwidth_estimator = (ewma_bandwidth_estimator_EwmaBandWidthEstimator);
// CONCATENATED MODULE: ./src/controller/abr-controller.js
var abr_controller__createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function abr_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function abr_controller__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 abr_controller__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; }
/*
* simple ABR Controller
* - compute next level based on last fragment bw heuristics
* - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling
*/
var abr_controller_AbrController = function (_EventHandler) {
abr_controller__inherits(AbrController, _EventHandler);
function AbrController(hls) {
abr_controller__classCallCheck(this, AbrController);
var _this = abr_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].FRAG_LOADING, events["a" /* default */].FRAG_LOADED, events["a" /* default */].FRAG_BUFFERED, events["a" /* default */].ERROR));
_this.lastLoadedFragLevel = 0;
_this._nextAutoLevel = -1;
_this.hls = hls;
_this.timer = null;
_this._bwEstimator = null;
_this.onCheck = _this._abandonRulesCheck.bind(_this);
return _this;
}
AbrController.prototype.destroy = function destroy() {
this.clearTimer();
event_handler.prototype.destroy.call(this);
};
AbrController.prototype.onFragLoading = function onFragLoading(data) {
var frag = data.frag;
if (frag.type === 'main') {
if (!this.timer) {
this.timer = setInterval(this.onCheck, 100);
}
// lazy init of bw Estimator, rationale is that we use different params for Live/VoD
// so we need to wait for stream manifest / playlist type to instantiate it.
if (!this._bwEstimator) {
var hls = this.hls,
level = data.frag.level,
isLive = hls.levels[level].details.live,
config = hls.config,
ewmaFast = void 0,
ewmaSlow = void 0;
if (isLive) {
ewmaFast = config.abrEwmaFastLive;
ewmaSlow = config.abrEwmaSlowLive;
} else {
ewmaFast = config.abrEwmaFastVoD;
ewmaSlow = config.abrEwmaSlowVoD;
}
this._bwEstimator = new ewma_bandwidth_estimator(hls, ewmaSlow, ewmaFast, config.abrEwmaDefaultEstimate);
}
this.fragCurrent = frag;
}
};
AbrController.prototype._abandonRulesCheck = function _abandonRulesCheck() {
/*
monitor fragment retrieval time...
we compute expected time of arrival of the complete fragment.
we compare it to expected time of buffer starvation
*/
var hls = this.hls,
v = hls.media,
frag = this.fragCurrent,
loader = frag.loader,
minAutoLevel = hls.minAutoLevel;
// if loader has been destroyed or loading has been aborted, stop timer and return
if (!loader || loader.stats && loader.stats.aborted) {
logger["b" /* logger */].warn('frag loader destroy or aborted, disarm abandonRules');
this.clearTimer();
return;
}
var stats = loader.stats;
/* only monitor frag retrieval time if
(video not paused OR first fragment being loaded(ready state === HAVE_NOTHING = 0)) AND autoswitching enabled AND not lowest level (=> means that we have several levels) */
if (v && stats && (!v.paused && v.playbackRate !== 0 || !v.readyState) && frag.autoLevel && frag.level) {
var requestDelay = performance.now() - stats.trequest,
playbackRate = Math.abs(v.playbackRate);
// monitor fragment load progress after half of expected fragment duration,to stabilize bitrate
if (requestDelay > 500 * frag.duration / playbackRate) {
var levels = hls.levels,
loadRate = Math.max(1, stats.bw ? stats.bw / 8 : stats.loaded * 1000 / requestDelay),
// byte/s; at least 1 byte/s to avoid division by zero
// compute expected fragment length using frag duration and level bitrate. also ensure that expected len is gte than already loaded size
level = levels[frag.level],
levelBitrate = level.realBitrate ? Math.max(level.realBitrate, level.bitrate) : level.bitrate,
expectedLen = stats.total ? stats.total : Math.max(stats.loaded, Math.round(frag.duration * levelBitrate / 8)),
pos = v.currentTime,
fragLoadedDelay = (expectedLen - stats.loaded) / loadRate,
bufferStarvationDelay = (buffer_helper.bufferInfo(v, pos, hls.config.maxBufferHole).end - pos) / playbackRate;
// consider emergency switch down only if we have less than 2 frag buffered AND
// time to finish loading current fragment is bigger than buffer starvation delay
// ie if we risk buffer starvation if bw does not increase quickly
if (bufferStarvationDelay < 2 * frag.duration / playbackRate && fragLoadedDelay > bufferStarvationDelay) {
var fragLevelNextLoadedDelay = void 0,
nextLoadLevel = void 0;
// lets iterate through lower level and try to find the biggest one that could avoid rebuffering
// we start from current level - 1 and we step down , until we find a matching level
for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
// compute time to load next fragment at lower level
// 0.8 : consider only 80% of current bw to be conservative
// 8 = bits per byte (bps/Bps)
var levelNextBitrate = levels[nextLoadLevel].realBitrate ? Math.max(levels[nextLoadLevel].realBitrate, levels[nextLoadLevel].bitrate) : levels[nextLoadLevel].bitrate;
fragLevelNextLoadedDelay = frag.duration * levelNextBitrate / (8 * 0.8 * loadRate);
if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
// we found a lower level that be rebuffering free with current estimated bw !
break;
}
}
// only emergency switch down if it takes less time to load new fragment at lowest level instead
// of finishing loading current one ...
if (fragLevelNextLoadedDelay < fragLoadedDelay) {
logger["b" /* logger */].warn('loading too slow, abort fragment loading and switch to level ' + nextLoadLevel + ':fragLoadedDelay[' + nextLoadLevel + ']<fragLoadedDelay[' + (frag.level - 1) + '];bufferStarvationDelay:' + fragLevelNextLoadedDelay.toFixed(1) + '<' + fragLoadedDelay.toFixed(1) + ':' + bufferStarvationDelay.toFixed(1));
// force next load level in auto mode
hls.nextLoadLevel = nextLoadLevel;
// update bw estimate for this fragment before cancelling load (this will help reducing the bw)
this._bwEstimator.sample(requestDelay, stats.loaded);
//abort fragment loading
loader.abort();
// stop abandon rules timer
this.clearTimer();
hls.trigger(events["a" /* default */].FRAG_LOAD_EMERGENCY_ABORTED, { frag: frag, stats: stats });
}
}
}
}
};
AbrController.prototype.onFragLoaded = function onFragLoaded(data) {
var frag = data.frag;
if (frag.type === 'main' && !isNaN(frag.sn)) {
// stop monitoring bw once frag loaded
this.clearTimer();
// store level id after successful fragment load
this.lastLoadedFragLevel = frag.level;
// reset forced auto level value so that next level will be selected
this._nextAutoLevel = -1;
// compute level average bitrate
if (this.hls.config.abrMaxWithRealBitrate) {
var level = this.hls.levels[frag.level];
var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + data.stats.loaded;
var loadedDuration = (level.loaded ? level.loaded.duration : 0) + data.frag.duration;
level.loaded = { bytes: loadedBytes, duration: loadedDuration };
level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
}
// if fragment has been loaded to perform a bitrate test,
if (data.frag.bitrateTest) {
var stats = data.stats;
stats.tparsed = stats.tbuffered = stats.tload;
this.onFragBuffered(data);
}
}
};
AbrController.prototype.onFragBuffered = function onFragBuffered(data) {
var stats = data.stats,
frag = data.frag;
// only update stats on first frag buffering
// if same frag is loaded multiple times, it might be in browser cache, and loaded quickly
// and leading to wrong bw estimation
// on bitrate test, also only update stats once (if tload = tbuffered == on FRAG_LOADED)
if (stats.aborted !== true && frag.loadCounter === 1 && frag.type === 'main' && !isNaN(frag.sn) && (!frag.bitrateTest || stats.tload === stats.tbuffered)) {
// use tparsed-trequest instead of tbuffered-trequest to compute fragLoadingProcessing; rationale is that buffer appending only happens once media is attached
// in case we use config.startFragPrefetch while media is not attached yet, fragment might be parsed while media not attached yet, but it will only be buffered on media attached
// as a consequence it could happen really late in the process. meaning that appending duration might appears huge ... leading to underestimated throughput estimation
var fragLoadingProcessingMs = stats.tparsed - stats.trequest;
logger["b" /* logger */].log('latency/loading/parsing/append/kbps:' + Math.round(stats.tfirst - stats.trequest) + '/' + Math.round(stats.tload - stats.tfirst) + '/' + Math.round(stats.tparsed - stats.tload) + '/' + Math.round(stats.tbuffered - stats.tparsed) + '/' + Math.round(8 * stats.loaded / (stats.tbuffered - stats.trequest)));
this._bwEstimator.sample(fragLoadingProcessingMs, stats.loaded);
stats.bwEstimate = this._bwEstimator.getEstimate();
// if fragment has been loaded to perform a bitrate test, (hls.startLevel = -1), store bitrate test delay duration
if (frag.bitrateTest) {
this.bitrateTestDelay = fragLoadingProcessingMs / 1000;
} else {
this.bitrateTestDelay = 0;
}
}
};
AbrController.prototype.onError = function onError(data) {
// stop timer in case of frag loading error
switch (data.details) {
case errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR:
case errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT:
this.clearTimer();
break;
default:
break;
}
};
AbrController.prototype.clearTimer = function clearTimer() {
clearInterval(this.timer);
this.timer = null;
};
// return next auto level
AbrController.prototype._findBestLevel = function _findBestLevel(currentLevel, currentFragDuration, currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor, levels) {
for (var i = maxAutoLevel; i >= minAutoLevel; i--) {
var levelInfo = levels[i],
levelDetails = levelInfo.details,
avgDuration = levelDetails ? levelDetails.totalduration / levelDetails.fragments.length : currentFragDuration,
live = levelDetails ? levelDetails.live : false,
adjustedbw = void 0;
// follow algorithm captured from stagefright :
// https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
// Pick the highest bandwidth stream below or equal to estimated bandwidth.
// consider only 80% of the available bandwidth, but if we are switching up,
// be even more conservative (70%) to avoid overestimating and immediately
// switching back.
if (i <= currentLevel) {
adjustedbw = bwFactor * currentBw;
} else {
adjustedbw = bwUpFactor * currentBw;
}
var bitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate,
fetchDuration = bitrate * avgDuration / adjustedbw;
logger["b" /* logger */].trace('level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: ' + i + '/' + Math.round(adjustedbw) + '/' + bitrate + '/' + avgDuration + '/' + maxFetchDuration + '/' + fetchDuration);
// if adjusted bw is greater than level bitrate AND
if (adjustedbw > bitrate && (
// fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
// we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...
// special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that _findBestLevel will return -1
!fetchDuration || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)) {
// as we are looping from highest to lowest, this will return the best achievable quality level
return i;
}
}
// not enough time budget even with quality level 0 ... rebuffering might happen
return -1;
};
abr_controller__createClass(AbrController, [{
key: 'nextAutoLevel',
get: function get() {
var forcedAutoLevel = this._nextAutoLevel;
var bwEstimator = this._bwEstimator;
// in case next auto level has been forced, and bw not available or not reliable, return forced value
if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) {
return forcedAutoLevel;
}
// compute next level using ABR logic
var nextABRAutoLevel = this._nextABRAutoLevel;
// if forced auto level has been defined, use it to cap ABR computed quality level
if (forcedAutoLevel !== -1) {
nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel);
}
return nextABRAutoLevel;
},
set: function set(nextLevel) {
this._nextAutoLevel = nextLevel;
}
}, {
key: '_nextABRAutoLevel',
get: function get() {
var hls = this.hls,
maxAutoLevel = hls.maxAutoLevel,
levels = hls.levels,
config = hls.config,
minAutoLevel = hls.minAutoLevel;
var v = hls.media,
currentLevel = this.lastLoadedFragLevel,
currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0,
pos = v ? v.currentTime : 0,
// playbackRate is the absolute value of the playback rate; if v.playbackRate is 0, we use 1 to load as
// if we're playing back at the normal rate.
playbackRate = v && v.playbackRate !== 0 ? Math.abs(v.playbackRate) : 1.0,
avgbw = this._bwEstimator ? this._bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate,
// bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
bufferStarvationDelay = (buffer_helper.bufferInfo(v, pos, config.maxBufferHole).end - pos) / playbackRate;
// First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
var bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor, levels);
if (bestLevel >= 0) {
return bestLevel;
} else {
logger["b" /* logger */].trace('rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering');
// not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering
// if no matching level found, logic will return 0
var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay,
bwFactor = config.abrBandWidthFactor,
bwUpFactor = config.abrBandWidthUpFactor;
if (bufferStarvationDelay === 0) {
// in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
var bitrateTestDelay = this.bitrateTestDelay;
if (bitrateTestDelay) {
// if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
// max video loading delay used in automatic start level selection :
// in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
// the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
// cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
logger["b" /* logger */].trace('bitrate test took ' + Math.round(1000 * bitrateTestDelay) + 'ms, set first fragment max fetchDuration to ' + Math.round(1000 * maxStarvationDelay) + ' ms');
// don't use conservative factor on bitrate test
bwFactor = bwUpFactor = 1;
}
}
bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor, levels);
return Math.max(bestLevel, 0);
}
}
}]);
return AbrController;
}(event_handler);
/* harmony default export */ var abr_controller = (abr_controller_AbrController);
// CONCATENATED MODULE: ./src/controller/buffer-controller.js
function buffer_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function buffer_controller__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 buffer_controller__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; }
/*
* Buffer Controller
*/
var buffer_controller_MediaSource = getMediaSource();
var buffer_controller_BufferController = function (_EventHandler) {
buffer_controller__inherits(BufferController, _EventHandler);
function BufferController(hls) {
buffer_controller__classCallCheck(this, BufferController);
// the value that we have set mediasource.duration to
// (the actual duration may be tweaked slighly by the browser)
var _this = buffer_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHING, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].MANIFEST_PARSED, events["a" /* default */].BUFFER_RESET, events["a" /* default */].BUFFER_APPENDING, events["a" /* default */].BUFFER_CODECS, events["a" /* default */].BUFFER_EOS, events["a" /* default */].BUFFER_FLUSHING, events["a" /* default */].LEVEL_PTS_UPDATED, events["a" /* default */].LEVEL_UPDATED));
_this._msDuration = null;
// the value that we want to set mediaSource.duration to
_this._levelDuration = null;
// Source Buffer listeners
_this.onsbue = _this.onSBUpdateEnd.bind(_this);
_this.onsbe = _this.onSBUpdateError.bind(_this);
_this.pendingTracks = {};
_this.tracks = {};
return _this;
}
BufferController.prototype.destroy = function destroy() {
event_handler.prototype.destroy.call(this);
};
BufferController.prototype.onLevelPtsUpdated = function onLevelPtsUpdated(data) {
var type = data.type;
var audioTrack = this.tracks.audio;
// Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
// in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
// is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos). At the time of change we issue
// `SourceBuffer.abort()` and adjusting `SourceBuffer.timestampOffset` if `SourceBuffer.updating` is false or awaiting `updateend`
// event if SB is in updating state.
// More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
if (type === 'audio' && audioTrack && audioTrack.container === 'audio/mpeg') {
// Chrome audio mp3 track
var audioBuffer = this.sourceBuffer.audio;
var delta = Math.abs(audioBuffer.timestampOffset - data.start);
// adjust timestamp offset if time delta is greater than 100ms
if (delta > 0.1) {
var updating = audioBuffer.updating;
try {
audioBuffer.abort();
} catch (err) {
updating = true;
logger["b" /* logger */].warn('can not abort audio buffer: ' + err);
}
if (!updating) {
logger["b" /* logger */].warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + data.start);
audioBuffer.timestampOffset = data.start;
} else {
this.audioTimestampOffset = data.start;
}
}
}
};
BufferController.prototype.onManifestParsed = function onManifestParsed(data) {
var audioExpected = data.audio,
videoExpected = data.video || data.levels.length && data.audio,
sourceBufferNb = 0;
// in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller
// sourcebuffers will be created all at once when the expected nb of tracks will be reached
// in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
// it will contain the expected nb of source buffers, no need to compute it
if (data.altAudio && (audioExpected || videoExpected)) {
sourceBufferNb = (audioExpected ? 1 : 0) + (videoExpected ? 1 : 0);
logger["b" /* logger */].log(sourceBufferNb + ' sourceBuffer(s) expected');
}
this.sourceBufferNb = sourceBufferNb;
};
BufferController.prototype.onMediaAttaching = function onMediaAttaching(data) {
var media = this.media = data.media;
if (media) {
// setup the media source
var ms = this.mediaSource = new buffer_controller_MediaSource();
//Media Source listeners
this.onmso = this.onMediaSourceOpen.bind(this);
this.onmse = this.onMediaSourceEnded.bind(this);
this.onmsc = this.onMediaSourceClose.bind(this);
ms.addEventListener('sourceopen', this.onmso);
ms.addEventListener('sourceended', this.onmse);
ms.addEventListener('sourceclose', this.onmsc);
// link video and media Source
media.src = URL.createObjectURL(ms);
}
};
BufferController.prototype.onMediaDetaching = function onMediaDetaching() {
logger["b" /* logger */].log('media source detaching');
var ms = this.mediaSource;
if (ms) {
if (ms.readyState === 'open') {
try {
// endOfStream could trigger exception if any sourcebuffer is in updating state
// we don't really care about checking sourcebuffer state here,
// as we are anyway detaching the MediaSource
// let's just avoid this exception to propagate
ms.endOfStream();
} catch (err) {
logger["b" /* logger */].warn('onMediaDetaching:' + err.message + ' while calling endOfStream');
}
}
ms.removeEventListener('sourceopen', this.onmso);
ms.removeEventListener('sourceended', this.onmse);
ms.removeEventListener('sourceclose', this.onmsc);
// Detach properly the MediaSource from the HTMLMediaElement as
// suggested in https://github.com/w3c/media-source/issues/53.
if (this.media) {
URL.revokeObjectURL(this.media.src);
this.media.removeAttribute('src');
this.media.load();
}
this.mediaSource = null;
this.media = null;
this.pendingTracks = {};
this.tracks = {};
this.sourceBuffer = {};
this.flushRange = [];
this.segments = [];
this.appended = 0;
}
this.onmso = this.onmse = this.onmsc = null;
this.hls.trigger(events["a" /* default */].MEDIA_DETACHED);
};
BufferController.prototype.onMediaSourceOpen = function onMediaSourceOpen() {
logger["b" /* logger */].log('media source opened');
this.hls.trigger(events["a" /* default */].MEDIA_ATTACHED, { media: this.media });
var mediaSource = this.mediaSource;
if (mediaSource) {
// once received, don't listen anymore to sourceopen event
mediaSource.removeEventListener('sourceopen', this.onmso);
}
this.checkPendingTracks();
};
BufferController.prototype.checkPendingTracks = function checkPendingTracks() {
// if any buffer codecs pending, check if we have enough to create sourceBuffers
var pendingTracks = this.pendingTracks,
pendingTracksNb = Object.keys(pendingTracks).length;
// if any pending tracks and (if nb of pending tracks gt or equal than expected nb or if unknown expected nb)
if (pendingTracksNb && (this.sourceBufferNb <= pendingTracksNb || this.sourceBufferNb === 0)) {
// ok, let's create them now !
this.createSourceBuffers(pendingTracks);
this.pendingTracks = {};
// append any pending segments now !
this.doAppending();
}
};
BufferController.prototype.onMediaSourceClose = function onMediaSourceClose() {
logger["b" /* logger */].log('media source closed');
};
BufferController.prototype.onMediaSourceEnded = function onMediaSourceEnded() {
logger["b" /* logger */].log('media source ended');
};
BufferController.prototype.onSBUpdateEnd = function onSBUpdateEnd() {
// update timestampOffset
if (this.audioTimestampOffset) {
var audioBuffer = this.sourceBuffer.audio;
logger["b" /* logger */].warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + this.audioTimestampOffset);
audioBuffer.timestampOffset = this.audioTimestampOffset;
delete this.audioTimestampOffset;
}
if (this._needsFlush) {
this.doFlush();
}
if (this._needsEos) {
this.checkEos();
}
this.appending = false;
var parent = this.parent;
// count nb of pending segments waiting for appending on this sourcebuffer
var pending = this.segments.reduce(function (counter, segment) {
return segment.parent === parent ? counter + 1 : counter;
}, 0);
this.hls.trigger(events["a" /* default */].BUFFER_APPENDED, { parent: parent, pending: pending });
// don't append in flushing mode
if (!this._needsFlush) {
this.doAppending();
}
this.updateMediaElementDuration();
};
BufferController.prototype.onSBUpdateError = function onSBUpdateError(event) {
logger["b" /* logger */].error('sourceBuffer error:', event);
// according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
// this error might not always be fatal (it is fatal if decode error is set, in that case
// it will be followed by a mediaElement error ...)
this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_APPENDING_ERROR, fatal: false });
// we don't need to do more than that, as accordin to the spec, updateend will be fired just after
};
BufferController.prototype.onBufferReset = function onBufferReset() {
var sourceBuffer = this.sourceBuffer;
for (var type in sourceBuffer) {
var sb = sourceBuffer[type];
try {
this.mediaSource.removeSourceBuffer(sb);
sb.removeEventListener('updateend', this.onsbue);
sb.removeEventListener('error', this.onsbe);
} catch (err) {}
}
this.sourceBuffer = {};
this.flushRange = [];
this.segments = [];
this.appended = 0;
};
BufferController.prototype.onBufferCodecs = function onBufferCodecs(tracks) {
// if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks
// if sourcebuffers already created, do nothing ...
if (Object.keys(this.sourceBuffer).length === 0) {
for (var trackName in tracks) {
this.pendingTracks[trackName] = tracks[trackName];
}
var mediaSource = this.mediaSource;
if (mediaSource && mediaSource.readyState === 'open') {
// try to create sourcebuffers if mediasource opened
this.checkPendingTracks();
}
}
};
BufferController.prototype.createSourceBuffers = function createSourceBuffers(tracks) {
var sourceBuffer = this.sourceBuffer,
mediaSource = this.mediaSource;
for (var trackName in tracks) {
if (!sourceBuffer[trackName]) {
var track = tracks[trackName];
// use levelCodec as first priority
var codec = track.levelCodec || track.codec;
var mimeType = track.container + ';codecs=' + codec;
logger["b" /* logger */].log('creating sourceBuffer(' + mimeType + ')');
try {
var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
sb.addEventListener('updateend', this.onsbue);
sb.addEventListener('error', this.onsbe);
this.tracks[trackName] = { codec: codec, container: track.container };
track.buffer = sb;
} catch (err) {
logger["b" /* logger */].error('error while trying to add sourceBuffer:' + err.message);
this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_ADD_CODEC_ERROR, fatal: false, err: err, mimeType: mimeType });
}
}
}
this.hls.trigger(events["a" /* default */].BUFFER_CREATED, { tracks: tracks });
};
BufferController.prototype.onBufferAppending = function onBufferAppending(data) {
if (!this._needsFlush) {
if (!this.segments) {
this.segments = [data];
} else {
this.segments.push(data);
}
this.doAppending();
}
};
BufferController.prototype.onBufferAppendFail = function onBufferAppendFail(data) {
logger["b" /* logger */].error('sourceBuffer error:', data.event);
// according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
// this error might not always be fatal (it is fatal if decode error is set, in that case
// it will be followed by a mediaElement error ...)
this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_APPENDING_ERROR, fatal: false });
};
// on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()
BufferController.prototype.onBufferEos = function onBufferEos(data) {
var sb = this.sourceBuffer;
var dataType = data.type;
for (var type in sb) {
if (!dataType || type === dataType) {
if (!sb[type].ended) {
sb[type].ended = true;
logger["b" /* logger */].log(type + ' sourceBuffer now EOS');
}
}
}
this.checkEos();
};
// if all source buffers are marked as ended, signal endOfStream() to MediaSource.
BufferController.prototype.checkEos = function checkEos() {
var sb = this.sourceBuffer,
mediaSource = this.mediaSource;
if (!mediaSource || mediaSource.readyState !== 'open') {
this._needsEos = false;
return;
}
for (var type in sb) {
var sbobj = sb[type];
if (!sbobj.ended) {
return;
}
if (sbobj.updating) {
this._needsEos = true;
return;
}
}
logger["b" /* logger */].log('all media data available, signal endOfStream() to MediaSource and stop loading fragment');
//Notify the media element that it now has all of the media data
try {
mediaSource.endOfStream();
} catch (e) {
logger["b" /* logger */].warn('exception while calling mediaSource.endOfStream()');
}
this._needsEos = false;
};
BufferController.prototype.onBufferFlushing = function onBufferFlushing(data) {
this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: data.type });
// attempt flush immediatly
this.flushBufferCounter = 0;
this.doFlush();
};
BufferController.prototype.onLevelUpdated = function onLevelUpdated(event) {
var details = event.details;
if (details.fragments.length === 0) {
return;
}
this._levelDuration = details.totalduration + details.fragments[0].start;
this.updateMediaElementDuration();
};
// https://github.com/video-dev/hls.js/issues/355
BufferController.prototype.updateMediaElementDuration = function updateMediaElementDuration() {
var media = this.media,
mediaSource = this.mediaSource,
sourceBuffer = this.sourceBuffer,
levelDuration = this._levelDuration;
if (levelDuration === null || !media || !mediaSource || !sourceBuffer || media.readyState === 0 || mediaSource.readyState !== 'open') {
return;
}
for (var type in sourceBuffer) {
if (sourceBuffer[type].updating) {
// can't set duration whilst a buffer is updating
return;
}
}
if (this._msDuration === null) {
// initialise to the value that the media source is reporting
this._msDuration = mediaSource.duration;
}
var duration = media.duration;
// levelDuration was the last value we set.
// not using mediaSource.duration as the browser may tweak this value
// only update mediasource duration if its value increase, this is to avoid
// flushing already buffered portion when switching between quality level
if (levelDuration > this._msDuration && levelDuration > duration || duration === Infinity || isNaN(duration)) {
logger["b" /* logger */].log('Updating mediasource duration to ' + levelDuration.toFixed(3));
this._msDuration = mediaSource.duration = levelDuration;
}
};
BufferController.prototype.doFlush = function doFlush() {
// loop through all buffer ranges to flush
while (this.flushRange.length) {
var range = this.flushRange[0];
// flushBuffer will abort any buffer append in progress and flush Audio/Video Buffer
if (this.flushBuffer(range.start, range.end, range.type)) {
// range flushed, remove from flush array
this.flushRange.shift();
this.flushBufferCounter = 0;
} else {
this._needsFlush = true;
// avoid looping, wait for SB update end to retrigger a flush
return;
}
}
if (this.flushRange.length === 0) {
// everything flushed
this._needsFlush = false;
// let's recompute this.appended, which is used to avoid flush looping
var appended = 0;
var sourceBuffer = this.sourceBuffer;
try {
for (var type in sourceBuffer) {
appended += sourceBuffer[type].buffered.length;
}
} catch (error) {
// error could be thrown while accessing buffered, in case sourcebuffer has already been removed from MediaSource
// this is harmess at this stage, catch this to avoid reporting an internal exception
logger["b" /* logger */].error('error while accessing sourceBuffer.buffered');
}
this.appended = appended;
this.hls.trigger(events["a" /* default */].BUFFER_FLUSHED);
}
};
BufferController.prototype.doAppending = function doAppending() {
var hls = this.hls,
sourceBuffer = this.sourceBuffer,
segments = this.segments;
if (Object.keys(sourceBuffer).length) {
if (this.media.error) {
this.segments = [];
logger["b" /* logger */].error('trying to append although a media error occured, flush segment and abort');
return;
}
if (this.appending) {
//logger.log(`sb appending in progress`);
return;
}
if (segments && segments.length) {
var segment = segments.shift();
try {
var type = segment.type,
sb = sourceBuffer[type];
if (sb) {
if (!sb.updating) {
// reset sourceBuffer ended flag before appending segment
sb.ended = false;
//logger.log(`appending ${segment.content} ${type} SB, size:${segment.data.length}, ${segment.parent}`);
this.parent = segment.parent;
sb.appendBuffer(segment.data);
this.appendError = 0;
this.appended++;
this.appending = true;
} else {
segments.unshift(segment);
}
} else {
// in case we don't have any source buffer matching with this segment type,
// it means that Mediasource fails to create sourcebuffer
// discard this segment, and trigger update end
this.onSBUpdateEnd();
}
} catch (err) {
// in case any error occured while appending, put back segment in segments table
logger["b" /* logger */].error('error while trying to append buffer:' + err.message);
segments.unshift(segment);
var event = { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, parent: segment.parent };
if (err.code !== 22) {
if (this.appendError) {
this.appendError++;
} else {
this.appendError = 1;
}
event.details = errors["a" /* ErrorDetails */].BUFFER_APPEND_ERROR;
/* with UHD content, we could get loop of quota exceeded error until
browser is able to evict some data from sourcebuffer. retrying help recovering this
*/
if (this.appendError > hls.config.appendErrorMaxRetry) {
logger["b" /* logger */].log('fail ' + hls.config.appendErrorMaxRetry + ' times to append segment in sourceBuffer');
segments = [];
event.fatal = true;
hls.trigger(events["a" /* default */].ERROR, event);
return;
} else {
event.fatal = false;
hls.trigger(events["a" /* default */].ERROR, event);
}
} else {
// QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
// let's stop appending any segments, and report BUFFER_FULL_ERROR error
this.segments = [];
event.details = errors["a" /* ErrorDetails */].BUFFER_FULL_ERROR;
event.fatal = false;
hls.trigger(events["a" /* default */].ERROR, event);
return;
}
}
}
}
};
/*
flush specified buffered range,
return true once range has been flushed.
as sourceBuffer.remove() is asynchronous, flushBuffer will be retriggered on sourceBuffer update end
*/
BufferController.prototype.flushBuffer = function flushBuffer(startOffset, endOffset, typeIn) {
var sb,
i,
bufStart,
bufEnd,
flushStart,
flushEnd,
sourceBuffer = this.sourceBuffer;
if (Object.keys(sourceBuffer).length) {
logger["b" /* logger */].log('flushBuffer,pos/start/end: ' + this.media.currentTime.toFixed(3) + '/' + startOffset + '/' + endOffset);
// safeguard to avoid infinite looping : don't try to flush more than the nb of appended segments
if (this.flushBufferCounter < this.appended) {
for (var type in sourceBuffer) {
// check if sourcebuffer type is defined (typeIn): if yes, let's only flush this one
// if no, let's flush all sourcebuffers
if (typeIn && type !== typeIn) {
continue;
}
sb = sourceBuffer[type];
// we are going to flush buffer, mark source buffer as 'not ended'
sb.ended = false;
if (!sb.updating) {
try {
for (i = 0; i < sb.buffered.length; i++) {
bufStart = sb.buffered.start(i);
bufEnd = sb.buffered.end(i);
// workaround firefox not able to properly flush multiple buffered range.
if (navigator.userAgent.toLowerCase().indexOf('firefox') !== -1 && endOffset === Number.POSITIVE_INFINITY) {
flushStart = startOffset;
flushEnd = endOffset;
} else {
flushStart = Math.max(bufStart, startOffset);
flushEnd = Math.min(bufEnd, endOffset);
}
/* sometimes sourcebuffer.remove() does not flush
the exact expected time range.
to avoid rounding issues/infinite loop,
only flush buffer range of length greater than 500ms.
*/
if (Math.min(flushEnd, bufEnd) - flushStart > 0.5) {
this.flushBufferCounter++;
logger["b" /* logger */].log('flush ' + type + ' [' + flushStart + ',' + flushEnd + '], of [' + bufStart + ',' + bufEnd + '], pos:' + this.media.currentTime);
sb.remove(flushStart, flushEnd);
return false;
}
}
} catch (e) {
logger["b" /* logger */].warn('exception while accessing sourcebuffer, it might have been removed from MediaSource');
}
} else {
//logger.log('abort ' + type + ' append in progress');
// this will abort any appending in progress
//sb.abort();
logger["b" /* logger */].warn('cannot flush, sb updating in progress');
return false;
}
}
} else {
logger["b" /* logger */].warn('abort flushing too many retries');
}
logger["b" /* logger */].log('buffer flushed');
}
// everything flushed !
return true;
};
return BufferController;
}(event_handler);
/* harmony default export */ var buffer_controller = (buffer_controller_BufferController);
// CONCATENATED MODULE: ./src/controller/cap-level-controller.js
var cap_level_controller__createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function cap_level_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function cap_level_controller__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 cap_level_controller__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; }
/*
* cap stream level to media size dimension controller
*/
var cap_level_controller_CapLevelController = function (_EventHandler) {
cap_level_controller__inherits(CapLevelController, _EventHandler);
function CapLevelController(hls) {
cap_level_controller__classCallCheck(this, CapLevelController);
return cap_level_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].FPS_DROP_LEVEL_CAPPING, events["a" /* default */].MEDIA_ATTACHING, events["a" /* default */].MANIFEST_PARSED));
}
CapLevelController.prototype.destroy = function destroy() {
if (this.hls.config.capLevelToPlayerSize) {
this.media = this.restrictedLevels = null;
this.autoLevelCapping = Number.POSITIVE_INFINITY;
if (this.timer) {
this.timer = clearInterval(this.timer);
}
}
};
CapLevelController.prototype.onFpsDropLevelCapping = function onFpsDropLevelCapping(data) {
// Don't add a restricted level more than once
if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) {
this.restrictedLevels.push(data.droppedLevel);
}
};
CapLevelController.prototype.onMediaAttaching = function onMediaAttaching(data) {
this.media = data.media instanceof HTMLVideoElement ? data.media : null;
};
CapLevelController.prototype.onManifestParsed = function onManifestParsed(data) {
var hls = this.hls;
this.restrictedLevels = [];
if (hls.config.capLevelToPlayerSize) {
this.autoLevelCapping = Number.POSITIVE_INFINITY;
this.levels = data.levels;
hls.firstLevel = this.getMaxLevel(data.firstLevel);
clearInterval(this.timer);
this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);
this.detectPlayerSize();
}
};
CapLevelController.prototype.detectPlayerSize = function detectPlayerSize() {
if (this.media) {
var levelsLength = this.levels ? this.levels.length : 0;
if (levelsLength) {
var hls = this.hls;
hls.autoLevelCapping = this.getMaxLevel(levelsLength - 1);
if (hls.autoLevelCapping > this.autoLevelCapping) {
// if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
// usually happen when the user go to the fullscreen mode.
hls.streamController.nextLevelSwitch();
}
this.autoLevelCapping = hls.autoLevelCapping;
}
}
};
/*
* returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
*/
CapLevelController.prototype.getMaxLevel = function getMaxLevel(capLevelIndex) {
var _this2 = this;
if (!this.levels) {
return -1;
}
var validLevels = this.levels.filter(function (level, index) {
return CapLevelController.isLevelAllowed(index, _this2.restrictedLevels) && index <= capLevelIndex;
});
return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
};
CapLevelController.isLevelAllowed = function isLevelAllowed(level) {
var restrictedLevels = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
return restrictedLevels.indexOf(level) === -1;
};
CapLevelController.getMaxLevelByMediaSize = function getMaxLevelByMediaSize(levels, width, height) {
if (!levels || levels && !levels.length) {
return -1;
}
// Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
// to determine whether we've chosen the greatest bandwidth for the media's dimensions
var atGreatestBandiwdth = function atGreatestBandiwdth(curLevel, nextLevel) {
if (!nextLevel) {
return true;
}
return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
};
// If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
// the max level
var maxLevelIndex = levels.length - 1;
for (var i = 0; i < levels.length; i += 1) {
var level = levels[i];
if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) {
maxLevelIndex = i;
break;
}
}
return maxLevelIndex;
};
cap_level_controller__createClass(CapLevelController, [{
key: 'mediaWidth',
get: function get() {
var width = void 0;
var media = this.media;
if (media) {
width = media.width || media.clientWidth || media.offsetWidth;
width *= CapLevelController.contentScaleFactor;
}
return width;
}
}, {
key: 'mediaHeight',
get: function get() {
var height = void 0;
var media = this.media;
if (media) {
height = media.height || media.clientHeight || media.offsetHeight;
height *= CapLevelController.contentScaleFactor;
}
return height;
}
}], [{
key: 'contentScaleFactor',
get: function get() {
var pixelRatio = 1;
try {
pixelRatio = window.devicePixelRatio;
} catch (e) {}
return pixelRatio;
}
}]);
return CapLevelController;
}(event_handler);
/* harmony default export */ var cap_level_controller = (cap_level_controller_CapLevelController);
// CONCATENATED MODULE: ./src/controller/fps-controller.js
function fps_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function fps_controller__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 fps_controller__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; }
/*
* FPS Controller
*/
var fps_controller_FPSController = function (_EventHandler) {
fps_controller__inherits(FPSController, _EventHandler);
function FPSController(hls) {
fps_controller__classCallCheck(this, FPSController);
return fps_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHING));
}
FPSController.prototype.destroy = function destroy() {
if (this.timer) {
clearInterval(this.timer);
}
this.isVideoPlaybackQualityAvailable = false;
};
FPSController.prototype.onMediaAttaching = function onMediaAttaching(data) {
var config = this.hls.config;
if (config.capLevelOnFPSDrop) {
var video = this.video = data.media instanceof HTMLVideoElement ? data.media : null;
if (typeof video.getVideoPlaybackQuality === 'function') {
this.isVideoPlaybackQualityAvailable = true;
}
clearInterval(this.timer);
this.timer = setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
}
};
FPSController.prototype.checkFPS = function checkFPS(video, decodedFrames, droppedFrames) {
var currentTime = performance.now();
if (decodedFrames) {
if (this.lastTime) {
var currentPeriod = currentTime - this.lastTime,
currentDropped = droppedFrames - this.lastDroppedFrames,
currentDecoded = decodedFrames - this.lastDecodedFrames,
droppedFPS = 1000 * currentDropped / currentPeriod,
hls = this.hls;
hls.trigger(events["a" /* default */].FPS_DROP, { currentDropped: currentDropped, currentDecoded: currentDecoded, totalDroppedFrames: droppedFrames });
if (droppedFPS > 0) {
//logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
var currentLevel = hls.currentLevel;
logger["b" /* logger */].warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
currentLevel = currentLevel - 1;
hls.trigger(events["a" /* default */].FPS_DROP_LEVEL_CAPPING, { level: currentLevel, droppedLevel: hls.currentLevel });
hls.autoLevelCapping = currentLevel;
hls.streamController.nextLevelSwitch();
}
}
}
}
this.lastTime = currentTime;
this.lastDroppedFrames = droppedFrames;
this.lastDecodedFrames = decodedFrames;
}
};
FPSController.prototype.checkFPSInterval = function checkFPSInterval() {
var video = this.video;
if (video) {
if (this.isVideoPlaybackQualityAvailable) {
var videoPlaybackQuality = video.getVideoPlaybackQuality();
this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
} else {
this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
}
}
};
return FPSController;
}(event_handler);
/* harmony default export */ var fps_controller = (fps_controller_FPSController);
// CONCATENATED MODULE: ./src/utils/xhr-loader.js
function xhr_loader__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* XHR based logger
*/
var xhr_loader_XhrLoader = function () {
function XhrLoader(config) {
xhr_loader__classCallCheck(this, XhrLoader);
if (config && config.xhrSetup) {
this.xhrSetup = config.xhrSetup;
}
}
XhrLoader.prototype.destroy = function destroy() {
this.abort();
this.loader = null;
};
XhrLoader.prototype.abort = function abort() {
var loader = this.loader;
if (loader && loader.readyState !== 4) {
this.stats.aborted = true;
loader.abort();
}
window.clearTimeout(this.requestTimeout);
this.requestTimeout = null;
window.clearTimeout(this.retryTimeout);
this.retryTimeout = null;
};
XhrLoader.prototype.load = function load(context, config, callbacks) {
this.context = context;
this.config = config;
this.callbacks = callbacks;
this.stats = { trequest: performance.now(), retry: 0 };
this.retryDelay = config.retryDelay;
this.loadInternal();
};
XhrLoader.prototype.loadInternal = function loadInternal() {
var xhr,
context = this.context;
xhr = this.loader = new XMLHttpRequest();
var stats = this.stats;
stats.tfirst = 0;
stats.loaded = 0;
var xhrSetup = this.xhrSetup;
try {
if (xhrSetup) {
try {
xhrSetup(xhr, context.url);
} catch (e) {
// fix xhrSetup: (xhr, url) => {xhr.setRequestHeader("Content-Language", "test");}
// not working, as xhr.setRequestHeader expects xhr.readyState === OPEN
xhr.open('GET', context.url, true);
xhrSetup(xhr, context.url);
}
}
if (!xhr.readyState) {
xhr.open('GET', context.url, true);
}
} catch (e) {
// IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
this.callbacks.onError({ code: xhr.status, text: e.message }, context, xhr);
return;
}
if (context.rangeEnd) {
xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
}
xhr.onreadystatechange = this.readystatechange.bind(this);
xhr.onprogress = this.loadprogress.bind(this);
xhr.responseType = context.responseType;
// setup timeout before we perform request
this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), this.config.timeout);
xhr.send();
};
XhrLoader.prototype.readystatechange = function readystatechange(event) {
var xhr = event.currentTarget,
readyState = xhr.readyState,
stats = this.stats,
context = this.context,
config = this.config;
// don't proceed if xhr has been aborted
if (stats.aborted) {
return;
}
// >= HEADERS_RECEIVED
if (readyState >= 2) {
// clear xhr timeout and rearm it if readyState less than 4
window.clearTimeout(this.requestTimeout);
if (stats.tfirst === 0) {
stats.tfirst = Math.max(performance.now(), stats.trequest);
}
if (readyState === 4) {
var status = xhr.status;
// http status between 200 to 299 are all successful
if (status >= 200 && status < 300) {
stats.tload = Math.max(stats.tfirst, performance.now());
var data = void 0,
len = void 0;
if (context.responseType === 'arraybuffer') {
data = xhr.response;
len = data.byteLength;
} else {
data = xhr.responseText;
len = data.length;
}
stats.loaded = stats.total = len;
var response = { url: xhr.responseURL, data: data };
this.callbacks.onSuccess(response, stats, context, xhr);
} else {
// if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
if (stats.retry >= config.maxRetry || status >= 400 && status < 499) {
logger["b" /* logger */].error(status + ' while loading ' + context.url);
this.callbacks.onError({ code: status, text: xhr.statusText }, context, xhr);
} else {
// retry
logger["b" /* logger */].warn(status + ' while loading ' + context.url + ', retrying in ' + this.retryDelay + '...');
// aborts and resets internal state
this.destroy();
// schedule retry
this.retryTimeout = window.setTimeout(this.loadInternal.bind(this), this.retryDelay);
// set exponential backoff
this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay);
stats.retry++;
}
}
} else {
// readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), config.timeout);
}
}
};
XhrLoader.prototype.loadtimeout = function loadtimeout() {
logger["b" /* logger */].warn('timeout while loading ' + this.context.url);
this.callbacks.onTimeout(this.stats, this.context, null);
};
XhrLoader.prototype.loadprogress = function loadprogress(event) {
var xhr = event.currentTarget,
stats = this.stats;
stats.loaded = event.loaded;
if (event.lengthComputable) {
stats.total = event.total;
}
var onProgress = this.callbacks.onProgress;
if (onProgress) {
// third arg is to provide on progress data
onProgress(stats, this.context, null, xhr);
}
};
return XhrLoader;
}();
/* harmony default export */ var xhr_loader = (xhr_loader_XhrLoader);
// EXTERNAL MODULE: ./src/empty.js
var empty = __webpack_require__(3);
var empty_default = /*#__PURE__*/__webpack_require__.n(empty);
// CONCATENATED MODULE: ./src/config.js
/**
* HLS config
*/
//import FetchLoader from './utils/fetch-loader';
var hlsDefaultConfig = {
autoStartLoad: true, // used by stream-controller
startPosition: -1, // used by stream-controller
defaultAudioCodec: undefined, // used by stream-controller
debug: false, // used by logger
capLevelOnFPSDrop: false, // used by fps-controller
capLevelToPlayerSize: false, // used by cap-level-controller
initialLiveManifestSize: 1, // used by stream-controller
maxBufferLength: 30, // used by stream-controller
maxBufferSize: 60 * 1000 * 1000, // used by stream-controller
maxBufferHole: 0.5, // used by stream-controller
maxSeekHole: 2, // used by stream-controller
lowBufferWatchdogPeriod: 0.5, // used by stream-controller
highBufferWatchdogPeriod: 3, // used by stream-controller
nudgeOffset: 0.1, // used by stream-controller
nudgeMaxRetry: 3, // used by stream-controller
maxFragLookUpTolerance: 0.25, // used by stream-controller
liveSyncDurationCount: 3, // used by stream-controller
liveMaxLatencyDurationCount: Infinity, // used by stream-controller
liveSyncDuration: undefined, // used by stream-controller
liveMaxLatencyDuration: undefined, // used by stream-controller
maxMaxBufferLength: 600, // used by stream-controller
enableWorker: true, // used by demuxer
enableSoftwareAES: true, // used by decrypter
manifestLoadingTimeOut: 10000, // used by playlist-loader
manifestLoadingMaxRetry: 1, // used by playlist-loader
manifestLoadingRetryDelay: 1000, // used by playlist-loader
manifestLoadingMaxRetryTimeout: 64000, // used by playlist-loader
startLevel: undefined, // used by level-controller
levelLoadingTimeOut: 10000, // used by playlist-loader
levelLoadingMaxRetry: 4, // used by playlist-loader
levelLoadingRetryDelay: 1000, // used by playlist-loader
levelLoadingMaxRetryTimeout: 64000, // used by playlist-loader
fragLoadingTimeOut: 20000, // used by fragment-loader
fragLoadingMaxRetry: 6, // used by fragment-loader
fragLoadingRetryDelay: 1000, // used by fragment-loader
fragLoadingMaxRetryTimeout: 64000, // used by fragment-loader
fragLoadingLoopThreshold: 3, // used by stream-controller
startFragPrefetch: false, // used by stream-controller
fpsDroppedMonitoringPeriod: 5000, // used by fps-controller
fpsDroppedMonitoringThreshold: 0.2, // used by fps-controller
appendErrorMaxRetry: 3, // used by buffer-controller
loader: xhr_loader,
//loader: FetchLoader,
fLoader: undefined,
pLoader: undefined,
xhrSetup: undefined,
fetchSetup: undefined,
abrController: abr_controller,
bufferController: buffer_controller,
capLevelController: cap_level_controller,
fpsController: fps_controller,
stretchShortVideoTrack: false, // used by mp4-remuxer
maxAudioFramesDrift: 1, // used by mp4-remuxer
forceKeyFrameOnDiscontinuity: true, // used by ts-demuxer
abrEwmaFastLive: 3, // used by abr-controller
abrEwmaSlowLive: 9, // used by abr-controller
abrEwmaFastVoD: 3, // used by abr-controller
abrEwmaSlowVoD: 9, // used by abr-controller
abrEwmaDefaultEstimate: 5e5, // 500 kbps // used by abr-controller
abrBandWidthFactor: 0.95, // used by abr-controller
abrBandWidthUpFactor: 0.7, // used by abr-controller
abrMaxWithRealBitrate: false, // used by abr-controller
maxStarvationDelay: 4, // used by abr-controller
maxLoadingDelay: 4, // used by abr-controller
minAutoBitrate: 0 // used by hls
};
if (false) {
hlsDefaultConfig.subtitleStreamController = SubtitleStreamController;
hlsDefaultConfig.subtitleTrackController = SubtitleTrackController;
hlsDefaultConfig.timelineController = TimelineController;
hlsDefaultConfig.cueHandler = Cues;
hlsDefaultConfig.enableCEA708Captions = true; // used by timeline-controller
hlsDefaultConfig.enableWebVTT = true; // used by timeline-controller
hlsDefaultConfig.captionsTextTrack1Label = 'English'; // used by timeline-controller
hlsDefaultConfig.captionsTextTrack1LanguageCode = 'en'; // used by timeline-controller
hlsDefaultConfig.captionsTextTrack2Label = 'Spanish'; // used by timeline-controller
hlsDefaultConfig.captionsTextTrack2LanguageCode = 'es'; // used by timeline-controller
}
if (false) {
hlsDefaultConfig.audioStreamController = AudioStreamController;
hlsDefaultConfig.audioTrackController = AudioTrackController;
}
// CONCATENATED MODULE: ./src/hls.js
var hls__createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function hls__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* HLS interface
*/
var hls_Hls = function () {
Hls.isSupported = function isSupported() {
var mediaSource = getMediaSource();
var sourceBuffer = window.SourceBuffer || window.WebKitSourceBuffer;
var isTypeSupported = mediaSource && typeof mediaSource.isTypeSupported === 'function' && mediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"');
// if SourceBuffer is exposed ensure its API is valid
// safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
var sourceBufferValidAPI = !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';
return isTypeSupported && sourceBufferValidAPI;
};
hls__createClass(Hls, null, [{
key: 'version',
get: function get() {
return "0.8.5";
}
}, {
key: 'Events',
get: function get() {
return events["a" /* default */];
}
}, {
key: 'ErrorTypes',
get: function get() {
return errors["b" /* ErrorTypes */];
}
}, {
key: 'ErrorDetails',
get: function get() {
return errors["a" /* ErrorDetails */];
}
}, {
key: 'DefaultConfig',
get: function get() {
if (!Hls.defaultConfig) {
return hlsDefaultConfig;
}
return Hls.defaultConfig;
},
set: function set(defaultConfig) {
Hls.defaultConfig = defaultConfig;
}
}]);
function Hls() {
var _this = this;
var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
hls__classCallCheck(this, Hls);
var defaultConfig = Hls.DefaultConfig;
if ((config.liveSyncDurationCount || config.liveMaxLatencyDurationCount) && (config.liveSyncDuration || config.liveMaxLatencyDuration)) {
throw new Error('Illegal hls.js config: don\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration');
}
for (var prop in defaultConfig) {
if (prop in config) {
continue;
}
config[prop] = defaultConfig[prop];
}
if (config.liveMaxLatencyDurationCount !== undefined && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) {
throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"');
}
if (config.liveMaxLatencyDuration !== undefined && (config.liveMaxLatencyDuration <= config.liveSyncDuration || config.liveSyncDuration === undefined)) {
throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"');
}
Object(logger["a" /* enableLogs */])(config.debug);
this.config = config;
this._autoLevelCapping = -1;
// observer setup
var observer = this.observer = new events_default.a();
observer.trigger = function trigger(event) {
for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
data[_key - 1] = arguments[_key];
}
observer.emit.apply(observer, [event, event].concat(data));
};
observer.off = function off(event) {
for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
data[_key2 - 1] = arguments[_key2];
}
observer.removeListener.apply(observer, [event].concat(data));
};
this.on = observer.on.bind(observer);
this.off = observer.off.bind(observer);
this.trigger = observer.trigger.bind(observer);
// core controllers and network loaders
var abrController = this.abrController = new config.abrController(this);
var bufferController = new config.bufferController(this);
var capLevelController = new config.capLevelController(this);
var fpsController = new config.fpsController(this);
var playListLoader = new playlist_loader(this);
var fragmentLoader = new fragment_loader(this);
var keyLoader = new key_loader(this);
var id3TrackController = new id3_track_controller(this);
// network controllers
var levelController = this.levelController = new level_controller(this);
var streamController = this.streamController = new stream_controller(this);
var networkControllers = [levelController, streamController];
// optional audio stream controller
var Controller = config.audioStreamController;
if (Controller) {
networkControllers.push(new Controller(this));
}
this.networkControllers = networkControllers;
var coreComponents = [playListLoader, fragmentLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController];
// optional audio track and subtitle controller
Controller = config.audioTrackController;
if (Controller) {
var audioTrackController = new Controller(this);
this.audioTrackController = audioTrackController;
coreComponents.push(audioTrackController);
}
Controller = config.subtitleTrackController;
if (Controller) {
var subtitleTrackController = new Controller(this);
this.subtitleTrackController = subtitleTrackController;
coreComponents.push(subtitleTrackController);
}
// optional subtitle controller
[config.subtitleStreamController, config.timelineController].forEach(function (Controller) {
if (Controller) {
coreComponents.push(new Controller(_this));
}
});
this.coreComponents = coreComponents;
}
Hls.prototype.destroy = function destroy() {
logger["b" /* logger */].log('destroy');
this.trigger(events["a" /* default */].DESTROYING);
this.detachMedia();
this.coreComponents.concat(this.networkControllers).forEach(function (component) {
component.destroy();
});
this.url = null;
this.observer.removeAllListeners();
this._autoLevelCapping = -1;
};
Hls.prototype.attachMedia = function attachMedia(media) {
logger["b" /* logger */].log('attachMedia');
this.media = media;
this.trigger(events["a" /* default */].MEDIA_ATTACHING, { media: media });
};
Hls.prototype.detachMedia = function detachMedia() {
logger["b" /* logger */].log('detachMedia');
this.trigger(events["a" /* default */].MEDIA_DETACHING);
this.media = null;
};
Hls.prototype.loadSource = function loadSource(url) {
url = url_toolkit_default.a.buildAbsoluteURL(window.location.href, url, { alwaysNormalize: true });
logger["b" /* logger */].log('loadSource:' + url);
this.url = url;
// when attaching to a source URL, trigger a playlist load
this.trigger(events["a" /* default */].MANIFEST_LOADING, { url: url });
};
Hls.prototype.startLoad = function startLoad() {
var startPosition = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : -1;
logger["b" /* logger */].log('startLoad(' + startPosition + ')');
this.networkControllers.forEach(function (controller) {
controller.startLoad(startPosition);
});
};
Hls.prototype.stopLoad = function stopLoad() {
logger["b" /* logger */].log('stopLoad');
this.networkControllers.forEach(function (controller) {
controller.stopLoad();
});
};
Hls.prototype.swapAudioCodec = function swapAudioCodec() {
logger["b" /* logger */].log('swapAudioCodec');
this.streamController.swapAudioCodec();
};
Hls.prototype.recoverMediaError = function recoverMediaError() {
logger["b" /* logger */].log('recoverMediaError');
var media = this.media;
this.detachMedia();
this.attachMedia(media);
};
/** Return all quality levels **/
hls__createClass(Hls, [{
key: 'levels',
get: function get() {
return this.levelController.levels;
}
/** Return current playback quality level **/
}, {
key: 'currentLevel',
get: function get() {
return this.streamController.currentLevel;
}
/* set quality level immediately (-1 for automatic level selection) */
,
set: function set(newLevel) {
logger["b" /* logger */].log('set currentLevel:' + newLevel);
this.loadLevel = newLevel;
this.streamController.immediateLevelSwitch();
}
/** Return next playback quality level (quality level of next fragment) **/
}, {
key: 'nextLevel',
get: function get() {
return this.streamController.nextLevel;
}
/* set quality level for next fragment (-1 for automatic level selection) */
,
set: function set(newLevel) {
logger["b" /* logger */].log('set nextLevel:' + newLevel);
this.levelController.manualLevel = newLevel;
this.streamController.nextLevelSwitch();
}
/** Return the quality level of current/last loaded fragment **/
}, {
key: 'loadLevel',
get: function get() {
return this.levelController.level;
}
/* set quality level for current/next loaded fragment (-1 for automatic level selection) */
,
set: function set(newLevel) {
logger["b" /* logger */].log('set loadLevel:' + newLevel);
this.levelController.manualLevel = newLevel;
}
/** Return the quality level of next loaded fragment **/
}, {
key: 'nextLoadLevel',
get: function get() {
return this.levelController.nextLoadLevel;
}
/** set quality level of next loaded fragment **/
,
set: function set(level) {
this.levelController.nextLoadLevel = level;
}
/** Return first level (index of first level referenced in manifest)
**/
}, {
key: 'firstLevel',
get: function get() {
return Math.max(this.levelController.firstLevel, this.minAutoLevel);
}
/** set first level (index of first level referenced in manifest)
**/
,
set: function set(newLevel) {
logger["b" /* logger */].log('set firstLevel:' + newLevel);
this.levelController.firstLevel = newLevel;
}
/** Return start level (level of first fragment that will be played back)
if not overrided by user, first level appearing in manifest will be used as start level
if -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
**/
}, {
key: 'startLevel',
get: function get() {
return this.levelController.startLevel;
}
/** set start level (level of first fragment that will be played back)
if not overrided by user, first level appearing in manifest will be used as start level
if -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
**/
,
set: function set(newLevel) {
logger["b" /* logger */].log('set startLevel:' + newLevel);
var hls = this;
// if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
if (newLevel !== -1) {
newLevel = Math.max(newLevel, hls.minAutoLevel);
}
hls.levelController.startLevel = newLevel;
}
/** Return the capping/max level value that could be used by automatic level selection algorithm **/
}, {
key: 'autoLevelCapping',
get: function get() {
return this._autoLevelCapping;
}
/** set the capping/max level value that could be used by automatic level selection algorithm **/
,
set: function set(newLevel) {
logger["b" /* logger */].log('set autoLevelCapping:' + newLevel);
this._autoLevelCapping = newLevel;
}
/* check if we are in automatic level selection mode */
}, {
key: 'autoLevelEnabled',
get: function get() {
return this.levelController.manualLevel === -1;
}
/* return manual level */
}, {
key: 'manualLevel',
get: function get() {
return this.levelController.manualLevel;
}
/* return min level selectable in auto mode according to config.minAutoBitrate */
}, {
key: 'minAutoLevel',
get: function get() {
var hls = this,
levels = hls.levels,
minAutoBitrate = hls.config.minAutoBitrate,
len = levels ? levels.length : 0;
for (var i = 0; i < len; i++) {
var levelNextBitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate;
if (levelNextBitrate > minAutoBitrate) {
return i;
}
}
return 0;
}
/* return max level selectable in auto mode according to autoLevelCapping */
}, {
key: 'maxAutoLevel',
get: function get() {
var hls = this;
var levels = hls.levels;
var autoLevelCapping = hls.autoLevelCapping;
var maxAutoLevel = void 0;
if (autoLevelCapping === -1 && levels && levels.length) {
maxAutoLevel = levels.length - 1;
} else {
maxAutoLevel = autoLevelCapping;
}
return maxAutoLevel;
}
// return next auto level
}, {
key: 'nextAutoLevel',
get: function get() {
var hls = this;
// ensure next auto level is between min and max auto level
return Math.min(Math.max(hls.abrController.nextAutoLevel, hls.minAutoLevel), hls.maxAutoLevel);
}
// this setter is used to force next auto level
// this is useful to force a switch down in auto mode : in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
// forced value is valid for one fragment. upon succesful frag loading at forced level, this value will be resetted to -1 by ABR controller
,
set: function set(nextLevel) {
var hls = this;
hls.abrController.nextAutoLevel = Math.max(hls.minAutoLevel, nextLevel);
}
/** get alternate audio tracks list from playlist **/
}, {
key: 'audioTracks',
get: function get() {
var audioTrackController = this.audioTrackController;
return audioTrackController ? audioTrackController.audioTracks : [];
}
/** get index of the selected audio track (index in audio track lists) **/
}, {
key: 'audioTrack',
get: function get() {
var audioTrackController = this.audioTrackController;
return audioTrackController ? audioTrackController.audioTrack : -1;
}
/** select an audio track, based on its index in audio track lists**/
,
set: function set(audioTrackId) {
var audioTrackController = this.audioTrackController;
if (audioTrackController) {
audioTrackController.audioTrack = audioTrackId;
}
}
}, {
key: 'liveSyncPosition',
get: function get() {
return this.streamController.liveSyncPosition;
}
/** get alternate subtitle tracks list from playlist **/
}, {
key: 'subtitleTracks',
get: function get() {
var subtitleTrackController = this.subtitleTrackController;
return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
}
/** get index of the selected subtitle track (index in subtitle track lists) **/
}, {
key: 'subtitleTrack',
get: function get() {
var subtitleTrackController = this.subtitleTrackController;
return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
}
/** select an subtitle track, based on its index in subtitle track lists**/
,
set: function set(subtitleTrackId) {
var subtitleTrackController = this.subtitleTrackController;
if (subtitleTrackController) {
subtitleTrackController.subtitleTrack = subtitleTrackId;
}
}
}, {
key: 'subtitleDisplay',
get: function get() {
var subtitleTrackController = this.subtitleTrackController;
return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
},
set: function set(value) {
var subtitleTrackController = this.subtitleTrackController;
if (subtitleTrackController) {
subtitleTrackController.subtitleDisplay = value;
}
}
}]);
return Hls;
}();
/* harmony default export */ var src_hls = __webpack_exports__["default"] = (hls_Hls);
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
function webpackBootstrapFunc (modules) {
/******/ // 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] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.l = 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;
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/";
/******/ // on error function for async loading
/******/ __webpack_require__.oe = function(err) { console.error(err); throw err; };
var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE)
return f.default || f // try to call default if defined to also support babel esmodule exports
}
// http://stackoverflow.com/a/2593661/130442
function quoteRegExp (str) {
return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&')
}
function getModuleDependencies (module) {
var retval = []
var fnString = module.toString()
var wrapperSignature = fnString.match(/^function\s?\(\w+,\s*\w+,\s*(\w+)\)/)
if (!wrapperSignature) return retval
var webpackRequireName = wrapperSignature[1]
var re = new RegExp('(\\\\n|\\W)' + quoteRegExp(webpackRequireName) + '\\((\/\\*.*?\\*\/)?\s?.*?([\\.|\\-|\\w|\/|@]+).*?\\)', 'g') // additional chars when output.pathinfo is true
var match
while ((match = re.exec(fnString))) {
retval.push(match[3])
}
return retval
}
function getRequiredModules (sources, moduleId) {
var modulesQueue = [moduleId]
var requiredModules = []
var seenModules = {}
while (modulesQueue.length) {
var moduleToCheck = modulesQueue.pop()
if (seenModules[moduleToCheck] || !sources[moduleToCheck]) continue
seenModules[moduleToCheck] = true
requiredModules.push(moduleToCheck)
var newModules = getModuleDependencies(sources[moduleToCheck])
modulesQueue = modulesQueue.concat(newModules)
}
return requiredModules
}
module.exports = function (moduleId, options) {
options = options || {}
var sources = __webpack_require__.m
var requiredModules = options.all ? Object.keys(sources) : getRequiredModules(sources, moduleId)
var src = '(' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[id].toString() }).join(',') + '})(self);'
var blob = new window.Blob([src], { type: 'text/javascript' })
if (options.bare) { return blob }
var URL = window.URL || window.webkitURL || window.mozURL || window.msURL
var workerUrl = URL.createObjectURL(blob)
var worker = new window.Worker(workerUrl)
worker.objectURL = workerUrl
return worker
}
/***/ }),
/* 10 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__demux_demuxer_inline__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__events__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_logger__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_events__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_events___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3_events__);
/* demuxer web worker.
* - listen to worker message, and trigger DemuxerInline upon reception of Fragments.
* - provides MP4 Boxes back to main thread using [transferable objects](https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast) in order to minimize message passing overhead.
*/
var DemuxerWorker = function DemuxerWorker(self) {
// observer setup
var observer = new __WEBPACK_IMPORTED_MODULE_3_events___default.a();
observer.trigger = function trigger(event) {
for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
data[_key - 1] = arguments[_key];
}
observer.emit.apply(observer, [event, event].concat(data));
};
observer.off = function off(event) {
for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
data[_key2 - 1] = arguments[_key2];
}
observer.removeListener.apply(observer, [event].concat(data));
};
var forwardMessage = function forwardMessage(ev, data) {
self.postMessage({ event: ev, data: data });
};
self.addEventListener('message', function (ev) {
var data = ev.data;
//console.log('demuxer cmd:' + data.cmd);
switch (data.cmd) {
case 'init':
var config = JSON.parse(data.config);
self.demuxer = new __WEBPACK_IMPORTED_MODULE_0__demux_demuxer_inline__["a" /* default */](observer, data.typeSupported, config, data.vendor);
try {
Object(__WEBPACK_IMPORTED_MODULE_2__utils_logger__["a" /* enableLogs */])(config.debug === true);
} catch (err) {
console.warn('demuxerWorker: unable to enable logs');
}
// signal end of worker init
forwardMessage('init', null);
break;
case 'demux':
self.demuxer.push(data.data, data.decryptdata, data.initSegment, data.audioCodec, data.videoCodec, data.timeOffset, data.discontinuity, data.trackSwitch, data.contiguous, data.duration, data.accurateTimeOffset, data.defaultInitPTS);
break;
default:
break;
}
});
// forward events to main thread
observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_DECRYPTED, forwardMessage);
observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_PARSING_INIT_SEGMENT, forwardMessage);
observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_PARSED, forwardMessage);
observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].ERROR, forwardMessage);
observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_PARSING_METADATA, forwardMessage);
observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_PARSING_USERDATA, forwardMessage);
observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].INIT_PTS_FOUND, forwardMessage);
// special case for FRAG_PARSING_DATA: pass data1/data2 as transferable object (no copy)
observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_PARSING_DATA, function (ev, data) {
var transferable = [];
var message = { event: ev, data: data };
if (data.data1) {
message.data1 = data.data1.buffer;
transferable.push(data.data1.buffer);
delete data.data1;
}
if (data.data2) {
message.data2 = data.data2.buffer;
transferable.push(data.data2.buffer);
delete data.data2;
}
self.postMessage(message, transferable);
});
};
/* harmony default export */ __webpack_exports__["default"] = (DemuxerWorker);
/***/ })
/******/ ])["default"];
});
//# sourceMappingURL=hls.light.js.map | joeyparrish/cdnjs | ajax/libs/hls.js/0.8.5/hls.light.js | JavaScript | mit | 454,278 |
/* =============================================================
* bootstrap-typeahead.js v2.0.4
* http://twitter.github.com/bootstrap/javascript.html#typeahead
* =============================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================================================ */
!function($){
"use strict"; // jshint ;_;
/* TYPEAHEAD PUBLIC CLASS DEFINITION
* ================================= */
var Typeahead = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, $.fn.typeahead.defaults, options)
this.matcher = this.options.matcher || this.matcher
this.sorter = this.options.sorter || this.sorter
this.highlighter = this.options.highlighter || this.highlighter
this.updater = this.options.updater || this.updater
this.$menu = $(this.options.menu).appendTo('body')
this.source = this.options.source
this.shown = false
this.listen()
}
Typeahead.prototype = {
constructor: Typeahead
, select: function () {
var val = this.$menu.find('.active').attr('data-value')
this.$element
.val(this.updater(val))
.change()
return this.hide()
}
, updater: function (item) {
return item
}
, show: function () {
var pos = $.extend({}, this.$element.offset(), {
height: this.$element[0].offsetHeight
})
this.$menu.css({
top: pos.top + pos.height
, left: pos.left
})
this.$menu.show()
this.shown = true
return this
}
, hide: function () {
this.$menu.hide()
this.shown = false
return this
}
, lookup: function (event) {
var that = this
, items
, q
this.query = this.$element.val()
if (!this.query) {
return this.shown ? this.hide() : this
}
items = $.grep(this.source, function (item) {
return that.matcher(item)
})
items = this.sorter(items)
if (!items.length) {
return this.shown ? this.hide() : this
}
return this.render(items.slice(0, this.options.items)).show()
}
, matcher: function (item) {
return ~item.toLowerCase().indexOf(this.query.toLowerCase())
}
, sorter: function (items) {
var beginswith = []
, caseSensitive = []
, caseInsensitive = []
, item
while (item = items.shift()) {
if (!item.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item)
else if (~item.indexOf(this.query)) caseSensitive.push(item)
else caseInsensitive.push(item)
}
return beginswith.concat(caseSensitive, caseInsensitive)
}
, highlighter: function (item) {
var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
return '<strong>' + match + '</strong>'
})
}
, render: function (items) {
var that = this
items = $(items).map(function (i, item) {
i = $(that.options.item).attr('data-value', item)
i.find('a').html(that.highlighter(item))
return i[0]
})
items.first().addClass('active')
this.$menu.html(items)
return this
}
, next: function (event) {
var active = this.$menu.find('.active').removeClass('active')
, next = active.next()
if (!next.length) {
next = $(this.$menu.find('li')[0])
}
next.addClass('active')
}
, prev: function (event) {
var active = this.$menu.find('.active').removeClass('active')
, prev = active.prev()
if (!prev.length) {
prev = this.$menu.find('li').last()
}
prev.addClass('active')
}
, listen: function () {
this.$element
.on('blur', $.proxy(this.blur, this))
.on('keypress', $.proxy(this.keypress, this))
.on('keyup', $.proxy(this.keyup, this))
.on('keydown', $.proxy(this.keypress, this))
this.$menu
.on('click', $.proxy(this.click, this))
.on('mouseenter', 'li', $.proxy(this.mouseenter, this))
}
, keyup: function (e) {
switch(e.keyCode) {
case 40: // down arrow
case 38: // up arrow
break
case 9: // tab
case 13: // enter
if (!this.shown) return
this.select()
break
case 27: // escape
if (!this.shown) return
this.hide()
break
default:
this.lookup()
}
e.stopPropagation()
e.preventDefault()
}
, keypress: function (e) {
if (!this.shown) return
switch(e.keyCode) {
case 9: // tab
case 13: // enter
case 27: // escape
e.preventDefault()
break
case 38: // up arrow
if (e.type != 'keydown') break
e.preventDefault()
this.prev()
break
case 40: // down arrow
if (e.type != 'keydown') break
e.preventDefault()
this.next()
break
}
e.stopPropagation()
}
, blur: function (e) {
var that = this
setTimeout(function () { that.hide() }, 150)
}
, click: function (e) {
e.stopPropagation()
e.preventDefault()
this.select()
}
, mouseenter: function (e) {
this.$menu.find('.active').removeClass('active')
$(e.currentTarget).addClass('active')
}
}
/* TYPEAHEAD PLUGIN DEFINITION
* =========================== */
$.fn.typeahead = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('typeahead')
, options = typeof option == 'object' && option
if (!data) $this.data('typeahead', (data = new Typeahead(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.typeahead.defaults = {
source: []
, items: 8
, menu: '<ul class="typeahead dropdown-menu"></ul>'
, item: '<li><a href="#"></a></li>'
}
$.fn.typeahead.Constructor = Typeahead
/* TYPEAHEAD DATA-API
* ================== */
$(function () {
$('body').on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) {
var $this = $(this)
if ($this.data('typeahead')) return
e.preventDefault()
$this.typeahead($this.data())
})
})
}(window.jQuery); | FlixMaster/mwEmbed | docs/bootstrap/docs/assets/js/bootstrap-typeahead.js | JavaScript | agpl-3.0 | 7,004 |
// Copyright 2008 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 Runtime development CSS Compiler emulation, via javascript.
* This class provides an approximation to CSSCompiler's functionality by
* hacking the live CSSOM.
* This code is designed to be inserted in the DOM immediately after the last
* style block in HEAD when in development mode, i.e. you are not using a
* running instance of a CSS Compiler to pass your CSS through.
*/
goog.provide('goog.debug.DevCss');
goog.provide('goog.debug.DevCss.UserAgent');
goog.require('goog.asserts');
goog.require('goog.cssom');
goog.require('goog.dom.classlist');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.string');
goog.require('goog.userAgent');
/**
* A class for solving development CSS issues/emulating the CSS Compiler.
* @param {goog.debug.DevCss.UserAgent=} opt_userAgent The user agent, if not
* passed in, will be determined using goog.userAgent.
* @param {number|string=} opt_userAgentVersion The user agent's version.
* If not passed in, will be determined using goog.userAgent.
* @throws {Error} When userAgent detection fails.
* @constructor
* @final
*/
goog.debug.DevCss = function(opt_userAgent, opt_userAgentVersion) {
if (!opt_userAgent) {
// Walks through the known goog.userAgents.
if (goog.userAgent.IE) {
opt_userAgent = goog.debug.DevCss.UserAgent.IE;
} else if (goog.userAgent.GECKO) {
opt_userAgent = goog.debug.DevCss.UserAgent.GECKO;
} else if (goog.userAgent.WEBKIT) {
opt_userAgent = goog.debug.DevCss.UserAgent.WEBKIT;
} else if (goog.userAgent.MOBILE) {
opt_userAgent = goog.debug.DevCss.UserAgent.MOBILE;
} else if (goog.userAgent.OPERA) {
opt_userAgent = goog.debug.DevCss.UserAgent.OPERA;
}
}
switch (opt_userAgent) {
case goog.debug.DevCss.UserAgent.OPERA:
case goog.debug.DevCss.UserAgent.IE:
case goog.debug.DevCss.UserAgent.GECKO:
case goog.debug.DevCss.UserAgent.FIREFOX:
case goog.debug.DevCss.UserAgent.WEBKIT:
case goog.debug.DevCss.UserAgent.SAFARI:
case goog.debug.DevCss.UserAgent.MOBILE:
break;
default:
throw Error('Could not determine the user agent from known UserAgents');
}
/**
* One of goog.debug.DevCss.UserAgent.
* @type {string}
* @private
*/
this.userAgent_ = opt_userAgent;
/**
* @type {Object}
* @private
*/
this.userAgentTokens_ = {};
/**
* @type {number|string}
* @private
*/
this.userAgentVersion_ = opt_userAgentVersion || goog.userAgent.VERSION;
this.generateUserAgentTokens_();
/**
* @type {boolean}
* @private
*/
this.isIe6OrLess_ = this.userAgent_ == goog.debug.DevCss.UserAgent.IE &&
goog.string.compareVersions('7', this.userAgentVersion_) > 0;
if (this.isIe6OrLess_) {
/**
* @type {Array<{classNames,combinedClassName,els}>}
* @private
*/
this.ie6CombinedMatches_ = [];
}
};
/**
* Rewrites the CSSOM as needed to activate any useragent-specific selectors.
* @param {boolean=} opt_enableIe6ReadyHandler If true(the default), and the
* userAgent is ie6, we set a document "ready" event handler to walk the DOM
* and make combined selector className changes. Having this parameter also
* aids unit testing.
*/
goog.debug.DevCss.prototype.activateBrowserSpecificCssRules = function(
opt_enableIe6ReadyHandler) {
var enableIe6EventHandler = goog.isDef(opt_enableIe6ReadyHandler) ?
opt_enableIe6ReadyHandler : true;
var cssRules = goog.cssom.getAllCssStyleRules();
for (var i = 0, cssRule; cssRule = cssRules[i]; i++) {
this.replaceBrowserSpecificClassNames_(cssRule);
}
// Since we may have manipulated the rules above, we'll have to do a
// complete sweep again if we're in IE6. Luckily performance doesn't
// matter for this tool.
if (this.isIe6OrLess_) {
cssRules = goog.cssom.getAllCssStyleRules();
for (var i = 0, cssRule; cssRule = cssRules[i]; i++) {
this.replaceIe6CombinedSelectors_(cssRule);
}
}
// Add an event listener for document ready to rewrite any necessary
// combined classnames in IE6.
if (this.isIe6OrLess_ && enableIe6EventHandler) {
goog.events.listen(document, goog.events.EventType.LOAD, goog.bind(
this.addIe6CombinedClassNames_, this));
}
};
/**
* A list of possible user agent strings.
* @enum {string}
*/
goog.debug.DevCss.UserAgent = {
OPERA: 'OPERA',
IE: 'IE',
GECKO: 'GECKO',
FIREFOX: 'GECKO',
WEBKIT: 'WEBKIT',
SAFARI: 'WEBKIT',
MOBILE: 'MOBILE'
};
/**
* A list of strings that may be used for matching in CSS files/development.
* @enum {string}
* @private
*/
goog.debug.DevCss.CssToken_ = {
USERAGENT: 'USERAGENT',
SEPARATOR: '-',
LESS_THAN: 'LT',
GREATER_THAN: 'GT',
LESS_THAN_OR_EQUAL: 'LTE',
GREATER_THAN_OR_EQUAL: 'GTE',
IE6_SELECTOR_TEXT: 'goog-ie6-selector',
IE6_COMBINED_GLUE: '_'
};
/**
* Generates user agent token match strings with comparison and version bits.
* For example:
* userAgentTokens_.ANY will be like 'GECKO'
* userAgentTokens_.LESS_THAN will be like 'GECKO-LT3' etc...
* @private
*/
goog.debug.DevCss.prototype.generateUserAgentTokens_ = function() {
this.userAgentTokens_.ANY = goog.debug.DevCss.CssToken_.USERAGENT +
goog.debug.DevCss.CssToken_.SEPARATOR + this.userAgent_;
this.userAgentTokens_.EQUALS = this.userAgentTokens_.ANY +
goog.debug.DevCss.CssToken_.SEPARATOR;
this.userAgentTokens_.LESS_THAN = this.userAgentTokens_.ANY +
goog.debug.DevCss.CssToken_.SEPARATOR +
goog.debug.DevCss.CssToken_.LESS_THAN;
this.userAgentTokens_.LESS_THAN_OR_EQUAL = this.userAgentTokens_.ANY +
goog.debug.DevCss.CssToken_.SEPARATOR +
goog.debug.DevCss.CssToken_.LESS_THAN_OR_EQUAL;
this.userAgentTokens_.GREATER_THAN = this.userAgentTokens_.ANY +
goog.debug.DevCss.CssToken_.SEPARATOR +
goog.debug.DevCss.CssToken_.GREATER_THAN;
this.userAgentTokens_.GREATER_THAN_OR_EQUAL = this.userAgentTokens_.ANY +
goog.debug.DevCss.CssToken_.SEPARATOR +
goog.debug.DevCss.CssToken_.GREATER_THAN_OR_EQUAL;
};
/**
* Gets the version number bit from a selector matching userAgentToken.
* @param {string} selectorText The selector text of a CSS rule.
* @param {string} userAgentToken Includes the LTE/GTE bit to see if it matches.
* @return {string|undefined} The version number.
* @private
*/
goog.debug.DevCss.prototype.getVersionNumberFromSelectorText_ = function(
selectorText, userAgentToken) {
var regex = new RegExp(userAgentToken + '([\\d\\.]+)');
var matches = regex.exec(selectorText);
if (matches && matches.length == 2) {
return matches[1];
}
};
/**
* Extracts a rule version from the selector text, and if it finds one, calls
* compareVersions against it and the passed in token string to provide the
* value needed to determine if we have a match or not.
* @param {CSSRule} cssRule The rule to test against.
* @param {string} token The match token to test against the rule.
* @return {!Array|undefined} A tuple with the result of the compareVersions
* call and the matched ruleVersion.
* @private
*/
goog.debug.DevCss.prototype.getRuleVersionAndCompare_ = function(cssRule,
token) {
if (!cssRule.selectorText.match(token)) {
return;
}
var ruleVersion = this.getVersionNumberFromSelectorText_(
cssRule.selectorText, token);
if (!ruleVersion) {
return;
}
var comparison = goog.string.compareVersions(this.userAgentVersion_,
ruleVersion);
return [comparison, ruleVersion];
};
/**
* Replaces a CSS selector if we have matches based on our useragent/version.
* Example: With a selector like ".USERAGENT-IE-LTE6 .class { prop: value }" if
* we are running IE6 we'll end up with ".class { prop: value }", thereby
* "activating" the selector.
* @param {CSSRule} cssRule The cssRule to potentially replace.
* @private
*/
goog.debug.DevCss.prototype.replaceBrowserSpecificClassNames_ = function(
cssRule) {
// If we don't match the browser token, we can stop now.
if (!cssRule.selectorText.match(this.userAgentTokens_.ANY)) {
return;
}
// We know it will begin as a classname.
var additionalRegexString;
// Tests "Less than or equals".
var compared = this.getRuleVersionAndCompare_(cssRule,
this.userAgentTokens_.LESS_THAN_OR_EQUAL);
if (compared && compared.length) {
if (compared[0] > 0) {
return;
}
additionalRegexString = this.userAgentTokens_.LESS_THAN_OR_EQUAL +
compared[1];
}
// Tests "Less than".
compared = this.getRuleVersionAndCompare_(cssRule,
this.userAgentTokens_.LESS_THAN);
if (compared && compared.length) {
if (compared[0] > -1) {
return;
}
additionalRegexString = this.userAgentTokens_.LESS_THAN + compared[1];
}
// Tests "Greater than or equals".
compared = this.getRuleVersionAndCompare_(cssRule,
this.userAgentTokens_.GREATER_THAN_OR_EQUAL);
if (compared && compared.length) {
if (compared[0] < 0) {
return;
}
additionalRegexString = this.userAgentTokens_.GREATER_THAN_OR_EQUAL +
compared[1];
}
// Tests "Greater than".
compared = this.getRuleVersionAndCompare_(cssRule,
this.userAgentTokens_.GREATER_THAN);
if (compared && compared.length) {
if (compared[0] < 1) {
return;
}
additionalRegexString = this.userAgentTokens_.GREATER_THAN + compared[1];
}
// Tests "Equals".
compared = this.getRuleVersionAndCompare_(cssRule,
this.userAgentTokens_.EQUALS);
if (compared && compared.length) {
if (compared[0] != 0) {
return;
}
additionalRegexString = this.userAgentTokens_.EQUALS + compared[1];
}
// If we got to here without generating the additionalRegexString, then
// we did not match any of our comparison token strings, and we want a
// general browser token replacement.
if (!additionalRegexString) {
additionalRegexString = this.userAgentTokens_.ANY;
}
// We need to match at least a single whitespace character to know that
// we are matching the entire useragent string token.
var regexString = '\\.' + additionalRegexString + '\\s+';
var re = new RegExp(regexString, 'g');
var currentCssText = goog.cssom.getCssTextFromCssRule(cssRule);
// Replacing the token with '' activates the selector for this useragent.
var newCssText = currentCssText.replace(re, '');
if (newCssText != currentCssText) {
goog.cssom.replaceCssRule(cssRule, newCssText);
}
};
/**
* Replaces IE6 combined selector rules with a workable development alternative.
* IE6 actually parses .class1.class2 {} to simply .class2 {} which is nasty.
* To fully support combined selectors in IE6 this function needs to be paired
* with a call to replace the relevant DOM elements classNames as well.
* @see {this.addIe6CombinedClassNames_}
* @param {CSSRule} cssRule The rule to potentially fix.
* @private
*/
goog.debug.DevCss.prototype.replaceIe6CombinedSelectors_ = function(cssRule) {
// This match only ever works in IE because other UA's won't have our
// IE6_SELECTOR_TEXT in the cssText property.
if (cssRule.style.cssText &&
cssRule.style.cssText.match(
goog.debug.DevCss.CssToken_.IE6_SELECTOR_TEXT)) {
var cssText = goog.cssom.getCssTextFromCssRule(cssRule);
var combinedSelectorText = this.getIe6CombinedSelectorText_(cssText);
if (combinedSelectorText) {
var newCssText = combinedSelectorText + '{' + cssRule.style.cssText + '}';
goog.cssom.replaceCssRule(cssRule, newCssText);
}
}
};
/**
* Gets the appropriate new combined selector text for IE6.
* Also adds an entry onto ie6CombinedMatches_ with relevant info for the
* likely following call to walk the DOM and rewrite the class attribute.
* Example: With a selector like
* ".class2 { -goog-ie6-selector: .class1.class2; prop: value }".
* this function will return:
* ".class1_class2 { prop: value }".
* @param {string} cssText The CSS selector text and css rule text combined.
* @return {?string} The rewritten css rule text.
* @private
*/
goog.debug.DevCss.prototype.getIe6CombinedSelectorText_ = function(cssText) {
var regex = new RegExp(goog.debug.DevCss.CssToken_.IE6_SELECTOR_TEXT +
'\\s*:\\s*\\"([^\\"]+)\\"', 'gi');
var matches = regex.exec(cssText);
if (matches) {
var combinedSelectorText = matches[1];
// To aid in later fixing the DOM, we need to split up the possible
// selector groups by commas.
var groupedSelectors = combinedSelectorText.split(/\s*\,\s*/);
for (var i = 0, selector; selector = groupedSelectors[i]; i++) {
// Strips off the leading ".".
var combinedClassName = selector.substr(1);
var classNames = combinedClassName.split(
goog.debug.DevCss.CssToken_.IE6_COMBINED_GLUE);
var entry = {
classNames: classNames,
combinedClassName: combinedClassName,
els: []
};
this.ie6CombinedMatches_.push(entry);
}
return combinedSelectorText;
}
return null;
};
/**
* Adds combined selectors with underscores to make them "work" in IE6.
* @see {this.replaceIe6CombinedSelectors_}
* @private
*/
goog.debug.DevCss.prototype.addIe6CombinedClassNames_ = function() {
if (!this.ie6CombinedMatches_.length) {
return;
}
var allEls = document.getElementsByTagName('*');
var matches = [];
// Match nodes for all classNames.
for (var i = 0, classNameEntry; classNameEntry =
this.ie6CombinedMatches_[i]; i++) {
for (var j = 0, el; el = allEls[j]; j++) {
var classNamesLength = classNameEntry.classNames.length;
for (var k = 0, className; className = classNameEntry.classNames[k];
k++) {
if (!goog.dom.classlist.contains(goog.asserts.assert(el), className)) {
break;
}
if (k == classNamesLength - 1) {
classNameEntry.els.push(el);
}
}
}
// Walks over our matching nodes and fixes them.
if (classNameEntry.els.length) {
for (var j = 0, el; el = classNameEntry.els[j]; j++) {
goog.asserts.assert(el);
if (!goog.dom.classlist.contains(el,
classNameEntry.combinedClassName)) {
goog.dom.classlist.add(el, classNameEntry.combinedClassName);
}
}
}
}
};
| pulkitsinghal/selenium | third_party/closure/goog/debug/devcss/devcss.js | JavaScript | apache-2.0 | 14,953 |
JSIL.loadGlobalScript = function (uri, onComplete, dllName) {
var anchor = document.createElement("a");
anchor.href = uri;
var absoluteUri = anchor.href;
var done = false;
var body = document.getElementsByTagName("body")[0];
var scriptTag = document.createElement("script");
JSIL.Browser.RegisterOneShotEventListener(
scriptTag, "load", true,
function ScriptTag_Load (e) {
if (dllName)
JSIL.EndLoadNativeLibrary(dllName);
if (done)
return;
done = true;
onComplete(scriptTag, null);
}
);
JSIL.Browser.RegisterOneShotEventListener(
scriptTag, "error", true,
function ScriptTag_Error (e) {
if (dllName)
JSIL.EndLoadNativeLibrary(dllName);
if (done)
return;
done = true;
onComplete(null, e);
}
);
scriptTag.type = "text/javascript";
scriptTag.src = absoluteUri;
try {
if (dllName)
JSIL.BeginLoadNativeLibrary(dllName);
body.appendChild(scriptTag);
} catch (exc) {
done = true;
onComplete(null, exc);
}
};
var warnedAboutOpera = false;
var warnedAboutCORS = false;
var warnedAboutCORSImage = false;
var hasCORSXhr = false, hasCORSImage = false;
function getAbsoluteUrl (localUrl) {
var temp = document.createElement("a");
temp.href = localUrl;
return temp.href;
};
function doXHR (uri, asBinary, onComplete) {
var req = null, isXDR = false;
var needCORS = jsilConfig.CORS;
var urlPrefix = window.location.protocol + "//" + window.location.host + "/";
var absoluteUrl = getAbsoluteUrl(uri);
var sameHost = (absoluteUrl.indexOf(urlPrefix) >= 0);
needCORS = needCORS && !sameHost;
if (location.protocol === "file:") {
var errorText = "Loading assets from file:// is not possible in modern web browsers. You must host your application on a web server.";
if (console && console.error) {
console.error(errorText + "\nFailed to load: " + uri);
onComplete(null, errorText);
return;
} else {
throw new Error(errorText);
}
} else {
req = new XMLHttpRequest();
if (needCORS && !("withCredentials" in req)) {
if ((!asBinary) && (typeof (XDomainRequest) !== "undefined")) {
isXDR = true;
req = new XDomainRequest();
} else {
if (!warnedAboutCORS) {
JSIL.Host.logWriteLine("WARNING: This application requires support for CORS, and your browser does not appear to have it. Loading may fail.");
warnedAboutCORS = true;
}
onComplete(null, "CORS unavailable");
return;
}
}
}
var isDone = false;
var releaseEventListeners = function () {
req.onprogress = null;
req.onload = null;
req.onerror = null;
req.ontimeout = null;
req.onreadystatechange = null;
};
var succeeded = function (response, status, statusText) {
if (isDone)
return;
isDone = true;
releaseEventListeners();
if (status >= 400) {
onComplete(
{
response: response,
status: status,
statusText: statusText
},
statusText || status
);
} else {
onComplete(
{
response: response,
status: status,
statusText: statusText
}, null
);
}
};
var failed = function (error) {
if (isDone)
return;
isDone = true;
releaseEventListeners();
onComplete(null, error);
};
if (isXDR) {
// http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/30ef3add-767c-4436-b8a9-f1ca19b4812e
req.onprogress = function () {};
req.onload = function () {
succeeded(req.responseText);
};
req.onerror = function () {
failed("Unknown error");
};
req.ontimeout = function () {
failed("Timed out");
};
} else {
req.onreadystatechange = function (evt) {
if (req.readyState != 4)
return;
if (isDone)
return;
if (asBinary) {
var bytes;
var ieResponseBody = null;
try {
if (
(typeof (ArrayBuffer) === "function") &&
(typeof (req.response) === "object") &&
(req.response !== null)
) {
var buffer = req.response;
bytes = new Uint8Array(buffer);
} else if (
(typeof (VBArray) !== "undefined") &&
("responseBody" in req) &&
((ieResponseBody = new VBArray(req.responseBody).toArray()) != null)
) {
bytes = ieResponseBody;
} else if (req.responseText) {
var text = req.responseText;
bytes = JSIL.StringToByteArray(text);
} else {
failed("Unknown error");
return;
}
} catch (exc) {
failed(exc);
return;
}
succeeded(bytes, req.status, req.statusText);
} else {
try {
var responseText = req.responseText;
} catch (exc) {
failed(exc);
return;
}
succeeded(responseText, req.status, req.statusText);
}
};
}
try {
if (isXDR) {
req.open('GET', uri);
} else {
req.open('GET', uri, true);
}
} catch (exc) {
failed(exc);
}
if (asBinary) {
if (typeof (ArrayBuffer) === "function") {
req.responseType = 'arraybuffer';
}
if (typeof (req.overrideMimeType) !== "undefined") {
req.overrideMimeType('application/octet-stream; charset=x-user-defined');
} else {
req.setRequestHeader('Accept-Charset', 'x-user-defined');
}
} else {
if (typeof (req.overrideMimeType) !== "undefined") {
req.overrideMimeType('text/plain; charset=x-user-defined');
} else {
req.setRequestHeader('Accept-Charset', 'x-user-defined');
}
}
try {
if (isXDR) {
req.send(null);
} else {
req.send();
}
} catch (exc) {
failed(exc);
}
};
function loadTextAsync (uri, onComplete) {
return doXHR(uri, false, function (result, error) {
if (result)
onComplete(result.response, error);
else
onComplete(null, error);
});
};
function postProcessResultNormal (bytes) {
return bytes;
};
function postProcessResultOpera (bytes) {
// Opera sniffs content types on request bodies and if they're text, converts them to 16-bit unicode :|
if (
(bytes[1] === 0) &&
(bytes[3] === 0) &&
(bytes[5] === 0) &&
(bytes[7] === 0)
) {
if (!warnedAboutOpera) {
JSIL.Host.logWriteLine("WARNING: Your version of Opera has a bug that corrupts downloaded file data. Please update to a new version or try a better browser.");
warnedAboutOpera = true;
}
var resultBytes = new Array(bytes.length / 2);
for (var i = 0, j = 0, l = bytes.length; i < l; i += 2, j += 1) {
resultBytes[j] = bytes[i];
}
return resultBytes;
} else {
return bytes;
}
};
function loadBinaryFileAsync (uri, onComplete) {
var postProcessResult = postProcessResultNormal;
if (window.navigator.userAgent.indexOf("Opera/") >= 0) {
postProcessResult = postProcessResultOpera;
}
return doXHR(uri, true, function (result, error) {
if (result)
onComplete(postProcessResult(result.response), error);
else
onComplete(null, error);
});
}
var finishLoadingScript = function (state, path, onError, dllName) {
state.pendingScriptLoads += 1;
JSIL.loadGlobalScript(path, function (result, error) {
state.pendingScriptLoads -= 1;
if (error) {
var errorText = "Network request failed: " + stringifyLoadError(error);
state.assetLoadFailures.push(
[path, errorText]
);
if (jsilConfig.onLoadFailure) {
try {
jsilConfig.onLoadFailure(path, errorText);
} catch (exc2) {
}
}
onError(errorText);
}
}, dllName);
};
var loadScriptInternal = function (uri, onError, onDoneLoading, state, dllName) {
var absoluteUrl = getAbsoluteUrl(uri);
var finisher = function () {
finishLoadingScript(state, uri, onError, dllName);
};
if (absoluteUrl.indexOf("file://") === 0) {
// No browser properly supports XHR against file://
onDoneLoading(finisher);
} else {
loadTextAsync(uri, function (result, error) {
if ((result !== null) && (!error))
onDoneLoading(finisher);
else
onError(error);
});
}
};
var assetLoaders = {
"Library": function loadLibrary (filename, data, onError, onDoneLoading, state) {
if (state.jsilInitialized)
throw new Error("A library was loaded after JSIL initialization");
var uri = jsilConfig.libraryRoot + filename;
loadScriptInternal(uri, onError, onDoneLoading, state);
},
"NativeLibrary": function loadNativeLibrary (filename, data, onError, onDoneLoading, state) {
if (state.jsilInitialized)
throw new Error("A script was loaded after JSIL initialization");
var uri = jsilConfig.libraryRoot + filename;
loadScriptInternal(uri, onError, onDoneLoading, state, filename);
},
"Script": function loadScript (filename, data, onError, onDoneLoading, state) {
if (state.jsilInitialized)
throw new Error("A script was loaded after JSIL initialization");
var uri = jsilConfig.scriptRoot + filename;
loadScriptInternal(uri, onError, onDoneLoading, state);
},
"Image": function loadImage (filename, data, onError, onDoneLoading) {
var e = document.createElement("img");
if (jsilConfig.CORS) {
if (hasCORSImage) {
e.crossOrigin = "";
} else if (hasCORSXhr && ($blobBuilderInfo.hasBlobBuilder || $blobBuilderInfo.hasBlobCtor)) {
if (!warnedAboutCORSImage) {
JSIL.Host.logWriteLine("WARNING: This application requires support for CORS, and your browser does not support it for images. Using workaround...");
warnedAboutCORSImage = true;
}
return loadImageCORSHack(filename, data, onError, onDoneLoading);
} else {
if (!warnedAboutCORSImage) {
JSIL.Host.logWriteLine("WARNING: This application requires support for CORS, and your browser does not support it.");
warnedAboutCORSImage = true;
}
onError("CORS unavailable");
return;
}
}
var finisher = function () {
$jsilbrowserstate.allAssetNames.push(filename);
allAssets[getAssetName(filename)] = new HTML5ImageAsset(getAssetName(filename, true), e);
};
JSIL.Browser.RegisterOneShotEventListener(e, "error", true, onError);
JSIL.Browser.RegisterOneShotEventListener(e, "load", true, onDoneLoading.bind(null, finisher));
e.src = jsilConfig.contentRoot + filename;
},
"File": function loadFile (filename, data, onError, onDoneLoading) {
loadBinaryFileAsync(jsilConfig.fileRoot + filename, function (result, error) {
if ((result !== null) && (!error)) {
$jsilbrowserstate.allFileNames.push(filename);
allFiles[filename.toLowerCase()] = result;
onDoneLoading(null);
} else {
onError(error);
}
});
},
"SoundBank": function loadSoundBank (filename, data, onError, onDoneLoading) {
loadTextAsync(jsilConfig.contentRoot + filename, function (result, error) {
if ((result !== null) && (!error)) {
var finisher = function () {
$jsilbrowserstate.allAssetNames.push(filename);
allAssets[getAssetName(filename)] = JSON.parse(result);
};
onDoneLoading(finisher);
} else {
onError(error);
}
});
},
"Resources": function loadResources (filename, data, onError, onDoneLoading) {
loadTextAsync(jsilConfig.scriptRoot + filename, function (result, error) {
if ((result !== null) && (!error)) {
var finisher = function () {
$jsilbrowserstate.allAssetNames.push(filename);
allAssets[getAssetName(filename)] = JSON.parse(result);
};
onDoneLoading(finisher);
} else {
onError(error);
}
});
},
"ManifestResource": function loadManifestResourceStream (filename, data, onError, onDoneLoading) {
loadBinaryFileAsync(jsilConfig.scriptRoot + filename, function (result, error) {
if ((result !== null) && (!error)) {
var dict = allManifestResources[data.assembly];
if (!dict)
dict = allManifestResources[data.assembly] = Object.create(null);
dict[filename.toLowerCase()] = result;
onDoneLoading(null);
} else {
onError(error);
}
});
}
};
function $makeXNBAssetLoader (key, typeName) {
assetLoaders[key] = function (filename, data, onError, onDoneLoading) {
loadBinaryFileAsync(jsilConfig.contentRoot + filename, function (result, error) {
if ((result !== null) && (!error)) {
var finisher = function () {
$jsilbrowserstate.allAssetNames.push(filename);
var key = getAssetName(filename, false);
var assetName = getAssetName(filename, true);
var parsedTypeName = JSIL.ParseTypeName(typeName);
var type = JSIL.GetTypeInternal(parsedTypeName, JSIL.GlobalNamespace, true);
allAssets[key] = JSIL.CreateInstanceOfType(type, "_ctor", [assetName, result]);
};
onDoneLoading(finisher);
} else {
onError(error);
}
});
};
};
function loadImageCORSHack (filename, data, onError, onDoneLoading) {
var sourceURL = jsilConfig.contentRoot + filename;
// FIXME: Pass mime type through from original XHR somehow?
var mimeType = "application/octet-stream";
var sourceURLLower = sourceURL.toLowerCase();
if (sourceURLLower.indexOf(".png") >= 0) {
mimeType = "image/png";
} else if (
(sourceURLLower.indexOf(".jpg") >= 0) ||
(sourceURLLower.indexOf(".jpeg") >= 0)
) {
mimeType = "image/jpeg";
}
loadBinaryFileAsync(sourceURL, function (result, error) {
if ((result !== null) && (!error)) {
var objectURL = null;
try {
objectURL = JSIL.GetObjectURLForBytes(result, mimeType);
} catch (exc) {
onError(exc);
return;
}
var e = document.createElement("img");
var finisher = function () {
$jsilbrowserstate.allAssetNames.push(filename);
allAssets[getAssetName(filename)] = new HTML5ImageAsset(getAssetName(filename, true), e);
};
JSIL.Browser.RegisterOneShotEventListener(e, "error", true, onError);
JSIL.Browser.RegisterOneShotEventListener(e, "load", true, onDoneLoading.bind(null, finisher));
e.src = objectURL;
} else {
onError(error);
}
});
};
function initCORSHack () {
hasCORSXhr = false;
hasCORSImage = false;
try {
var xhr = new XMLHttpRequest();
hasCORSXhr = xhr && ("withCredentials" in xhr);
} catch (exc) {
}
try {
var img = document.createElement("img");
hasCORSImage = img && ("crossOrigin" in img);
} catch (exc) {
}
}
function initAssetLoaders () {
JSIL.InitBlobBuilder();
initCORSHack();
initSoundLoader();
$makeXNBAssetLoader("XNB", "RawXNBAsset");
$makeXNBAssetLoader("SpriteFont", "SpriteFontAsset");
$makeXNBAssetLoader("Texture2D", "Texture2DAsset");
}; | Durwella/TryJSIL | packages/JSIL/Libraries/JSIL.Browser.Loaders.js | JavaScript | mit | 15,244 |
/* global require,module */
'use strict';
var utils = require('./utils');
var Resource = require('./resource');
var CssParser = require('./css-parser');
var HtmlParser = require('./html-parser');
var Promise = require('./promise');
var push = Array.prototype.push;
function Spider (htmlFiles, options) {
options = utils.options(Spider.defaults, options);
// 支持单个 HTML 地址传入
if (typeof htmlFiles === 'string') {
htmlFiles = [htmlFiles];
}
// 处理多个 HTML,这些 HTML 文件可能会引用相同的 CSS
return Promise.all(htmlFiles.map(function (htmlFile) {
return new Spider.Parser(htmlFile, options);
})).then(function (list) {
var webFonts = [];
var chars = {};
var unique = {};
utils.reduce(list).forEach(function (font) {
var charsCache = chars[font.id];
if (charsCache) {
// 合并多个页面查询到的字符
push.apply(charsCache, font.chars);
} else if (!unique[font.id]) {
unique[font.id] = true;
chars[font.id] = font.chars;
webFonts.push(new Spider.Model(
font.id,
font.family,
font.files,
font.chars,
font.selectors
));
}
});
webFonts.forEach(function (font) {
font.chars = chars[font.id];
// 对字符进行除重操作
if (options.unique) {
font.chars = utils.unique(font.chars);
}
// 对字符按照编码进行排序
if (options.sort) {
font.chars.sort(sort);
}
// 将数组转成字符串并删除无用字符
font.chars = font.chars.join('').replace(/[\n\r\t]/g, '');
});
return webFonts;
function sort (a, b) {
return a.charCodeAt() - b.charCodeAt();
}
});
}
Spider.Model = function WebFont (id, name, files, chars, selectors) {
this.id = id;
this.name = name;
this.files = files;
this.chars = chars;
this.selectors = selectors;
};
/*
* 解析 HTML
* @param {String} 文件绝对路径
* @return {Promise}
*/
Spider.Parser = function (htmlFile, options) {
return new Promise(function (resolve, reject) {
var resource;
var isBuffer = typeof htmlFile === 'object' && htmlFile.isBuffer();
if (isBuffer) {
resource = resolve(new Resource.Model(
htmlFile.path,
htmlFile.contents.toString(),
utils.options(options, {
from: 'Node',
cache: false
})
));
htmlFile = htmlFile.path;
} else {
resource = new Resource(
htmlFile,
null,
utils.options(options, {
from: 'Node',
cache: false
}
));
}
this.options = options;
var spiderBeforeLoad = options.spiderBeforeLoad;
var spiderLoad = options.spiderLoad;
var spiderError = options.spiderError;
spiderBeforeLoad(htmlFile);
new HtmlParser(resource)
.then(function (htmlParser) {
this.htmlParser = htmlParser;
this.htmlFile = htmlFile;
return htmlParser;
}.bind(this))
.then(this.getCssInfo.bind(this))
.then(this.getFontInfo.bind(this))
.then(this.getCharsInfo.bind(this))
.then(function (webFonts) {
spiderLoad(htmlFile);
resolve(webFonts);
})
.catch(function (errors) {
spiderError(htmlFile, errors);
reject(errors);
});
}.bind(this));
};
Spider.Parser.prototype = {
constructor: Spider.Parser,
/*
* 获取当前页面 link 标签与 style 标签的 CSS 解析结果
* @return {Promise} Array<CssParser.Model>
*/
getCssInfo: function () {
var htmlFile = this.htmlFile;
var htmlParser = this.htmlParser;
var options = this.options;
var resources = [];
// 获取外链样式资源
var cssFiles = htmlParser.getCssFiles();
// 获取 style 标签内容资源
var cssContents = htmlParser.getCssContents();
cssFiles.forEach(function (cssFile, index) {
if (!cssFile) {
return;
}
var line = index + 1;
var from = 'link:nth-of-type(' + line + ')';
resources.push(
new Resource(
cssFile,
null,
utils.options(options, {
cache: true,
from: from
})
)
);
});
cssContents.forEach(function (content, index) {
if (!content) {
return;
}
var line = index + 1;
var from = 'style:nth-of-type(' + line + ')';
var cssFile = htmlFile + '#' + from;
resources.push(
new Resource(
cssFile,
content,
utils.options(options, {
cache: false,
from: from
})
)
);
});
return Promise.all(resources.map(function (resource) {
return new CssParser(resource);
}))
// 对二维数组扁平化处理
.then(utils.reduce);
},
/*
* 分析 CSS 中的字体相关信息
*/
getFontInfo: function (cssInfo) {
var webFonts = [];
var styleRules = [];
// 分离 @font-face 数据与选择器数据
cssInfo.forEach(function (item) {
if (item.type === 'CSSFontFaceRule') {
webFonts.push(item);
} else if (item.type === 'CSSStyleRule') {
styleRules.push(item);
}
});
// 匹配选择器与 @font-face 定义的字体
webFonts.forEach(function (fontFace) {
styleRules.forEach(function (styleRule) {
if (styleRule.id.indexOf(fontFace.id) !== -1) {
push.apply(fontFace.selectors, styleRule.selectors);
fontFace.selectors = utils.unique(fontFace.selectors);
// css content 属性收集的字符
push.apply(fontFace.chars, styleRule.chars);
}
});
});
return webFonts;
},
getCharsInfo: function (webFonts) {
var that = this;
webFonts.forEach(function (fontFace) {
var selector = fontFace.selectors.join(', ');
var chars = that.htmlParser.querySelectorChars(selector);
push.apply(fontFace.chars, chars);
});
return webFonts;
}
};
/*
* 默认选项
*/
Spider.defaults = {
spiderBeforeLoad: function () {},
spiderLoad: function () {},
spiderError: function () {},
debug: false,
sort: true, // 是否将查询到的文本按字体中字符的顺序排列
unique: true // 是否去除重复字符
};
utils.mix(Spider.defaults, CssParser.defaults);
utils.mix(Spider.defaults, HtmlParser.defaults);
utils.mix(Spider.defaults, Resource.defaults);
module.exports = Spider; | hongtao008/font-spider | src/spider/index.js | JavaScript | mit | 7,676 |
<!-- //HORA
var popUpWin=0;
function popUpWindow(URLStr, yes, left, top, width, height){
if(popUpWin){
if(!popUpWin.closed)
popUpWin.close();
}
popUpWin = open(URLStr, 'popUpWin', 'resizable=no,scrollbars='+yes+',menubar=no,toolbar=no,status=no,location=no,titlebar=no,directories=no", width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
}
//--> | jairolh/hermes | funcion/ventana.js | JavaScript | gpl-2.0 | 416 |
var here = require('kcd-common-tools/utils/here');
module.exports = {
output: { library: 'ngFormlyTemplatesBootstrap' },
externals: {
angular: 'angular',
'angular-formly': {
root: 'ngFormly',
amd: 'angular-formly',
commonjs2: 'angular-formly',
commonjs: 'angular-formly'
},
'api-check': {
root: 'apiCheck',
amd: 'api-check',
commonjs2: 'api-check',
commonjs: 'api-check'
}
},
resolve: {
alias: {
'angular-fix': here('src/angular-fix')
}
}
};
| hubz00/PlanPlanet | src/main/resources/static/node_modules/angular-formly-templates-bootstrap/scripts/webpack-overrides.js | JavaScript | apache-2.0 | 535 |
//// [sourceMap-FileWithComments.ts]
// Interface
interface IPoint {
getDist(): number;
}
// Module
module Shapes {
// Class
export class Point implements IPoint {
// Constructor
constructor(public x: number, public y: number) { }
// Instance member
getDist() { return Math.sqrt(this.x * this.x + this.y * this.y); }
// Static member
static origin = new Point(0, 0);
}
// Variable comment after class
var a = 10;
export function foo() {
}
/** comment after function
* this is another comment
*/
var b = 10;
}
/** Local Variable */
var p: IPoint = new Shapes.Point(3, 4);
var dist = p.getDist();
//// [sourceMap-FileWithComments.js]
// Module
var Shapes;
(function (Shapes) {
// Class
var Point = /** @class */ (function () {
// Constructor
function Point(x, y) {
this.x = x;
this.y = y;
}
// Instance member
Point.prototype.getDist = function () { return Math.sqrt(this.x * this.x + this.y * this.y); };
// Static member
Point.origin = new Point(0, 0);
return Point;
}());
Shapes.Point = Point;
// Variable comment after class
var a = 10;
function foo() {
}
Shapes.foo = foo;
/** comment after function
* this is another comment
*/
var b = 10;
})(Shapes || (Shapes = {}));
/** Local Variable */
var p = new Shapes.Point(3, 4);
var dist = p.getDist();
//# sourceMappingURL=sourceMap-FileWithComments.js.map | basarat/TypeScript | tests/baselines/reference/sourceMap-FileWithComments.js | JavaScript | apache-2.0 | 1,587 |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
var request = require('request'),
express = require('express'),
url = require('url'),
colors = require('colors'),
cors = require('connect-xcors'),
server = require('./index'),
conf = require('./conf');
colors.mode = "console";
// TODO: Yes, we know. The API token is a joke.
function authenticated(key) {
return key === "ABC";
}
function contentIsXML(contentType) {
return !!(contentType && contentType.match(/xml/));
}
function getUserAgent(req, proxyReqHeaders) {
var userAgent;
if (proxyReqHeaders["x-ripple-user-agent"]) {
userAgent = proxyReqHeaders["x-ripple-user-agent"];
delete proxyReqHeaders["x-ripple-user-agent"];
} else if (req.query.ripple_user_agent) {
userAgent = unescape(req.query.ripple_user_agent);
} else {
userAgent = proxyReqHeaders["user-agent"];
}
return userAgent;
}
function proxy(req, res, callback) {
var parsedURL = url.parse(unescape(req.query.tinyhippos_rurl)),
proxyReqData,
proxyReqHeaders,
proxyReq;
if (authenticated(req.query.tinyhippos_apikey)) {
console.log("INFO:".green + " Proxying cross origin XMLHttpRequest - " + parsedURL.href);
proxyReqHeaders = Object.keys(req.headers).reduce(function (headers, key) {
if (key !== "origin") {
headers[key] = req.headers[key];
}
return headers;
}, {});
proxyReqHeaders["host"] = parsedURL.host;
proxyReqHeaders["user-agent"] = getUserAgent(req, proxyReqHeaders);
// HACK: Makes https://google.com crash (issue with node? request? us?)
delete proxyReqHeaders["accept-encoding"];
proxyReqData = {
url: parsedURL,
method: req.method,
headers: proxyReqHeaders,
jar: false
};
if (Object.keys(req.body).length > 0) {
if (req.get("content-type") === "application/json") {
proxyReqData.body = JSON.stringify(req.body);
} else {
proxyReqData.form = req.body;
}
}
// Attempt to catch any sync errors
try {
proxyReq = request(proxyReqData, function (error, response, body) {
if (error) {
console.log("ERROR:".red + " Proxying failed with:", error);
res.send(500, error);
} else if (callback) {
callback(response, body);
}
});
// If no callback, use pipe (which means body & response objects are not needed post-request)
// The callback in request(... function (error) {}) (above) is still called when node http client hits unrecoverable error
if (!callback) {
proxyReq.pipe(res);
}
} catch (e) {
res.send(500, e.toString());
}
} else {
res.send(200, "You shall not pass!");
}
}
function xhrProxyHandler(req, res/*, next*/) {
proxy(req, res);
}
function jsonpXHRProxyHandler(req, res/*, next*/) {
var callbackMethod = req.query.callback;
proxy(req, res, function callback(response, body) {
var reqData = {
headers: response.headers,
status: response.statusCode,
response: body
};
if (contentIsXML(response.headers["content-type"])) {
reqData.responseXML = body;
} else {
reqData.responseText = body;
}
res.set("Content-Type", "application/json");
res.send(callbackMethod + "(" + JSON.stringify(reqData) + ");");
});
}
function start(options, app) {
var corsOptions = {
origins: ["*"],
methods: ['HEAD', 'GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'TRACE', 'CONNECT', 'PATCH'],
credentials: true,
headers: []
};
if (!options) { options = {}; }
if (!options.port) { options.port = conf.ports.proxy; }
if (!app) { app = server.start(options); }
if (!options.route) {
options.route = "";
} else if (!options.route.match(/^\//)) {
options.route = "/" + options.route;
}
app.use(function (req, res, next) {
var headers;
if (req.headers["access-control-request-headers"]) {
headers = req.headers["access-control-request-headers"].split(", ");
headers.forEach(function (header) {
if (!corsOptions.headers.some(function (h) {
return h === header;
})) {
corsOptions.headers.push(header);
}
});
}
next();
});
app.use(cors(corsOptions));
app.use(express.bodyParser());
app.all(options.route + "/xhr_proxy", xhrProxyHandler);
app.all(options.route + "/jsonp_xhr_proxy", jsonpXHRProxyHandler);
console.log("INFO:".green + " CORS XHR proxy service on: " +
("http://localhost:" + app._port + options.route + "/xhr_proxy").cyan);
console.log("INFO:".green + " JSONP XHR proxy service on: " +
("http://localhost:" + app._port + options.route + "/jsonp_xhr_proxy").cyan);
return app;
}
module.exports = {
start: start
};
| sangjin3/webida-server | src/server/notify/ext/incubator-ripple/lib/server/proxy.js | JavaScript | apache-2.0 | 6,090 |
// DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py.
// OffscreenCanvas test in a worker:2d.path.roundrect.3.radii.2.dompoint
// Description:Verify that when three radii are given to roundRect(), the second radius, specified as a DOMPoint, applies to the top-right and bottom-left corners.
// Note:
importScripts("/resources/testharness.js");
importScripts("/html/canvas/resources/canvas-tests.js");
var t = async_test("Verify that when three radii are given to roundRect(), the second radius, specified as a DOMPoint, applies to the top-right and bottom-left corners.");
var t_pass = t.done.bind(t);
var t_fail = t.step_func(function(reason) {
throw reason;
});
t.step(function() {
var canvas = new OffscreenCanvas(100, 50);
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#f00';
ctx.fillRect(0, 0, 100, 50);
ctx.roundRect(0, 0, 100, 50, [0, new DOMPoint(40, 20), 0]);
ctx.fillStyle = '#0f0';
ctx.fill();
// top-right corner
_assertPixel(canvas, 79,1, 255,0,0,255, "79,1", "255,0,0,255");
_assertPixel(canvas, 58,1, 0,255,0,255, "58,1", "0,255,0,255");
_assertPixel(canvas, 98,10, 255,0,0,255, "98,10", "255,0,0,255");
_assertPixel(canvas, 98,21, 0,255,0,255, "98,21", "0,255,0,255");
// bottom-left corner
_assertPixel(canvas, 20,48, 255,0,0,255, "20,48", "255,0,0,255");
_assertPixel(canvas, 41,48, 0,255,0,255, "41,48", "0,255,0,255");
_assertPixel(canvas, 1,39, 255,0,0,255, "1,39", "255,0,0,255");
_assertPixel(canvas, 1,28, 0,255,0,255, "1,28", "0,255,0,255");
// other corners
_assertPixel(canvas, 1,1, 0,255,0,255, "1,1", "0,255,0,255");
_assertPixel(canvas, 98,48, 0,255,0,255, "98,48", "0,255,0,255");
t.done();
});
done();
| chromium/chromium | third_party/blink/web_tests/external/wpt/html/canvas/offscreen/path-objects/2d.path.roundrect.3.radii.2.dompoint.worker.js | JavaScript | bsd-3-clause | 1,677 |
var inputNumber = document.getElementById('input-number');
html5Slider.noUiSlider.on('update', function( values, handle ) {
var value = values[handle];
if ( handle ) {
inputNumber.value = value;
} else {
select.value = Math.round(value);
}
});
select.addEventListener('change', function(){
html5Slider.noUiSlider.set([this.value, null]);
});
inputNumber.addEventListener('change', function(){
html5Slider.noUiSlider.set([null, this.value]);
});
| atlefren/beerdatabase | web/static/js/lib/nouislider/documentation/examples/html5-link.js | JavaScript | mit | 460 |
/*
* Copyright (c) 2015 Memorial Sloan-Kettering Cancer Center.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS
* FOR A PARTICULAR PURPOSE. The software and documentation provided hereunder
* is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no
* obligations to provide maintenance, support, updates, enhancements or
* modifications. In no event shall Memorial Sloan-Kettering Cancer Center be
* liable to any party for direct, indirect, special, incidental or
* consequential damages, including lost profits, arising out of the use of this
* software and its documentation, even if Memorial Sloan-Kettering Cancer
* Center has been advised of the possibility of such damage.
*/
/*
* This file is part of cBioPortal.
*
* cBioPortal is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Gideon Dresdner June 2013
//
// thanks Mike Bostock, http://bl.ocks.org/mbostock/4341954
;
// some utility functions for calculating kernel density estimates, a few
// kernel to try, and some helper functions for processing mutation allele data
// from the patient view
var AlleleFreqPlotUtils = (function() {
var NO_DATA = undefined; // this was set by the patient view
// params: alt_counts (array of numbers), ref_counts (array of numbers)
// returns array of numbers
//
// returns an array of alt_count / (alt_count + ref_count). If either
// alt_count or ref_count equal NO_DATA, then returns 0 in that entry
//
// or, if there is no valid data, returns `undefined`
var process_data = function(alt_counts, ref_counts, caseId) {
// validate:
// * that data exists
var validated = _.find(alt_counts, function(data) { return data[caseId]!==NO_DATA; });
if (!validated) {
return undefined;
}
return d3.zip(alt_counts, ref_counts).map(function(pair) {
return pair[0][caseId] === NO_DATA === pair[1][caseId] ? 0 : (pair[0][caseId] / (pair[0][caseId] + pair[1][caseId]));
});
};
// params: instance of GenomicEventObserver, from the patient view
//
// extracts the relevant data from the GenomicEventObserver and runs
// process_data
var extract_and_process = function(genomicEventObs, caseId) {
var alt_counts = genomicEventObs.mutations.data['alt-count'];
var ref_counts = genomicEventObs.mutations.data['ref-count'];
return process_data(alt_counts, ref_counts, caseId);
};
// params: variance, basically a smoothing parameter for this situation
//
// returns the gaussian function, aka kernel
var gaussianKernel = function(variance) {
var mean = 0;
return function(x) {
return (1 / (variance * Math.sqrt(2 * Math.PI)))
* Math.exp( -1 * Math.pow((x - mean), 2) / (2 * Math.pow(variance, 2)));
};
};
// params: kernel, list of points
//
// returns a function, call it kde, that takes a list of sample points, samples, and
// returns a list of pairs [x, y] where y is the average of
// kernel(sample - x)
// for all sample in samples
var kernelDensityEstimator = function(kernel, x) {
return function(sample) {
return x.map(function(z) {
return [z, d3.mean(sample, function(v) { return kernel(z - v); })];
});
};
};
// params: u, some number
// uniform kernel
var uniform = function(u) {
return Math.abs(u) <= 1 ? .5 * u : 0;
};
// Silverman's rule of thumb for calculating the bandwith parameter for
// kde with Gaussian kernel. Turns out that one can calculate the optimal
// bandwidth when using the Gaussian kernel (not a surprise). It turns out
// to basically be, a function of the variance of the data and the number
// of data points.
//
// http://en.wikipedia.org/wiki/Kernel_density_estimation#Practical_estimation_of_the_bandwidth
var calculate_bandwidth = function(data) {
var mean = d3.mean(data);
var variance = d3.mean(data.map(function(d) { return Math.pow(d - mean, 2); }));
var standard_deviation = Math.pow(variance, .5);
var bandwidth = 1.06 * standard_deviation * Math.pow(data.length, -1/5);
return bandwidth;
};
return {
process_data: process_data,
extract_and_process: extract_and_process,
kernelDensityEstimator: kernelDensityEstimator,
gaussianKernel: gaussianKernel,
calculate_bandwidth: calculate_bandwidth
};
}());
var AlleleFreqPlotMulti = function(div, data, options, order) {
// If nolegend is false, the div this is called on must be attached and
// rendered at call time or else Firefox will throw an error on the call
// to getBBox
//var fillcolors = d3.scale.category10();
// construct colors, if a duplicate found replace it with 'darker'
var colors = {};
var colorhist = {};
if (!order) {
order = {};
}
if (Object.keys(order).length === 0) {
var order_ctr = 0;
for (var k in data) {
if (data.hasOwnProperty(k)) {
order[k] = order_ctr;
order_ctr += 1;
}
}
}
for (var k in data) {
if (data.hasOwnProperty(k)) {
/*var ind = Object.keys(colors).length;
colors[k] = {stroke:fillcolors(ind), fill:fillcolors(ind)};*/
var col = d3.rgb(window.caseMetaData.color[k]).toString();
while (col in colorhist && col !== "#000000") {
col = d3.rgb(col).darker(0.4).toString();
}
colorhist[col] = true;
colors[k] = {stroke:col, fill:col};
}
}
// data is a map of sample id to list of data
var options = options || { label_font_size: "11.5px", xticks: 3, yticks: 8, nolegend:false}; // init
var label_dist_to_axis = options.xticks === 0 ? 13 : 30;
options.margin = options.margin || {};
var margin = $.extend({top: 20, right: 30, bottom: 30 + label_dist_to_axis / 2, left: 50},
options.margin);
var width = options.width || 200;
var height = options.height || (500 + label_dist_to_axis) / 2 - margin.top - margin.bottom;
// x scale and axis
var x = d3.scale.linear()
.domain([-0.1,1])
.range([0,width]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(options.xticks);
var utils = AlleleFreqPlotUtils; // alias
// make kde's
var bandwidth = {};
var kde = {};
var plot_data = {};
for (var k in data) {
if (data.hasOwnProperty(k)) {
bandwidth[k] = Math.max(utils.calculate_bandwidth(data[k]), 0.01);
kde[k] = utils.kernelDensityEstimator(utils.gaussianKernel(bandwidth[k]), x.ticks(100));
plot_data[k] = kde[k](data[k]);
}
}
// make histograms
var histogram = d3.layout.histogram().frequency(false).bins(x.ticks(30));
var binned_data = {};
for (var k in data) {
if (data.hasOwnProperty(k)) {
binned_data[k] = histogram(data[k]);
}
}
// calculate range of values that y takes
var all_plot_data = [];
for (var k in plot_data) {
if (plot_data.hasOwnProperty(k)) {
all_plot_data = all_plot_data.concat(plot_data[k]);
}
}
var ycoords = all_plot_data.map(function(d) { return d[1]; });
var ydomain = [d3.min(ycoords), d3.max(ycoords)];
var y = d3.scale.linear()
.domain(ydomain)
.range([height, 0]);
var line = d3.svg.line()
.x(function(d) { return x(d[0]); })
.y(function(d) { return y(d[1]); });
var svg = d3.select(div).append("svg")
.attr("width", width + margin.left + (options.yticks === 0 ? 0 : margin.right) + (options.nolegend? 0 : 100))
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + (options.yticks === 0 ? margin.left / 2 : margin.left) + "," + margin.top + ")");
// x axis
var x_axis = svg.append("g")
.attr("transform", "translate(0,"+height+")")
.call(xAxis);
// applies some common line and path css attributes to the selection. The
// only reason this isn't getting put into its own css file is due to the
// spectre of pdf export
var applyCss = function(selection) {
return selection
.attr('fill', 'none')
.attr('stroke', '#000')
.attr('shape-rendering', 'crispEdges');
};
applyCss(x_axis.selectAll('path'));
applyCss(x_axis.selectAll('line'));
// x-axis label
x_axis
.append("text")
//.attr("class", "label")
.attr("x", width / 2)
.attr("y", label_dist_to_axis)
.attr("font-size", options.label_font_size)
.style("text-anchor", "middle")
.style("font-style", "italic")
.text("variant allele frequency");
// make the y-axis mutation count
var all_binned_data = [];
for (var k in binned_data) {
if (binned_data.hasOwnProperty(k)) {
all_binned_data = all_binned_data.concat(binned_data[k]);
}
}
var mutation_counts = all_binned_data.map(function(d) { return d.length; });
var mutation_count_range = [0, d3.max(mutation_counts)]
// create y axis
var yAxis = d3.svg.axis()
.scale(y.copy().domain(mutation_count_range))
.orient("left")
.ticks(options.yticks);
// render axis
var y_axis = svg.append("g").call(yAxis);
// takes a number and returns a displacement length for the
// yaxis label
//
// *signature:* `number -> number`
var displace_by_digits = function(n) {
var stringified = "" + n;
var no_digits = stringified.split("").length;
// there will be a comma in the string, i.e. 1,000 not 1000
if (no_digits >= 4) {
no_digits += 1.5;
}
return no_digits * 7 / 3;
};
var ylabel_dist_to_axis = label_dist_to_axis;
ylabel_dist_to_axis += options.yticks === 0 ? 0 : displace_by_digits(mutation_count_range[1]);
// y axis label
y_axis
.append("text")
//.attr("class","label")
.attr("transform", "rotate(-90)")
.attr("x", - height/2)
.attr("y", -ylabel_dist_to_axis)
.attr("font-size", options.label_font_size)
.style("text-anchor","middle")
.style("font-style", "italic")
.text("mutation count");
applyCss(y_axis.selectAll('path')).attr('display', options.yticks === 0? '' : 'none');
applyCss(y_axis.selectAll('line'));
// calculate new domain for the binned data
var binned_yvalues = all_binned_data.map(function(d) { return d.y;});
var binned_ydomain = [d3.min(binned_yvalues), d3.max(binned_yvalues)];
var binned_yscale = y.copy();
binned_yscale.domain(binned_ydomain);
// make bar charts
for (var k in binned_data) {
if (binned_data.hasOwnProperty(k)) {
svg.selectAll(".bar")
.data(binned_data[k])
.enter().insert("rect")
.attr("x", function(d) { return x(d.x) + 1; })
.attr("y", function(d) { return binned_yscale(d.y); })
.attr('class', window.caseIds.indexOf(k)+'_viz_hist viz_hist')
.attr("width", x(binned_data[k][0].dx + binned_data[k][0].x) - x(binned_data[k][0].x) - 1)
.attr("height", function(d) {return (height - binned_yscale(d.y)); })
.attr('fill', colors[k].fill)
.attr('opacity', (Object.keys(data).length > 1 ? '0.1': '0.3'))
;
}
}
// make kde plots
for (var k in plot_data) {
if (plot_data.hasOwnProperty(k)) {
svg.append("path")
.datum(plot_data[k])
.attr("d", line)
.attr('class', 'curve '+window.caseIds.indexOf(k)+'_viz_curve viz_curve')
.attr('fill', 'none')
.attr('stroke', colors[k].stroke)
.attr('stroke-width', '1.5px')
.attr('opacity', '0.9')
.attr('data-legend',function() { return k; })
.attr('data-legend-pos', function() { return order[k];})
;
}
}
// make legend
if (!options.nolegend && Object.keys(data).length > 1) {
var legend_font_size = 13;
var legend = svg.append("g")
.attr('class', 'legend')
.attr('transform', 'translate('+(width+25)+',0)')
.style('font-size', legend_font_size+"px")
;
d3.legend(legend, legend_font_size);
}
return div;
}
// d3.legend.js
// (C) 2012 ziggy.jonsson.nyc@gmail.com
// Modifications by Adam Abeshouse adama@cbio.mskcc.org
// MIT licence
var highlightSample = function (k) {
$('.viz_hist').hide();
$('.viz_curve').hide();
if (window.allele_freq_plot_histogram_toggle) {
$("." + window.caseIds.indexOf(k) + "_viz_hist").show();
$("." + window.caseIds.indexOf(k) + "_viz_hist").attr('opacity', '0.5');
}
if (window.allele_freq_plot_curve_toggle) {
$("." + window.caseIds.indexOf(k) + "_viz_curve").show();
}
}
var showSamples = function () {
if (window.allele_freq_plot_histogram_toggle) {
$('.viz_hist').show();
$(".viz_hist").attr('opacity', '0.1');
}
if (window.allele_freq_plot_curve_toggle) {
$('.viz_curve').show();
}
}
d3.legend = function(g, font_size) {
g.each(function() {
var g= d3.select(this),
items = {},
svg = d3.select(g.property("nearestViewportElement")),
legendPadding = g.attr("data-style-padding") || 5,
lb = g.selectAll(".legend-box").data([true]),
li = g.selectAll(".legend-items").data([true])
li.enter().append("g").classed("legend-items",true);
svg.selectAll("[data-legend]").each(function() {
var self = d3.select(this)
items[self.attr("data-legend")] = {
pos : self.attr("data-legend-pos") || this.getBBox().y,
color : self.attr("data-legend-color") != undefined ? self.attr("data-legend-color") : self.style("fill") != 'none' ? self.style("fill") : self.style("stroke")
}
})
items = d3.entries(items).sort(function(a,b) { return a.value.pos-b.value.pos})
var maxLabelLength = 10;
var spacing = 0.4;
li.selectAll("text")
.data(items,function(d) { return d.key;})
.call(function(d) { d.enter().append("text");})
.call(function(d) { d.exit().remove();})
.attr("y",function(d,i) { return (i-0.1+i*spacing)+"em";})
.attr("x","1em")
.text(function(d) {
var key = d.key;
var label = key.length > maxLabelLength ? key.substring(0,4) + "..." + key.slice(-3) : key;
return label;
})
;
li.selectAll("circle")
.data(items,function(d) { return d.key})
.call(function(d) { d.enter().append("circle");})
.call(function(d) { d.exit().remove()})
.attr("cy",function(d,i) { return (i-0.5+i*spacing)+"em"})
.attr("cx",0)
.attr("r","0.5em")
.style("fill",function(d) { return d.value.color;})
;
for (var i=0, keys=Object.keys(items); i<keys.length; i++) {
li.append("text")
.attr("x",0)
.attr("y", (i-0.5+i*spacing)*font_size)
.attr("fill","white")
.attr("font-size","10")
.attr("dy","0.34em")
.attr("text-anchor","middle")
.text(window.caseMetaData.label[items[keys[i]].key])
;
}
li.selectAll("rect")
.data(items, function(d) { return d.key;})
.call(function(d) { d.enter().append("rect");})
.call(function(d) { d.exit().remove();})
.attr("id", function(d) { return d.key+"legend_hover_rect";})
.attr("y", function(d,i) { return (i-1+i*spacing-spacing/2)+"em";})
.attr("x","-0.8em")
.attr('width',function(d) { return '110px';})
.attr('height',(1+spacing)+'em')
.style('fill',function(d) { return d.value.color;})
.attr('opacity', '0')
.on('mouseover', (Object.keys(items).length > 1 ?
function(d) {
$(this).attr('opacity','0.2'); highlightSample(d.key);
} : function(d) {}))
.on('mouseout', function(d) { $(this).attr('opacity','0');})
;
for (var i=0; i<items.length; i++) {
var k = items[i].key;
if (k.length > maxLabelLength) {
$("#"+k+"legend_hover_rect").attr("title", k);
$("#"+k+"legend_hover_rect").qtip({
content: { attr: 'title' },
style: { classes: 'qtip-light qtip-rounded' },
position: { my:'center left',at:'center right',viewport: $(window) }
});
}
}
li.on('mouseout', (Object.keys(items).length > 1 ? function() { showSamples(); } : function() {}));
// Reposition and resize the box
var lbbox = li[0][0].getBBox()
lb.attr("x",(lbbox.x-legendPadding))
.attr("y",(lbbox.y-legendPadding))
.attr("height",(lbbox.height+2*legendPadding))
.attr("width",(lbbox.width+2*legendPadding));
})
return g;
}
//
// appends labels and such that are specific to the allele frequency density
// plot
//
// makes a kernel density plot of the data and dumps it into the div. Optional
// options parameter which supports attributes:
// * `width` number
// * `height` number
// * `label_font_size` string in pixels (px)
//
// *signature:* `DOM el, array, obj -> DOM el (with plot inside)`
var AlleleFreqPlot = function(div, data, options) {
var options = options || { label_font_size: "10.5px", xticks: 3, yticks: 8 }; // init
var label_dist_to_axis = options.xticks === 0 ? 13 : 30;
options.margin = options.margin || {};
var margin = $.extend({top: 20, right: 30, bottom: 30 + label_dist_to_axis / 2, left: 50},
options.margin);
var width = options.width || 200,
height = options.height || (500 + label_dist_to_axis) / 2 - margin.top - margin.bottom;
// x scale and axis
var x = d3.scale.linear()
.domain([-.1, 1])
.range([0, width]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(options.xticks);
var utils = AlleleFreqPlotUtils; // alias
// make a kde
var bandwidth = utils.calculate_bandwidth(data);
var kde = utils.kernelDensityEstimator(utils.gaussianKernel(bandwidth), x.ticks(100));
var plot_data = kde(data);
// make a histogram
var histogram = d3.layout.histogram()
.frequency(false)
.bins(x.ticks(30));
var binned_data = histogram(data);
// calculate the range of values that y takes
var ydomain = plot_data.map(function(d){ return d[1]; }); // plot_data is a list of 2-ples
ydomain = [d3.min(ydomain), d3.max(ydomain)];
var y = d3.scale.linear()
.domain(ydomain)
.range([height, 0]);
var line = d3.svg.line()
.x(function(d) { return x(d[0]); })
.y(function(d) { return y(d[1]); });
var svg = d3.select(div).append("svg")
.attr("width", width + margin.left + (options.yticks === 0 ? 0 : margin.right))
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + (options.yticks === 0 ? margin.left / 2 : margin.left) + "," + margin.top + ")");
// x axis
var x_axis = svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// applies some common line and path css attributes to the selection. The
// only reason this isn't getting put into its own css file is due to the
// spectre of pdf export
var applyCss = function(selection) {
return selection
.attr('fill', 'none')
.attr('stroke', '#000')
.attr('shape-rendering', 'crispEdges');
};
applyCss(x_axis.selectAll('path'));
applyCss(x_axis.selectAll('line'));
// x-axis label
x_axis
.append("text")
.attr("class", "label")
.attr("x", width / 2)
.attr("y", label_dist_to_axis)
.attr('font-size', options.label_font_size)
.style("text-anchor", "middle")
.text("variant allele frequency");
// make the y-axis mutation count
mutation_count_range = binned_data.map(function(d) { return d.length; });
var max_no_mutations = d3.max(mutation_count_range);
mutation_count_range = [d3.min(mutation_count_range),
max_no_mutations];
// create axis
var yAxis = d3.svg.axis()
.scale(y.copy().domain(mutation_count_range))
.orient("left")
.ticks(options.yticks);
// render axis
var y_axis = svg.append("g")
//.attr("transform", "translate(" + -10 + ",0)")
.call(yAxis);
// takes a number and returns a displacement length for the
// yaxis label
//
// *signature:* `number -> number`
var displace_by_digits = function(n) {
var stringified = "" + n;
var no_digits = stringified.split("").length;
// there will be a comma in the string, i.e. 1,000 not 1000
if (no_digits >= 4) {
no_digits += 1.5;
}
return no_digits * 7 / 3;
};
var ylabel_dist_to_axis = label_dist_to_axis;
ylabel_dist_to_axis += options.yticks === 0 ? 0 : displace_by_digits(max_no_mutations);
// y-axis label
y_axis
.append("text")
.attr("class", "label")
.attr("transform", "rotate(" + "-" + 90 + ")")
// axis' have also been rotated
.attr("x", - height / 2)
.attr("y", - ylabel_dist_to_axis)
.attr('font-size', options.label_font_size)
.style("text-anchor", "middle")
.text("mutation count");
applyCss(y_axis.selectAll('path')).attr('display', options.yticks === 0 ? '' : 'none');
applyCss(y_axis.selectAll('line'));
// calculate a new domain for the binned data
var binned_ydomain = binned_data.map(function(d) { return d.y; });
binned_ydomain = [d3.min(binned_ydomain), d3.max(binned_ydomain)];
var binned_yscale = y.copy();
binned_yscale.domain(binned_ydomain);
// make a bar chart
svg.selectAll(".bar")
.data(binned_data)
.enter().insert("rect")
.attr("x", function(d) { return x(d.x) + 1; })
.attr("y", function(d) { return binned_yscale(d.y); })
.attr("width", x(binned_data[0].dx + binned_data[0].x) - x(binned_data[0].x) - 1)
.attr("height", function(d) {return (height - binned_yscale(d.y)); })
.attr('fill', '#1974b8')
;
var kde_path = svg.append("path")
.datum(plot_data)
.attr("d", line)
.attr('class', 'curve')
.attr('fill', 'none')
.attr('stroke', '#000')
.attr('stroke-width', '1.5px');
return div;
};
| bihealth/cbioportal | portal/src/main/webapp/js/src/patient-view/AlleleFreqPlot.js | JavaScript | agpl-3.0 | 24,058 |
kWidget.addReadyCallback( function( playerId ){
var kdp = document.getElementById( playerId );
/**
* The main chaptersEdit object:
*/
var chaptersEdit = function(kdp){
return this.init(kdp);
}
chaptersEdit.prototype = {
// the left offset of the cuepoint
leftOffset: 20,
// flag to control seeking on playhead updates:
seekOnPlayHeadUpdate: false,
// The current active cuePoint
activeCuePoint: null,
// Current time of the playhead
currentTime: 0,
init: function( kdp ){
var _this = this;
this.kdp = kdp;
// init the cuePoints data controller with the current entryId:
this.cuePoints = new kWidget.cuePointsDataController({
'wid' : this.getAttr( 'configProxy.kw.id' ),
'entryId' : this.getAttr( 'mediaProxy.entry.id' ),
'tags' : this.getConfig('tags') || 'chaptering', // default cuePoint name
'ks' : this.getConfig('ks'),
// pass in customDataFields array
'customDataFields': this.getConfig( 'customDataFields' ) ?
this.getConfig( 'customDataFields' ).split(',') :
[]
});
// setup app targets:
this.$prop = this.getConfig( 'editPropId') ?
$('#' + this.getConfig( 'editPropId') ) :
$('<div>').insertAfter( kdp );
this.$timeline = this.getConfig( 'editTimelineId' ) ?
$( '#' + this.getConfig( 'editTimelineId' ) ) :
$('<div>').insertAfter( this.$prop );
// Add classes for css styles:
this.$prop.addClass( 'k-prop' ).text('loading');
this.$timeline.addClass( 'k-timeline' ).text('loading');
// Add in default metadata:
this.cuePoints.load(function( status ){
if( status.code ){
_this.$timeline.empty();
_this.$prop.empty();
_this.handleDataError( status );
return ;
}
_this.displayPropEdit();
_this.refreshTimeline();
_this.addTimelineBindings();
// set the playhead at zero for startup ( without a seek )
_this.updatePlayheadUi( 0 );
});
},
displayPropEdit: function(){
var _this = this;
// check if we have a KS ( required for edit and display )
// check if we have an active cuePoint
if( this.activeCuePoint){
this.showEditCuePoint();
} else{
this.showAddCuePoint();
}
},
showEditCuePoint: function(){
var _this = this;
var cueTilte = this.activeCuePoint.get('text') ?
this.activeCuePoint.get('text').substr( 0, 25 ) :
this.activeCuePoint.get('id');
this.$prop.empty().append(
$('<h3>')
.attr('title', this.activeCuePoint.get('text') )
.text('Edit Chapter: ' + cueTilte ),
this.getEditCuePoint( this.activeCuePoint ),
$('<a>').addClass( "btn" ).text( "Update" ).click( function(){
// Trigger cuePoint time update:
_this.$prop.find( '.k-currentTime' ).trigger('change');
var _saveButton = this;
$( this ).addClass( "disabled" ).text( 'saving ...' ).siblings('.btn').addClass( "disabled" );
_this.cuePoints.update( _this.activeCuePoint.get(), function( data ){
if( !_this.handleDataError( data ) ){
return ;
}
// refresh timeline and re-display edit: :
_this.setActiveEditCuePoint( data.id );
});
}),
$( '<span>').text(' '),
$('<a>').addClass( "btn" ).text( "Remove" ).click(function(){
// update text to removing, disable self and sibling buttons
$( this ).addClass( "disabled" ).text( 'removing ...' ).siblings('.btn').addClass( "disabled" );
// issue a delete api call:
_this.cuePoints.remove( _this.activeCuePoint, function( data ){
if( ! _this.handleDataError( data ) ){
return ;
}
// refresh timeline:
_this.refreshTimeline();
// show add:
_this.showAddCuePoint();
});
})
);
},
getAddChapterButton:function( curCuePoint ){
var _this = this;
return $('<a>').addClass( "btn" ).text( "Add" ).click(function(){
var _addButton = this;
$( this ).addClass( "disabled" ).text( 'adding ...' );
// Trigger cuePoint time update:
_this.$prop.find( '.k-currentTime' ).trigger('change');
// insert the current cuePoint
_this.cuePoints.add({
'entryId': _this.getAttr( 'mediaProxy.entry.id' ),
// Get direct mapping data:
'startTime': curCuePoint.get( 'startTime' ),
'partnerData': curCuePoint.get( 'partnerData' ),
'text': curCuePoint.get('text')
} , function( data ){
if( ! _this.handleDataError( data ) ){
return ;
}
_this.setActiveEditCuePoint( data.id );
})
})
},
showAddCuePoint: function(){
var _this = this;
var curCuePoint = this.cuePoints.newCuePoint( {} );
this.$prop.empty().append(
$('<h3>').text( 'Add Chapter:' ),
this.getEditCuePoint( curCuePoint ),
this.getAddChapterButton( curCuePoint )
);
},
setActiveEditCuePoint: function( id ){
this.deselectCuePoint();
// set active:
this.activeCuePoint = this.cuePoints.getById( id );
// refresh timeline:
this.refreshTimeline();
// switch to "edit"
this.showEditCuePoint();
this.updatePlayhead(
this.activeCuePoint.get( 'startTime' ) / 1000
);
},
handleDataError: function( data ){
// check for errors;
if( !data || data.code ){
this.$prop.find('.alert-error').remove();
this.$prop.append(
this.getError( data )
);
return false;
}
return true;
},
getError: function( errorData ){
var error = {
'title': "Error",
'msg': "Unknown error"
}
switch( errorData.code ){
case "SERVICE_FORBIDDEN":
var win = ( self == top ) ? window : top;
if( win.location.hash.indexOf( 'uiconf_id') !== -1 ){
error.title = "URL includes uiconf_id #config";
error.msg = " Kaltura Secret can not be used with uiConf URL based config." +
"Please save settings, and remove url based config"
break;
}
error.title = "Missing Kaltura Secret";
error.msg = "The chapters editor appears to be missing a valid kaltura secret." +
" Please login."
break;
default:
if( errorData.message ){
error.msg = errorData.message
}
break;
}
return $('<div class="alert alert-error">' +
//'<button type="button" class="close" data-dismiss="alert">x</button>' +
'<h4>' + error.title + '</h4> ' +
error.msg +
'</div>' );
},
getEditCuePoint: function( curCuePoint ){
var _this = this;
// get the edit table for the cuePoint
$editTable = curCuePoint.getEditTable();
// add special binding for time update:
$editTable.find( '.k-currentTime' )
.off('blur')
.on('blur', function(){
// check if "editing a cue point"
if( _this.activeCuePoint ){
_this.refreshTimeline();
}
_this.updatePlayhead(
kWidget.npt2seconds( $( this ).val() )
);
})
return $editTable;
},
addTimelineBindings: function(){
var _this = this;
this.$timeline.click(function( event ){
var clickTime;
if( event.offsetX < _this.leftOffset ){
clickTime = 0;
} else{
if( !event.offsetX ){
event.offsetX = event.pageX - _this.$timeline.offset().left;
}
// update the playhead tracker
clickTime = ( (event.offsetX - _this.leftOffset ) / _this.getTimelineWidth() ) * _this.getAttr('mediaProxy.entry.duration');
}
_this.deselectCuePoint();
// show add new
_this.showAddCuePoint();
// update playhead
_this.updatePlayhead( clickTime );
});
// add playhead tracker
kdp.kBind('playerUpdatePlayhead', function( ct ){
_this.updatePlayheadUi( ct );
} )
},
updatePlayhead: function( time ){
// update the current time:
this.currentTime = time;
// seek to that time
kdp.sendNotification( 'doSeek', time );
// do the ui update
this.updatePlayheadUi( time );
},
updatePlayheadUi: function( time ) {
// time target:
var timeTarget = ( time / this.getAttr('mediaProxy.entry.duration') ) * this.getTimelineWidth();
// update playhead on timeline:
this.$timeline.find( '.k-playhead' ).css({
'left': ( this.leftOffset + timeTarget) + 'px'
});
// Check if we can update current time: ( don't update if a chapter is selected )
this.$prop.find( '.k-currentTime' ).val(
kWidget.seconds2npt( time, true )
)
},
getTimelineWidth: function(){
return ( this.$timeline.width() - this.leftOffset );
},
refreshTimeline: function(){
this.$timeline.empty();
var numOfTimeIncludes = 8;
// have a max of 10 time listings across the width
var listingWidth = this.$timeline.width() / numOfTimeIncludes;
var docstext = "Click anywhere within the timeline area to add a new chapter";
if (this.cuePoints.get().length > 0) {
docstext += ". Click any chapter marker to edit a chapter";
}
// draw main top level timeline
this.$timeline.append(
$('<div>').addClass( 'k-timeline-background' ),
$('<div>').addClass( 'k-baseline'),
$('<span>').addClass('k-timeline-docs').text(docstext)
).css({
'position': 'relative',
'height': '100px'
})
// draw the playhead marker
this.$timeline.append(
$('<div>')
.addClass('k-playhead')
.css({
'position': 'absolute',
'top': '25px',
'left': this.leftOffset + 'px',
'width' : '1px',
'height': '60px',
'background':'red'
})
)
// Draw all vertical measurement lines:
var j =0;
for( var i = this.leftOffset; i< this.$timeline.width(); i+= ( listingWidth / 4 ) ){
if( j == 0 ){
var curMarker = i - this.leftOffset;
var markerTime = ( curMarker / this.getTimelineWidth() ) * this.getAttr('mediaProxy.entry.duration');
// append large marker
this.$timeline.append(
$('<div>').css({
'position': 'absolute',
'top': '25px',
'left': i + 'px',
'width' : '3px',
'height': '14px',
'background':'black'
}),
$('<span>').css({
'position': 'absolute',
'top': '5px',
'margin-left': '-10px',
'left': i + 'px',
'width' : '70px',
'height': '14px',
}).text(
kWidget.seconds2npt( markerTime )
)
);
} else {
this.$timeline.append(
$('<div>').css({
'position': 'absolute',
'top': '30px',
'left': i + 'px',
'width' : '2px',
'height': '8px',
'background':'gray'
})
);
}
j++;
if( j == 6 ){
j= 0;
}
}
// draw the cuePoints:
this.drawCuePoints();
},
deselectCuePoint: function(){
// make sure no other cuePoint is active:
this.$timeline.find( '.k-cuepoint').removeClass('active');
this.displayPropEdit();
this.activeCuePoint = null;
},
selectCuePoint: function( cuePoint ){
var _this = this;
// unselect other cuePoints:
_this.deselectCuePoint();
// activate the current :
_this.activeCuePoint = cuePoint;
$( '#k-cuepoint-' + cuePoint.get('id') ).addClass( 'active' );
// update the cue point editor:
_this.displayPropEdit();
// select the current cueTime
_this.updatePlayhead( cuePoint.get('startTime') / 1000 );
},
/**
* Draw all the cuePoints to the screen.
*/
drawCuePoints: function(){
var _this = this;
// remove all old cue points
_this.$timeline.find( '.k-cuepoint').remove();
$.each( this.cuePoints.get(), function( inx, curCuePoint){
var cueTime = curCuePoint.get( 'startTime' ) / 1000;
var timeTarget = ( cueTime / _this.getAttr('mediaProxy.entry.duration') ) * _this.getTimelineWidth();
var $cuePoint = $('<div>')
.addClass( 'k-cuepoint' )
.attr( 'id', 'k-cuepoint-' + curCuePoint.get('id') )
.css({
'left': ( _this.leftOffset + timeTarget) + 'px'
})
.attr('title', curCuePoint.get('text') )
.click(function(){
// select the current cuePoint
_this.selectCuePoint( curCuePoint );
// don't propagate down to parent timeline:
return false;
})
if( _this.activeCuePoint && _this.activeCuePoint.get('id') == curCuePoint.get('id') ){
$cuePoint.addClass('active');
}
_this.$timeline.append(
$cuePoint
)
});
},
normalizeAttrValue: function( attrValue ){
// normalize flash kdp string values
switch( attrValue ){
case "null":
return null;
break;
case "true":
return true;
break;
case "false":
return false;
break;
}
return attrValue;
},
getAttr: function( attr ){
return this.normalizeAttrValue(
this.kdp.evaluate( '{' + attr + '}' )
);
},
getConfig : function( attr ){
if( this.configOverride && typeof this.configOverride[ attr ] !== 'undefind' ){
return this.configOverride[ attr ];
}
return this.normalizeAttrValue(
this.kdp.evaluate('{chaptersEdit.' + attr + '}' )
);
}
}
/*****************************************************************
* Application initialization
****************************************************************/
window['chaptersEditMediaReady'] = function(){
// make sure we have jQuery
if( !window.jQuery ){
kWidget.appendScriptUrl( '//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js', function(){
new chaptersEdit(kdp)
});
return ;
}
new chaptersEdit(kdp);
};
kdp.addJsListener( "mediaReady", "chaptersEditMediaReady" );
});
| alexmilk/mwEmbed | kWidget/onPagePlugins/chapters/chaptersEdit.js | JavaScript | agpl-3.0 | 13,308 |
/*
* Shopware 5
* Copyright (c) shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*
* @category Shopware
* @package Base
* @subpackage Component
* @version $Id$
* @author shopware AG
*/
Ext.define('Shopware.apps.Base.view.element.Color', {
extend: 'Ext.form.TriggerField',
alias: [
'widget.base-element-color'
],
triggerConfig: {
src: Ext.BLANK_IMAGE_URL,
tag: "img",
cls: "x-form-trigger x-form-color-trigger"
},
//invalidText: "Colors must be in a the hex format #FFFFFF.",
// {literal}
regex: /^#([0-9A-F]{6}|[0-9A-F]{3})$/i,
// {/literal}
initComponent: function () {
this.callParent()
this.addEvents('select');
this.on('change', function (c, v) {
this.onSelect(c, v);
}, this);
},
// private
onDestroy: function () {
Ext.destroy(this.menu);
this.callParent();
},
afterRender: function () {
this.callParent(arguments)
this.inputEl.setStyle('background', this.value);
this.detectFontColor();
},
onTriggerClick: function (e) {
if (this.disabled) {
return;
}
this.menu = new Ext.ux.ColorPicker({
shadow: true,
autoShow: true,
hideOnClick: false
});
this.menu.alignTo(this.inputEl, 'tl-bl?');
this.menuEvents('on');
this.menu.show(this.inputEl);
},
menuEvents: function (method) {
this.menu[method]('select', this.onSelect, this);
this.menu[method]('hide', this.onMenuHide, this);
this.menu[method]('show', this.onFocus, this);
},
onSelect: function (m, d) {
d = Ext.isString(d) && d.substr(0, 1) != '#' ? '#' + d : d;
this.setValue(d);
this.fireEvent('select', this, d);
this.inputEl.setStyle('background', d);
this.detectFontColor();
},
detectFontColor: function () {
var value = this.value;
if (!this.menu || !this.menu.picker.rawValue) {
if (!value) {
value = '#FFF';
}
if (value.length < 6) {
value = value + value.slice(1, 5);
};
var h2d = function (d) {
return parseInt(d, 16);
}
value = [
h2d(value.slice(1, 3)),
h2d(value.slice(3, 5)),
h2d(value.slice(5))
];
} else {
value = this.menu.picker.rawValue;
}
var avg = (value[0] + value[1] + value[2]) / 3;
this.inputEl.setStyle('color', (isNaN(avg) || avg > 128) ? '#000' : '#FFF');
},
onMenuHide: function () {
this.focus(false, 60);
this.menuEvents('un');
}
});
Ext.define('Ext.ux.ColorPicker', {
extend: 'Ext.menu.ColorPicker',
initComponent: function () {
var me = this;
me.height = 100;
me.hideOnClick = true;
me.callParent();
return me.processEvent();
},
processEvent: function () {
return;
var me = this;
me.picker.clearListeners();
me.relayEvents(me.picker, ['select']);
if (me.hideOnClick) {
me.on('select', me.hidePickerOnSelect, me);
}
}
});
| simkli/shopware | themes/Backend/ExtJs/backend/base/component/element/color.js | JavaScript | agpl-3.0 | 4,156 |
// fix Promise Problem on JSContext of iOS7~8
// @see https://bugs.webkit.org/show_bug.cgi?id=135866
const { WXEnvironment } = global
/* istanbul ignore next */
if (WXEnvironment && WXEnvironment.platform === 'iOS') {
global.Promise = undefined
}
| Neeeo/incubator-weex | html5/shared/promise.js | JavaScript | apache-2.0 | 250 |
import React from 'react';
import RefreshIndicator from 'material-ui/RefreshIndicator';
const style = {
container: {
position: 'relative',
},
refresh: {
display: 'inline-block',
position: 'relative',
},
};
const RefreshIndicatorExampleSimple = () => (
<div style={style.container}>
<RefreshIndicator
percentage={30}
size={40}
left={10}
top={0}
status="ready"
style={style.refresh}
/>
<RefreshIndicator
percentage={60}
size={50}
left={65}
top={0}
status="ready"
style={style.refresh}
/>
<RefreshIndicator
percentage={80}
size={60}
left={120}
top={0}
color={"red"}
status="ready"
style={style.refresh}
/>
<RefreshIndicator
percentage={100}
size={70}
left={175}
top={0}
color={"red"} // Overridden by percentage={100}
status="ready"
style={style.refresh}
/>
</div>
);
export default RefreshIndicatorExampleSimple;
| pomerantsev/material-ui | docs/src/app/components/pages/components/RefreshIndicator/ExampleReady.js | JavaScript | mit | 1,026 |
/**
* Utility class for setting/reading values from browser cookies.
* Values can be written using the {@link #set} method.
* Values can be read using the {@link #get} method.
* A cookie can be invalidated on the client machine using the {@link #clear} method.
*/
Ext.define('Ext.util.Cookies', {
singleton: true,
/**
* Creates a cookie with the specified name and value. Additional settings for the cookie may be optionally specified
* (for example: expiration, access restriction, SSL).
* @param {String} name The name of the cookie to set.
* @param {Object} value The value to set for the cookie.
* @param {Object} [expires] Specify an expiration date the cookie is to persist until. Note that the specified Date
* object will be converted to Greenwich Mean Time (GMT).
* @param {String} [path] Setting a path on the cookie restricts access to pages that match that path. Defaults to all
* pages ('/').
* @param {String} [domain] Setting a domain restricts access to pages on a given domain (typically used to allow
* cookie access across subdomains). For example, "sencha.com" will create a cookie that can be accessed from any
* subdomain of sencha.com, including www.sencha.com, support.sencha.com, etc.
* @param {Boolean} [secure] Specify true to indicate that the cookie should only be accessible via SSL on a page
* using the HTTPS protocol. Defaults to false. Note that this will only work if the page calling this code uses the
* HTTPS protocol, otherwise the cookie will be created with default options.
*/
set : function(name, value){
var argv = arguments,
argc = arguments.length,
expires = (argc > 2) ? argv[2] : null,
path = (argc > 3) ? argv[3] : '/',
domain = (argc > 4) ? argv[4] : null,
secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape(value) + ((expires === null) ? "" : ("; expires=" + expires.toUTCString())) + ((path === null) ? "" : ("; path=" + path)) + ((domain === null) ? "" : ("; domain=" + domain)) + ((secure === true) ? "; secure" : "");
},
/**
* Retrieves cookies that are accessible by the current page. If a cookie does not exist, `get()` returns null. The
* following example retrieves the cookie called "valid" and stores the String value in the variable validStatus.
*
* var validStatus = Ext.util.Cookies.get("valid");
*
* @param {String} name The name of the cookie to get
* @return {Object} Returns the cookie value for the specified name;
* null if the cookie name does not exist.
*/
get : function(name) {
var parts = document.cookie.split('; '),
len = parts.length,
item, i;
// In modern browsers, a cookie with an empty string will be stored:
// MyName=
// In older versions of IE, it will be stored as:
// MyName
// So here we iterate over all the parts in an attempt to match the key.
for (i = 0; i < len; ++i) {
item = parts[i].split('=');
if (item[0] === name) {
return item[1] || '';
}
}
return null;
},
/**
* Removes a cookie with the provided name from the browser
* if found by setting its expiration date to sometime in the past.
* @param {String} name The name of the cookie to remove
* @param {String} [path] The path for the cookie.
* This must be included if you included a path while setting the cookie.
*/
clear : function(name, path){
if (this.get(name)) {
path = path || '/';
document.cookie = name + '=' + '; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=' + path;
}
},
/**
* @private
*/
getCookieVal : function(offset){
var cookie = document.cookie,
endstr = cookie.indexOf(";", offset);
if (endstr == -1) {
endstr = cookie.length;
}
return unescape(cookie.substring(offset, endstr));
}
});
| applifireAlgo/ZenClubApp | zenws/src/main/webapp/ext/src/util/Cookies.js | JavaScript | gpl-3.0 | 4,150 |
describe('$mdToast service', function() {
beforeEach(module('material.components.toast'));
beforeEach(function () {
module(function ($provide) {
$provide.value('$mdMedia', function () {
return true;
});
});
});
afterEach(inject(function($material) {
$material.flushOutstandingAnimations();
}));
function setup(options) {
var promise;
inject(function($mdToast, $material, $timeout) {
options = options || {};
promise = $mdToast.show(options);
$material.flushOutstandingAnimations();
});
return promise;
}
describe('simple()', function() {
hasConfigMethods(['content', 'action', 'capsule', 'highlightAction', 'theme', 'toastClass']);
it('should have `._md` class indicator', inject(function($mdToast, $material) {
var parent = angular.element('<div>');
$mdToast.show(
$mdToast.simple({
parent: parent,
content: 'Do something',
theme: 'some-theme',
capsule: true
}));
$material.flushOutstandingAnimations();
expect(parent.find('md-toast').hasClass('_md')).toBe(true);
}));
it('supports a basic toast', inject(function($mdToast, $rootScope, $timeout, $material, $browser) {
var openAndclosed = false;
var parent = angular.element('<div>');
$mdToast.show(
$mdToast.simple({
parent: parent,
content: 'Do something',
theme: 'some-theme',
capsule: true
})
).then(function() {
openAndclosed = true;
});
$material.flushOutstandingAnimations();
expect(parent.find('span').text().trim()).toBe('Do something');
expect(parent.find('span')).toHaveClass('md-toast-text');
expect(parent.find('md-toast')).toHaveClass('md-capsule');
expect(parent.find('md-toast').attr('md-theme')).toBe('some-theme');
$material.flushInterimElement();
expect(openAndclosed).toBe(true);
}));
it('supports dynamicly updating the content', inject(function($mdToast, $rootScope, $rootElement) {
var parent = angular.element('<div>');
$mdToast.showSimple('Hello world');
$rootScope.$digest();
$mdToast.updateContent('Goodbye world');
$rootScope.$digest();
expect($rootElement.find('span').text().trim()).toBe('Goodbye world');
}));
it('supports an action toast', inject(function($mdToast, $rootScope, $material) {
var resolved = false;
var parent = angular.element('<div>');
$mdToast.show(
$mdToast.simple({
content: 'Do something',
parent: parent
})
.action('Click me')
.highlightAction(true)
).then(function() {
resolved = true;
});
$material.flushOutstandingAnimations();
var button = parent.find('button');
expect(button.text().trim()).toBe('Click me');
button.triggerHandler('click');
$material.flushInterimElement();
expect(resolved).toBe(true);
}));
it('should apply the highlight class when using highlightAction', inject(function($mdToast, $rootScope, $material) {
var parent = angular.element('<div>');
$mdToast.show(
$mdToast.simple({
content: 'Marked as read',
parent: parent
})
.action('UNDO')
.highlightAction(true)
.highlightClass('md-warn')
);
$material.flushOutstandingAnimations();
var button = parent.find('button');
expect(button.text().trim()).toBe('UNDO');
expect(button).toHaveClass('md-highlight');
expect(button).toHaveClass('md-warn');
}));
it('adds the specified class to md-toast when using toastClass', inject(function($mdToast, $material) {
var parent = angular.element('<div>');
$mdToast.show(
$mdToast.simple()
.parent(parent)
.toastClass('test')
);
$material.flushOutstandingAnimations();
expect(parent.find('md-toast').hasClass('test')).toBe(true);
}));
describe('when using custom interpolation symbols', function() {
beforeEach(module(function($interpolateProvider) {
$interpolateProvider.startSymbol('[[').endSymbol(']]');
}));
it('displays correctly', inject(function($mdToast, $rootScope) {
var parent = angular.element('<div>');
var toast = $mdToast.simple({
content: 'Do something',
parent: parent
}).action('Click me');
$mdToast.show(toast);
$rootScope.$digest();
var content = parent.find('span').eq(0);
var button = parent.find('button');
expect(content.text().trim()).toBe('Do something');
expect(button.text().trim()).toBe('Click me');
}));
it('displays correctly with parent()', inject(function($mdToast, $rootScope) {
var parent = angular.element('<div>');
var toast = $mdToast.simple({
content: 'Do something',
})
.parent(parent)
.action('Click me');
$mdToast.show(toast);
$rootScope.$digest();
var content = parent.find('span').eq(0);
var button = parent.find('button');
expect(content.text().trim()).toBe('Do something');
expect(button.text().trim()).toBe('Click me');
}));
});
function hasConfigMethods(methods) {
angular.forEach(methods, function(method) {
return it('supports config method #' + method, inject(function($mdToast) {
var basic = $mdToast.simple();
expect(typeof basic[method]).toBe('function');
expect(basic[method]()).toBe(basic);
}));
});
}
});
describe('build()', function() {
describe('options', function() {
it('should have template', inject(function($timeout, $rootScope, $rootElement) {
var parent = angular.element('<div>');
setup({
template: '<md-toast>{{1}}234</md-toast>',
appendTo: parent
});
var toast = $rootElement.find('md-toast');
$timeout.flush();
expect(toast.text().trim()).toBe('1234');
}));
it('should have templateUrl', inject(function($timeout, $rootScope, $templateCache, $rootElement) {
$templateCache.put('template.html', '<md-toast>hello, {{1}}</md-toast>');
setup({
templateUrl: 'template.html',
});
var toast = $rootElement.find('md-toast');
expect(toast.text().trim()).toBe('hello, 1');
}));
it('should not throw an error if template starts with comment', inject(function($timeout, $rootScope, $rootElement) {
var parent = angular.element('<div>');
setup({
template: '<!-- COMMENT --><md-toast>{{1}}234</md-toast>',
appendTo: parent
});
var toast = $rootElement.find('md-toast');
$timeout.flush();
expect(toast.length).not.toBe(0);
}));
it('should correctly wrap the custom template', inject(function($timeout, $rootScope, $rootElement) {
var parent = angular.element('<div>');
setup({
template: '<md-toast>Message</md-toast>',
appendTo: parent
});
var toast = $rootElement.find('md-toast');
$timeout.flush();
expect(toast[0].querySelector('.md-toast-content').textContent).toBe('Message');
}));
it('should add position class to toast', inject(function($rootElement, $timeout) {
setup({
template: '<md-toast>',
position: 'top left'
});
var toast = $rootElement.find('md-toast');
$timeout.flush();
expect(toast.hasClass('md-top')).toBe(true);
expect(toast.hasClass('md-left')).toBe(true);
}));
it('should wrap toast content with .md-toast-content', inject(function($rootElement, $timeout) {
setup({
template: '<md-toast><p>Charmander</p></md-toast>',
position: 'top left'
});
var toast = $rootElement.find('md-toast')[0];
$timeout.flush();
expect(toast.children.length).toBe(1);
var toastContent = toast.children[0];
var contentSpan = toastContent.children[0];
expect(toastContent.classList.contains('md-toast-content'));
expect(toastContent.textContent).toMatch('Charmander');
expect(contentSpan).not.toHaveClass('md-toast-text');
}));
describe('sm screen', function () {
beforeEach(function () {
module(function ($provide) {
$provide.value('$mdMedia', function () {
return false;
});
});
});
it('should always be on bottom', inject(function($rootElement, $material) {
disableAnimations();
setup({
template: '<md-toast>'
});
expect($rootElement.hasClass('md-toast-open-bottom')).toBe(true);
$material.flushInterimElement();
setup({
template: '<md-toast>',
position: 'top'
});
expect($rootElement.hasClass('md-toast-open-bottom')).toBe(true);
}));
});
});
});
describe('lifecycle', function() {
describe('should hide',function() {
it('current toast when showing new one', inject(function($rootElement, $material) {
disableAnimations();
setup({
template: '<md-toast class="one">'
});
expect($rootElement[0].querySelector('md-toast.one')).toBeTruthy();
expect($rootElement[0].querySelector('md-toast.two')).toBeFalsy();
expect($rootElement[0].querySelector('md-toast.three')).toBeFalsy();
$material.flushInterimElement();
setup({
template: '<md-toast class="two">'
});
expect($rootElement[0].querySelector('md-toast.one')).toBeFalsy();
expect($rootElement[0].querySelector('md-toast.two')).toBeTruthy();
expect($rootElement[0].querySelector('md-toast.three')).toBeFalsy();
$material.flushInterimElement();
setup({
template: '<md-toast class="three">'
});
$material.flushOutstandingAnimations();
expect($rootElement[0].querySelector('md-toast.one')).toBeFalsy();
expect($rootElement[0].querySelector('md-toast.two')).toBeFalsy();
expect($rootElement[0].querySelector('md-toast.three')).toBeTruthy();
}));
it('after duration', inject(function($timeout, $animate, $rootElement) {
disableAnimations();
var parent = angular.element('<div>');
var hideDelay = 1234;
setup({
template: '<md-toast />',
hideDelay: hideDelay
});
expect($rootElement.find('md-toast').length).toBe(1);
$timeout.flush(hideDelay);
expect($rootElement.find('md-toast').length).toBe(0);
}));
it('and resolve with default `true`', inject(function($timeout, $material, $mdToast) {
disableAnimations();
var hideDelay = 1234, result, fault;
setup({
template: '<md-toast />',
hideDelay: 1234
}).then(
function(response){ result = response; },
function(error){ fault = error; }
);
$mdToast.hide();
$material.flushInterimElement();
expect(result).toBe(undefined);
expect(angular.isUndefined(fault)).toBe(true);
}));
it('and resolve with specified value', inject(function($timeout, $animate, $material, $mdToast) {
disableAnimations();
var hideDelay = 1234, result, fault;
setup({
template: '<md-toast />',
hideDelay: 1234
}).then(
function(response){ result = response; },
function(error){ fault = error; }
);
$mdToast.hide("secret");
$material.flushInterimElement();
expect(result).toBe("secret");
expect(angular.isUndefined(fault)).toBe(true);
}));
it('and resolve `true` after timeout', inject(function($timeout, $material) {
disableAnimations();
var hideDelay = 1234, result, fault;
setup({
template: '<md-toast />',
hideDelay: 1234
}).then(
function(response){ result = response; },
function(error){ fault = error; }
);
$material.flushInterimElement();
expect(result).toBe(undefined);
expect(angular.isUndefined(fault)).toBe(true);
}));
it('and resolve `ok` with click on OK button', inject(function($mdToast, $rootScope, $timeout, $material, $browser) {
var result, fault;
var parent = angular.element('<div>');
var toast = $mdToast.simple({
parent: parent,
content: 'Do something'
}).action('Close with "ok" response');
$mdToast
.show(toast)
.then(
function(response){ result = response; },
function(error){ fault = error; }
);
$material.flushOutstandingAnimations();
parent.find('button').triggerHandler('click');
$material.flushInterimElement();
expect(result).toBe('ok');
expect(angular.isUndefined(fault)).toBe(true);
}));
});
it('should add class to toastParent', inject(function($rootElement, $material) {
disableAnimations();
setup({
template: '<md-toast>'
});
expect($rootElement.hasClass('md-toast-open-bottom')).toBe(true);
$material.flushInterimElement();
setup({
template: '<md-toast>',
position: 'top'
});
expect($rootElement.hasClass('md-toast-open-top')).toBe(true);
}));
});
});
| HiOA-ABI/nikita-noark5-core | web/dependencies/external/angular-material/src/components/toast/toast.spec.js | JavaScript | agpl-3.0 | 13,836 |
/*******************************************************
* task service implementation
* internal JSON representor format (server)
* May 2015
* Mike Amundsen (@mamund)
* Soundtrack : Complete Collection : B.B. King (2008)
*******************************************************/
// internal JSON representor
module.exports = repjson;
function repjson(object) {
// emit the full internal representor graph
return JSON.stringify(object, null, 2);
}
// EOF
| RESTFest/ndcoslo2015 | representors/repjson.js | JavaScript | mit | 469 |
/**
* 拓展对象
*/
exports.extend = function extend(target) {
var sources = Array.prototype.slice.call(arguments, 1);
for (var i = 0; i < sources.length; i += 1) {
var source = sources[i];
for (var key in source) {
if (source.hasOwnProperty(key)) {
target[key] = source[key];
}
}
}
return target;
}; | ymqy/LearnBook | 微信小程序/UI组件/WeApp-Demo/vendor/qcloud-weapp-client-sdk/lib/utils.js | JavaScript | mit | 387 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var InteractivityDetect_1 = require("../../../Enums/InteractivityDetect");
var Events_1 = require("./Events/Events");
var Modes_1 = require("./Modes/Modes");
var HoverMode_1 = require("../../../Enums/Modes/HoverMode");
var Interactivity = (function () {
function Interactivity() {
this.detectsOn = InteractivityDetect_1.InteractivityDetect.canvas;
this.events = new Events_1.Events();
this.modes = new Modes_1.Modes();
}
Object.defineProperty(Interactivity.prototype, "detect_on", {
get: function () {
return this.detectsOn;
},
set: function (value) {
this.detectsOn = value;
},
enumerable: true,
configurable: true
});
Interactivity.prototype.load = function (data, particles) {
var _a, _b, _c;
if (data !== undefined) {
var detectsOn = (_a = data.detectsOn) !== null && _a !== void 0 ? _a : data.detect_on;
if (detectsOn !== undefined) {
this.detectsOn = detectsOn;
}
this.events.load(data.events);
this.modes.load(data.modes, particles);
if (((_c = (_b = data.modes) === null || _b === void 0 ? void 0 : _b.slow) === null || _c === void 0 ? void 0 : _c.active) === true) {
if (this.events.onHover.mode instanceof Array) {
if (this.events.onHover.mode.indexOf(HoverMode_1.HoverMode.slow) < 0) {
this.events.onHover.mode.push(HoverMode_1.HoverMode.slow);
}
}
else if (this.events.onHover.mode !== HoverMode_1.HoverMode.slow) {
this.events.onHover.mode = [this.events.onHover.mode, HoverMode_1.HoverMode.slow];
}
}
}
};
return Interactivity;
}());
exports.Interactivity = Interactivity;
| cdnjs/cdnjs | ajax/libs/tsparticles/1.13.0/Classes/Options/Interactivity/Interactivity.js | JavaScript | mit | 1,960 |
/*
Copyright (c) 2010, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.com/yui/license.html
version: 3.2.0
build: 2676
*/
YUI.add("dd-gestures",function(A){A.DD.Drag.START_EVENT="gesturemovestart";A.DD.Drag.prototype._prep=function(){this._dragThreshMet=false;var C=this.get("node"),B=A.DD.DDM;C.addClass(B.CSS_PREFIX+"-draggable");C.on(A.DD.Drag.START_EVENT,A.bind(this._handleMouseDownEvent,this),{minDistance:0,minTime:0});C.on("gesturemoveend",A.bind(this._handleMouseUp,this),{standAlone:true});C.on("dragstart",A.bind(this._fixDragStart,this));};A.DD.DDM._setupListeners=function(){var B=A.DD.DDM;this._createPG();this._active=true;A.one(A.config.doc).on("gesturemove",A.throttle(A.bind(B._move,B),B.get("throttleTime")),{standAlone:true});};},"3.2.0",{skinnable:false,requires:["dd-drag","event-synthetic","event-gestures"]}); | dhamma-dev/SEA | web/lib/yui/3.2.0/build/dd/dd-gestures-min.js | JavaScript | gpl-3.0 | 878 |
function testInterpreterReentry4() {
var obj = {a:1, b:1, c:1, d:1, get e() 1000 };
for (var p in obj)
obj[p];
}
testInterpreterReentry4();
| glycerine/vj | src/js-1.8.5/js/src/jit-test/tests/basic/testInterpreterReentry4.js | JavaScript | apache-2.0 | 156 |
"use strict";
var helpers = require("../../helpers/helpers");
exports["Europe/Kaliningrad"] = {
"1916" : helpers.makeTestYear("Europe/Kaliningrad", [
["1916-04-30T21:59:59+00:00", "22:59:59", "CET", -60],
["1916-04-30T22:00:00+00:00", "00:00:00", "CEST", -120],
["1916-09-30T22:59:59+00:00", "00:59:59", "CEST", -120],
["1916-09-30T23:00:00+00:00", "00:00:00", "CET", -60]
]),
"1917" : helpers.makeTestYear("Europe/Kaliningrad", [
["1917-04-16T00:59:59+00:00", "01:59:59", "CET", -60],
["1917-04-16T01:00:00+00:00", "03:00:00", "CEST", -120],
["1917-09-17T00:59:59+00:00", "02:59:59", "CEST", -120],
["1917-09-17T01:00:00+00:00", "02:00:00", "CET", -60]
]),
"1918" : helpers.makeTestYear("Europe/Kaliningrad", [
["1918-04-15T00:59:59+00:00", "01:59:59", "CET", -60],
["1918-04-15T01:00:00+00:00", "03:00:00", "CEST", -120],
["1918-09-16T00:59:59+00:00", "02:59:59", "CEST", -120],
["1918-09-16T01:00:00+00:00", "02:00:00", "CET", -60]
]),
"1940" : helpers.makeTestYear("Europe/Kaliningrad", [
["1940-04-01T00:59:59+00:00", "01:59:59", "CET", -60],
["1940-04-01T01:00:00+00:00", "03:00:00", "CEST", -120]
]),
"1942" : helpers.makeTestYear("Europe/Kaliningrad", [
["1942-11-02T00:59:59+00:00", "02:59:59", "CEST", -120],
["1942-11-02T01:00:00+00:00", "02:00:00", "CET", -60]
]),
"1943" : helpers.makeTestYear("Europe/Kaliningrad", [
["1943-03-29T00:59:59+00:00", "01:59:59", "CET", -60],
["1943-03-29T01:00:00+00:00", "03:00:00", "CEST", -120],
["1943-10-04T00:59:59+00:00", "02:59:59", "CEST", -120],
["1943-10-04T01:00:00+00:00", "02:00:00", "CET", -60]
]),
"1944" : helpers.makeTestYear("Europe/Kaliningrad", [
["1944-04-03T00:59:59+00:00", "01:59:59", "CET", -60],
["1944-04-03T01:00:00+00:00", "03:00:00", "CEST", -120],
["1944-10-02T00:59:59+00:00", "02:59:59", "CEST", -120],
["1944-10-02T01:00:00+00:00", "02:00:00", "CET", -60],
["1944-12-31T22:59:59+00:00", "23:59:59", "CET", -60],
["1944-12-31T23:00:00+00:00", "01:00:00", "CET", -120]
]),
"1945" : helpers.makeTestYear("Europe/Kaliningrad", [
["1945-04-28T21:59:59+00:00", "23:59:59", "CET", -120],
["1945-04-28T22:00:00+00:00", "01:00:00", "CEST", -180],
["1945-10-31T20:59:59+00:00", "23:59:59", "CEST", -180],
["1945-10-31T21:00:00+00:00", "23:00:00", "CET", -120],
["1945-12-31T21:59:59+00:00", "23:59:59", "CET", -120],
["1945-12-31T22:00:00+00:00", "01:00:00", "MSK", -180]
]),
"1981" : helpers.makeTestYear("Europe/Kaliningrad", [
["1981-03-31T20:59:59+00:00", "23:59:59", "MSK", -180],
["1981-03-31T21:00:00+00:00", "01:00:00", "MSD", -240],
["1981-09-30T19:59:59+00:00", "23:59:59", "MSD", -240],
["1981-09-30T20:00:00+00:00", "23:00:00", "MSK", -180]
]),
"1982" : helpers.makeTestYear("Europe/Kaliningrad", [
["1982-03-31T20:59:59+00:00", "23:59:59", "MSK", -180],
["1982-03-31T21:00:00+00:00", "01:00:00", "MSD", -240],
["1982-09-30T19:59:59+00:00", "23:59:59", "MSD", -240],
["1982-09-30T20:00:00+00:00", "23:00:00", "MSK", -180]
]),
"1983" : helpers.makeTestYear("Europe/Kaliningrad", [
["1983-03-31T20:59:59+00:00", "23:59:59", "MSK", -180],
["1983-03-31T21:00:00+00:00", "01:00:00", "MSD", -240],
["1983-09-30T19:59:59+00:00", "23:59:59", "MSD", -240],
["1983-09-30T20:00:00+00:00", "23:00:00", "MSK", -180]
]),
"1984" : helpers.makeTestYear("Europe/Kaliningrad", [
["1984-03-31T20:59:59+00:00", "23:59:59", "MSK", -180],
["1984-03-31T21:00:00+00:00", "01:00:00", "MSD", -240],
["1984-09-29T22:59:59+00:00", "02:59:59", "MSD", -240],
["1984-09-29T23:00:00+00:00", "02:00:00", "MSK", -180]
]),
"1985" : helpers.makeTestYear("Europe/Kaliningrad", [
["1985-03-30T22:59:59+00:00", "01:59:59", "MSK", -180],
["1985-03-30T23:00:00+00:00", "03:00:00", "MSD", -240],
["1985-09-28T22:59:59+00:00", "02:59:59", "MSD", -240],
["1985-09-28T23:00:00+00:00", "02:00:00", "MSK", -180]
]),
"1986" : helpers.makeTestYear("Europe/Kaliningrad", [
["1986-03-29T22:59:59+00:00", "01:59:59", "MSK", -180],
["1986-03-29T23:00:00+00:00", "03:00:00", "MSD", -240],
["1986-09-27T22:59:59+00:00", "02:59:59", "MSD", -240],
["1986-09-27T23:00:00+00:00", "02:00:00", "MSK", -180]
]),
"1987" : helpers.makeTestYear("Europe/Kaliningrad", [
["1987-03-28T22:59:59+00:00", "01:59:59", "MSK", -180],
["1987-03-28T23:00:00+00:00", "03:00:00", "MSD", -240],
["1987-09-26T22:59:59+00:00", "02:59:59", "MSD", -240],
["1987-09-26T23:00:00+00:00", "02:00:00", "MSK", -180]
]),
"1988" : helpers.makeTestYear("Europe/Kaliningrad", [
["1988-03-26T22:59:59+00:00", "01:59:59", "MSK", -180],
["1988-03-26T23:00:00+00:00", "03:00:00", "MSD", -240],
["1988-09-24T22:59:59+00:00", "02:59:59", "MSD", -240],
["1988-09-24T23:00:00+00:00", "02:00:00", "MSK", -180]
]),
"1989" : helpers.makeTestYear("Europe/Kaliningrad", [
["1989-03-25T22:59:59+00:00", "01:59:59", "MSK", -180],
["1989-03-25T23:00:00+00:00", "03:00:00", "MSD", -240],
["1989-09-23T22:59:59+00:00", "02:59:59", "MSD", -240],
["1989-09-23T23:00:00+00:00", "02:00:00", "MSK", -180]
]),
"1990" : helpers.makeTestYear("Europe/Kaliningrad", [
["1990-03-24T22:59:59+00:00", "01:59:59", "MSK", -180],
["1990-03-24T23:00:00+00:00", "03:00:00", "MSD", -240],
["1990-09-29T22:59:59+00:00", "02:59:59", "MSD", -240],
["1990-09-29T23:00:00+00:00", "02:00:00", "MSK", -180]
]),
"1991" : helpers.makeTestYear("Europe/Kaliningrad", [
["1991-03-30T22:59:59+00:00", "01:59:59", "MSK", -180],
["1991-03-30T23:00:00+00:00", "02:00:00", "EEST", -180],
["1991-09-28T23:59:59+00:00", "02:59:59", "EEST", -180],
["1991-09-29T00:00:00+00:00", "02:00:00", "EET", -120]
]),
"1992" : helpers.makeTestYear("Europe/Kaliningrad", [
["1992-03-28T20:59:59+00:00", "22:59:59", "EET", -120],
["1992-03-28T21:00:00+00:00", "00:00:00", "EEST", -180],
["1992-09-26T19:59:59+00:00", "22:59:59", "EEST", -180],
["1992-09-26T20:00:00+00:00", "22:00:00", "EET", -120]
]),
"1993" : helpers.makeTestYear("Europe/Kaliningrad", [
["1993-03-27T23:59:59+00:00", "01:59:59", "EET", -120],
["1993-03-28T00:00:00+00:00", "03:00:00", "EEST", -180],
["1993-09-25T23:59:59+00:00", "02:59:59", "EEST", -180],
["1993-09-26T00:00:00+00:00", "02:00:00", "EET", -120]
]),
"1994" : helpers.makeTestYear("Europe/Kaliningrad", [
["1994-03-26T23:59:59+00:00", "01:59:59", "EET", -120],
["1994-03-27T00:00:00+00:00", "03:00:00", "EEST", -180],
["1994-09-24T23:59:59+00:00", "02:59:59", "EEST", -180],
["1994-09-25T00:00:00+00:00", "02:00:00", "EET", -120]
]),
"1995" : helpers.makeTestYear("Europe/Kaliningrad", [
["1995-03-25T23:59:59+00:00", "01:59:59", "EET", -120],
["1995-03-26T00:00:00+00:00", "03:00:00", "EEST", -180],
["1995-09-23T23:59:59+00:00", "02:59:59", "EEST", -180],
["1995-09-24T00:00:00+00:00", "02:00:00", "EET", -120]
]),
"1996" : helpers.makeTestYear("Europe/Kaliningrad", [
["1996-03-30T23:59:59+00:00", "01:59:59", "EET", -120],
["1996-03-31T00:00:00+00:00", "03:00:00", "EEST", -180],
["1996-10-26T23:59:59+00:00", "02:59:59", "EEST", -180],
["1996-10-27T00:00:00+00:00", "02:00:00", "EET", -120]
]),
"1997" : helpers.makeTestYear("Europe/Kaliningrad", [
["1997-03-29T23:59:59+00:00", "01:59:59", "EET", -120],
["1997-03-30T00:00:00+00:00", "03:00:00", "EEST", -180],
["1997-10-25T23:59:59+00:00", "02:59:59", "EEST", -180],
["1997-10-26T00:00:00+00:00", "02:00:00", "EET", -120]
]),
"1998" : helpers.makeTestYear("Europe/Kaliningrad", [
["1998-03-28T23:59:59+00:00", "01:59:59", "EET", -120],
["1998-03-29T00:00:00+00:00", "03:00:00", "EEST", -180],
["1998-10-24T23:59:59+00:00", "02:59:59", "EEST", -180],
["1998-10-25T00:00:00+00:00", "02:00:00", "EET", -120]
]),
"1999" : helpers.makeTestYear("Europe/Kaliningrad", [
["1999-03-27T23:59:59+00:00", "01:59:59", "EET", -120],
["1999-03-28T00:00:00+00:00", "03:00:00", "EEST", -180],
["1999-10-30T23:59:59+00:00", "02:59:59", "EEST", -180],
["1999-10-31T00:00:00+00:00", "02:00:00", "EET", -120]
]),
"2000" : helpers.makeTestYear("Europe/Kaliningrad", [
["2000-03-25T23:59:59+00:00", "01:59:59", "EET", -120],
["2000-03-26T00:00:00+00:00", "03:00:00", "EEST", -180],
["2000-10-28T23:59:59+00:00", "02:59:59", "EEST", -180],
["2000-10-29T00:00:00+00:00", "02:00:00", "EET", -120]
]),
"2001" : helpers.makeTestYear("Europe/Kaliningrad", [
["2001-03-24T23:59:59+00:00", "01:59:59", "EET", -120],
["2001-03-25T00:00:00+00:00", "03:00:00", "EEST", -180],
["2001-10-27T23:59:59+00:00", "02:59:59", "EEST", -180],
["2001-10-28T00:00:00+00:00", "02:00:00", "EET", -120]
]),
"2002" : helpers.makeTestYear("Europe/Kaliningrad", [
["2002-03-30T23:59:59+00:00", "01:59:59", "EET", -120],
["2002-03-31T00:00:00+00:00", "03:00:00", "EEST", -180],
["2002-10-26T23:59:59+00:00", "02:59:59", "EEST", -180],
["2002-10-27T00:00:00+00:00", "02:00:00", "EET", -120]
]),
"2003" : helpers.makeTestYear("Europe/Kaliningrad", [
["2003-03-29T23:59:59+00:00", "01:59:59", "EET", -120],
["2003-03-30T00:00:00+00:00", "03:00:00", "EEST", -180],
["2003-10-25T23:59:59+00:00", "02:59:59", "EEST", -180],
["2003-10-26T00:00:00+00:00", "02:00:00", "EET", -120]
]),
"2004" : helpers.makeTestYear("Europe/Kaliningrad", [
["2004-03-27T23:59:59+00:00", "01:59:59", "EET", -120],
["2004-03-28T00:00:00+00:00", "03:00:00", "EEST", -180],
["2004-10-30T23:59:59+00:00", "02:59:59", "EEST", -180],
["2004-10-31T00:00:00+00:00", "02:00:00", "EET", -120]
]),
"2005" : helpers.makeTestYear("Europe/Kaliningrad", [
["2005-03-26T23:59:59+00:00", "01:59:59", "EET", -120],
["2005-03-27T00:00:00+00:00", "03:00:00", "EEST", -180],
["2005-10-29T23:59:59+00:00", "02:59:59", "EEST", -180],
["2005-10-30T00:00:00+00:00", "02:00:00", "EET", -120]
]),
"2006" : helpers.makeTestYear("Europe/Kaliningrad", [
["2006-03-25T23:59:59+00:00", "01:59:59", "EET", -120],
["2006-03-26T00:00:00+00:00", "03:00:00", "EEST", -180],
["2006-10-28T23:59:59+00:00", "02:59:59", "EEST", -180],
["2006-10-29T00:00:00+00:00", "02:00:00", "EET", -120]
]),
"2007" : helpers.makeTestYear("Europe/Kaliningrad", [
["2007-03-24T23:59:59+00:00", "01:59:59", "EET", -120],
["2007-03-25T00:00:00+00:00", "03:00:00", "EEST", -180],
["2007-10-27T23:59:59+00:00", "02:59:59", "EEST", -180],
["2007-10-28T00:00:00+00:00", "02:00:00", "EET", -120]
]),
"2008" : helpers.makeTestYear("Europe/Kaliningrad", [
["2008-03-29T23:59:59+00:00", "01:59:59", "EET", -120],
["2008-03-30T00:00:00+00:00", "03:00:00", "EEST", -180],
["2008-10-25T23:59:59+00:00", "02:59:59", "EEST", -180],
["2008-10-26T00:00:00+00:00", "02:00:00", "EET", -120]
]),
"2009" : helpers.makeTestYear("Europe/Kaliningrad", [
["2009-03-28T23:59:59+00:00", "01:59:59", "EET", -120],
["2009-03-29T00:00:00+00:00", "03:00:00", "EEST", -180],
["2009-10-24T23:59:59+00:00", "02:59:59", "EEST", -180],
["2009-10-25T00:00:00+00:00", "02:00:00", "EET", -120]
]),
"2010" : helpers.makeTestYear("Europe/Kaliningrad", [
["2010-03-27T23:59:59+00:00", "01:59:59", "EET", -120],
["2010-03-28T00:00:00+00:00", "03:00:00", "EEST", -180],
["2010-10-30T23:59:59+00:00", "02:59:59", "EEST", -180],
["2010-10-31T00:00:00+00:00", "02:00:00", "EET", -120]
]),
"2011" : helpers.makeTestYear("Europe/Kaliningrad", [
["2011-03-26T23:59:59+00:00", "01:59:59", "EET", -120],
["2011-03-27T00:00:00+00:00", "03:00:00", "FET", -180]
]),
"2014" : helpers.makeTestYear("Europe/Kaliningrad", [
["2014-10-25T22:59:59+00:00", "01:59:59", "FET", -180],
["2014-10-25T23:00:00+00:00", "01:00:00", "EET", -120]
])
}; | Bladefidz/ocfa_yii | vendor/bower-asset/moment-timezone/tests/zones/europe/kaliningrad.js | JavaScript | bsd-3-clause | 11,587 |
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'fakeobjects', 'th', {
anchor: 'แทรก/แก้ไข Anchor',
flash: 'ภาพอนิเมชั่นแฟลช',
hiddenfield: 'ฮิดเดนฟิลด์',
iframe: 'IFrame',
unknown: 'วัตถุไม่ทราบชนิด'
} );
| SeeyaSia/www | web/libraries/ckeditor/plugins/fakeobjects/lang/th.js | JavaScript | gpl-2.0 | 436 |
$(document).keydown(function (event) {
if (event.ctrlKey) {
if (event.key === "Enter") {
if ($(".form.factory").is(":visible")) {
$("#SaveButton").trigger("click");
return false;
};
};
};
}); | Johann-Schwarz/mixerp | src/FrontEnd/Scripts/Modules/ScrudFactory/form/event-on-doc-keydown.js | JavaScript | gpl-3.0 | 274 |
import React, {PropTypes} from 'react';
const FuelSavingsTextInput = (props) => {
const handleChange = (e) => {
props.onChange(props.name, e.target.value);
};
return (
<input
className="small"
type="text"
placeholder={props.placeholder}
value={props.value}
onChange={handleChange}/>
);
};
FuelSavingsTextInput.propTypes = {
name: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
placeholder: PropTypes.string,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
])
};
export default FuelSavingsTextInput;
| Takaitra/RecipeRunt | web/src/components/FuelSavingsTextInput.js | JavaScript | apache-2.0 | 602 |