repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
minemidnight/eris-additions | lib/Role/addable.js | 362 | module.exports = Eris => {
Object.defineProperty(Eris.Role.prototype, "addable", {
get: function() {
const clientMember = this.guild.members.get(this.guild.shard.client.user.id);
return clientMember.permission.has("manageRoles") && clientMember.highestRole.higherThan(this);
}
});
};
module.exports.deps = ["Member.highestRole", "Role.higherThan"];
| mit |
neowutran/Nuitinfo | nuitinfo/protected/common/extensions/EGMap/EGMapRectangle.php | 7952 | <?php
/**
*
* EGMapRectangle
* A GoogleMap Rectangle
*
* @author Antonio Ramirez Cobos
*
* Example:
*
* $bounds = new EGMapBounds(new EGMapCoord(25.774252, -80.190262),new EGMapCoord(32.321384, -64.75737) );
* $rec = new EGMapRectangle($bounds);
* $rec->addHtmlInfoWindow(new EGMapInfoWindow('Hey! I am a rectangle!'));
* $gMap->addRectangle($rec);
*
*
* @copyright
*
* Copyright (c) 2011 Antonio Ramirez
* 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.
*
*/
class EGMapRectangle extends EGMapBase
{
protected $options = array(
// LatLngBounds The bounds.
'bounds' => null, // EGMapBounds
// Indicates whether this Rectangle handles click events. Defaults to true.
'clickable' => true,
// Map on which to display Circle.
'map' => null,
// stroke color of the edge of the rectangle
'strokeColor' => '"#FF0000"',
//stroke opacity of the edge of the rectangle
'strokeOpacity' => 0.8,
//stroke weight of the edge of the rectangle
'strokeWeight' => 2,
//fill color of the rectangle
'fillColor' => '"#FF0000"',
//fill opacity of the rectangle
'fillOpacity' => 0.35,
'zIndex' => 0
);
/**
*
* Info window object attached to the object
*
* @var EGMapInfoWindow
*/
protected $info_window = null;
/**
*
* If the Info window is shared or not
*
* @var boolean
*/
protected $info_window_shared = false;
/**
*
* Events attached to the object
*
* @var array
*/
protected $events = null;
/**
*
* google maps js object name
*
* @var string
*/
protected $rectangle_object = 'google.maps.Rectangle';
/**
*
* @param EGMapBounds bounds coordinates of the rectangle
* @param string $js_name name of the rectangle variable
* @param array $options of the rectangle
* @param EGmapEvent[] array of GoogleMap Events linked to the rectangle
*
* @author Antonio Ramirez
*/
public function __construct(EGMapBounds $bounds, $options = array(), $js_name = 'rectangle', $events = array())
{
if ($js_name !== 'rectangle') {
$this->setJsName($js_name);
}
$this->setOptions($options);
$this->setBounds($bounds);
$this->events = new CTypedList('EGMapEvent');
$this->setEvents($events);
}
/**
*
* Batch set events by an array of EGMapEvents
*
* @param array $events
*/
public function setEvents($events)
{
if (!is_array($events)) {
throw new CException(Yii::t(
'EGMap',
'Parameter of "{class}.{method}" {e}.',
array('{class}' => get_class($this), '{method}' => 'setEvents', '{e}' => 'must be of type array')
));
}
if (null === $this->events) {
$this->events = new CTypedList('EGMapEvent');
}
foreach ($events as $e) {
$this->events->add($e);
}
}
/**
* Adds an event listener to the marker
*
* @param EGMapEvent $event
*/
public function addEvent(EGMapEvent $event)
{
$this->events->add($event);
}
/**
* @param array $options
*
* @author Antonio Ramirez
*/
public function setOptions($options)
{
$this->options = array_merge($this->options, $options);
}
/**
* gets the bounds of the rectangle
*
* @return EGMapBounds | null $bounds
* @author Antonio Ramirez
*/
public function getBounds()
{
return $this->options['bounds'];
}
/**
* sets the bounds coordinates of the rectangle
*
* @param EGMapBounds $bounds
*
* @author Antonio Ramirez Cobos
*/
public function setBounds(EGMapBounds $bounds)
{
$this->options['bounds'] = $bounds;
}
/**
*
* Return center of bounds
*/
public function getCenterOfBounds()
{
if (null !== $this->getBounds() && $this->getBounds() instanceof EGMapBounds) {
return $this->getBounds()->getCenterCoord();
}
return null;
}
/**
* @param string $map_js_name
*
* @return string Javascript code to create the rectangle
* @author Antonio Ramirez
*/
public function toJs($map_js_name = 'map')
{
$this->options['map'] = $map_js_name;
$return = '';
if (null !== $this->info_window) {
if ($this->info_window_shared) {
$info_window_name = $map_js_name . '_info_window';
$this->addEvent(
new EGMapEvent(
'click',
'if (' . $info_window_name . ') ' . $info_window_name . '.close();' . PHP_EOL .
$info_window_name . ' = ' . $this->info_window->getJsName() . ';' . PHP_EOL .
$info_window_name . ".setPosition(" . $this->getCenterOfBounds()->toJs() . ");" . PHP_EOL .
$info_window_name . ".open(" . $map_js_name . ");" . PHP_EOL
)
);
} else {
$this->addEvent(
new EGMapEvent('click',
$this->info_window->getJsName() . ".setPosition(" . $this->getCenterOfBounds()->toJs(
) . ");" . PHP_EOL .
$this->info_window->getJsName() . ".open(" . $map_js_name . ");" . PHP_EOL
)
);
}
$return .= $this->info_window->toJs();
}
$return .= 'var ' . $this->getJsName() . ' = new ' . $this->rectangle_object . '(' . EGMap::encode(
$this->options
) . ');' . PHP_EOL;
foreach ($this->events as $event) {
$return .= $event->getEventJs($this->getJsName()) . PHP_EOL;
}
return $return;
}
/**
* Adds an onlick listener that open a html window with some text
*
* @param EGMapInfoWindow $info_window
* @param boolean $shared among other markers (unique info_window display)
*
* @author Antonio Ramirez
*/
public function addHtmlInfoWindow(EGMapInfoWindow $info_window, $shared = true)
{
$this->info_window = $info_window;
$this->info_window_shared = $shared;
}
/**
*
* @return boolean if info window is shared or not
*/
public function htmlInfoWindowShared()
{
return $this->info_window_shared;
}
/**
* @return EGMapInfoWindow
* @author Antonio Ramirez
*/
public function getHtmlInfoWindow()
{
return $this->info_window;
}
}
| mit |
Caroga/AngularBOX | Gruntfile.js | 4128 | module.exports = function (grunt) {
grunt.initConfig({
//Read package information
pkg: grunt.file.readJSON('package.json'),
bower: {
install: {
options: {
targetDir: './vendor',
install: true,
verbose: true,
cleanTargetDir: true,
//cleanBowerDir: true,
bowerOptions: {}
}
}
},
concat: {
options: {
separator: ';',
stripBanners: {'block': true, 'line': true},
banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
},
dist: {
src: [
'vendor/angular/angular.js',
'vendor/jquery/jquery.js',
'vendor/**/*.js',
'src/app/app.js'
],
dest: 'web/js/app.js' //<%= pkg.name %>-<%= pkg.version %>.js
}
},
uglify: {
dist: {
files: {
'web/js/app.js': 'web/js/app.js'
}
}
},
copy: {
dist: {
files: [{
flatten: true,
src: 'src/index.html',
dest: 'web/index.html'
}, {
expand: true,
cwd: 'src/assets/images',
src: '*',
dest: 'web/images/'
},{
expand: true,
cwd: 'bower_components/bootstrap/fonts/',
src: 'glyphicons-halflings-regular.*',
dest: 'web/fonts/'
},{
expand: true,
cwd: 'bower_components/components-font-awesome/fonts',
src: '*',
dest: 'web/fonts/'
},{
// Added seperate copy task since grunt-bower cannot handle export overrides properly
cwd: "bower_components/bootstrap",
expand: true,
flatten: true,
src: "less/*.less",
dest: "vendor/bootstrap/"
},{
// Added seperate copy task since grunt-bower cannot handle export overrides properly
cwd: "bower_components/bootstrap",
expand: true,
flatten: true,
src: "less/mixins/*.less",
dest: "vendor/bootstrap/mixins"
}
]
}
},
watch: {
scripts: {
files: [
'src/**/*.js',
'src/**/*.html',
'src/**/*.less'
],
tasks: ['compile']
}
},
less: {
dist: {
options: {
paths: ['vendor/bootstrap'],
compress: true,
cleancss: true
},
files: {
"web/css/style.css": [
"src/assets/less/bootstrap.less",
"vendor/components-font-awesome/font-awesome.css",
"src/assets/less/style.less"
]
}
}
},
clean: {
dist: {
src: ["bower_components"]
}
}
});
grunt.loadNpmTasks('grunt-bower-task');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.registerTask('default', ['bower:install', 'compile']);
grunt.registerTask('compile', ['concat:dist', 'copy:dist', 'less:dist', 'clean:dist','uglify']);
};
| mit |
dalezak/Saskatoon_AED_Locations | hooks/after_platform_add/010_install_sim.js | 458 | #!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;
var root = process.argv[2];
var platform = process.env.CORDOVA_PLATFORMS;
function puts(error, stdout, stderr) {
console.log(stdout);
}
function installCordovaIosSim() {
process.stdout.write("installCordovaIosSim");
exec("cd platforms/ios/cordova && npm install ios-sim", puts)
}
if (platform === 'ios') {
installCordovaIosSim();
}
| mit |
apixphp/restapixlib | src/apix/bin/commands/execution/services/socialize.php | 1433 | <?php
namespace Src\App\__projectName__\V1\Config;
class Socialize
{
/**
* project socialize git repo config.
*
* static call git repo settings for every service.
* @return array
*/
public static function gitRepo()
{
return [
'remote'=>[
'origin'=>[
'url'=>null
]
]
];
}
/**
* project socialize facebook config.
*
* static call facebook settings for every service.
* @return array
*/
public static function facebook()
{
return [
'accessToken'=>'xxx',
'appId'=>'xxx',
'appSecret'=>'xxx',
'appVersion'=>'xxx'
];
}
/**
* project socialize instagram config.
*
* static call instagram settings for every service.
* @return array
*/
public static function instagram()
{
return [
];
}
/**
* project socialize twitter config.
*
* static call twitter settings for every service.
* @return array
*/
public static function twitter()
{
return [
];
}
/**
* project socialize googlePlus config.
*
* static call googlePlus settings for every service.
* @return array
*/
public static function googlePlus()
{
return [
];
}
}
| mit |
G43riko/JavaUtils | GLib2/src/main/java/org/utils/logger/GLogger.java | 3145 | package org.utils.logger;
import org.utils.enums.Keys;
import java.io.PrintStream;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
public class GLogger {
private static final List<Wrapper> logs = new LinkedList<>();
private static PrintStream logStream;
private static PrintStream errorStream;
private static LogTypes type = LogTypes.LOGS;
public static void setStreams() {
setStream(System.out, System.err);
}
public static void log(GLog log, String... params) {
Wrapper wrapper = new Wrapper(params);
wrapper.log = log;
logs.add(wrapper);
if (type == LogTypes.LOGS || type == LogTypes.PRINTS) {
if (logStream == null) {
throwError(GError.UNSET_LOG_STREAM);
}
logStream.println(log + Keys.SPACE.value + String.join(Keys.SPACE.value, params));
}
}
public static void setStream(PrintStream logStream, PrintStream errorStream) {
GLogger.logStream = logStream;
GLogger.errorStream = errorStream;
}
public static void setLogStream(PrintStream logStream) {
GLogger.logStream = logStream;
}
public static void setErrorStream(PrintStream errorStream) {
GLogger.errorStream = errorStream;
}
public static void print(String... params) {
if (type == LogTypes.PRINTS || type == LogTypes.LOGS || type == LogTypes.ERRORS) {
if (logStream == null) {
throwError(GError.UNSET_LOG_STREAM);
}
logStream.println(String.join(Keys.SPACE.value, params));
}
}
public static void error(GError error, String... params) {
logs.add(new Wrapper(error, params));
if (type == LogTypes.LOGS || type == LogTypes.ERRORS || type == LogTypes.PRINTS) {
if (logStream == null) {
throwError(GError.UNSET_LOG_STREAM);
}
errorStream.println(error + Keys.SPACE.value + String.join(Keys.SPACE.value, params));
}
}
public static void setLogType(LogTypes type) {
GLogger.type = type;
}
public static void throwError(GError gError) {
throw getError(gError);
}
private static Error getError(GError gError) {
return new Error(gError.toString());
}
public static void error(GError error, Exception exception, String... params) {
logs.add(new Wrapper(error, exception, params));
if (type == LogTypes.LOGS || type == LogTypes.ERRORS) {
if (logStream == null) {
throwError(GError.UNSET_LOG_STREAM);
}
errorStream.println(error + Keys.SPACE.value + String.join(Keys.SPACE.value, params));
}
}
public static List<Wrapper> getLogs() {
return logs.stream().filter(Wrapper::isLog).collect(Collectors.toList());
}
public static List<Wrapper> getErrors() {
return logs.stream().filter(Wrapper::isError).collect(Collectors.toList());
}
public enum LogTypes {
NONE, ERRORS, PRINTS, LOGS
}
}
| mit |
nsanitate/DefinitelyTyped | slickgrid/SlickGrid.d.ts | 51048 | // Type definitions for SlickGrid 2.1.0
// Project: https://github.com/mleibman/SlickGrid
// Definitions by: Josh Baldwin <https://github.com/jbaldwin/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/*
SlickGrid-2.1.d.ts may be freely distributed under the MIT license.
Copyright (c) 2013 Josh Baldwin https://github.com/jbaldwin/SlickGrid.d.ts
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.
*/
/// <reference path="../jquery/jquery.d.ts" />
interface DOMEvent extends Event {}
declare module Slick {
/**
* slick.core.js
**/
/**
* An event object for passing data to event handlers and letting them control propagation.
* <p>This is pretty much identical to how W3C and jQuery implement events.</p>
* @class EventData
* @constructor
**/
export class EventData {
constructor();
/***
* Stops event from propagating up the DOM tree.
* @method stopPropagation
*/
public stopPropagation(): void;
/***
* Returns whether stopPropagation was called on this event object.
* @method isPropagationStopped
* @return {Boolean}
*/
public isPropagationStopped(): boolean;
/***
* Prevents the rest of the handlers from being executed.
* @method stopImmediatePropagation
*/
public stopImmediatePropagation(): void;
/***
* Returns whether stopImmediatePropagation was called on this event object.\
* @method isImmediatePropagationStopped
* @return {Boolean}
*/
public isImmediatePropagationStopped(): boolean;
}
/***
* A simple publisher-subscriber implementation.
* @class Event
* @constructor
*/
export class Event<T> {
constructor();
/***
* Adds an event handler to be called when the event is fired.
* <p>Event handler will receive two arguments - an <code>EventData</code> and the <code>data</code>
* object the event was fired with.<p>
* @method subscribe
* @param fn {Function} Event handler.
*/
public subscribe(fn: (eventData: EventData, data: T) => any ): void;
/***
* Removes an event handler added with <code>subscribe(fn)</code>.
* @method unsubscribe
* @param fn {Function} Event handler to be removed.
*/
public unsubscribe(fn: (eventData: EventData, data: T) => any ): void;
/***
* Fires an event notifying all subscribers.
* @method notify
* @param args {Object} Additional data object to be passed to all handlers.
* @param e {EventData}
* Optional.
* An <code>EventData</code> object to be passed to all handlers.
* For DOM events, an existing W3C/jQuery event object can be passed in.
* @param scope {Object}
* Optional.
* The scope ("this") within which the handler will be executed.
* If not specified, the scope will be set to the <code>Event</code> instance.
* @return Last run callback result.
* @note slick.core.Event.notify shows this method as returning a value, type is unknown.
*/
public notify(args?: T, e?: EventData, scope?: any): any;
public notify(args?: T, e?: DOMEvent, scope?: any): any;
}
// todo: is this private? there are no comments in the code
export class EventHandler {
constructor();
public subscribe(event: EventData, handler: Function): EventHandler;
public unsubscribe(event: EventData, handler: Function): EventHandler;
public unsubscribeAll(): EventHandler;
}
/***
* A structure containing a range of cells.
* @class Range
**/
export class Range {
/**
* A structure containing a range of cells.
* @constructor
* @param fromRow {Integer} Starting row.
* @param fromCell {Integer} Starting cell.
* @param toRow {Integer} Optional. Ending row. Defaults to <code>fromRow</code>.
* @param toCell {Integer} Optional. Ending cell. Defaults to <code>fromCell</code>.
**/
constructor(fromRow: number, fromCell: number, toRow?: number, toCell?: number);
/***
* @property fromRow
* @type {Integer}
*/
public fromRow: number;
/***
* @property fromCell
* @type {Integer}
*/
public fromCell: number;
/***
* @property toRow
* @type {Integer}
*/
public toRow: number;
/***
* @property toCell
* @type {Integer}
*/
public toCell: number;
/***
* Returns whether a range represents a single row.
* @method isSingleRow
* @return {Boolean}
*/
public isSingleRow(): boolean;
/***
* Returns whether a range represents a single cell.
* @method isSingleCell
* @return {Boolean}
*/
public isSingleCell(): boolean;
/***
* Returns whether a range contains a given cell.
* @method contains
* @param row {Integer}
* @param cell {Integer}
* @return {Boolean}
*/
public contains(row: number, cell: number): boolean;
/***
* Returns a readable representation of a range.
* @method toString
* @return {String}
*/
public toString(): string;
}
/***
* A base class that all special / non-data rows (like Group and GroupTotals) derive from.
* @class NonDataItem
* @constructor
*/
export class NonDataRow {
}
/***
* Information about a group of rows.
* @class Group
* @extends Slick.NonDataItem
* @constructor
*/
export class Group<T, R> extends NonDataRow {
constructor();
/**
* Grouping level, starting with 0.
* @property level
* @type {Number}
*/
public level: number;
/***
* Number of rows in the group.
* @property count
* @type {Integer}
*/
public count: number;
/***
* Grouping value.
* @property value
* @type {Object}
*/
public value: T;
/***
* Formatted display value of the group.
* @property title
* @type {String}
*/
public title: string;
/***
* Whether a group is collapsed.
* @property collapsed
* @type {Boolean}
*/
public collapsed: boolean;
/***
* GroupTotals, if any.
* @property totals
* @type {GroupTotals}
*/
public totals: GroupTotals<T, R>;
/**
* Rows that are part of the group.
* @property rows
* @type {Array}
*/
public rows: R[];
/**
* Sub-groups that are part of the group.
* @property groups
* @type {Array}
*/
public groups: Group<T, R>[];
/**
* A unique key used to identify the group. This key can be used in calls to DataView
* collapseGroup() or expandGroup().
* @property groupingKey
* @type {Object}
*/
public groupingKey: any;
/***
* Compares two Group instances.
* @method equals
* @return {Boolean}
* @param group {Group} Group instance to compare to.
* todo: this is on the prototype (NonDataRow()) instance, not Group, maybe doesn't matter?
*/
public equals(group: Group<T, R>): boolean;
}
/***
* Information about group totals.
* An instance of GroupTotals will be created for each totals row and passed to the aggregators
* so that they can store arbitrary data in it. That data can later be accessed by group totals
* formatters during the display.
* @class GroupTotals
* @extends Slick.NonDataItem
* @constructor
*/
export class GroupTotals<T, R> extends NonDataRow {
constructor();
/***
* Parent Group.
* @param group
* @type {Group}
*/
public group: Group<T, R>;
}
/***
* A locking helper to track the active edit controller and ensure that only a single controller
* can be active at a time. This prevents a whole class of state and validation synchronization
* issues. An edit controller (such as SlickGrid) can query if an active edit is in progress
* and attempt a commit or cancel before proceeding.
* @class EditorLock
* @constructor
*/
export class EditorLock<T extends Slick.SlickData> {
constructor();
/***
* Returns true if a specified edit controller is active (has the edit lock).
* If the parameter is not specified, returns true if any edit controller is active.
* @method isActive
* @param editController {EditController}
* @return {Boolean}
*/
public isActive(editController: Editors.Editor<T>): boolean;
/***
* Sets the specified edit controller as the active edit controller (acquire edit lock).
* If another edit controller is already active, and exception will be thrown.
* @method activate
* @param editController {EditController} edit controller acquiring the lock
*/
public activate(editController: Editors.Editor<T>): void;
/***
* Unsets the specified edit controller as the active edit controller (release edit lock).
* If the specified edit controller is not the active one, an exception will be thrown.
* @method deactivate
* @param editController {EditController} edit controller releasing the lock
*/
public deactivate(editController: Editors.Editor<T>): void;
/***
* Attempts to commit the current edit by calling "commitCurrentEdit" method on the active edit
* controller and returns whether the commit attempt was successful (commit may fail due to validation
* errors, etc.). Edit controller's "commitCurrentEdit" must return true if the commit has succeeded
* and false otherwise. If no edit controller is active, returns true.
* @method commitCurrentEdit
* @return {Boolean}
*/
public commitCurrentEdit(): boolean;
/***
* Attempts to cancel the current edit by calling "cancelCurrentEdit" method on the active edit
* controller and returns whether the edit was successfully cancelled. If no edit controller is
* active, returns true.
* @method cancelCurrentEdit
* @return {Boolean}
*/
public cancelCurrentEdit(): boolean;
}
/**
* A global singleton editor lock.
* @class GlobalEditorLock
* @static
* @constructor
**/
export var GlobalEditorLock: EditorLock<Slick.SlickData>;
/**
* slick.grid.js
**/
/**
* Options which you can apply to the columns objects.
**/
export interface Column<T extends Slick.SlickData> {
/**
* This accepts a function of the form function(cellNode, row, dataContext, colDef) and is used to post-process the cell's DOM node / nodes
* @param cellNode
* @param row
* @param dataContext
* @param colDef
* @return
**/
asyncPostRender?: (cellNode:any, row:any, dataContext:any, colDef:any) => void;
/**
* Used by the the slick.rowMoveManager.js plugin for moving rows. Has no effect without the plugin installed.
**/
behavior?: any;
/**
* In the "Add New" row, determines whether clicking cells in this column can trigger row addition. If true, clicking on the cell in this column in the "Add New" row will not trigger row addition.
**/
cannotTriggerInsert?: boolean;
/**
* Accepts a string as a class name, applies that class to every row cell in the column.
**/
cssClass?: string;
/**
* When set to true, the first user click on the header will do a descending sort. When set to false, the first user click on the header will do an ascending sort.
**/
defaultSortAsc?: boolean;
/**
* The editor for cell edits {TextEditor, IntegerEditor, DateEditor...} See slick.editors.js
**/
editor?: any; // typeof Editors.Editor<T>;
/**
* The property name in the data object to pull content from. (This is assumed to be on the root of the data object.)
**/
field?: string;
/**
* When set to false, clicking on a cell in this column will not select the row for that cell. The cells in this column will also be skipped during tab navigation.
**/
focusable?: boolean;
/**
* This accepts a function of the form function(row, cell, value, columnDef, dataContext) and returns a formatted version of the data in each cell of this column. For example, setting formatter to function(r, c, v, cd, dc) { return "Hello!"; } would overwrite every value in the column with "Hello!" See defaultFormatter in slick.grid.js for an example formatter.
* @param row
* @param cell
* @param value
* @param columnDef
* @param dataContext
* @return
**/
formatter?: Formatter<T>;
/**
* Accepts a string as a class name, applies that class to the cell for the column header.
**/
headerCssClass?: string;
/**
* A unique identifier for the column within the grid.
**/
id?: string;
/**
* Set the maximum allowable width of this column, in pixels.
**/
maxWidth?: number;
/**
* Set the minimum allowable width of this column, in pixels.
**/
minWidth?: number;
/**
* The text to display on the column heading.
**/
name?: string;
/**
* If set to true, whenever this column is resized, the entire table view will rerender.
**/
rerenderOnResize?: boolean;
/**
* If false, column can no longer be resized.
**/
resizable?: boolean;
/**
* If false, when a row is selected, the CSS class for selected cells ("selected" by default) is not applied to the cell in this column.
**/
selectable?: boolean;
/**
* If true, the column will be sortable by clicking on the header.
**/
sortable?: boolean;
/**
* If set to a non-empty string, a tooltip will appear on hover containing the string.
**/
toolTip?: string;
/**
* Width of the column in pixels. (May often be overridden by things like minWidth, maxWidth, forceFitColumns, etc.)
**/
width?: number;
}
export interface EditorFactory {
getEditor<T>(column: Column<T>): Editors.Editor<T>;
}
export interface FormatterFactory<T extends Slick.SlickData> {
getFormatter(column: Column<T>): Formatter<any>;
}
export interface GridOptions<T extends Slick.SlickData> {
/**
* Makes cell editors load asynchronously after a small delay. This greatly increases keyboard navigation speed.
**/
asyncEditorLoading?: boolean;
/**
* Delay after which cell editor is loaded. Ignored unless asyncEditorLoading is true.
**/
asyncEditorLoadDelay?: number;
/**
*
**/
asyncPostRenderDelay?: number;
/**
* Cell will not automatically go into edit mode when selected.
**/
autoEdit?: boolean;
/**
*
**/
autoHeight?: boolean;
/**
* A CSS class to apply to flashing cells via flashCell().
**/
cellFlashingCssClass?: string;
/**
* A CSS class to apply to cells highlighted via setHighlightedCells().
**/
cellHighlightCssClass?: string;
/**
*
**/
dataItemColumnValueExtractor?: any;
/**
*
**/
defaultColumnWidth?: number;
/**
*
**/
defaultFormatter?: Formatter<T>;
/**
*
**/
editable?: boolean;
/**
* Not listed as a default under options in slick.grid.js
**/
editCommandHandler?: any; // queueAndExecuteCommand
/**
* A factory object responsible to creating an editor for a given cell. Must implement getEditor(column).
**/
editorFactory?: EditorFactory;
/**
* A Slick.EditorLock instance to use for controlling concurrent data edits.
**/
editorLock?: EditorLock<T>;
/**
* If true, a blank row will be displayed at the bottom - typing values in that row will add a new one. Must subscribe to onAddNewRow to save values.
**/
enableAddRow?: boolean;
/**
* If true, async post rendering will occur and asyncPostRender delegates on columns will be called.
**/
enableAsyncPostRender?: boolean;
/**
* *WARNING*: Not contained in SlickGrid 2.1, may be deprecated
**/
enableCellRangeSelection?: any;
/**
* Appears to enable cell virtualisation for optimised speed with large datasets
**/
enableCellNavigation?: boolean;
/**
*
**/
enableColumnReorder?: boolean;
/**
* *WARNING*: Not contained in SlickGrid 2.1, may be deprecated
**/
enableRowReordering?: any;
/**
*
**/
enableTextSelectionOnCells?: boolean;
/**
* @see Example: Explicit Initialization
**/
explicitInitialization?: boolean;
/**
* Force column sizes to fit into the container (preventing horizontal scrolling). Effectively sets column width to be 1/Number of Columns which on small containers may not be desirable
**/
forceFitColumns?: boolean;
/**
*
**/
forceSyncScrolling?: boolean;
/**
* A factory object responsible to creating a formatter for a given cell. Must implement getFormatter(column).
**/
formatterFactory?: FormatterFactory<T>;
/**
* Will expand the table row divs to the full width of the container, table cell divs will remain aligned to the left
**/
fullWidthRows?: boolean;
/**
*
**/
headerRowHeight?: number;
/**
*
**/
leaveSpaceForNewRows?: boolean;
/**
* @see Example: Multi-Column Sort
**/
multiColumnSort?: boolean;
/**
*
**/
multiSelect?: boolean;
/**
*
**/
rowHeight?: number;
/**
*
**/
selectedCellCssClass?: string;
/**
*
**/
showHeaderRow?: boolean;
/**
* If true, the column being resized will change its width as the mouse is dragging the resize handle. If false, the column will resize after mouse drag ends.
**/
syncColumnCellResize?: boolean;
/**
*
**/
topPanelHeight?: number;
}
export interface DataProvider<T extends SlickData> {
getItem(index: number): T;
getLength(): number;
}
export interface SlickData {
// todo ? might be able to leave as empty
}
/**
* Selecting cells in SlickGrid is handled by a selection model.
* Selection models are controllers responsible for handling user interactions and notifying subscribers of the changes in the selection. Selection is represented as an array of Slick.Range objects.
* You can get the current selection model from the grid by calling getSelectionModel() and set a different one using setSelectionModel(selectionModel). By default, no selection model is set.
* The grid also provides two helper methods to simplify development - getSelectedRows() and setSelectedRows(rowsArray), as well as an onSelectedRowsChanged event.
* SlickGrid includes two pre-made selection models - Slick.CellSelectionModel and Slick.RowSelectionModel, but you can easily write a custom one.
**/
export class SelectionModel<T extends SlickData, E> {
/**
* An initializer function that will be called with an instance of the grid whenever a selection model is registered with setSelectionModel. The selection model can use this to initialize its state and subscribe to grid events.
**/
init(grid: Grid<T>): void;
/**
* A destructor function that will be called whenever a selection model is unregistered from the grid by a call to setSelectionModel with another selection model or whenever a grid with this selection model is destroyed. The selection model can use this destructor to unsubscribe from grid events and release all resources (remove DOM nodes, event listeners, etc.).
**/
destroy(): void;
onSelectedRangesChanged: Slick.Event<E>;
}
export class Grid<T extends SlickData> {
/**
* Create an instance of the grid.
* @param container Container node to create the grid in. This can be a DOM Element, a jQuery node, or a jQuery selector.
* @param data Databinding source. This can either be a regular JavaScript array or a custom object exposing getItem(index) and getLength() functions.
* @param columns An array of column definition objects. See Column Options for a list of options that can be included on each column definition object.
* @param options Additional options. See Grid Options for a list of options that can be included.
**/
constructor(
container: string,
data: T[],
columns: Column<T>[],
options: GridOptions<T>);
constructor(
container: HTMLElement,
data: T[],
columns: Column<T>[],
options: GridOptions<T>);
constructor(
container: string,
data: DataProvider<T>,
columns: Column<T>[],
options: GridOptions<T>);
constructor(
container: HTMLElement,
data: DataProvider<T>,
columns: Column<T>[],
options: GridOptions<T>);
// #region Core
/**
* Initializes the grid. Called after plugins are registered. Normally, this is called by the constructor, so you don't need to call it. However, in certain cases you may need to delay the initialization until some other process has finished. In that case, set the explicitInitialization option to true and call the grid.init() manually.
**/
public init(): void;
/**
* todo: no docs
**/
public destroy(): void;
/**
* Returns an array of every data object, unless you're using DataView in which case it returns a DataView object.
* @return
**/
public getData(): any;
//public getData(): T[];
// Issue: typescript limitation, cannot differentiate calls by return type only, so need to cast to DataView or T[].
//public getData(): DataView;
/**
* Returns the databinding item at a given position.
* @param index Item index.
* @return
**/
public getDataItem(index: number): T;
/**
* Sets a new source for databinding and removes all rendered rows. Note that this doesn't render the new rows - you can follow it with a call to render() to do that.
* @param newData New databinding source using a regular JavaScript array..
* @param scrollToTop If true, the grid will reset the vertical scroll position to the top of the grid.
**/
public setData(newData: T[], scrollToTop: boolean): void;
/**
* Sets a new source for databinding and removes all rendered rows. Note that this doesn't render the new rows - you can follow it with a call to render() to do that.
* @param newData New databinding source using a custom object exposing getItem(index) and getLength() functions.
* @param scrollToTop If true, the grid will reset the vertical scroll position to the top of the grid.
**/
public setData(newData: DataProvider<T>, scrollToTop: boolean): void;
/**
* Returns the size of the databinding source.
* @return
**/
public getDataLength(): number;
/**
* Returns an object containing all of the Grid options set on the grid. See a list of Grid Options here.
* @return
**/
public getOptions(): GridOptions<any>;
/**
* Returns an array of row indices corresponding to the currently selected rows.
* @return
**/
public getSelectedRows(): number[];
/**
* Returns the current SelectionModel. See here for more information about SelectionModels.
* @return
**/
public getSelectionModel(): SelectionModel<any, any>;
/**
* Extends grid options with a given hash. If an there is an active edit, the grid will attempt to commit the changes and only continue if the attempt succeeds.
* @options An object with configuration options.
**/
public setOptions(options: GridOptions<T>): void;
/**
* Accepts an array of row indices and applies the current selectedCellCssClass to the cells in the row, respecting whether cells have been flagged as selectable.
* @param rowsArray An array of row numbers.
**/
public setSelectedRows(rowsArray: number[]): void;
/**
* Unregisters a current selection model and registers a new one. See the definition of SelectionModel for more information.
* @selectionModel A SelectionModel.
**/
public setSelectionModel(selectionModel: SelectionModel<T, any>): void; // todo: don't know the type of the event data type
// #endregion Core
// #region Columns
/**
* Proportionately resizes all columns to fill available horizontal space. This does not take the cell contents into consideration.
**/
public autosizeColumns(): void;
/**
* Returns the index of a column with a given id. Since columns can be reordered by the user, this can be used to get the column definition independent of the order:
* @param id A column id.
* @return
**/
public getColumnIndex(id: string): number;
/**
* Returns an array of column definitions, containing the option settings for each individual column.
* @return
**/
public getColumns(): Column<T>[];
/**
* Sets grid columns. Column headers will be recreated and all rendered rows will be removed. To rerender the grid (if necessary), call render().
* @param columnDefinitions An array of column definitions.
**/
public setColumns(columnDefinitions: Column<T>[]): void;
/**
* Accepts a columnId string and an ascending boolean. Applies a sort glyph in either ascending or descending form to the header of the column. Note that this does not actually sort the column. It only adds the sort glyph to the header.
* @param columnId
* @param ascending
**/
public setSortColumn(columnId: string, ascending: boolean): void;
/**
* Accepts an array of objects in the form [ { columnId: [string], sortAsc: [boolean] }, ... ]. When called, this will apply a sort glyph in either ascending or descending form to the header of each column specified in the array. Note that this does not actually sort the column. It only adds the sort glyph to the header
* @param cols
**/
public setSortColumns(cols: { columnId: string; sortAsc: boolean }[]): void;
/**
* todo: no docs or comments available
* @return
**/
public getSortColumns(): Column<T>[];
/**
* Updates an existing column definition and a corresponding header DOM element with the new title and tooltip.
* @param columnId Column id.
* @param title New column name.
* @param toolTip New column tooltip.
**/
public updateColumnHeader(columnId: string, title?: string, toolTip?: string): void;
// #endregion Columns
// #region Cells
/**
* Adds an "overlay" of CSS classes to cell DOM elements. SlickGrid can have many such overlays associated with different keys and they are frequently used by plugins. For example, SlickGrid uses this method internally to decorate selected cells with selectedCellCssClass (see options).
* @param key A unique key you can use in calls to setCellCssStyles and removeCellCssStyles. If a hash with that key has already been set, an exception will be thrown.
* @param hash A hash of additional cell CSS classes keyed by row number and then by column id. Multiple CSS classes can be specified and separated by space.
* @example
* {
* 0: {
* "number_column": "cell-bold",
* "title_column": "cell-title cell-highlighted"
* },
* 4: {
* "percent_column": "cell-highlighted"
* }
* }
**/
public addCellCssStyles(key: string, hash: CellCssStylesHash): void;
/**
* Returns true if you can click on a given cell and make it the active focus.
* @param row A row index.
* @param col A column index.
* @return
**/
public canCellBeActive(row: number, col: number): boolean;
/**
* Returns true if selecting the row causes this particular cell to have the selectedCellCssClass applied to it. A cell can be selected if it exists and if it isn't on an empty / "Add New" row and if it is not marked as "unselectable" in the column definition.
* @param row A row index.
* @param col A column index.
* @return
**/
public canCellBeSelected(row: number, col: number): boolean;
/**
* Attempts to switch the active cell into edit mode. Will throw an error if the cell is set to be not editable. Uses the specified editor, otherwise defaults to any default editor for that given cell.
* @param editor A SlickGrid editor (see examples in slick.editors.js).
**/
public editActiveCell(editor: Editors.Editor<T>): void;
/**
* Flashes the cell twice by toggling the CSS class 4 times.
* @param row A row index.
* @param cell A column index.
* @param speed (optional) - The milliseconds delay between the toggling calls. Defaults to 100 ms.
**/
public flashCell(row: number, cell: number, speed?: number): void;
/**
* Returns an object representing the coordinates of the currently active cell:
* @example
* {
* row: activeRow,
* cell: activeCell
* }
* @return
**/
public getActiveCell(): Cell;
/**
* Returns the DOM element containing the currently active cell. If no cell is active, null is returned.
* @return
**/
public getActiveCellNode(): HTMLElement;
/**
* Returns an object representing information about the active cell's position. All coordinates are absolute and take into consideration the visibility and scrolling position of all ancestors.
* @return
**/
public getActiveCellPosition(): CellPosition;
/**
* Accepts a key name, returns the group of CSS styles defined under that name. See setCellCssStyles for more info.
* @param key A string.
* @return
**/
public getCellCssStyles(key: string): CellCssStylesHash;
/**
* Returns the active cell editor. If there is no actively edited cell, null is returned.
* @return
**/
public getCellEditor(): Editors.Editor<any>;
/**
* Returns a hash containing row and cell indexes from a standard W3C/jQuery event.
* @param e A standard W3C/jQuery event.
* @return
**/
public getCellFromEvent<T>(e: Event<T>): Cell; // todo: !! Unsure on return type !!
/**
* Returns a hash containing row and cell indexes. Coordinates are relative to the top left corner of the grid beginning with the first row (not including the column headers).
* @param x An x coordinate.
* @param y A y coordinate.
* @return
**/
public getCellFromPoint(x: number, y: number): Cell; // todo: !! Unsure on return type !!
/**
* Returns a DOM element containing a cell at a given row and cell.
* @param row A row index.
* @param cell A column index.
* @return
**/
public getCellNode(row: number, cell: number): HTMLElement;
/**
* Returns an object representing information about a cell's position. All coordinates are absolute and take into consideration the visibility and scrolling position of all ancestors.
* @param row A row index.
* @param cell A column index.
* @return
**/
public getCellNodeBox(row: number, cell: number): CellPosition;
/**
* Accepts a row integer and a cell integer, scrolling the view to the row where row is its row index, and cell is its cell index. Optionally accepts a forceEdit boolean which, if true, will attempt to initiate the edit dialogue for the field in the specified cell.
* Unlike setActiveCell, this scrolls the row into the viewport and sets the keyboard focus.
* @param row A row index.
* @param cell A column index.
* @param forceEdit If true, will attempt to initiate the edit dialogue for the field in the specified cell.
* @return
**/
public gotoCell(row: number, cell: number, forceEdit?: boolean): void;
/**
* todo: no docs
* @return
**/
public getTopPanel(): HTMLElement;
/**
* todo: no docs
* @param visible
**/
public setTopPanelVisibility(visible: boolean): void;
/**
* todo: no docs
* @param visible
**/
public setHeaderRowVisibility(visible: boolean): void;
/**
* todo: no docs
* @return
**/
public getHeaderRow(): HTMLElement;
/**
* todo: no docs, return type is probably wrong -> "return $header && $header[0]"
* @param columnId
* @return
**/
public getHeaderRowColumn(columnId: string): Column<any>;
/**
* todo: no docs
* @return
**/
public getGridPosition(): CellPosition;
/**
* Switches the active cell one row down skipping unselectable cells. Returns a boolean saying whether it was able to complete or not.
* @return
**/
public navigateDown(): boolean;
/**
* Switches the active cell one cell left skipping unselectable cells. Unline navigatePrev, navigateLeft stops at the first cell of the row. Returns a boolean saying whether it was able to complete or not.
* @return
**/
public navigateLeft(): boolean;
/**
* Tabs over active cell to the next selectable cell. Returns a boolean saying whether it was able to complete or not.
* @return
**/
public navigateNext(): boolean;
/**
* Tabs over active cell to the previous selectable cell. Returns a boolean saying whether it was able to complete or not.
* @return
**/
public navigatePrev(): boolean;
/**
* Switches the active cell one cell right skipping unselectable cells. Unline navigateNext, navigateRight stops at the last cell of the row. Returns a boolean saying whether it was able to complete or not.
* @return
**/
public navigateRight(): boolean;
/**
* Switches the active cell one row up skipping unselectable cells. Returns a boolean saying whether it was able to complete or not.
* @return
**/
public navigateUp(): boolean;
/**
* Removes an "overlay" of CSS classes from cell DOM elements. See setCellCssStyles for more.
* @param key A string key.
**/
public removeCellCssStyles(key: string): void;
/**
* Resets active cell.
**/
public resetActiveCell(): void;
/**
* Sets an active cell.
* @param row A row index.
* @param cell A column index.
**/
public setActiveCell(row: number, cell: number): void;
/**
* Sets CSS classes to specific grid cells by calling removeCellCssStyles(key) followed by addCellCssStyles(key, hash). key is name for this set of styles so you can reference it later - to modify it or remove it, for example. hash is a per-row-index, per-column-name nested hash of CSS classes to apply.
* Suppose you have a grid with columns:
* ["login", "name", "birthday", "age", "likes_icecream", "favorite_cake"]
* ...and you'd like to highlight the "birthday" and "age" columns for people whose birthday is today, in this case, rows at index 0 and 9. (The first and tenth row in the grid).
* @param key A string key. Will overwrite any data already associated with this key.
* @param hash A hash of additional cell CSS classes keyed by row number and then by column id. Multiple CSS classes can be specified and separated by space.
**/
public setCellCssStyles(key: string, hash: CellCssStylesHash): void;
// #endregion Cells
// #region Events
public onScroll: Slick.Event<OnScrollEventData>;
public onSort: Slick.Event<OnSortEventData<T>>;
public onHeaderMouseEnter: Slick.Event<OnHeaderMouseEventData<T>>;
public onHeaderMouseLeave: Slick.Event<OnHeaderMouseEventData<T>>;
public onHeaderContextMenu: Slick.Event<OnHeaderContextMenuEventData<T>>;
public onHeaderClick: Slick.Event<OnHeaderClickEventData<T>>;
public onHeaderCellRendered: Slick.Event<OnHeaderCellRenderedEventData<T>>;
public onBeforeHeaderCellDestroy: Slick.Event<OnBeforeHeaderCellDestroyEventData<T>>;
public onHeaderRowCellRendered: Slick.Event<OnHeaderRowCellRenderedEventData<T>>;
public onBeforeHeaderRowCellDestroy: Slick.Event<OnBeforeHeaderRowCellDestroyEventData<T>>;
public onMouseEnter: Slick.Event<OnMouseEnterEventData>;
public onMouseLeave: Slick.Event<OnMouseLeaveEventData>;
public onClick: Slick.Event<OnClickEventData>;
public onDblClick: Slick.Event<OnDblClickEventData>;
public onContextMenu: Slick.Event<OnContextMenuEventData>;
public onKeyDown: Slick.Event<OnKeyDownEventData>;
public onAddNewRow: Slick.Event<OnAddNewRowEventData<T>>;
public onValidationError: Slick.Event<OnValidationErrorEventData<T>>;
public onColumnsReordered: Slick.Event<OnColumnsReorderedEventData>;
public onColumnsResized: Slick.Event<OnColumnsResizedEventData>;
public onCellChange: Slick.Event<OnCellChangeEventData<T>>;
public onBeforeEditCell: Slick.Event<OnBeforeEditCellEventData<T>>;
public onBeforeCellEditorDestroy: Slick.Event<OnBeforeCellEditorDestroyEventData<T>>;
public onBeforeDestroy: Slick.Event<OnBeforeDestroyEventData>;
public onActiveCellChanged: Slick.Event<OnActiveCellChangedEventData>;
public onActiveCellPositionChanged: Slick.Event<OnActiveCellPositionChangedEventData>;
public onDragInit: Slick.Event<OnDragInitEventData>;
public onDragStart: Slick.Event<OnDragStartEventData>;
public onDrag: Slick.Event<OnDragEventData>;
public onDragEnd: Slick.Event<OnDragEndEventData>;
public onSelectedRowsChanged: Slick.Event<OnSelectedRowsChangedEventData>;
public onCellCssStylesChanged: Slick.Event<OnCellCssStylesChangedEventData>;
public onViewportChanged: Slick.Event<OnViewportChangedEventData>;
// #endregion Events
// #region Plugins
public registerPlugin(plugin: Plugin<T>): void;
public unregisterPlugin(plugin: Plugin<T>): void;
// #endregion Plugins
// #region Rendering
public render(): void;
public invalidate(): void;
public invalidateRow(row: number): void;
public invalidateRows(rows: number[]): void;
public updateCell(row: number, cell: number): void;
public updateRow(row: number): void;
public getViewport(viewportTop?: number, viewportLeft?: number): Viewport;
public getRenderedRange(viewportTop: number, viewportLeft: number): Viewport;
public resizeCanvas(): void;
public updateRowCount(): void;
public scrollRowIntoView(row: number, doPaging: boolean): void;
public scrollRowToTop(row: number): void;
public scrollCellIntoView(row: number, cell: number, doPaging: boolean): void;
public getCanvasNode(): HTMLCanvasElement;
public focus(): void;
// #endregion Rendering
// #region Editors
public getEditorLock(): EditorLock<any>;
public getEditController(): { commitCurrentEdit():boolean; cancelCurrentEdit():boolean; };
// #endregion Editors
}
export interface OnCellCssStylesChangedEventData {
key: string;
hash: CellCssStylesHash;
}
export interface OnSelectedRowsChangedEventData {
rows: number[];
}
export interface OnDragEndEventData {
// todo: need to understand $canvas drag event parameter's 'dd' object
// the documentation is not enlightening
}
export interface OnDragEventData {
// todo: need to understand $canvas drag event parameter's 'dd' object
// the documentation is not enlightening
}
export interface OnDragStartEventData {
// todo: need to understand $canvas drag event parameter's 'dd' object
// the documentation is not enlightening
}
export interface OnDragInitEventData {
// todo: need to understand $canvas drag event parameter's 'dd' object
// the documentation is not enlightening
}
export interface OnActiveCellPositionChangedEventData {
}
export interface OnActiveCellChangedEventData {
row: number;
cell: number;
}
export interface OnBeforeDestroyEventData {
}
export interface OnBeforeCellEditorDestroyEventData<T extends Slick.SlickData> {
editor: Editors.Editor<T>;
}
export interface OnBeforeEditCellEventData<T extends SlickData> {
row: number;
cell: number;
item: T;
column: Column<T>;
}
export interface OnCellChangeEventData<T extends SlickData> {
row: number;
cell: number;
item: T;
}
export interface OnColumnsResizedEventData {
}
export interface OnColumnsReorderedEventData {
}
export interface OnValidationErrorEventData<T extends SlickData> {
editor: Editors.Editor<T>;
cellNode: HTMLElement;
validationResults: ValidateResults;
row: number;
cell: number;
column: Column<T>;
}
export interface OnAddNewRowEventData<T extends SlickData> {
item: T;
column: Column<T>;
}
export interface OnKeyDownEventData {
row: number;
cell: number;
}
export interface OnContextMenuEventData {
}
export interface OnDblClickEventData {
row: number;
cell: number;
}
export interface OnClickEventData {
row: number;
cell: number;
}
export interface OnMouseLeaveEventData {
}
export interface OnMouseEnterEventData {
}
export interface OnBeforeHeaderRowCellDestroyEventData<T extends SlickData> {
node: HTMLElement; // todo: might be JQuery instance
column: Column<T>;
}
export interface OnHeaderRowCellRenderedEventData<T extends SlickData> {
node: HTMLElement; // todo: might be JQuery instance
column: Column<T>;
}
export interface OnBeforeHeaderCellDestroyEventData<T extends SlickData> {
node: HTMLElement; // todo: might be JQuery instance
column: Column<T>;
}
export interface OnHeaderCellRenderedEventData<T extends SlickData> {
node: HTMLElement; // todo: might be JQuery instance
column: Column<T>;
}
export interface OnHeaderClickEventData<T extends SlickData> {
column: Column<T>;
}
export interface OnHeaderContextMenuEventData<T extends SlickData> {
column: Column<T>;
}
export interface OnHeaderMouseEventData<T extends SlickData> {
column: Column<T>;
}
// todo: merge with existing column definition
export interface Column<T extends SlickData> {
sortCol?: Column<T>;
sortAsc?: boolean;
}
export interface OnSortEventData<T extends SlickData> {
multiColumnSort: boolean;
sortCol?: Column<T>;
sortCols: Column<T>[];
sortAsc?: boolean;
}
export interface OnScrollEventData {
scrollLeft: number;
scrollTop: number;
}
export interface OnViewportChangedEventData {
}
export interface Cell {
row: number;
cell: number;
}
export interface CellPosition extends Position {
bottom: number;
height: number;
right: number;
visible: boolean;
width: number;
}
export interface Position {
top: number;
left: number;
}
export interface CellCssStylesHash {
[index: number]: {
[id: string]: string;
}
}
export interface Viewport {
top: number;
bottom: number;
leftPx: number;
rightPx: number;
}
export interface ValidateResults {
valid: boolean;
msg: string;
}
export module Editors {
export interface EditorOptions<T extends Slick.SlickData> {
column: Column<T>;
container: HTMLElement;
grid: Grid<T>;
}
export class Editor<T extends Slick.SlickData> {
constructor(args: EditorOptions<T>);
public init(): void;
public destroy(): void;
public focus(): void;
public loadValue(item:any): void; // todo: typeof(item)
public applyValue(item:any, state: string): void; // todo: typeof(item)
public isValueChanged(): boolean;
public serializeValue(): any;
public validate(): ValidateResults;
}
export class Text<T extends Slick.SlickData> extends Editor<T> {
constructor(args: EditorOptions<T>);
public getValue(): string;
public setValue(val: string): void;
public serializeValue(): string;
}
export class Integer<T extends Slick.SlickData> extends Editor<T> {
constructor(args: EditorOptions<T>);
public serializeValue(): number;
}
export class Date<T extends Slick.SlickData> extends Editor<T> {
constructor(args: EditorOptions<T>);
public show(): void;
public hide(): void;
public position(position: Position): void;
public serializeValue(): string;
}
export class YesNoSelect<T extends Slick.SlickData> extends Editor<T> {
constructor(args: EditorOptions<T>);
public serializeValue(): boolean;
}
export class Checkbox<T extends Slick.SlickData> extends Editor<T> {
constructor(args: EditorOptions<T>);
public serializeValue(): boolean;
}
export class PercentComplete<T extends Slick.SlickData> extends Editor<T> {
constructor(args: EditorOptions<T>);
public serializeValue(): number;
}
export class LongText<T extends Slick.SlickData> extends Editor<T> {
constructor(args: EditorOptions<T>);
public handleKeyDown(e: DOMEvent): void;
public save(): void;
public cancel(): void;
public hide(): void;
public show(): void;
public position(position: Position): void;
public serializeValue(): string;
}
}
export interface Formatter<T extends Slick.SlickData> {
(row: number, cell: number, value: any, columnDef: Column<T>, dataContext: SlickData): string;
}
export module Formatters {
var PercentComplete: Formatter<Slick.SlickData>;
var PercentCompleteBar: Formatter<Slick.SlickData>;
var YesNo: Formatter<Slick.SlickData>;
var Checkmark: Formatter<Slick.SlickData>;
}
export module Data {
export interface DataViewOptions<T extends Slick.SlickData> {
groupItemMetadataProvider?: GroupItemMetadataProvider<T>;
inlineFilters?: boolean;
}
/**
* Item -> Data by index
* Row -> Data by row
**/
export class DataView<T extends Slick.SlickData> implements DataProvider<T> {
constructor(options?: DataViewOptions<T>);
public beginUpdate(): void;
public endUpdate(): void;
public setPagingOptions(args: PagingOptions): void;
public getPagingInfo(): PagingOptions;
public getItems(): T[];
public setItems(data: T[], objectIdProperty?: string): void;
public setFilter(filterFn: (item: T, args:any) => boolean): void; // todo: typeof(args)
public sort(comparer: Function, ascending: boolean): void; // todo: typeof(comparer), should be the same callback as Array.sort
public fastSort(field: string, ascending: boolean): void;
public fastSort(field: Function, ascending: boolean): void; // todo: typeof(field), should be the same callback as Array.sort
public reSort(): void;
public setGrouping(groupingInfo: GroupingOptions<T>): void;
public getGrouping(): GroupingOptions<T>;
/**
* @deprecated
**/
public groupBy(valueGetter:any, valueFormatter:any, sortComparer:any): void;
/**
* @deprecated
**/
public setAggregators(groupAggregators:any, includeCollapsed:any): void;
/**
* @param level Optional level to collapse. If not specified, applies to all levels.
**/
public collapseAllGroups(level?: number): void;
/**
* @param level Optional level to collapse. If not specified, applies to all levels.
**/
public expandAllGroups(level?: number): void;
/**
* @param varArgs Either a Slick.Group's "groupingKey" property, or a
* variable argument list of grouping values denoting a unique path to the row. For
* example, calling collapseGroup('high', '10%') will collapse the '10%' subgroup of
* the 'high' setGrouping.
*/
public collapseGroup(...varArgs: string[]): void;
/**
* @param varArgs Either a Slick.Group's "groupingKey" property, or a
* variable argument list of grouping values denoting a unique path to the row. For
* example, calling expandGroup('high', '10%') will expand the '10%' subgroup of
* the 'high' setGrouping.
*/
public expandGroup(...varArgs: string[]): void;
public getGroups(): Group<T, any>[];
public getIdxById(id: string): number;
public getRowById(): T;
public getItemById(id: any): T;
public getItemByIdx(): T;
public mapRowsToIds(rowArray: T[]): string[];
public setRefreshHints(hints: RefreshHints): void;
public setFilterArgs(args: any): void;
public refresh(): void;
public updateItem(id: string, item: T): void;
public insertItem(insertBefore: number, item: T): void;
public addItem(item: T): void;
public deleteItem(id: string): void;
public syncGridSelection(grid: Grid<T>, preserveHidden: boolean): void;
public syncGridCellCssStyles(grid: Grid<T>, key: string): void;
public getLength(): number;
public getItem(index: number): T;
public getItemMetadata(): void;
public onRowCountChanged: Slick.Event<OnRowCountChangedEventData>;
public onRowsChanged: Slick.Event<OnRowsChangedEventData>;
public onPagingInfoChanged: Slick.Event<OnPagingInfoChangedEventData>;
}
export interface GroupingOptions<T> {
getter: Function; // todo
formatter: Formatter<T>;
comparer: (a:any, b:any) => any; // todo
predefinedValues: any[]; // todo
aggregators: Aggregators.Aggregator<T>[];
aggregateEmpty: boolean;
aggregateCollapsed: boolean;
aggregateChildGroups: boolean;
collapsed: boolean;
displayTotalsRow: boolean;
}
export interface PagingOptions {
pageSize?: number;
pageNum?: number;
totalRows?: number;
totalPages?: number;
}
export interface RefreshHints {
isFilterNarrowing?: boolean;
isFilterExpanding?: boolean;
isFilterUnchanged?: boolean;
ignoreDiffsBefore?: boolean;
ignoreDiffsAfter?: boolean;
}
export interface OnRowCountChangedEventData {
// empty
}
export interface OnRowsChangedEventData {
// empty
}
export interface OnPagingInfoChangedEventData extends PagingOptions {
}
export module Aggregators {
export class Aggregator<T extends Slick.SlickData> {
public field: string;
public init(): void;
public accumulate(item: T): void;
public storeResult(groupTotals: GroupTotals<T, any>): void; // todo "R"
}
export class Avg<T> extends Aggregator<T> {
}
export class Min<T> extends Aggregator<T> {
}
export class Max<T> extends Aggregator<T> {
}
export class Sum<T> extends Aggregator<T> {
}
}
/***
* Provides item metadata for group (Slick.Group) and totals (Slick.Totals) rows produced by the DataView.
* This metadata overrides the default behavior and formatting of those rows so that they appear and function
* correctly when processed by the grid.
*
* This class also acts as a grid plugin providing event handlers to expand & collapse groups.
* If "grid.registerPlugin(...)" is not called, expand & collapse will not work.
*
* @class GroupItemMetadataProvider
* @module Data
* @namespace Slick.Data
* @constructor
* @param options
*/
export class GroupItemMetadataProvider<T extends Slick.SlickData> {
public init(): void;
public destroy(): void;
public getGroupRowMetadata(): GroupRowMetadata<T>;
public getTotalsRowMetadata(): TotalsRowMetadata<T>;
}
export interface GroupRowMetadata<T extends Slick.SlickData> {
selectable: boolean;
focusable: boolean;
cssClasses: string;
columns: {
0: {
colspan: string;
formatter: Formatter<T>;
editor: Slick.Editors.Editor<T>;
}
};
}
export interface TotalsRowMetadata<T extends Slick.SlickData> {
selectable: boolean;
focusable: boolean;
cssClasses: string;
formatter: Formatter<T>;
editor: Slick.Editors.Editor<T>;
}
export interface GroupItemMetadataProviderOptions {
groupCssClass?: string;
groupTitleCssClass?: string;
totalsCssClass?: string;
groupFocusable?: boolean;
totalsFocusable?: boolean;
toggleCssClass?: string;
toggleExpandedCssCass?: string;
toggleCollapsedCssClass?: string;
enableExpandCollapse?: boolean;
}
//export class RemoteModel {
// public data: any;
// public clear(): any;
// public isDataLoaded(): any;
// public ensureData(): any;
// public reloadData(): any;
// public setSort(): any;
// public setSearch(): any;
// public onDataLoading: Slick.Event<OnDataLoadingEventData>;
// public onDataLoaded: Slick.Event<OnDataLoadedEventData>;
//}
//export interface OnDataLoadingEventData {
//}
//export interface OnDataLoadedEventData {
//}
}
export class Plugin<T extends Slick.SlickData> {
constructor(options: PluginOptions);
public init(grid: Grid<T>): void;
public destroy(): void;
}
export interface PluginOptions {
// extend your plugin options here
}
}
| mit |
TheOpenCloudEngine/metaworks | metaworks3/src/main/java/org/metaworks/component/MenuGroup.ejs.js | 625 | var org_metaworks_component_MenuGroup = function(objectId, className){
this.objectId = objectId;
this.className = className;
this.objectDivId = mw3._getObjectDivId(this.objectId);
this.objectDiv = $('#' + this.objectDivId);
this.object = mw3.objects[this.objectId];
// make menu groups for ArrayFace.ejs
var groupDiv = this.objectDiv.children(':first');
groupDiv.addClass('basic').addClass('fakehbox').addClass('aligncenter');
groupDiv.css({'padding': '0px 5px',
'position': 'static',
'min-width': '0px',
'min-height': '0px',
'max-width': '9990px',
'max-height': '10000px'});
}; | mit |
Azure/azure-sdk-for-ruby | management/azure_mgmt_api_management/lib/2018-06-01-preview/generated/azure_mgmt_api_management/models/error_field_contract.rb | 1778 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::ApiManagement::Mgmt::V2018_06_01_preview
module Models
#
# Error Field contract.
#
class ErrorFieldContract
include MsRestAzure
# @return [String] Property level error code.
attr_accessor :code
# @return [String] Human-readable representation of property-level error.
attr_accessor :message
# @return [String] Property name.
attr_accessor :target
#
# Mapper for ErrorFieldContract class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ErrorFieldContract',
type: {
name: 'Composite',
class_name: 'ErrorFieldContract',
model_properties: {
code: {
client_side_validation: true,
required: false,
serialized_name: 'code',
type: {
name: 'String'
}
},
message: {
client_side_validation: true,
required: false,
serialized_name: 'message',
type: {
name: 'String'
}
},
target: {
client_side_validation: true,
required: false,
serialized_name: 'target',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| mit |
sysid/kg | rain/data_augmentation_test.py | 2909 | # -*- coding: utf-8 -*-
"""
@author: Aaron Sim
Kaggle competition: How Much Did It Rain II
'Dropin' augmentation of test data
"""
import gc
import numpy as np
import pandas as pd
dpath = "./data/rain/"
INPUT_WIDTH = 19 # Any length >= 19, which is the max no. of time obs per hour
#NUM_RAND = 61 # No. of augmented samples
NUM_RAND = 1 # No. of augmented samples
COLUMNS = ['Id','minutes_past', 'radardist_km', 'Ref', 'Ref_5x5_10th',
'Ref_5x5_50th', 'Ref_5x5_90th', 'RefComposite',
'RefComposite_5x5_10th', 'RefComposite_5x5_50th',
'RefComposite_5x5_90th', 'RhoHV', 'RhoHV_5x5_10th',
'RhoHV_5x5_50th', 'RhoHV_5x5_90th', 'Zdr', 'Zdr_5x5_10th',
'Zdr_5x5_50th', 'Zdr_5x5_90th', 'Kdp', 'Kdp_5x5_10th',
'Kdp_5x5_50th', 'Kdp_5x5_90th']
####### 1. Define 'dropin' augmentation function #######
def extend_series(X, rng, target_len=19):
"""Augment time series to a fixed length by duplicating vectors
Args:
X (2D ndarray): Sequence of radar features in a single hour
rng (numpy RandomState object): random number generator
target_len (int): fixed target length of the sequence
Returns:
the augmented sequence
"""
curr_len = X.shape[0]
extra_needed = target_len-curr_len
if (extra_needed > 0):
reps = [1]*(curr_len)
add_ind = rng.randint(0, curr_len, size=extra_needed)
new_reps = [np.sum(add_ind==j) for j in range(curr_len)]
new_reps = np.array(reps) + np.array(new_reps)
X = np.repeat(X, new_reps, axis=0)
return X
####### 2. Create random seeds #######
# Any lists would do...
rng_seed_list1 = [234561, 23451, 2341, 231, 21, 678901, 67891, 6781, 671, 16,
77177]
rng_seed_list2 = [x for x in range(9725, 9727+50*7, 7)]
rng_seed_list3 = [x for x in range(9726, 9728+50*7, 7)]
rng_seed_list = rng_seed_list1 + rng_seed_list2 + rng_seed_list3
assert len(rng_seed_list) >= NUM_RAND
####### 3. Augment training data #######
data = np.load(dpath+"processed_test.npy")
obs_ids_all = np.load("./test/obs_ids_test.npy")
data_pd = pd.DataFrame(data=data[:,0:], columns=COLUMNS)
data_pd_ids_all = np.array(data_pd['Id'])
data_pd_ids_selected = np.in1d(data_pd_ids_all, obs_ids_all)
data_pd_filtered = data_pd[data_pd_ids_selected]
data_pd_gp = pd.groupby(data_pd_filtered, "Id")
data_size = len(data_pd_gp)
for jj, rng_seed in enumerate(rng_seed_list[0:NUM_RAND]):
rng = np.random.RandomState(rng_seed)
output = np.empty((data_size, INPUT_WIDTH, 22))
i = 0
for _, group in data_pd_gp:
group_array = np.array(group)
X = extend_series(group_array[:,1:23], rng, target_len=INPUT_WIDTH)
output[i,:,:] = X[:,:]
i += 1
print("X.shape", X.shape)
print("output.shape", output.shape)
np.save("./test/data_test_augmented_t%s_rand%s.npy" %
(INPUT_WIDTH, jj), output)
gc.collect()
| mit |
surevine/spiffing | src/classification.cc | 2482 | /***
Copyright 2014-2015 Dave Cridland
Copyright 2014-2015 Surevine Ltd
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.
***/
#include <spiffing/classification.h>
#include <spiffing/categorygroup.h>
#include <spiffing/equivclass.h>
#include <spiffing/label.h>
#include <spiffing/exceptions.h>
using namespace Spiffing;
Classification::Classification(lacv_t lacv, std::string const & name, unsigned long hierarchy, bool obsolete)
: m_lacv{lacv}, m_name{name}, m_hierarchy{hierarchy}, m_obsolete{obsolete} {
}
void Classification::addRequiredCategory(std::unique_ptr<CategoryGroup> && reqCats) {
m_reqCats.insert(std::move(reqCats));
}
void Classification::compile(Spif const & spif) {
for (auto & req : m_reqCats) {
req->compile(spif);
}
}
bool Classification::valid(Label const & label) const {
for (auto const & req : m_reqCats) {
if (!req->matches(label)) return false;
}
return true;
}
void Classification::equivEncrypt(std::shared_ptr<EquivClassification> const & equiv) {
m_equivEncrypt.insert(std::make_pair(equiv->policy_id(), equiv));
}
void Classification::equivDecrypt(std::shared_ptr<EquivClassification> const & equiv) {
m_equivDecrypt.insert(std::make_pair(equiv->policy_id(), equiv));
}
std::unique_ptr<Label> Classification::encrypt(Label const & old, std::string const & policy_id) const {
auto i = m_equivEncrypt.find(policy_id);
if (i == m_equivEncrypt.end()) throw equiv_error("No equivalent classification");
auto equiv = (*i).second;
return equiv->create();
}
| mit |
JavadRasouli/angular2-persian-utils | src/services/national-code.service.ts | 1249 | import { Injectable } from '@angular/core';
@Injectable()
export class NationalCodeService {
constructor() { }
isValid(nationalCode: string): boolean {
return this.vlaidate(nationalCode);
}
private vlaidate(nationalCode: string): boolean {
if (nationalCode == undefined)
return false;
if (nationalCode.length !== 10)
return false;
switch (nationalCode) {
case '0000000000':
case '1111111111':
case '2222222222':
case '3333333333':
case '4444444444':
case '5555555555':
case '6666666666':
case '7777777777':
case '8888888888':
case '9999999999':
return false;
}
var c = parseInt(nationalCode.charAt(9));
var n = parseInt(nationalCode.charAt(0)) * 10 + parseInt(nationalCode.charAt(1)) * 9 + parseInt(nationalCode.charAt(2)) * 8 + parseInt(nationalCode.charAt(3)) * 7 + parseInt(nationalCode.charAt(4)) * 6 + parseInt(nationalCode.charAt(5)) * 5 + parseInt(nationalCode.charAt(6)) * 4 + parseInt(nationalCode.charAt(7)) * 3 + parseInt(nationalCode.charAt(8)) * 2;
var r = n - Math.round(n / 11) * 11;
if ((r == 0 && r == c) || (r == 1 && c == 1) || (r > 1 && c == 11 - r))
return true;
return false;
}
}
| mit |
michakpl/ContactManager | spec/models/person_spec.rb | 913 | require 'rails_helper'
RSpec.describe Person, type: :model do
let(:person) { Fabricate(:person) }
it 'is invalid without a first name' do
person.first_name = nil
expect(person).not_to be_valid
end
it 'is invalid without a last name' do
person.last_name = nil
expect(person).not_to be_valid
end
it 'is valid' do
expect(person).to be_valid
end
it 'has an array of phone numbers' do
person.phone_numbers.build(number: '555-8888')
expect(person.phone_numbers.map(&:number)).to eq(['555-8888'])
end
it 'has an array of email addresses' do
person.email_addresses.build(address: '[email protected]')
expect(person.email_addresses.map(&:address)).to eq(['[email protected]'])
end
it "convert to a string with last name, fist name" do
expect(person.to_s).to eq "Smith, Alice"
end
it 'is associated with a user' do
expect(person).to respond_to(:user)
end
end | mit |
wulkano/kap | renderer/components/config/tab.js | 5310 | import React from 'react';
import PropTypes from 'prop-types';
import Linkify from 'react-linkify';
import Item, {Link} from '../preferences/item';
import Select from '../preferences/item/select';
import Switch from '../preferences/item/switch';
import ColorPicker from '../preferences/item/color-picker';
import {OpenOnGithubIcon, OpenConfigIcon} from '../../vectors';
const horizontalTypes = [
'boolean',
'hexColor'
];
const ConfigInput = ({name, type, schema, value, onChange, hasErrors}) => {
if (type === 'hexColor') {
return <ColorPicker value={value} name={name} hasErrors={hasErrors} onChange={value => onChange(name, value)}/>;
}
if (type === 'select') {
const options = schema.enum.map(value => ({label: value, value}));
return <Select full tabIndex={0} options={options} selected={value} onSelect={value => onChange(name, value)}/>;
}
if (type === 'boolean') {
return <Switch tabIndex={0} checked={value} onClick={() => onChange(name, !value)}/>;
}
const className = hasErrors ? 'has-errors' : '';
const handleChange = event => {
const value = type === 'number' ? Number.parseFloat(event.target.value) : event.currentTarget.value;
onChange(name, value);
};
return (
<div>
<input
className={className}
value={value || ''}
type={type === 'number' ? 'number' : 'text'}
onChange={handleChange}
/>
<style jsx>{`
input {
outline: none;
width: 100%;
border: 1px solid var(--input-border-color);
background: var(--input-background-color);
color: var(--title-color);
border-radius: 3px;
box-sizing: border-box;
height: 32px;
padding: 4px 8px;
line-height: 32px;
font-size: 12px;
margin-top: 8px;
outline: none;
box-shadow: var(--input-shadow);
}
.has-errors {
background: rgba(255,59,48,0.10);
border-color: rgba(255,59,48,0.20);
}
input:focus {
border-color: var(--kap);
}
div {
width: 100%;
}
`}</style>
</div>
);
};
ConfigInput.propTypes = {
name: PropTypes.string,
type: PropTypes.string,
schema: PropTypes.object,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.bool,
PropTypes.number
]),
onChange: PropTypes.elementType.isRequired,
hasErrors: PropTypes.bool
};
class Tab extends React.Component {
render() {
const {validator, values, onChange, openConfig, viewOnGithub, serviceTitle} = this.props;
const {config, errors, description} = validator;
const allErrors = errors || [];
return (
<div className="container">
{
description && (
<div className="description">
<Linkify component={Link}>{description}</Linkify>
</div>
)
}
{
[...Object.keys(config)].map(key => {
const schema = config[key];
const type = schema.customType || (schema.enum ? 'select' : schema.type);
const itemErrors = allErrors
.filter(({dataPath}) => dataPath.endsWith(key))
.map(({message}) => `This ${message}`);
return (
<Item
key={key}
small
title={schema.title}
subtitle={schema.description}
vertical={!horizontalTypes.includes(type)}
errors={itemErrors}
>
<ConfigInput
hasErrors={itemErrors.length > 0}
name={key}
type={type}
schema={schema}
value={values[key]}
onChange={onChange}
/>
</Item>
);
})
}
{
!serviceTitle && (
<Item subtitle="Open config file" onClick={openConfig}>
<div className="icon-container"><OpenConfigIcon fill="var(--kap)" hoverFill="var(--kap)" onClick={openConfig}/></div>
</Item>
)
}
<Item last subtitle="View plugin on GitHub" onClick={viewOnGithub}>
<div className="icon-container"><OpenOnGithubIcon size="20px" fill="var(--kap)" hoverFill="var(--kap)" onClick={viewOnGithub}/></div>
</Item>
<style jsx>{`
.container {
width: 100%;
height: 100%;
overflow-y: auto;
}
.description {
color: var(--subtitle-color);
font-weight: normal;
font-size: 1.4rem;
width: 100%;
padding: 16px 16px 0 16px;
box-sizing: border-box;
}
.icon-container {
width: 24px;
height: 24px;
display: flex;
justify-content: center;
align-items: center;
}
`}</style>
</div>
);
}
}
Tab.propTypes = {
validator: PropTypes.elementType,
values: PropTypes.object,
onChange: PropTypes.elementType.isRequired,
openConfig: PropTypes.elementType.isRequired,
viewOnGithub: PropTypes.elementType.isRequired,
serviceTitle: PropTypes.string
};
export default Tab;
| mit |
janssonav/ngx-datatable | release/directives/visibility.directive.js | 2329 | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@angular/core");
/**
* Visibility Observer Directive
*
* Usage:
*
* <div
* visibilityObserver
* (visible)="onVisible($event)">
* </div>
*
*/
var VisibilityDirective = (function () {
function VisibilityDirective(element, zone) {
this.element = element;
this.zone = zone;
this.isVisible = false;
this.visible = new core_1.EventEmitter();
}
VisibilityDirective.prototype.ngOnInit = function () {
this.runCheck();
};
VisibilityDirective.prototype.ngOnDestroy = function () {
clearTimeout(this.timeout);
};
VisibilityDirective.prototype.onVisibilityChange = function () {
var _this = this;
// trigger zone recalc for columns
this.zone.run(function () {
_this.isVisible = true;
_this.visible.emit(true);
});
};
VisibilityDirective.prototype.runCheck = function () {
var _this = this;
var check = function () {
// https://davidwalsh.name/offsetheight-visibility
var _a = _this.element.nativeElement, offsetHeight = _a.offsetHeight, offsetWidth = _a.offsetWidth;
if (offsetHeight && offsetWidth) {
clearTimeout(_this.timeout);
_this.onVisibilityChange();
}
else {
clearTimeout(_this.timeout);
_this.zone.runOutsideAngular(function () {
_this.timeout = setTimeout(function () { return check(); }, 50);
});
}
};
setTimeout(function () { return check(); });
};
VisibilityDirective.decorators = [
{ type: core_1.Directive, args: [{ selector: '[visibilityObserver]' },] },
];
/** @nocollapse */
VisibilityDirective.ctorParameters = function () { return [
{ type: core_1.ElementRef, },
{ type: core_1.NgZone, },
]; };
VisibilityDirective.propDecorators = {
'isVisible': [{ type: core_1.HostBinding, args: ['class.visible',] },],
'visible': [{ type: core_1.Output },],
};
return VisibilityDirective;
}());
exports.VisibilityDirective = VisibilityDirective;
//# sourceMappingURL=visibility.directive.js.map | mit |
kyasar/mapis | src/main/java/com/cherchy/markod/repository/CategoryRepository.java | 384 | package com.cherchy.markod.repository;
import com.cherchy.markod.model.Category;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CategoryRepository extends MongoRepository<Category, String> {
List<Category> findByNameContainingIgnoreCase(String name);
}
| mit |
jesprider/cmove | gulpfile.js | 187 | var gulp = require('gulp'),
uglify = require('gulp-uglify');
gulp.task('compress', function() {
gulp.src('lib/*.js')
.pipe(uglify())
.pipe(gulp.dest('dist'))
}); | mit |
lxy528/Benchmark | src/main/java/securibench/micro/basic/Basic19.java | 1576 | /**
@author Benjamin Livshits <[email protected]>
$Id: Basic19.java,v 1.7 2006/04/04 20:00:40 livshits Exp $
*/
package securibench.micro.basic;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import securibench.micro.BasicTestCase;
import securibench.micro.MicroTestCase;
/**
* @servlet description="simple SQL injection with prepared statements"
* @servlet vuln_count = "1"
* */
public class Basic19 extends BasicTestCase implements MicroTestCase {
private static final String FIELD_NAME = "name";
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String name = req.getParameter(FIELD_NAME);
Connection con = null;
try {
con = DriverManager.getConnection(MicroTestCase.CONNECTION_STRING);
con.prepareStatement("select * from Users where name=" + name); /* BAD */
} catch (SQLException e) {
System.err.println("An error occurred");
} finally {
try {
if(con != null) con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public String getDescription() {
return "simple SQL injection with prepared statements";
}
public int getVulnerabilityCount() {
return 1;
}
} | mit |
freeformsystems/jsr-conf | lib/runtime.js | 1357 | /**
* Directives that may be modified at runtime using
* CONFIG SET.
*
* See: config.c
*/
var runtime = [
'dbfilename',
'requirepass',
'masterauth',
'maxmemory',
'maxclients',
'hz',
'maxmemory-policy',
'maxmemory-samples',
'timeout',
'tcp-keepalive',
'appendfsync',
'no-appendfsync-on-rewrite',
'appendonly',
'auto-aof-rewrite-percentage',
'auto-aof-rewrite-min-size',
'aof-rewrite-incremental-fsync',
'aof-load-truncated',
'save',
'slave-serve-stale-data',
'slave-read-only',
'dir',
'hash-max-ziplist-entries',
'hash-max-ziplist-value',
'list-max-ziplist-entries',
'list-max-ziplist-value',
'set-max-intset-entries',
'zset-max-ziplist-entries',
'zset-max-ziplist-value',
'hll-sparse-max-bytes',
'lua-time-limit',
'slowlog-log-slower-than',
'slowlog-max-len',
'latency-monitor-threshold',
'loglevel',
'client-output-buffer-limit',
'stop-writes-on-bgsave-error',
'repl-ping-slave-period',
'repl-timeout',
'repl-backlog-size',
'repl-backlog-ttl',
'watchdog-period',
'rdbcompression',
'notify-keyspace-events',
'repl-disable-tcp-nodelay',
'slave-priority',
'min-slaves-to-write',
'min-slaves-max-lag',
'cluster-require-full-coverage',
'cluster-node-timeout',
'cluster-migration-barrier',
'cluster-slave-validity-factor',
]
module.exports = runtime;
| mit |
aaronjbaptiste/snap-pad | app/models/BaseModel.php | 412 | <?php
class BaseModel extends Eloquent {
protected $errors;
public function validate()
{
$validation = Validator::make($this->getAttributes(), static::$rules);
if ($validation->fails()) {
$this->errors = $validation->messages();
return false;
}
return true;
}
public function getErrors()
{
return $this->errors;
}
} | mit |
stpettersens/full-monkey | src/main.rs | 5105 | /*
Full Monkey.
Generic preprocessor tool.
Copyright 2016 Sam Saint-Pettersen.
Released under the MIT/X11 License.
*/
extern crate clioptions;
extern crate regex;
use clioptions::CliOptions;
use regex::Regex;
use std::io::{BufRead, BufReader, Write};
use std::fs::File;
use std::process::exit;
fn preprocess(input: &str, output: &str, conditions: &str, verbose: bool) {
let mut loc: Vec<String> = Vec::new();
let mut preprocessed: Vec<String> = Vec::new();
let mut cond = String::new();
let mut set_conds: Vec<String> = Vec::new();
let mut prefixed: Vec<String> = Vec::new();
let mut prefixes: Vec<String> = Vec::new();
let mut in_pp = false;
let conditions = conditions.split(",");
for sc in conditions {
set_conds.push(sc.to_string());
}
let f = File::open(input).unwrap();
let file = BufReader::new(&f);
for l in file.lines() {
let l = l.unwrap();
// Process prefix...
let mut p = Regex::new("#prefix (.*) with (.*)").unwrap();
if p.is_match(&l) {
for cap in p.captures_iter(&l) {
prefixed.push(cap.at(1).unwrap().to_string());
prefixes.push(cap.at(2).unwrap().to_string());
}
continue;
}
// Process conditional (if/else/elseif)...
p = Regex::new("#[else]*[if]* (.*)").unwrap();
if p.is_match(&l) {
for cap in p.captures_iter(&l) {
cond = cap.at(1).unwrap().to_string();
in_pp = true;
}
continue;
}
// Process end block...
p = Regex::new("#[fi|endif]").unwrap();
if p.is_match(&l) {
in_pp = false;
continue;
}
// Push relevant LoC to vector...
for sc in set_conds.clone() {
if in_pp && cond == sc {
preprocessed.push(l.to_string());
}
}
if !in_pp {
preprocessed.push(l.to_string());
continue;
}
}
// Do any alterations:
for line in preprocessed {
let mut fl = line;
for (i, p) in prefixed.iter().enumerate() {
let r = Regex::new(®ex::quote(&p)).unwrap();
let repl = format!("{}{}", &prefixes[i], &p);
fl = r.replace_all(&fl, &repl[..]);
}
loc.push(fl);
}
loc.push(String::new());
if verbose {
println!("Preprocessing {} --> {}", input, output);
}
let mut w = File::create(output).unwrap();
let _ = w.write_all(loc.join("\n").as_bytes());
}
fn display_version() {
println!("Full Monkey v. 0.1");
println!(r" __");
println!(r"w c(..)o (");
println!(r" \__(-) __)");
println!(r" /\ (");
println!(r" /(_)___)");
println!(r" w /|");
println!(r" | \");
println!(r" m m");
println!("\nMonkey appears courtesy of ejm97:");
println!("http://www.ascii-art.de/ascii/mno/monkey.txt");
exit(0);
}
fn display_error(program: &str, error: &str) {
println!("Error: {}.", error);
display_usage(&program, -1);
}
fn display_usage(program: &str, exit_code: i32) {
println!("\nFull Monkey.");
println!("Generic preprocessor tool.");
println!("\nCopyright 2016 Sam Saint-Pettersen.");
println!("Released under the MIT/X11 License.");
println!("\n{} -f|--file <input> [-c|--condition <condition(s)>] -o|--out <output>", program);
println!("[-l|--verbose][-h|--help | -v|--version]");
println!("\n-f|--file: File to run preprocessing on.");
println!("-c|--conditon: Comma delimited list of conditon(s) to apply.");
println!("-o|--out: File to output preprocessed LoC to.");
println!("-l|--verbose: Display message to console on process.");
println!("-h|--help: Display this help information and exit.");
println!("-v|--version: Display program version and exit.");
exit(exit_code);
}
fn main() {
let cli = CliOptions::new("fm");
let program = cli.get_program();
let mut input = String::new();
let mut output = String::new();
let mut conditions = String::new();
let mut verbose = false;
if cli.get_num() > 1 {
for (i, a) in cli.get_args().iter().enumerate() {
match a.trim() {
"-h" | "--help" => display_usage(&program, 0),
"-v" | "--version" => display_version(),
"-f" | "--file" => input = cli.next_argument(i),
"-c" | "--condition" => conditions = cli.next_argument(i),
"-o" | "--out" => output = cli.next_argument(i),
"-l" | "--verbose" => verbose = true,
_ => continue,
}
}
if input.is_empty() {
display_error(&program, "No input specified");
}
if output.is_empty() {
display_error(&program, "No output specified");
}
preprocess(&input, &output, &conditions, verbose);
}
else {
display_error(&program, "No options specified");
}
}
| mit |
kmc7468/Luce | Include/Luce/System/Detail/UnitType.hh | 1857 | #ifndef LUCE_HEADER_SYSTEM_DETAIL_UNITTYPE_HH
#define LUCE_HEADER_SYSTEM_DETAIL_UNITTYPE_HH
#if LUCE_MACRO_SUPPORTED_RVALUE_REF
#include <utility>
#endif
namespace Luce
{
namespace System
{
#if LUCE_MACRO_SUPPORTED_CONSTEXPR
LUCE_MACRO_CONSTEXPR UnitType::UnitType() LUCE_MACRO_NOEXCEPT
: Value_(static_cast<Enumeration>(0))
{}
LUCE_MACRO_CONSTEXPR UnitType::UnitType(const Enumeration& unit_type) LUCE_MACRO_NOEXCEPT
: Value_(unit_type)
{}
LUCE_MACRO_CONSTEXPR UnitType::UnitType(const UnitType& unit_type) LUCE_MACRO_NOEXCEPT
: Value_(unit_type.Value_)
{}
#if LUCE_MACRO_SUPPORTED_RVALUE_REF
LUCE_MACRO_CONSTEXPR UnitType::UnitType(UnitType&& unit_type) LUCE_MACRO_NOEXCEPT
: Value_(std::move(unit_type.Value_))
{}
#endif
LUCE_MACRO_CONSTEXPR
bool UnitType::operator==(const UnitType& unit_type) const LUCE_MACRO_NOEXCEPT
{
return Value_ == unit_type.Value_;
}
LUCE_MACRO_CONSTEXPR
bool UnitType::operator!=(const UnitType& unit_type) const LUCE_MACRO_NOEXCEPT
{
return Value_ != unit_type.Value_;
}
LUCE_MACRO_CONSTEXPR UnitType UnitType::FromString(const char* const str)
{
return FromString_(str, 0);
}
LUCE_MACRO_CONSTEXPR UnitType UnitType::FromString_(const char* const str,
std::size_t index)
{
return StrCmp_(str, Enum_String_[index]) ?
Enum_Item_[index] : FromString_(str, index + 1);
}
LUCE_MACRO_CONSTEXPR bool UnitType::StrCmp_(const char* lhs, const char* rhs)
{
return *lhs == *rhs && (*lhs == '\0' || StrCmp_(lhs + 1, rhs + 1));
}
LUCE_MACRO_CONSTEXPR const char* const UnitType::ToString() const
{
return ToString_(0);
}
LUCE_MACRO_CONSTEXPR
const char* const UnitType::ToString_(std::size_t index) const
{
return Value_ == Enum_Index_[index] ? Enum_String_[index] :
ToString_(index + 1);
}
#endif
}
}
#endif | mit |
Permafrost/Tundra | code/source/tundra/collection/map/object.java | 11090 | package tundra.collection.map;
// -----( IS Java Code Template v1.2
// -----( CREATED: 2021-09-30 05:50:25 AEST
// -----( ON-HOST: -
import com.wm.data.*;
import com.wm.util.Values;
import com.wm.app.b2b.server.Service;
import com.wm.app.b2b.server.ServiceException;
// --- <<IS-START-IMPORTS>> ---
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import permafrost.tundra.collection.ConcurrentMapHelper;
import permafrost.tundra.collection.MapHelper;
import permafrost.tundra.data.IDataHelper;
import permafrost.tundra.lang.BooleanHelper;
import permafrost.tundra.lang.ExceptionHelper;
import permafrost.tundra.math.IntegerHelper;
// --- <<IS-END-IMPORTS>> ---
public final class object
{
// ---( internal utility methods )---
final static object _instance = new object();
static object _newInstance() { return new object(); }
static object _cast(Object o) { return (object)o; }
// ---( server methods )---
public static final void clear (IData pipeline)
throws ServiceException
{
// --- <<IS-START(clear)>> ---
// @subtype unknown
// @sigtype java 3.5
// [i] object:0:optional $map
IDataCursor cursor = pipeline.getCursor();
try {
Map map = IDataHelper.get(cursor, "$map", Map.class);
MapHelper.clear(map);
} finally {
cursor.destroy();
}
// --- <<IS-END>> ---
}
public static final void create (IData pipeline)
throws ServiceException
{
// --- <<IS-START(create)>> ---
// @subtype unknown
// @sigtype java 3.5
// [i] field:0:optional $key.class
// [i] field:0:optional $value.class
// [i] field:0:optional $sorted? {"false","true"}
// [o] object:0:optional $map
IDataCursor cursor = pipeline.getCursor();
try {
Class keyClass = IDataHelper.get(cursor, "$key.class", Class.class);
Class valueClass = IDataHelper.get(cursor, "$value.class", Class.class);
create(pipeline, keyClass == null ? Object.class : keyClass, valueClass == null ? Object.class : valueClass);
} finally {
cursor.destroy();
}
// --- <<IS-END>> ---
}
public static final void documentify (IData pipeline)
throws ServiceException
{
// --- <<IS-START(documentify)>> ---
// @subtype unknown
// @sigtype java 3.5
// [i] object:0:optional $map
// [o] record:0:optional $document
IDataCursor cursor = pipeline.getCursor();
try {
Map map = IDataHelper.get(cursor, "$map", Map.class);
IDataHelper.put(cursor, "$document", MapHelper.documentify(map), false);
} finally {
cursor.destroy();
}
// --- <<IS-END>> ---
}
public static final void get (IData pipeline)
throws ServiceException
{
// --- <<IS-START(get)>> ---
// @subtype unknown
// @sigtype java 3.5
// [i] object:0:optional $map
// [i] object:0:required $key
// [o] field:0:required $key.exists? {"false","true"}
// [o] object:0:optional $value
get(pipeline, Object.class, Object.class);
// --- <<IS-END>> ---
}
public static final void keys (IData pipeline)
throws ServiceException
{
// --- <<IS-START(keys)>> ---
// @subtype unknown
// @sigtype java 3.5
// [i] object:0:optional $map
// [o] object:1:optional $keys
// [o] field:0:required $keys.length
IDataCursor cursor = pipeline.getCursor();
try {
Map map = IDataHelper.get(cursor, "$map", Map.class);
Object[] keys = MapHelper.keys(map);
IDataHelper.put(cursor, "$keys", keys, false);
IDataHelper.put(cursor, "$keys.length", keys == null ? 0 : keys.length, String.class);
} finally {
cursor.destroy();
}
// --- <<IS-END>> ---
}
public static final void length (IData pipeline)
throws ServiceException
{
// --- <<IS-START(length)>> ---
// @subtype unknown
// @sigtype java 3.5
// [i] object:0:optional $map
// [o] field:0:required $length
IDataCursor cursor = pipeline.getCursor();
try {
Map map = IDataHelper.get(cursor, "$map", Map.class);
IDataHelper.put(cursor, "$length", MapHelper.length(map), String.class);
} finally {
cursor.destroy();
}
// --- <<IS-END>> ---
}
public static final void mapify (IData pipeline)
throws ServiceException
{
// --- <<IS-START(mapify)>> ---
// @subtype unknown
// @sigtype java 3.5
// [i] record:0:optional $document
// [i] field:0:optional $value.class
// [i] field:0:optional $sorted? {"false","true"}
// [o] object:0:optional $map
IDataCursor cursor = pipeline.getCursor();
try {
Class valueClass = IDataHelper.get(cursor, "$value.class", Class.class);
mapify(pipeline, valueClass == null ? Object.class : valueClass);
} finally {
cursor.destroy();
}
// --- <<IS-END>> ---
}
public static final void put (IData pipeline)
throws ServiceException
{
// --- <<IS-START(put)>> ---
// @subtype unknown
// @sigtype java 3.5
// [i] object:0:optional $map
// [i] object:0:required $key
// [i] field:0:optional $key.absent? {"false","true"}
// [i] object:0:required $value
// [o] object:0:required $map
// [o] object:0:required $value
IDataCursor cursor = pipeline.getCursor();
try {
Map map = IDataHelper.get(cursor, "$map", Map.class);
Object key = IDataHelper.get(cursor, "$key");
boolean keyAbsent = IDataHelper.getOrDefault(cursor, "$key.absent?", Boolean.class, false);
Object value = IDataHelper.get(cursor, "$value");
if (map == null) map = ConcurrentMapHelper.create();
if (keyAbsent) {
Object existingValue = ConcurrentMapHelper.putIfAbsent((ConcurrentMap)map, key, value);
if (existingValue != null) value = existingValue;
} else {
MapHelper.put(map, key, value);
}
IDataHelper.put(cursor, "$map", map);
IDataHelper.put(cursor, "$value", value);
} finally {
cursor.destroy();
}
// --- <<IS-END>> ---
}
public static final void remove (IData pipeline)
throws ServiceException
{
// --- <<IS-START(remove)>> ---
// @subtype unknown
// @sigtype java 3.5
// [i] object:0:optional $map
// [i] object:0:required $key
// [i] object:0:optional $value
// [o] field:0:required $key.removed? {"false","true"}
// [o] object:0:optional $value
IDataCursor cursor = pipeline.getCursor();
try {
Map map = IDataHelper.get(cursor, "$map", Map.class);
Object key = IDataHelper.get(cursor, "$key");
Object value = IDataHelper.get(cursor, "$value");
boolean removed = true;
if (value == null) {
value = MapHelper.remove(map, key);
} else {
removed = ConcurrentMapHelper.remove((ConcurrentMap)map, key, value);
}
IDataHelper.put(cursor, "$key.removed?", removed, String.class);
} finally {
cursor.destroy();
}
// --- <<IS-END>> ---
}
public static final void replace (IData pipeline)
throws ServiceException
{
// --- <<IS-START(replace)>> ---
// @subtype unknown
// @sigtype java 3.5
// [i] object:0:optional $map
// [i] object:0:required $key
// [i] object:0:optional $value.old
// [i] object:0:required $value.new
// [o] field:0:required $value.replaced? {"false","true"}
IDataCursor cursor = pipeline.getCursor();
try {
ConcurrentMap map = IDataHelper.get(cursor, "$map", ConcurrentMap.class);
Object key = IDataHelper.get(cursor, "$key");
Object oldValue = IDataHelper.get(cursor, "$value.old");
Object newValue = IDataHelper.get(cursor, "$value.new");
if (oldValue == null) {
IDataHelper.put(cursor, "$value.replaced?", ConcurrentMapHelper.replace(map, key, newValue) != null, String.class);
} else {
IDataHelper.put(cursor, "$value.replaced?", ConcurrentMapHelper.replace(map, key, oldValue, newValue), String.class);
}
} finally {
cursor.destroy();
}
// --- <<IS-END>> ---
}
public static final void values (IData pipeline)
throws ServiceException
{
// --- <<IS-START(values)>> ---
// @subtype unknown
// @sigtype java 3.5
// [i] object:0:optional $map
// [o] object:1:optional $values
IDataCursor cursor = pipeline.getCursor();
try {
Map map = IDataHelper.get(cursor, "$map", Map.class);
Object[] values = MapHelper.values(map);
IDataHelper.put(cursor, "$values", values, false);
IDataHelper.put(cursor, "$values.length", values == null ? 0 : values.length, String.class);
} finally {
cursor.destroy();
}
// --- <<IS-END>> ---
}
// --- <<IS-START-SHARED>> ---
/**
* Returns a new Map representation of the given IData object.
*
* @param pipeline The pipeline containing the arguments to the method.
* @param keyClass The class of keys stored in the Map.
* @param valueClass The class of values stored in the Map.
* @param <K> The class of keys stored in the Map.
* @param <V> The class of values stored in the Map.
*/
public static <K, V> void create(IData pipeline, Class<K> keyClass, Class<V> valueClass) {
IDataCursor cursor = pipeline.getCursor();
try {
boolean sorted = IDataHelper.get(cursor, "$sorted?", Boolean.class);
IDataHelper.put(cursor, "$map", ConcurrentMapHelper.create(sorted));
} finally {
cursor.destroy();
}
}
/**
* Returns the value associated with the given key in the given Map.
*
* @param pipeline The pipeline containing the arguments to the method.
* @param keyClass The class of keys stored in the Map.
* @param valueClass The class of values stored in the Map.
* @param <K> The class of keys stored in the Map.
* @param <V> The class of values stored in the Map.
*/
public static <K, V> void get(IData pipeline, Class<K> keyClass, Class<V> valueClass) {
IDataCursor cursor = pipeline.getCursor();
try {
Map map = IDataHelper.get(cursor, "$map", Map.class);
K key = IDataHelper.get(cursor, "$key", keyClass);
V value = (V)MapHelper.get(map, key);
IDataHelper.put(cursor, "$key.exists?", value != null, String.class);
IDataHelper.put(cursor, "$value", value, false);
} finally {
cursor.destroy();
}
}
/**
* Returns a new Map representation of the given IData object.
*
* @param pipeline The pipeline containing the arguments to the method.
* @param valueClass The class of values stored in the Map.
* @param <V> The class of values stored in the Map.
*/
public static <V> void mapify(IData pipeline, Class<V> valueClass) {
IDataCursor cursor = pipeline.getCursor();
try {
IData document = IDataHelper.get(cursor, "$document", IData.class);
boolean sorted = IDataHelper.getOrDefault(cursor, "$sorted?", Boolean.class, false);
IDataHelper.put(cursor, "$map", ConcurrentMapHelper.mapify(document, sorted, valueClass), false);
} finally {
cursor.destroy();
}
}
// --- <<IS-END-SHARED>> ---
}
| mit |
LouisStAmour/proj4rb19 | test/test_units.rb | 1212 | $: << 'lib' << 'ext'
require File.join(File.dirname(__FILE__), '..', 'lib', 'proj4')
require 'test/unit'
if Proj4::LIBVERSION >= 449
class UnitsTest < Test::Unit::TestCase
def test_get_all
units = Proj4::Unit.list.sort.collect{ |u| u.id }
assert units.index('km')
assert units.index('m')
assert units.index('yd')
assert units.index('us-mi')
end
def test_one
unit = Proj4::Unit.get('km')
assert_kind_of Proj4::Unit, unit
assert_equal 'km', unit.id
assert_equal 'km', unit.to_s
assert_equal '1000.', unit.to_meter
assert_equal 'Kilometer', unit.name
assert_equal '#<Proj4::Unit id="km", to_meter="1000.", name="Kilometer">', unit.inspect
end
def test_compare
u1 = Proj4::Unit.get('km')
u2 = Proj4::Unit.get('km')
assert u1 == u2
end
def test_failed_get
unit = Proj4::Unit.get('foo')
assert_nil unit
end
def test_new
assert_raise TypeError do
Proj4::Unit.new
end
end
end
end
| mit |
wyrover/SharpDX | Source/Toolkit/SharpDX.Toolkit/Graphics/SpriteFontDataContentReader.cs | 1611 | // Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// 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.
using System.IO;
using SharpDX.Toolkit.Content;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// Content reader for <see cref="SpriteFontData"/>.
/// </summary>
class SpriteFontDataContentReader : IContentReader
{
public object ReadContent(IContentManager readerManager, ref ContentReaderParameters parameters)
{
parameters.KeepStreamOpen = false;
return SpriteFontData.Load(parameters.Stream);
}
}
} | mit |
xgundam05/vox-to-obj | scripts/voxel/magicaVoxel.js | 3653 | // MagicaVoxel File Loader Module
// ===============================
var fs = require('fs');
var voxmodel = require('./voxModel.js');
// Helper Objects
function MVoxChunk(i, s, cs, c, ch){
this.id = i;
this.size = s;
this.childrenSize = cs;
this.contents = c;
this.children = ch;
}
// Load from a file
function load(fname){
var file = fs.openSync(fname, 'r');
var buffer = new Buffer(4);
// Read the Magic Number
fs.readSync(file, buffer, 0, 4);
if (buffer.toString('ascii') != 'VOX ')
return undefined;
// Read Version number, discard
fs.readSync(file, buffer, 0, 4);
// Read MAIN chunk
main = readChunk(file);
// Close it up
fs.closeSync(file);
return loadFromMain(main);
}
// Load the data from the MAIN chunk
function loadFromMain(chunk){
var size = undefined;
var voxels = undefined;
var palette = undefined;
var model = undefined;
// Load the Chunks
for (var i = 0; i < chunk.children.length; i++){
if (chunk.children[i].id == 'SIZE')
size = chunk.children[i];
else if (chunk.children[i].id == 'XYZI')
voxels = chunk.children[i];
else if (chunk.children[i].id == 'RGBI')
palette = chunk.children[i];
}
// MagicaVoxel uses Z for height...we use it for depth
if (size !== undefined && voxels !== undefined){
var w = size.contents.readUIntLE(0, 4);
var h = size.contents.readUIntLE(4, 4);
var d = size.contents.readUIntLE(8, 4);
if (w > 0 && h > 0 && d > 0){
model = voxmodel({width: w, height: d, depth: h, zUp: false});
var numVoxels = voxels.contents.readUIntLE(0, 4);
for (var j = 0; j < numVoxels; j++){
var x = voxels.contents[(j * 4) + 4];
var y = voxels.contents[(j * 4) + 5];
var z = voxels.contents[(j * 4) + 6];
var i = voxels.contents[(j * 4) + 7];
var index = x + (z * model.width) + ((model.depth - 1 - y) * model.width * model.height);
if (index < w * h * d){
model.data[index] = i;
}
}
}
}
if (palette !== undefined){
model.palette[0] = {r: 0, g: 0, b: 0, a: 0};
for (var i = 0; i < palette.size; i += 4){
var red = palette.contents[i + 0];
var green = palette.contents[i + 1];
var blue = palette.contents[i + 2];
var alpha = palette.contents[i + 3];
model.palette.push({
r: red,
g: green,
b: blue,
a: alpha
});
}
}
else {
// Load a default palette of some sort
model.palette[0] = {r: 0, g: 0, b: 0, a: 0};
for (var i = 0; i < 255; i++){
model.palette.push({
r: i,
g: i,
b: i,
a: 1
});
}
}
return model;
}
// Read a MagicaVoxel chunk from a file
function readChunk(file){
var chunk = new MVoxChunk('', 0, 0, undefined, []);
var buffer = new Buffer(4);
// Read ID
if (fs.readSync(file, buffer, 0, 4) > 0)
chunk.id = buffer.toString('ascii');
// Read Size
if (fs.readSync(file, buffer, 0, 4) > 0)
chunk.size = buffer.readUIntLE(0, 4);
// Read Size of Children
if (fs.readSync(file, buffer, 0, 4) > 0)
chunk.childrenSize = buffer.readUIntLE(0, 4);
// Read Data
if (chunk.size > 0){
chunk.contents = new Buffer(chunk.size);
fs.readSync(file, chunk.contents, 0, chunk.size);
}
// Read Children Data
var currentSize = 0;
if (chunk.childrenSize > 0){
while (currentSize < chunk.childrenSize){
var childChunk = readChunk(file);
chunk.children.push(childChunk);
currentSize += 12 + childChunk.size + childChunk.childrenSize;
}
}
return chunk;
}
// Exported Functions
exports.load = load;
| mit |
demandchain/test_support | spec/lib/test_support/pretty_formatter_spec.rb | 22894 | require 'spec_helper'
require ::File.expand_path("../../../lib/test_support/pretty_formatter", File.dirname(__FILE__))
describe TestSupport::PrettyFormatter do
let(:formatted_string) { "#<AClass\nmy_variable = \"a value \",\n \"another\"=0>" }
let(:simple_class) { "#<AClass>" }
let(:simple_variable) { "#<AClass \"variable\"=\"value\", something = something else>" }
let(:simple_variable_expectations) { "#<AClass\n \"variable\" = \"value\",\n something = something else\n>" }
let(:simple_array) { "#<AClass \"array\" = [\"value\", something here, \"\\\"some\\\\thing\\\"\"]>" }
let(:simple_array_expectations) { "#<AClass\n \"array\" =\n [\n \"value\",\n something here,\n \"\\\"some\\\\thing\\\"\"\n ]\n>" }
let(:simple_hash) { "#<AClass \"hash\" = {:value => something here, \"\\\"some\\\\thing\\\"\" => a value, symbol: :symbol_also } >" }
let(:simple_hash_expectations) { "#<AClass\n \"hash\" =\n {\n :value => something here,\n \"\\\"some\\\\thing\\\"\" => a value,\n symbol: :symbol_also\n }\n>" }
it "doesn't format a formatted string" do
pretty = TestSupport::PrettyFormatter.format_string(formatted_string)
expect(pretty).to be == formatted_string
pretty = TestSupport::PrettyFormatter.format_string(formatted_string.gsub(/\n/, " "))
expect(pretty).to_not be == formatted_string
end
it "formats a simple class" do
pretty = TestSupport::PrettyFormatter.format_string(simple_class)
expect(pretty).to be == simple_class
end
it "formats a simple variable" do
pretty = TestSupport::PrettyFormatter.format_string(simple_variable)
expect(pretty).to be == simple_variable_expectations
end
it "formats a simple class in bigger text" do
pre_text = rand(0..1) == 0 ? "#{Faker::Lorem.sentence}\n" : ""
post_text = rand(0..1) == 0 ? "\n#{Faker::Lorem.sentence}" : ""
pretty = TestSupport::PrettyFormatter.format_string("#{pre_text[0..-2]}#{simple_variable}#{post_text[1..-1]}")
expect(pretty).to be == expectation_in_text(simple_variable_expectations, pre_text, post_text)
end
it "formats an array" do
pretty = TestSupport::PrettyFormatter.format_string(simple_array)
expect(pretty).to be == simple_array_expectations
end
it "formats a simple array in bigger text" do
pre_text = rand(0..1) == 0 ? "#{Faker::Lorem.sentence}\n" : ""
post_text = rand(0..1) == 0 ? "\n#{Faker::Lorem.sentence}" : ""
pretty = TestSupport::PrettyFormatter.format_string("#{pre_text[0..-2]}#{simple_array}#{post_text[1..-1]}")
expect(pretty).to be == expectation_in_text(simple_array_expectations, pre_text, post_text)
end
it "formats an hash" do
pretty = TestSupport::PrettyFormatter.format_string(simple_hash)
expect(pretty).to be == simple_hash_expectations
end
it "formats a simple hash in bigger text" do
pre_text = rand(0..1) == 0 ? "#{Faker::Lorem.sentence}\n" : ""
post_text = rand(0..1) == 0 ? "\n#{Faker::Lorem.sentence}" : ""
pretty = TestSupport::PrettyFormatter.format_string("#{pre_text[0..-2]}#{simple_hash}#{post_text[1..-1]}")
expect(pretty).to be == expectation_in_text(simple_hash_expectations, pre_text, post_text)
end
it "formats a known problem string 1" do
format_value = "#<class @silencers=#<class @silencers=[#<Proc:0x007f8d9f2a15f0@/Users/elittell/.rvm/gems/ruby-1.9.3-p327@homerun/gems/railties-3.2.13/lib/rails/backtrace_cleaner.rb:15>]>, \"HTTP_HO\"=\"HTTP_HO\">"
pretty = TestSupport::PrettyFormatter.format_string(format_value)
expect(pretty).to be == "#<class\n @silencers =\n #<class\n @silencers =\n [\n #<Proc:0x007f8d9f2a15f0@/Users/elittell/.rvm/gems/ruby-1.9.3-p327@homerun/gems/railties-3.2.13/lib/rails/backtrace_cleaner.rb:15>\n ]\n >,\n \"HTTP_HO\" = \"HTTP_HO\"\n>"
end
it "formats an implied hash" do
format_value = "#<DbInjector::Deal id: 1, slug: \"6ff445f3\", type: \"daily-deal\">"
pretty = TestSupport::PrettyFormatter.format_string(format_value)
expect(pretty).to be == "#<DbInjector::Deal\n id: 1,\n slug: \"6ff445f3\",\n type: \"daily-deal\"\n>"
format_value = "".html_safe + "#<DbInjector::Deal id: 1, slug: \"6ff445f3\", type: \"daily-deal\">"
pretty = TestSupport::PrettyFormatter.format_string(format_value)
expect(pretty).to be == "#<DbInjector::Deal\n id: 1,\n slug: "6ff445f3",\n type: "daily-deal"\n>"
expect(pretty).to be_html_safe
end
it "formats parameters" do
format_value = "Parameters: { \"id\" => \"value\", \"deal\"=>{\"affinity_score\"=>nil, \"buy_button_clicks\"=>6 }, \"custom_data\"=>{\"custom_data\"=>{}} }"
pretty = TestSupport::PrettyFormatter.format_string(format_value)
expected = "Parameters:\n {\n \"id\" => \"value\",\n \"deal\" =>\n {\n \"affinity_score\" => nil,\n \"buy_button_clicks\" => 6\n },\n \"custom_data\" =>\n {\n \"custom_data\" =>\n {\n }\n }\n }"
expect(pretty).to be == expected
format_value = "".html_safe + format_value
expected = "".html_safe + expected
pretty = TestSupport::PrettyFormatter.format_string(format_value)
expect(pretty).to be == expected
expect(pretty).to be_html_safe
end
it "formats parameters embedded in text" do
format_value = "this is some expectation_in_text Parameters: { \"id\" => \"value\", \"deal\"=>{\"affinity_score\"=>nil, \"buy_button_clicks\"=>6 }, \"custom_data\"=>{\"custom_data\"=>{}} } this is some expectation_in_text"
pretty = TestSupport::PrettyFormatter.format_string(format_value)
expected = "this is some expectation_in_text\n Parameters:\n {\n \"id\" => \"value\",\n \"deal\" =>\n {\n \"affinity_score\" => nil,\n \"buy_button_clicks\" => 6\n },\n \"custom_data\" =>\n {\n \"custom_data\" =>\n {\n }\n }\n }\n this is some expectation_in_text"
expect(pretty).to be == expected
format_value = "".html_safe + format_value
expected = "".html_safe + expected
pretty = TestSupport::PrettyFormatter.format_string(format_value)
expect(pretty).to be == expected
expect(pretty).to be_html_safe
end
it "formats multiple parameters embedded in text" do
format_value = "this is some expectation_in_text Parameters: { \"id\" => \"value\", \"deal\"=>{\"affinity_score\"=>nil, \"buy_button_clicks\"=>6 }, \"custom_data\"=>{\"custom_data\"=>{}} } this is some expectation_in_textthis is some expectation_in_text Parameters: { \"id\" => \"value\", \"deal\"=>{\"affinity_score\"=>nil, \"buy_button_clicks\"=>6 }, \"custom_data\"=>{\"custom_data\"=>{}} } this is some expectation_in_text"
pretty = TestSupport::PrettyFormatter.format_string(format_value)
expected = "this is some expectation_in_text\n Parameters:\n {\n \"id\" => \"value\",\n \"deal\" =>\n {\n \"affinity_score\" => nil,\n \"buy_button_clicks\" => 6\n },\n \"custom_data\" =>\n {\n \"custom_data\" =>\n {\n }\n }\n }\n this is some expectation_in_textthis is some expectation_in_text\n Parameters:\n {\n \"id\" => \"value\",\n \"deal\" =>\n {\n \"affinity_score\" => nil,\n \"buy_button_clicks\" => 6\n },\n \"custom_data\" =>\n {\n \"custom_data\" =>\n {\n }\n }\n }\n this is some expectation_in_text"
expect(pretty).to be == expected
format_value = "".html_safe + format_value
expected = "".html_safe + expected
pretty = TestSupport::PrettyFormatter.format_string(format_value)
expect(pretty).to be == expected
expect(pretty).to be_html_safe
end
it "formats multiple parameters embedded in text" do
format_value = "[PartnerScope] Set to: chameleon_basic\nProcessing by DealsController#show as HTML\n Parameters: {\";id\"=>\"5e2a61bd\"}\nGET http://admin-homerun.localhost:3001//api/v2/deals/5e2a61bd.json?include=all"
pretty = TestSupport::PrettyFormatter.format_string(format_value)
expected = "[PartnerScope] Set to: chameleon_basic\nProcessing by DealsController#show as HTML\n Parameters:\n {\n \";id\" => \"5e2a61bd\"\n }\n\nGET http://admin-homerun.localhost:3001//api/v2/deals/5e2a61bd.json?include=all"
expect(pretty).to be == expected
format_value = ("".html_safe + format_value).to_s
expected = "".html_safe + expected
pretty = TestSupport::PrettyFormatter.format_string(format_value)
expect(pretty).to be == expected
expect(pretty).to be_html_safe
end
(1..100).to_a.each do |index|
it "formats a complicated value (#{index})" do
@seed_value = rand(100000000000000000000000000000000000000..899999999999999999999999999999999999999)
puts("@seed_value = #{@seed_value}")
srand(@seed_value)
test_value, expected_value = create_value(0, [:class, :embedded_class, :implied_hash, :parameters].sample)
pretty = TestSupport::PrettyFormatter.format_string(test_value)
expect(pretty).to be == expected_value
end
it "formats an html_safe complicated value (#{index})" do
@seed_value = rand(100000000000000000000000000000000000000..899999999999999999999999999999999999999)
puts("@seed_value = #{@seed_value}")
srand(@seed_value)
test_value, expected_value = create_value(0, [:class, :embedded_class, :implied_hash, :parameters].sample)
test_value = "".html_safe + test_value
expected_value = "".html_safe + expected_value
pretty = TestSupport::PrettyFormatter.format_string(test_value)
expect(pretty).to be == expected_value
expect(pretty).to be_html_safe
end
end
end
def create_simple_value(type, options = {})
case type
when :whitespace
if rand(0..10) == 0
simple_val = ""
else
simple_val = " " * rand(1..10)
simple_val += "\t" * rand(0..10)
unless options[:spaces_only]
simple_val += "\n" * rand(0..10)
simple_val += "\r" * rand(0..10)
end
simple_val = simple_val.split("").sample(100).join("")
end
when :value_name_simple, :value_method
simple_val = Faker::Lorem.word
simple_val = "#{simple_val}?" if rand(0..1) == 0
simple_val = "@#{simple_val}" if rand(0..1) == 0
when :value_name_string, :hash_key_string, :value_string
simple_val = "\"#{Faker::Lorem.sentence}\""
when :value_name_complex_string, :value_complex_string, :hash_key_complex_string
simple_val = "'#{'{}<>[]\"\#~?/`!@#$%^&*()-_=+`'}".split("").sample(rand(5..10)).join("")
simple_val = "#{simple_val}#{Faker::Lorem.word}".split("").join("")
simple_val = "#{Faker::Lorem.sentence} #{simple_val}".split(" ").join(" ")
simple_val = simple_val.gsub(/([\\\"])/, "\\\\\\1")
simple_val = "\"#{simple_val}\""
when :value_simple
case [:number, :float, :date, :date_time, :string, :word].sample
when :number
simple_val = rand(-9999999999..9999999999)
when :float
simple_val = rand * (10 ** rand(0..15))
when :date
simple_val = Date.today + rand(-99999..99999).days
when :date_time
simple_val = DateTime.now + rand(-9999999999..9999999999).seconds
when :string
simple_val = Faker::Lorem.sentence
when :word
simple_val = Faker::Lorem.word
end
when :hash_key_symbol
simple_val = ":#{Faker::Lorem.word}"
when :hash_key_reversed_symbol
simple_val = "#{Faker::Lorem.word}:"
end
simple_val.to_s
end
def create_value(level, type, options = {})
case type
when :parameters
sub_options = options.merge({ spaces_only: true })
pre_value = rand(0..1) == 0 ? Faker::Lorem.sentence : ""
post_value = rand(0..1) == 0 ? Faker::Lorem.sentence : ""
unless pre_value.blank?
if rand(0..1) == 0
pre_value << create_simple_value(:whitespace, options)
end
end
unless post_value.blank?
if rand(0..1) == 0
post_value = "#{create_simple_value(:whitespace, options)}#{post_value}"
end
end
if pre_value.blank?
val, expected = create_value(level + 1, :hash, sub_options)
else
val, expected = create_value(level + 2, :hash, sub_options)
end
unless post_value.blank?
post_value = "\n#{post_value}"
end
value_val = "#{pre_value}Parameters:#{create_simple_value(:whitespace, sub_options)}#{val}#{post_value}"
value_expect = "#{pre_value.rstrip}#{pre_value.rstrip.blank? ? "" : "\n "}Parameters:\n#{expected}\n#{post_value.rstrip}"
rand(0..5).times do
pre_value = rand(0..1) == 0 ? Faker::Lorem.sentence : ""
post_value = rand(0..1) == 0 ? Faker::Lorem.sentence : ""
if rand(0..1) == 0
val = create_simple_value(:whitespace, options)
value_val << val
value_expect << val
end
if rand(0..1) == 0
val = Faker::Lorem.sentence
value_val << val
value_expect << val
if rand(0..1) == 0
val = create_simple_value(:whitespace, options)
value_val << val
value_expect << val
end
end
if pre_value.blank?
if rand(0..1) == 0
pre_value << create_simple_value(:whitespace, options)
end
end
unless post_value.blank?
if rand(0..1) == 0
post_value = "#{create_simple_value(:whitespace, options)}#{post_value}"
end
end
unless post_value.blank?
post_value = "\n#{post_value}"
end
if pre_value.rstrip.blank?
value_expect.rstrip!
end
val, expected = create_value(level + 2, :hash, sub_options)
value_val << "#{pre_value}Parameters:#{create_simple_value(:whitespace, sub_options)}#{val}#{post_value}"
value_expect << "#{pre_value.rstrip}\n Parameters:\n#{expected}\n#{post_value.rstrip}"
end
value_expect.rstrip!
when :embedded_class
pre_value = rand(0..1) == 0 ? Faker::Lorem.sentence : ""
post_value = rand(0..1) == 0 ? Faker::Lorem.sentence : ""
unless pre_value.blank?
if rand(0..1) == 0
pre_value << create_simple_value(:whitespace, options)
end
end
unless post_value.blank?
if rand(0..1) == 0
post_value = "#{create_simple_value(:whitespace, options)}#{post_value}"
end
end
if pre_value.blank?
val, expected = create_value(level, :class_with_value, options)
else
val, expected = create_value(level + 1, :class_with_value, options)
end
unless post_value.blank?
post_value = "\n#{post_value}"
end
value_val = "#{pre_value}#{val}#{post_value}"
value_expect = "#{pre_value.rstrip}#{pre_value.rstrip.blank? ? "" : "\n"}#{expected}\n#{post_value.rstrip}"
rand(0..5).times do
pre_value = rand(0..1) == 0 ? Faker::Lorem.sentence : ""
post_value = rand(0..1) == 0 ? Faker::Lorem.sentence : ""
if rand(0..1) == 0
val = create_simple_value(:whitespace, options)
value_val << val
value_expect << val
end
if rand(0..1) == 0
val = Faker::Lorem.sentence
value_val << val
value_expect << val
if rand(0..1) == 0
val = create_simple_value(:whitespace, options)
value_val << val
value_expect << val
end
end
if pre_value.blank?
if rand(0..1) == 0
pre_value << create_simple_value(:whitespace, options)
end
end
unless post_value.blank?
if rand(0..1) == 0
post_value = "#{create_simple_value(:whitespace, options)}#{post_value}"
end
end
unless post_value.blank?
post_value = "\n#{post_value}"
end
if pre_value.rstrip.blank?
value_expect.rstrip!
end
val, expected = create_value(level + 1, :class, options)
value_val << "#{pre_value}#{val}#{post_value}"
value_expect << "#{pre_value.rstrip}\n#{expected}\n#{post_value.rstrip}"
end
value_expect.rstrip!
when :class, :class_with_value
name = create_simple_value(:value_name_simple, options)
value_val = "\#<#{name}#{" " * rand(1..10)}"
value_expect = "#{" " * level}\#<#{name}"
append_value = ""
append_expect = "\n"
range_start = type == :class ? 0 : 1
rand(range_start..5).times do
name = create_simple_value([:value_name_complex_string, :value_name_simple, :value_name_string].sample, options)
val_type = [:class, :value, :hash, :array].sample
val_type = :value if level > 4 || rand(0.1) == 0
case val_type
when :class, :hash, :array
val, expected = create_value(level + 2, val_type, options)
when :value
val = create_simple_value([:value_simple, :value_string, :value_method, :value_complex_string].sample, options)
expected = val
end
value_val << "#{append_value}#{name}#{create_simple_value(:whitespace, options)}=#{create_simple_value(:whitespace, options)}#{val}"
if val_type == :value
value_expect << "#{append_expect}#{" " * (level + 1)}#{name} = #{expected}"
else
value_expect << "#{append_expect}#{" " * (level + 1)}#{name} =\n#{expected}"
end
append_value = ",#{create_simple_value(:whitespace, options)}"
append_expect = ",\n"
end
unless append_expect.empty?
append_expect = append_expect[1..-1]
end
unless append_expect.empty?
append_expect << " " * level
end
value_val << "#{" " * rand(0..10)}>"
value_expect << "#{append_expect}>"
when :implied_hash
options.merge!({ spaces_only: true })
name = create_simple_value(:value_name_simple, options)
value_val = "\#<#{name}#{" " * rand(1..10)}"
value_expect = "#{" " * level}\#<#{name}"
append_value = ""
append_expect = "\n"
rand(1..5).times do
hash_type = [:hash_key_reversed_symbol].sample
name = create_simple_value(hash_type, options)
val_type = [:class, :value, :hash, :array].sample
val_type = :value if level > 4 || rand(0.1) == 0
case val_type
when :class, :hash, :array
val, expected = create_value(level + 2, val_type, options)
when :value
val = create_simple_value([:value_simple, :value_string, :value_method, :value_complex_string].sample, options)
expected = val
end
value_val << "#{append_value}#{name}#{" " * rand(1..10)}#{val}"
if val_type == :value
value_expect << "#{append_expect}#{" " * (level + 1)}#{name} #{expected}"
else
value_expect << "#{append_expect}#{" " * (level + 1)}#{name}\n#{expected}"
end
append_value = ",#{create_simple_value(:whitespace, options)}"
append_expect = ",\n"
end
value_val << "#{create_simple_value(:whitespace, options)}>"
value_expect << "\n#{" " * level}>"
when :hash
value_val = "{#{create_simple_value(:whitespace, options)}"
value_expect = "#{" " * level}{\n"
append_value = ""
append_expect = ""
rand(1..5).times do
hash_type = [:hash_key_string, :hash_key_complex_string, :hash_key_symbol, :hash_key_reversed_symbol].sample
name = create_simple_value(hash_type, options)
val_type = [:class, :value, :hash, :array].sample
val_type = :value if level > 4 || rand(0.1) == 0
case val_type
when :class, :hash, :array
val, expected = create_value(level + 2, val_type, options)
when :value
val = create_simple_value([:value_simple, :value_string, :value_method, :value_complex_string].sample, options)
expected = val
end
case hash_type
when :hash_key_reversed_symbol
value_val << "#{append_value}#{name}#{create_simple_value(:whitespace, options)}#{val}"
if val_type == :value
value_expect << "#{append_expect}#{" " * (level + 1)}#{name} #{expected}"
else
value_expect << "#{append_expect}#{" " * (level + 1)}#{name}\n#{expected}"
end
else
value_val << "#{append_value}#{name}#{create_simple_value(:whitespace, options)}=>#{create_simple_value(:whitespace, options)}#{val}"
if val_type == :value
value_expect << "#{append_expect}#{" " * (level + 1)}#{name} => #{expected}"
else
value_expect << "#{append_expect}#{" " * (level + 1)}#{name} =>\n#{expected}"
end
end
append_value = ",#{create_simple_value(:whitespace, options)}"
append_expect = ",\n"
end
value_val << "#{create_simple_value(:whitespace, options)}}"
value_expect << "\n#{" " * level}}"
when :array
value_val = "[#{create_simple_value(:whitespace, options)}"
value_expect = "#{" " * level}[\n"
append_value = ""
append_expect = ""
rand(1..5).times do
val_type = [:class, :value, :hash, :array].sample
val_type = :value if level > 4 || rand(0.1) == 0
case val_type
when :class, :hash, :array
val, expected = create_value(level + 1, val_type, options)
when :value
val = create_simple_value([:value_simple, :value_string, :value_method, :value_complex_string].sample, options)
expected = "#{" " * (level + 1)}#{val}"
end
value_val << "#{append_value}#{val}"
value_expect << "#{append_expect}#{expected}"
append_value = ",#{create_simple_value(:whitespace, options)}"
append_expect = ",\n"
end
value_val << "#{create_simple_value(:whitespace, options)}]"
value_expect << "\n#{" " * level}]"
end
[value_val, value_expect]
end
def expectation_in_text(expected_text, pre_text, post_text)
expected = "#{pre_text}#{expected_text}#{post_text}"
expected = expected.gsub("\n", "\n ") unless pre_text.empty?
expected = expected.gsub(post_text.gsub("\n", "\n "), post_text)
expected
end | mit |
Em-Ant/fcc-options-app | app/routes/report.js | 495 | 'use strict';
var express = require('express');
var router = express.Router();
var Controller = require('../controllers/reportHandler.js');
var controller = new Controller();
var isLoggedIn = require('../auth/ensureAuth.js').isLoggedIn;
//retrieves all routes
router.get('/vehicles', isLoggedIn, controller.vehiclesReport);
router.get('/consumers', isLoggedIn, controller.consumersReport);
router.get('/directions/:v_id', isLoggedIn, controller.getDocxDirections);
module.exports = router;
| mit |
rsheftel/pandas_market_calendars | tests/test_ose_calendar.py | 5245 | """
Currently only 2017, 2018 and 2019 dates are confirmed.
Dates based on:
- (not this is for OBX and Equity Derivatives)
https://www.oslobors.no/obnewsletter/download/1e05ee05a9c1a472da4c715435ff1314/file/file/Bortfallskalender%202017-2019.pdf
- https://www.oslobors.no/ob_eng/Oslo-Boers/About-Oslo-Boers/Opening-hours
"""
import pandas as pd
import pytest
import pytz
from pandas_market_calendars.exchange_calendar_ose import OSEExchangeCalendar
TIMEZONE = pytz.timezone("Europe/Oslo")
def test_time_zone():
assert OSEExchangeCalendar().tz == pytz.timezone("Europe/Oslo")
def test_name():
assert OSEExchangeCalendar().name == "OSE"
def test_open_time_tz():
ose = OSEExchangeCalendar()
assert ose.open_time.tzinfo == ose.tz
def test_close_time_tz():
ose = OSEExchangeCalendar()
assert ose.close_time.tzinfo == ose.tz
def test_2017_calendar():
ose = OSEExchangeCalendar()
ose_schedule = ose.schedule(
start_date=pd.Timestamp("2017-04-11", tz=TIMEZONE),
end_date=pd.Timestamp("2017-04-13", tz=TIMEZONE)
)
regular_holidays_2017 = [
pd.Timestamp("2017-04-13", tz=TIMEZONE),
pd.Timestamp("2017-04-14", tz=TIMEZONE),
pd.Timestamp("2017-04-17", tz=TIMEZONE),
pd.Timestamp("2017-05-01", tz=TIMEZONE),
pd.Timestamp("2017-05-17", tz=TIMEZONE),
pd.Timestamp("2017-05-25", tz=TIMEZONE),
pd.Timestamp("2017-06-05", tz=TIMEZONE),
pd.Timestamp("2017-12-25", tz=TIMEZONE),
pd.Timestamp("2017-12-26", tz=TIMEZONE)
]
half_trading_days_2017 = [
pd.Timestamp("2017-04-12", tz=TIMEZONE)
]
valid_market_dates = ose.valid_days("2017-01-01", "2017-12-31", tz=TIMEZONE)
for closed_market_date in regular_holidays_2017:
assert closed_market_date not in valid_market_dates
for half_trading_day in half_trading_days_2017:
assert half_trading_day in valid_market_dates
assert ose.open_at_time(
schedule=ose_schedule,
timestamp=pd.Timestamp("2017-04-12 12PM", tz=TIMEZONE)
)
with pytest.raises(ValueError):
ose.open_at_time(
schedule=ose_schedule,
timestamp=pd.Timestamp("2017-04-12 2PM", tz=TIMEZONE)
)
def test_2018_calendar():
ose = OSEExchangeCalendar()
ose_schedule = ose.schedule(
start_date=pd.Timestamp("2018-03-27", tz=TIMEZONE),
end_date=pd.Timestamp("2018-03-29", tz=TIMEZONE)
)
regular_holidays_2018 = [
pd.Timestamp("2018-01-01", tz=TIMEZONE),
pd.Timestamp("2018-03-29", tz=TIMEZONE),
pd.Timestamp("2018-03-30", tz=TIMEZONE),
pd.Timestamp("2018-05-01", tz=TIMEZONE),
pd.Timestamp("2018-05-10", tz=TIMEZONE),
pd.Timestamp("2018-05-17", tz=TIMEZONE),
pd.Timestamp("2018-05-21", tz=TIMEZONE),
pd.Timestamp("2018-12-24", tz=TIMEZONE),
pd.Timestamp("2018-12-25", tz=TIMEZONE),
pd.Timestamp("2018-12-26", tz=TIMEZONE),
pd.Timestamp("2018-12-31", tz=TIMEZONE)
]
half_trading_days_2018 = [
pd.Timestamp("2018-03-28", tz=TIMEZONE)
]
valid_market_dates = ose.valid_days("2018-01-01", "2018-12-31", tz=TIMEZONE)
for closed_market_date in regular_holidays_2018:
assert closed_market_date not in valid_market_dates
for half_trading_day in half_trading_days_2018:
assert half_trading_day in valid_market_dates
assert ose.open_at_time(
schedule=ose_schedule,
timestamp=pd.Timestamp("2018-03-28 12PM", tz=TIMEZONE)
)
with pytest.raises(ValueError):
ose.open_at_time(
schedule=ose_schedule,
timestamp=pd.Timestamp("2018-03-28 1:10PM", tz=TIMEZONE)
)
def test_2019_calendar():
ose = OSEExchangeCalendar()
ose_schedule = ose.schedule(
start_date=pd.Timestamp("2019-04-16", tz=TIMEZONE),
end_date=pd.Timestamp("2019-04-18", tz=TIMEZONE)
)
regular_holidays_2019 = [
pd.Timestamp("2019-01-01", tz=TIMEZONE),
pd.Timestamp("2019-04-18", tz=TIMEZONE),
pd.Timestamp("2019-04-19", tz=TIMEZONE),
pd.Timestamp("2019-04-22", tz=TIMEZONE),
pd.Timestamp("2019-05-01", tz=TIMEZONE),
pd.Timestamp("2019-05-17", tz=TIMEZONE),
pd.Timestamp("2019-05-30", tz=TIMEZONE),
pd.Timestamp("2019-06-10", tz=TIMEZONE),
pd.Timestamp("2019-12-24", tz=TIMEZONE),
pd.Timestamp("2019-12-25", tz=TIMEZONE),
pd.Timestamp("2019-12-26", tz=TIMEZONE),
pd.Timestamp("2019-12-31", tz=TIMEZONE)
]
half_trading_days_2019 = [
pd.Timestamp("2019-04-17", tz=TIMEZONE)
]
valid_market_dates = ose.valid_days("2019-01-01", "2019-12-31", tz=TIMEZONE)
for closed_market_date in regular_holidays_2019:
assert closed_market_date not in valid_market_dates
for half_trading_day in half_trading_days_2019:
assert half_trading_day in valid_market_dates
assert ose.open_at_time(
schedule=ose_schedule,
timestamp=pd.Timestamp("2019-04-17 12PM", tz=TIMEZONE)
)
with pytest.raises(ValueError):
ose.open_at_time(
schedule=ose_schedule,
timestamp=pd.Timestamp("2019-04-17 1:10PM", tz=TIMEZONE)
)
| mit |
tokenly/xchain-client | src/Exception/XChainException.php | 342 | <?php
namespace Tokenly\XChainClient\Exception;
use Exception;
/*
* XChainException
*/
class XChainException extends Exception
{
public function setErrorName($account_error_name) {
$this->account_error_name = $account_error_name;
}
public function getErrorName() {
return $this->account_error_name;
}
}
| mit |
svlcode/HomeManager | sources/HomeManager/HomeManager.GUI/Views/Base/BaseActionView.cs | 1767 | using System;
using System.Data;
using System.Windows.Forms;
using HomeBudget.Dao;
using HomeBudget.Forms;
using HomeManager.GUI.Enums;
using HomeManager.Model.Dao.Impl;
namespace HomeBudget.Views.Base
{
public abstract class BaseActionView
{
public abstract string Caption { get; }
public abstract ViewTypeEnum View { get; }
protected DataTable GetDataTableFromView(string dbViewName)
{
var sysViewDao = new SysViewDao();
return sysViewDao.GetDataTableFromView(dbViewName);
}
protected void OpenEntityFormRecord(IEntityForm form, int entityId)
{
form.SetCurrentId(entityId);
OpenEntityFormRecord(form);
}
protected void OpenEntityFormRecord(IEntityForm form)
{
bool refreshView = CarRefreshAfterFormHasClosed(form);
if (refreshView)
{
OnRecordSaved();
}
}
private bool CarRefreshAfterFormHasClosed(IEntityForm form)
{
bool refreshView = false;
using (form)
{
if (form.ShowDialog() == DialogResult.OK)
{
refreshView = true;
}
}
return refreshView;
}
public event EventHandler RecordSaved;
protected void OnRecordSaved()
{
if (RecordSaved != null)
{
RecordSaved(this, EventArgs.Empty);
}
}
public abstract DataTable GetOverviewData();
public abstract void OpenRecord(int id);
public abstract void DeleteRecord(int id);
public abstract void AddNewRecord();
}
} | mit |
jadget/jadget-exception | src/test/java/net/jadget/exception/OverlappingScopes3.java | 806 | package net.jadget.exception;
import net.jadget.exception.ErrorCode;
import net.jadget.exception.ErrorCodes;
import net.jadget.exception.Range;
public enum OverlappingScopes3 implements ErrorCode {
SOME_ERROR(1, "SomeError")
;
@Override
public int offset() {
return code;
}
@Override
public String getName() {
return name;
}
@Override
public Range getRange() {
return scope;
}
@Override
public String toString() {
return ErrorCodes.formatErrorCode(this);
}
private OverlappingScopes3(int code, String name) {
this.code = code;
this.name = name;
}
private final int code;
private final String name;
private static final Range scope = new Range(200, 299);
}
| mit |
luckysailor/broker | lib/broker/version.rb | 38 | module Broker
VERSION = "0.1.2"
end
| mit |
SuperbCoders/superb_text_constructor | lib/superb_text_constructor/engine.rb | 655 | module SuperbTextConstructor
class Engine < ::Rails::Engine
isolate_namespace SuperbTextConstructor
initializer 'superb_text_constructor.view_helpers' do |app|
ActionView::Base.send :include, SuperbTextConstructor::ViewHelpers::RenderBlocksHelper
ActionView::Base.send :include, SuperbTextConstructor::ViewHelpers::EditorHelper
ActionView::Base.send :include, SuperbTextConstructor::ViewHelpers::SanitizeBlockHelper
end
initializer 'superb_text_constructor.assets.precompile' do |app|
app.config.assets.precompile += %w( superb_text_constructor/custom.js superb_text_constructor/custom.css )
end
end
end
| mit |
Sedatb23/DiscordBot | src/VoiceUDPClient.js | 2835 | const dgram = require('dgram');
const dns = require('dns');
class VoiceUDPClient {
constructor(voiceClient) {
this._bot = voiceClient._bot;
this._voiceClient = voiceClient;
}
initConnection(data) {
this._socket = dgram.createSocket('udp4');
this._socket.once('message', message => {
const packet = this.parseLocalPacket(message);
if (packet.error) {
return;
}
// this._endpoint = packet.address;
// this._port = packet.port;
this._voiceClient.send(1, {
protocol: 'udp',
data: {
address: packet.address,
port: packet.port,
mode: 'xsalsa20_poly1305',
},
});
});
this._socket.on('message', message => this._voiceClient._voiceReceiver.handle(message));
this._endpoint = data.ip;
this._port = data.port;
this.findEndpointAddress().then(() => {
const blankMessage = Buffer.alloc(70);
blankMessage.writeUIntBE(data.ssrc, 0, 4);
this.send(blankMessage);
});
}
/**
* Tries to resolve the voice server endpoint to an address
* @returns {Promise<string>}
*/
findEndpointAddress() {
return new Promise((resolve, reject) => {
dns.lookup(this._endpoint, (error, address) => {
if (error) {
reject(error);
return;
}
this._discordAddress = address;
resolve(address);
});
});
}
send(packet) {
return new Promise((resolve, reject) => {
if (!this._socket) {
throw new Error('Tried to send a UDP packet, but there is no socket available.');
}
if (!this._discordAddress) {
throw new Error('Malformed UDP address or port. ' + this._discordAddress);
}
this._socket.send(packet, 0, packet.length, this._port, this._discordAddress, error => {
if (error) {
reject(error);
}
else {
resolve(packet);
}
});
});
}
parseLocalPacket(message) {
try {
const packet = Buffer.from(message);
let address = '';
for (let i = 4; i < packet.indexOf(0, i); i++) address += String.fromCharCode(packet[i]);
const port = parseInt(packet.readUIntLE(packet.length - 2, 2).toString(10), 10);
return { address, port };
} catch (error) {
return { error };
}
}
}
module.exports = VoiceUDPClient; | mit |
coolsgupta/machine_learning_nanodegree | Model_Evaluation_and_Validation/evaluation_metrics/precision_vs_recall.py | 1439 | # As with the previous exercises, let's look at the performance of a couple of classifiers
# on the familiar Titanic dataset. Add a train/test split, then store the results in the
# dictionary provided.
import numpy as np
import pandas as pd
# Load the dataset
X = pd.read_csv('titanic_data.csv')
X = X._get_numeric_data()
y = X['Survived']
del X['Age'], X['Survived']
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import recall_score as recall
from sklearn.metrics import precision_score as precision
from sklearn.naive_bayes import GaussianNB
from sklearn.cross_validation import train_test_split
# TODO: split the data into training and testing sets,
# using the standard settings for train_test_split.
# Then, train and test the classifiers with your newly split data instead of X and y.
x_train, x_test, y_train, y_test = train_test_split(X,y,test_size=0.4,random_state=0)
clf1 = DecisionTreeClassifier()
clf1.fit(x_train, y_train)
print "Decision Tree recall: {:.2f} and precision: {:.2f}".format(recall(y_test,clf1.predict(x_test)),precision(y_test,clf1.predict(x_test)))
clf2 = GaussianNB()
clf2.fit(x_train, y_train)
print "GaussianNB recall: {:.2f} and precision: {:.2f}".format(recall(y_test,clf2.predict(x_test)),precision(y_test,clf2.predict(x_test)))
results = {
"Naive Bayes Recall": 0.38,
"Naive Bayes Precision": 0.58,
"Decision Tree Recall": 0.51,
"Decision Tree Precision": 0.61
} | mit |
EdLeming/echidna | echidna/output/plot.py | 3068 | from mpl_toolkits.mplot3d import Axes3D
import pylab
import numpy
def _produce_axis(low, high, bins):
""" This method produces an array that represents the axis between low and
high with bins.
Args:
low (float): Low edge of the axis
high (float): High edge of the axis
bins (int): Number of bins
"""
return [low + x * (high - low) / bins for x in range(bins)]
def plot_projection(spectra, dimension):
""" Plot the spectra as projected onto the dimension.
For example dimension == 0 will plot the spectra as projected onto the
energy dimension.
Args:
spectra (:class:`echidna.core.spectra`): The spectra to plot.
dimension (int): The dimension to project the spectra onto.
"""
figure = pylab.figure()
axis = figure.add_subplot(1, 1, 1)
if dimension == 0:
x = _produce_axis(spectra._energy_low, spectra._energy_high, spectra._energy_bins)
width = spectra._energy_width
pylab.xlabel("Energy [MeV]")
elif dimension == 1:
x = _produce_axis(spectra._radial_low, spectra._radial_high, spectra._radial_bins)
width = spectra._radial_width
pylab.xlabel("Radius [mm]")
elif dimension == 2:
x = _produce_axis(spectra._time_low, spectra._time_high, spectra._time_bins)
width = spectra._time_width
pylab.xlabel("Time [yr]")
pylab.ylabel("Count per %f bin" % width)
data = spectra.project(dimension)
axis.bar(x, data, width=width)
pylab.show()
def plot_surface(spectra, dimension):
""" Plot the spectra with the dimension projected out.
For example dimension == 0 will plot the spectra as projected onto the
radial and time dimensions i.e. not energy.
Args:
spectra (:class:`echidna.core.spectra`): The spectra to plot.
dimension (int): The dimension to project out.
"""
figure = pylab.figure()
axis = figure.add_subplot(111, projection='3d')
if dimension == 0:
x = _produce_axis(spectra._radial_low, spectra._radial_high, spectra._radial_bins)
y = _produce_axis(spectra._energy_low, spectra._energy_high, spectra._energy_bins)
data = spectra.surface(2)
axis.set_xlabel("Radius [mm]")
axis.set_ylabel("Energy [MeV]")
elif dimension == 1:
x = _produce_axis(spectra._time_low, spectra._time_high, spectra._time_bins)
y = _produce_axis(spectra._energy_low, spectra._energy_high, spectra._energy_bins)
data = spectra.surface(1)
axis.set_xlabel("Time [yr]")
axis.set_ylabel("Energy [MeV]")
elif dimension == 2:
x = _produce_axis(spectra._time_low, spectra._time_high, spectra._time_bins)
y = _produce_axis(spectra._radial_low, spectra._radial_high, spectra._radial_bins)
data = spectra.surface(0)
axis.set_xlabel("Time [yr]")
axis.set_ylabel("Radius [mm]")
axis.set_zlabel("Count per bin")
X, Y = numpy.meshgrid(x, y) # `plot_surface` expects `x` and `y` data to be 2D
axis.plot_surface(X, Y, data)
pylab.show()
| mit |
platoon-djs/platoon-se | app/views/emails/e-request.php | 4576 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head lang="sv">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Single-Column Responsive Email Template</title>
<style type="text/css">
@media only screen and (min-device-width: 541px) {
.content {
width: 540px !important;
}
}
.header {
padding: 40px 30px 20px;
font-family: sans-serif;
font-size: 33px; line-height: 38px; font-weight: bold;
color: #B3DBFF;
}
.body {
padding: 20px 10px;
font-family: sans-serif;
}
.button {text-align: center; font-size: 18px; font-family: sans-serif; font-weight: bold; padding: 0 30px 0 30px;}
.button a {color: #ffffff; text-decoration: none;}
</style>
</head>
<body>
<!--[if (gte mso 9)|(IE)]>
<table width="540" align="center" cellpadding="0" cellspacing="0" border="0">
<tr>
<td>
<![endif]-->
<table class="content" align="center" cellpadding="0" cellspacing="0" border="0" style="width: 100%; max-width: 600px;">
<tr>
<td class="header" bgcolor="#0074D9" style="padding: 40px 30px 20px;font-family: sans-serif;font-size: 33px;line-height: 38px;font-weight: bold;color: #B3DBFF;">Bokningsförfrågan</td>
</tr>
<tr>
<td class="body" bgcolor="#f8f8f8" style="padding: 20px 10px;font-family: sans-serif;width:100%">
<table align="left">
<tr align="left">
<td colspan="2">
<h3 style="margin:10px 0 5px">Kontaktuppgifter</h3>
</td>
</tr>
<tr align="left">
<th width="40%">Namn</th>
<td><?php echo $name?></td>
</tr>
<tr align="left">
<th>E-post</th>
<td><?php echo $email?></td>
</tr>
<tr align="left">
<th>Telefonnummer</th>
<td><?php echo $phone?></td>
</tr>
<tr align="left">
<td colspan="2">
<h3 style="margin:10px 0 5px">Eventinformation</h3>
</td>
</tr>
<tr align="left">
<th>Event</th>
<td><?php echo $event?></td>
</tr>
<tr align="left">
<th>Datum</th>
<td><?php echo $date?></td>
</tr>
<tr align="left">
<th>Tid</th>
<td><?php echo $timeFrom . '-' . $timeTo?></td>
</tr>
<tr align="left">
<th>Plats</th>
<td><?php echo $place?></td>
</tr>
<tr align="left">
<th>Ljud</th>
<td><?php echo $sound?></td>
</tr>
<tr align="left">
<th>Ljus</th>
<td><?php echo $light?></td>
</tr>
<tr align="left">
<th>Tidig rodd</th>
<td><?php echo $setup?></td>
</tr>
<tr align="left">
<td colspan="2">
<h3 style="margin:10px 0 5px">Övrig information</h3>
</td>
</tr>
<tr align="left">
<th>Referens</th>
<td><?php echo $renown?></td>
</tr>
<tr align="left">
<th colspan="2">Meddelande</th>
</tr>
<tr>
<td colspan="2"><?php echo nl2br($description)?></td>
</tr>
<tr><td colspan="2"> </td></tr>
<tr><td colspan="2"> </td></tr>
</table>
</td>
</tr>
</table>
<!--[if (gte mso 9)|(IE)]>
</td>
</tr>
</table>
<![endif]-->
</body>
</html>
| mit |
kenny-nelson/GomiBako | Tools/NayaNET/Naya/MainViewModel.cs | 2409 | //-----------------------------------------------------------------------
// <copyright file="MainViewModel.cs" company="none">
// Copyright (c) kenny-nelson All Rights Reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Naya
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Dodai;
using Dodai.Commands;
using Dodai.Menus;
using Dodai.Panels;
using Dodai.Plugins;
using Dodai.ViewModels;
using Naya.Modules.About;
/// <summary>
/// メインビューのビューモデルクラスです。
/// </summary>
public class MainViewModel : WorkspaceViewModel
{
private readonly ICommand exitCommand;
private readonly ICommand aboutCommand;
/// <summary>
/// コンストラクタです。
/// </summary>
public MainViewModel()
{
this.exitCommand =
new ViewReceiverCommand<object>(param => this.ExecuteExit(param), param => { return this.CanExecuteExit(param); });
this.aboutCommand =
new ViewReceiverCommand<object>(param => this.ExecuteAbout(param), param => { return this.CanExecuteAbout(param); });
}
/// <summary>
/// Exit処理を行うコマンドを取得します。
/// </summary>
public ICommand ExitCommand
{
get
{
return this.exitCommand;
}
}
/// <summary>
/// About 処理を行うコマンドを取得します。
/// </summary>
public ICommand AboutCommand
{
get
{
return this.aboutCommand;
}
}
private void ExecuteExit(object parameter)
{
}
private bool CanExecuteExit(object parameter)
{
return true;
}
private void ExecuteAbout(object parameter)
{
GlobalPresenter.Show<AboutDialog>();
}
private bool CanExecuteAbout(object parameter)
{
return true;
}
}
}
| mit |
Azure/azure-sdk-for-ruby | management/azure_mgmt_batchai/lib/2018-03-01/generated/azure_mgmt_batchai/models/file_server_provisioning_state.rb | 481 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::BatchAI::Mgmt::V2018_03_01
module Models
#
# Defines values for FileServerProvisioningState
#
module FileServerProvisioningState
Creating = "creating"
Updating = "updating"
Deleting = "deleting"
Succeeded = "succeeded"
Failed = "failed"
end
end
end
| mit |
aaronsaray/tell-me-about-my-browser | src/Util/Di.php | 1398 | <?php
/**
* The custom Dependency injection extension of Pimple
*
* @author Aaron Saray
*/
namespace AboutBrowser\Util;
/**
* Class Di
* @package AboutBrowser\Util
*/
class Di extends \Pimple\Container
{
/**
* @var \AboutBrowser\Util\Di
*/
protected static $instance;
/**
* Get the instance of this
* @return Di
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self;
}
return self::$instance;
}
/**
* Fill the container
*/
public function __construct()
{
$this->offsetSet('entityManager', function($c) {
$isDevMode = getenv('APPLICATION_ENV') == 'development';
$config = \Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration(array(__DIR__ . '/../Model'), $isDevMode);
$conn = array(
'driver' => 'pdo_mysql',
'dbname' => 'browser',
'user' => getenv('MYSQL_USER'),
'password' => getenv('MYSQL_PASS')
);
$entityManager = \Doctrine\ORM\EntityManager::create($conn, $config);
return $entityManager;
});
$this->offsetSet('visitorService', function($c) {
return new \AboutBrowser\Service\Visitor($c['entityManager']);
});
}
} | mit |
facash/facoin | contrib/qt_translations.py | 612 | #!/usr/bin/env python
# Helpful little script that spits out a comma-separated list of
# language codes for Qt icons that should be included
# in binary facoin distributions
import glob
import os
import re
import sys
if len(sys.argv) != 3:
sys.exit("Usage: %s $QTDIR/translations $FACOINDIR/src/qt/locale"%sys.argv[0])
d1 = sys.argv[1]
d2 = sys.argv[2]
l1 = set([ re.search(r'qt_(.*).qm', f).group(1) for f in glob.glob(os.path.join(d1, 'qt_*.qm')) ])
l2 = set([ re.search(r'facoin_(.*).qm', f).group(1) for f in glob.glob(os.path.join(d2, 'facoin_*.qm')) ])
print ",".join(sorted(l1.intersection(l2)))
| mit |
rflynn/radixtree | src/example.py | 141 | # ex: set ts=4 et:
from radixtree import RadixTree, URLTree
r = RadixTree()
r.insert('foo.bar')
r.insert('foo')
r.insert('baz')
print r
| mit |
2Gramm/jQueryUIBundle | ZweigrammJQueryUIBundle.php | 299 | <?php
namespace Zweigramm\JQueryUIBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
/**
* Class ZweigrammJQueryUIBundle
*
* @package Zweigramm\JQueryUIBundle
* @copyright 2Gramm Werbeagentur 2013
* @link http://www.2gramm.com
*/
class ZweigrammJQueryUIBundle extends Bundle
{
} | mit |
nosenseworrying/xmlsoccer | spec/spec_helper.rb | 62 | require 'xml_soccer'
RSpec.configure do |config|
end | mit |
moonglum/dncts | features/step_definitions/basic_steps.rb | 5223 | require "./features/support/server"
require "./features/support/graphs"
server = Server.instance
Given(/^player "(.*)" registered$/) do |player_name|
server.create_player(player_name)
end
Given(/^lobby "(.*)" was created$/) do |lobby_name|
server.create_lobby(lobby_name)
end
When(/^player "(.*)" joins lobby "(.*)"$/) do |player_name, lobby_name|
server.join_lobby(lobby_name, player_name)
end
When(/^player "(.*)" leaves lobby "(.*)"$/) do |player_name, lobby_name|
server.leave_lobby(lobby_name, player_name)
end
Then(/^lobby "(.*)" should be listed$/) do |lobby_name|
lobbies = server.list_lobbies
expect(lobbies.any? { |lobby| lobby["lobby_name"] == lobby_name }).to be(true)
end
Then(/^the player "(.*)" should be in the game of lobby "(.*)"$/) do |player_name, lobby_name|
game = server.get_game_for_lobby(lobby_name)
expect(game["players"].any? { |player| player["player_name"] == player_name }).to be(true)
end
Then(/^the player "(.*)" should not be in the game of lobby "(.*)"$/) do |player_name, lobby_name|
game = server.get_game_for_lobby(lobby_name)
expect(game["players"].any? { |player| player["player_name"] == player_name }).to be(false)
end
Then(/^the game of lobby "(.*)" should not be started$/) do |lobby_name|
game = server.get_game_for_lobby(lobby_name)
expect(game["is_started"]).to be(false)
end
Then(/^the game of lobby "(.*)" should be started$/) do |lobby_name|
game = server.get_game_for_lobby(lobby_name)
expect(game["is_started"]).to be(true)
end
When(/^the game of lobby "(.*)" is started with the "(.*)" graph$/) do |lobby_name, graph_name|
graph = GRAPHS[graph_name]
server.start_game(lobby_name, graph)
end
Then(/^the lobby "(.*)" should contain (\d+) vertices and (\d+) edges?$/) do |lobby_name, number_of_vertices, number_of_edges|
game = server.get_game_for_lobby(lobby_name)
expect(game["vertices"].length).to be(number_of_vertices.to_i)
expect(game["edges"].length).to be(number_of_edges.to_i)
end
Given(/^player "(.*)" is in the game "(.*)" playing on the "(.*)" graph$/) do |player_name, lobby_name, graph_name|
graph = GRAPHS[graph_name]
server.create_player(player_name)
server.create_lobby(lobby_name)
server.join_lobby(lobby_name, player_name)
server.start_game(lobby_name, graph)
end
When(/^player "(.*)" sets his or her position to "(.*?)","(.*?)"$/) do |player_name, lat, lon|
player_id = server.players[player_name]
server.update({
"player" => { "id" => player_id, "lat" => lat, "lon" => lon },
"vertex" => ""
})
end
Then(/^the position of player "(.*)" in the game "(.*)" should be "(.*?)","(.*?)"$/) do |player_name, lobby_name, lat, lon|
player_id = server.players[player_name]
game_state = server.get_game_state_for_lobby(lobby_name)
expect(game_state["players"].any? { |player|
player["id"] == player_id and player["lat"] == lat and player["lon"] == lon
}).to be(true)
end
When(/^player "(.*)" sets his or her position and the position of vertex "(.*?)" to "(.*?)","(.*?)"$/) do |player_name, vertex_id, lat, lon|
player_id = server.players[player_name]
server.update({
"player" => { "id" => player_id, "lat" => lat, "lon" => lon },
"vertex" => { "id" => vertex_id, "lat" => lat, "lon" => lon, "carrier" => player_id }
})
end
Then(/^the position of vertex "(\d+)" in the game "(.*)" should be "(.*?)","(.*?)"$/) do |vertex_id, lobby_name, lat, lon|
game_state = server.get_game_state_for_lobby(lobby_name)
expect(game_state["vertices"].any? { |vertex|
vertex["id"] == vertex_id and vertex["lat"] == lat and vertex["lon"] == lon
}).to be(true)
end
When(/^player "(.*)" drops the vertex "(\d+)" and sets his or her position to "(.*?)","(.*?)"$/) do |player_name, vertex_id, lat, lon|
player_id = server.players[player_name]
server.update({
"player" => { "id" => player_id, "lat" => lat, "lon" => lon },
"vertex" => { "id" => vertex_id, "lat" => lat, "lon" => lon, "carrier" => "" }
})
end
Then(/^vertex "(\d+)" in the game "(.*)" should be dropped$/) do |vertex_id, lobby_name|
game_state = server.get_game_state_for_lobby(lobby_name)
expect(game_state["vertices"].any? { |vertex|
vertex["id"] == vertex_id and vertex["carrier"] == ""
}).to be(true)
end
Then(/^the game "(.*)" should not be finished$/) do |lobby_name|
game_state = server.get_game_state_for_lobby(lobby_name)
expect(game_state["is_finished"]).to eq(false)
end
When(/^the game "(.*)" is finished$/) do |lobby_name|
server.finish_game_for_lobby(lobby_name)
end
Then(/^the game "(.*)" should be finished$/) do |lobby_name|
game_state = server.get_game_state_for_lobby(lobby_name)
expect(game_state["is_finished"]).to eq(true)
end
When(/^the player "(.*)" has submitted his or statistics$/) do |player_name|
player_statistics = {
"distance" => 12,
"different_vertices_touched" => 121,
"total_vertices_touched" => 21
}
server.post_player_statistics_for_lobby(player_statistics, player_name)
end
Then(/^the game statistics of the game "(.*)" should contain the statistics of (\d+) player$/) do |lobby_name, size|
game_statistics = server.get_game_statistics_for_lobby(lobby_name)
expect(game_statistics.size).to be(size.to_i)
end
| mit |
frptools/collectable | packages/map/tests/getSize.ts | 655 | import test from 'ava';
import { empty, remove, set, size } from '../src';
test('returns 0 when the map empty', t => {
t.is(size(empty()), 0);
});
test('returns the correct size after adding entries', t => {
var map1 = set('x', 1, empty());
var map2 = set('x', 2, map1);
var map3 = set('y', 1, map1);
t.is(size(map1), 1);
t.is(size(map2), 1);
t.is(size(map3), 2);
});
test('returns the correct size after removing entries', t => {
var map = set('x', 1, empty());
map = set('y', 3, map);
map = set('z', 5, map);
t.is(size(map = remove('x', map)), 2);
t.is(size(map = remove('y', map)), 1);
t.is(size(remove('z', map)), 0);
});
| mit |
MiguelMendonca/project-template | api/src/routes/hello.js | 850 | var server = require('./../index.js')
var resources = require('./../resources')
server.route({
method: 'GET',
path: '/hello',
handler: resources.hello.get
})
server.route({
method: 'POST',
path: '/hello',
handler: resources.hello.post
})
server.route({
method:'POST',
path: '/login',
handler: resources.hello.login
})
server.route({
method:'POST',
path: '/reqs',
handler: resources.hello.reqs
})
server.route({
method:'POST',
path: '/pats',
handler: resources.hello.pats
})
server.route({
method:'POST',
path: '/selpat',
handler: resources.hello.selpat
})
server.route({
method:'GET',
path: '/acts',
handler: resources.hello.acts
})
server.route({
method:'POST',
path: '/reimburse',
handler: resources.hello.reimburse
})
server.route({
method:'POST',
path:'/updatereq',
handler: resources.hello.updatereq
}) | mit |
gubenkovalik/vgchat | resources/views/emails/confirmation.blade.php | 221 | <html>
<body>
<h3>Ссылка для подтверждения: <br/><a href="https://jencat.ml/confirmation/{{$token}}" target="_blank">https://jencat.ml/confirmation/{{$token}}</a></h3>
</body>
</html> | mit |
nicklandgrebe/caprese | spec/response_document_spec.rb | 34481 | require 'spec_helper'
describe 'Resource document structure', type: :request do
let!(:comments) { create_list :comment, 3 }
describe 'non-JSON url' do
before { get "/api/v1/static" }
it 'responds' do
expect(response.status).to eq(200)
end
it 'does not force a JSON resource document' do
expect { json }.to raise_error(JSON::ParserError)
end
end
describe 'Content-Type header' do
before { get '/api/v1/comments', params: {}, headers: { 'Content-Type' => content_type } }
context 'application/json' do
let(:content_type) { 'application/json' }
it 'accepts request' do
expect(response.status).to eq(200)
end
it 'responds with application/vnd.api+json' do
expect(response.headers['Content-Type']).to eq('application/vnd.api+json; charset=utf-8')
end
end
context 'application/vnd.api+json' do
let(:content_type) { 'application/vnd.api+json' }
it 'accepts request' do
expect(response.status).to eq(200)
end
it 'responds with application/vnd.api+json' do
expect(response.headers['Content-Type']).to eq('application/vnd.api+json; charset=utf-8')
end
end
end
describe 'type' do
before { get "/api/v1/#{resource.class.name.underscore.pluralize}/#{resource.id}" }
subject(:resource) { comments.first }
it 'uses the resource model name' do
expect(json['data']['type']).to eq('comments')
end
context 'when resource is serialized by parent resource model serializer' do
subject(:resource) { create :post, :with_attachments }
it 'uses the parent resource model name' do
expect(json['data']['relationships']['attachments']['data'][0]['type']).to eq('attachments')
end
end
end
describe 'meta' do
before do
API::V1::CommentsController.send :define_method, :add_meta_tag do
meta[:tag_1] = 100
meta[:tag_2] = 'tagged'
end
API::V1::CommentsController.before_query(:add_meta_tag)
end
after do
API::V1::CommentsController.instance_variable_set('@before_query_callbacks', [])
end
before { get '/api/v1/comments/' }
it 'adds meta tags to the response document' do
expect(json['meta']['tag_1']).to eq(100)
expect(json['meta']['tag_2']).to eq('tagged')
end
end
describe 'links' do
before { Rails.application.routes.default_url_options[:host] = 'http://www.example.com' }
before { get "/api/v1/#{resource_path}/#{resource.id}" }
subject(:resource) { comments.first }
let(:resource_path) { resource.class.name.underscore.pluralize }
it 'includes self link' do
expect(json['data']['links']['self']).to eq(Rails.application.routes.url_helpers.api_v1_comment_url(resource))
end
context 'when overriden self link' do
subject(:resource) { User.first }
it 'overrides self link' do
expect(json['data']['links']['self']).to eq('override')
end
end
context 'when overriden self link' do
subject(:resource) { User.first }
it 'overrides self link' do
expect(json['data']['links']['self']).to eq('override')
end
end
# TODO: Implement and spec only_path option
context 'when resource is serialized by parent resource model serializer' do
subject(:resource) { create :image }
let(:resource_path) { 'attachments' }
it 'uses the parent resource model link' do
expect(json['data']['links']['self']).to(
eq(Rails.application.routes.url_helpers.api_v1_attachment_url(resource))
)
end
end
end
describe 'relationships' do
context 'when scoping relationships' do
let(:post) { create :post }
let!(:comments) { create_list :comment, 2, post: post, user: post.user }
let!(:other_comments) { create_list :comment, 1, post: post, user: create(:user) }
before do
API::V1::PostSerializer.instance_eval do
define_method :relationship_scope do |name, scope|
case name
when :comments
scope.where(user: object.user)
else
scope
end
end
end
end
after do
API::V1::PostSerializer.instance_eval do
remove_method :relationship_scope
end
end
before { get "/api/v1/posts/#{post.id}?include=comments" }
it 'only includes scoped relationship items' do
expect(json['included'].count).to eq(2)
end
end
context 'when specifically serializing relationships' do
let(:post) { create :post }
let!(:comments) { create_list :comment, 2, post: post, user: post.user }
before do
API::V1::PostsController.instance_eval do
define_method :relationship_serializer do |name|
case name
when :comments
API::V1::SpecificCommentSerializer
end
end
end
end
after do
API::V1::PostsController.instance_eval do
remove_method :relationship_serializer
end
end
before { get "/api/v1/posts/#{post.id}/comments" }
it 'uses specific serializer' do
expect(json['data'][0]['attributes']['custom_attribute']).not_to be_nil
end
end
context 'when optimizing relationships' do
before { Caprese.config.optimize_relationships = true }
after { Caprese.config.optimize_relationships = false }
before { get "/api/v1/comments/#{comments.first.id}#{query_str}" }
context 'when association included' do
subject(:query_str) { '?include=post' }
it 'serializes the relationship data' do
expect(json['data']['relationships']['post']['data']).not_to be_nil
end
end
context 'when association not included' do
subject(:query_str) { '' }
it 'does not serialize the relationship' do
expect(json['data']['relationships'].try(:[], 'post')).to be_nil
end
end
context 'when deep nesting' do
subject(:post_params) { json['included'].detect { |r| r['type'] == 'posts' } }
context 'when association included' do
subject(:query_str) { '?include=post.user' }
it 'serializes the relationship data' do
expect(post_params['relationships']['user']['data']).not_to be_nil
end
it 'includes the relationship' do
expect(json['included'].detect { |r| r['type'] == 'users' }).not_to be_nil
end
end
context 'when association not included' do
subject(:query_str) { '?include=post' }
it 'does not serialize the relationship data' do
expect(post_params['relationships'].try(:[], 'user')).to be_nil
end
end
end
end
end
context 'when circular relationship' do
before { Caprese.config.optimize_relationships = true }
after { Caprese.config.optimize_relationships = false }
let!(:post) { create :post, :with_comments_and_replies, comment_count: 3 }
before { get "/api/v1/posts/#{post.id}#{query_str}" }
subject(:query_str) { '?include=comments.comment_reply.child,comments.user' }
it 'replaces includes with later includes' do
include = json['included'].select { |i| i['type'] == 'comments' }[1]
expect(include['relationships']['user']['data']).to be_present
include_2 = json['included'].detect { |i| i['type'] == 'users' && i['id'] == include['relationships']['user']['data']['id'] }
expect(include_2).to be_present
end
end
describe 'error source pointers' do
context 'nested relationship primary data' do
before do
API::V1::CommentsController.send :define_method, :add_error do |resource|
resource.errors.add('post.user.type')
end
API::V1::CommentsController.before_create(:add_error)
end
after do
API::V1::CommentsController.instance_variable_set('@before_create_callbacks', [])
end
before { post "/api/v1/#{type}/", params: { data: data } }
subject(:data) do
output = { type: type }
output.merge!(attributes: attributes)
output.merge!(relationships: relationships)
end
subject(:type) { 'comments' }
subject(:attributes) { { body: 'One body' } }
subject(:relationships) do
{
user: { data: { type: 'users', id: create(:user).id } },
post: { data: { type: 'posts', id: create(:post).id } }
}
end
it 'creates the correct pointer' do
expect(json['errors'][0]['source']['pointer']).to eq('/data/relationships/post/data/relationships/user/data/type')
end
end
end
describe 'aliasing' do
describe 'attribute mocking' do
before do
Comment.instance_eval do
define_method :caprese_is_attribute? do |name|
%w(not_attribute).include?(name.to_s)
end
end
API::V1::CommentsController.send :define_method, :add_error do |resource|
resource.errors.add(:not_attribute, :blank)
end
API::V1::CommentsController.before_create(:add_error)
end
after do
API::V1::CommentsController.instance_variable_set('@before_create_callbacks', [])
Comment.instance_eval do
remove_method :caprese_is_attribute?
end
end
before { post '/api/v1/comments', params: { data: { type: 'comments' } } }
it 'indicates that the alias is an attribute' do
expect(json['errors'][0]['source']['pointer']).to eq('/data/attributes/not_attribute')
end
end
describe 'aliasing an attribute' do
before do
Comment.instance_eval do
def caprese_field_aliases
{
content: :body
}
end
end
API::V1::CommentSerializer.instance_eval do
attributes :content
end
end
after do
Comment.instance_eval do
def caprese_field_aliases
{}
end
end
API::V1::CommentSerializer.instance_eval do
self._attributes_data = _attributes_data.except(:content)
end
end
describe 'get' do
before { get "/api/v1/comments#{query_str}" }
let(:query_str) { '' }
it 'aliases attribute' do
expect(json['data'][0]['attributes']['content']).not_to be_nil
end
context 'filtering' do
let(:filtered) { create :comment, body: '123456abc' }
let(:query_str) { "?filter[content]=#{filtered.body}" }
it 'filters by alias' do
expect(json['data'].count).to eq(1)
end
end
context 'select' do
let(:query_str) { '?fields[comments]=content' }
it 'selects the aliased field' do
expect(json['data'][0]['attributes']['content']).not_to be_nil
end
it 'does not select other fields' do
expect(json['data'][0]['attributes']['created_at']).to be_nil
end
end
context 'sort' do
let(:query_str) { '?sort=-content' }
it 'sorts by the aliased field' do
expect(json['data'].map { |c| c['id'].to_i }).to match(Comment.order(body: :desc).ids)
end
end
end
describe 'post' do
before { post '/api/v1/comments', params: { data: data } }
let(:content) { 'mah awesome body' }
let(:data) do
{
type: 'comments',
attributes: {
content: content
},
relationships: {
post: {
data: { type: 'posts', id: comments.first.post.id.to_s }
},
user: {
data: { type: 'users', id: comments.first.user.id.to_s }
}
}
}
end
it 'converts aliased attribute' do
expect(Comment.last.body).to eq(content)
end
end
describe 'patch' do
before { patch "/api/v1/comments/#{existing_resource.id}", params: { data: data } }
let(:existing_resource) { create :comment }
let(:content) { 'mah awesome body!' }
let(:data) do
{
type: 'comments',
id: existing_resource.id.to_s,
attributes: {
content: content
}
}
end
before { existing_resource.reload }
it 'converts aliased attribute' do
expect(existing_resource.body).to eq(content)
end
end
end
describe 'aliasing a relationship' do
before do
Comment.instance_eval do
def caprese_field_aliases
{
article: :post
}
end
end
API::V1::CommentSerializer.instance_eval do
belongs_to :article
end
end
after do
Comment.instance_eval do
def caprese_field_aliases
{}
end
end
API::V1::CommentSerializer.instance_eval do
self._reflections = _reflections.except(:article)
end
end
describe 'get' do
before { Rails.application.routes.default_url_options[:host] = 'http://www.example.com' }
before { get "/api/v1/comments#{query_str}" }
let(:query_str) { '' }
it 'aliases relationship' do
expect(json['data'][0]['relationships']['article']).not_to be_nil
end
it 'aliases relationship links' do
expect(json['data'][0]['relationships']['article']['links']['self']).to eq(
Rails.application.routes.url_helpers.relationship_definition_api_v1_comment_url(
comments.first,
relationship: 'article'
)
)
end
context 'include' do
let(:query_str) { '?include=article' }
it 'includes aliased relationship' do
expect(json['included'].map { |t| t['type'] }).to include('posts')
end
end
end
describe 'post' do
before { post '/api/v1/comments', params: { data: data } }
let(:article) { create :post }
let(:data) do
{
type: 'comments',
attributes: {
body: 'My body'
},
relationships: {
article: {
data: { type: 'posts', id: article.id.to_s }
},
user: {
data: { type: 'users', id: comments.first.user.id.to_s }
}
}
}
end
it 'converts aliased relationship' do
expect(Comment.last.post).to eq(article)
end
end
describe 'patch' do
before { patch "/api/v1/comments/#{existing_resource.id}", params: { data: data } }
let(:existing_resource) { create :comment }
let(:article) { create :post }
let(:data) do
{
type: 'comments',
id: existing_resource.id.to_s,
relationships: {
article: {
data: { type: 'posts', id: article.id.to_s }
}
}
}
end
before { existing_resource.reload }
it 'converts aliased relationship' do
expect(existing_resource.post).to eq(article)
end
end
describe 'relationship endpoints' do
let(:comment) { comments.first }
describe 'get data' do
before { get "/api/v1/comments/#{comment.id}/article" }
it 'responds with aliased relationship data' do
expect(json['data']['type']).to eq('posts')
end
end
describe 'get definition' do
before { get "/api/v1/comments/#{comment.id}/relationships/article" }
it 'responds with aliased relationship data' do
expect(json['data']['type']).to eq('posts')
end
end
describe 'update definition' do
before { patch "/api/v1/comments/#{comment.id}/relationships/article", params: { data: data } }
let(:data) do
[
{
type: 'posts', id: my_post.id.to_s
}
]
end
let(:other_comment) { Comment.where.not(id: comment.id).first }
let(:my_post) { other_comment.post }
before { comment.reload && other_comment.reload }
it 'persists the aliased type resource relationship' do
expect(comment.post).to eq(my_post)
end
end
end
end
describe 'aliasing an attribute of an unaliased relationship' do
before do
Post.instance_eval do
def caprese_field_aliases
{
name: :title
}
end
end
API::V1::PostSerializer.instance_eval do
attributes :name
end
end
after do
Post.instance_eval do
def caprese_field_aliases
{}
end
end
API::V1::PostSerializer.instance_eval do
self._attributes_data = _attributes_data.except(:name)
end
end
describe 'get' do
before { get "/api/v1/comments#{query_str}" }
let(:query_str) { '?include=post' }
it 'aliases attribute' do
expect(json['included'][0]['attributes']['name']).not_to be_nil
end
context 'select' do
let(:query_str) { '?include=post&fields[posts]=name' }
it 'selects the aliased field' do
expect(json['included'][0]['attributes']['name']).not_to be_nil
end
it 'does not select other fields' do
expect(json['included'][0]['attributes']['created_at']).to be_nil
end
end
end
describe 'post' do
before { post '/api/v1/comments', params: { data: data } }
let(:name) { 'A valid name' }
let(:data) do
{
type: 'comments',
attributes: {
body: 'A body'
},
relationships: {
post: {
data: {
type: 'posts',
attributes: {
name: name
},
relationships: {
user: {
data: {
type: 'users',
id: create(:user).id.to_s
}
}
}
}
},
user: {
data: {
type: 'users',
id: create(:user).id.to_s
}
}
}
}
end
it 'aliases attribute' do
expect(Comment.last.post.title).to eq(name)
end
context 'when attribute invalid' do
let(:name) { '' }
it 'responds with error source pointer to aliased relationship aliased attribute' do
expect(json['errors'][0]['source']['pointer']).to eq('/data/relationships/post/data/attributes/name')
end
end
end
describe 'patch' do
before { patch "/api/v1/comments/#{existing_resource.id}", params: { data: data } }
let(:existing_resource) { create :comment }
let(:name) { 'A valid name' }
let(:data) do
{
type: 'comments',
id: existing_resource.id.to_s,
relationships: {
post: {
data: {
type: 'posts',
id: existing_resource.post.id.to_s,
attributes: {
name: name
}
}
}
}
}
end
before { existing_resource.reload }
it 'aliases attribute' do
expect(existing_resource.post.title).to eq(name)
end
context 'when attribute invalid' do
let(:name) { '' }
it 'responds with error source pointer to aliased relationship aliased attribute' do
expect(json['errors'][0]['source']['pointer']).to eq('/data/relationships/post/data/attributes/name')
end
end
end
end
describe 'aliasing an attribute of an aliased relationship' do
before do
Comment.instance_eval do
def caprese_field_aliases
{
article: :post
}
end
end
Post.instance_eval do
def caprese_field_aliases
{
name: :title
}
end
def caprese_type
:article
end
end
API::V1::CommentSerializer.instance_eval do
belongs_to :article
end
API::V1::ArticleSerializer.instance_eval do
attributes :name
end
API::V1::ApplicationController.class_eval do
def resource_type_aliases
{
articles: :posts
}
end
end
end
after do
Comment.instance_eval do
def caprese_field_aliases
{}
end
end
Post.instance_eval do
def caprese_field_aliases
{}
end
def caprese_type
:post
end
end
API::V1::CommentSerializer.instance_eval do
self._reflections = _reflections.except(:article)
end
API::V1::ArticleSerializer.instance_eval do
self._attributes_data = _attributes_data.except(:name)
end
API::V1::ApplicationController.class_eval do
def resource_type_aliases
{}
end
end
end
describe 'get' do
before { get "/api/v1/comments#{query_str}" }
let(:query_str) { '?include=article' }
it 'aliases attribute' do
expect(json['included'][0]['attributes']['name']).not_to be_nil
end
context 'select' do
let(:query_str) { '?include=article&fields[articles]=name' }
it 'selects the aliased field' do
expect(json['included'][0]['attributes']['name']).not_to be_nil
end
it 'does not select other fields' do
expect(json['included'][0]['attributes']['created_at']).to be_nil
end
end
end
describe 'post' do
before { post '/api/v1/comments', params: { data: data } }
let(:name) { 'A valid name' }
let(:data) do
{
type: 'comments',
attributes: {
body: 'A body'
},
relationships: {
article: {
data: {
type: 'articles',
attributes: {
name: name
},
relationships: {
user: {
data: {
type: 'users',
id: create(:user).id.to_s
}
}
}
}
},
user: {
data: {
type: 'users',
id: create(:user).id.to_s
}
}
}
}
end
it 'aliases attribute' do
expect(Comment.last.post.title).to eq(name)
end
context 'when attribute invalid' do
let(:name) { '' }
it 'responds with error source pointer to aliased relationship aliased attribute' do
expect(json['errors'][0]['source']['pointer']).to eq('/data/relationships/article/data/attributes/name')
end
end
end
describe 'patch' do
before { patch "/api/v1/comments/#{existing_resource.id}", params: { data: data } }
let(:existing_resource) { create :comment }
let(:name) { 'A valid name' }
let(:data) do
{
type: 'comments',
id: existing_resource.id.to_s,
relationships: {
article: {
data: {
type: 'articles',
id: existing_resource.post.id.to_s,
attributes: {
name: name
}
}
}
}
}
end
before { existing_resource.reload }
it 'aliases attribute' do
expect(existing_resource.post.title).to eq(name)
end
context 'when attribute invalid' do
let(:name) { '' }
it 'responds with error source pointer to aliased relationship aliased attribute' do
expect(json['errors'][0]['source']['pointer']).to eq('/data/relationships/article/data/attributes/name')
end
end
end
end
describe 'aliasing a relationship of an aliased relationship' do
before do
Comment.instance_eval do
def caprese_field_aliases
{
article: :post
}
end
end
Post.instance_eval do
def caprese_field_aliases
{
submitter: :user
}
end
def caprese_type
:article
end
end
API::V1::CommentSerializer.instance_eval do
belongs_to :article
end
API::V1::ArticleSerializer.instance_eval do
belongs_to :submitter
end
API::V1::ApplicationController.class_eval do
def resource_type_aliases
{
articles: :posts,
submitters: :users
}
end
def record_scope(type)
case type
when :submitters
User.all
else
super
end
end
end
end
after do
Comment.instance_eval do
def caprese_field_aliases
{}
end
end
Post.instance_eval do
def caprese_field_aliases
{}
end
end
API::V1::CommentSerializer.instance_eval do
self._reflections = _reflections.except(:article)
end
API::V1::ArticleSerializer.instance_eval do
self._reflections = _reflections.except(:submitter)
end
API::V1::ApplicationController.class_eval do
def resource_type_aliases
{}
end
end
end
describe 'get' do
before { get "/api/v1/comments#{query_str}" }
let(:query_str) { '?include=article.submitter' }
it 'aliases relationship' do
expect(json['included'][0]['relationships']['submitter']).not_to be_nil
end
context 'select' do
let(:query_str) { '?include=article.submitter&fields[submitters]=name' }
let(:include) { json['included'].detect { |i| i['type'] == 'submitters' } }
it 'selects the aliased field' do
expect(include['attributes']['name']).not_to be_nil
end
it 'does not select other fields' do
expect(include['attributes']['created_at']).to be_nil
end
end
end
describe 'post' do
before { post '/api/v1/comments', params: { data: data } }
let(:submitter_id) { create(:user).id.to_s }
let(:data) do
{
type: 'comments',
attributes: {
body: 'A body'
},
relationships: {
article: {
data: {
type: 'articles',
attributes: {
title: 'name'
},
relationships: {
submitter: {
data: {
type: 'submitters',
id: submitter_id
}
}
}
}
},
user: {
data: {
type: 'users',
id: create(:user).id.to_s
}
}
}
}
end
it 'aliases relationship' do
expect(Comment.last.post.user.id.to_s).to eq(submitter_id)
end
context 'when relationship invalid' do
let(:submitter_id) { 'a' }
it 'responds with error source pointer to aliased relationship aliased relationship' do
expect(json['errors'][0]['source']['pointer']).to eq('/data/relationships/article/data/relationships/submitter/data')
end
end
end
describe 'patch' do
before { patch "/api/v1/comments/#{existing_resource.id}", params: { data: data } }
let(:existing_resource) { create :comment }
let(:submitter_id) { create(:user).id.to_s }
let(:data) do
{
type: 'comments',
id: existing_resource.id.to_s,
relationships: {
article: {
data: {
type: 'articles',
id: existing_resource.post.id.to_s,
relationships: {
submitter: {
data: {
type: 'submitters',
id: submitter_id
}
}
}
}
}
}
}
end
before { existing_resource.reload }
it 'aliases relationship' do
expect(existing_resource.post.user.id.to_s).to eq(submitter_id)
end
context 'when relationship invalid' do
let(:submitter_id) { 'a' }
it 'responds with error source pointer to aliased relationship aliased relationship' do
expect(json['errors'][0]['source']['pointer']).to eq('/data/relationships/article/data/relationships/submitter/data')
end
end
end
end
describe 'aliasing a type' do
before do
Comment.instance_eval do
def caprese_type
:review
end
end
API::V1::ApplicationController.class_eval do
def resource_type_aliases
{
reviews: :comments
}
end
end
end
after do
Comment.instance_eval do
def caprese_type
:comment
end
end
API::V1::ApplicationController.class_eval do
def resource_type_aliases
{}
end
end
end
describe 'get' do
before { get "/api/v1/comments#{query_str}" }
let(:query_str) { '' }
it 'aliases relationship' do
expect(json['data'][0]['type']).to eq('reviews')
end
context 'select' do
let(:query_str) { '?fields[reviews]=body' }
it 'selects the fields' do
expect(json['data'][0]['attributes']['body']).not_to be_nil
end
it 'does not select the other fields' do
expect(json['data'][0]['attributes']['created_at']).to be_nil
end
end
end
describe 'post' do
before { post "/api/v1/#{type}", params: { data: data } }
let(:type) { 'comments' }
let(:data) do
{
type: 'reviews',
attributes: {
body: 'abcdef123456'
},
relationships: {
post: {
data: { type: 'posts', id: Post.last.id.to_s }
},
user: {
data: { type: 'users', id: comments.first.user.id.to_s }
}
}
}
end
it 'persists the aliased typed resource' do
expect(Comment.last.body).to eq('abcdef123456')
end
context 'as relationship' do
let(:type) { 'posts' }
let(:comment) { create :comment }
let(:data) do
{
type: 'posts',
attributes: {
title: 'a title'
},
relationships: {
comments: {
data: [{ type: 'reviews', id: comment.id.to_s }]
},
user: {
data: { type: 'users', id: comments.first.user.id.to_s }
}
}
}
end
it 'persists the aliased typed relationship resource' do
expect(Post.last.comments.first).to eq(comment)
end
end
end
describe 'relationship endpoints' do
let(:my_post) { comments.first.post }
describe 'get data' do
before { get "/api/v1/posts/#{my_post.id}/comments" }
it 'aliases relationship resource type' do
expect(json['data'].select { |c| c['type'] == 'reviews' }.count).to eq(my_post.comments.size)
end
end
describe 'get definition' do
before { get "/api/v1/posts/#{my_post.id}/relationships/comments" }
it 'aliases relationship resource type' do
expect(json['data'].select { |c| c['type'] == 'reviews' }.count).to eq(my_post.comments.size)
end
end
describe 'update definition' do
before { patch "/api/v1/posts/#{my_post.id}/relationships/comments", params: { data: data } }
let(:data) do
[
{
type: 'reviews', id: comment.id.to_s
}
]
end
let(:other_post) { Post.where.not(id: my_post.id).first }
let(:comment) { other_post.comments.create(body: 'done', user: Post.first.user) }
before { my_post.reload && other_post.reload }
it 'persists the aliased type resource relationship' do
expect(my_post.comments.first).to eq(comment)
end
end
end
describe 'included' do
before { get "/api/v1/posts?include=comments" }
it 'includes the aliased type resources' do
expect(json['included'].select { |c| c['type'] == 'reviews' }.count).to eq(Comment.count)
end
end
end
end
end
| mit |
Azure/azure-sdk-for-ruby | management/azure_mgmt_web/lib/2016-03-01/generated/azure_mgmt_web/models/recommendation_rule.rb | 7448 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Web::Mgmt::V2016_03_01
module Models
#
# Represents a recommendation rule that the recommendation engine can
# perform.
#
class RecommendationRule < ProxyOnlyResource
include MsRestAzure
# @return [String] Unique name of the rule.
attr_accessor :recommendation_rule_name
# @return [String] UI friendly name of the rule.
attr_accessor :display_name
# @return [String] Localized name of the rule (Good for UI).
attr_accessor :message
# @return Recommendation ID of an associated recommendation object tied
# to the rule, if exists.
# If such an object doesn't exist, it is set to null.
attr_accessor :recommendation_id
# @return [String] Localized detailed description of the rule.
attr_accessor :description
# @return [String] Name of action that is recommended by this rule in
# string.
attr_accessor :action_name
# @return [NotificationLevel] Level of impact indicating how critical
# this rule is. Possible values include: 'Critical', 'Warning',
# 'Information', 'NonUrgentSuggestion'
attr_accessor :level
# @return [Channels] List of available channels that this rule applies.
# Possible values include: 'Notification', 'Api', 'Email', 'Webhook',
# 'All'
attr_accessor :channels
# @return [Array<String>] An array of category tags that the rule
# contains.
attr_accessor :tags
# @return [Boolean] True if this is associated with a dynamically added
# rule
attr_accessor :is_dynamic
# @return [String] Extension name of the portal if exists. Applicable to
# dynamic rule only.
attr_accessor :extension_name
# @return [String] Deep link to a blade on the portal. Applicable to
# dynamic rule only.
attr_accessor :blade_name
# @return [String] Forward link to an external document associated with
# the rule. Applicable to dynamic rule only.
attr_accessor :forward_link
#
# Mapper for RecommendationRule class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'RecommendationRule',
type: {
name: 'Composite',
class_name: 'RecommendationRule',
model_properties: {
id: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'id',
type: {
name: 'String'
}
},
name: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'name',
type: {
name: 'String'
}
},
kind: {
client_side_validation: true,
required: false,
serialized_name: 'kind',
type: {
name: 'String'
}
},
type: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'type',
type: {
name: 'String'
}
},
recommendation_rule_name: {
client_side_validation: true,
required: false,
serialized_name: 'properties.name',
type: {
name: 'String'
}
},
display_name: {
client_side_validation: true,
required: false,
serialized_name: 'properties.displayName',
type: {
name: 'String'
}
},
message: {
client_side_validation: true,
required: false,
serialized_name: 'properties.message',
type: {
name: 'String'
}
},
recommendation_id: {
client_side_validation: true,
required: false,
serialized_name: 'properties.recommendationId',
type: {
name: 'String'
}
},
description: {
client_side_validation: true,
required: false,
serialized_name: 'properties.description',
type: {
name: 'String'
}
},
action_name: {
client_side_validation: true,
required: false,
serialized_name: 'properties.actionName',
type: {
name: 'String'
}
},
level: {
client_side_validation: true,
required: false,
serialized_name: 'properties.level',
type: {
name: 'Enum',
module: 'NotificationLevel'
}
},
channels: {
client_side_validation: true,
required: false,
serialized_name: 'properties.channels',
type: {
name: 'Enum',
module: 'Channels'
}
},
tags: {
client_side_validation: true,
required: false,
serialized_name: 'properties.tags',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
},
is_dynamic: {
client_side_validation: true,
required: false,
serialized_name: 'properties.isDynamic',
type: {
name: 'Boolean'
}
},
extension_name: {
client_side_validation: true,
required: false,
serialized_name: 'properties.extensionName',
type: {
name: 'String'
}
},
blade_name: {
client_side_validation: true,
required: false,
serialized_name: 'properties.bladeName',
type: {
name: 'String'
}
},
forward_link: {
client_side_validation: true,
required: false,
serialized_name: 'properties.forwardLink',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| mit |
Icenium/SignalR | SignalR.ServiceBus/IOThreadTimer.cs | 20521 | namespace SignalR.ServiceBus
{
using System;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
using Microsoft.Win32.SafeHandles;
class IOThreadTimer
{
const int maxSkewInMillisecondsDefault = 100;
static long systemTimeResolutionTicks = -1;
Action<object> callback;
object callbackState;
long dueTime;
int index;
long maxSkew;
TimerGroup timerGroup;
public IOThreadTimer(Action<object> callback, object callbackState, bool isTypicallyCanceledShortlyAfterBeingSet)
: this(callback, callbackState, isTypicallyCanceledShortlyAfterBeingSet, maxSkewInMillisecondsDefault)
{
}
public IOThreadTimer(Action<object> callback, object callbackState, bool isTypicallyCanceledShortlyAfterBeingSet, int maxSkewInMilliseconds)
{
this.callback = callback;
this.callbackState = callbackState;
this.maxSkew = Ticks.FromMilliseconds(maxSkewInMilliseconds);
this.timerGroup =
(isTypicallyCanceledShortlyAfterBeingSet ? TimerManager.Value.VolatileTimerGroup : TimerManager.Value.StableTimerGroup);
}
public static long SystemTimeResolutionTicks
{
get
{
if (IOThreadTimer.systemTimeResolutionTicks == -1)
{
IOThreadTimer.systemTimeResolutionTicks = GetSystemTimeResolution();
}
return IOThreadTimer.systemTimeResolutionTicks;
}
}
static long GetSystemTimeResolution()
{
int dummyAdjustment;
uint increment;
uint dummyAdjustmentDisabled;
if (UnsafeNativeMethods.GetSystemTimeAdjustment(out dummyAdjustment, out increment, out dummyAdjustmentDisabled) != 0)
{
return increment;
}
// Assume the default, which is around 15 milliseconds.
return 15 * TimeSpan.TicksPerMillisecond;
}
public bool Cancel()
{
return TimerManager.Value.Cancel(this);
}
public void Set(TimeSpan timeFromNow)
{
if (timeFromNow == TimeSpan.MaxValue)
{
throw new ArgumentException("IOThreadTimer cannot accept Timespan.MaxValue.", "timeFromNow");
}
SetAt(Ticks.Add(Ticks.Now, Ticks.FromTimeSpan(timeFromNow)));
}
public void Set(int millisecondsFromNow)
{
SetAt(Ticks.Add(Ticks.Now, Ticks.FromMilliseconds(millisecondsFromNow)));
}
public void SetAt(long newDueTime)
{
if (newDueTime >= TimeSpan.MaxValue.Ticks || newDueTime < 0)
{
string errorMessage = string.Format(
CultureInfo.CurrentCulture,
"The value supplied must be between {0} and {1}.",
0,
TimeSpan.MaxValue.Ticks - 1);
throw new ArgumentOutOfRangeException("newDueTime", newDueTime, errorMessage);
}
TimerManager.Value.Set(this, newDueTime);
}
class TimerManager : IDisposable
{
const long maxTimeToWaitForMoreTimers = 1000 * TimeSpan.TicksPerMillisecond;
static TimerManager value = new TimerManager();
Action<object> onWaitCallback;
TimerGroup stableTimerGroup;
TimerGroup volatileTimerGroup;
WaitableTimer[] waitableTimers;
bool waitScheduled;
public TimerManager()
{
this.onWaitCallback = new Action<object>(OnWaitCallback);
this.stableTimerGroup = new TimerGroup();
this.volatileTimerGroup = new TimerGroup();
this.waitableTimers = new WaitableTimer[] { this.stableTimerGroup.WaitableTimer, this.volatileTimerGroup.WaitableTimer };
}
object ThisLock
{
get { return this; }
}
public static TimerManager Value
{
get
{
return TimerManager.value;
}
}
public TimerGroup StableTimerGroup
{
get
{
return this.stableTimerGroup;
}
}
public TimerGroup VolatileTimerGroup
{
get
{
return this.volatileTimerGroup;
}
}
public void Set(IOThreadTimer timer, long dueTime)
{
long timeDiff = dueTime - timer.dueTime;
if (timeDiff < 0)
{
timeDiff = -timeDiff;
}
if (timeDiff > timer.maxSkew)
{
lock (ThisLock)
{
TimerGroup timerGroup = timer.timerGroup;
TimerQueue timerQueue = timerGroup.TimerQueue;
if (timer.index > 0)
{
if (timerQueue.UpdateTimer(timer, dueTime))
{
UpdateWaitableTimer(timerGroup);
}
}
else
{
if (timerQueue.InsertTimer(timer, dueTime))
{
UpdateWaitableTimer(timerGroup);
if (timerQueue.Count == 1)
{
EnsureWaitScheduled();
}
}
}
}
}
}
public bool Cancel(IOThreadTimer timer)
{
lock (ThisLock)
{
if (timer.index > 0)
{
TimerGroup timerGroup = timer.timerGroup;
TimerQueue timerQueue = timerGroup.TimerQueue;
timerQueue.DeleteTimer(timer);
if (timerQueue.Count > 0)
{
UpdateWaitableTimer(timerGroup);
}
else
{
TimerGroup otherTimerGroup = GetOtherTimerGroup(timerGroup);
if (otherTimerGroup.TimerQueue.Count == 0)
{
long now = Ticks.Now;
long thisGroupRemainingTime = timerGroup.WaitableTimer.DueTime - now;
long otherGroupRemainingTime = otherTimerGroup.WaitableTimer.DueTime - now;
if (thisGroupRemainingTime > maxTimeToWaitForMoreTimers &&
otherGroupRemainingTime > maxTimeToWaitForMoreTimers)
{
timerGroup.WaitableTimer.Set(Ticks.Add(now, maxTimeToWaitForMoreTimers));
}
}
}
return true;
}
else
{
return false;
}
}
}
void EnsureWaitScheduled()
{
if (!this.waitScheduled)
{
ScheduleWait();
}
}
TimerGroup GetOtherTimerGroup(TimerGroup timerGroup)
{
if (object.ReferenceEquals(timerGroup, this.volatileTimerGroup))
{
return this.stableTimerGroup;
}
else
{
return this.volatileTimerGroup;
}
}
void OnWaitCallback(object state)
{
WaitHandle.WaitAny(this.waitableTimers);
long now = Ticks.Now;
lock (ThisLock)
{
this.waitScheduled = false;
ScheduleElapsedTimers(now);
ReactivateWaitableTimers();
ScheduleWaitIfAnyTimersLeft();
}
}
void ReactivateWaitableTimers()
{
ReactivateWaitableTimer(this.stableTimerGroup);
ReactivateWaitableTimer(this.volatileTimerGroup);
}
static void ReactivateWaitableTimer(TimerGroup timerGroup)
{
TimerQueue timerQueue = timerGroup.TimerQueue;
if (timerQueue.Count > 0)
{
timerGroup.WaitableTimer.Set(timerQueue.MinTimer.dueTime);
}
else
{
timerGroup.WaitableTimer.Set(long.MaxValue);
}
}
void ScheduleElapsedTimers(long now)
{
ScheduleElapsedTimers(this.stableTimerGroup, now);
ScheduleElapsedTimers(this.volatileTimerGroup, now);
}
static void ScheduleElapsedTimers(TimerGroup timerGroup, long now)
{
TimerQueue timerQueue = timerGroup.TimerQueue;
while (timerQueue.Count > 0)
{
IOThreadTimer timer = timerQueue.MinTimer;
long timeDiff = timer.dueTime - now;
if (timeDiff <= timer.maxSkew)
{
timerQueue.DeleteMinTimer();
IOThreadScheduler.ScheduleCallbackNoFlow(timer.callback, timer.callbackState);
}
else
{
break;
}
}
}
void ScheduleWait()
{
IOThreadScheduler.ScheduleCallbackNoFlow(this.onWaitCallback, null);
this.waitScheduled = true;
}
void ScheduleWaitIfAnyTimersLeft()
{
if (this.stableTimerGroup.TimerQueue.Count > 0 ||
this.volatileTimerGroup.TimerQueue.Count > 0)
{
ScheduleWait();
}
}
static void UpdateWaitableTimer(TimerGroup timerGroup)
{
WaitableTimer waitableTimer = timerGroup.WaitableTimer;
IOThreadTimer minTimer = timerGroup.TimerQueue.MinTimer;
long timeDiff = waitableTimer.DueTime - minTimer.dueTime;
if (timeDiff < 0)
{
timeDiff = -timeDiff;
}
if (timeDiff > minTimer.maxSkew)
{
waitableTimer.Set(minTimer.dueTime);
}
}
public void Dispose()
{
this.stableTimerGroup.Dispose();
this.volatileTimerGroup.Dispose();
GC.SuppressFinalize(this);
}
}
class TimerGroup : IDisposable
{
TimerQueue timerQueue;
WaitableTimer waitableTimer;
public TimerGroup()
{
this.waitableTimer = new WaitableTimer();
this.waitableTimer.Set(long.MaxValue);
this.timerQueue = new TimerQueue();
}
public TimerQueue TimerQueue
{
get
{
return this.timerQueue;
}
}
public WaitableTimer WaitableTimer
{
get
{
return this.waitableTimer;
}
}
public void Dispose()
{
this.waitableTimer.Dispose();
GC.SuppressFinalize(this);
}
}
class TimerQueue
{
int count;
IOThreadTimer[] timers;
public TimerQueue()
{
this.timers = new IOThreadTimer[4];
}
public int Count
{
get { return count; }
}
public IOThreadTimer MinTimer
{
get
{
return timers[1];
}
}
public void DeleteMinTimer()
{
IOThreadTimer minTimer = this.MinTimer;
DeleteMinTimerCore();
minTimer.index = 0;
minTimer.dueTime = 0;
}
public void DeleteTimer(IOThreadTimer timer)
{
int index = timer.index;
IOThreadTimer[] tempTimers = this.timers;
for (; ; )
{
int parentIndex = index / 2;
if (parentIndex >= 1)
{
IOThreadTimer parentTimer = tempTimers[parentIndex];
tempTimers[index] = parentTimer;
parentTimer.index = index;
}
else
{
break;
}
index = parentIndex;
}
timer.index = 0;
timer.dueTime = 0;
tempTimers[1] = null;
DeleteMinTimerCore();
}
public bool InsertTimer(IOThreadTimer timer, long dueTime)
{
IOThreadTimer[] tempTimers = this.timers;
int index = this.count + 1;
if (index == tempTimers.Length)
{
tempTimers = new IOThreadTimer[tempTimers.Length * 2];
Array.Copy(this.timers, tempTimers, this.timers.Length);
this.timers = tempTimers;
}
this.count = index;
if (index > 1)
{
for (; ; )
{
int parentIndex = index / 2;
if (parentIndex == 0)
{
break;
}
IOThreadTimer parent = tempTimers[parentIndex];
if (parent.dueTime > dueTime)
{
tempTimers[index] = parent;
parent.index = index;
index = parentIndex;
}
else
{
break;
}
}
}
tempTimers[index] = timer;
timer.index = index;
timer.dueTime = dueTime;
return index == 1;
}
public bool UpdateTimer(IOThreadTimer timer, long newDueTime)
{
int index = timer.index;
IOThreadTimer[] tempTimers = this.timers;
int tempCount = this.count;
int parentIndex = index / 2;
if (parentIndex == 0 ||
tempTimers[parentIndex].dueTime <= newDueTime)
{
int leftChildIndex = index * 2;
if (leftChildIndex > tempCount ||
tempTimers[leftChildIndex].dueTime >= newDueTime)
{
int rightChildIndex = leftChildIndex + 1;
if (rightChildIndex > tempCount ||
tempTimers[rightChildIndex].dueTime >= newDueTime)
{
timer.dueTime = newDueTime;
return index == 1;
}
}
}
DeleteTimer(timer);
InsertTimer(timer, newDueTime);
return true;
}
void DeleteMinTimerCore()
{
int currentCount = this.count;
if (currentCount == 1)
{
this.count = 0;
this.timers[1] = null;
}
else
{
IOThreadTimer[] tempTimers = this.timers;
IOThreadTimer lastTimer = tempTimers[currentCount];
this.count = --currentCount;
int index = 1;
for (; ; )
{
int leftChildIndex = index * 2;
if (leftChildIndex > currentCount)
{
break;
}
int childIndex;
IOThreadTimer child;
if (leftChildIndex < currentCount)
{
IOThreadTimer leftChild = tempTimers[leftChildIndex];
int rightChildIndex = leftChildIndex + 1;
IOThreadTimer rightChild = tempTimers[rightChildIndex];
if (rightChild.dueTime < leftChild.dueTime)
{
child = rightChild;
childIndex = rightChildIndex;
}
else
{
child = leftChild;
childIndex = leftChildIndex;
}
}
else
{
childIndex = leftChildIndex;
child = tempTimers[childIndex];
}
if (lastTimer.dueTime > child.dueTime)
{
tempTimers[index] = child;
child.index = index;
}
else
{
break;
}
index = childIndex;
if (leftChildIndex >= currentCount)
{
break;
}
}
tempTimers[index] = lastTimer;
lastTimer.index = index;
tempTimers[currentCount + 1] = null;
}
}
}
class WaitableTimer : WaitHandle
{
long dueTime;
public WaitableTimer()
{
this.SafeWaitHandle = TimerHelper.CreateWaitableTimer();
}
public long DueTime
{
get { return this.dueTime; }
}
public void Set(long newDueTime)
{
this.dueTime = TimerHelper.Set(this.SafeWaitHandle, newDueTime);
}
static class TimerHelper
{
public static SafeWaitHandle CreateWaitableTimer()
{
SafeWaitHandle handle = UnsafeNativeMethods.CreateWaitableTimer(IntPtr.Zero, false, null);
if (handle.IsInvalid)
{
Exception exception = new Win32Exception();
handle.SetHandleAsInvalid();
throw exception;
}
return handle;
}
public static long Set(SafeWaitHandle timer, long dueTime)
{
if (!UnsafeNativeMethods.SetWaitableTimer(timer, ref dueTime, 0, IntPtr.Zero, IntPtr.Zero, false))
{
throw new Win32Exception();
}
return dueTime;
}
}
}
}
}
| mit |
rsdebest/pingtool | public/modules/checks/controllers/checks.client.controller.js | 1149 | 'use strict';
angular.module('checks').controller('ChecksController', ['$scope', '$http', 'Socket', '$location',
function($scope, $http, Socket, $location) {
this.init = function(){
$scope.checks = [];
$scope.totalChecks = $scope.checks.length;
// Refactor to a service...
this.fetchChecks();
if($location.search().filter){
$scope.checksFilter = $location.search().filter;
}
};
this.fetchChecks = function(){
$http.get('/api')
.success(function(data, status, headers, config) {
$scope.lastUpdatedAt(data.lastUpdate);
$scope.checks = data.checks;
})
.error(function(data, status, headers, config) {
console.error('Error! Something went wrong');
console.error(data);
});
};
$scope.saveFilterUrl = function(){
$location.search('filter', $scope.checksFilter);
};
Socket.on('checks.updated', function(data) {
$scope.checks = data.checks;
$scope.lastUpdatedAt(data.lastUpdate);
console.log('>>> Updated the checks');
console.log(data.checks);
});
$scope.lastUpdatedAt = function(timestamp){
$scope.time = timestamp;
}
this.init();
}
]); | mit |
cschwarz/AppShell | src/AppShell.NativeMaps.Mobile.Android/Resources/Resource.Designer.cs | 237152 | #pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: global::Android.Runtime.ResourceDesignerAttribute("AppShell.NativeMaps.Mobile.Android.Resource", IsApplication=false)]
namespace AppShell.NativeMaps.Mobile.Android
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")]
public partial class Resource
{
static Resource()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
public partial class Animation
{
// aapt resource value: 0x7f040000
public static int abc_fade_in = 2130968576;
// aapt resource value: 0x7f040001
public static int abc_fade_out = 2130968577;
// aapt resource value: 0x7f040002
public static int abc_grow_fade_in_from_bottom = 2130968578;
// aapt resource value: 0x7f040003
public static int abc_popup_enter = 2130968579;
// aapt resource value: 0x7f040004
public static int abc_popup_exit = 2130968580;
// aapt resource value: 0x7f040005
public static int abc_shrink_fade_out_from_bottom = 2130968581;
// aapt resource value: 0x7f040006
public static int abc_slide_in_bottom = 2130968582;
// aapt resource value: 0x7f040007
public static int abc_slide_in_top = 2130968583;
// aapt resource value: 0x7f040008
public static int abc_slide_out_bottom = 2130968584;
// aapt resource value: 0x7f040009
public static int abc_slide_out_top = 2130968585;
// aapt resource value: 0x7f04000a
public static int design_bottom_sheet_slide_in = 2130968586;
// aapt resource value: 0x7f04000b
public static int design_bottom_sheet_slide_out = 2130968587;
// aapt resource value: 0x7f04000c
public static int design_fab_in = 2130968588;
// aapt resource value: 0x7f04000d
public static int design_fab_out = 2130968589;
// aapt resource value: 0x7f04000e
public static int design_snackbar_in = 2130968590;
// aapt resource value: 0x7f04000f
public static int design_snackbar_out = 2130968591;
static Animation()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Animation()
{
}
}
public partial class Animator
{
// aapt resource value: 0x7f050000
public static int design_appbar_state_list_animator = 2131034112;
static Animator()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Animator()
{
}
}
public partial class Attribute
{
// aapt resource value: 0x7f01007c
public static int actionBarDivider = 2130772092;
// aapt resource value: 0x7f01007d
public static int actionBarItemBackground = 2130772093;
// aapt resource value: 0x7f010076
public static int actionBarPopupTheme = 2130772086;
// aapt resource value: 0x7f01007b
public static int actionBarSize = 2130772091;
// aapt resource value: 0x7f010078
public static int actionBarSplitStyle = 2130772088;
// aapt resource value: 0x7f010077
public static int actionBarStyle = 2130772087;
// aapt resource value: 0x7f010072
public static int actionBarTabBarStyle = 2130772082;
// aapt resource value: 0x7f010071
public static int actionBarTabStyle = 2130772081;
// aapt resource value: 0x7f010073
public static int actionBarTabTextStyle = 2130772083;
// aapt resource value: 0x7f010079
public static int actionBarTheme = 2130772089;
// aapt resource value: 0x7f01007a
public static int actionBarWidgetTheme = 2130772090;
// aapt resource value: 0x7f010097
public static int actionButtonStyle = 2130772119;
// aapt resource value: 0x7f010093
public static int actionDropDownStyle = 2130772115;
// aapt resource value: 0x7f0100e9
public static int actionLayout = 2130772201;
// aapt resource value: 0x7f01007e
public static int actionMenuTextAppearance = 2130772094;
// aapt resource value: 0x7f01007f
public static int actionMenuTextColor = 2130772095;
// aapt resource value: 0x7f010082
public static int actionModeBackground = 2130772098;
// aapt resource value: 0x7f010081
public static int actionModeCloseButtonStyle = 2130772097;
// aapt resource value: 0x7f010084
public static int actionModeCloseDrawable = 2130772100;
// aapt resource value: 0x7f010086
public static int actionModeCopyDrawable = 2130772102;
// aapt resource value: 0x7f010085
public static int actionModeCutDrawable = 2130772101;
// aapt resource value: 0x7f01008a
public static int actionModeFindDrawable = 2130772106;
// aapt resource value: 0x7f010087
public static int actionModePasteDrawable = 2130772103;
// aapt resource value: 0x7f01008c
public static int actionModePopupWindowStyle = 2130772108;
// aapt resource value: 0x7f010088
public static int actionModeSelectAllDrawable = 2130772104;
// aapt resource value: 0x7f010089
public static int actionModeShareDrawable = 2130772105;
// aapt resource value: 0x7f010083
public static int actionModeSplitBackground = 2130772099;
// aapt resource value: 0x7f010080
public static int actionModeStyle = 2130772096;
// aapt resource value: 0x7f01008b
public static int actionModeWebSearchDrawable = 2130772107;
// aapt resource value: 0x7f010074
public static int actionOverflowButtonStyle = 2130772084;
// aapt resource value: 0x7f010075
public static int actionOverflowMenuStyle = 2130772085;
// aapt resource value: 0x7f0100eb
public static int actionProviderClass = 2130772203;
// aapt resource value: 0x7f0100ea
public static int actionViewClass = 2130772202;
// aapt resource value: 0x7f01009f
public static int activityChooserViewStyle = 2130772127;
// aapt resource value: 0x7f0100c4
public static int alertDialogButtonGroupStyle = 2130772164;
// aapt resource value: 0x7f0100c5
public static int alertDialogCenterButtons = 2130772165;
// aapt resource value: 0x7f0100c3
public static int alertDialogStyle = 2130772163;
// aapt resource value: 0x7f0100c6
public static int alertDialogTheme = 2130772166;
// aapt resource value: 0x7f0100d9
public static int allowStacking = 2130772185;
// aapt resource value: 0x7f0100da
public static int alpha = 2130772186;
// aapt resource value: 0x7f01001b
public static int ambientEnabled = 2130771995;
// aapt resource value: 0x7f0100e1
public static int arrowHeadLength = 2130772193;
// aapt resource value: 0x7f0100e2
public static int arrowShaftLength = 2130772194;
// aapt resource value: 0x7f0100cb
public static int autoCompleteTextViewStyle = 2130772171;
// aapt resource value: 0x7f010045
public static int background = 2130772037;
// aapt resource value: 0x7f010047
public static int backgroundSplit = 2130772039;
// aapt resource value: 0x7f010046
public static int backgroundStacked = 2130772038;
// aapt resource value: 0x7f01011e
public static int backgroundTint = 2130772254;
// aapt resource value: 0x7f01011f
public static int backgroundTintMode = 2130772255;
// aapt resource value: 0x7f0100e3
public static int barLength = 2130772195;
// aapt resource value: 0x7f010149
public static int behavior_autoHide = 2130772297;
// aapt resource value: 0x7f010126
public static int behavior_hideable = 2130772262;
// aapt resource value: 0x7f010152
public static int behavior_overlapTop = 2130772306;
// aapt resource value: 0x7f010125
public static int behavior_peekHeight = 2130772261;
// aapt resource value: 0x7f010127
public static int behavior_skipCollapsed = 2130772263;
// aapt resource value: 0x7f010147
public static int borderWidth = 2130772295;
// aapt resource value: 0x7f01009c
public static int borderlessButtonStyle = 2130772124;
// aapt resource value: 0x7f010141
public static int bottomSheetDialogTheme = 2130772289;
// aapt resource value: 0x7f010142
public static int bottomSheetStyle = 2130772290;
// aapt resource value: 0x7f010099
public static int buttonBarButtonStyle = 2130772121;
// aapt resource value: 0x7f0100c9
public static int buttonBarNegativeButtonStyle = 2130772169;
// aapt resource value: 0x7f0100ca
public static int buttonBarNeutralButtonStyle = 2130772170;
// aapt resource value: 0x7f0100c8
public static int buttonBarPositiveButtonStyle = 2130772168;
// aapt resource value: 0x7f010098
public static int buttonBarStyle = 2130772120;
// aapt resource value: 0x7f010113
public static int buttonGravity = 2130772243;
// aapt resource value: 0x7f01005a
public static int buttonPanelSideLayout = 2130772058;
// aapt resource value: 0x7f010025
public static int buttonSize = 2130772005;
// aapt resource value: 0x7f0100cc
public static int buttonStyle = 2130772172;
// aapt resource value: 0x7f0100cd
public static int buttonStyleSmall = 2130772173;
// aapt resource value: 0x7f0100db
public static int buttonTint = 2130772187;
// aapt resource value: 0x7f0100dc
public static int buttonTintMode = 2130772188;
// aapt resource value: 0x7f01000c
public static int cameraBearing = 2130771980;
// aapt resource value: 0x7f01001d
public static int cameraMaxZoomPreference = 2130771997;
// aapt resource value: 0x7f01001c
public static int cameraMinZoomPreference = 2130771996;
// aapt resource value: 0x7f01000d
public static int cameraTargetLat = 2130771981;
// aapt resource value: 0x7f01000e
public static int cameraTargetLng = 2130771982;
// aapt resource value: 0x7f01000f
public static int cameraTilt = 2130771983;
// aapt resource value: 0x7f010010
public static int cameraZoom = 2130771984;
// aapt resource value: 0x7f010000
public static int cardBackgroundColor = 2130771968;
// aapt resource value: 0x7f010001
public static int cardCornerRadius = 2130771969;
// aapt resource value: 0x7f010002
public static int cardElevation = 2130771970;
// aapt resource value: 0x7f010003
public static int cardMaxElevation = 2130771971;
// aapt resource value: 0x7f010005
public static int cardPreventCornerOverlap = 2130771973;
// aapt resource value: 0x7f010004
public static int cardUseCompatPadding = 2130771972;
// aapt resource value: 0x7f0100ce
public static int checkboxStyle = 2130772174;
// aapt resource value: 0x7f0100cf
public static int checkedTextViewStyle = 2130772175;
// aapt resource value: 0x7f010024
public static int circleCrop = 2130772004;
// aapt resource value: 0x7f0100f6
public static int closeIcon = 2130772214;
// aapt resource value: 0x7f010057
public static int closeItemLayout = 2130772055;
// aapt resource value: 0x7f010115
public static int collapseContentDescription = 2130772245;
// aapt resource value: 0x7f010114
public static int collapseIcon = 2130772244;
// aapt resource value: 0x7f010134
public static int collapsedTitleGravity = 2130772276;
// aapt resource value: 0x7f01012e
public static int collapsedTitleTextAppearance = 2130772270;
// aapt resource value: 0x7f0100dd
public static int color = 2130772189;
// aapt resource value: 0x7f0100bb
public static int colorAccent = 2130772155;
// aapt resource value: 0x7f0100c2
public static int colorBackgroundFloating = 2130772162;
// aapt resource value: 0x7f0100bf
public static int colorButtonNormal = 2130772159;
// aapt resource value: 0x7f0100bd
public static int colorControlActivated = 2130772157;
// aapt resource value: 0x7f0100be
public static int colorControlHighlight = 2130772158;
// aapt resource value: 0x7f0100bc
public static int colorControlNormal = 2130772156;
// aapt resource value: 0x7f0100b9
public static int colorPrimary = 2130772153;
// aapt resource value: 0x7f0100ba
public static int colorPrimaryDark = 2130772154;
// aapt resource value: 0x7f010026
public static int colorScheme = 2130772006;
// aapt resource value: 0x7f0100c0
public static int colorSwitchThumbNormal = 2130772160;
// aapt resource value: 0x7f0100fb
public static int commitIcon = 2130772219;
// aapt resource value: 0x7f010050
public static int contentInsetEnd = 2130772048;
// aapt resource value: 0x7f010054
public static int contentInsetEndWithActions = 2130772052;
// aapt resource value: 0x7f010051
public static int contentInsetLeft = 2130772049;
// aapt resource value: 0x7f010052
public static int contentInsetRight = 2130772050;
// aapt resource value: 0x7f01004f
public static int contentInsetStart = 2130772047;
// aapt resource value: 0x7f010053
public static int contentInsetStartWithNavigation = 2130772051;
// aapt resource value: 0x7f010006
public static int contentPadding = 2130771974;
// aapt resource value: 0x7f01000a
public static int contentPaddingBottom = 2130771978;
// aapt resource value: 0x7f010007
public static int contentPaddingLeft = 2130771975;
// aapt resource value: 0x7f010008
public static int contentPaddingRight = 2130771976;
// aapt resource value: 0x7f010009
public static int contentPaddingTop = 2130771977;
// aapt resource value: 0x7f01012f
public static int contentScrim = 2130772271;
// aapt resource value: 0x7f0100c1
public static int controlBackground = 2130772161;
// aapt resource value: 0x7f010168
public static int counterEnabled = 2130772328;
// aapt resource value: 0x7f010169
public static int counterMaxLength = 2130772329;
// aapt resource value: 0x7f01016b
public static int counterOverflowTextAppearance = 2130772331;
// aapt resource value: 0x7f01016a
public static int counterTextAppearance = 2130772330;
// aapt resource value: 0x7f010048
public static int customNavigationLayout = 2130772040;
// aapt resource value: 0x7f0100f5
public static int defaultQueryHint = 2130772213;
// aapt resource value: 0x7f010091
public static int dialogPreferredPadding = 2130772113;
// aapt resource value: 0x7f010090
public static int dialogTheme = 2130772112;
// aapt resource value: 0x7f01003e
public static int displayOptions = 2130772030;
// aapt resource value: 0x7f010044
public static int divider = 2130772036;
// aapt resource value: 0x7f01009e
public static int dividerHorizontal = 2130772126;
// aapt resource value: 0x7f0100e7
public static int dividerPadding = 2130772199;
// aapt resource value: 0x7f01009d
public static int dividerVertical = 2130772125;
// aapt resource value: 0x7f0100df
public static int drawableSize = 2130772191;
// aapt resource value: 0x7f010039
public static int drawerArrowStyle = 2130772025;
// aapt resource value: 0x7f0100b0
public static int dropDownListViewStyle = 2130772144;
// aapt resource value: 0x7f010094
public static int dropdownListPreferredItemHeight = 2130772116;
// aapt resource value: 0x7f0100a5
public static int editTextBackground = 2130772133;
// aapt resource value: 0x7f0100a4
public static int editTextColor = 2130772132;
// aapt resource value: 0x7f0100d0
public static int editTextStyle = 2130772176;
// aapt resource value: 0x7f010055
public static int elevation = 2130772053;
// aapt resource value: 0x7f010166
public static int errorEnabled = 2130772326;
// aapt resource value: 0x7f010167
public static int errorTextAppearance = 2130772327;
// aapt resource value: 0x7f010059
public static int expandActivityOverflowButtonDrawable = 2130772057;
// aapt resource value: 0x7f010120
public static int expanded = 2130772256;
// aapt resource value: 0x7f010135
public static int expandedTitleGravity = 2130772277;
// aapt resource value: 0x7f010128
public static int expandedTitleMargin = 2130772264;
// aapt resource value: 0x7f01012c
public static int expandedTitleMarginBottom = 2130772268;
// aapt resource value: 0x7f01012b
public static int expandedTitleMarginEnd = 2130772267;
// aapt resource value: 0x7f010129
public static int expandedTitleMarginStart = 2130772265;
// aapt resource value: 0x7f01012a
public static int expandedTitleMarginTop = 2130772266;
// aapt resource value: 0x7f01012d
public static int expandedTitleTextAppearance = 2130772269;
// aapt resource value: 0x7f010038
public static int externalRouteEnabledDrawable = 2130772024;
// aapt resource value: 0x7f010145
public static int fabSize = 2130772293;
// aapt resource value: 0x7f01014a
public static int foregroundInsidePadding = 2130772298;
// aapt resource value: 0x7f0100e0
public static int gapBetweenBars = 2130772192;
// aapt resource value: 0x7f0100f7
public static int goIcon = 2130772215;
// aapt resource value: 0x7f010150
public static int headerLayout = 2130772304;
// aapt resource value: 0x7f01003a
public static int height = 2130772026;
// aapt resource value: 0x7f01004e
public static int hideOnContentScroll = 2130772046;
// aapt resource value: 0x7f01016c
public static int hintAnimationEnabled = 2130772332;
// aapt resource value: 0x7f010165
public static int hintEnabled = 2130772325;
// aapt resource value: 0x7f010164
public static int hintTextAppearance = 2130772324;
// aapt resource value: 0x7f010096
public static int homeAsUpIndicator = 2130772118;
// aapt resource value: 0x7f010049
public static int homeLayout = 2130772041;
// aapt resource value: 0x7f010042
public static int icon = 2130772034;
// aapt resource value: 0x7f0100f3
public static int iconifiedByDefault = 2130772211;
// aapt resource value: 0x7f010023
public static int imageAspectRatio = 2130772003;
// aapt resource value: 0x7f010022
public static int imageAspectRatioAdjust = 2130772002;
// aapt resource value: 0x7f0100a6
public static int imageButtonStyle = 2130772134;
// aapt resource value: 0x7f01004b
public static int indeterminateProgressStyle = 2130772043;
// aapt resource value: 0x7f010058
public static int initialActivityCount = 2130772056;
// aapt resource value: 0x7f010151
public static int insetForeground = 2130772305;
// aapt resource value: 0x7f01003b
public static int isLightTheme = 2130772027;
// aapt resource value: 0x7f01014e
public static int itemBackground = 2130772302;
// aapt resource value: 0x7f01014c
public static int itemIconTint = 2130772300;
// aapt resource value: 0x7f01004d
public static int itemPadding = 2130772045;
// aapt resource value: 0x7f01014f
public static int itemTextAppearance = 2130772303;
// aapt resource value: 0x7f01014d
public static int itemTextColor = 2130772301;
// aapt resource value: 0x7f010139
public static int keylines = 2130772281;
// aapt resource value: 0x7f010020
public static int latLngBoundsNorthEastLatitude = 2130772000;
// aapt resource value: 0x7f010021
public static int latLngBoundsNorthEastLongitude = 2130772001;
// aapt resource value: 0x7f01001e
public static int latLngBoundsSouthWestLatitude = 2130771998;
// aapt resource value: 0x7f01001f
public static int latLngBoundsSouthWestLongitude = 2130771999;
// aapt resource value: 0x7f0100f2
public static int layout = 2130772210;
// aapt resource value: 0x7f010028
public static int layoutManager = 2130772008;
// aapt resource value: 0x7f01013c
public static int layout_anchor = 2130772284;
// aapt resource value: 0x7f01013e
public static int layout_anchorGravity = 2130772286;
// aapt resource value: 0x7f01013b
public static int layout_behavior = 2130772283;
// aapt resource value: 0x7f010137
public static int layout_collapseMode = 2130772279;
// aapt resource value: 0x7f010138
public static int layout_collapseParallaxMultiplier = 2130772280;
// aapt resource value: 0x7f010140
public static int layout_dodgeInsetEdges = 2130772288;
// aapt resource value: 0x7f01013f
public static int layout_insetEdge = 2130772287;
// aapt resource value: 0x7f01013d
public static int layout_keyline = 2130772285;
// aapt resource value: 0x7f010123
public static int layout_scrollFlags = 2130772259;
// aapt resource value: 0x7f010124
public static int layout_scrollInterpolator = 2130772260;
// aapt resource value: 0x7f0100b8
public static int listChoiceBackgroundIndicator = 2130772152;
// aapt resource value: 0x7f010092
public static int listDividerAlertDialog = 2130772114;
// aapt resource value: 0x7f01005e
public static int listItemLayout = 2130772062;
// aapt resource value: 0x7f01005b
public static int listLayout = 2130772059;
// aapt resource value: 0x7f0100d8
public static int listMenuViewStyle = 2130772184;
// aapt resource value: 0x7f0100b1
public static int listPopupWindowStyle = 2130772145;
// aapt resource value: 0x7f0100ab
public static int listPreferredItemHeight = 2130772139;
// aapt resource value: 0x7f0100ad
public static int listPreferredItemHeightLarge = 2130772141;
// aapt resource value: 0x7f0100ac
public static int listPreferredItemHeightSmall = 2130772140;
// aapt resource value: 0x7f0100ae
public static int listPreferredItemPaddingLeft = 2130772142;
// aapt resource value: 0x7f0100af
public static int listPreferredItemPaddingRight = 2130772143;
// aapt resource value: 0x7f010011
public static int liteMode = 2130771985;
// aapt resource value: 0x7f010043
public static int logo = 2130772035;
// aapt resource value: 0x7f010118
public static int logoDescription = 2130772248;
// aapt resource value: 0x7f01000b
public static int mapType = 2130771979;
// aapt resource value: 0x7f010153
public static int maxActionInlineWidth = 2130772307;
// aapt resource value: 0x7f010112
public static int maxButtonHeight = 2130772242;
// aapt resource value: 0x7f0100e5
public static int measureWithLargestChild = 2130772197;
// aapt resource value: 0x7f01002c
public static int mediaRouteAudioTrackDrawable = 2130772012;
// aapt resource value: 0x7f01002d
public static int mediaRouteButtonStyle = 2130772013;
// aapt resource value: 0x7f01002e
public static int mediaRouteCloseDrawable = 2130772014;
// aapt resource value: 0x7f01002f
public static int mediaRouteControlPanelThemeOverlay = 2130772015;
// aapt resource value: 0x7f010030
public static int mediaRouteDefaultIconDrawable = 2130772016;
// aapt resource value: 0x7f010031
public static int mediaRoutePauseDrawable = 2130772017;
// aapt resource value: 0x7f010032
public static int mediaRoutePlayDrawable = 2130772018;
// aapt resource value: 0x7f010033
public static int mediaRouteSpeakerGroupIconDrawable = 2130772019;
// aapt resource value: 0x7f010034
public static int mediaRouteSpeakerIconDrawable = 2130772020;
// aapt resource value: 0x7f010035
public static int mediaRouteStopDrawable = 2130772021;
// aapt resource value: 0x7f010036
public static int mediaRouteTheme = 2130772022;
// aapt resource value: 0x7f010037
public static int mediaRouteTvIconDrawable = 2130772023;
// aapt resource value: 0x7f01014b
public static int menu = 2130772299;
// aapt resource value: 0x7f01005c
public static int multiChoiceItemLayout = 2130772060;
// aapt resource value: 0x7f010117
public static int navigationContentDescription = 2130772247;
// aapt resource value: 0x7f010116
public static int navigationIcon = 2130772246;
// aapt resource value: 0x7f01003d
public static int navigationMode = 2130772029;
// aapt resource value: 0x7f0100ee
public static int overlapAnchor = 2130772206;
// aapt resource value: 0x7f0100f0
public static int paddingBottomNoButtons = 2130772208;
// aapt resource value: 0x7f01011c
public static int paddingEnd = 2130772252;
// aapt resource value: 0x7f01011b
public static int paddingStart = 2130772251;
// aapt resource value: 0x7f0100f1
public static int paddingTopNoTitle = 2130772209;
// aapt resource value: 0x7f0100b5
public static int panelBackground = 2130772149;
// aapt resource value: 0x7f0100b7
public static int panelMenuListTheme = 2130772151;
// aapt resource value: 0x7f0100b6
public static int panelMenuListWidth = 2130772150;
// aapt resource value: 0x7f01016f
public static int passwordToggleContentDescription = 2130772335;
// aapt resource value: 0x7f01016e
public static int passwordToggleDrawable = 2130772334;
// aapt resource value: 0x7f01016d
public static int passwordToggleEnabled = 2130772333;
// aapt resource value: 0x7f010170
public static int passwordToggleTint = 2130772336;
// aapt resource value: 0x7f010171
public static int passwordToggleTintMode = 2130772337;
// aapt resource value: 0x7f0100a2
public static int popupMenuStyle = 2130772130;
// aapt resource value: 0x7f010056
public static int popupTheme = 2130772054;
// aapt resource value: 0x7f0100a3
public static int popupWindowStyle = 2130772131;
// aapt resource value: 0x7f0100ec
public static int preserveIconSpacing = 2130772204;
// aapt resource value: 0x7f010146
public static int pressedTranslationZ = 2130772294;
// aapt resource value: 0x7f01004c
public static int progressBarPadding = 2130772044;
// aapt resource value: 0x7f01004a
public static int progressBarStyle = 2130772042;
// aapt resource value: 0x7f0100fd
public static int queryBackground = 2130772221;
// aapt resource value: 0x7f0100f4
public static int queryHint = 2130772212;
// aapt resource value: 0x7f0100d1
public static int radioButtonStyle = 2130772177;
// aapt resource value: 0x7f0100d2
public static int ratingBarStyle = 2130772178;
// aapt resource value: 0x7f0100d3
public static int ratingBarStyleIndicator = 2130772179;
// aapt resource value: 0x7f0100d4
public static int ratingBarStyleSmall = 2130772180;
// aapt resource value: 0x7f01002a
public static int reverseLayout = 2130772010;
// aapt resource value: 0x7f010144
public static int rippleColor = 2130772292;
// aapt resource value: 0x7f010027
public static int scopeUris = 2130772007;
// aapt resource value: 0x7f010133
public static int scrimAnimationDuration = 2130772275;
// aapt resource value: 0x7f010132
public static int scrimVisibleHeightTrigger = 2130772274;
// aapt resource value: 0x7f0100f9
public static int searchHintIcon = 2130772217;
// aapt resource value: 0x7f0100f8
public static int searchIcon = 2130772216;
// aapt resource value: 0x7f0100aa
public static int searchViewStyle = 2130772138;
// aapt resource value: 0x7f0100d5
public static int seekBarStyle = 2130772181;
// aapt resource value: 0x7f01009a
public static int selectableItemBackground = 2130772122;
// aapt resource value: 0x7f01009b
public static int selectableItemBackgroundBorderless = 2130772123;
// aapt resource value: 0x7f0100e8
public static int showAsAction = 2130772200;
// aapt resource value: 0x7f0100e6
public static int showDividers = 2130772198;
// aapt resource value: 0x7f010109
public static int showText = 2130772233;
// aapt resource value: 0x7f01005f
public static int showTitle = 2130772063;
// aapt resource value: 0x7f01005d
public static int singleChoiceItemLayout = 2130772061;
// aapt resource value: 0x7f010029
public static int spanCount = 2130772009;
// aapt resource value: 0x7f0100de
public static int spinBars = 2130772190;
// aapt resource value: 0x7f010095
public static int spinnerDropDownItemStyle = 2130772117;
// aapt resource value: 0x7f0100d6
public static int spinnerStyle = 2130772182;
// aapt resource value: 0x7f010108
public static int splitTrack = 2130772232;
// aapt resource value: 0x7f010060
public static int srcCompat = 2130772064;
// aapt resource value: 0x7f01002b
public static int stackFromEnd = 2130772011;
// aapt resource value: 0x7f0100ef
public static int state_above_anchor = 2130772207;
// aapt resource value: 0x7f010121
public static int state_collapsed = 2130772257;
// aapt resource value: 0x7f010122
public static int state_collapsible = 2130772258;
// aapt resource value: 0x7f01013a
public static int statusBarBackground = 2130772282;
// aapt resource value: 0x7f010130
public static int statusBarScrim = 2130772272;
// aapt resource value: 0x7f0100ed
public static int subMenuArrow = 2130772205;
// aapt resource value: 0x7f0100fe
public static int submitBackground = 2130772222;
// aapt resource value: 0x7f01003f
public static int subtitle = 2130772031;
// aapt resource value: 0x7f01010b
public static int subtitleTextAppearance = 2130772235;
// aapt resource value: 0x7f01011a
public static int subtitleTextColor = 2130772250;
// aapt resource value: 0x7f010041
public static int subtitleTextStyle = 2130772033;
// aapt resource value: 0x7f0100fc
public static int suggestionRowLayout = 2130772220;
// aapt resource value: 0x7f010106
public static int switchMinWidth = 2130772230;
// aapt resource value: 0x7f010107
public static int switchPadding = 2130772231;
// aapt resource value: 0x7f0100d7
public static int switchStyle = 2130772183;
// aapt resource value: 0x7f010105
public static int switchTextAppearance = 2130772229;
// aapt resource value: 0x7f010157
public static int tabBackground = 2130772311;
// aapt resource value: 0x7f010156
public static int tabContentStart = 2130772310;
// aapt resource value: 0x7f010159
public static int tabGravity = 2130772313;
// aapt resource value: 0x7f010154
public static int tabIndicatorColor = 2130772308;
// aapt resource value: 0x7f010155
public static int tabIndicatorHeight = 2130772309;
// aapt resource value: 0x7f01015b
public static int tabMaxWidth = 2130772315;
// aapt resource value: 0x7f01015a
public static int tabMinWidth = 2130772314;
// aapt resource value: 0x7f010158
public static int tabMode = 2130772312;
// aapt resource value: 0x7f010163
public static int tabPadding = 2130772323;
// aapt resource value: 0x7f010162
public static int tabPaddingBottom = 2130772322;
// aapt resource value: 0x7f010161
public static int tabPaddingEnd = 2130772321;
// aapt resource value: 0x7f01015f
public static int tabPaddingStart = 2130772319;
// aapt resource value: 0x7f010160
public static int tabPaddingTop = 2130772320;
// aapt resource value: 0x7f01015e
public static int tabSelectedTextColor = 2130772318;
// aapt resource value: 0x7f01015c
public static int tabTextAppearance = 2130772316;
// aapt resource value: 0x7f01015d
public static int tabTextColor = 2130772317;
// aapt resource value: 0x7f010066
public static int textAllCaps = 2130772070;
// aapt resource value: 0x7f01008d
public static int textAppearanceLargePopupMenu = 2130772109;
// aapt resource value: 0x7f0100b2
public static int textAppearanceListItem = 2130772146;
// aapt resource value: 0x7f0100b3
public static int textAppearanceListItemSecondary = 2130772147;
// aapt resource value: 0x7f0100b4
public static int textAppearanceListItemSmall = 2130772148;
// aapt resource value: 0x7f01008f
public static int textAppearancePopupMenuHeader = 2130772111;
// aapt resource value: 0x7f0100a8
public static int textAppearanceSearchResultSubtitle = 2130772136;
// aapt resource value: 0x7f0100a7
public static int textAppearanceSearchResultTitle = 2130772135;
// aapt resource value: 0x7f01008e
public static int textAppearanceSmallPopupMenu = 2130772110;
// aapt resource value: 0x7f0100c7
public static int textColorAlertDialogListItem = 2130772167;
// aapt resource value: 0x7f010143
public static int textColorError = 2130772291;
// aapt resource value: 0x7f0100a9
public static int textColorSearchUrl = 2130772137;
// aapt resource value: 0x7f01011d
public static int theme = 2130772253;
// aapt resource value: 0x7f0100e4
public static int thickness = 2130772196;
// aapt resource value: 0x7f010104
public static int thumbTextPadding = 2130772228;
// aapt resource value: 0x7f0100ff
public static int thumbTint = 2130772223;
// aapt resource value: 0x7f010100
public static int thumbTintMode = 2130772224;
// aapt resource value: 0x7f010063
public static int tickMark = 2130772067;
// aapt resource value: 0x7f010064
public static int tickMarkTint = 2130772068;
// aapt resource value: 0x7f010065
public static int tickMarkTintMode = 2130772069;
// aapt resource value: 0x7f010061
public static int tint = 2130772065;
// aapt resource value: 0x7f010062
public static int tintMode = 2130772066;
// aapt resource value: 0x7f01003c
public static int title = 2130772028;
// aapt resource value: 0x7f010136
public static int titleEnabled = 2130772278;
// aapt resource value: 0x7f01010c
public static int titleMargin = 2130772236;
// aapt resource value: 0x7f010110
public static int titleMarginBottom = 2130772240;
// aapt resource value: 0x7f01010e
public static int titleMarginEnd = 2130772238;
// aapt resource value: 0x7f01010d
public static int titleMarginStart = 2130772237;
// aapt resource value: 0x7f01010f
public static int titleMarginTop = 2130772239;
// aapt resource value: 0x7f010111
public static int titleMargins = 2130772241;
// aapt resource value: 0x7f01010a
public static int titleTextAppearance = 2130772234;
// aapt resource value: 0x7f010119
public static int titleTextColor = 2130772249;
// aapt resource value: 0x7f010040
public static int titleTextStyle = 2130772032;
// aapt resource value: 0x7f010131
public static int toolbarId = 2130772273;
// aapt resource value: 0x7f0100a1
public static int toolbarNavigationButtonStyle = 2130772129;
// aapt resource value: 0x7f0100a0
public static int toolbarStyle = 2130772128;
// aapt resource value: 0x7f010101
public static int track = 2130772225;
// aapt resource value: 0x7f010102
public static int trackTint = 2130772226;
// aapt resource value: 0x7f010103
public static int trackTintMode = 2130772227;
// aapt resource value: 0x7f010012
public static int uiCompass = 2130771986;
// aapt resource value: 0x7f01001a
public static int uiMapToolbar = 2130771994;
// aapt resource value: 0x7f010013
public static int uiRotateGestures = 2130771987;
// aapt resource value: 0x7f010014
public static int uiScrollGestures = 2130771988;
// aapt resource value: 0x7f010015
public static int uiTiltGestures = 2130771989;
// aapt resource value: 0x7f010016
public static int uiZoomControls = 2130771990;
// aapt resource value: 0x7f010017
public static int uiZoomGestures = 2130771991;
// aapt resource value: 0x7f010148
public static int useCompatPadding = 2130772296;
// aapt resource value: 0x7f010018
public static int useViewLifecycle = 2130771992;
// aapt resource value: 0x7f0100fa
public static int voiceIcon = 2130772218;
// aapt resource value: 0x7f010067
public static int windowActionBar = 2130772071;
// aapt resource value: 0x7f010069
public static int windowActionBarOverlay = 2130772073;
// aapt resource value: 0x7f01006a
public static int windowActionModeOverlay = 2130772074;
// aapt resource value: 0x7f01006e
public static int windowFixedHeightMajor = 2130772078;
// aapt resource value: 0x7f01006c
public static int windowFixedHeightMinor = 2130772076;
// aapt resource value: 0x7f01006b
public static int windowFixedWidthMajor = 2130772075;
// aapt resource value: 0x7f01006d
public static int windowFixedWidthMinor = 2130772077;
// aapt resource value: 0x7f01006f
public static int windowMinWidthMajor = 2130772079;
// aapt resource value: 0x7f010070
public static int windowMinWidthMinor = 2130772080;
// aapt resource value: 0x7f010068
public static int windowNoTitle = 2130772072;
// aapt resource value: 0x7f010019
public static int zOrderOnTop = 2130771993;
static Attribute()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Attribute()
{
}
}
public partial class Boolean
{
// aapt resource value: 0x7f0d0000
public static int abc_action_bar_embed_tabs = 2131558400;
// aapt resource value: 0x7f0d0001
public static int abc_allow_stacked_button_bar = 2131558401;
// aapt resource value: 0x7f0d0002
public static int abc_config_actionMenuItemAllCaps = 2131558402;
// aapt resource value: 0x7f0d0003
public static int abc_config_closeDialogWhenTouchOutside = 2131558403;
// aapt resource value: 0x7f0d0004
public static int abc_config_showMenuShortcutsWhenKeyboardPresent = 2131558404;
static Boolean()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Boolean()
{
}
}
public partial class Color
{
// aapt resource value: 0x7f080052
public static int abc_background_cache_hint_selector_material_dark = 2131230802;
// aapt resource value: 0x7f080053
public static int abc_background_cache_hint_selector_material_light = 2131230803;
// aapt resource value: 0x7f080054
public static int abc_btn_colored_borderless_text_material = 2131230804;
// aapt resource value: 0x7f080055
public static int abc_btn_colored_text_material = 2131230805;
// aapt resource value: 0x7f080056
public static int abc_color_highlight_material = 2131230806;
// aapt resource value: 0x7f080057
public static int abc_hint_foreground_material_dark = 2131230807;
// aapt resource value: 0x7f080058
public static int abc_hint_foreground_material_light = 2131230808;
// aapt resource value: 0x7f08000d
public static int abc_input_method_navigation_guard = 2131230733;
// aapt resource value: 0x7f080059
public static int abc_primary_text_disable_only_material_dark = 2131230809;
// aapt resource value: 0x7f08005a
public static int abc_primary_text_disable_only_material_light = 2131230810;
// aapt resource value: 0x7f08005b
public static int abc_primary_text_material_dark = 2131230811;
// aapt resource value: 0x7f08005c
public static int abc_primary_text_material_light = 2131230812;
// aapt resource value: 0x7f08005d
public static int abc_search_url_text = 2131230813;
// aapt resource value: 0x7f08000e
public static int abc_search_url_text_normal = 2131230734;
// aapt resource value: 0x7f08000f
public static int abc_search_url_text_pressed = 2131230735;
// aapt resource value: 0x7f080010
public static int abc_search_url_text_selected = 2131230736;
// aapt resource value: 0x7f08005e
public static int abc_secondary_text_material_dark = 2131230814;
// aapt resource value: 0x7f08005f
public static int abc_secondary_text_material_light = 2131230815;
// aapt resource value: 0x7f080060
public static int abc_tint_btn_checkable = 2131230816;
// aapt resource value: 0x7f080061
public static int abc_tint_default = 2131230817;
// aapt resource value: 0x7f080062
public static int abc_tint_edittext = 2131230818;
// aapt resource value: 0x7f080063
public static int abc_tint_seek_thumb = 2131230819;
// aapt resource value: 0x7f080064
public static int abc_tint_spinner = 2131230820;
// aapt resource value: 0x7f080065
public static int abc_tint_switch_thumb = 2131230821;
// aapt resource value: 0x7f080066
public static int abc_tint_switch_track = 2131230822;
// aapt resource value: 0x7f080011
public static int accent_material_dark = 2131230737;
// aapt resource value: 0x7f080012
public static int accent_material_light = 2131230738;
// aapt resource value: 0x7f080013
public static int background_floating_material_dark = 2131230739;
// aapt resource value: 0x7f080014
public static int background_floating_material_light = 2131230740;
// aapt resource value: 0x7f080015
public static int background_material_dark = 2131230741;
// aapt resource value: 0x7f080016
public static int background_material_light = 2131230742;
// aapt resource value: 0x7f080017
public static int bright_foreground_disabled_material_dark = 2131230743;
// aapt resource value: 0x7f080018
public static int bright_foreground_disabled_material_light = 2131230744;
// aapt resource value: 0x7f080019
public static int bright_foreground_inverse_material_dark = 2131230745;
// aapt resource value: 0x7f08001a
public static int bright_foreground_inverse_material_light = 2131230746;
// aapt resource value: 0x7f08001b
public static int bright_foreground_material_dark = 2131230747;
// aapt resource value: 0x7f08001c
public static int bright_foreground_material_light = 2131230748;
// aapt resource value: 0x7f08001d
public static int button_material_dark = 2131230749;
// aapt resource value: 0x7f08001e
public static int button_material_light = 2131230750;
// aapt resource value: 0x7f080000
public static int cardview_dark_background = 2131230720;
// aapt resource value: 0x7f080001
public static int cardview_light_background = 2131230721;
// aapt resource value: 0x7f080002
public static int cardview_shadow_end_color = 2131230722;
// aapt resource value: 0x7f080003
public static int cardview_shadow_start_color = 2131230723;
// aapt resource value: 0x7f080067
public static int common_google_signin_btn_text_dark = 2131230823;
// aapt resource value: 0x7f080004
public static int common_google_signin_btn_text_dark_default = 2131230724;
// aapt resource value: 0x7f080005
public static int common_google_signin_btn_text_dark_disabled = 2131230725;
// aapt resource value: 0x7f080006
public static int common_google_signin_btn_text_dark_focused = 2131230726;
// aapt resource value: 0x7f080007
public static int common_google_signin_btn_text_dark_pressed = 2131230727;
// aapt resource value: 0x7f080068
public static int common_google_signin_btn_text_light = 2131230824;
// aapt resource value: 0x7f080008
public static int common_google_signin_btn_text_light_default = 2131230728;
// aapt resource value: 0x7f080009
public static int common_google_signin_btn_text_light_disabled = 2131230729;
// aapt resource value: 0x7f08000a
public static int common_google_signin_btn_text_light_focused = 2131230730;
// aapt resource value: 0x7f08000b
public static int common_google_signin_btn_text_light_pressed = 2131230731;
// aapt resource value: 0x7f080047
public static int design_bottom_navigation_shadow_color = 2131230791;
// aapt resource value: 0x7f080069
public static int design_error = 2131230825;
// aapt resource value: 0x7f080048
public static int design_fab_shadow_end_color = 2131230792;
// aapt resource value: 0x7f080049
public static int design_fab_shadow_mid_color = 2131230793;
// aapt resource value: 0x7f08004a
public static int design_fab_shadow_start_color = 2131230794;
// aapt resource value: 0x7f08004b
public static int design_fab_stroke_end_inner_color = 2131230795;
// aapt resource value: 0x7f08004c
public static int design_fab_stroke_end_outer_color = 2131230796;
// aapt resource value: 0x7f08004d
public static int design_fab_stroke_top_inner_color = 2131230797;
// aapt resource value: 0x7f08004e
public static int design_fab_stroke_top_outer_color = 2131230798;
// aapt resource value: 0x7f08004f
public static int design_snackbar_background_color = 2131230799;
// aapt resource value: 0x7f080050
public static int design_textinput_error_color_dark = 2131230800;
// aapt resource value: 0x7f080051
public static int design_textinput_error_color_light = 2131230801;
// aapt resource value: 0x7f08006a
public static int design_tint_password_toggle = 2131230826;
// aapt resource value: 0x7f08001f
public static int dim_foreground_disabled_material_dark = 2131230751;
// aapt resource value: 0x7f080020
public static int dim_foreground_disabled_material_light = 2131230752;
// aapt resource value: 0x7f080021
public static int dim_foreground_material_dark = 2131230753;
// aapt resource value: 0x7f080022
public static int dim_foreground_material_light = 2131230754;
// aapt resource value: 0x7f080023
public static int foreground_material_dark = 2131230755;
// aapt resource value: 0x7f080024
public static int foreground_material_light = 2131230756;
// aapt resource value: 0x7f080025
public static int highlighted_text_material_dark = 2131230757;
// aapt resource value: 0x7f080026
public static int highlighted_text_material_light = 2131230758;
// aapt resource value: 0x7f080027
public static int material_blue_grey_800 = 2131230759;
// aapt resource value: 0x7f080028
public static int material_blue_grey_900 = 2131230760;
// aapt resource value: 0x7f080029
public static int material_blue_grey_950 = 2131230761;
// aapt resource value: 0x7f08002a
public static int material_deep_teal_200 = 2131230762;
// aapt resource value: 0x7f08002b
public static int material_deep_teal_500 = 2131230763;
// aapt resource value: 0x7f08002c
public static int material_grey_100 = 2131230764;
// aapt resource value: 0x7f08002d
public static int material_grey_300 = 2131230765;
// aapt resource value: 0x7f08002e
public static int material_grey_50 = 2131230766;
// aapt resource value: 0x7f08002f
public static int material_grey_600 = 2131230767;
// aapt resource value: 0x7f080030
public static int material_grey_800 = 2131230768;
// aapt resource value: 0x7f080031
public static int material_grey_850 = 2131230769;
// aapt resource value: 0x7f080032
public static int material_grey_900 = 2131230770;
// aapt resource value: 0x7f08000c
public static int notification_action_color_filter = 2131230732;
// aapt resource value: 0x7f080033
public static int notification_icon_bg_color = 2131230771;
// aapt resource value: 0x7f080034
public static int notification_material_background_media_default_color = 2131230772;
// aapt resource value: 0x7f080035
public static int primary_dark_material_dark = 2131230773;
// aapt resource value: 0x7f080036
public static int primary_dark_material_light = 2131230774;
// aapt resource value: 0x7f080037
public static int primary_material_dark = 2131230775;
// aapt resource value: 0x7f080038
public static int primary_material_light = 2131230776;
// aapt resource value: 0x7f080039
public static int primary_text_default_material_dark = 2131230777;
// aapt resource value: 0x7f08003a
public static int primary_text_default_material_light = 2131230778;
// aapt resource value: 0x7f08003b
public static int primary_text_disabled_material_dark = 2131230779;
// aapt resource value: 0x7f08003c
public static int primary_text_disabled_material_light = 2131230780;
// aapt resource value: 0x7f08003d
public static int ripple_material_dark = 2131230781;
// aapt resource value: 0x7f08003e
public static int ripple_material_light = 2131230782;
// aapt resource value: 0x7f08003f
public static int secondary_text_default_material_dark = 2131230783;
// aapt resource value: 0x7f080040
public static int secondary_text_default_material_light = 2131230784;
// aapt resource value: 0x7f080041
public static int secondary_text_disabled_material_dark = 2131230785;
// aapt resource value: 0x7f080042
public static int secondary_text_disabled_material_light = 2131230786;
// aapt resource value: 0x7f080043
public static int switch_thumb_disabled_material_dark = 2131230787;
// aapt resource value: 0x7f080044
public static int switch_thumb_disabled_material_light = 2131230788;
// aapt resource value: 0x7f08006b
public static int switch_thumb_material_dark = 2131230827;
// aapt resource value: 0x7f08006c
public static int switch_thumb_material_light = 2131230828;
// aapt resource value: 0x7f080045
public static int switch_thumb_normal_material_dark = 2131230789;
// aapt resource value: 0x7f080046
public static int switch_thumb_normal_material_light = 2131230790;
static Color()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Color()
{
}
}
public partial class Dimension
{
// aapt resource value: 0x7f090018
public static int abc_action_bar_content_inset_material = 2131296280;
// aapt resource value: 0x7f090019
public static int abc_action_bar_content_inset_with_nav = 2131296281;
// aapt resource value: 0x7f09000d
public static int abc_action_bar_default_height_material = 2131296269;
// aapt resource value: 0x7f09001a
public static int abc_action_bar_default_padding_end_material = 2131296282;
// aapt resource value: 0x7f09001b
public static int abc_action_bar_default_padding_start_material = 2131296283;
// aapt resource value: 0x7f090021
public static int abc_action_bar_elevation_material = 2131296289;
// aapt resource value: 0x7f090022
public static int abc_action_bar_icon_vertical_padding_material = 2131296290;
// aapt resource value: 0x7f090023
public static int abc_action_bar_overflow_padding_end_material = 2131296291;
// aapt resource value: 0x7f090024
public static int abc_action_bar_overflow_padding_start_material = 2131296292;
// aapt resource value: 0x7f09000e
public static int abc_action_bar_progress_bar_size = 2131296270;
// aapt resource value: 0x7f090025
public static int abc_action_bar_stacked_max_height = 2131296293;
// aapt resource value: 0x7f090026
public static int abc_action_bar_stacked_tab_max_width = 2131296294;
// aapt resource value: 0x7f090027
public static int abc_action_bar_subtitle_bottom_margin_material = 2131296295;
// aapt resource value: 0x7f090028
public static int abc_action_bar_subtitle_top_margin_material = 2131296296;
// aapt resource value: 0x7f090029
public static int abc_action_button_min_height_material = 2131296297;
// aapt resource value: 0x7f09002a
public static int abc_action_button_min_width_material = 2131296298;
// aapt resource value: 0x7f09002b
public static int abc_action_button_min_width_overflow_material = 2131296299;
// aapt resource value: 0x7f09000c
public static int abc_alert_dialog_button_bar_height = 2131296268;
// aapt resource value: 0x7f09002c
public static int abc_button_inset_horizontal_material = 2131296300;
// aapt resource value: 0x7f09002d
public static int abc_button_inset_vertical_material = 2131296301;
// aapt resource value: 0x7f09002e
public static int abc_button_padding_horizontal_material = 2131296302;
// aapt resource value: 0x7f09002f
public static int abc_button_padding_vertical_material = 2131296303;
// aapt resource value: 0x7f090030
public static int abc_cascading_menus_min_smallest_width = 2131296304;
// aapt resource value: 0x7f090011
public static int abc_config_prefDialogWidth = 2131296273;
// aapt resource value: 0x7f090031
public static int abc_control_corner_material = 2131296305;
// aapt resource value: 0x7f090032
public static int abc_control_inset_material = 2131296306;
// aapt resource value: 0x7f090033
public static int abc_control_padding_material = 2131296307;
// aapt resource value: 0x7f090012
public static int abc_dialog_fixed_height_major = 2131296274;
// aapt resource value: 0x7f090013
public static int abc_dialog_fixed_height_minor = 2131296275;
// aapt resource value: 0x7f090014
public static int abc_dialog_fixed_width_major = 2131296276;
// aapt resource value: 0x7f090015
public static int abc_dialog_fixed_width_minor = 2131296277;
// aapt resource value: 0x7f090034
public static int abc_dialog_list_padding_bottom_no_buttons = 2131296308;
// aapt resource value: 0x7f090035
public static int abc_dialog_list_padding_top_no_title = 2131296309;
// aapt resource value: 0x7f090016
public static int abc_dialog_min_width_major = 2131296278;
// aapt resource value: 0x7f090017
public static int abc_dialog_min_width_minor = 2131296279;
// aapt resource value: 0x7f090036
public static int abc_dialog_padding_material = 2131296310;
// aapt resource value: 0x7f090037
public static int abc_dialog_padding_top_material = 2131296311;
// aapt resource value: 0x7f090038
public static int abc_dialog_title_divider_material = 2131296312;
// aapt resource value: 0x7f090039
public static int abc_disabled_alpha_material_dark = 2131296313;
// aapt resource value: 0x7f09003a
public static int abc_disabled_alpha_material_light = 2131296314;
// aapt resource value: 0x7f09003b
public static int abc_dropdownitem_icon_width = 2131296315;
// aapt resource value: 0x7f09003c
public static int abc_dropdownitem_text_padding_left = 2131296316;
// aapt resource value: 0x7f09003d
public static int abc_dropdownitem_text_padding_right = 2131296317;
// aapt resource value: 0x7f09003e
public static int abc_edit_text_inset_bottom_material = 2131296318;
// aapt resource value: 0x7f09003f
public static int abc_edit_text_inset_horizontal_material = 2131296319;
// aapt resource value: 0x7f090040
public static int abc_edit_text_inset_top_material = 2131296320;
// aapt resource value: 0x7f090041
public static int abc_floating_window_z = 2131296321;
// aapt resource value: 0x7f090042
public static int abc_list_item_padding_horizontal_material = 2131296322;
// aapt resource value: 0x7f090043
public static int abc_panel_menu_list_width = 2131296323;
// aapt resource value: 0x7f090044
public static int abc_progress_bar_height_material = 2131296324;
// aapt resource value: 0x7f090045
public static int abc_search_view_preferred_height = 2131296325;
// aapt resource value: 0x7f090046
public static int abc_search_view_preferred_width = 2131296326;
// aapt resource value: 0x7f090047
public static int abc_seekbar_track_background_height_material = 2131296327;
// aapt resource value: 0x7f090048
public static int abc_seekbar_track_progress_height_material = 2131296328;
// aapt resource value: 0x7f090049
public static int abc_select_dialog_padding_start_material = 2131296329;
// aapt resource value: 0x7f09001d
public static int abc_switch_padding = 2131296285;
// aapt resource value: 0x7f09004a
public static int abc_text_size_body_1_material = 2131296330;
// aapt resource value: 0x7f09004b
public static int abc_text_size_body_2_material = 2131296331;
// aapt resource value: 0x7f09004c
public static int abc_text_size_button_material = 2131296332;
// aapt resource value: 0x7f09004d
public static int abc_text_size_caption_material = 2131296333;
// aapt resource value: 0x7f09004e
public static int abc_text_size_display_1_material = 2131296334;
// aapt resource value: 0x7f09004f
public static int abc_text_size_display_2_material = 2131296335;
// aapt resource value: 0x7f090050
public static int abc_text_size_display_3_material = 2131296336;
// aapt resource value: 0x7f090051
public static int abc_text_size_display_4_material = 2131296337;
// aapt resource value: 0x7f090052
public static int abc_text_size_headline_material = 2131296338;
// aapt resource value: 0x7f090053
public static int abc_text_size_large_material = 2131296339;
// aapt resource value: 0x7f090054
public static int abc_text_size_medium_material = 2131296340;
// aapt resource value: 0x7f090055
public static int abc_text_size_menu_header_material = 2131296341;
// aapt resource value: 0x7f090056
public static int abc_text_size_menu_material = 2131296342;
// aapt resource value: 0x7f090057
public static int abc_text_size_small_material = 2131296343;
// aapt resource value: 0x7f090058
public static int abc_text_size_subhead_material = 2131296344;
// aapt resource value: 0x7f09000f
public static int abc_text_size_subtitle_material_toolbar = 2131296271;
// aapt resource value: 0x7f090059
public static int abc_text_size_title_material = 2131296345;
// aapt resource value: 0x7f090010
public static int abc_text_size_title_material_toolbar = 2131296272;
// aapt resource value: 0x7f090000
public static int cardview_compat_inset_shadow = 2131296256;
// aapt resource value: 0x7f090001
public static int cardview_default_elevation = 2131296257;
// aapt resource value: 0x7f090002
public static int cardview_default_radius = 2131296258;
// aapt resource value: 0x7f090076
public static int design_appbar_elevation = 2131296374;
// aapt resource value: 0x7f090077
public static int design_bottom_navigation_active_item_max_width = 2131296375;
// aapt resource value: 0x7f090078
public static int design_bottom_navigation_active_text_size = 2131296376;
// aapt resource value: 0x7f090079
public static int design_bottom_navigation_elevation = 2131296377;
// aapt resource value: 0x7f09007a
public static int design_bottom_navigation_height = 2131296378;
// aapt resource value: 0x7f09007b
public static int design_bottom_navigation_item_max_width = 2131296379;
// aapt resource value: 0x7f09007c
public static int design_bottom_navigation_item_min_width = 2131296380;
// aapt resource value: 0x7f09007d
public static int design_bottom_navigation_margin = 2131296381;
// aapt resource value: 0x7f09007e
public static int design_bottom_navigation_shadow_height = 2131296382;
// aapt resource value: 0x7f09007f
public static int design_bottom_navigation_text_size = 2131296383;
// aapt resource value: 0x7f090080
public static int design_bottom_sheet_modal_elevation = 2131296384;
// aapt resource value: 0x7f090081
public static int design_bottom_sheet_peek_height_min = 2131296385;
// aapt resource value: 0x7f090082
public static int design_fab_border_width = 2131296386;
// aapt resource value: 0x7f090083
public static int design_fab_elevation = 2131296387;
// aapt resource value: 0x7f090084
public static int design_fab_image_size = 2131296388;
// aapt resource value: 0x7f090085
public static int design_fab_size_mini = 2131296389;
// aapt resource value: 0x7f090086
public static int design_fab_size_normal = 2131296390;
// aapt resource value: 0x7f090087
public static int design_fab_translation_z_pressed = 2131296391;
// aapt resource value: 0x7f090088
public static int design_navigation_elevation = 2131296392;
// aapt resource value: 0x7f090089
public static int design_navigation_icon_padding = 2131296393;
// aapt resource value: 0x7f09008a
public static int design_navigation_icon_size = 2131296394;
// aapt resource value: 0x7f09006e
public static int design_navigation_max_width = 2131296366;
// aapt resource value: 0x7f09008b
public static int design_navigation_padding_bottom = 2131296395;
// aapt resource value: 0x7f09008c
public static int design_navigation_separator_vertical_padding = 2131296396;
// aapt resource value: 0x7f09006f
public static int design_snackbar_action_inline_max_width = 2131296367;
// aapt resource value: 0x7f090070
public static int design_snackbar_background_corner_radius = 2131296368;
// aapt resource value: 0x7f09008d
public static int design_snackbar_elevation = 2131296397;
// aapt resource value: 0x7f090071
public static int design_snackbar_extra_spacing_horizontal = 2131296369;
// aapt resource value: 0x7f090072
public static int design_snackbar_max_width = 2131296370;
// aapt resource value: 0x7f090073
public static int design_snackbar_min_width = 2131296371;
// aapt resource value: 0x7f09008e
public static int design_snackbar_padding_horizontal = 2131296398;
// aapt resource value: 0x7f09008f
public static int design_snackbar_padding_vertical = 2131296399;
// aapt resource value: 0x7f090074
public static int design_snackbar_padding_vertical_2lines = 2131296372;
// aapt resource value: 0x7f090090
public static int design_snackbar_text_size = 2131296400;
// aapt resource value: 0x7f090091
public static int design_tab_max_width = 2131296401;
// aapt resource value: 0x7f090075
public static int design_tab_scrollable_min_width = 2131296373;
// aapt resource value: 0x7f090092
public static int design_tab_text_size = 2131296402;
// aapt resource value: 0x7f090093
public static int design_tab_text_size_2line = 2131296403;
// aapt resource value: 0x7f09005a
public static int disabled_alpha_material_dark = 2131296346;
// aapt resource value: 0x7f09005b
public static int disabled_alpha_material_light = 2131296347;
// aapt resource value: 0x7f09005c
public static int highlight_alpha_material_colored = 2131296348;
// aapt resource value: 0x7f09005d
public static int highlight_alpha_material_dark = 2131296349;
// aapt resource value: 0x7f09005e
public static int highlight_alpha_material_light = 2131296350;
// aapt resource value: 0x7f09005f
public static int hint_alpha_material_dark = 2131296351;
// aapt resource value: 0x7f090060
public static int hint_alpha_material_light = 2131296352;
// aapt resource value: 0x7f090061
public static int hint_pressed_alpha_material_dark = 2131296353;
// aapt resource value: 0x7f090062
public static int hint_pressed_alpha_material_light = 2131296354;
// aapt resource value: 0x7f090003
public static int item_touch_helper_max_drag_scroll_per_frame = 2131296259;
// aapt resource value: 0x7f090004
public static int item_touch_helper_swipe_escape_max_velocity = 2131296260;
// aapt resource value: 0x7f090005
public static int item_touch_helper_swipe_escape_velocity = 2131296261;
// aapt resource value: 0x7f090006
public static int mr_controller_volume_group_list_item_height = 2131296262;
// aapt resource value: 0x7f090007
public static int mr_controller_volume_group_list_item_icon_size = 2131296263;
// aapt resource value: 0x7f090008
public static int mr_controller_volume_group_list_max_height = 2131296264;
// aapt resource value: 0x7f09000b
public static int mr_controller_volume_group_list_padding_top = 2131296267;
// aapt resource value: 0x7f090009
public static int mr_dialog_fixed_width_major = 2131296265;
// aapt resource value: 0x7f09000a
public static int mr_dialog_fixed_width_minor = 2131296266;
// aapt resource value: 0x7f090063
public static int notification_action_icon_size = 2131296355;
// aapt resource value: 0x7f090064
public static int notification_action_text_size = 2131296356;
// aapt resource value: 0x7f090065
public static int notification_big_circle_margin = 2131296357;
// aapt resource value: 0x7f09001e
public static int notification_content_margin_start = 2131296286;
// aapt resource value: 0x7f090066
public static int notification_large_icon_height = 2131296358;
// aapt resource value: 0x7f090067
public static int notification_large_icon_width = 2131296359;
// aapt resource value: 0x7f09001f
public static int notification_main_column_padding_top = 2131296287;
// aapt resource value: 0x7f090020
public static int notification_media_narrow_margin = 2131296288;
// aapt resource value: 0x7f090068
public static int notification_right_icon_size = 2131296360;
// aapt resource value: 0x7f09001c
public static int notification_right_side_padding_top = 2131296284;
// aapt resource value: 0x7f090069
public static int notification_small_icon_background_padding = 2131296361;
// aapt resource value: 0x7f09006a
public static int notification_small_icon_size_as_large = 2131296362;
// aapt resource value: 0x7f09006b
public static int notification_subtext_size = 2131296363;
// aapt resource value: 0x7f09006c
public static int notification_top_pad = 2131296364;
// aapt resource value: 0x7f09006d
public static int notification_top_pad_large_text = 2131296365;
static Dimension()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Dimension()
{
}
}
public partial class Drawable
{
// aapt resource value: 0x7f020000
public static int abc_ab_share_pack_mtrl_alpha = 2130837504;
// aapt resource value: 0x7f020001
public static int abc_action_bar_item_background_material = 2130837505;
// aapt resource value: 0x7f020002
public static int abc_btn_borderless_material = 2130837506;
// aapt resource value: 0x7f020003
public static int abc_btn_check_material = 2130837507;
// aapt resource value: 0x7f020004
public static int abc_btn_check_to_on_mtrl_000 = 2130837508;
// aapt resource value: 0x7f020005
public static int abc_btn_check_to_on_mtrl_015 = 2130837509;
// aapt resource value: 0x7f020006
public static int abc_btn_colored_material = 2130837510;
// aapt resource value: 0x7f020007
public static int abc_btn_default_mtrl_shape = 2130837511;
// aapt resource value: 0x7f020008
public static int abc_btn_radio_material = 2130837512;
// aapt resource value: 0x7f020009
public static int abc_btn_radio_to_on_mtrl_000 = 2130837513;
// aapt resource value: 0x7f02000a
public static int abc_btn_radio_to_on_mtrl_015 = 2130837514;
// aapt resource value: 0x7f02000b
public static int abc_btn_switch_to_on_mtrl_00001 = 2130837515;
// aapt resource value: 0x7f02000c
public static int abc_btn_switch_to_on_mtrl_00012 = 2130837516;
// aapt resource value: 0x7f02000d
public static int abc_cab_background_internal_bg = 2130837517;
// aapt resource value: 0x7f02000e
public static int abc_cab_background_top_material = 2130837518;
// aapt resource value: 0x7f02000f
public static int abc_cab_background_top_mtrl_alpha = 2130837519;
// aapt resource value: 0x7f020010
public static int abc_control_background_material = 2130837520;
// aapt resource value: 0x7f020011
public static int abc_dialog_material_background = 2130837521;
// aapt resource value: 0x7f020012
public static int abc_edit_text_material = 2130837522;
// aapt resource value: 0x7f020013
public static int abc_ic_ab_back_material = 2130837523;
// aapt resource value: 0x7f020014
public static int abc_ic_arrow_drop_right_black_24dp = 2130837524;
// aapt resource value: 0x7f020015
public static int abc_ic_clear_material = 2130837525;
// aapt resource value: 0x7f020016
public static int abc_ic_commit_search_api_mtrl_alpha = 2130837526;
// aapt resource value: 0x7f020017
public static int abc_ic_go_search_api_material = 2130837527;
// aapt resource value: 0x7f020018
public static int abc_ic_menu_copy_mtrl_am_alpha = 2130837528;
// aapt resource value: 0x7f020019
public static int abc_ic_menu_cut_mtrl_alpha = 2130837529;
// aapt resource value: 0x7f02001a
public static int abc_ic_menu_overflow_material = 2130837530;
// aapt resource value: 0x7f02001b
public static int abc_ic_menu_paste_mtrl_am_alpha = 2130837531;
// aapt resource value: 0x7f02001c
public static int abc_ic_menu_selectall_mtrl_alpha = 2130837532;
// aapt resource value: 0x7f02001d
public static int abc_ic_menu_share_mtrl_alpha = 2130837533;
// aapt resource value: 0x7f02001e
public static int abc_ic_search_api_material = 2130837534;
// aapt resource value: 0x7f02001f
public static int abc_ic_star_black_16dp = 2130837535;
// aapt resource value: 0x7f020020
public static int abc_ic_star_black_36dp = 2130837536;
// aapt resource value: 0x7f020021
public static int abc_ic_star_black_48dp = 2130837537;
// aapt resource value: 0x7f020022
public static int abc_ic_star_half_black_16dp = 2130837538;
// aapt resource value: 0x7f020023
public static int abc_ic_star_half_black_36dp = 2130837539;
// aapt resource value: 0x7f020024
public static int abc_ic_star_half_black_48dp = 2130837540;
// aapt resource value: 0x7f020025
public static int abc_ic_voice_search_api_material = 2130837541;
// aapt resource value: 0x7f020026
public static int abc_item_background_holo_dark = 2130837542;
// aapt resource value: 0x7f020027
public static int abc_item_background_holo_light = 2130837543;
// aapt resource value: 0x7f020028
public static int abc_list_divider_mtrl_alpha = 2130837544;
// aapt resource value: 0x7f020029
public static int abc_list_focused_holo = 2130837545;
// aapt resource value: 0x7f02002a
public static int abc_list_longpressed_holo = 2130837546;
// aapt resource value: 0x7f02002b
public static int abc_list_pressed_holo_dark = 2130837547;
// aapt resource value: 0x7f02002c
public static int abc_list_pressed_holo_light = 2130837548;
// aapt resource value: 0x7f02002d
public static int abc_list_selector_background_transition_holo_dark = 2130837549;
// aapt resource value: 0x7f02002e
public static int abc_list_selector_background_transition_holo_light = 2130837550;
// aapt resource value: 0x7f02002f
public static int abc_list_selector_disabled_holo_dark = 2130837551;
// aapt resource value: 0x7f020030
public static int abc_list_selector_disabled_holo_light = 2130837552;
// aapt resource value: 0x7f020031
public static int abc_list_selector_holo_dark = 2130837553;
// aapt resource value: 0x7f020032
public static int abc_list_selector_holo_light = 2130837554;
// aapt resource value: 0x7f020033
public static int abc_menu_hardkey_panel_mtrl_mult = 2130837555;
// aapt resource value: 0x7f020034
public static int abc_popup_background_mtrl_mult = 2130837556;
// aapt resource value: 0x7f020035
public static int abc_ratingbar_indicator_material = 2130837557;
// aapt resource value: 0x7f020036
public static int abc_ratingbar_material = 2130837558;
// aapt resource value: 0x7f020037
public static int abc_ratingbar_small_material = 2130837559;
// aapt resource value: 0x7f020038
public static int abc_scrubber_control_off_mtrl_alpha = 2130837560;
// aapt resource value: 0x7f020039
public static int abc_scrubber_control_to_pressed_mtrl_000 = 2130837561;
// aapt resource value: 0x7f02003a
public static int abc_scrubber_control_to_pressed_mtrl_005 = 2130837562;
// aapt resource value: 0x7f02003b
public static int abc_scrubber_primary_mtrl_alpha = 2130837563;
// aapt resource value: 0x7f02003c
public static int abc_scrubber_track_mtrl_alpha = 2130837564;
// aapt resource value: 0x7f02003d
public static int abc_seekbar_thumb_material = 2130837565;
// aapt resource value: 0x7f02003e
public static int abc_seekbar_tick_mark_material = 2130837566;
// aapt resource value: 0x7f02003f
public static int abc_seekbar_track_material = 2130837567;
// aapt resource value: 0x7f020040
public static int abc_spinner_mtrl_am_alpha = 2130837568;
// aapt resource value: 0x7f020041
public static int abc_spinner_textfield_background_material = 2130837569;
// aapt resource value: 0x7f020042
public static int abc_switch_thumb_material = 2130837570;
// aapt resource value: 0x7f020043
public static int abc_switch_track_mtrl_alpha = 2130837571;
// aapt resource value: 0x7f020044
public static int abc_tab_indicator_material = 2130837572;
// aapt resource value: 0x7f020045
public static int abc_tab_indicator_mtrl_alpha = 2130837573;
// aapt resource value: 0x7f020046
public static int abc_text_cursor_material = 2130837574;
// aapt resource value: 0x7f020047
public static int abc_text_select_handle_left_mtrl_dark = 2130837575;
// aapt resource value: 0x7f020048
public static int abc_text_select_handle_left_mtrl_light = 2130837576;
// aapt resource value: 0x7f020049
public static int abc_text_select_handle_middle_mtrl_dark = 2130837577;
// aapt resource value: 0x7f02004a
public static int abc_text_select_handle_middle_mtrl_light = 2130837578;
// aapt resource value: 0x7f02004b
public static int abc_text_select_handle_right_mtrl_dark = 2130837579;
// aapt resource value: 0x7f02004c
public static int abc_text_select_handle_right_mtrl_light = 2130837580;
// aapt resource value: 0x7f02004d
public static int abc_textfield_activated_mtrl_alpha = 2130837581;
// aapt resource value: 0x7f02004e
public static int abc_textfield_default_mtrl_alpha = 2130837582;
// aapt resource value: 0x7f02004f
public static int abc_textfield_search_activated_mtrl_alpha = 2130837583;
// aapt resource value: 0x7f020050
public static int abc_textfield_search_default_mtrl_alpha = 2130837584;
// aapt resource value: 0x7f020051
public static int abc_textfield_search_material = 2130837585;
// aapt resource value: 0x7f020052
public static int abc_vector_test = 2130837586;
// aapt resource value: 0x7f020053
public static int avd_hide_password = 2130837587;
// aapt resource value: 0x7f020122
public static int avd_hide_password_1 = 2130837794;
// aapt resource value: 0x7f020123
public static int avd_hide_password_2 = 2130837795;
// aapt resource value: 0x7f020124
public static int avd_hide_password_3 = 2130837796;
// aapt resource value: 0x7f020054
public static int avd_show_password = 2130837588;
// aapt resource value: 0x7f020125
public static int avd_show_password_1 = 2130837797;
// aapt resource value: 0x7f020126
public static int avd_show_password_2 = 2130837798;
// aapt resource value: 0x7f020127
public static int avd_show_password_3 = 2130837799;
// aapt resource value: 0x7f020055
public static int common_full_open_on_phone = 2130837589;
// aapt resource value: 0x7f020056
public static int common_google_signin_btn_icon_dark = 2130837590;
// aapt resource value: 0x7f020057
public static int common_google_signin_btn_icon_dark_disabled = 2130837591;
// aapt resource value: 0x7f020058
public static int common_google_signin_btn_icon_dark_focused = 2130837592;
// aapt resource value: 0x7f020059
public static int common_google_signin_btn_icon_dark_normal = 2130837593;
// aapt resource value: 0x7f02005a
public static int common_google_signin_btn_icon_dark_pressed = 2130837594;
// aapt resource value: 0x7f02005b
public static int common_google_signin_btn_icon_light = 2130837595;
// aapt resource value: 0x7f02005c
public static int common_google_signin_btn_icon_light_disabled = 2130837596;
// aapt resource value: 0x7f02005d
public static int common_google_signin_btn_icon_light_focused = 2130837597;
// aapt resource value: 0x7f02005e
public static int common_google_signin_btn_icon_light_normal = 2130837598;
// aapt resource value: 0x7f02005f
public static int common_google_signin_btn_icon_light_pressed = 2130837599;
// aapt resource value: 0x7f020060
public static int common_google_signin_btn_text_dark = 2130837600;
// aapt resource value: 0x7f020061
public static int common_google_signin_btn_text_dark_disabled = 2130837601;
// aapt resource value: 0x7f020062
public static int common_google_signin_btn_text_dark_focused = 2130837602;
// aapt resource value: 0x7f020063
public static int common_google_signin_btn_text_dark_normal = 2130837603;
// aapt resource value: 0x7f020064
public static int common_google_signin_btn_text_dark_pressed = 2130837604;
// aapt resource value: 0x7f020065
public static int common_google_signin_btn_text_light = 2130837605;
// aapt resource value: 0x7f020066
public static int common_google_signin_btn_text_light_disabled = 2130837606;
// aapt resource value: 0x7f020067
public static int common_google_signin_btn_text_light_focused = 2130837607;
// aapt resource value: 0x7f020068
public static int common_google_signin_btn_text_light_normal = 2130837608;
// aapt resource value: 0x7f020069
public static int common_google_signin_btn_text_light_pressed = 2130837609;
// aapt resource value: 0x7f02006a
public static int design_bottom_navigation_item_background = 2130837610;
// aapt resource value: 0x7f02006b
public static int design_fab_background = 2130837611;
// aapt resource value: 0x7f02006c
public static int design_ic_visibility = 2130837612;
// aapt resource value: 0x7f02006d
public static int design_ic_visibility_off = 2130837613;
// aapt resource value: 0x7f02006e
public static int design_password_eye = 2130837614;
// aapt resource value: 0x7f02006f
public static int design_snackbar_background = 2130837615;
// aapt resource value: 0x7f020070
public static int ic_audiotrack_dark = 2130837616;
// aapt resource value: 0x7f020071
public static int ic_audiotrack_light = 2130837617;
// aapt resource value: 0x7f020072
public static int ic_dialog_close_dark = 2130837618;
// aapt resource value: 0x7f020073
public static int ic_dialog_close_light = 2130837619;
// aapt resource value: 0x7f020074
public static int ic_group_collapse_00 = 2130837620;
// aapt resource value: 0x7f020075
public static int ic_group_collapse_01 = 2130837621;
// aapt resource value: 0x7f020076
public static int ic_group_collapse_02 = 2130837622;
// aapt resource value: 0x7f020077
public static int ic_group_collapse_03 = 2130837623;
// aapt resource value: 0x7f020078
public static int ic_group_collapse_04 = 2130837624;
// aapt resource value: 0x7f020079
public static int ic_group_collapse_05 = 2130837625;
// aapt resource value: 0x7f02007a
public static int ic_group_collapse_06 = 2130837626;
// aapt resource value: 0x7f02007b
public static int ic_group_collapse_07 = 2130837627;
// aapt resource value: 0x7f02007c
public static int ic_group_collapse_08 = 2130837628;
// aapt resource value: 0x7f02007d
public static int ic_group_collapse_09 = 2130837629;
// aapt resource value: 0x7f02007e
public static int ic_group_collapse_10 = 2130837630;
// aapt resource value: 0x7f02007f
public static int ic_group_collapse_11 = 2130837631;
// aapt resource value: 0x7f020080
public static int ic_group_collapse_12 = 2130837632;
// aapt resource value: 0x7f020081
public static int ic_group_collapse_13 = 2130837633;
// aapt resource value: 0x7f020082
public static int ic_group_collapse_14 = 2130837634;
// aapt resource value: 0x7f020083
public static int ic_group_collapse_15 = 2130837635;
// aapt resource value: 0x7f020084
public static int ic_group_expand_00 = 2130837636;
// aapt resource value: 0x7f020085
public static int ic_group_expand_01 = 2130837637;
// aapt resource value: 0x7f020086
public static int ic_group_expand_02 = 2130837638;
// aapt resource value: 0x7f020087
public static int ic_group_expand_03 = 2130837639;
// aapt resource value: 0x7f020088
public static int ic_group_expand_04 = 2130837640;
// aapt resource value: 0x7f020089
public static int ic_group_expand_05 = 2130837641;
// aapt resource value: 0x7f02008a
public static int ic_group_expand_06 = 2130837642;
// aapt resource value: 0x7f02008b
public static int ic_group_expand_07 = 2130837643;
// aapt resource value: 0x7f02008c
public static int ic_group_expand_08 = 2130837644;
// aapt resource value: 0x7f02008d
public static int ic_group_expand_09 = 2130837645;
// aapt resource value: 0x7f02008e
public static int ic_group_expand_10 = 2130837646;
// aapt resource value: 0x7f02008f
public static int ic_group_expand_11 = 2130837647;
// aapt resource value: 0x7f020090
public static int ic_group_expand_12 = 2130837648;
// aapt resource value: 0x7f020091
public static int ic_group_expand_13 = 2130837649;
// aapt resource value: 0x7f020092
public static int ic_group_expand_14 = 2130837650;
// aapt resource value: 0x7f020093
public static int ic_group_expand_15 = 2130837651;
// aapt resource value: 0x7f020094
public static int ic_media_pause_dark = 2130837652;
// aapt resource value: 0x7f020095
public static int ic_media_pause_light = 2130837653;
// aapt resource value: 0x7f020096
public static int ic_media_play_dark = 2130837654;
// aapt resource value: 0x7f020097
public static int ic_media_play_light = 2130837655;
// aapt resource value: 0x7f020098
public static int ic_media_stop_dark = 2130837656;
// aapt resource value: 0x7f020099
public static int ic_media_stop_light = 2130837657;
// aapt resource value: 0x7f02009a
public static int ic_mr_button_connected_00_dark = 2130837658;
// aapt resource value: 0x7f02009b
public static int ic_mr_button_connected_00_light = 2130837659;
// aapt resource value: 0x7f02009c
public static int ic_mr_button_connected_01_dark = 2130837660;
// aapt resource value: 0x7f02009d
public static int ic_mr_button_connected_01_light = 2130837661;
// aapt resource value: 0x7f02009e
public static int ic_mr_button_connected_02_dark = 2130837662;
// aapt resource value: 0x7f02009f
public static int ic_mr_button_connected_02_light = 2130837663;
// aapt resource value: 0x7f0200a0
public static int ic_mr_button_connected_03_dark = 2130837664;
// aapt resource value: 0x7f0200a1
public static int ic_mr_button_connected_03_light = 2130837665;
// aapt resource value: 0x7f0200a2
public static int ic_mr_button_connected_04_dark = 2130837666;
// aapt resource value: 0x7f0200a3
public static int ic_mr_button_connected_04_light = 2130837667;
// aapt resource value: 0x7f0200a4
public static int ic_mr_button_connected_05_dark = 2130837668;
// aapt resource value: 0x7f0200a5
public static int ic_mr_button_connected_05_light = 2130837669;
// aapt resource value: 0x7f0200a6
public static int ic_mr_button_connected_06_dark = 2130837670;
// aapt resource value: 0x7f0200a7
public static int ic_mr_button_connected_06_light = 2130837671;
// aapt resource value: 0x7f0200a8
public static int ic_mr_button_connected_07_dark = 2130837672;
// aapt resource value: 0x7f0200a9
public static int ic_mr_button_connected_07_light = 2130837673;
// aapt resource value: 0x7f0200aa
public static int ic_mr_button_connected_08_dark = 2130837674;
// aapt resource value: 0x7f0200ab
public static int ic_mr_button_connected_08_light = 2130837675;
// aapt resource value: 0x7f0200ac
public static int ic_mr_button_connected_09_dark = 2130837676;
// aapt resource value: 0x7f0200ad
public static int ic_mr_button_connected_09_light = 2130837677;
// aapt resource value: 0x7f0200ae
public static int ic_mr_button_connected_10_dark = 2130837678;
// aapt resource value: 0x7f0200af
public static int ic_mr_button_connected_10_light = 2130837679;
// aapt resource value: 0x7f0200b0
public static int ic_mr_button_connected_11_dark = 2130837680;
// aapt resource value: 0x7f0200b1
public static int ic_mr_button_connected_11_light = 2130837681;
// aapt resource value: 0x7f0200b2
public static int ic_mr_button_connected_12_dark = 2130837682;
// aapt resource value: 0x7f0200b3
public static int ic_mr_button_connected_12_light = 2130837683;
// aapt resource value: 0x7f0200b4
public static int ic_mr_button_connected_13_dark = 2130837684;
// aapt resource value: 0x7f0200b5
public static int ic_mr_button_connected_13_light = 2130837685;
// aapt resource value: 0x7f0200b6
public static int ic_mr_button_connected_14_dark = 2130837686;
// aapt resource value: 0x7f0200b7
public static int ic_mr_button_connected_14_light = 2130837687;
// aapt resource value: 0x7f0200b8
public static int ic_mr_button_connected_15_dark = 2130837688;
// aapt resource value: 0x7f0200b9
public static int ic_mr_button_connected_15_light = 2130837689;
// aapt resource value: 0x7f0200ba
public static int ic_mr_button_connected_16_dark = 2130837690;
// aapt resource value: 0x7f0200bb
public static int ic_mr_button_connected_16_light = 2130837691;
// aapt resource value: 0x7f0200bc
public static int ic_mr_button_connected_17_dark = 2130837692;
// aapt resource value: 0x7f0200bd
public static int ic_mr_button_connected_17_light = 2130837693;
// aapt resource value: 0x7f0200be
public static int ic_mr_button_connected_18_dark = 2130837694;
// aapt resource value: 0x7f0200bf
public static int ic_mr_button_connected_18_light = 2130837695;
// aapt resource value: 0x7f0200c0
public static int ic_mr_button_connected_19_dark = 2130837696;
// aapt resource value: 0x7f0200c1
public static int ic_mr_button_connected_19_light = 2130837697;
// aapt resource value: 0x7f0200c2
public static int ic_mr_button_connected_20_dark = 2130837698;
// aapt resource value: 0x7f0200c3
public static int ic_mr_button_connected_20_light = 2130837699;
// aapt resource value: 0x7f0200c4
public static int ic_mr_button_connected_21_dark = 2130837700;
// aapt resource value: 0x7f0200c5
public static int ic_mr_button_connected_21_light = 2130837701;
// aapt resource value: 0x7f0200c6
public static int ic_mr_button_connected_22_dark = 2130837702;
// aapt resource value: 0x7f0200c7
public static int ic_mr_button_connected_22_light = 2130837703;
// aapt resource value: 0x7f0200c8
public static int ic_mr_button_connecting_00_dark = 2130837704;
// aapt resource value: 0x7f0200c9
public static int ic_mr_button_connecting_00_light = 2130837705;
// aapt resource value: 0x7f0200ca
public static int ic_mr_button_connecting_01_dark = 2130837706;
// aapt resource value: 0x7f0200cb
public static int ic_mr_button_connecting_01_light = 2130837707;
// aapt resource value: 0x7f0200cc
public static int ic_mr_button_connecting_02_dark = 2130837708;
// aapt resource value: 0x7f0200cd
public static int ic_mr_button_connecting_02_light = 2130837709;
// aapt resource value: 0x7f0200ce
public static int ic_mr_button_connecting_03_dark = 2130837710;
// aapt resource value: 0x7f0200cf
public static int ic_mr_button_connecting_03_light = 2130837711;
// aapt resource value: 0x7f0200d0
public static int ic_mr_button_connecting_04_dark = 2130837712;
// aapt resource value: 0x7f0200d1
public static int ic_mr_button_connecting_04_light = 2130837713;
// aapt resource value: 0x7f0200d2
public static int ic_mr_button_connecting_05_dark = 2130837714;
// aapt resource value: 0x7f0200d3
public static int ic_mr_button_connecting_05_light = 2130837715;
// aapt resource value: 0x7f0200d4
public static int ic_mr_button_connecting_06_dark = 2130837716;
// aapt resource value: 0x7f0200d5
public static int ic_mr_button_connecting_06_light = 2130837717;
// aapt resource value: 0x7f0200d6
public static int ic_mr_button_connecting_07_dark = 2130837718;
// aapt resource value: 0x7f0200d7
public static int ic_mr_button_connecting_07_light = 2130837719;
// aapt resource value: 0x7f0200d8
public static int ic_mr_button_connecting_08_dark = 2130837720;
// aapt resource value: 0x7f0200d9
public static int ic_mr_button_connecting_08_light = 2130837721;
// aapt resource value: 0x7f0200da
public static int ic_mr_button_connecting_09_dark = 2130837722;
// aapt resource value: 0x7f0200db
public static int ic_mr_button_connecting_09_light = 2130837723;
// aapt resource value: 0x7f0200dc
public static int ic_mr_button_connecting_10_dark = 2130837724;
// aapt resource value: 0x7f0200dd
public static int ic_mr_button_connecting_10_light = 2130837725;
// aapt resource value: 0x7f0200de
public static int ic_mr_button_connecting_11_dark = 2130837726;
// aapt resource value: 0x7f0200df
public static int ic_mr_button_connecting_11_light = 2130837727;
// aapt resource value: 0x7f0200e0
public static int ic_mr_button_connecting_12_dark = 2130837728;
// aapt resource value: 0x7f0200e1
public static int ic_mr_button_connecting_12_light = 2130837729;
// aapt resource value: 0x7f0200e2
public static int ic_mr_button_connecting_13_dark = 2130837730;
// aapt resource value: 0x7f0200e3
public static int ic_mr_button_connecting_13_light = 2130837731;
// aapt resource value: 0x7f0200e4
public static int ic_mr_button_connecting_14_dark = 2130837732;
// aapt resource value: 0x7f0200e5
public static int ic_mr_button_connecting_14_light = 2130837733;
// aapt resource value: 0x7f0200e6
public static int ic_mr_button_connecting_15_dark = 2130837734;
// aapt resource value: 0x7f0200e7
public static int ic_mr_button_connecting_15_light = 2130837735;
// aapt resource value: 0x7f0200e8
public static int ic_mr_button_connecting_16_dark = 2130837736;
// aapt resource value: 0x7f0200e9
public static int ic_mr_button_connecting_16_light = 2130837737;
// aapt resource value: 0x7f0200ea
public static int ic_mr_button_connecting_17_dark = 2130837738;
// aapt resource value: 0x7f0200eb
public static int ic_mr_button_connecting_17_light = 2130837739;
// aapt resource value: 0x7f0200ec
public static int ic_mr_button_connecting_18_dark = 2130837740;
// aapt resource value: 0x7f0200ed
public static int ic_mr_button_connecting_18_light = 2130837741;
// aapt resource value: 0x7f0200ee
public static int ic_mr_button_connecting_19_dark = 2130837742;
// aapt resource value: 0x7f0200ef
public static int ic_mr_button_connecting_19_light = 2130837743;
// aapt resource value: 0x7f0200f0
public static int ic_mr_button_connecting_20_dark = 2130837744;
// aapt resource value: 0x7f0200f1
public static int ic_mr_button_connecting_20_light = 2130837745;
// aapt resource value: 0x7f0200f2
public static int ic_mr_button_connecting_21_dark = 2130837746;
// aapt resource value: 0x7f0200f3
public static int ic_mr_button_connecting_21_light = 2130837747;
// aapt resource value: 0x7f0200f4
public static int ic_mr_button_connecting_22_dark = 2130837748;
// aapt resource value: 0x7f0200f5
public static int ic_mr_button_connecting_22_light = 2130837749;
// aapt resource value: 0x7f0200f6
public static int ic_mr_button_disabled_dark = 2130837750;
// aapt resource value: 0x7f0200f7
public static int ic_mr_button_disabled_light = 2130837751;
// aapt resource value: 0x7f0200f8
public static int ic_mr_button_disconnected_dark = 2130837752;
// aapt resource value: 0x7f0200f9
public static int ic_mr_button_disconnected_light = 2130837753;
// aapt resource value: 0x7f0200fa
public static int ic_mr_button_grey = 2130837754;
// aapt resource value: 0x7f0200fb
public static int ic_vol_type_speaker_dark = 2130837755;
// aapt resource value: 0x7f0200fc
public static int ic_vol_type_speaker_group_dark = 2130837756;
// aapt resource value: 0x7f0200fd
public static int ic_vol_type_speaker_group_light = 2130837757;
// aapt resource value: 0x7f0200fe
public static int ic_vol_type_speaker_light = 2130837758;
// aapt resource value: 0x7f0200ff
public static int ic_vol_type_tv_dark = 2130837759;
// aapt resource value: 0x7f020100
public static int ic_vol_type_tv_light = 2130837760;
// aapt resource value: 0x7f020101
public static int mr_button_connected_dark = 2130837761;
// aapt resource value: 0x7f020102
public static int mr_button_connected_light = 2130837762;
// aapt resource value: 0x7f020103
public static int mr_button_connecting_dark = 2130837763;
// aapt resource value: 0x7f020104
public static int mr_button_connecting_light = 2130837764;
// aapt resource value: 0x7f020105
public static int mr_button_dark = 2130837765;
// aapt resource value: 0x7f020106
public static int mr_button_light = 2130837766;
// aapt resource value: 0x7f020107
public static int mr_dialog_close_dark = 2130837767;
// aapt resource value: 0x7f020108
public static int mr_dialog_close_light = 2130837768;
// aapt resource value: 0x7f020109
public static int mr_dialog_material_background_dark = 2130837769;
// aapt resource value: 0x7f02010a
public static int mr_dialog_material_background_light = 2130837770;
// aapt resource value: 0x7f02010b
public static int mr_group_collapse = 2130837771;
// aapt resource value: 0x7f02010c
public static int mr_group_expand = 2130837772;
// aapt resource value: 0x7f02010d
public static int mr_media_pause_dark = 2130837773;
// aapt resource value: 0x7f02010e
public static int mr_media_pause_light = 2130837774;
// aapt resource value: 0x7f02010f
public static int mr_media_play_dark = 2130837775;
// aapt resource value: 0x7f020110
public static int mr_media_play_light = 2130837776;
// aapt resource value: 0x7f020111
public static int mr_media_stop_dark = 2130837777;
// aapt resource value: 0x7f020112
public static int mr_media_stop_light = 2130837778;
// aapt resource value: 0x7f020113
public static int mr_vol_type_audiotrack_dark = 2130837779;
// aapt resource value: 0x7f020114
public static int mr_vol_type_audiotrack_light = 2130837780;
// aapt resource value: 0x7f020115
public static int navigation_empty_icon = 2130837781;
// aapt resource value: 0x7f020116
public static int notification_action_background = 2130837782;
// aapt resource value: 0x7f020117
public static int notification_bg = 2130837783;
// aapt resource value: 0x7f020118
public static int notification_bg_low = 2130837784;
// aapt resource value: 0x7f020119
public static int notification_bg_low_normal = 2130837785;
// aapt resource value: 0x7f02011a
public static int notification_bg_low_pressed = 2130837786;
// aapt resource value: 0x7f02011b
public static int notification_bg_normal = 2130837787;
// aapt resource value: 0x7f02011c
public static int notification_bg_normal_pressed = 2130837788;
// aapt resource value: 0x7f02011d
public static int notification_icon_background = 2130837789;
// aapt resource value: 0x7f020120
public static int notification_template_icon_bg = 2130837792;
// aapt resource value: 0x7f020121
public static int notification_template_icon_low_bg = 2130837793;
// aapt resource value: 0x7f02011e
public static int notification_tile_bg = 2130837790;
// aapt resource value: 0x7f02011f
public static int notify_panel_notification_icon_bg = 2130837791;
static Drawable()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Drawable()
{
}
}
public partial class Id
{
// aapt resource value: 0x7f0c00a8
public static int action0 = 2131493032;
// aapt resource value: 0x7f0c006e
public static int action_bar = 2131492974;
// aapt resource value: 0x7f0c0001
public static int action_bar_activity_content = 2131492865;
// aapt resource value: 0x7f0c006d
public static int action_bar_container = 2131492973;
// aapt resource value: 0x7f0c0069
public static int action_bar_root = 2131492969;
// aapt resource value: 0x7f0c0002
public static int action_bar_spinner = 2131492866;
// aapt resource value: 0x7f0c004c
public static int action_bar_subtitle = 2131492940;
// aapt resource value: 0x7f0c004b
public static int action_bar_title = 2131492939;
// aapt resource value: 0x7f0c00a5
public static int action_container = 2131493029;
// aapt resource value: 0x7f0c006f
public static int action_context_bar = 2131492975;
// aapt resource value: 0x7f0c00ac
public static int action_divider = 2131493036;
// aapt resource value: 0x7f0c00a6
public static int action_image = 2131493030;
// aapt resource value: 0x7f0c0003
public static int action_menu_divider = 2131492867;
// aapt resource value: 0x7f0c0004
public static int action_menu_presenter = 2131492868;
// aapt resource value: 0x7f0c006b
public static int action_mode_bar = 2131492971;
// aapt resource value: 0x7f0c006a
public static int action_mode_bar_stub = 2131492970;
// aapt resource value: 0x7f0c004d
public static int action_mode_close_button = 2131492941;
// aapt resource value: 0x7f0c00a7
public static int action_text = 2131493031;
// aapt resource value: 0x7f0c00b5
public static int actions = 2131493045;
// aapt resource value: 0x7f0c004e
public static int activity_chooser_view_content = 2131492942;
// aapt resource value: 0x7f0c0029
public static int add = 2131492905;
// aapt resource value: 0x7f0c0014
public static int adjust_height = 2131492884;
// aapt resource value: 0x7f0c0015
public static int adjust_width = 2131492885;
// aapt resource value: 0x7f0c0062
public static int alertTitle = 2131492962;
// aapt resource value: 0x7f0c0047
public static int all = 2131492935;
// aapt resource value: 0x7f0c002e
public static int always = 2131492910;
// aapt resource value: 0x7f0c0019
public static int auto = 2131492889;
// aapt resource value: 0x7f0c002b
public static int beginning = 2131492907;
// aapt resource value: 0x7f0c0033
public static int bottom = 2131492915;
// aapt resource value: 0x7f0c0055
public static int buttonPanel = 2131492949;
// aapt resource value: 0x7f0c00a9
public static int cancel_action = 2131493033;
// aapt resource value: 0x7f0c003a
public static int center = 2131492922;
// aapt resource value: 0x7f0c003b
public static int center_horizontal = 2131492923;
// aapt resource value: 0x7f0c003c
public static int center_vertical = 2131492924;
// aapt resource value: 0x7f0c0065
public static int checkbox = 2131492965;
// aapt resource value: 0x7f0c00b1
public static int chronometer = 2131493041;
// aapt resource value: 0x7f0c0043
public static int clip_horizontal = 2131492931;
// aapt resource value: 0x7f0c0044
public static int clip_vertical = 2131492932;
// aapt resource value: 0x7f0c002f
public static int collapseActionView = 2131492911;
// aapt resource value: 0x7f0c007f
public static int container = 2131492991;
// aapt resource value: 0x7f0c0058
public static int contentPanel = 2131492952;
// aapt resource value: 0x7f0c0080
public static int coordinator = 2131492992;
// aapt resource value: 0x7f0c005f
public static int custom = 2131492959;
// aapt resource value: 0x7f0c005e
public static int customPanel = 2131492958;
// aapt resource value: 0x7f0c001a
public static int dark = 2131492890;
// aapt resource value: 0x7f0c006c
public static int decor_content_parent = 2131492972;
// aapt resource value: 0x7f0c0051
public static int default_activity_button = 2131492945;
// aapt resource value: 0x7f0c0082
public static int design_bottom_sheet = 2131492994;
// aapt resource value: 0x7f0c0089
public static int design_menu_item_action_area = 2131493001;
// aapt resource value: 0x7f0c0088
public static int design_menu_item_action_area_stub = 2131493000;
// aapt resource value: 0x7f0c0087
public static int design_menu_item_text = 2131492999;
// aapt resource value: 0x7f0c0086
public static int design_navigation_view = 2131492998;
// aapt resource value: 0x7f0c001e
public static int disableHome = 2131492894;
// aapt resource value: 0x7f0c0070
public static int edit_query = 2131492976;
// aapt resource value: 0x7f0c002c
public static int end = 2131492908;
// aapt resource value: 0x7f0c00bb
public static int end_padder = 2131493051;
// aapt resource value: 0x7f0c0035
public static int enterAlways = 2131492917;
// aapt resource value: 0x7f0c0036
public static int enterAlwaysCollapsed = 2131492918;
// aapt resource value: 0x7f0c0037
public static int exitUntilCollapsed = 2131492919;
// aapt resource value: 0x7f0c004f
public static int expand_activities_button = 2131492943;
// aapt resource value: 0x7f0c0064
public static int expanded_menu = 2131492964;
// aapt resource value: 0x7f0c0045
public static int fill = 2131492933;
// aapt resource value: 0x7f0c0046
public static int fill_horizontal = 2131492934;
// aapt resource value: 0x7f0c003d
public static int fill_vertical = 2131492925;
// aapt resource value: 0x7f0c0049
public static int @fixed = 2131492937;
// aapt resource value: 0x7f0c0005
public static int home = 2131492869;
// aapt resource value: 0x7f0c001f
public static int homeAsUp = 2131492895;
// aapt resource value: 0x7f0c000f
public static int hybrid = 2131492879;
// aapt resource value: 0x7f0c0053
public static int icon = 2131492947;
// aapt resource value: 0x7f0c00b6
public static int icon_group = 2131493046;
// aapt resource value: 0x7f0c0016
public static int icon_only = 2131492886;
// aapt resource value: 0x7f0c0030
public static int ifRoom = 2131492912;
// aapt resource value: 0x7f0c0050
public static int image = 2131492944;
// aapt resource value: 0x7f0c00b2
public static int info = 2131493042;
// aapt resource value: 0x7f0c0000
public static int item_touch_helper_previous_elevation = 2131492864;
// aapt resource value: 0x7f0c007e
public static int largeLabel = 2131492990;
// aapt resource value: 0x7f0c003e
public static int left = 2131492926;
// aapt resource value: 0x7f0c001b
public static int light = 2131492891;
// aapt resource value: 0x7f0c00b7
public static int line1 = 2131493047;
// aapt resource value: 0x7f0c00b9
public static int line3 = 2131493049;
// aapt resource value: 0x7f0c001c
public static int listMode = 2131492892;
// aapt resource value: 0x7f0c0052
public static int list_item = 2131492946;
// aapt resource value: 0x7f0c00bd
public static int masked = 2131493053;
// aapt resource value: 0x7f0c00ab
public static int media_actions = 2131493035;
// aapt resource value: 0x7f0c002d
public static int middle = 2131492909;
// aapt resource value: 0x7f0c0048
public static int mini = 2131492936;
// aapt resource value: 0x7f0c0097
public static int mr_art = 2131493015;
// aapt resource value: 0x7f0c008c
public static int mr_chooser_list = 2131493004;
// aapt resource value: 0x7f0c008f
public static int mr_chooser_route_desc = 2131493007;
// aapt resource value: 0x7f0c008d
public static int mr_chooser_route_icon = 2131493005;
// aapt resource value: 0x7f0c008e
public static int mr_chooser_route_name = 2131493006;
// aapt resource value: 0x7f0c008b
public static int mr_chooser_title = 2131493003;
// aapt resource value: 0x7f0c0094
public static int mr_close = 2131493012;
// aapt resource value: 0x7f0c009a
public static int mr_control_divider = 2131493018;
// aapt resource value: 0x7f0c00a0
public static int mr_control_playback_ctrl = 2131493024;
// aapt resource value: 0x7f0c00a3
public static int mr_control_subtitle = 2131493027;
// aapt resource value: 0x7f0c00a2
public static int mr_control_title = 2131493026;
// aapt resource value: 0x7f0c00a1
public static int mr_control_title_container = 2131493025;
// aapt resource value: 0x7f0c0095
public static int mr_custom_control = 2131493013;
// aapt resource value: 0x7f0c0096
public static int mr_default_control = 2131493014;
// aapt resource value: 0x7f0c0091
public static int mr_dialog_area = 2131493009;
// aapt resource value: 0x7f0c0090
public static int mr_expandable_area = 2131493008;
// aapt resource value: 0x7f0c00a4
public static int mr_group_expand_collapse = 2131493028;
// aapt resource value: 0x7f0c0098
public static int mr_media_main_control = 2131493016;
// aapt resource value: 0x7f0c0093
public static int mr_name = 2131493011;
// aapt resource value: 0x7f0c0099
public static int mr_playback_control = 2131493017;
// aapt resource value: 0x7f0c0092
public static int mr_title_bar = 2131493010;
// aapt resource value: 0x7f0c009b
public static int mr_volume_control = 2131493019;
// aapt resource value: 0x7f0c009c
public static int mr_volume_group_list = 2131493020;
// aapt resource value: 0x7f0c009e
public static int mr_volume_item_icon = 2131493022;
// aapt resource value: 0x7f0c009f
public static int mr_volume_slider = 2131493023;
// aapt resource value: 0x7f0c0024
public static int multiply = 2131492900;
// aapt resource value: 0x7f0c0085
public static int navigation_header_container = 2131492997;
// aapt resource value: 0x7f0c0031
public static int never = 2131492913;
// aapt resource value: 0x7f0c0010
public static int none = 2131492880;
// aapt resource value: 0x7f0c0011
public static int normal = 2131492881;
// aapt resource value: 0x7f0c00b4
public static int notification_background = 2131493044;
// aapt resource value: 0x7f0c00ae
public static int notification_main_column = 2131493038;
// aapt resource value: 0x7f0c00ad
public static int notification_main_column_container = 2131493037;
// aapt resource value: 0x7f0c0041
public static int parallax = 2131492929;
// aapt resource value: 0x7f0c0057
public static int parentPanel = 2131492951;
// aapt resource value: 0x7f0c0042
public static int pin = 2131492930;
// aapt resource value: 0x7f0c0006
public static int progress_circular = 2131492870;
// aapt resource value: 0x7f0c0007
public static int progress_horizontal = 2131492871;
// aapt resource value: 0x7f0c0067
public static int radio = 2131492967;
// aapt resource value: 0x7f0c003f
public static int right = 2131492927;
// aapt resource value: 0x7f0c00b3
public static int right_icon = 2131493043;
// aapt resource value: 0x7f0c00af
public static int right_side = 2131493039;
// aapt resource value: 0x7f0c0012
public static int satellite = 2131492882;
// aapt resource value: 0x7f0c0025
public static int screen = 2131492901;
// aapt resource value: 0x7f0c0038
public static int scroll = 2131492920;
// aapt resource value: 0x7f0c005d
public static int scrollIndicatorDown = 2131492957;
// aapt resource value: 0x7f0c0059
public static int scrollIndicatorUp = 2131492953;
// aapt resource value: 0x7f0c005a
public static int scrollView = 2131492954;
// aapt resource value: 0x7f0c004a
public static int scrollable = 2131492938;
// aapt resource value: 0x7f0c0072
public static int search_badge = 2131492978;
// aapt resource value: 0x7f0c0071
public static int search_bar = 2131492977;
// aapt resource value: 0x7f0c0073
public static int search_button = 2131492979;
// aapt resource value: 0x7f0c0078
public static int search_close_btn = 2131492984;
// aapt resource value: 0x7f0c0074
public static int search_edit_frame = 2131492980;
// aapt resource value: 0x7f0c007a
public static int search_go_btn = 2131492986;
// aapt resource value: 0x7f0c0075
public static int search_mag_icon = 2131492981;
// aapt resource value: 0x7f0c0076
public static int search_plate = 2131492982;
// aapt resource value: 0x7f0c0077
public static int search_src_text = 2131492983;
// aapt resource value: 0x7f0c007b
public static int search_voice_btn = 2131492987;
// aapt resource value: 0x7f0c007c
public static int select_dialog_listview = 2131492988;
// aapt resource value: 0x7f0c0066
public static int shortcut = 2131492966;
// aapt resource value: 0x7f0c0020
public static int showCustom = 2131492896;
// aapt resource value: 0x7f0c0021
public static int showHome = 2131492897;
// aapt resource value: 0x7f0c0022
public static int showTitle = 2131492898;
// aapt resource value: 0x7f0c007d
public static int smallLabel = 2131492989;
// aapt resource value: 0x7f0c0084
public static int snackbar_action = 2131492996;
// aapt resource value: 0x7f0c0083
public static int snackbar_text = 2131492995;
// aapt resource value: 0x7f0c0039
public static int snap = 2131492921;
// aapt resource value: 0x7f0c0056
public static int spacer = 2131492950;
// aapt resource value: 0x7f0c0008
public static int split_action_bar = 2131492872;
// aapt resource value: 0x7f0c0026
public static int src_atop = 2131492902;
// aapt resource value: 0x7f0c0027
public static int src_in = 2131492903;
// aapt resource value: 0x7f0c0028
public static int src_over = 2131492904;
// aapt resource value: 0x7f0c0017
public static int standard = 2131492887;
// aapt resource value: 0x7f0c0040
public static int start = 2131492928;
// aapt resource value: 0x7f0c00aa
public static int status_bar_latest_event_content = 2131493034;
// aapt resource value: 0x7f0c0068
public static int submenuarrow = 2131492968;
// aapt resource value: 0x7f0c0079
public static int submit_area = 2131492985;
// aapt resource value: 0x7f0c001d
public static int tabMode = 2131492893;
// aapt resource value: 0x7f0c0013
public static int terrain = 2131492883;
// aapt resource value: 0x7f0c00ba
public static int text = 2131493050;
// aapt resource value: 0x7f0c00b8
public static int text2 = 2131493048;
// aapt resource value: 0x7f0c005c
public static int textSpacerNoButtons = 2131492956;
// aapt resource value: 0x7f0c005b
public static int textSpacerNoTitle = 2131492955;
// aapt resource value: 0x7f0c008a
public static int text_input_password_toggle = 2131493002;
// aapt resource value: 0x7f0c000c
public static int textinput_counter = 2131492876;
// aapt resource value: 0x7f0c000d
public static int textinput_error = 2131492877;
// aapt resource value: 0x7f0c00b0
public static int time = 2131493040;
// aapt resource value: 0x7f0c0054
public static int title = 2131492948;
// aapt resource value: 0x7f0c0063
public static int titleDividerNoCustom = 2131492963;
// aapt resource value: 0x7f0c0061
public static int title_template = 2131492961;
// aapt resource value: 0x7f0c0034
public static int top = 2131492916;
// aapt resource value: 0x7f0c0060
public static int topPanel = 2131492960;
// aapt resource value: 0x7f0c0081
public static int touch_outside = 2131492993;
// aapt resource value: 0x7f0c000a
public static int transition_current_scene = 2131492874;
// aapt resource value: 0x7f0c000b
public static int transition_scene_layoutid_cache = 2131492875;
// aapt resource value: 0x7f0c0009
public static int up = 2131492873;
// aapt resource value: 0x7f0c0023
public static int useLogo = 2131492899;
// aapt resource value: 0x7f0c000e
public static int view_offset_helper = 2131492878;
// aapt resource value: 0x7f0c00bc
public static int visible = 2131493052;
// aapt resource value: 0x7f0c009d
public static int volume_item_container = 2131493021;
// aapt resource value: 0x7f0c0018
public static int wide = 2131492888;
// aapt resource value: 0x7f0c0032
public static int withText = 2131492914;
// aapt resource value: 0x7f0c002a
public static int wrap_content = 2131492906;
static Id()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Id()
{
}
}
public partial class Integer
{
// aapt resource value: 0x7f0b0004
public static int abc_config_activityDefaultDur = 2131427332;
// aapt resource value: 0x7f0b0005
public static int abc_config_activityShortDur = 2131427333;
// aapt resource value: 0x7f0b0009
public static int app_bar_elevation_anim_duration = 2131427337;
// aapt resource value: 0x7f0b000a
public static int bottom_sheet_slide_duration = 2131427338;
// aapt resource value: 0x7f0b0006
public static int cancel_button_image_alpha = 2131427334;
// aapt resource value: 0x7f0b0008
public static int design_snackbar_text_max_lines = 2131427336;
// aapt resource value: 0x7f0b0000
public static int google_play_services_version = 2131427328;
// aapt resource value: 0x7f0b000b
public static int hide_password_duration = 2131427339;
// aapt resource value: 0x7f0b0001
public static int mr_controller_volume_group_list_animation_duration_ms = 2131427329;
// aapt resource value: 0x7f0b0002
public static int mr_controller_volume_group_list_fade_in_duration_ms = 2131427330;
// aapt resource value: 0x7f0b0003
public static int mr_controller_volume_group_list_fade_out_duration_ms = 2131427331;
// aapt resource value: 0x7f0b000c
public static int show_password_duration = 2131427340;
// aapt resource value: 0x7f0b0007
public static int status_bar_notification_info_maxnum = 2131427335;
static Integer()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Integer()
{
}
}
public partial class Interpolator
{
// aapt resource value: 0x7f060000
public static int mr_fast_out_slow_in = 2131099648;
// aapt resource value: 0x7f060001
public static int mr_linear_out_slow_in = 2131099649;
static Interpolator()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Interpolator()
{
}
}
public partial class Layout
{
// aapt resource value: 0x7f030000
public static int abc_action_bar_title_item = 2130903040;
// aapt resource value: 0x7f030001
public static int abc_action_bar_up_container = 2130903041;
// aapt resource value: 0x7f030002
public static int abc_action_bar_view_list_nav_layout = 2130903042;
// aapt resource value: 0x7f030003
public static int abc_action_menu_item_layout = 2130903043;
// aapt resource value: 0x7f030004
public static int abc_action_menu_layout = 2130903044;
// aapt resource value: 0x7f030005
public static int abc_action_mode_bar = 2130903045;
// aapt resource value: 0x7f030006
public static int abc_action_mode_close_item_material = 2130903046;
// aapt resource value: 0x7f030007
public static int abc_activity_chooser_view = 2130903047;
// aapt resource value: 0x7f030008
public static int abc_activity_chooser_view_list_item = 2130903048;
// aapt resource value: 0x7f030009
public static int abc_alert_dialog_button_bar_material = 2130903049;
// aapt resource value: 0x7f03000a
public static int abc_alert_dialog_material = 2130903050;
// aapt resource value: 0x7f03000b
public static int abc_alert_dialog_title_material = 2130903051;
// aapt resource value: 0x7f03000c
public static int abc_dialog_title_material = 2130903052;
// aapt resource value: 0x7f03000d
public static int abc_expanded_menu_layout = 2130903053;
// aapt resource value: 0x7f03000e
public static int abc_list_menu_item_checkbox = 2130903054;
// aapt resource value: 0x7f03000f
public static int abc_list_menu_item_icon = 2130903055;
// aapt resource value: 0x7f030010
public static int abc_list_menu_item_layout = 2130903056;
// aapt resource value: 0x7f030011
public static int abc_list_menu_item_radio = 2130903057;
// aapt resource value: 0x7f030012
public static int abc_popup_menu_header_item_layout = 2130903058;
// aapt resource value: 0x7f030013
public static int abc_popup_menu_item_layout = 2130903059;
// aapt resource value: 0x7f030014
public static int abc_screen_content_include = 2130903060;
// aapt resource value: 0x7f030015
public static int abc_screen_simple = 2130903061;
// aapt resource value: 0x7f030016
public static int abc_screen_simple_overlay_action_mode = 2130903062;
// aapt resource value: 0x7f030017
public static int abc_screen_toolbar = 2130903063;
// aapt resource value: 0x7f030018
public static int abc_search_dropdown_item_icons_2line = 2130903064;
// aapt resource value: 0x7f030019
public static int abc_search_view = 2130903065;
// aapt resource value: 0x7f03001a
public static int abc_select_dialog_material = 2130903066;
// aapt resource value: 0x7f03001b
public static int design_bottom_navigation_item = 2130903067;
// aapt resource value: 0x7f03001c
public static int design_bottom_sheet_dialog = 2130903068;
// aapt resource value: 0x7f03001d
public static int design_layout_snackbar = 2130903069;
// aapt resource value: 0x7f03001e
public static int design_layout_snackbar_include = 2130903070;
// aapt resource value: 0x7f03001f
public static int design_layout_tab_icon = 2130903071;
// aapt resource value: 0x7f030020
public static int design_layout_tab_text = 2130903072;
// aapt resource value: 0x7f030021
public static int design_menu_item_action_area = 2130903073;
// aapt resource value: 0x7f030022
public static int design_navigation_item = 2130903074;
// aapt resource value: 0x7f030023
public static int design_navigation_item_header = 2130903075;
// aapt resource value: 0x7f030024
public static int design_navigation_item_separator = 2130903076;
// aapt resource value: 0x7f030025
public static int design_navigation_item_subheader = 2130903077;
// aapt resource value: 0x7f030026
public static int design_navigation_menu = 2130903078;
// aapt resource value: 0x7f030027
public static int design_navigation_menu_item = 2130903079;
// aapt resource value: 0x7f030028
public static int design_text_input_password_icon = 2130903080;
// aapt resource value: 0x7f030029
public static int mr_chooser_dialog = 2130903081;
// aapt resource value: 0x7f03002a
public static int mr_chooser_list_item = 2130903082;
// aapt resource value: 0x7f03002b
public static int mr_controller_material_dialog_b = 2130903083;
// aapt resource value: 0x7f03002c
public static int mr_controller_volume_item = 2130903084;
// aapt resource value: 0x7f03002d
public static int mr_playback_control = 2130903085;
// aapt resource value: 0x7f03002e
public static int mr_volume_control = 2130903086;
// aapt resource value: 0x7f03002f
public static int notification_action = 2130903087;
// aapt resource value: 0x7f030030
public static int notification_action_tombstone = 2130903088;
// aapt resource value: 0x7f030031
public static int notification_media_action = 2130903089;
// aapt resource value: 0x7f030032
public static int notification_media_cancel_action = 2130903090;
// aapt resource value: 0x7f030033
public static int notification_template_big_media = 2130903091;
// aapt resource value: 0x7f030034
public static int notification_template_big_media_custom = 2130903092;
// aapt resource value: 0x7f030035
public static int notification_template_big_media_narrow = 2130903093;
// aapt resource value: 0x7f030036
public static int notification_template_big_media_narrow_custom = 2130903094;
// aapt resource value: 0x7f030037
public static int notification_template_custom_big = 2130903095;
// aapt resource value: 0x7f030038
public static int notification_template_icon_group = 2130903096;
// aapt resource value: 0x7f030039
public static int notification_template_lines_media = 2130903097;
// aapt resource value: 0x7f03003a
public static int notification_template_media = 2130903098;
// aapt resource value: 0x7f03003b
public static int notification_template_media_custom = 2130903099;
// aapt resource value: 0x7f03003c
public static int notification_template_part_chronometer = 2130903100;
// aapt resource value: 0x7f03003d
public static int notification_template_part_time = 2130903101;
// aapt resource value: 0x7f03003e
public static int select_dialog_item_material = 2130903102;
// aapt resource value: 0x7f03003f
public static int select_dialog_multichoice_material = 2130903103;
// aapt resource value: 0x7f030040
public static int select_dialog_singlechoice_material = 2130903104;
// aapt resource value: 0x7f030041
public static int support_simple_spinner_dropdown_item = 2130903105;
static Layout()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Layout()
{
}
}
public partial class String
{
// aapt resource value: 0x7f0a0050
public static int ApplicationName = 2131361872;
// aapt resource value: 0x7f0a004f
public static int Hello = 2131361871;
// aapt resource value: 0x7f0a0026
public static int abc_action_bar_home_description = 2131361830;
// aapt resource value: 0x7f0a0027
public static int abc_action_bar_home_description_format = 2131361831;
// aapt resource value: 0x7f0a0028
public static int abc_action_bar_home_subtitle_description_format = 2131361832;
// aapt resource value: 0x7f0a0029
public static int abc_action_bar_up_description = 2131361833;
// aapt resource value: 0x7f0a002a
public static int abc_action_menu_overflow_description = 2131361834;
// aapt resource value: 0x7f0a002b
public static int abc_action_mode_done = 2131361835;
// aapt resource value: 0x7f0a002c
public static int abc_activity_chooser_view_see_all = 2131361836;
// aapt resource value: 0x7f0a002d
public static int abc_activitychooserview_choose_application = 2131361837;
// aapt resource value: 0x7f0a002e
public static int abc_capital_off = 2131361838;
// aapt resource value: 0x7f0a002f
public static int abc_capital_on = 2131361839;
// aapt resource value: 0x7f0a003b
public static int abc_font_family_body_1_material = 2131361851;
// aapt resource value: 0x7f0a003c
public static int abc_font_family_body_2_material = 2131361852;
// aapt resource value: 0x7f0a003d
public static int abc_font_family_button_material = 2131361853;
// aapt resource value: 0x7f0a003e
public static int abc_font_family_caption_material = 2131361854;
// aapt resource value: 0x7f0a003f
public static int abc_font_family_display_1_material = 2131361855;
// aapt resource value: 0x7f0a0040
public static int abc_font_family_display_2_material = 2131361856;
// aapt resource value: 0x7f0a0041
public static int abc_font_family_display_3_material = 2131361857;
// aapt resource value: 0x7f0a0042
public static int abc_font_family_display_4_material = 2131361858;
// aapt resource value: 0x7f0a0043
public static int abc_font_family_headline_material = 2131361859;
// aapt resource value: 0x7f0a0044
public static int abc_font_family_menu_material = 2131361860;
// aapt resource value: 0x7f0a0045
public static int abc_font_family_subhead_material = 2131361861;
// aapt resource value: 0x7f0a0046
public static int abc_font_family_title_material = 2131361862;
// aapt resource value: 0x7f0a0030
public static int abc_search_hint = 2131361840;
// aapt resource value: 0x7f0a0031
public static int abc_searchview_description_clear = 2131361841;
// aapt resource value: 0x7f0a0032
public static int abc_searchview_description_query = 2131361842;
// aapt resource value: 0x7f0a0033
public static int abc_searchview_description_search = 2131361843;
// aapt resource value: 0x7f0a0034
public static int abc_searchview_description_submit = 2131361844;
// aapt resource value: 0x7f0a0035
public static int abc_searchview_description_voice = 2131361845;
// aapt resource value: 0x7f0a0036
public static int abc_shareactionprovider_share_with = 2131361846;
// aapt resource value: 0x7f0a0037
public static int abc_shareactionprovider_share_with_application = 2131361847;
// aapt resource value: 0x7f0a0038
public static int abc_toolbar_collapse_description = 2131361848;
// aapt resource value: 0x7f0a0047
public static int appbar_scrolling_view_behavior = 2131361863;
// aapt resource value: 0x7f0a0048
public static int bottom_sheet_behavior = 2131361864;
// aapt resource value: 0x7f0a0049
public static int character_counter_pattern = 2131361865;
// aapt resource value: 0x7f0a0000
public static int common_google_play_services_enable_button = 2131361792;
// aapt resource value: 0x7f0a0001
public static int common_google_play_services_enable_text = 2131361793;
// aapt resource value: 0x7f0a0002
public static int common_google_play_services_enable_title = 2131361794;
// aapt resource value: 0x7f0a0003
public static int common_google_play_services_install_button = 2131361795;
// aapt resource value: 0x7f0a0004
public static int common_google_play_services_install_text = 2131361796;
// aapt resource value: 0x7f0a0005
public static int common_google_play_services_install_title = 2131361797;
// aapt resource value: 0x7f0a0006
public static int common_google_play_services_notification_ticker = 2131361798;
// aapt resource value: 0x7f0a0010
public static int common_google_play_services_unknown_issue = 2131361808;
// aapt resource value: 0x7f0a0007
public static int common_google_play_services_unsupported_text = 2131361799;
// aapt resource value: 0x7f0a0008
public static int common_google_play_services_update_button = 2131361800;
// aapt resource value: 0x7f0a0009
public static int common_google_play_services_update_text = 2131361801;
// aapt resource value: 0x7f0a000a
public static int common_google_play_services_update_title = 2131361802;
// aapt resource value: 0x7f0a000b
public static int common_google_play_services_updating_text = 2131361803;
// aapt resource value: 0x7f0a000c
public static int common_google_play_services_wear_update_text = 2131361804;
// aapt resource value: 0x7f0a000d
public static int common_open_on_phone = 2131361805;
// aapt resource value: 0x7f0a000e
public static int common_signin_button_text = 2131361806;
// aapt resource value: 0x7f0a000f
public static int common_signin_button_text_long = 2131361807;
// aapt resource value: 0x7f0a0011
public static int mr_button_content_description = 2131361809;
// aapt resource value: 0x7f0a0012
public static int mr_cast_button_connected = 2131361810;
// aapt resource value: 0x7f0a0013
public static int mr_cast_button_connecting = 2131361811;
// aapt resource value: 0x7f0a0014
public static int mr_cast_button_disconnected = 2131361812;
// aapt resource value: 0x7f0a0015
public static int mr_chooser_searching = 2131361813;
// aapt resource value: 0x7f0a0016
public static int mr_chooser_title = 2131361814;
// aapt resource value: 0x7f0a0017
public static int mr_controller_album_art = 2131361815;
// aapt resource value: 0x7f0a0018
public static int mr_controller_casting_screen = 2131361816;
// aapt resource value: 0x7f0a0019
public static int mr_controller_close_description = 2131361817;
// aapt resource value: 0x7f0a001a
public static int mr_controller_collapse_group = 2131361818;
// aapt resource value: 0x7f0a001b
public static int mr_controller_disconnect = 2131361819;
// aapt resource value: 0x7f0a001c
public static int mr_controller_expand_group = 2131361820;
// aapt resource value: 0x7f0a001d
public static int mr_controller_no_info_available = 2131361821;
// aapt resource value: 0x7f0a001e
public static int mr_controller_no_media_selected = 2131361822;
// aapt resource value: 0x7f0a001f
public static int mr_controller_pause = 2131361823;
// aapt resource value: 0x7f0a0020
public static int mr_controller_play = 2131361824;
// aapt resource value: 0x7f0a0025
public static int mr_controller_stop = 2131361829;
// aapt resource value: 0x7f0a0021
public static int mr_controller_stop_casting = 2131361825;
// aapt resource value: 0x7f0a0022
public static int mr_controller_volume_slider = 2131361826;
// aapt resource value: 0x7f0a0023
public static int mr_system_route_name = 2131361827;
// aapt resource value: 0x7f0a0024
public static int mr_user_route_category_name = 2131361828;
// aapt resource value: 0x7f0a004a
public static int password_toggle_content_description = 2131361866;
// aapt resource value: 0x7f0a004b
public static int path_password_eye = 2131361867;
// aapt resource value: 0x7f0a004c
public static int path_password_eye_mask_strike_through = 2131361868;
// aapt resource value: 0x7f0a004d
public static int path_password_eye_mask_visible = 2131361869;
// aapt resource value: 0x7f0a004e
public static int path_password_strike_through = 2131361870;
// aapt resource value: 0x7f0a0039
public static int search_menu_title = 2131361849;
// aapt resource value: 0x7f0a003a
public static int status_bar_notification_info_overflow = 2131361850;
static String()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private String()
{
}
}
public partial class Style
{
// aapt resource value: 0x7f0700ae
public static int AlertDialog_AppCompat = 2131165358;
// aapt resource value: 0x7f0700af
public static int AlertDialog_AppCompat_Light = 2131165359;
// aapt resource value: 0x7f0700b0
public static int Animation_AppCompat_Dialog = 2131165360;
// aapt resource value: 0x7f0700b1
public static int Animation_AppCompat_DropDownUp = 2131165361;
// aapt resource value: 0x7f070170
public static int Animation_Design_BottomSheetDialog = 2131165552;
// aapt resource value: 0x7f0700b2
public static int Base_AlertDialog_AppCompat = 2131165362;
// aapt resource value: 0x7f0700b3
public static int Base_AlertDialog_AppCompat_Light = 2131165363;
// aapt resource value: 0x7f0700b4
public static int Base_Animation_AppCompat_Dialog = 2131165364;
// aapt resource value: 0x7f0700b5
public static int Base_Animation_AppCompat_DropDownUp = 2131165365;
// aapt resource value: 0x7f070001
public static int Base_CardView = 2131165185;
// aapt resource value: 0x7f0700b6
public static int Base_DialogWindowTitle_AppCompat = 2131165366;
// aapt resource value: 0x7f0700b7
public static int Base_DialogWindowTitleBackground_AppCompat = 2131165367;
// aapt resource value: 0x7f07004e
public static int Base_TextAppearance_AppCompat = 2131165262;
// aapt resource value: 0x7f07004f
public static int Base_TextAppearance_AppCompat_Body1 = 2131165263;
// aapt resource value: 0x7f070050
public static int Base_TextAppearance_AppCompat_Body2 = 2131165264;
// aapt resource value: 0x7f070036
public static int Base_TextAppearance_AppCompat_Button = 2131165238;
// aapt resource value: 0x7f070051
public static int Base_TextAppearance_AppCompat_Caption = 2131165265;
// aapt resource value: 0x7f070052
public static int Base_TextAppearance_AppCompat_Display1 = 2131165266;
// aapt resource value: 0x7f070053
public static int Base_TextAppearance_AppCompat_Display2 = 2131165267;
// aapt resource value: 0x7f070054
public static int Base_TextAppearance_AppCompat_Display3 = 2131165268;
// aapt resource value: 0x7f070055
public static int Base_TextAppearance_AppCompat_Display4 = 2131165269;
// aapt resource value: 0x7f070056
public static int Base_TextAppearance_AppCompat_Headline = 2131165270;
// aapt resource value: 0x7f07001a
public static int Base_TextAppearance_AppCompat_Inverse = 2131165210;
// aapt resource value: 0x7f070057
public static int Base_TextAppearance_AppCompat_Large = 2131165271;
// aapt resource value: 0x7f07001b
public static int Base_TextAppearance_AppCompat_Large_Inverse = 2131165211;
// aapt resource value: 0x7f070058
public static int Base_TextAppearance_AppCompat_Light_Widget_PopupMenu_Large = 2131165272;
// aapt resource value: 0x7f070059
public static int Base_TextAppearance_AppCompat_Light_Widget_PopupMenu_Small = 2131165273;
// aapt resource value: 0x7f07005a
public static int Base_TextAppearance_AppCompat_Medium = 2131165274;
// aapt resource value: 0x7f07001c
public static int Base_TextAppearance_AppCompat_Medium_Inverse = 2131165212;
// aapt resource value: 0x7f07005b
public static int Base_TextAppearance_AppCompat_Menu = 2131165275;
// aapt resource value: 0x7f0700b8
public static int Base_TextAppearance_AppCompat_SearchResult = 2131165368;
// aapt resource value: 0x7f07005c
public static int Base_TextAppearance_AppCompat_SearchResult_Subtitle = 2131165276;
// aapt resource value: 0x7f07005d
public static int Base_TextAppearance_AppCompat_SearchResult_Title = 2131165277;
// aapt resource value: 0x7f07005e
public static int Base_TextAppearance_AppCompat_Small = 2131165278;
// aapt resource value: 0x7f07001d
public static int Base_TextAppearance_AppCompat_Small_Inverse = 2131165213;
// aapt resource value: 0x7f07005f
public static int Base_TextAppearance_AppCompat_Subhead = 2131165279;
// aapt resource value: 0x7f07001e
public static int Base_TextAppearance_AppCompat_Subhead_Inverse = 2131165214;
// aapt resource value: 0x7f070060
public static int Base_TextAppearance_AppCompat_Title = 2131165280;
// aapt resource value: 0x7f07001f
public static int Base_TextAppearance_AppCompat_Title_Inverse = 2131165215;
// aapt resource value: 0x7f0700a3
public static int Base_TextAppearance_AppCompat_Widget_ActionBar_Menu = 2131165347;
// aapt resource value: 0x7f070061
public static int Base_TextAppearance_AppCompat_Widget_ActionBar_Subtitle = 2131165281;
// aapt resource value: 0x7f070062
public static int Base_TextAppearance_AppCompat_Widget_ActionBar_Subtitle_Inverse = 2131165282;
// aapt resource value: 0x7f070063
public static int Base_TextAppearance_AppCompat_Widget_ActionBar_Title = 2131165283;
// aapt resource value: 0x7f070064
public static int Base_TextAppearance_AppCompat_Widget_ActionBar_Title_Inverse = 2131165284;
// aapt resource value: 0x7f070065
public static int Base_TextAppearance_AppCompat_Widget_ActionMode_Subtitle = 2131165285;
// aapt resource value: 0x7f070066
public static int Base_TextAppearance_AppCompat_Widget_ActionMode_Title = 2131165286;
// aapt resource value: 0x7f070067
public static int Base_TextAppearance_AppCompat_Widget_Button = 2131165287;
// aapt resource value: 0x7f0700aa
public static int Base_TextAppearance_AppCompat_Widget_Button_Borderless_Colored = 2131165354;
// aapt resource value: 0x7f0700ab
public static int Base_TextAppearance_AppCompat_Widget_Button_Colored = 2131165355;
// aapt resource value: 0x7f0700a4
public static int Base_TextAppearance_AppCompat_Widget_Button_Inverse = 2131165348;
// aapt resource value: 0x7f0700b9
public static int Base_TextAppearance_AppCompat_Widget_DropDownItem = 2131165369;
// aapt resource value: 0x7f070068
public static int Base_TextAppearance_AppCompat_Widget_PopupMenu_Header = 2131165288;
// aapt resource value: 0x7f070069
public static int Base_TextAppearance_AppCompat_Widget_PopupMenu_Large = 2131165289;
// aapt resource value: 0x7f07006a
public static int Base_TextAppearance_AppCompat_Widget_PopupMenu_Small = 2131165290;
// aapt resource value: 0x7f07006b
public static int Base_TextAppearance_AppCompat_Widget_Switch = 2131165291;
// aapt resource value: 0x7f07006c
public static int Base_TextAppearance_AppCompat_Widget_TextView_SpinnerItem = 2131165292;
// aapt resource value: 0x7f0700ba
public static int Base_TextAppearance_Widget_AppCompat_ExpandedMenu_Item = 2131165370;
// aapt resource value: 0x7f07006d
public static int Base_TextAppearance_Widget_AppCompat_Toolbar_Subtitle = 2131165293;
// aapt resource value: 0x7f07006e
public static int Base_TextAppearance_Widget_AppCompat_Toolbar_Title = 2131165294;
// aapt resource value: 0x7f07006f
public static int Base_Theme_AppCompat = 2131165295;
// aapt resource value: 0x7f0700bb
public static int Base_Theme_AppCompat_CompactMenu = 2131165371;
// aapt resource value: 0x7f070020
public static int Base_Theme_AppCompat_Dialog = 2131165216;
// aapt resource value: 0x7f070021
public static int Base_Theme_AppCompat_Dialog_Alert = 2131165217;
// aapt resource value: 0x7f0700bc
public static int Base_Theme_AppCompat_Dialog_FixedSize = 2131165372;
// aapt resource value: 0x7f070022
public static int Base_Theme_AppCompat_Dialog_MinWidth = 2131165218;
// aapt resource value: 0x7f070010
public static int Base_Theme_AppCompat_DialogWhenLarge = 2131165200;
// aapt resource value: 0x7f070070
public static int Base_Theme_AppCompat_Light = 2131165296;
// aapt resource value: 0x7f0700bd
public static int Base_Theme_AppCompat_Light_DarkActionBar = 2131165373;
// aapt resource value: 0x7f070023
public static int Base_Theme_AppCompat_Light_Dialog = 2131165219;
// aapt resource value: 0x7f070024
public static int Base_Theme_AppCompat_Light_Dialog_Alert = 2131165220;
// aapt resource value: 0x7f0700be
public static int Base_Theme_AppCompat_Light_Dialog_FixedSize = 2131165374;
// aapt resource value: 0x7f070025
public static int Base_Theme_AppCompat_Light_Dialog_MinWidth = 2131165221;
// aapt resource value: 0x7f070011
public static int Base_Theme_AppCompat_Light_DialogWhenLarge = 2131165201;
// aapt resource value: 0x7f0700bf
public static int Base_ThemeOverlay_AppCompat = 2131165375;
// aapt resource value: 0x7f0700c0
public static int Base_ThemeOverlay_AppCompat_ActionBar = 2131165376;
// aapt resource value: 0x7f0700c1
public static int Base_ThemeOverlay_AppCompat_Dark = 2131165377;
// aapt resource value: 0x7f0700c2
public static int Base_ThemeOverlay_AppCompat_Dark_ActionBar = 2131165378;
// aapt resource value: 0x7f070026
public static int Base_ThemeOverlay_AppCompat_Dialog = 2131165222;
// aapt resource value: 0x7f070027
public static int Base_ThemeOverlay_AppCompat_Dialog_Alert = 2131165223;
// aapt resource value: 0x7f0700c3
public static int Base_ThemeOverlay_AppCompat_Light = 2131165379;
// aapt resource value: 0x7f070028
public static int Base_V11_Theme_AppCompat_Dialog = 2131165224;
// aapt resource value: 0x7f070029
public static int Base_V11_Theme_AppCompat_Light_Dialog = 2131165225;
// aapt resource value: 0x7f07002a
public static int Base_V11_ThemeOverlay_AppCompat_Dialog = 2131165226;
// aapt resource value: 0x7f070032
public static int Base_V12_Widget_AppCompat_AutoCompleteTextView = 2131165234;
// aapt resource value: 0x7f070033
public static int Base_V12_Widget_AppCompat_EditText = 2131165235;
// aapt resource value: 0x7f070071
public static int Base_V21_Theme_AppCompat = 2131165297;
// aapt resource value: 0x7f070072
public static int Base_V21_Theme_AppCompat_Dialog = 2131165298;
// aapt resource value: 0x7f070073
public static int Base_V21_Theme_AppCompat_Light = 2131165299;
// aapt resource value: 0x7f070074
public static int Base_V21_Theme_AppCompat_Light_Dialog = 2131165300;
// aapt resource value: 0x7f070075
public static int Base_V21_ThemeOverlay_AppCompat_Dialog = 2131165301;
// aapt resource value: 0x7f0700a1
public static int Base_V22_Theme_AppCompat = 2131165345;
// aapt resource value: 0x7f0700a2
public static int Base_V22_Theme_AppCompat_Light = 2131165346;
// aapt resource value: 0x7f0700a5
public static int Base_V23_Theme_AppCompat = 2131165349;
// aapt resource value: 0x7f0700a6
public static int Base_V23_Theme_AppCompat_Light = 2131165350;
// aapt resource value: 0x7f0700c4
public static int Base_V7_Theme_AppCompat = 2131165380;
// aapt resource value: 0x7f0700c5
public static int Base_V7_Theme_AppCompat_Dialog = 2131165381;
// aapt resource value: 0x7f0700c6
public static int Base_V7_Theme_AppCompat_Light = 2131165382;
// aapt resource value: 0x7f0700c7
public static int Base_V7_Theme_AppCompat_Light_Dialog = 2131165383;
// aapt resource value: 0x7f0700c8
public static int Base_V7_ThemeOverlay_AppCompat_Dialog = 2131165384;
// aapt resource value: 0x7f0700c9
public static int Base_V7_Widget_AppCompat_AutoCompleteTextView = 2131165385;
// aapt resource value: 0x7f0700ca
public static int Base_V7_Widget_AppCompat_EditText = 2131165386;
// aapt resource value: 0x7f0700cb
public static int Base_Widget_AppCompat_ActionBar = 2131165387;
// aapt resource value: 0x7f0700cc
public static int Base_Widget_AppCompat_ActionBar_Solid = 2131165388;
// aapt resource value: 0x7f0700cd
public static int Base_Widget_AppCompat_ActionBar_TabBar = 2131165389;
// aapt resource value: 0x7f070076
public static int Base_Widget_AppCompat_ActionBar_TabText = 2131165302;
// aapt resource value: 0x7f070077
public static int Base_Widget_AppCompat_ActionBar_TabView = 2131165303;
// aapt resource value: 0x7f070078
public static int Base_Widget_AppCompat_ActionButton = 2131165304;
// aapt resource value: 0x7f070079
public static int Base_Widget_AppCompat_ActionButton_CloseMode = 2131165305;
// aapt resource value: 0x7f07007a
public static int Base_Widget_AppCompat_ActionButton_Overflow = 2131165306;
// aapt resource value: 0x7f0700ce
public static int Base_Widget_AppCompat_ActionMode = 2131165390;
// aapt resource value: 0x7f0700cf
public static int Base_Widget_AppCompat_ActivityChooserView = 2131165391;
// aapt resource value: 0x7f070034
public static int Base_Widget_AppCompat_AutoCompleteTextView = 2131165236;
// aapt resource value: 0x7f07007b
public static int Base_Widget_AppCompat_Button = 2131165307;
// aapt resource value: 0x7f07007c
public static int Base_Widget_AppCompat_Button_Borderless = 2131165308;
// aapt resource value: 0x7f07007d
public static int Base_Widget_AppCompat_Button_Borderless_Colored = 2131165309;
// aapt resource value: 0x7f0700d0
public static int Base_Widget_AppCompat_Button_ButtonBar_AlertDialog = 2131165392;
// aapt resource value: 0x7f0700a7
public static int Base_Widget_AppCompat_Button_Colored = 2131165351;
// aapt resource value: 0x7f07007e
public static int Base_Widget_AppCompat_Button_Small = 2131165310;
// aapt resource value: 0x7f07007f
public static int Base_Widget_AppCompat_ButtonBar = 2131165311;
// aapt resource value: 0x7f0700d1
public static int Base_Widget_AppCompat_ButtonBar_AlertDialog = 2131165393;
// aapt resource value: 0x7f070080
public static int Base_Widget_AppCompat_CompoundButton_CheckBox = 2131165312;
// aapt resource value: 0x7f070081
public static int Base_Widget_AppCompat_CompoundButton_RadioButton = 2131165313;
// aapt resource value: 0x7f0700d2
public static int Base_Widget_AppCompat_CompoundButton_Switch = 2131165394;
// aapt resource value: 0x7f07000f
public static int Base_Widget_AppCompat_DrawerArrowToggle = 2131165199;
// aapt resource value: 0x7f0700d3
public static int Base_Widget_AppCompat_DrawerArrowToggle_Common = 2131165395;
// aapt resource value: 0x7f070082
public static int Base_Widget_AppCompat_DropDownItem_Spinner = 2131165314;
// aapt resource value: 0x7f070035
public static int Base_Widget_AppCompat_EditText = 2131165237;
// aapt resource value: 0x7f070083
public static int Base_Widget_AppCompat_ImageButton = 2131165315;
// aapt resource value: 0x7f0700d4
public static int Base_Widget_AppCompat_Light_ActionBar = 2131165396;
// aapt resource value: 0x7f0700d5
public static int Base_Widget_AppCompat_Light_ActionBar_Solid = 2131165397;
// aapt resource value: 0x7f0700d6
public static int Base_Widget_AppCompat_Light_ActionBar_TabBar = 2131165398;
// aapt resource value: 0x7f070084
public static int Base_Widget_AppCompat_Light_ActionBar_TabText = 2131165316;
// aapt resource value: 0x7f070085
public static int Base_Widget_AppCompat_Light_ActionBar_TabText_Inverse = 2131165317;
// aapt resource value: 0x7f070086
public static int Base_Widget_AppCompat_Light_ActionBar_TabView = 2131165318;
// aapt resource value: 0x7f070087
public static int Base_Widget_AppCompat_Light_PopupMenu = 2131165319;
// aapt resource value: 0x7f070088
public static int Base_Widget_AppCompat_Light_PopupMenu_Overflow = 2131165320;
// aapt resource value: 0x7f0700d7
public static int Base_Widget_AppCompat_ListMenuView = 2131165399;
// aapt resource value: 0x7f070089
public static int Base_Widget_AppCompat_ListPopupWindow = 2131165321;
// aapt resource value: 0x7f07008a
public static int Base_Widget_AppCompat_ListView = 2131165322;
// aapt resource value: 0x7f07008b
public static int Base_Widget_AppCompat_ListView_DropDown = 2131165323;
// aapt resource value: 0x7f07008c
public static int Base_Widget_AppCompat_ListView_Menu = 2131165324;
// aapt resource value: 0x7f07008d
public static int Base_Widget_AppCompat_PopupMenu = 2131165325;
// aapt resource value: 0x7f07008e
public static int Base_Widget_AppCompat_PopupMenu_Overflow = 2131165326;
// aapt resource value: 0x7f0700d8
public static int Base_Widget_AppCompat_PopupWindow = 2131165400;
// aapt resource value: 0x7f07002b
public static int Base_Widget_AppCompat_ProgressBar = 2131165227;
// aapt resource value: 0x7f07002c
public static int Base_Widget_AppCompat_ProgressBar_Horizontal = 2131165228;
// aapt resource value: 0x7f07008f
public static int Base_Widget_AppCompat_RatingBar = 2131165327;
// aapt resource value: 0x7f0700a8
public static int Base_Widget_AppCompat_RatingBar_Indicator = 2131165352;
// aapt resource value: 0x7f0700a9
public static int Base_Widget_AppCompat_RatingBar_Small = 2131165353;
// aapt resource value: 0x7f0700d9
public static int Base_Widget_AppCompat_SearchView = 2131165401;
// aapt resource value: 0x7f0700da
public static int Base_Widget_AppCompat_SearchView_ActionBar = 2131165402;
// aapt resource value: 0x7f070090
public static int Base_Widget_AppCompat_SeekBar = 2131165328;
// aapt resource value: 0x7f0700db
public static int Base_Widget_AppCompat_SeekBar_Discrete = 2131165403;
// aapt resource value: 0x7f070091
public static int Base_Widget_AppCompat_Spinner = 2131165329;
// aapt resource value: 0x7f070012
public static int Base_Widget_AppCompat_Spinner_Underlined = 2131165202;
// aapt resource value: 0x7f070092
public static int Base_Widget_AppCompat_TextView_SpinnerItem = 2131165330;
// aapt resource value: 0x7f0700dc
public static int Base_Widget_AppCompat_Toolbar = 2131165404;
// aapt resource value: 0x7f070093
public static int Base_Widget_AppCompat_Toolbar_Button_Navigation = 2131165331;
// aapt resource value: 0x7f070171
public static int Base_Widget_Design_AppBarLayout = 2131165553;
// aapt resource value: 0x7f070172
public static int Base_Widget_Design_TabLayout = 2131165554;
// aapt resource value: 0x7f070000
public static int CardView = 2131165184;
// aapt resource value: 0x7f070002
public static int CardView_Dark = 2131165186;
// aapt resource value: 0x7f070003
public static int CardView_Light = 2131165187;
// aapt resource value: 0x7f07002d
public static int Platform_AppCompat = 2131165229;
// aapt resource value: 0x7f07002e
public static int Platform_AppCompat_Light = 2131165230;
// aapt resource value: 0x7f070094
public static int Platform_ThemeOverlay_AppCompat = 2131165332;
// aapt resource value: 0x7f070095
public static int Platform_ThemeOverlay_AppCompat_Dark = 2131165333;
// aapt resource value: 0x7f070096
public static int Platform_ThemeOverlay_AppCompat_Light = 2131165334;
// aapt resource value: 0x7f07002f
public static int Platform_V11_AppCompat = 2131165231;
// aapt resource value: 0x7f070030
public static int Platform_V11_AppCompat_Light = 2131165232;
// aapt resource value: 0x7f070037
public static int Platform_V14_AppCompat = 2131165239;
// aapt resource value: 0x7f070038
public static int Platform_V14_AppCompat_Light = 2131165240;
// aapt resource value: 0x7f070097
public static int Platform_V21_AppCompat = 2131165335;
// aapt resource value: 0x7f070098
public static int Platform_V21_AppCompat_Light = 2131165336;
// aapt resource value: 0x7f0700ac
public static int Platform_V25_AppCompat = 2131165356;
// aapt resource value: 0x7f0700ad
public static int Platform_V25_AppCompat_Light = 2131165357;
// aapt resource value: 0x7f070031
public static int Platform_Widget_AppCompat_Spinner = 2131165233;
// aapt resource value: 0x7f070040
public static int RtlOverlay_DialogWindowTitle_AppCompat = 2131165248;
// aapt resource value: 0x7f070041
public static int RtlOverlay_Widget_AppCompat_ActionBar_TitleItem = 2131165249;
// aapt resource value: 0x7f070042
public static int RtlOverlay_Widget_AppCompat_DialogTitle_Icon = 2131165250;
// aapt resource value: 0x7f070043
public static int RtlOverlay_Widget_AppCompat_PopupMenuItem = 2131165251;
// aapt resource value: 0x7f070044
public static int RtlOverlay_Widget_AppCompat_PopupMenuItem_InternalGroup = 2131165252;
// aapt resource value: 0x7f070045
public static int RtlOverlay_Widget_AppCompat_PopupMenuItem_Text = 2131165253;
// aapt resource value: 0x7f070046
public static int RtlOverlay_Widget_AppCompat_Search_DropDown = 2131165254;
// aapt resource value: 0x7f070047
public static int RtlOverlay_Widget_AppCompat_Search_DropDown_Icon1 = 2131165255;
// aapt resource value: 0x7f070048
public static int RtlOverlay_Widget_AppCompat_Search_DropDown_Icon2 = 2131165256;
// aapt resource value: 0x7f070049
public static int RtlOverlay_Widget_AppCompat_Search_DropDown_Query = 2131165257;
// aapt resource value: 0x7f07004a
public static int RtlOverlay_Widget_AppCompat_Search_DropDown_Text = 2131165258;
// aapt resource value: 0x7f07004b
public static int RtlOverlay_Widget_AppCompat_SearchView_MagIcon = 2131165259;
// aapt resource value: 0x7f07004c
public static int RtlUnderlay_Widget_AppCompat_ActionButton = 2131165260;
// aapt resource value: 0x7f07004d
public static int RtlUnderlay_Widget_AppCompat_ActionButton_Overflow = 2131165261;
// aapt resource value: 0x7f0700dd
public static int TextAppearance_AppCompat = 2131165405;
// aapt resource value: 0x7f0700de
public static int TextAppearance_AppCompat_Body1 = 2131165406;
// aapt resource value: 0x7f0700df
public static int TextAppearance_AppCompat_Body2 = 2131165407;
// aapt resource value: 0x7f0700e0
public static int TextAppearance_AppCompat_Button = 2131165408;
// aapt resource value: 0x7f0700e1
public static int TextAppearance_AppCompat_Caption = 2131165409;
// aapt resource value: 0x7f0700e2
public static int TextAppearance_AppCompat_Display1 = 2131165410;
// aapt resource value: 0x7f0700e3
public static int TextAppearance_AppCompat_Display2 = 2131165411;
// aapt resource value: 0x7f0700e4
public static int TextAppearance_AppCompat_Display3 = 2131165412;
// aapt resource value: 0x7f0700e5
public static int TextAppearance_AppCompat_Display4 = 2131165413;
// aapt resource value: 0x7f0700e6
public static int TextAppearance_AppCompat_Headline = 2131165414;
// aapt resource value: 0x7f0700e7
public static int TextAppearance_AppCompat_Inverse = 2131165415;
// aapt resource value: 0x7f0700e8
public static int TextAppearance_AppCompat_Large = 2131165416;
// aapt resource value: 0x7f0700e9
public static int TextAppearance_AppCompat_Large_Inverse = 2131165417;
// aapt resource value: 0x7f0700ea
public static int TextAppearance_AppCompat_Light_SearchResult_Subtitle = 2131165418;
// aapt resource value: 0x7f0700eb
public static int TextAppearance_AppCompat_Light_SearchResult_Title = 2131165419;
// aapt resource value: 0x7f0700ec
public static int TextAppearance_AppCompat_Light_Widget_PopupMenu_Large = 2131165420;
// aapt resource value: 0x7f0700ed
public static int TextAppearance_AppCompat_Light_Widget_PopupMenu_Small = 2131165421;
// aapt resource value: 0x7f0700ee
public static int TextAppearance_AppCompat_Medium = 2131165422;
// aapt resource value: 0x7f0700ef
public static int TextAppearance_AppCompat_Medium_Inverse = 2131165423;
// aapt resource value: 0x7f0700f0
public static int TextAppearance_AppCompat_Menu = 2131165424;
// aapt resource value: 0x7f070039
public static int TextAppearance_AppCompat_Notification = 2131165241;
// aapt resource value: 0x7f070099
public static int TextAppearance_AppCompat_Notification_Info = 2131165337;
// aapt resource value: 0x7f07009a
public static int TextAppearance_AppCompat_Notification_Info_Media = 2131165338;
// aapt resource value: 0x7f0700f1
public static int TextAppearance_AppCompat_Notification_Line2 = 2131165425;
// aapt resource value: 0x7f0700f2
public static int TextAppearance_AppCompat_Notification_Line2_Media = 2131165426;
// aapt resource value: 0x7f07009b
public static int TextAppearance_AppCompat_Notification_Media = 2131165339;
// aapt resource value: 0x7f07009c
public static int TextAppearance_AppCompat_Notification_Time = 2131165340;
// aapt resource value: 0x7f07009d
public static int TextAppearance_AppCompat_Notification_Time_Media = 2131165341;
// aapt resource value: 0x7f07003a
public static int TextAppearance_AppCompat_Notification_Title = 2131165242;
// aapt resource value: 0x7f07009e
public static int TextAppearance_AppCompat_Notification_Title_Media = 2131165342;
// aapt resource value: 0x7f0700f3
public static int TextAppearance_AppCompat_SearchResult_Subtitle = 2131165427;
// aapt resource value: 0x7f0700f4
public static int TextAppearance_AppCompat_SearchResult_Title = 2131165428;
// aapt resource value: 0x7f0700f5
public static int TextAppearance_AppCompat_Small = 2131165429;
// aapt resource value: 0x7f0700f6
public static int TextAppearance_AppCompat_Small_Inverse = 2131165430;
// aapt resource value: 0x7f0700f7
public static int TextAppearance_AppCompat_Subhead = 2131165431;
// aapt resource value: 0x7f0700f8
public static int TextAppearance_AppCompat_Subhead_Inverse = 2131165432;
// aapt resource value: 0x7f0700f9
public static int TextAppearance_AppCompat_Title = 2131165433;
// aapt resource value: 0x7f0700fa
public static int TextAppearance_AppCompat_Title_Inverse = 2131165434;
// aapt resource value: 0x7f0700fb
public static int TextAppearance_AppCompat_Widget_ActionBar_Menu = 2131165435;
// aapt resource value: 0x7f0700fc
public static int TextAppearance_AppCompat_Widget_ActionBar_Subtitle = 2131165436;
// aapt resource value: 0x7f0700fd
public static int TextAppearance_AppCompat_Widget_ActionBar_Subtitle_Inverse = 2131165437;
// aapt resource value: 0x7f0700fe
public static int TextAppearance_AppCompat_Widget_ActionBar_Title = 2131165438;
// aapt resource value: 0x7f0700ff
public static int TextAppearance_AppCompat_Widget_ActionBar_Title_Inverse = 2131165439;
// aapt resource value: 0x7f070100
public static int TextAppearance_AppCompat_Widget_ActionMode_Subtitle = 2131165440;
// aapt resource value: 0x7f070101
public static int TextAppearance_AppCompat_Widget_ActionMode_Subtitle_Inverse = 2131165441;
// aapt resource value: 0x7f070102
public static int TextAppearance_AppCompat_Widget_ActionMode_Title = 2131165442;
// aapt resource value: 0x7f070103
public static int TextAppearance_AppCompat_Widget_ActionMode_Title_Inverse = 2131165443;
// aapt resource value: 0x7f070104
public static int TextAppearance_AppCompat_Widget_Button = 2131165444;
// aapt resource value: 0x7f070105
public static int TextAppearance_AppCompat_Widget_Button_Borderless_Colored = 2131165445;
// aapt resource value: 0x7f070106
public static int TextAppearance_AppCompat_Widget_Button_Colored = 2131165446;
// aapt resource value: 0x7f070107
public static int TextAppearance_AppCompat_Widget_Button_Inverse = 2131165447;
// aapt resource value: 0x7f070108
public static int TextAppearance_AppCompat_Widget_DropDownItem = 2131165448;
// aapt resource value: 0x7f070109
public static int TextAppearance_AppCompat_Widget_PopupMenu_Header = 2131165449;
// aapt resource value: 0x7f07010a
public static int TextAppearance_AppCompat_Widget_PopupMenu_Large = 2131165450;
// aapt resource value: 0x7f07010b
public static int TextAppearance_AppCompat_Widget_PopupMenu_Small = 2131165451;
// aapt resource value: 0x7f07010c
public static int TextAppearance_AppCompat_Widget_Switch = 2131165452;
// aapt resource value: 0x7f07010d
public static int TextAppearance_AppCompat_Widget_TextView_SpinnerItem = 2131165453;
// aapt resource value: 0x7f070173
public static int TextAppearance_Design_CollapsingToolbar_Expanded = 2131165555;
// aapt resource value: 0x7f070174
public static int TextAppearance_Design_Counter = 2131165556;
// aapt resource value: 0x7f070175
public static int TextAppearance_Design_Counter_Overflow = 2131165557;
// aapt resource value: 0x7f070176
public static int TextAppearance_Design_Error = 2131165558;
// aapt resource value: 0x7f070177
public static int TextAppearance_Design_Hint = 2131165559;
// aapt resource value: 0x7f070178
public static int TextAppearance_Design_Snackbar_Message = 2131165560;
// aapt resource value: 0x7f070179
public static int TextAppearance_Design_Tab = 2131165561;
// aapt resource value: 0x7f070004
public static int TextAppearance_MediaRouter_PrimaryText = 2131165188;
// aapt resource value: 0x7f070005
public static int TextAppearance_MediaRouter_SecondaryText = 2131165189;
// aapt resource value: 0x7f070006
public static int TextAppearance_MediaRouter_Title = 2131165190;
// aapt resource value: 0x7f07003b
public static int TextAppearance_StatusBar_EventContent = 2131165243;
// aapt resource value: 0x7f07003c
public static int TextAppearance_StatusBar_EventContent_Info = 2131165244;
// aapt resource value: 0x7f07003d
public static int TextAppearance_StatusBar_EventContent_Line2 = 2131165245;
// aapt resource value: 0x7f07003e
public static int TextAppearance_StatusBar_EventContent_Time = 2131165246;
// aapt resource value: 0x7f07003f
public static int TextAppearance_StatusBar_EventContent_Title = 2131165247;
// aapt resource value: 0x7f07010e
public static int TextAppearance_Widget_AppCompat_ExpandedMenu_Item = 2131165454;
// aapt resource value: 0x7f07010f
public static int TextAppearance_Widget_AppCompat_Toolbar_Subtitle = 2131165455;
// aapt resource value: 0x7f070110
public static int TextAppearance_Widget_AppCompat_Toolbar_Title = 2131165456;
// aapt resource value: 0x7f070111
public static int Theme_AppCompat = 2131165457;
// aapt resource value: 0x7f070112
public static int Theme_AppCompat_CompactMenu = 2131165458;
// aapt resource value: 0x7f070013
public static int Theme_AppCompat_DayNight = 2131165203;
// aapt resource value: 0x7f070014
public static int Theme_AppCompat_DayNight_DarkActionBar = 2131165204;
// aapt resource value: 0x7f070015
public static int Theme_AppCompat_DayNight_Dialog = 2131165205;
// aapt resource value: 0x7f070016
public static int Theme_AppCompat_DayNight_Dialog_Alert = 2131165206;
// aapt resource value: 0x7f070017
public static int Theme_AppCompat_DayNight_Dialog_MinWidth = 2131165207;
// aapt resource value: 0x7f070018
public static int Theme_AppCompat_DayNight_DialogWhenLarge = 2131165208;
// aapt resource value: 0x7f070019
public static int Theme_AppCompat_DayNight_NoActionBar = 2131165209;
// aapt resource value: 0x7f070113
public static int Theme_AppCompat_Dialog = 2131165459;
// aapt resource value: 0x7f070114
public static int Theme_AppCompat_Dialog_Alert = 2131165460;
// aapt resource value: 0x7f070115
public static int Theme_AppCompat_Dialog_MinWidth = 2131165461;
// aapt resource value: 0x7f070116
public static int Theme_AppCompat_DialogWhenLarge = 2131165462;
// aapt resource value: 0x7f070117
public static int Theme_AppCompat_Light = 2131165463;
// aapt resource value: 0x7f070118
public static int Theme_AppCompat_Light_DarkActionBar = 2131165464;
// aapt resource value: 0x7f070119
public static int Theme_AppCompat_Light_Dialog = 2131165465;
// aapt resource value: 0x7f07011a
public static int Theme_AppCompat_Light_Dialog_Alert = 2131165466;
// aapt resource value: 0x7f07011b
public static int Theme_AppCompat_Light_Dialog_MinWidth = 2131165467;
// aapt resource value: 0x7f07011c
public static int Theme_AppCompat_Light_DialogWhenLarge = 2131165468;
// aapt resource value: 0x7f07011d
public static int Theme_AppCompat_Light_NoActionBar = 2131165469;
// aapt resource value: 0x7f07011e
public static int Theme_AppCompat_NoActionBar = 2131165470;
// aapt resource value: 0x7f07017a
public static int Theme_Design = 2131165562;
// aapt resource value: 0x7f07017b
public static int Theme_Design_BottomSheetDialog = 2131165563;
// aapt resource value: 0x7f07017c
public static int Theme_Design_Light = 2131165564;
// aapt resource value: 0x7f07017d
public static int Theme_Design_Light_BottomSheetDialog = 2131165565;
// aapt resource value: 0x7f07017e
public static int Theme_Design_Light_NoActionBar = 2131165566;
// aapt resource value: 0x7f07017f
public static int Theme_Design_NoActionBar = 2131165567;
// aapt resource value: 0x7f070007
public static int Theme_MediaRouter = 2131165191;
// aapt resource value: 0x7f070008
public static int Theme_MediaRouter_Light = 2131165192;
// aapt resource value: 0x7f070009
public static int Theme_MediaRouter_Light_DarkControlPanel = 2131165193;
// aapt resource value: 0x7f07000a
public static int Theme_MediaRouter_LightControlPanel = 2131165194;
// aapt resource value: 0x7f07011f
public static int ThemeOverlay_AppCompat = 2131165471;
// aapt resource value: 0x7f070120
public static int ThemeOverlay_AppCompat_ActionBar = 2131165472;
// aapt resource value: 0x7f070121
public static int ThemeOverlay_AppCompat_Dark = 2131165473;
// aapt resource value: 0x7f070122
public static int ThemeOverlay_AppCompat_Dark_ActionBar = 2131165474;
// aapt resource value: 0x7f070123
public static int ThemeOverlay_AppCompat_Dialog = 2131165475;
// aapt resource value: 0x7f070124
public static int ThemeOverlay_AppCompat_Dialog_Alert = 2131165476;
// aapt resource value: 0x7f070125
public static int ThemeOverlay_AppCompat_Light = 2131165477;
// aapt resource value: 0x7f07000b
public static int ThemeOverlay_MediaRouter_Dark = 2131165195;
// aapt resource value: 0x7f07000c
public static int ThemeOverlay_MediaRouter_Light = 2131165196;
// aapt resource value: 0x7f070126
public static int Widget_AppCompat_ActionBar = 2131165478;
// aapt resource value: 0x7f070127
public static int Widget_AppCompat_ActionBar_Solid = 2131165479;
// aapt resource value: 0x7f070128
public static int Widget_AppCompat_ActionBar_TabBar = 2131165480;
// aapt resource value: 0x7f070129
public static int Widget_AppCompat_ActionBar_TabText = 2131165481;
// aapt resource value: 0x7f07012a
public static int Widget_AppCompat_ActionBar_TabView = 2131165482;
// aapt resource value: 0x7f07012b
public static int Widget_AppCompat_ActionButton = 2131165483;
// aapt resource value: 0x7f07012c
public static int Widget_AppCompat_ActionButton_CloseMode = 2131165484;
// aapt resource value: 0x7f07012d
public static int Widget_AppCompat_ActionButton_Overflow = 2131165485;
// aapt resource value: 0x7f07012e
public static int Widget_AppCompat_ActionMode = 2131165486;
// aapt resource value: 0x7f07012f
public static int Widget_AppCompat_ActivityChooserView = 2131165487;
// aapt resource value: 0x7f070130
public static int Widget_AppCompat_AutoCompleteTextView = 2131165488;
// aapt resource value: 0x7f070131
public static int Widget_AppCompat_Button = 2131165489;
// aapt resource value: 0x7f070132
public static int Widget_AppCompat_Button_Borderless = 2131165490;
// aapt resource value: 0x7f070133
public static int Widget_AppCompat_Button_Borderless_Colored = 2131165491;
// aapt resource value: 0x7f070134
public static int Widget_AppCompat_Button_ButtonBar_AlertDialog = 2131165492;
// aapt resource value: 0x7f070135
public static int Widget_AppCompat_Button_Colored = 2131165493;
// aapt resource value: 0x7f070136
public static int Widget_AppCompat_Button_Small = 2131165494;
// aapt resource value: 0x7f070137
public static int Widget_AppCompat_ButtonBar = 2131165495;
// aapt resource value: 0x7f070138
public static int Widget_AppCompat_ButtonBar_AlertDialog = 2131165496;
// aapt resource value: 0x7f070139
public static int Widget_AppCompat_CompoundButton_CheckBox = 2131165497;
// aapt resource value: 0x7f07013a
public static int Widget_AppCompat_CompoundButton_RadioButton = 2131165498;
// aapt resource value: 0x7f07013b
public static int Widget_AppCompat_CompoundButton_Switch = 2131165499;
// aapt resource value: 0x7f07013c
public static int Widget_AppCompat_DrawerArrowToggle = 2131165500;
// aapt resource value: 0x7f07013d
public static int Widget_AppCompat_DropDownItem_Spinner = 2131165501;
// aapt resource value: 0x7f07013e
public static int Widget_AppCompat_EditText = 2131165502;
// aapt resource value: 0x7f07013f
public static int Widget_AppCompat_ImageButton = 2131165503;
// aapt resource value: 0x7f070140
public static int Widget_AppCompat_Light_ActionBar = 2131165504;
// aapt resource value: 0x7f070141
public static int Widget_AppCompat_Light_ActionBar_Solid = 2131165505;
// aapt resource value: 0x7f070142
public static int Widget_AppCompat_Light_ActionBar_Solid_Inverse = 2131165506;
// aapt resource value: 0x7f070143
public static int Widget_AppCompat_Light_ActionBar_TabBar = 2131165507;
// aapt resource value: 0x7f070144
public static int Widget_AppCompat_Light_ActionBar_TabBar_Inverse = 2131165508;
// aapt resource value: 0x7f070145
public static int Widget_AppCompat_Light_ActionBar_TabText = 2131165509;
// aapt resource value: 0x7f070146
public static int Widget_AppCompat_Light_ActionBar_TabText_Inverse = 2131165510;
// aapt resource value: 0x7f070147
public static int Widget_AppCompat_Light_ActionBar_TabView = 2131165511;
// aapt resource value: 0x7f070148
public static int Widget_AppCompat_Light_ActionBar_TabView_Inverse = 2131165512;
// aapt resource value: 0x7f070149
public static int Widget_AppCompat_Light_ActionButton = 2131165513;
// aapt resource value: 0x7f07014a
public static int Widget_AppCompat_Light_ActionButton_CloseMode = 2131165514;
// aapt resource value: 0x7f07014b
public static int Widget_AppCompat_Light_ActionButton_Overflow = 2131165515;
// aapt resource value: 0x7f07014c
public static int Widget_AppCompat_Light_ActionMode_Inverse = 2131165516;
// aapt resource value: 0x7f07014d
public static int Widget_AppCompat_Light_ActivityChooserView = 2131165517;
// aapt resource value: 0x7f07014e
public static int Widget_AppCompat_Light_AutoCompleteTextView = 2131165518;
// aapt resource value: 0x7f07014f
public static int Widget_AppCompat_Light_DropDownItem_Spinner = 2131165519;
// aapt resource value: 0x7f070150
public static int Widget_AppCompat_Light_ListPopupWindow = 2131165520;
// aapt resource value: 0x7f070151
public static int Widget_AppCompat_Light_ListView_DropDown = 2131165521;
// aapt resource value: 0x7f070152
public static int Widget_AppCompat_Light_PopupMenu = 2131165522;
// aapt resource value: 0x7f070153
public static int Widget_AppCompat_Light_PopupMenu_Overflow = 2131165523;
// aapt resource value: 0x7f070154
public static int Widget_AppCompat_Light_SearchView = 2131165524;
// aapt resource value: 0x7f070155
public static int Widget_AppCompat_Light_Spinner_DropDown_ActionBar = 2131165525;
// aapt resource value: 0x7f070156
public static int Widget_AppCompat_ListMenuView = 2131165526;
// aapt resource value: 0x7f070157
public static int Widget_AppCompat_ListPopupWindow = 2131165527;
// aapt resource value: 0x7f070158
public static int Widget_AppCompat_ListView = 2131165528;
// aapt resource value: 0x7f070159
public static int Widget_AppCompat_ListView_DropDown = 2131165529;
// aapt resource value: 0x7f07015a
public static int Widget_AppCompat_ListView_Menu = 2131165530;
// aapt resource value: 0x7f07009f
public static int Widget_AppCompat_NotificationActionContainer = 2131165343;
// aapt resource value: 0x7f0700a0
public static int Widget_AppCompat_NotificationActionText = 2131165344;
// aapt resource value: 0x7f07015b
public static int Widget_AppCompat_PopupMenu = 2131165531;
// aapt resource value: 0x7f07015c
public static int Widget_AppCompat_PopupMenu_Overflow = 2131165532;
// aapt resource value: 0x7f07015d
public static int Widget_AppCompat_PopupWindow = 2131165533;
// aapt resource value: 0x7f07015e
public static int Widget_AppCompat_ProgressBar = 2131165534;
// aapt resource value: 0x7f07015f
public static int Widget_AppCompat_ProgressBar_Horizontal = 2131165535;
// aapt resource value: 0x7f070160
public static int Widget_AppCompat_RatingBar = 2131165536;
// aapt resource value: 0x7f070161
public static int Widget_AppCompat_RatingBar_Indicator = 2131165537;
// aapt resource value: 0x7f070162
public static int Widget_AppCompat_RatingBar_Small = 2131165538;
// aapt resource value: 0x7f070163
public static int Widget_AppCompat_SearchView = 2131165539;
// aapt resource value: 0x7f070164
public static int Widget_AppCompat_SearchView_ActionBar = 2131165540;
// aapt resource value: 0x7f070165
public static int Widget_AppCompat_SeekBar = 2131165541;
// aapt resource value: 0x7f070166
public static int Widget_AppCompat_SeekBar_Discrete = 2131165542;
// aapt resource value: 0x7f070167
public static int Widget_AppCompat_Spinner = 2131165543;
// aapt resource value: 0x7f070168
public static int Widget_AppCompat_Spinner_DropDown = 2131165544;
// aapt resource value: 0x7f070169
public static int Widget_AppCompat_Spinner_DropDown_ActionBar = 2131165545;
// aapt resource value: 0x7f07016a
public static int Widget_AppCompat_Spinner_Underlined = 2131165546;
// aapt resource value: 0x7f07016b
public static int Widget_AppCompat_TextView_SpinnerItem = 2131165547;
// aapt resource value: 0x7f07016c
public static int Widget_AppCompat_Toolbar = 2131165548;
// aapt resource value: 0x7f07016d
public static int Widget_AppCompat_Toolbar_Button_Navigation = 2131165549;
// aapt resource value: 0x7f07016f
public static int Widget_Design_AppBarLayout = 2131165551;
// aapt resource value: 0x7f070180
public static int Widget_Design_BottomNavigationView = 2131165568;
// aapt resource value: 0x7f070181
public static int Widget_Design_BottomSheet_Modal = 2131165569;
// aapt resource value: 0x7f070182
public static int Widget_Design_CollapsingToolbar = 2131165570;
// aapt resource value: 0x7f070183
public static int Widget_Design_CoordinatorLayout = 2131165571;
// aapt resource value: 0x7f070184
public static int Widget_Design_FloatingActionButton = 2131165572;
// aapt resource value: 0x7f070185
public static int Widget_Design_NavigationView = 2131165573;
// aapt resource value: 0x7f070186
public static int Widget_Design_ScrimInsetsFrameLayout = 2131165574;
// aapt resource value: 0x7f070187
public static int Widget_Design_Snackbar = 2131165575;
// aapt resource value: 0x7f07016e
public static int Widget_Design_TabLayout = 2131165550;
// aapt resource value: 0x7f070188
public static int Widget_Design_TextInputLayout = 2131165576;
// aapt resource value: 0x7f07000d
public static int Widget_MediaRouter_Light_MediaRouteButton = 2131165197;
// aapt resource value: 0x7f07000e
public static int Widget_MediaRouter_MediaRouteButton = 2131165198;
static Style()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Style()
{
}
}
public partial class Styleable
{
public static int[] ActionBar = new int[] {
2130772026,
2130772028,
2130772029,
2130772030,
2130772031,
2130772032,
2130772033,
2130772034,
2130772035,
2130772036,
2130772037,
2130772038,
2130772039,
2130772040,
2130772041,
2130772042,
2130772043,
2130772044,
2130772045,
2130772046,
2130772047,
2130772048,
2130772049,
2130772050,
2130772051,
2130772052,
2130772053,
2130772054,
2130772118};
// aapt resource value: 10
public static int ActionBar_background = 10;
// aapt resource value: 12
public static int ActionBar_backgroundSplit = 12;
// aapt resource value: 11
public static int ActionBar_backgroundStacked = 11;
// aapt resource value: 21
public static int ActionBar_contentInsetEnd = 21;
// aapt resource value: 25
public static int ActionBar_contentInsetEndWithActions = 25;
// aapt resource value: 22
public static int ActionBar_contentInsetLeft = 22;
// aapt resource value: 23
public static int ActionBar_contentInsetRight = 23;
// aapt resource value: 20
public static int ActionBar_contentInsetStart = 20;
// aapt resource value: 24
public static int ActionBar_contentInsetStartWithNavigation = 24;
// aapt resource value: 13
public static int ActionBar_customNavigationLayout = 13;
// aapt resource value: 3
public static int ActionBar_displayOptions = 3;
// aapt resource value: 9
public static int ActionBar_divider = 9;
// aapt resource value: 26
public static int ActionBar_elevation = 26;
// aapt resource value: 0
public static int ActionBar_height = 0;
// aapt resource value: 19
public static int ActionBar_hideOnContentScroll = 19;
// aapt resource value: 28
public static int ActionBar_homeAsUpIndicator = 28;
// aapt resource value: 14
public static int ActionBar_homeLayout = 14;
// aapt resource value: 7
public static int ActionBar_icon = 7;
// aapt resource value: 16
public static int ActionBar_indeterminateProgressStyle = 16;
// aapt resource value: 18
public static int ActionBar_itemPadding = 18;
// aapt resource value: 8
public static int ActionBar_logo = 8;
// aapt resource value: 2
public static int ActionBar_navigationMode = 2;
// aapt resource value: 27
public static int ActionBar_popupTheme = 27;
// aapt resource value: 17
public static int ActionBar_progressBarPadding = 17;
// aapt resource value: 15
public static int ActionBar_progressBarStyle = 15;
// aapt resource value: 4
public static int ActionBar_subtitle = 4;
// aapt resource value: 6
public static int ActionBar_subtitleTextStyle = 6;
// aapt resource value: 1
public static int ActionBar_title = 1;
// aapt resource value: 5
public static int ActionBar_titleTextStyle = 5;
public static int[] ActionBarLayout = new int[] {
16842931};
// aapt resource value: 0
public static int ActionBarLayout_android_layout_gravity = 0;
public static int[] ActionMenuItemView = new int[] {
16843071};
// aapt resource value: 0
public static int ActionMenuItemView_android_minWidth = 0;
public static int[] ActionMenuView;
public static int[] ActionMode = new int[] {
2130772026,
2130772032,
2130772033,
2130772037,
2130772039,
2130772055};
// aapt resource value: 3
public static int ActionMode_background = 3;
// aapt resource value: 4
public static int ActionMode_backgroundSplit = 4;
// aapt resource value: 5
public static int ActionMode_closeItemLayout = 5;
// aapt resource value: 0
public static int ActionMode_height = 0;
// aapt resource value: 2
public static int ActionMode_subtitleTextStyle = 2;
// aapt resource value: 1
public static int ActionMode_titleTextStyle = 1;
public static int[] ActivityChooserView = new int[] {
2130772056,
2130772057};
// aapt resource value: 1
public static int ActivityChooserView_expandActivityOverflowButtonDrawable = 1;
// aapt resource value: 0
public static int ActivityChooserView_initialActivityCount = 0;
public static int[] AlertDialog = new int[] {
16842994,
2130772058,
2130772059,
2130772060,
2130772061,
2130772062,
2130772063};
// aapt resource value: 0
public static int AlertDialog_android_layout = 0;
// aapt resource value: 1
public static int AlertDialog_buttonPanelSideLayout = 1;
// aapt resource value: 5
public static int AlertDialog_listItemLayout = 5;
// aapt resource value: 2
public static int AlertDialog_listLayout = 2;
// aapt resource value: 3
public static int AlertDialog_multiChoiceItemLayout = 3;
// aapt resource value: 6
public static int AlertDialog_showTitle = 6;
// aapt resource value: 4
public static int AlertDialog_singleChoiceItemLayout = 4;
public static int[] AppBarLayout = new int[] {
16842964,
2130772053,
2130772256};
// aapt resource value: 0
public static int AppBarLayout_android_background = 0;
// aapt resource value: 1
public static int AppBarLayout_elevation = 1;
// aapt resource value: 2
public static int AppBarLayout_expanded = 2;
public static int[] AppBarLayoutStates = new int[] {
2130772257,
2130772258};
// aapt resource value: 0
public static int AppBarLayoutStates_state_collapsed = 0;
// aapt resource value: 1
public static int AppBarLayoutStates_state_collapsible = 1;
public static int[] AppBarLayout_Layout = new int[] {
2130772259,
2130772260};
// aapt resource value: 0
public static int AppBarLayout_Layout_layout_scrollFlags = 0;
// aapt resource value: 1
public static int AppBarLayout_Layout_layout_scrollInterpolator = 1;
public static int[] AppCompatImageView = new int[] {
16843033,
2130772064,
2130772065,
2130772066};
// aapt resource value: 0
public static int AppCompatImageView_android_src = 0;
// aapt resource value: 1
public static int AppCompatImageView_srcCompat = 1;
// aapt resource value: 2
public static int AppCompatImageView_tint = 2;
// aapt resource value: 3
public static int AppCompatImageView_tintMode = 3;
public static int[] AppCompatSeekBar = new int[] {
16843074,
2130772067,
2130772068,
2130772069};
// aapt resource value: 0
public static int AppCompatSeekBar_android_thumb = 0;
// aapt resource value: 1
public static int AppCompatSeekBar_tickMark = 1;
// aapt resource value: 2
public static int AppCompatSeekBar_tickMarkTint = 2;
// aapt resource value: 3
public static int AppCompatSeekBar_tickMarkTintMode = 3;
public static int[] AppCompatTextHelper = new int[] {
16842804,
16843117,
16843118,
16843119,
16843120,
16843666,
16843667};
// aapt resource value: 2
public static int AppCompatTextHelper_android_drawableBottom = 2;
// aapt resource value: 6
public static int AppCompatTextHelper_android_drawableEnd = 6;
// aapt resource value: 3
public static int AppCompatTextHelper_android_drawableLeft = 3;
// aapt resource value: 4
public static int AppCompatTextHelper_android_drawableRight = 4;
// aapt resource value: 5
public static int AppCompatTextHelper_android_drawableStart = 5;
// aapt resource value: 1
public static int AppCompatTextHelper_android_drawableTop = 1;
// aapt resource value: 0
public static int AppCompatTextHelper_android_textAppearance = 0;
public static int[] AppCompatTextView = new int[] {
16842804,
2130772070};
// aapt resource value: 0
public static int AppCompatTextView_android_textAppearance = 0;
// aapt resource value: 1
public static int AppCompatTextView_textAllCaps = 1;
public static int[] AppCompatTheme = new int[] {
16842839,
16842926,
2130772071,
2130772072,
2130772073,
2130772074,
2130772075,
2130772076,
2130772077,
2130772078,
2130772079,
2130772080,
2130772081,
2130772082,
2130772083,
2130772084,
2130772085,
2130772086,
2130772087,
2130772088,
2130772089,
2130772090,
2130772091,
2130772092,
2130772093,
2130772094,
2130772095,
2130772096,
2130772097,
2130772098,
2130772099,
2130772100,
2130772101,
2130772102,
2130772103,
2130772104,
2130772105,
2130772106,
2130772107,
2130772108,
2130772109,
2130772110,
2130772111,
2130772112,
2130772113,
2130772114,
2130772115,
2130772116,
2130772117,
2130772118,
2130772119,
2130772120,
2130772121,
2130772122,
2130772123,
2130772124,
2130772125,
2130772126,
2130772127,
2130772128,
2130772129,
2130772130,
2130772131,
2130772132,
2130772133,
2130772134,
2130772135,
2130772136,
2130772137,
2130772138,
2130772139,
2130772140,
2130772141,
2130772142,
2130772143,
2130772144,
2130772145,
2130772146,
2130772147,
2130772148,
2130772149,
2130772150,
2130772151,
2130772152,
2130772153,
2130772154,
2130772155,
2130772156,
2130772157,
2130772158,
2130772159,
2130772160,
2130772161,
2130772162,
2130772163,
2130772164,
2130772165,
2130772166,
2130772167,
2130772168,
2130772169,
2130772170,
2130772171,
2130772172,
2130772173,
2130772174,
2130772175,
2130772176,
2130772177,
2130772178,
2130772179,
2130772180,
2130772181,
2130772182,
2130772183,
2130772184};
// aapt resource value: 23
public static int AppCompatTheme_actionBarDivider = 23;
// aapt resource value: 24
public static int AppCompatTheme_actionBarItemBackground = 24;
// aapt resource value: 17
public static int AppCompatTheme_actionBarPopupTheme = 17;
// aapt resource value: 22
public static int AppCompatTheme_actionBarSize = 22;
// aapt resource value: 19
public static int AppCompatTheme_actionBarSplitStyle = 19;
// aapt resource value: 18
public static int AppCompatTheme_actionBarStyle = 18;
// aapt resource value: 13
public static int AppCompatTheme_actionBarTabBarStyle = 13;
// aapt resource value: 12
public static int AppCompatTheme_actionBarTabStyle = 12;
// aapt resource value: 14
public static int AppCompatTheme_actionBarTabTextStyle = 14;
// aapt resource value: 20
public static int AppCompatTheme_actionBarTheme = 20;
// aapt resource value: 21
public static int AppCompatTheme_actionBarWidgetTheme = 21;
// aapt resource value: 50
public static int AppCompatTheme_actionButtonStyle = 50;
// aapt resource value: 46
public static int AppCompatTheme_actionDropDownStyle = 46;
// aapt resource value: 25
public static int AppCompatTheme_actionMenuTextAppearance = 25;
// aapt resource value: 26
public static int AppCompatTheme_actionMenuTextColor = 26;
// aapt resource value: 29
public static int AppCompatTheme_actionModeBackground = 29;
// aapt resource value: 28
public static int AppCompatTheme_actionModeCloseButtonStyle = 28;
// aapt resource value: 31
public static int AppCompatTheme_actionModeCloseDrawable = 31;
// aapt resource value: 33
public static int AppCompatTheme_actionModeCopyDrawable = 33;
// aapt resource value: 32
public static int AppCompatTheme_actionModeCutDrawable = 32;
// aapt resource value: 37
public static int AppCompatTheme_actionModeFindDrawable = 37;
// aapt resource value: 34
public static int AppCompatTheme_actionModePasteDrawable = 34;
// aapt resource value: 39
public static int AppCompatTheme_actionModePopupWindowStyle = 39;
// aapt resource value: 35
public static int AppCompatTheme_actionModeSelectAllDrawable = 35;
// aapt resource value: 36
public static int AppCompatTheme_actionModeShareDrawable = 36;
// aapt resource value: 30
public static int AppCompatTheme_actionModeSplitBackground = 30;
// aapt resource value: 27
public static int AppCompatTheme_actionModeStyle = 27;
// aapt resource value: 38
public static int AppCompatTheme_actionModeWebSearchDrawable = 38;
// aapt resource value: 15
public static int AppCompatTheme_actionOverflowButtonStyle = 15;
// aapt resource value: 16
public static int AppCompatTheme_actionOverflowMenuStyle = 16;
// aapt resource value: 58
public static int AppCompatTheme_activityChooserViewStyle = 58;
// aapt resource value: 95
public static int AppCompatTheme_alertDialogButtonGroupStyle = 95;
// aapt resource value: 96
public static int AppCompatTheme_alertDialogCenterButtons = 96;
// aapt resource value: 94
public static int AppCompatTheme_alertDialogStyle = 94;
// aapt resource value: 97
public static int AppCompatTheme_alertDialogTheme = 97;
// aapt resource value: 1
public static int AppCompatTheme_android_windowAnimationStyle = 1;
// aapt resource value: 0
public static int AppCompatTheme_android_windowIsFloating = 0;
// aapt resource value: 102
public static int AppCompatTheme_autoCompleteTextViewStyle = 102;
// aapt resource value: 55
public static int AppCompatTheme_borderlessButtonStyle = 55;
// aapt resource value: 52
public static int AppCompatTheme_buttonBarButtonStyle = 52;
// aapt resource value: 100
public static int AppCompatTheme_buttonBarNegativeButtonStyle = 100;
// aapt resource value: 101
public static int AppCompatTheme_buttonBarNeutralButtonStyle = 101;
// aapt resource value: 99
public static int AppCompatTheme_buttonBarPositiveButtonStyle = 99;
// aapt resource value: 51
public static int AppCompatTheme_buttonBarStyle = 51;
// aapt resource value: 103
public static int AppCompatTheme_buttonStyle = 103;
// aapt resource value: 104
public static int AppCompatTheme_buttonStyleSmall = 104;
// aapt resource value: 105
public static int AppCompatTheme_checkboxStyle = 105;
// aapt resource value: 106
public static int AppCompatTheme_checkedTextViewStyle = 106;
// aapt resource value: 86
public static int AppCompatTheme_colorAccent = 86;
// aapt resource value: 93
public static int AppCompatTheme_colorBackgroundFloating = 93;
// aapt resource value: 90
public static int AppCompatTheme_colorButtonNormal = 90;
// aapt resource value: 88
public static int AppCompatTheme_colorControlActivated = 88;
// aapt resource value: 89
public static int AppCompatTheme_colorControlHighlight = 89;
// aapt resource value: 87
public static int AppCompatTheme_colorControlNormal = 87;
// aapt resource value: 84
public static int AppCompatTheme_colorPrimary = 84;
// aapt resource value: 85
public static int AppCompatTheme_colorPrimaryDark = 85;
// aapt resource value: 91
public static int AppCompatTheme_colorSwitchThumbNormal = 91;
// aapt resource value: 92
public static int AppCompatTheme_controlBackground = 92;
// aapt resource value: 44
public static int AppCompatTheme_dialogPreferredPadding = 44;
// aapt resource value: 43
public static int AppCompatTheme_dialogTheme = 43;
// aapt resource value: 57
public static int AppCompatTheme_dividerHorizontal = 57;
// aapt resource value: 56
public static int AppCompatTheme_dividerVertical = 56;
// aapt resource value: 75
public static int AppCompatTheme_dropDownListViewStyle = 75;
// aapt resource value: 47
public static int AppCompatTheme_dropdownListPreferredItemHeight = 47;
// aapt resource value: 64
public static int AppCompatTheme_editTextBackground = 64;
// aapt resource value: 63
public static int AppCompatTheme_editTextColor = 63;
// aapt resource value: 107
public static int AppCompatTheme_editTextStyle = 107;
// aapt resource value: 49
public static int AppCompatTheme_homeAsUpIndicator = 49;
// aapt resource value: 65
public static int AppCompatTheme_imageButtonStyle = 65;
// aapt resource value: 83
public static int AppCompatTheme_listChoiceBackgroundIndicator = 83;
// aapt resource value: 45
public static int AppCompatTheme_listDividerAlertDialog = 45;
// aapt resource value: 115
public static int AppCompatTheme_listMenuViewStyle = 115;
// aapt resource value: 76
public static int AppCompatTheme_listPopupWindowStyle = 76;
// aapt resource value: 70
public static int AppCompatTheme_listPreferredItemHeight = 70;
// aapt resource value: 72
public static int AppCompatTheme_listPreferredItemHeightLarge = 72;
// aapt resource value: 71
public static int AppCompatTheme_listPreferredItemHeightSmall = 71;
// aapt resource value: 73
public static int AppCompatTheme_listPreferredItemPaddingLeft = 73;
// aapt resource value: 74
public static int AppCompatTheme_listPreferredItemPaddingRight = 74;
// aapt resource value: 80
public static int AppCompatTheme_panelBackground = 80;
// aapt resource value: 82
public static int AppCompatTheme_panelMenuListTheme = 82;
// aapt resource value: 81
public static int AppCompatTheme_panelMenuListWidth = 81;
// aapt resource value: 61
public static int AppCompatTheme_popupMenuStyle = 61;
// aapt resource value: 62
public static int AppCompatTheme_popupWindowStyle = 62;
// aapt resource value: 108
public static int AppCompatTheme_radioButtonStyle = 108;
// aapt resource value: 109
public static int AppCompatTheme_ratingBarStyle = 109;
// aapt resource value: 110
public static int AppCompatTheme_ratingBarStyleIndicator = 110;
// aapt resource value: 111
public static int AppCompatTheme_ratingBarStyleSmall = 111;
// aapt resource value: 69
public static int AppCompatTheme_searchViewStyle = 69;
// aapt resource value: 112
public static int AppCompatTheme_seekBarStyle = 112;
// aapt resource value: 53
public static int AppCompatTheme_selectableItemBackground = 53;
// aapt resource value: 54
public static int AppCompatTheme_selectableItemBackgroundBorderless = 54;
// aapt resource value: 48
public static int AppCompatTheme_spinnerDropDownItemStyle = 48;
// aapt resource value: 113
public static int AppCompatTheme_spinnerStyle = 113;
// aapt resource value: 114
public static int AppCompatTheme_switchStyle = 114;
// aapt resource value: 40
public static int AppCompatTheme_textAppearanceLargePopupMenu = 40;
// aapt resource value: 77
public static int AppCompatTheme_textAppearanceListItem = 77;
// aapt resource value: 78
public static int AppCompatTheme_textAppearanceListItemSecondary = 78;
// aapt resource value: 79
public static int AppCompatTheme_textAppearanceListItemSmall = 79;
// aapt resource value: 42
public static int AppCompatTheme_textAppearancePopupMenuHeader = 42;
// aapt resource value: 67
public static int AppCompatTheme_textAppearanceSearchResultSubtitle = 67;
// aapt resource value: 66
public static int AppCompatTheme_textAppearanceSearchResultTitle = 66;
// aapt resource value: 41
public static int AppCompatTheme_textAppearanceSmallPopupMenu = 41;
// aapt resource value: 98
public static int AppCompatTheme_textColorAlertDialogListItem = 98;
// aapt resource value: 68
public static int AppCompatTheme_textColorSearchUrl = 68;
// aapt resource value: 60
public static int AppCompatTheme_toolbarNavigationButtonStyle = 60;
// aapt resource value: 59
public static int AppCompatTheme_toolbarStyle = 59;
// aapt resource value: 2
public static int AppCompatTheme_windowActionBar = 2;
// aapt resource value: 4
public static int AppCompatTheme_windowActionBarOverlay = 4;
// aapt resource value: 5
public static int AppCompatTheme_windowActionModeOverlay = 5;
// aapt resource value: 9
public static int AppCompatTheme_windowFixedHeightMajor = 9;
// aapt resource value: 7
public static int AppCompatTheme_windowFixedHeightMinor = 7;
// aapt resource value: 6
public static int AppCompatTheme_windowFixedWidthMajor = 6;
// aapt resource value: 8
public static int AppCompatTheme_windowFixedWidthMinor = 8;
// aapt resource value: 10
public static int AppCompatTheme_windowMinWidthMajor = 10;
// aapt resource value: 11
public static int AppCompatTheme_windowMinWidthMinor = 11;
// aapt resource value: 3
public static int AppCompatTheme_windowNoTitle = 3;
public static int[] BottomNavigationView = new int[] {
2130772053,
2130772299,
2130772300,
2130772301,
2130772302};
// aapt resource value: 0
public static int BottomNavigationView_elevation = 0;
// aapt resource value: 4
public static int BottomNavigationView_itemBackground = 4;
// aapt resource value: 2
public static int BottomNavigationView_itemIconTint = 2;
// aapt resource value: 3
public static int BottomNavigationView_itemTextColor = 3;
// aapt resource value: 1
public static int BottomNavigationView_menu = 1;
public static int[] BottomSheetBehavior_Layout = new int[] {
2130772261,
2130772262,
2130772263};
// aapt resource value: 1
public static int BottomSheetBehavior_Layout_behavior_hideable = 1;
// aapt resource value: 0
public static int BottomSheetBehavior_Layout_behavior_peekHeight = 0;
// aapt resource value: 2
public static int BottomSheetBehavior_Layout_behavior_skipCollapsed = 2;
public static int[] ButtonBarLayout = new int[] {
2130772185};
// aapt resource value: 0
public static int ButtonBarLayout_allowStacking = 0;
public static int[] CardView = new int[] {
16843071,
16843072,
2130771968,
2130771969,
2130771970,
2130771971,
2130771972,
2130771973,
2130771974,
2130771975,
2130771976,
2130771977,
2130771978};
// aapt resource value: 1
public static int CardView_android_minHeight = 1;
// aapt resource value: 0
public static int CardView_android_minWidth = 0;
// aapt resource value: 2
public static int CardView_cardBackgroundColor = 2;
// aapt resource value: 3
public static int CardView_cardCornerRadius = 3;
// aapt resource value: 4
public static int CardView_cardElevation = 4;
// aapt resource value: 5
public static int CardView_cardMaxElevation = 5;
// aapt resource value: 7
public static int CardView_cardPreventCornerOverlap = 7;
// aapt resource value: 6
public static int CardView_cardUseCompatPadding = 6;
// aapt resource value: 8
public static int CardView_contentPadding = 8;
// aapt resource value: 12
public static int CardView_contentPaddingBottom = 12;
// aapt resource value: 9
public static int CardView_contentPaddingLeft = 9;
// aapt resource value: 10
public static int CardView_contentPaddingRight = 10;
// aapt resource value: 11
public static int CardView_contentPaddingTop = 11;
public static int[] CollapsingToolbarLayout = new int[] {
2130772028,
2130772264,
2130772265,
2130772266,
2130772267,
2130772268,
2130772269,
2130772270,
2130772271,
2130772272,
2130772273,
2130772274,
2130772275,
2130772276,
2130772277,
2130772278};
// aapt resource value: 13
public static int CollapsingToolbarLayout_collapsedTitleGravity = 13;
// aapt resource value: 7
public static int CollapsingToolbarLayout_collapsedTitleTextAppearance = 7;
// aapt resource value: 8
public static int CollapsingToolbarLayout_contentScrim = 8;
// aapt resource value: 14
public static int CollapsingToolbarLayout_expandedTitleGravity = 14;
// aapt resource value: 1
public static int CollapsingToolbarLayout_expandedTitleMargin = 1;
// aapt resource value: 5
public static int CollapsingToolbarLayout_expandedTitleMarginBottom = 5;
// aapt resource value: 4
public static int CollapsingToolbarLayout_expandedTitleMarginEnd = 4;
// aapt resource value: 2
public static int CollapsingToolbarLayout_expandedTitleMarginStart = 2;
// aapt resource value: 3
public static int CollapsingToolbarLayout_expandedTitleMarginTop = 3;
// aapt resource value: 6
public static int CollapsingToolbarLayout_expandedTitleTextAppearance = 6;
// aapt resource value: 12
public static int CollapsingToolbarLayout_scrimAnimationDuration = 12;
// aapt resource value: 11
public static int CollapsingToolbarLayout_scrimVisibleHeightTrigger = 11;
// aapt resource value: 9
public static int CollapsingToolbarLayout_statusBarScrim = 9;
// aapt resource value: 0
public static int CollapsingToolbarLayout_title = 0;
// aapt resource value: 15
public static int CollapsingToolbarLayout_titleEnabled = 15;
// aapt resource value: 10
public static int CollapsingToolbarLayout_toolbarId = 10;
public static int[] CollapsingToolbarLayout_Layout = new int[] {
2130772279,
2130772280};
// aapt resource value: 0
public static int CollapsingToolbarLayout_Layout_layout_collapseMode = 0;
// aapt resource value: 1
public static int CollapsingToolbarLayout_Layout_layout_collapseParallaxMultiplier = 1;
public static int[] ColorStateListItem = new int[] {
16843173,
16843551,
2130772186};
// aapt resource value: 2
public static int ColorStateListItem_alpha = 2;
// aapt resource value: 1
public static int ColorStateListItem_android_alpha = 1;
// aapt resource value: 0
public static int ColorStateListItem_android_color = 0;
public static int[] CompoundButton = new int[] {
16843015,
2130772187,
2130772188};
// aapt resource value: 0
public static int CompoundButton_android_button = 0;
// aapt resource value: 1
public static int CompoundButton_buttonTint = 1;
// aapt resource value: 2
public static int CompoundButton_buttonTintMode = 2;
public static int[] CoordinatorLayout = new int[] {
2130772281,
2130772282};
// aapt resource value: 0
public static int CoordinatorLayout_keylines = 0;
// aapt resource value: 1
public static int CoordinatorLayout_statusBarBackground = 1;
public static int[] CoordinatorLayout_Layout = new int[] {
16842931,
2130772283,
2130772284,
2130772285,
2130772286,
2130772287,
2130772288};
// aapt resource value: 0
public static int CoordinatorLayout_Layout_android_layout_gravity = 0;
// aapt resource value: 2
public static int CoordinatorLayout_Layout_layout_anchor = 2;
// aapt resource value: 4
public static int CoordinatorLayout_Layout_layout_anchorGravity = 4;
// aapt resource value: 1
public static int CoordinatorLayout_Layout_layout_behavior = 1;
// aapt resource value: 6
public static int CoordinatorLayout_Layout_layout_dodgeInsetEdges = 6;
// aapt resource value: 5
public static int CoordinatorLayout_Layout_layout_insetEdge = 5;
// aapt resource value: 3
public static int CoordinatorLayout_Layout_layout_keyline = 3;
public static int[] DesignTheme = new int[] {
2130772289,
2130772290,
2130772291};
// aapt resource value: 0
public static int DesignTheme_bottomSheetDialogTheme = 0;
// aapt resource value: 1
public static int DesignTheme_bottomSheetStyle = 1;
// aapt resource value: 2
public static int DesignTheme_textColorError = 2;
public static int[] DrawerArrowToggle = new int[] {
2130772189,
2130772190,
2130772191,
2130772192,
2130772193,
2130772194,
2130772195,
2130772196};
// aapt resource value: 4
public static int DrawerArrowToggle_arrowHeadLength = 4;
// aapt resource value: 5
public static int DrawerArrowToggle_arrowShaftLength = 5;
// aapt resource value: 6
public static int DrawerArrowToggle_barLength = 6;
// aapt resource value: 0
public static int DrawerArrowToggle_color = 0;
// aapt resource value: 2
public static int DrawerArrowToggle_drawableSize = 2;
// aapt resource value: 3
public static int DrawerArrowToggle_gapBetweenBars = 3;
// aapt resource value: 1
public static int DrawerArrowToggle_spinBars = 1;
// aapt resource value: 7
public static int DrawerArrowToggle_thickness = 7;
public static int[] FloatingActionButton = new int[] {
2130772053,
2130772254,
2130772255,
2130772292,
2130772293,
2130772294,
2130772295,
2130772296};
// aapt resource value: 1
public static int FloatingActionButton_backgroundTint = 1;
// aapt resource value: 2
public static int FloatingActionButton_backgroundTintMode = 2;
// aapt resource value: 6
public static int FloatingActionButton_borderWidth = 6;
// aapt resource value: 0
public static int FloatingActionButton_elevation = 0;
// aapt resource value: 4
public static int FloatingActionButton_fabSize = 4;
// aapt resource value: 5
public static int FloatingActionButton_pressedTranslationZ = 5;
// aapt resource value: 3
public static int FloatingActionButton_rippleColor = 3;
// aapt resource value: 7
public static int FloatingActionButton_useCompatPadding = 7;
public static int[] FloatingActionButton_Behavior_Layout = new int[] {
2130772297};
// aapt resource value: 0
public static int FloatingActionButton_Behavior_Layout_behavior_autoHide = 0;
public static int[] ForegroundLinearLayout = new int[] {
16843017,
16843264,
2130772298};
// aapt resource value: 0
public static int ForegroundLinearLayout_android_foreground = 0;
// aapt resource value: 1
public static int ForegroundLinearLayout_android_foregroundGravity = 1;
// aapt resource value: 2
public static int ForegroundLinearLayout_foregroundInsidePadding = 2;
public static int[] LinearLayoutCompat = new int[] {
16842927,
16842948,
16843046,
16843047,
16843048,
2130772036,
2130772197,
2130772198,
2130772199};
// aapt resource value: 2
public static int LinearLayoutCompat_android_baselineAligned = 2;
// aapt resource value: 3
public static int LinearLayoutCompat_android_baselineAlignedChildIndex = 3;
// aapt resource value: 0
public static int LinearLayoutCompat_android_gravity = 0;
// aapt resource value: 1
public static int LinearLayoutCompat_android_orientation = 1;
// aapt resource value: 4
public static int LinearLayoutCompat_android_weightSum = 4;
// aapt resource value: 5
public static int LinearLayoutCompat_divider = 5;
// aapt resource value: 8
public static int LinearLayoutCompat_dividerPadding = 8;
// aapt resource value: 6
public static int LinearLayoutCompat_measureWithLargestChild = 6;
// aapt resource value: 7
public static int LinearLayoutCompat_showDividers = 7;
public static int[] LinearLayoutCompat_Layout = new int[] {
16842931,
16842996,
16842997,
16843137};
// aapt resource value: 0
public static int LinearLayoutCompat_Layout_android_layout_gravity = 0;
// aapt resource value: 2
public static int LinearLayoutCompat_Layout_android_layout_height = 2;
// aapt resource value: 3
public static int LinearLayoutCompat_Layout_android_layout_weight = 3;
// aapt resource value: 1
public static int LinearLayoutCompat_Layout_android_layout_width = 1;
public static int[] ListPopupWindow = new int[] {
16843436,
16843437};
// aapt resource value: 0
public static int ListPopupWindow_android_dropDownHorizontalOffset = 0;
// aapt resource value: 1
public static int ListPopupWindow_android_dropDownVerticalOffset = 1;
public static int[] LoadingImageView = new int[] {
2130772002,
2130772003,
2130772004};
// aapt resource value: 2
public static int LoadingImageView_circleCrop = 2;
// aapt resource value: 1
public static int LoadingImageView_imageAspectRatio = 1;
// aapt resource value: 0
public static int LoadingImageView_imageAspectRatioAdjust = 0;
public static int[] MapAttrs = new int[] {
2130771979,
2130771980,
2130771981,
2130771982,
2130771983,
2130771984,
2130771985,
2130771986,
2130771987,
2130771988,
2130771989,
2130771990,
2130771991,
2130771992,
2130771993,
2130771994,
2130771995,
2130771996,
2130771997,
2130771998,
2130771999,
2130772000,
2130772001};
// aapt resource value: 16
public static int MapAttrs_ambientEnabled = 16;
// aapt resource value: 1
public static int MapAttrs_cameraBearing = 1;
// aapt resource value: 18
public static int MapAttrs_cameraMaxZoomPreference = 18;
// aapt resource value: 17
public static int MapAttrs_cameraMinZoomPreference = 17;
// aapt resource value: 2
public static int MapAttrs_cameraTargetLat = 2;
// aapt resource value: 3
public static int MapAttrs_cameraTargetLng = 3;
// aapt resource value: 4
public static int MapAttrs_cameraTilt = 4;
// aapt resource value: 5
public static int MapAttrs_cameraZoom = 5;
// aapt resource value: 21
public static int MapAttrs_latLngBoundsNorthEastLatitude = 21;
// aapt resource value: 22
public static int MapAttrs_latLngBoundsNorthEastLongitude = 22;
// aapt resource value: 19
public static int MapAttrs_latLngBoundsSouthWestLatitude = 19;
// aapt resource value: 20
public static int MapAttrs_latLngBoundsSouthWestLongitude = 20;
// aapt resource value: 6
public static int MapAttrs_liteMode = 6;
// aapt resource value: 0
public static int MapAttrs_mapType = 0;
// aapt resource value: 7
public static int MapAttrs_uiCompass = 7;
// aapt resource value: 15
public static int MapAttrs_uiMapToolbar = 15;
// aapt resource value: 8
public static int MapAttrs_uiRotateGestures = 8;
// aapt resource value: 9
public static int MapAttrs_uiScrollGestures = 9;
// aapt resource value: 10
public static int MapAttrs_uiTiltGestures = 10;
// aapt resource value: 11
public static int MapAttrs_uiZoomControls = 11;
// aapt resource value: 12
public static int MapAttrs_uiZoomGestures = 12;
// aapt resource value: 13
public static int MapAttrs_useViewLifecycle = 13;
// aapt resource value: 14
public static int MapAttrs_zOrderOnTop = 14;
public static int[] MediaRouteButton = new int[] {
16843071,
16843072,
2130772024,
2130772187};
// aapt resource value: 1
public static int MediaRouteButton_android_minHeight = 1;
// aapt resource value: 0
public static int MediaRouteButton_android_minWidth = 0;
// aapt resource value: 3
public static int MediaRouteButton_buttonTint = 3;
// aapt resource value: 2
public static int MediaRouteButton_externalRouteEnabledDrawable = 2;
public static int[] MenuGroup = new int[] {
16842766,
16842960,
16843156,
16843230,
16843231,
16843232};
// aapt resource value: 5
public static int MenuGroup_android_checkableBehavior = 5;
// aapt resource value: 0
public static int MenuGroup_android_enabled = 0;
// aapt resource value: 1
public static int MenuGroup_android_id = 1;
// aapt resource value: 3
public static int MenuGroup_android_menuCategory = 3;
// aapt resource value: 4
public static int MenuGroup_android_orderInCategory = 4;
// aapt resource value: 2
public static int MenuGroup_android_visible = 2;
public static int[] MenuItem = new int[] {
16842754,
16842766,
16842960,
16843014,
16843156,
16843230,
16843231,
16843233,
16843234,
16843235,
16843236,
16843237,
16843375,
2130772200,
2130772201,
2130772202,
2130772203};
// aapt resource value: 14
public static int MenuItem_actionLayout = 14;
// aapt resource value: 16
public static int MenuItem_actionProviderClass = 16;
// aapt resource value: 15
public static int MenuItem_actionViewClass = 15;
// aapt resource value: 9
public static int MenuItem_android_alphabeticShortcut = 9;
// aapt resource value: 11
public static int MenuItem_android_checkable = 11;
// aapt resource value: 3
public static int MenuItem_android_checked = 3;
// aapt resource value: 1
public static int MenuItem_android_enabled = 1;
// aapt resource value: 0
public static int MenuItem_android_icon = 0;
// aapt resource value: 2
public static int MenuItem_android_id = 2;
// aapt resource value: 5
public static int MenuItem_android_menuCategory = 5;
// aapt resource value: 10
public static int MenuItem_android_numericShortcut = 10;
// aapt resource value: 12
public static int MenuItem_android_onClick = 12;
// aapt resource value: 6
public static int MenuItem_android_orderInCategory = 6;
// aapt resource value: 7
public static int MenuItem_android_title = 7;
// aapt resource value: 8
public static int MenuItem_android_titleCondensed = 8;
// aapt resource value: 4
public static int MenuItem_android_visible = 4;
// aapt resource value: 13
public static int MenuItem_showAsAction = 13;
public static int[] MenuView = new int[] {
16842926,
16843052,
16843053,
16843054,
16843055,
16843056,
16843057,
2130772204,
2130772205};
// aapt resource value: 4
public static int MenuView_android_headerBackground = 4;
// aapt resource value: 2
public static int MenuView_android_horizontalDivider = 2;
// aapt resource value: 5
public static int MenuView_android_itemBackground = 5;
// aapt resource value: 6
public static int MenuView_android_itemIconDisabledAlpha = 6;
// aapt resource value: 1
public static int MenuView_android_itemTextAppearance = 1;
// aapt resource value: 3
public static int MenuView_android_verticalDivider = 3;
// aapt resource value: 0
public static int MenuView_android_windowAnimationStyle = 0;
// aapt resource value: 7
public static int MenuView_preserveIconSpacing = 7;
// aapt resource value: 8
public static int MenuView_subMenuArrow = 8;
public static int[] NavigationView = new int[] {
16842964,
16842973,
16843039,
2130772053,
2130772299,
2130772300,
2130772301,
2130772302,
2130772303,
2130772304};
// aapt resource value: 0
public static int NavigationView_android_background = 0;
// aapt resource value: 1
public static int NavigationView_android_fitsSystemWindows = 1;
// aapt resource value: 2
public static int NavigationView_android_maxWidth = 2;
// aapt resource value: 3
public static int NavigationView_elevation = 3;
// aapt resource value: 9
public static int NavigationView_headerLayout = 9;
// aapt resource value: 7
public static int NavigationView_itemBackground = 7;
// aapt resource value: 5
public static int NavigationView_itemIconTint = 5;
// aapt resource value: 8
public static int NavigationView_itemTextAppearance = 8;
// aapt resource value: 6
public static int NavigationView_itemTextColor = 6;
// aapt resource value: 4
public static int NavigationView_menu = 4;
public static int[] PopupWindow = new int[] {
16843126,
16843465,
2130772206};
// aapt resource value: 1
public static int PopupWindow_android_popupAnimationStyle = 1;
// aapt resource value: 0
public static int PopupWindow_android_popupBackground = 0;
// aapt resource value: 2
public static int PopupWindow_overlapAnchor = 2;
public static int[] PopupWindowBackgroundState = new int[] {
2130772207};
// aapt resource value: 0
public static int PopupWindowBackgroundState_state_above_anchor = 0;
public static int[] RecycleListView = new int[] {
2130772208,
2130772209};
// aapt resource value: 0
public static int RecycleListView_paddingBottomNoButtons = 0;
// aapt resource value: 1
public static int RecycleListView_paddingTopNoTitle = 1;
public static int[] RecyclerView = new int[] {
16842948,
16842993,
2130772008,
2130772009,
2130772010,
2130772011};
// aapt resource value: 1
public static int RecyclerView_android_descendantFocusability = 1;
// aapt resource value: 0
public static int RecyclerView_android_orientation = 0;
// aapt resource value: 2
public static int RecyclerView_layoutManager = 2;
// aapt resource value: 4
public static int RecyclerView_reverseLayout = 4;
// aapt resource value: 3
public static int RecyclerView_spanCount = 3;
// aapt resource value: 5
public static int RecyclerView_stackFromEnd = 5;
public static int[] ScrimInsetsFrameLayout = new int[] {
2130772305};
// aapt resource value: 0
public static int ScrimInsetsFrameLayout_insetForeground = 0;
public static int[] ScrollingViewBehavior_Layout = new int[] {
2130772306};
// aapt resource value: 0
public static int ScrollingViewBehavior_Layout_behavior_overlapTop = 0;
public static int[] SearchView = new int[] {
16842970,
16843039,
16843296,
16843364,
2130772210,
2130772211,
2130772212,
2130772213,
2130772214,
2130772215,
2130772216,
2130772217,
2130772218,
2130772219,
2130772220,
2130772221,
2130772222};
// aapt resource value: 0
public static int SearchView_android_focusable = 0;
// aapt resource value: 3
public static int SearchView_android_imeOptions = 3;
// aapt resource value: 2
public static int SearchView_android_inputType = 2;
// aapt resource value: 1
public static int SearchView_android_maxWidth = 1;
// aapt resource value: 8
public static int SearchView_closeIcon = 8;
// aapt resource value: 13
public static int SearchView_commitIcon = 13;
// aapt resource value: 7
public static int SearchView_defaultQueryHint = 7;
// aapt resource value: 9
public static int SearchView_goIcon = 9;
// aapt resource value: 5
public static int SearchView_iconifiedByDefault = 5;
// aapt resource value: 4
public static int SearchView_layout = 4;
// aapt resource value: 15
public static int SearchView_queryBackground = 15;
// aapt resource value: 6
public static int SearchView_queryHint = 6;
// aapt resource value: 11
public static int SearchView_searchHintIcon = 11;
// aapt resource value: 10
public static int SearchView_searchIcon = 10;
// aapt resource value: 16
public static int SearchView_submitBackground = 16;
// aapt resource value: 14
public static int SearchView_suggestionRowLayout = 14;
// aapt resource value: 12
public static int SearchView_voiceIcon = 12;
public static int[] SignInButton = new int[] {
2130772005,
2130772006,
2130772007};
// aapt resource value: 0
public static int SignInButton_buttonSize = 0;
// aapt resource value: 1
public static int SignInButton_colorScheme = 1;
// aapt resource value: 2
public static int SignInButton_scopeUris = 2;
public static int[] SnackbarLayout = new int[] {
16843039,
2130772053,
2130772307};
// aapt resource value: 0
public static int SnackbarLayout_android_maxWidth = 0;
// aapt resource value: 1
public static int SnackbarLayout_elevation = 1;
// aapt resource value: 2
public static int SnackbarLayout_maxActionInlineWidth = 2;
public static int[] Spinner = new int[] {
16842930,
16843126,
16843131,
16843362,
2130772054};
// aapt resource value: 3
public static int Spinner_android_dropDownWidth = 3;
// aapt resource value: 0
public static int Spinner_android_entries = 0;
// aapt resource value: 1
public static int Spinner_android_popupBackground = 1;
// aapt resource value: 2
public static int Spinner_android_prompt = 2;
// aapt resource value: 4
public static int Spinner_popupTheme = 4;
public static int[] SwitchCompat = new int[] {
16843044,
16843045,
16843074,
2130772223,
2130772224,
2130772225,
2130772226,
2130772227,
2130772228,
2130772229,
2130772230,
2130772231,
2130772232,
2130772233};
// aapt resource value: 1
public static int SwitchCompat_android_textOff = 1;
// aapt resource value: 0
public static int SwitchCompat_android_textOn = 0;
// aapt resource value: 2
public static int SwitchCompat_android_thumb = 2;
// aapt resource value: 13
public static int SwitchCompat_showText = 13;
// aapt resource value: 12
public static int SwitchCompat_splitTrack = 12;
// aapt resource value: 10
public static int SwitchCompat_switchMinWidth = 10;
// aapt resource value: 11
public static int SwitchCompat_switchPadding = 11;
// aapt resource value: 9
public static int SwitchCompat_switchTextAppearance = 9;
// aapt resource value: 8
public static int SwitchCompat_thumbTextPadding = 8;
// aapt resource value: 3
public static int SwitchCompat_thumbTint = 3;
// aapt resource value: 4
public static int SwitchCompat_thumbTintMode = 4;
// aapt resource value: 5
public static int SwitchCompat_track = 5;
// aapt resource value: 6
public static int SwitchCompat_trackTint = 6;
// aapt resource value: 7
public static int SwitchCompat_trackTintMode = 7;
public static int[] TabItem = new int[] {
16842754,
16842994,
16843087};
// aapt resource value: 0
public static int TabItem_android_icon = 0;
// aapt resource value: 1
public static int TabItem_android_layout = 1;
// aapt resource value: 2
public static int TabItem_android_text = 2;
public static int[] TabLayout = new int[] {
2130772308,
2130772309,
2130772310,
2130772311,
2130772312,
2130772313,
2130772314,
2130772315,
2130772316,
2130772317,
2130772318,
2130772319,
2130772320,
2130772321,
2130772322,
2130772323};
// aapt resource value: 3
public static int TabLayout_tabBackground = 3;
// aapt resource value: 2
public static int TabLayout_tabContentStart = 2;
// aapt resource value: 5
public static int TabLayout_tabGravity = 5;
// aapt resource value: 0
public static int TabLayout_tabIndicatorColor = 0;
// aapt resource value: 1
public static int TabLayout_tabIndicatorHeight = 1;
// aapt resource value: 7
public static int TabLayout_tabMaxWidth = 7;
// aapt resource value: 6
public static int TabLayout_tabMinWidth = 6;
// aapt resource value: 4
public static int TabLayout_tabMode = 4;
// aapt resource value: 15
public static int TabLayout_tabPadding = 15;
// aapt resource value: 14
public static int TabLayout_tabPaddingBottom = 14;
// aapt resource value: 13
public static int TabLayout_tabPaddingEnd = 13;
// aapt resource value: 11
public static int TabLayout_tabPaddingStart = 11;
// aapt resource value: 12
public static int TabLayout_tabPaddingTop = 12;
// aapt resource value: 10
public static int TabLayout_tabSelectedTextColor = 10;
// aapt resource value: 8
public static int TabLayout_tabTextAppearance = 8;
// aapt resource value: 9
public static int TabLayout_tabTextColor = 9;
public static int[] TextAppearance = new int[] {
16842901,
16842902,
16842903,
16842904,
16842906,
16843105,
16843106,
16843107,
16843108,
2130772070};
// aapt resource value: 5
public static int TextAppearance_android_shadowColor = 5;
// aapt resource value: 6
public static int TextAppearance_android_shadowDx = 6;
// aapt resource value: 7
public static int TextAppearance_android_shadowDy = 7;
// aapt resource value: 8
public static int TextAppearance_android_shadowRadius = 8;
// aapt resource value: 3
public static int TextAppearance_android_textColor = 3;
// aapt resource value: 4
public static int TextAppearance_android_textColorHint = 4;
// aapt resource value: 0
public static int TextAppearance_android_textSize = 0;
// aapt resource value: 2
public static int TextAppearance_android_textStyle = 2;
// aapt resource value: 1
public static int TextAppearance_android_typeface = 1;
// aapt resource value: 9
public static int TextAppearance_textAllCaps = 9;
public static int[] TextInputLayout = new int[] {
16842906,
16843088,
2130772324,
2130772325,
2130772326,
2130772327,
2130772328,
2130772329,
2130772330,
2130772331,
2130772332,
2130772333,
2130772334,
2130772335,
2130772336,
2130772337};
// aapt resource value: 1
public static int TextInputLayout_android_hint = 1;
// aapt resource value: 0
public static int TextInputLayout_android_textColorHint = 0;
// aapt resource value: 6
public static int TextInputLayout_counterEnabled = 6;
// aapt resource value: 7
public static int TextInputLayout_counterMaxLength = 7;
// aapt resource value: 9
public static int TextInputLayout_counterOverflowTextAppearance = 9;
// aapt resource value: 8
public static int TextInputLayout_counterTextAppearance = 8;
// aapt resource value: 4
public static int TextInputLayout_errorEnabled = 4;
// aapt resource value: 5
public static int TextInputLayout_errorTextAppearance = 5;
// aapt resource value: 10
public static int TextInputLayout_hintAnimationEnabled = 10;
// aapt resource value: 3
public static int TextInputLayout_hintEnabled = 3;
// aapt resource value: 2
public static int TextInputLayout_hintTextAppearance = 2;
// aapt resource value: 13
public static int TextInputLayout_passwordToggleContentDescription = 13;
// aapt resource value: 12
public static int TextInputLayout_passwordToggleDrawable = 12;
// aapt resource value: 11
public static int TextInputLayout_passwordToggleEnabled = 11;
// aapt resource value: 14
public static int TextInputLayout_passwordToggleTint = 14;
// aapt resource value: 15
public static int TextInputLayout_passwordToggleTintMode = 15;
public static int[] Toolbar = new int[] {
16842927,
16843072,
2130772028,
2130772031,
2130772035,
2130772047,
2130772048,
2130772049,
2130772050,
2130772051,
2130772052,
2130772054,
2130772234,
2130772235,
2130772236,
2130772237,
2130772238,
2130772239,
2130772240,
2130772241,
2130772242,
2130772243,
2130772244,
2130772245,
2130772246,
2130772247,
2130772248,
2130772249,
2130772250};
// aapt resource value: 0
public static int Toolbar_android_gravity = 0;
// aapt resource value: 1
public static int Toolbar_android_minHeight = 1;
// aapt resource value: 21
public static int Toolbar_buttonGravity = 21;
// aapt resource value: 23
public static int Toolbar_collapseContentDescription = 23;
// aapt resource value: 22
public static int Toolbar_collapseIcon = 22;
// aapt resource value: 6
public static int Toolbar_contentInsetEnd = 6;
// aapt resource value: 10
public static int Toolbar_contentInsetEndWithActions = 10;
// aapt resource value: 7
public static int Toolbar_contentInsetLeft = 7;
// aapt resource value: 8
public static int Toolbar_contentInsetRight = 8;
// aapt resource value: 5
public static int Toolbar_contentInsetStart = 5;
// aapt resource value: 9
public static int Toolbar_contentInsetStartWithNavigation = 9;
// aapt resource value: 4
public static int Toolbar_logo = 4;
// aapt resource value: 26
public static int Toolbar_logoDescription = 26;
// aapt resource value: 20
public static int Toolbar_maxButtonHeight = 20;
// aapt resource value: 25
public static int Toolbar_navigationContentDescription = 25;
// aapt resource value: 24
public static int Toolbar_navigationIcon = 24;
// aapt resource value: 11
public static int Toolbar_popupTheme = 11;
// aapt resource value: 3
public static int Toolbar_subtitle = 3;
// aapt resource value: 13
public static int Toolbar_subtitleTextAppearance = 13;
// aapt resource value: 28
public static int Toolbar_subtitleTextColor = 28;
// aapt resource value: 2
public static int Toolbar_title = 2;
// aapt resource value: 14
public static int Toolbar_titleMargin = 14;
// aapt resource value: 18
public static int Toolbar_titleMarginBottom = 18;
// aapt resource value: 16
public static int Toolbar_titleMarginEnd = 16;
// aapt resource value: 15
public static int Toolbar_titleMarginStart = 15;
// aapt resource value: 17
public static int Toolbar_titleMarginTop = 17;
// aapt resource value: 19
public static int Toolbar_titleMargins = 19;
// aapt resource value: 12
public static int Toolbar_titleTextAppearance = 12;
// aapt resource value: 27
public static int Toolbar_titleTextColor = 27;
public static int[] View = new int[] {
16842752,
16842970,
2130772251,
2130772252,
2130772253};
// aapt resource value: 1
public static int View_android_focusable = 1;
// aapt resource value: 0
public static int View_android_theme = 0;
// aapt resource value: 3
public static int View_paddingEnd = 3;
// aapt resource value: 2
public static int View_paddingStart = 2;
// aapt resource value: 4
public static int View_theme = 4;
public static int[] ViewBackgroundHelper = new int[] {
16842964,
2130772254,
2130772255};
// aapt resource value: 0
public static int ViewBackgroundHelper_android_background = 0;
// aapt resource value: 1
public static int ViewBackgroundHelper_backgroundTint = 1;
// aapt resource value: 2
public static int ViewBackgroundHelper_backgroundTintMode = 2;
public static int[] ViewStubCompat = new int[] {
16842960,
16842994,
16842995};
// aapt resource value: 0
public static int ViewStubCompat_android_id = 0;
// aapt resource value: 2
public static int ViewStubCompat_android_inflatedId = 2;
// aapt resource value: 1
public static int ViewStubCompat_android_layout = 1;
static Styleable()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Styleable()
{
}
}
}
}
#pragma warning restore 1591
| mit |
Azure/azure-sdk-for-ruby | management/azure_mgmt_network/lib/2019-08-01/generated/azure_mgmt_network/models/managed_rule_set.rb | 2296 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2019_08_01
module Models
#
# Defines a managed rule set.
#
class ManagedRuleSet
include MsRestAzure
# @return [String] Defines the rule set type to use.
attr_accessor :rule_set_type
# @return [String] Defines the version of the rule set to use.
attr_accessor :rule_set_version
# @return [Array<ManagedRuleGroupOverride>] Defines the rule group
# overrides to apply to the rule set.
attr_accessor :rule_group_overrides
#
# Mapper for ManagedRuleSet class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ManagedRuleSet',
type: {
name: 'Composite',
class_name: 'ManagedRuleSet',
model_properties: {
rule_set_type: {
client_side_validation: true,
required: true,
serialized_name: 'ruleSetType',
type: {
name: 'String'
}
},
rule_set_version: {
client_side_validation: true,
required: true,
serialized_name: 'ruleSetVersion',
type: {
name: 'String'
}
},
rule_group_overrides: {
client_side_validation: true,
required: false,
serialized_name: 'ruleGroupOverrides',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'ManagedRuleGroupOverrideElementType',
type: {
name: 'Composite',
class_name: 'ManagedRuleGroupOverride'
}
}
}
}
}
}
}
end
end
end
end
| mit |
liuyang1/toy264 | h261/test.py | 167 | import sys
sys.path.append("..")
print(sys.path)
import bin
import h261
fn = "video.261"
data = open(fn, "rb").read()
pic = h261.Picture(data)
print(pic)
pic.dump()
| mit |
patrick-russell/fullcontacter | fullcontacter/lookup.py | 1126 | '''
Fullcontacter: A wrapper for the excellent and helpful Fullcontact.com APIs
Fullcontacter version 0.3
Utility module that uses requests to do the heavy lifting and get the data for further handling
'''
import requests
#configuration
API_VERSION = 'v2'
END_POINT = 'https://api.fullcontact.com/{0}/'.format(API_VERSION)
CLIENT_VERSION = '0.3'
USER_AGENT = 'Python /Fullcontacter: Fullcontact wrapper for Python. version {0} http://pypi.python.org/pypi/fullcontacter'.format(CLIENT_VERSION)
def lookup_request(fc_api, format, api_key, **kwargs):
lookup_end_point = END_POINT + fc_api + format
payload = {}
for key, value in kwargs.items():
payload[key] = value
payload['apiKey'] = api_key
lookup_request = requests.get(lookup_end_point, headers={'User-Agent': USER_AGENT}, params=payload)
if format == '.json':
results = {'satus_code': lookup_request.status_code, 'url': lookup_request.url, 'lookup': lookup_request.json()}
else:
results = {'satus_code': lookup_request.status_code, 'url': lookup_request.url, 'lookup': lookup_request.text}
return results
| mit |
jleeothon/tknz | tknz/grammar/TknzParser.java | 19851 | // Generated from tknz\grammar\Tknz.g4 by ANTLR 4.5
package tknz.grammar;
import java.util.TreeMap;
import tknz.core.Automaton;
import org.antlr.v4.runtime.atn.*;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.misc.*;
import org.antlr.v4.runtime.tree.*;
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
@SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"})
public class TknzParser extends Parser {
static { RuntimeMetaData.checkVersion("4.5", RuntimeMetaData.VERSION); }
protected static final DFA[] _decisionToDFA;
protected static final PredictionContextCache _sharedContextCache =
new PredictionContextCache();
public static final int
AUTOMATON=1, STATE=2, WITH=3, FROM=4, TO=5, GOTO=6, START=7, STOP=8, Identifier=9,
IGNORE=10, StringLiteral=11, WS=12, COMMENT=13;
public static final int
RULE_s = 0, RULE_automaton = 1, RULE_state = 2, RULE_transition = 3, RULE_setTransition = 4,
RULE_rangeTransition = 5, RULE_automatonModifiers = 6, RULE_stateModifier = 7,
RULE_start = 8, RULE_stop = 9;
public static final String[] ruleNames = {
"s", "automaton", "state", "transition", "setTransition", "rangeTransition",
"automatonModifiers", "stateModifier", "start", "stop"
};
private static final String[] _LITERAL_NAMES = {
null, "'automaton'", "'state'", "'with'", "'from'", "'to'", "'goto'",
"'start'", "'stop'", null, "'ignore'"
};
private static final String[] _SYMBOLIC_NAMES = {
null, "AUTOMATON", "STATE", "WITH", "FROM", "TO", "GOTO", "START", "STOP",
"Identifier", "IGNORE", "StringLiteral", "WS", "COMMENT"
};
public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);
/**
* @deprecated Use {@link #VOCABULARY} instead.
*/
@Deprecated
public static final String[] tokenNames;
static {
tokenNames = new String[_SYMBOLIC_NAMES.length];
for (int i = 0; i < tokenNames.length; i++) {
tokenNames[i] = VOCABULARY.getLiteralName(i);
if (tokenNames[i] == null) {
tokenNames[i] = VOCABULARY.getSymbolicName(i);
}
if (tokenNames[i] == null) {
tokenNames[i] = "<INVALID>";
}
}
}
@Override
@Deprecated
public String[] getTokenNames() {
return tokenNames;
}
@Override
public Vocabulary getVocabulary() {
return VOCABULARY;
}
@Override
public String getGrammarFileName() { return "Tknz.g4"; }
@Override
public String[] getRuleNames() { return ruleNames; }
@Override
public String getSerializedATN() { return _serializedATN; }
@Override
public ATN getATN() { return _ATN; }
public TknzParser(TokenStream input) {
super(input);
_interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache);
}
public static class SContext extends ParserRuleContext {
public List<AutomatonContext> automaton() {
return getRuleContexts(AutomatonContext.class);
}
public AutomatonContext automaton(int i) {
return getRuleContext(AutomatonContext.class,i);
}
public SContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_s; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof TknzListener ) ((TknzListener)listener).enterS(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof TknzListener ) ((TknzListener)listener).exitS(this);
}
}
public final SContext s() throws RecognitionException {
SContext _localctx = new SContext(_ctx, getState());
enterRule(_localctx, 0, RULE_s);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(23);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==AUTOMATON || _la==IGNORE) {
{
{
setState(20);
automaton();
}
}
setState(25);
_errHandler.sync(this);
_la = _input.LA(1);
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class AutomatonContext extends ParserRuleContext {
public TerminalNode AUTOMATON() { return getToken(TknzParser.AUTOMATON, 0); }
public TerminalNode Identifier() { return getToken(TknzParser.Identifier, 0); }
public List<AutomatonModifiersContext> automatonModifiers() {
return getRuleContexts(AutomatonModifiersContext.class);
}
public AutomatonModifiersContext automatonModifiers(int i) {
return getRuleContext(AutomatonModifiersContext.class,i);
}
public List<StateContext> state() {
return getRuleContexts(StateContext.class);
}
public StateContext state(int i) {
return getRuleContext(StateContext.class,i);
}
public AutomatonContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_automaton; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof TknzListener ) ((TknzListener)listener).enterAutomaton(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof TknzListener ) ((TknzListener)listener).exitAutomaton(this);
}
}
public final AutomatonContext automaton() throws RecognitionException {
AutomatonContext _localctx = new AutomatonContext(_ctx, getState());
enterRule(_localctx, 2, RULE_automaton);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(29);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==IGNORE) {
{
{
setState(26);
automatonModifiers();
}
}
setState(31);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(32);
match(AUTOMATON);
setState(33);
match(Identifier);
setState(37);
_errHandler.sync(this);
_la = _input.LA(1);
while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << STATE) | (1L << START) | (1L << STOP))) != 0)) {
{
{
setState(34);
state();
}
}
setState(39);
_errHandler.sync(this);
_la = _input.LA(1);
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class StateContext extends ParserRuleContext {
public TerminalNode STATE() { return getToken(TknzParser.STATE, 0); }
public TerminalNode Identifier() { return getToken(TknzParser.Identifier, 0); }
public List<StateModifierContext> stateModifier() {
return getRuleContexts(StateModifierContext.class);
}
public StateModifierContext stateModifier(int i) {
return getRuleContext(StateModifierContext.class,i);
}
public List<TransitionContext> transition() {
return getRuleContexts(TransitionContext.class);
}
public TransitionContext transition(int i) {
return getRuleContext(TransitionContext.class,i);
}
public StateContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_state; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof TknzListener ) ((TknzListener)listener).enterState(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof TknzListener ) ((TknzListener)listener).exitState(this);
}
}
public final StateContext state() throws RecognitionException {
StateContext _localctx = new StateContext(_ctx, getState());
enterRule(_localctx, 4, RULE_state);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(43);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==START || _la==STOP) {
{
{
setState(40);
stateModifier();
}
}
setState(45);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(46);
match(STATE);
setState(47);
match(Identifier);
setState(51);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==WITH || _la==FROM) {
{
{
setState(48);
transition();
}
}
setState(53);
_errHandler.sync(this);
_la = _input.LA(1);
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class TransitionContext extends ParserRuleContext {
public SetTransitionContext setTransition() {
return getRuleContext(SetTransitionContext.class,0);
}
public RangeTransitionContext rangeTransition() {
return getRuleContext(RangeTransitionContext.class,0);
}
public TransitionContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_transition; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof TknzListener ) ((TknzListener)listener).enterTransition(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof TknzListener ) ((TknzListener)listener).exitTransition(this);
}
}
public final TransitionContext transition() throws RecognitionException {
TransitionContext _localctx = new TransitionContext(_ctx, getState());
enterRule(_localctx, 6, RULE_transition);
try {
setState(56);
switch (_input.LA(1)) {
case WITH:
enterOuterAlt(_localctx, 1);
{
setState(54);
setTransition();
}
break;
case FROM:
enterOuterAlt(_localctx, 2);
{
setState(55);
rangeTransition();
}
break;
default:
throw new NoViableAltException(this);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class SetTransitionContext extends ParserRuleContext {
public TerminalNode WITH() { return getToken(TknzParser.WITH, 0); }
public TerminalNode StringLiteral() { return getToken(TknzParser.StringLiteral, 0); }
public TerminalNode GOTO() { return getToken(TknzParser.GOTO, 0); }
public TerminalNode Identifier() { return getToken(TknzParser.Identifier, 0); }
public SetTransitionContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_setTransition; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof TknzListener ) ((TknzListener)listener).enterSetTransition(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof TknzListener ) ((TknzListener)listener).exitSetTransition(this);
}
}
public final SetTransitionContext setTransition() throws RecognitionException {
SetTransitionContext _localctx = new SetTransitionContext(_ctx, getState());
enterRule(_localctx, 8, RULE_setTransition);
try {
enterOuterAlt(_localctx, 1);
{
setState(58);
match(WITH);
setState(59);
match(StringLiteral);
setState(60);
match(GOTO);
setState(61);
match(Identifier);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class RangeTransitionContext extends ParserRuleContext {
public TerminalNode FROM() { return getToken(TknzParser.FROM, 0); }
public List<TerminalNode> StringLiteral() { return getTokens(TknzParser.StringLiteral); }
public TerminalNode StringLiteral(int i) {
return getToken(TknzParser.StringLiteral, i);
}
public TerminalNode TO() { return getToken(TknzParser.TO, 0); }
public TerminalNode GOTO() { return getToken(TknzParser.GOTO, 0); }
public TerminalNode Identifier() { return getToken(TknzParser.Identifier, 0); }
public RangeTransitionContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_rangeTransition; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof TknzListener ) ((TknzListener)listener).enterRangeTransition(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof TknzListener ) ((TknzListener)listener).exitRangeTransition(this);
}
}
public final RangeTransitionContext rangeTransition() throws RecognitionException {
RangeTransitionContext _localctx = new RangeTransitionContext(_ctx, getState());
enterRule(_localctx, 10, RULE_rangeTransition);
try {
enterOuterAlt(_localctx, 1);
{
setState(63);
match(FROM);
setState(64);
match(StringLiteral);
setState(65);
match(TO);
setState(66);
match(StringLiteral);
setState(67);
match(GOTO);
setState(68);
match(Identifier);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class AutomatonModifiersContext extends ParserRuleContext {
public TerminalNode IGNORE() { return getToken(TknzParser.IGNORE, 0); }
public AutomatonModifiersContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_automatonModifiers; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof TknzListener ) ((TknzListener)listener).enterAutomatonModifiers(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof TknzListener ) ((TknzListener)listener).exitAutomatonModifiers(this);
}
}
public final AutomatonModifiersContext automatonModifiers() throws RecognitionException {
AutomatonModifiersContext _localctx = new AutomatonModifiersContext(_ctx, getState());
enterRule(_localctx, 12, RULE_automatonModifiers);
try {
enterOuterAlt(_localctx, 1);
{
setState(70);
match(IGNORE);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class StateModifierContext extends ParserRuleContext {
public StartContext start() {
return getRuleContext(StartContext.class,0);
}
public StopContext stop() {
return getRuleContext(StopContext.class,0);
}
public StateModifierContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_stateModifier; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof TknzListener ) ((TknzListener)listener).enterStateModifier(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof TknzListener ) ((TknzListener)listener).exitStateModifier(this);
}
}
public final StateModifierContext stateModifier() throws RecognitionException {
StateModifierContext _localctx = new StateModifierContext(_ctx, getState());
enterRule(_localctx, 14, RULE_stateModifier);
try {
setState(74);
switch (_input.LA(1)) {
case START:
enterOuterAlt(_localctx, 1);
{
setState(72);
start();
}
break;
case STOP:
enterOuterAlt(_localctx, 2);
{
setState(73);
stop();
}
break;
default:
throw new NoViableAltException(this);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class StartContext extends ParserRuleContext {
public TerminalNode START() { return getToken(TknzParser.START, 0); }
public StartContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_start; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof TknzListener ) ((TknzListener)listener).enterStart(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof TknzListener ) ((TknzListener)listener).exitStart(this);
}
}
public final StartContext start() throws RecognitionException {
StartContext _localctx = new StartContext(_ctx, getState());
enterRule(_localctx, 16, RULE_start);
try {
enterOuterAlt(_localctx, 1);
{
setState(76);
match(START);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class StopContext extends ParserRuleContext {
public TerminalNode STOP() { return getToken(TknzParser.STOP, 0); }
public StopContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_stop; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof TknzListener ) ((TknzListener)listener).enterStop(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof TknzListener ) ((TknzListener)listener).exitStop(this);
}
}
public final StopContext stop() throws RecognitionException {
StopContext _localctx = new StopContext(_ctx, getState());
enterRule(_localctx, 18, RULE_stop);
try {
enterOuterAlt(_localctx, 1);
{
setState(78);
match(STOP);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static final String _serializedATN =
"\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd\3\17S\4\2\t\2\4\3\t"+
"\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\3"+
"\2\7\2\30\n\2\f\2\16\2\33\13\2\3\3\7\3\36\n\3\f\3\16\3!\13\3\3\3\3\3\3"+
"\3\7\3&\n\3\f\3\16\3)\13\3\3\4\7\4,\n\4\f\4\16\4/\13\4\3\4\3\4\3\4\7\4"+
"\64\n\4\f\4\16\4\67\13\4\3\5\3\5\5\5;\n\5\3\6\3\6\3\6\3\6\3\6\3\7\3\7"+
"\3\7\3\7\3\7\3\7\3\7\3\b\3\b\3\t\3\t\5\tM\n\t\3\n\3\n\3\13\3\13\3\13\2"+
"\2\f\2\4\6\b\n\f\16\20\22\24\2\2O\2\31\3\2\2\2\4\37\3\2\2\2\6-\3\2\2\2"+
"\b:\3\2\2\2\n<\3\2\2\2\fA\3\2\2\2\16H\3\2\2\2\20L\3\2\2\2\22N\3\2\2\2"+
"\24P\3\2\2\2\26\30\5\4\3\2\27\26\3\2\2\2\30\33\3\2\2\2\31\27\3\2\2\2\31"+
"\32\3\2\2\2\32\3\3\2\2\2\33\31\3\2\2\2\34\36\5\16\b\2\35\34\3\2\2\2\36"+
"!\3\2\2\2\37\35\3\2\2\2\37 \3\2\2\2 \"\3\2\2\2!\37\3\2\2\2\"#\7\3\2\2"+
"#\'\7\13\2\2$&\5\6\4\2%$\3\2\2\2&)\3\2\2\2\'%\3\2\2\2\'(\3\2\2\2(\5\3"+
"\2\2\2)\'\3\2\2\2*,\5\20\t\2+*\3\2\2\2,/\3\2\2\2-+\3\2\2\2-.\3\2\2\2."+
"\60\3\2\2\2/-\3\2\2\2\60\61\7\4\2\2\61\65\7\13\2\2\62\64\5\b\5\2\63\62"+
"\3\2\2\2\64\67\3\2\2\2\65\63\3\2\2\2\65\66\3\2\2\2\66\7\3\2\2\2\67\65"+
"\3\2\2\28;\5\n\6\29;\5\f\7\2:8\3\2\2\2:9\3\2\2\2;\t\3\2\2\2<=\7\5\2\2"+
"=>\7\r\2\2>?\7\b\2\2?@\7\13\2\2@\13\3\2\2\2AB\7\6\2\2BC\7\r\2\2CD\7\7"+
"\2\2DE\7\r\2\2EF\7\b\2\2FG\7\13\2\2G\r\3\2\2\2HI\7\f\2\2I\17\3\2\2\2J"+
"M\5\22\n\2KM\5\24\13\2LJ\3\2\2\2LK\3\2\2\2M\21\3\2\2\2NO\7\t\2\2O\23\3"+
"\2\2\2PQ\7\n\2\2Q\25\3\2\2\2\t\31\37\'-\65:L";
public static final ATN _ATN =
new ATNDeserializer().deserialize(_serializedATN.toCharArray());
static {
_decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];
for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
}
}
} | mit |
rcalderonpy/PaginaSimons | src/PersonalBundle/Controller/DefaultController.php | 1288 | <?php
namespace PersonalBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use PersonalBundle\Form\EmpresaType;
use PersonalBundle\Entity\Empresa;
class DefaultController extends Controller
{
public function indexAction(){
return $this->render('PersonalBundle:Default:index.html.twig');
}
public function cargaEmpresaAction(Request $request)
{
$empresa=new Empresa();
$form=$this->createForm(EmpresaType::class, $empresa);
$form->handleRequest($request);
if($form->isValid()){
$empresa
->setNombre($form->get("nombre")->getData())
->setApellido($form->get("apellido")->getData())
->setNpatMtess($form->get("npatMtess")->getData())
->setNpatIps($form->get("npatIps")->getData())
->setPwMtess($form->get("pwMtess")->getData())
->setPwIps($form->get("pwIps")->getData());
$em=$this->getDoctrine()->getEntityManager();
$em->persist($empresa);
$em->flush();
}
return $this->render('PersonalBundle:Default:empresa.html.twig', array(
"form"=>$form->createView()
));
}
} | mit |
AndCake/zino | src/zino-light.js | 3331 | import {isObj, toArray, identity} from './utils';
import * as browser from './browser';
import {Zino, actions, setDocument, setComponentLoader} from './facade';
import {setDataRegistry} from './core';
let urlRegistry = window.zinoTagRegistry || {},
dirtyTags = [],
mountTags = [],
parseCode = identity,
tagObserver = new MutationObserver(records => {
records.forEach(record => {
let added = record.addedNodes,
removed = record.removedNodes;
if (added.length > 0) {
mountTags = [].concat.call(added, mountTags);
} else if (removed.length > 0) {
[].forEach.call(removed, tag => {
(tag.children && toArray(tag.querySelectorAll('[__ready]')) || []).concat(tag).forEach(actions.unmount);
});
}
});
});
setDataRegistry(window.zinoDataRegistry || {});
window.Zino = Zino;
Zino.isBrowser = true;
Zino.isServer = false;
Zino.fetch = function(url, callback, cache, code) {
if (cache && urlRegistry[url] && !urlRegistry[url].callback) {
return callback(urlRegistry[url], 200);
} else if (isObj(urlRegistry[url])) {
return urlRegistry[url].callback.push(callback);
}
urlRegistry[url] = code || {
callback: [callback]
};
if (code) return;
let req = new XMLHttpRequest();
req.open('GET', url, true);
req.onreadystatechange = () => {
if (req.readyState === 4) {
let callbacks = urlRegistry[url].callback;
if (req.status === 200) {
urlRegistry[url] = req.responseText;
}
if (!cache) delete urlRegistry[url];
callbacks.forEach(cb => cb(req.responseText, req.status));
}
};
req.send();
};
setComponentLoader((url, fn) => {
Zino.fetch(url, (data, status) => {
let path = url.replace(/[^\/]+$/g, '');
if (status === 200) {
let code;
try {
data = parseCode(data);
code = new Function('return ' + data.replace(/url\((\\*['"])?(.*?)\1\)/g, function(g, quote, url) {
if (url.indexOf('data:') === 0 || url.indexOf('http') === 0 || url.indexOf('//') === 0 || url.indexOf('/') === 0) return g;
return 'url(' + path + url + ')';
}).replace(/\bZino.import\s*\(/g, 'Zino.import.call({path: ' + JSON.stringify(path) + '}, ').trim().replace(/;$/, ''))();
if (typeof code(() => {}, Zino) === 'function') {
code = code();
}
} catch(e) {
e.message = 'Unable to import tag ' + url.replace(/.*\//g, '') + ': ' + e.message;
throw e;
}
fn(code);
}
}, true);
});
setDocument(window.document);
export {Zino};
export function setParser(fn) { parseCode = fn; };
Zino.on('--zino-attach-events', browser.attachSubEvents);
Zino.on('--zino-rerender-tag', tag => dirtyTags.indexOf(tag) < 0 && dirtyTags.push(tag));
Zino.trigger('publish-style', '[__ready] { contain: content; }');
toArray(document.querySelectorAll('[rel="zino-tag"]')).forEach(tag => Zino.import(tag.href));
tagObserver.observe(document.body, {
subtree: true,
childList: true
});
function loopList(start, list, action) {
while (list.length > 0) {
let entry = list.shift();
if (entry instanceof NodeList || entry.length > 0) {
for (var all in entry) {
action(entry[all]);
}
} else {
action(entry);
}
if (performance.now() - start > 16) { break; }
}
}
requestAnimationFrame(function reRender(start) {
loopList(start, mountTags, actions.mount);
loopList(start, dirtyTags, actions.render);
requestAnimationFrame(reRender);
});
| mit |
k3v/dfx-and-more | src/ast/power.cc | 2936 | #include <math.h>
#include "dfxam.h"
using namespace dfxam::ast;
Power::Power(Expression* left, Expression* right)
: BinaryOperator(left, right) {}
// (f(x) ^ g(x))' = (e ^ ln(f(x) ^ g(x))) * (g(x)ln(f(x)))'
Expression* Power::derivative(repl::ExecutionEngine* eng, Function* respect) {
auto left = new Power(new E(), new Log(new E(), clone()));
auto right = new Product(getRight()->clone(), new Log(new E(), getLeft()->clone()));
Product* p = new Product(right->derivative(eng, respect), left);
delete right;
return p;
}
Expression* Power::substitute(repl::ExecutionEngine* eng) {
return new Power(getLeft()->substitute(eng), getRight()->substitute(eng));
}
//TODO
Expression* Power::simplify(repl::ExecutionEngine* eng) {
// std::cout << "Simplifying: " << this << std::endl;
auto left = getLeft()->simplify(eng);
auto right = getRight()->simplify(eng);
if (left->isConstant() && right->isConstant()) {
double lVal = static_cast<Constant*>(left)->getValue();
double rVal = static_cast<Constant*>(right)->getValue();
delete left;
delete right;
return new Constant(pow(lVal, rVal));
}
// 1 ^ x = 1
if (Constant::isConstantValue(left, 1)) {
delete right;
return left;
}
// x ^ 0 = 1
if (Constant::isConstantValue(right, 0)) {
delete left;
delete right;
return new Constant(1);
}
// x ^ 1 = x
if (Constant::isConstantValue(right, 1)) {
delete right;
return left;
}
if (Power* p = dynamic_cast<Power*>(left)) {
Product* pow = new Product(p->getRight()->clone(), right);
Power* ret = new Power(p->getLeft()->clone(), pow);
Expression* simpl = ret->simplify(eng);
delete left;
delete ret;
return simpl;
}
// a ^ log_a(x) = x
if (Log* l = dynamic_cast<Log*>(right)) {
if (left->equals(eng, l->getLeft())) {
auto r = l->getRight()->clone();
delete left;
delete right;
return r;
}
}
return new Power(left, right);
}
std::string Power::toString() const {
std::stringstream s;
s << "(" << getLeft()->toString() << ") ^ (" << getRight()->toString() << ")";
return s.str();
}
bool Power::equals(repl::ExecutionEngine* eng, Expression* expr) {
Power* p = nullptr;
if (!(p = dynamic_cast<Power*>(expr))) {
return false;
}
auto thisL = getLeft()->simplify(eng);
auto thisR = getRight()->simplify(eng);
auto exprL = p->getLeft()->simplify(eng);
auto exprR = p->getRight()->simplify(eng);
bool equality = thisL->equals(eng, exprL) && thisR->equals(eng, exprR);
delete thisL;
delete thisR;
delete exprL;
delete exprR;
return equality;
}
Expression* Power::clone() {
return new Power(getLeft()->clone(), getRight()->clone());
}
| mit |
jbejar/QuietStreets | userscripts/QuietStreets - Booking.com.user.js | 1489 | // ==UserScript==
// @name QuietStreets - Booking.com
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Embed Crimereports.com
// @author jbejar
// @match https://www.booking.com/hotel/us/*
// @grant none
// ==/UserScript==
var address = $("span.hp_address_subtitle").text().trim();
var search = encodeURIComponent(encodeURIComponent(address));
vals = $("a.map_static_zoom").attr("style").split(/[=,&]/);
lat = vals[4];
lng = vals[5];
iframe = '<iframe src="https://www.crimereports.com/home/?is_widget=true#!/dashboard?incident_types=Assault%252CAssault%2520with%2520Deadly%2520Weapon%252CBreaking%2520%2526%2520Entering%252CDisorder%252CDrugs%252CHomicide%252CKidnapping%252CLiquor%252COther%2520Sexual%2520Offense%252CProperty%2520Crime%252CProperty%2520Crime%2520Commercial%252CProperty%2520Crime%2520Residential%252CQuality%2520of%2520Life%252CRobbery%252CSexual%2520Assault%252CSexual%2520Offense%252CTheft%252CTheft%2520from%2520Vehicle%252CTheft%2520of%2520Vehicle&start_date=2017-03-25&end_date=2017-04-08&days=sunday%252Cmonday%252Ctuesday%252Cwednesday%252Cthursday%252Cfriday%252Csaturday&start_time=0&end_time=23&include_sex_offenders=false&zoom=16&lat=' +
lat + '&lng=' + lng + '¤t_tab=list&shapeIds=&shape_id=false&date_type=relative&searchText=' + search + '" width="768" height="586" style="border: 1px solid #28566c;"></iframe>';
$("#photos_distinct").after(iframe);
| mit |
danlo/RSS-Collector | lib/index.js | 12614 | /**
* @author [email protected] Daniel Lo
* @license MIT License. See LICENSE.txt
*/
/*jslint devel: true, undef: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: true */
/*global __dirname, require, setTimeout, clearTimeout */
"use strict";
var redis = require('redis'),
util = require('util'),
message = require('./message'),
pp = require('./util').pp;
require('./date');
var base = {
config: null,
end: function() { },
run: function() { },
help: function() {
return 'Need to add help for this item';
},
/*
* @return {redis.createClient}
*/
createRedis: function() {
return redis.createClient(this.config.redis.port, this.config.redis.host);
},
/*
* Will terminate the connection
* @param {redis.createClient} client
* @param {Function} callback(message) executes this code when msg.command == message.QUIT comes in.
* @return {redis.createClient}
*/
watchForQuit: function(callback) {
var self = this;
var client = this.createRedis();
var channel = this.config.redis_keys.channel;
client.on('connect', function() {
client.subscribe(self.config.redis_keys.channel);
});
client.on('message', function(channel, new_message) {
var msg = new message.Message();
msg.parseJSON(new_message);
if ( msg.command === message.QUIT ) {
callback(msg);
client.unsubscribe();
client.quit();
client.end();
}
});
return self;
}
};
/**
* Dump redis history and info to console
*/
function Dump() {
var self = this;
self.help = function() {
return '\'dump\' will dump the contents of redis to the console';
};
self.run = function() {
var client = this.createRedis();
self.end = function() {
client.quit();
client.end();
};
client.llen(this.config.redis_keys.history_key, function(err, reply) {
console.log('We are listening to redis server: redis://' + self.config.redis.host + ':' + self.config.redis.port);
console.log('The redis channel we are listening to is: ' + self.config.redis_keys.channel);
var count = parseInt(reply, 10);
console.log('There are ' + count + ' items stored in the history; history_key = ' + self.config.redis_keys.history_key);
client.lrange(self.config.redis_keys.history_key, 0, -1, function(err, reply) {
pp(reply);
for (var i = 0; i < reply.length; i += 1) {
console.log(reply[i]);
}
self.end();
});
});
};
}
Dump.prototype = base;
exports.Dump = Dump;
/**
* Send a quick message out via redis
*/
function Say() {
var self = this;
self.help = '\'say "message"\' will send the contents of a message to RSS-Collector via redis pub-sub';
self.run = function() {
var client = self.createRedis();
var mesg = new message.Message({
command: message.DATA,
category: 'command line',
data: Array.prototype.slice.call(arguments).join(' ')
});
client.on('connect', function() {
var json = mesg.toJSON();
console.log('Sending 1 messages to channel: ' + self.config.redis_keys.channel + ' message: ' + json);
client.publish(self.config.redis_keys.channel, json);
client.quit();
client.end();
});
};
}
Say.prototype = base;
exports.Say = Say;
/**
* Accept POST/GET requests and insert into the redis pub-sub model
*/
function AcceptHTTPInput() {
var self = this;
self.help = function() {
return '\'accept_http_input\' will start an http service at http://' + this.config.http_server_input.host + ':' + this.config.http_server_input.port + '/' + " which will accept GET messages\n";
};
self.running = false;
self.run = function() {
var http = require('http'),
url = require('url'),
client = self.createRedis();
self.running = false;
// server actions
var server = http.createServer();
server.on('request', function (req, res) {
if ( req.method === 'GET' ) {
// get the query parts and assign them to msg
var parts = url.parse(req.url, true);
var msg = new message.Message();
msg.bulk_assign(parts.query);
// save message
client.publish(self.config.redis_keys.channel, msg.toJSON());
// signify that we have recieved the content.
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('GET Received.\n');
if ( msg.command === message.QUIT ) {
self.end();
}
} else if ( req.method === 'POST' ) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('POST Received.\n');
}
});
// monitor for quit request
this.watchForQuit(function(msg) {
self.end();
});
// this is how we close
self.end = function() {
if ( self.running ) {
self.running = false;
client.quit();
client.end();
server.close();
}
};
server.listen(this.config.http_server_input.port, this.config.http_server_input.host);
console.log('HTTP Input Server running at http://' + this.config.http_server_input.host + ':' + this.config.http_server_input.port + '/');
this.running = true;
};
}
AcceptHTTPInput.prototype = base;
exports.AcceptHTTPInput = AcceptHTTPInput;
/*
* listener does nothing but listen to the pub-sub in redis and display the message to console
* This is useful for debugging
*/
function Listener() {
var self = this;
self.help = function() {
return "\'listener\' will monitor the redis channel and display messages.\n";
};
self.run = function() {
var client = self.createRedis();
// monitor for quit request
this.watchForQuit(function(msg) {
self.end();
});
client.on('message', function(channel, new_message) {
var msg = new message.Message();
msg.parseJSON(new_message);
console.log('listener recieved: ' + msg._raw );
});
// end
self.end = function() {
client.unsubscribe();
client.quit();
client.end();
};
client.subscribe(this.config.redis_keys.channel);
console.log('Listening to: ' + this.config.redis_keys.channel);
};
}
Listener.prototype = base;
exports.Listener = Listener;
/*
* RSSServer displays the history as an rss feed
*/
function RSSServer() {
var self = this;
self.help = function() {
return '\'rss_server\' will start an http rss service at http://' + this.config.http_server_rss.host + ':' + this.config.http_server_rss.port + '/' + "\n";
};
/* rss_header produces the rss header
* @param {http.ServerResponse} res
* @param {Date} date
*/
self.rss_header = function(res, date) {
if ( date === undefined ) {
date = new Date();
}
res.write('<?xml version="1.0" encoding="UTF-8" ?>' + "\n");
res.write('<rss version="2.0">' + "\n");
res.write('<channel>' + "\n");
res.write('<title>' + this.config.rss.title + '</title>' + "\n");
// res.write('<description>This is an example of an RSS feed</description>' + "\n");
res.write('<link>https://github.com/danlo</link>' + "\n");
res.write('<lastBuildDate>' + date.rfc822date() + '</lastBuildDate>' + "\n");
res.write('<pubDate>' + date.rfc822date() + '</pubDate>' + "\n");
};
/* rss_header produces the rss footer
* @param {http.ServerResponse} res
*/
self.rss_footer = function(res) {
res.write('</channel>' + "\n");
res.write('</rss>' + "\n");
};
/* rss_header produces the rss footer
* @param {http.ServerResponse} res
* @param {Message} msg
*/
self.rss_format = function(res, msg) {
res.write('<item>' + "\n");
res.write('<title>' + msg.category + ' / ' + msg.command + '</title>' + "\n");
res.write('<description>' + msg.data + '</description>' + "\n");
// res.write('<link>N/A</link>' + "\n");
res.write('<guid>' + msg.guid + '</guid>' + "\n");
res.write('<pubDate>' + msg.eventDate.rfc822date() + '</pubDate>' + "\n");
res.write('</item>' + "\n");
};
self.run = function() {
var client = self.createRedis();
var http = require('http');
var server = http.createServer(function (req, res) {
client.lrange(self.config.redis_keys.history_key, 0, -1, function(err, reply) {
res.writeHead(200, {'Content-Type': 'application/rss+xml'});
self.rss_header(res);
for (var i = 0; i < reply.length; i+=1) {
var msg = new message.Message();
msg.parseJSON(reply[i]);
self.rss_format(res, msg);
}
self.rss_footer(res);
res.end();
});
});
this.watchForQuit(function(msg) {
self.end();
});
// end
self.end = function() {
client.quit();
client.end();
server.close();
};
server.listen(this.config.http_server_rss.port, this.config.http_server_rss.host);
console.log('RSS Server running at http://' + this.config.http_server_rss.host + ':' + this.config.http_server_rss.port + '/');
};
}
RSSServer.prototype = base;
exports.RSSServer = RSSServer;
/*
* historian listens to the pub-sub channel and stores it into the history
*/
function Historian() {
var self = this;
self.help = function() {
return "'Historian' will record all messages on the redis channel: " + this.config.redis_keys.channel + ' start an http rss service at http://' + this.config.http_server_rss.host + ':' + this.config.http_server_rss.port + "/\n";
};
self.run = function() {
var listener = self.createRedis(),
history = self.createRedis();
this.watchForQuit(function(msg) {
self.end();
});
listener.on('message', function(channel, new_message) {
var msg = new message.Message();
msg.parseJSON(new_message);
if ( msg.command !== message.QUIT ) {
console.log('historian saving: ' + msg._raw);
history.lpush(self.config.redis_keys.history_key, msg, function(err, reply) {
if (parseInt(reply, 10) > self.config.history_max_count) {
// trim, key is too long
history.ltrim(self.config.redis_keys.history_key, 0, self.config.redis_keys.history_max_count - 1);
}
});
}
});
self.end = function() {
listener.unsubscribe();
listener.quit();
listener.end();
history.quit();
history.end();
};
listener.subscribe(this.config.redis_keys.channel);
console.log('historian is listening to: ' + this.config.redis_keys.channel);
};
}
Historian.prototype = base;
exports.Historian = Historian;
/*
* Purge will remove all RSS-Collector information
*/
function Purge() {
var self = this;
self.help = function() {
return "'purge' will remove all currently stored redis_keys associated with RSS-Collector\n";
};
self.run = function() {
var client = self.createRedis();
client.on('connect', function() {
client.del(self.config.redis_keys.channel);
client.del(self.config.redis_keys.history_key);
client.del(self.config.redis_keys.history_duration);
client.del(self.config.redis_keys.history_max_count);
client.quit();
client.end();
console.log('Purged RSS-Collector keys');
});
};
}
Purge.prototype = base;
exports.Purge = Purge;
| mit |
xiaohuihuigh/cpp | acm/hdu/1434.cpp | 1222 | #include<bits/stdc++.h>
using namespace std;
#define sa(x) scanf("%d",&x)
const int maxn = 10005;
struct node{
string name;
int rp;
bool operator < (const node a) const {
if(rp == a.rp)return name<a.name;
return rp>a.rp;
}
}g;
int main(){
string a;
int n,m;
while(cin>>n>>m){
priority_queue<node> q[maxn];
for(int i = 1;i<=n;i++){
int x;
cin>>x;
for (int j = 0;j<x;j++){
cin>>g.name>>g.rp;
q[i].push(g);
}
}
for(int i = 0;i<m;i++){
string a;
cin>>a;
if(a == "GETOUT"){
int d;
cin>>d;
g = q[d].top();
q[d].pop();
cout<<g.name<<endl;
}
else if(a == "JOIN"){
int d1,d2;
cin>>d1>>d2;
while(!q[d2].empty()){
g = q[d2].top();
q[d2].pop();
q[d1].push(g);
}
}
else{
int d;
cin>>d>>g.name>>g.rp;
q[d].push(g);
}
}
}
}
| mit |
EusthEnoptEron/Sketchball | Sketchball/Controls/ElementControl.Designer.cs | 1351 | namespace Sketchball.Controls
{
partial class ElementControl
{
/// <summary>
/// Erforderliche Designervariable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Verwendete Ressourcen bereinigen.
/// </summary>
/// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Vom Komponenten-Designer generierter Code
/// <summary>
/// Erforderliche Methode für die Designerunterstützung.
/// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// ElementControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Name = "ElementControl";
this.ResumeLayout(false);
}
#endregion
}
}
| mit |
cdnjs/cdnjs | ajax/libs/tinymce/5.6.0/plugins/print/plugin.min.js | 847 | /**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*
* Version: 5.6.0 (2020-11-18)
*/
!function(){"use strict";var n=tinymce.util.Tools.resolve("tinymce.PluginManager"),e=tinymce.util.Tools.resolve("tinymce.Env");n.add("print",function(n){var t,i;(t=n).addCommand("mcePrint",function(){e.browser.isIE()?t.getDoc().execCommand("print",!1,null):t.getWin().print()}),(i=n).ui.registry.addButton("print",{icon:"print",tooltip:"Print",onAction:function(){return i.execCommand("mcePrint")}}),i.ui.registry.addMenuItem("print",{text:"Print...",icon:"print",onAction:function(){return i.execCommand("mcePrint")}}),n.addShortcut("Meta+P","","mcePrint")})}(); | mit |
vkolova/bgscena | wp-content/themes/Activello-master/inc/widgets/widget-instagram.php | 3381 | <?php
/**
* instagram Widget
* activello Theme
*/
class activello_instagram_widget extends WP_Widget
{
function activello_instagram_widget(){
$widget_ops = array('classname' => 'activello-instagram','description' => esc_html__( "activello instagram Widget" ,'activello') );
parent::__construct('activello-instagram', esc_html__('activello instagram Widget','activello'), $widget_ops);
}
function widget($args , $instance) {
extract($args);
$title = isset($instance['title']) ? $instance['title'] : esc_html__('Follow us' , 'activello');
$instagram_id = isset($instance['instagram_id']) ? $instance['instagram_id'] : esc_html__('' , 'activello');
$tag_name = isset($instance['tag_name']) ? $instance['tag_name'] : esc_html__('awesome' , 'activello');
$limit = isset($instance['limit']) ? $instance['limit'] : 6;
echo $before_widget;
echo $before_title;
echo $title;
echo $after_title;
/**
* Widget Content
*/
?>
<script type="text/javascript">
var feed = new Instafeed({
get: 'tagged',
tagName: '<?php echo $tag_name; ?>',
clientId: '<?php echo $instagram_id; ?>',
limit: '<?php echo $limit; ?>',
});
feed.run();
</script>
<div id="instafeed"></div>
<?php
echo $after_widget;
}
function form($instance) {
if(!isset($instance['title']) ) $instance['title']='';
if(!isset($instance['instagram_id'])) $instance['instagram_id']='';
if(!isset($instance['tag_name'])) $instance['tag_name']='';
if(!isset($instance['limit'])) $instance['limit']='';
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php esc_html_e('Title ','activello') ?></label>
<input type="text" value="<?php echo esc_attr($instance['title']); ?>"
name="<?php echo $this->get_field_name('title'); ?>"
id="<?php $this->get_field_id('title'); ?>"
class="widefat" />
</p>
<p><label for="<?php echo $this->get_field_id('instagram_id'); ?>"><?php esc_html_e('Client ID ','activello') ?></label>
<input type="text" value="<?php echo esc_attr($instance['instagram_id']); ?>"
name="<?php echo $this->get_field_name('instagram_id'); ?>"
id="<?php $this->get_field_id('instagram_id'); ?>"
class="widefat" />
</p>
<p><label for="<?php echo $this->get_field_id('tag_name'); ?>"><?php esc_html_e('Tag Name ','activello') ?></label>
<input type="text" value="<?php echo esc_attr($instance['tag_name']); ?>"
name="<?php echo $this->get_field_name('tag_name'); ?>"
id="<?php $this->get_field_id('tag_name'); ?>"
class="widefat" />
</p>
<p><label for="<?php echo $this->get_field_id('limit'); ?>"><?php esc_html_e('Limit ','activello') ?></label>
<input type="text" value="<?php echo esc_attr($instance['limit']); ?>"
name="<?php echo $this->get_field_name('limit'); ?>"
id="<?php $this->get_field_id('limit'); ?>"
class="" />
</p>
<?php
}
}
?> | mit |
Azure/azure-sdk-for-ruby | management/azure_mgmt_storage/lib/2017-10-01/generated/azure_mgmt_storage/models/list_service_sas_response.rb | 1248 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Storage::Mgmt::V2017_10_01
module Models
#
# The List service SAS credentials operation response.
#
class ListServiceSasResponse
include MsRestAzure
# @return [String] List service SAS credentials of specific resource.
attr_accessor :service_sas_token
#
# Mapper for ListServiceSasResponse class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ListServiceSasResponse',
type: {
name: 'Composite',
class_name: 'ListServiceSasResponse',
model_properties: {
service_sas_token: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'serviceSasToken',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| mit |
dobakat/SharpMapTracker | TibiaCastDownloader/Properties/AssemblyInfo.cs | 1450 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TibiaCastDownloader")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TibiaCastDownloader")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("953eae33-c13b-4916-b0e8-aefbc4c52f10")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
MironovDmitry/dashing.net | src/dashing.net.jobs/TotalRequests.cs | 1552 | using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading;
using MySql.Data.MySqlClient;
using dashing.net.common;
using dashing.net.streaming;
namespace dashing.net.jobs
{
[Export(typeof(IJob))]
public class TotalRequests : IJob
{
private int requestsCount;
public Lazy<Timer> Timer { get; private set; }
public TotalRequests()
{
MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["SDP_MySQL"].ConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = (Properties.Resources.WOsCount_sql);
cmd.Connection = con;
MySqlDataReader reader;
try
{
cmd.Connection.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
requestsCount = Convert.ToInt16(reader["totalRequests"]);
}
}
catch
{
}
finally
{
cmd.Connection.Close();
}
Timer = new Lazy<Timer>(() => new Timer(SendMessage, null, TimeSpan.Zero, TimeSpan.FromSeconds(120)));
}
public void SendMessage(object sent)
{
Dashing.SendMessage(new { current = requestsCount, id = "totalRequests" });
}
}
} | mit |
Azure/azure-sdk-for-ruby | data/azure_graph_rbac/lib/1.6/generated/azure_graph_rbac/groups.rb | 42479 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::GraphRbac::V1_6
#
# The Graph RBAC Management Client
#
class Groups
include MsRestAzure
#
# Creates and initializes a new instance of the Groups class.
# @param client service class for accessing basic functionality.
#
def initialize(client)
@client = client
end
# @return [GraphRbacClient] reference to the GraphRbacClient
attr_reader :client
#
# Checks whether the specified user, group, contact, or service principal is a
# direct or transitive member of the specified group.
#
# @param parameters [CheckGroupMembershipParameters] The check group membership
# parameters.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [CheckGroupMembershipResult] operation results.
#
def is_member_of(parameters, custom_headers:nil)
response = is_member_of_async(parameters, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Checks whether the specified user, group, contact, or service principal is a
# direct or transitive member of the specified group.
#
# @param parameters [CheckGroupMembershipParameters] The check group membership
# parameters.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def is_member_of_with_http_info(parameters, custom_headers:nil)
is_member_of_async(parameters, custom_headers:custom_headers).value!
end
#
# Checks whether the specified user, group, contact, or service principal is a
# direct or transitive member of the specified group.
#
# @param parameters [CheckGroupMembershipParameters] The check group membership
# parameters.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def is_member_of_async(parameters, custom_headers:nil)
fail ArgumentError, 'parameters is nil' if parameters.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.tenant_id is nil' if @client.tenant_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
# Serialize Request
request_mapper = Azure::GraphRbac::V1_6::Models::CheckGroupMembershipParameters.mapper()
request_content = @client.serialize(request_mapper, parameters)
request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil
path_template = '{tenantID}/isMemberOf'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'tenantID' => @client.tenant_id},
query_params: {'api-version' => @client.api_version},
body: request_content,
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:post, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::GraphRbac::V1_6::Models::CheckGroupMembershipResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Remove a member from a group.
#
# @param group_object_id [String] The object ID of the group from which to
# remove the member.
# @param member_object_id [String] Member object id
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
#
def remove_member(group_object_id, member_object_id, custom_headers:nil)
response = remove_member_async(group_object_id, member_object_id, custom_headers:custom_headers).value!
nil
end
#
# Remove a member from a group.
#
# @param group_object_id [String] The object ID of the group from which to
# remove the member.
# @param member_object_id [String] Member object id
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def remove_member_with_http_info(group_object_id, member_object_id, custom_headers:nil)
remove_member_async(group_object_id, member_object_id, custom_headers:custom_headers).value!
end
#
# Remove a member from a group.
#
# @param group_object_id [String] The object ID of the group from which to
# remove the member.
# @param member_object_id [String] Member object id
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def remove_member_async(group_object_id, member_object_id, custom_headers:nil)
fail ArgumentError, 'group_object_id is nil' if group_object_id.nil?
fail ArgumentError, 'member_object_id is nil' if member_object_id.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.tenant_id is nil' if @client.tenant_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{tenantID}/groups/{groupObjectId}/$links/members/{memberObjectId}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'groupObjectId' => group_object_id,'memberObjectId' => member_object_id,'tenantID' => @client.tenant_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:delete, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 204
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result
end
promise.execute
end
#
# Add a member to a group.
#
# @param group_object_id [String] The object ID of the group to which to add
# the member.
# @param parameters [GroupAddMemberParameters] The URL of the member object,
# such as
# https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
#
def add_member(group_object_id, parameters, custom_headers:nil)
response = add_member_async(group_object_id, parameters, custom_headers:custom_headers).value!
nil
end
#
# Add a member to a group.
#
# @param group_object_id [String] The object ID of the group to which to add
# the member.
# @param parameters [GroupAddMemberParameters] The URL of the member object,
# such as
# https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def add_member_with_http_info(group_object_id, parameters, custom_headers:nil)
add_member_async(group_object_id, parameters, custom_headers:custom_headers).value!
end
#
# Add a member to a group.
#
# @param group_object_id [String] The object ID of the group to which to add
# the member.
# @param parameters [GroupAddMemberParameters] The URL of the member object,
# such as
# https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def add_member_async(group_object_id, parameters, custom_headers:nil)
fail ArgumentError, 'group_object_id is nil' if group_object_id.nil?
fail ArgumentError, 'parameters is nil' if parameters.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.tenant_id is nil' if @client.tenant_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
# Serialize Request
request_mapper = Azure::GraphRbac::V1_6::Models::GroupAddMemberParameters.mapper()
request_content = @client.serialize(request_mapper, parameters)
request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil
path_template = '{tenantID}/groups/{groupObjectId}/$links/members'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'groupObjectId' => group_object_id,'tenantID' => @client.tenant_id},
query_params: {'api-version' => @client.api_version},
body: request_content,
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:post, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 204
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result
end
promise.execute
end
#
# Create a group in the directory.
#
# @param parameters [GroupCreateParameters] The parameters for the group to
# create.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [ADGroup] operation results.
#
def create(parameters, custom_headers:nil)
response = create_async(parameters, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Create a group in the directory.
#
# @param parameters [GroupCreateParameters] The parameters for the group to
# create.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def create_with_http_info(parameters, custom_headers:nil)
create_async(parameters, custom_headers:custom_headers).value!
end
#
# Create a group in the directory.
#
# @param parameters [GroupCreateParameters] The parameters for the group to
# create.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def create_async(parameters, custom_headers:nil)
fail ArgumentError, 'parameters is nil' if parameters.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.tenant_id is nil' if @client.tenant_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
# Serialize Request
request_mapper = Azure::GraphRbac::V1_6::Models::GroupCreateParameters.mapper()
request_content = @client.serialize(request_mapper, parameters)
request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil
path_template = '{tenantID}/groups'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'tenantID' => @client.tenant_id},
query_params: {'api-version' => @client.api_version},
body: request_content,
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:post, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 201
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
# Deserialize Response
if status_code == 201
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::GraphRbac::V1_6::Models::ADGroup.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Gets list of groups for the current tenant.
#
# @param filter [String] The filter to apply to the operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Array<ADGroup>] operation results.
#
def list(filter:nil, custom_headers:nil)
first_page = list_as_lazy(filter:filter, custom_headers:custom_headers)
first_page.get_all_items
end
#
# Gets list of groups for the current tenant.
#
# @param filter [String] The filter to apply to the operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_with_http_info(filter:nil, custom_headers:nil)
list_async(filter:filter, custom_headers:custom_headers).value!
end
#
# Gets list of groups for the current tenant.
#
# @param filter [String] The filter to apply to the operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_async(filter:nil, custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.tenant_id is nil' if @client.tenant_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{tenantID}/groups'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'tenantID' => @client.tenant_id},
query_params: {'$filter' => filter,'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::GraphRbac::V1_6::Models::GroupListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Gets the members of a group.
#
# @param object_id [String] The object ID of the group whose members should be
# retrieved.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Array<AADObject>] operation results.
#
def get_group_members(object_id, custom_headers:nil)
first_page = get_group_members_as_lazy(object_id, custom_headers:custom_headers)
first_page.get_all_items
end
#
# Gets the members of a group.
#
# @param object_id [String] The object ID of the group whose members should be
# retrieved.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def get_group_members_with_http_info(object_id, custom_headers:nil)
get_group_members_async(object_id, custom_headers:custom_headers).value!
end
#
# Gets the members of a group.
#
# @param object_id [String] The object ID of the group whose members should be
# retrieved.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def get_group_members_async(object_id, custom_headers:nil)
fail ArgumentError, 'object_id is nil' if object_id.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.tenant_id is nil' if @client.tenant_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{tenantID}/groups/{objectId}/members'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'objectId' => object_id,'tenantID' => @client.tenant_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::GraphRbac::V1_6::Models::GetObjectsResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Gets group information from the directory.
#
# @param object_id [String] The object ID of the user for which to get group
# information.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [ADGroup] operation results.
#
def get(object_id, custom_headers:nil)
response = get_async(object_id, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Gets group information from the directory.
#
# @param object_id [String] The object ID of the user for which to get group
# information.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def get_with_http_info(object_id, custom_headers:nil)
get_async(object_id, custom_headers:custom_headers).value!
end
#
# Gets group information from the directory.
#
# @param object_id [String] The object ID of the user for which to get group
# information.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def get_async(object_id, custom_headers:nil)
fail ArgumentError, 'object_id is nil' if object_id.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.tenant_id is nil' if @client.tenant_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{tenantID}/groups/{objectId}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'objectId' => object_id,'tenantID' => @client.tenant_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::GraphRbac::V1_6::Models::ADGroup.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Delete a group from the directory.
#
# @param object_id [String] The object ID of the group to delete.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
#
def delete(object_id, custom_headers:nil)
response = delete_async(object_id, custom_headers:custom_headers).value!
nil
end
#
# Delete a group from the directory.
#
# @param object_id [String] The object ID of the group to delete.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def delete_with_http_info(object_id, custom_headers:nil)
delete_async(object_id, custom_headers:custom_headers).value!
end
#
# Delete a group from the directory.
#
# @param object_id [String] The object ID of the group to delete.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def delete_async(object_id, custom_headers:nil)
fail ArgumentError, 'object_id is nil' if object_id.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.tenant_id is nil' if @client.tenant_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{tenantID}/groups/{objectId}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'objectId' => object_id,'tenantID' => @client.tenant_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:delete, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 204
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result
end
promise.execute
end
#
# Gets a collection of object IDs of groups of which the specified group is a
# member.
#
# @param object_id [String] The object ID of the group for which to get group
# membership.
# @param parameters [GroupGetMemberGroupsParameters] Group filtering
# parameters.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [GroupGetMemberGroupsResult] operation results.
#
def get_member_groups(object_id, parameters, custom_headers:nil)
response = get_member_groups_async(object_id, parameters, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Gets a collection of object IDs of groups of which the specified group is a
# member.
#
# @param object_id [String] The object ID of the group for which to get group
# membership.
# @param parameters [GroupGetMemberGroupsParameters] Group filtering
# parameters.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def get_member_groups_with_http_info(object_id, parameters, custom_headers:nil)
get_member_groups_async(object_id, parameters, custom_headers:custom_headers).value!
end
#
# Gets a collection of object IDs of groups of which the specified group is a
# member.
#
# @param object_id [String] The object ID of the group for which to get group
# membership.
# @param parameters [GroupGetMemberGroupsParameters] Group filtering
# parameters.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def get_member_groups_async(object_id, parameters, custom_headers:nil)
fail ArgumentError, 'object_id is nil' if object_id.nil?
fail ArgumentError, 'parameters is nil' if parameters.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.tenant_id is nil' if @client.tenant_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
# Serialize Request
request_mapper = Azure::GraphRbac::V1_6::Models::GroupGetMemberGroupsParameters.mapper()
request_content = @client.serialize(request_mapper, parameters)
request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil
path_template = '{tenantID}/groups/{objectId}/getMemberGroups'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'objectId' => object_id,'tenantID' => @client.tenant_id},
query_params: {'api-version' => @client.api_version},
body: request_content,
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:post, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::GraphRbac::V1_6::Models::GroupGetMemberGroupsResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Gets a list of groups for the current tenant.
#
# @param next_link [String] Next link for the list operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Array<ADGroup>] operation results.
#
def list_next(next_link, custom_headers:nil)
response = list_next_async(next_link, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Gets a list of groups for the current tenant.
#
# @param next_link [String] Next link for the list operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_next_with_http_info(next_link, custom_headers:nil)
list_next_async(next_link, custom_headers:custom_headers).value!
end
#
# Gets a list of groups for the current tenant.
#
# @param next_link [String] Next link for the list operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_next_async(next_link, custom_headers:nil)
fail ArgumentError, 'next_link is nil' if next_link.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.tenant_id is nil' if @client.tenant_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{tenantID}/{nextLink}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'tenantID' => @client.tenant_id},
skip_encoding_path_params: {'nextLink' => next_link},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::GraphRbac::V1_6::Models::GroupListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Gets the members of a group.
#
# @param next_link [String] Next link for the list operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Array<AADObject>] operation results.
#
def get_group_members_next(next_link, custom_headers:nil)
response = get_group_members_next_async(next_link, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Gets the members of a group.
#
# @param next_link [String] Next link for the list operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def get_group_members_next_with_http_info(next_link, custom_headers:nil)
get_group_members_next_async(next_link, custom_headers:custom_headers).value!
end
#
# Gets the members of a group.
#
# @param next_link [String] Next link for the list operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def get_group_members_next_async(next_link, custom_headers:nil)
fail ArgumentError, 'next_link is nil' if next_link.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.tenant_id is nil' if @client.tenant_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{tenantID}/{nextLink}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'tenantID' => @client.tenant_id},
skip_encoding_path_params: {'nextLink' => next_link},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::GraphRbac::V1_6::Models::GetObjectsResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Gets list of groups for the current tenant.
#
# @param filter [String] The filter to apply to the operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [GroupListResult] which provide lazy access to pages of the response.
#
def list_as_lazy(filter:nil, custom_headers:nil)
response = list_async(filter:filter, custom_headers:custom_headers).value!
unless response.nil?
page = response.body
page.next_method = Proc.new do |next_link|
list_next_async(next_link, custom_headers:custom_headers)
end
page
end
end
#
# Gets the members of a group.
#
# @param object_id [String] The object ID of the group whose members should be
# retrieved.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [GetObjectsResult] which provide lazy access to pages of the
# response.
#
def get_group_members_as_lazy(object_id, custom_headers:nil)
response = get_group_members_async(object_id, custom_headers:custom_headers).value!
unless response.nil?
page = response.body
page.next_method = Proc.new do |next_link|
get_group_members_next_async(next_link, custom_headers:custom_headers)
end
page
end
end
end
end
| mit |
NikolaySpasov/Softuni | C# Advanced/01. Stacks-And-Queues/06. Math Potato/Properties/AssemblyInfo.cs | 1401 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("06. Math Potato")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("06. Math Potato")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9399505b-ab51-4122-ae09-8463d8294356")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
vektordev/javagames | src/client/ErrorWindow.java | 873 | package client;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class ErrorWindow extends JFrame {
public ErrorWindow(String ename, String emsg){
super("ERROR - " + ename);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new GridLayout(0,1));
this.add(new JLabel("An error has occured. Errormessage:"));
this.add(new JTextField(emsg));
JButton exitBtn = new JButton("OK");
exitBtn.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
close();
}
});
this.add(exitBtn);
this.setVisible(true);
}
public void close(){
this.setVisible(false);
}
}
| mit |
sarahyablok/go-force | force/force_test.go | 1708 | package force
import (
"github.com/nimajalali/go-force/sobjects"
"testing"
"net/http"
)
func TestCreateWithAccessToken(t *testing.T) {
// Manually grab an OAuth token, so that we can pass it into CreateWithAccessToken
oauth := &forceOauth{
clientId: testClientId,
clientSecret: testClientSecret,
userName: testUserName,
password: testPassword,
securityToken: testSecurityToken,
environment: testEnvironment,
client: http.DefaultClient,
}
forceApi := &ForceApi{
apiResources: make(map[string]string),
apiSObjects: make(map[string]*SObjectMetaData),
apiSObjectDescriptions: make(map[string]*SObjectDescription),
apiVersion: version,
oauth: oauth,
}
err := forceApi.oauth.Authenticate()
if err != nil {
t.Fatalf("Unable to authenticate: %#v", err)
}
if err := forceApi.oauth.Validate(); err != nil {
t.Fatalf("Oauth object is invlaid: %#v", err)
}
// We shouldn't hit any errors creating a new force instance and manually passing in these oauth details now.
newForceApi, err := CreateWithAccessToken(testVersion, testClientId, forceApi.oauth.AccessToken, forceApi.oauth.InstanceUrl, nil)
if err != nil {
t.Fatalf("Unable to create new force api instance using pre-defined oauth details: %#v", err)
}
if err := newForceApi.oauth.Validate(); err != nil {
t.Fatalf("Oauth object is invlaid: %#v", err)
}
// We should be able to make a basic query now with the newly created object (i.e. the oauth details should be correctly usable).
_, err = newForceApi.DescribeSObject(&sobjects.Account{})
if err != nil {
t.Fatalf("Failed to retrieve description of sobject: %v", err)
}
}
| mit |
cdnjs/cdnjs | ajax/libs/hls.js/1.1.2-0.canary.8062/hls.js | 993248 | typeof window !== "undefined" &&
(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, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // 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 = "./src/hls.ts");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./node_modules/eventemitter3/index.js":
/*!*********************************************!*\
!*** ./node_modules/eventemitter3/index.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var has = Object.prototype.hasOwnProperty
, prefix = '~';
/**
* Constructor to create a storage for our `EE` objects.
* An `Events` instance is a plain object whose properties are event names.
*
* @constructor
* @private
*/
function Events() {}
//
// We try to not inherit from `Object.prototype`. In some engines creating an
// instance in this way is faster than calling `Object.create(null)` directly.
// If `Object.create(null)` is not supported we prefix the event names with a
// character to make sure that the built-in object properties are not
// overridden or used as an attack vector.
//
if (Object.create) {
Events.prototype = Object.create(null);
//
// This hack is needed because the `__proto__` property is still inherited in
// some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
//
if (!new Events().__proto__) prefix = false;
}
/**
* Representation of a single event listener.
*
* @param {Function} fn The listener function.
* @param {*} context The context to invoke the listener with.
* @param {Boolean} [once=false] Specify if the listener is a one-time listener.
* @constructor
* @private
*/
function EE(fn, context, once) {
this.fn = fn;
this.context = context;
this.once = once || false;
}
/**
* Add a listener for a given event.
*
* @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
* @param {(String|Symbol)} event The event name.
* @param {Function} fn The listener function.
* @param {*} context The context to invoke the listener with.
* @param {Boolean} once Specify if the listener is a one-time listener.
* @returns {EventEmitter}
* @private
*/
function addListener(emitter, event, fn, context, once) {
if (typeof fn !== 'function') {
throw new TypeError('The listener must be a function');
}
var listener = new EE(fn, context || emitter, once)
, evt = prefix ? prefix + event : event;
if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
else emitter._events[evt] = [emitter._events[evt], listener];
return emitter;
}
/**
* Clear event by name.
*
* @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
* @param {(String|Symbol)} evt The Event name.
* @private
*/
function clearEvent(emitter, evt) {
if (--emitter._eventsCount === 0) emitter._events = new Events();
else delete emitter._events[evt];
}
/**
* Minimal `EventEmitter` interface that is molded against the Node.js
* `EventEmitter` interface.
*
* @constructor
* @public
*/
function EventEmitter() {
this._events = new Events();
this._eventsCount = 0;
}
/**
* Return an array listing the events for which the emitter has registered
* listeners.
*
* @returns {Array}
* @public
*/
EventEmitter.prototype.eventNames = function eventNames() {
var names = []
, events
, name;
if (this._eventsCount === 0) return names;
for (name in (events = this._events)) {
if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
}
if (Object.getOwnPropertySymbols) {
return names.concat(Object.getOwnPropertySymbols(events));
}
return names;
};
/**
* Return the listeners registered for a given event.
*
* @param {(String|Symbol)} event The event name.
* @returns {Array} The registered listeners.
* @public
*/
EventEmitter.prototype.listeners = function listeners(event) {
var evt = prefix ? prefix + event : event
, handlers = this._events[evt];
if (!handlers) return [];
if (handlers.fn) return [handlers.fn];
for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
ee[i] = handlers[i].fn;
}
return ee;
};
/**
* Return the number of listeners listening to a given event.
*
* @param {(String|Symbol)} event The event name.
* @returns {Number} The number of listeners.
* @public
*/
EventEmitter.prototype.listenerCount = function listenerCount(event) {
var evt = prefix ? prefix + event : event
, listeners = this._events[evt];
if (!listeners) return 0;
if (listeners.fn) return 1;
return listeners.length;
};
/**
* Calls each of the listeners registered for a given event.
*
* @param {(String|Symbol)} event The event name.
* @returns {Boolean} `true` if the event had listeners, else `false`.
* @public
*/
EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return false;
var listeners = this._events[evt]
, len = arguments.length
, args
, i;
if (listeners.fn) {
if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
switch (len) {
case 1: return listeners.fn.call(listeners.context), true;
case 2: return listeners.fn.call(listeners.context, a1), true;
case 3: return listeners.fn.call(listeners.context, a1, a2), true;
case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
}
for (i = 1, args = new Array(len -1); i < len; i++) {
args[i - 1] = arguments[i];
}
listeners.fn.apply(listeners.context, args);
} else {
var length = listeners.length
, j;
for (i = 0; i < length; i++) {
if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
switch (len) {
case 1: listeners[i].fn.call(listeners[i].context); break;
case 2: listeners[i].fn.call(listeners[i].context, a1); break;
case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
default:
if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
args[j - 1] = arguments[j];
}
listeners[i].fn.apply(listeners[i].context, args);
}
}
}
return true;
};
/**
* Add a listener for a given event.
*
* @param {(String|Symbol)} event The event name.
* @param {Function} fn The listener function.
* @param {*} [context=this] The context to invoke the listener with.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.on = function on(event, fn, context) {
return addListener(this, event, fn, context, false);
};
/**
* Add a one-time listener for a given event.
*
* @param {(String|Symbol)} event The event name.
* @param {Function} fn The listener function.
* @param {*} [context=this] The context to invoke the listener with.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.once = function once(event, fn, context) {
return addListener(this, event, fn, context, true);
};
/**
* Remove the listeners of a given event.
*
* @param {(String|Symbol)} event The event name.
* @param {Function} fn Only remove the listeners that match this function.
* @param {*} context Only remove the listeners that have this context.
* @param {Boolean} once Only remove one-time listeners.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return this;
if (!fn) {
clearEvent(this, evt);
return this;
}
var listeners = this._events[evt];
if (listeners.fn) {
if (
listeners.fn === fn &&
(!once || listeners.once) &&
(!context || listeners.context === context)
) {
clearEvent(this, evt);
}
} else {
for (var i = 0, events = [], length = listeners.length; i < length; i++) {
if (
listeners[i].fn !== fn ||
(once && !listeners[i].once) ||
(context && listeners[i].context !== context)
) {
events.push(listeners[i]);
}
}
//
// Reset the array, or remove it completely if we have no more listeners.
//
if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
else clearEvent(this, evt);
}
return this;
};
/**
* Remove all listeners, or those of the specified event.
*
* @param {(String|Symbol)} [event] The event name.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
var evt;
if (event) {
evt = prefix ? prefix + event : event;
if (this._events[evt]) clearEvent(this, evt);
} else {
this._events = new Events();
this._eventsCount = 0;
}
return this;
};
//
// Alias methods names because people roll like that.
//
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
//
// Expose the prefix.
//
EventEmitter.prefixed = prefix;
//
// Allow `EventEmitter` to be imported as module namespace.
//
EventEmitter.EventEmitter = EventEmitter;
//
// Expose the module.
//
if (true) {
module.exports = EventEmitter;
}
/***/ }),
/***/ "./node_modules/url-toolkit/src/url-toolkit.js":
/*!*****************************************************!*\
!*** ./node_modules/url-toolkit/src/url-toolkit.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// see https://tools.ietf.org/html/rfc1808
(function (root) {
var URL_REGEX =
/^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#[^]*)?$/;
var FIRST_SEGMENT_REGEX = /^([^\/?#]*)([^]*)$/;
var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
var URLToolkit = {
// 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 (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 = URLToolkit.parseURL(baseURL);
if (!basePartsForNormalise) {
throw new Error('Error trying to parse base URL.');
}
basePartsForNormalise.path = URLToolkit.normalizePath(
basePartsForNormalise.path
);
return URLToolkit.buildURLFromParts(basePartsForNormalise);
}
var relativeParts = URLToolkit.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 = URLToolkit.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
) {}
return path.split('').reverse().join('');
},
buildURLFromParts: function (parts) {
return (
parts.scheme +
parts.netLoc +
parts.path +
parts.params +
parts.query +
parts.fragment
);
},
};
if (true)
module.exports = URLToolkit;
else {}
})(this);
/***/ }),
/***/ "./node_modules/webworkify-webpack/index.js":
/*!**************************************************!*\
!*** ./node_modules/webworkify-webpack/index.js ***!
\**************************************************/
/*! no static exports found */
/***/ (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
/******/ });
/******/ }
/******/ };
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ // 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
}
var moduleNameReqExp = '[\\.|\\-|\\+|\\w|\/|@]+'
var dependencyRegExp = '\\(\\s*(\/\\*.*?\\*\/)?\\s*.*?(' + moduleNameReqExp + ').*?\\)' // additional chars when output.pathinfo is true
// http://stackoverflow.com/a/2593661/130442
function quoteRegExp (str) {
return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&')
}
function isNumeric(n) {
return !isNaN(1 * n); // 1 * n converts integers, integers as string ("123"), 1e3 and "1e3" to integers and strings to NaN
}
function getModuleDependencies (sources, module, queueName) {
var retval = {}
retval[queueName] = []
var fnString = module.toString()
var wrapperSignature = fnString.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/)
if (!wrapperSignature) return retval
var webpackRequireName = wrapperSignature[1]
// main bundle deps
var re = new RegExp('(\\\\n|\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g')
var match
while ((match = re.exec(fnString))) {
if (match[3] === 'dll-reference') continue
retval[queueName].push(match[3])
}
// dll deps
re = new RegExp('\\(' + quoteRegExp(webpackRequireName) + '\\("(dll-reference\\s(' + moduleNameReqExp + '))"\\)\\)' + dependencyRegExp, 'g')
while ((match = re.exec(fnString))) {
if (!sources[match[2]]) {
retval[queueName].push(match[1])
sources[match[2]] = __webpack_require__(match[1]).m
}
retval[match[2]] = retval[match[2]] || []
retval[match[2]].push(match[4])
}
// convert 1e3 back to 1000 - this can be important after uglify-js converted 1000 to 1e3
var keys = Object.keys(retval);
for (var i = 0; i < keys.length; i++) {
for (var j = 0; j < retval[keys[i]].length; j++) {
if (isNumeric(retval[keys[i]][j])) {
retval[keys[i]][j] = 1 * retval[keys[i]][j];
}
}
}
return retval
}
function hasValuesInQueues (queues) {
var keys = Object.keys(queues)
return keys.reduce(function (hasValues, key) {
return hasValues || queues[key].length > 0
}, false)
}
function getRequiredModules (sources, moduleId) {
var modulesQueue = {
main: [moduleId]
}
var requiredModules = {
main: []
}
var seenModules = {
main: {}
}
while (hasValuesInQueues(modulesQueue)) {
var queues = Object.keys(modulesQueue)
for (var i = 0; i < queues.length; i++) {
var queueName = queues[i]
var queue = modulesQueue[queueName]
var moduleToCheck = queue.pop()
seenModules[queueName] = seenModules[queueName] || {}
if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue
seenModules[queueName][moduleToCheck] = true
requiredModules[queueName] = requiredModules[queueName] || []
requiredModules[queueName].push(moduleToCheck)
var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName)
var newModulesKeys = Object.keys(newModules)
for (var j = 0; j < newModulesKeys.length; j++) {
modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []
modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])
}
}
}
return requiredModules
}
module.exports = function (moduleId, options) {
options = options || {}
var sources = {
main: __webpack_require__.m
}
var requiredModules = options.all ? { main: Object.keys(sources.main) } : getRequiredModules(sources, moduleId)
var src = ''
Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) {
var entryModule = 0
while (requiredModules[module][entryModule]) {
entryModule++
}
requiredModules[module].push(entryModule)
sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'
src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\n'
})
src = src + 'new ((' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[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
}
/***/ }),
/***/ "./src/config.ts":
/*!***********************!*\
!*** ./src/config.ts ***!
\***********************/
/*! exports provided: hlsDefaultConfig, mergeConfig, enableStreamingMode */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hlsDefaultConfig", function() { return hlsDefaultConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeConfig", function() { return mergeConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableStreamingMode", function() { return enableStreamingMode; });
/* harmony import */ var _controller_abr_controller__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./controller/abr-controller */ "./src/controller/abr-controller.ts");
/* harmony import */ var _controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./controller/audio-stream-controller */ "./src/controller/audio-stream-controller.ts");
/* harmony import */ var _controller_audio_track_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./controller/audio-track-controller */ "./src/controller/audio-track-controller.ts");
/* harmony import */ var _controller_subtitle_stream_controller__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./controller/subtitle-stream-controller */ "./src/controller/subtitle-stream-controller.ts");
/* harmony import */ var _controller_subtitle_track_controller__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./controller/subtitle-track-controller */ "./src/controller/subtitle-track-controller.ts");
/* harmony import */ var _controller_buffer_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./controller/buffer-controller */ "./src/controller/buffer-controller.ts");
/* harmony import */ var _controller_timeline_controller__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./controller/timeline-controller */ "./src/controller/timeline-controller.ts");
/* harmony import */ var _controller_cap_level_controller__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./controller/cap-level-controller */ "./src/controller/cap-level-controller.ts");
/* harmony import */ var _controller_fps_controller__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./controller/fps-controller */ "./src/controller/fps-controller.ts");
/* harmony import */ var _controller_eme_controller__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./controller/eme-controller */ "./src/controller/eme-controller.ts");
/* harmony import */ var _controller_cmcd_controller__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./controller/cmcd-controller */ "./src/controller/cmcd-controller.ts");
/* harmony import */ var _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./utils/xhr-loader */ "./src/utils/xhr-loader.ts");
/* harmony import */ var _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./utils/fetch-loader */ "./src/utils/fetch-loader.ts");
/* harmony import */ var _utils_cues__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./utils/cues */ "./src/utils/cues.ts");
/* harmony import */ var _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./utils/mediakeys-helper */ "./src/utils/mediakeys-helper.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./utils/logger */ "./src/utils/logger.ts");
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
// If possible, keep hlsDefaultConfig shallow
// It is cloned whenever a new Hls instance is created, by keeping the config
// shallow the properties are cloned, and we don't end up manipulating the default
var hlsDefaultConfig = _objectSpread(_objectSpread({
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
backBufferLength: Infinity,
// used by buffer-controller
maxBufferSize: 60 * 1000 * 1000,
// used by stream-controller
maxBufferHole: 0.1,
// used by stream-controller
highBufferWatchdogPeriod: 2,
// 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 latency-controller
liveMaxLatencyDurationCount: Infinity,
// used by latency-controller
liveSyncDuration: undefined,
// used by latency-controller
liveMaxLatencyDuration: undefined,
// used by latency-controller
maxLiveSyncPlaybackRate: 1,
// used by latency-controller
liveDurationInfinity: false,
// used by buffer-controller
liveBackBufferLength: null,
// used by buffer-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
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: _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_11__["default"],
// loader: FetchLoader,
fLoader: undefined,
// used by fragment-loader
pLoader: undefined,
// used by playlist-loader
xhrSetup: undefined,
// used by xhr-loader
licenseXhrSetup: undefined,
// used by eme-controller
licenseResponseCallback: undefined,
// used by eme-controller
abrController: _controller_abr_controller__WEBPACK_IMPORTED_MODULE_0__["default"],
bufferController: _controller_buffer_controller__WEBPACK_IMPORTED_MODULE_5__["default"],
capLevelController: _controller_cap_level_controller__WEBPACK_IMPORTED_MODULE_7__["default"],
fpsController: _controller_fps_controller__WEBPACK_IMPORTED_MODULE_8__["default"],
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
emeEnabled: false,
// used by eme-controller
widevineLicenseUrl: undefined,
// used by eme-controller
drmSystemOptions: {},
// used by eme-controller
requestMediaKeySystemAccessFunc: _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_14__["requestMediaKeySystemAccess"],
// used by eme-controller
testBandwidth: true,
progressive: false,
lowLatencyMode: true,
cmcd: undefined
}, timelineConfig()), {}, {
subtitleStreamController: true ? _controller_subtitle_stream_controller__WEBPACK_IMPORTED_MODULE_3__["SubtitleStreamController"] : undefined,
subtitleTrackController: true ? _controller_subtitle_track_controller__WEBPACK_IMPORTED_MODULE_4__["default"] : undefined,
timelineController: true ? _controller_timeline_controller__WEBPACK_IMPORTED_MODULE_6__["TimelineController"] : undefined,
audioStreamController: true ? _controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1__["default"] : undefined,
audioTrackController: true ? _controller_audio_track_controller__WEBPACK_IMPORTED_MODULE_2__["default"] : undefined,
emeController: true ? _controller_eme_controller__WEBPACK_IMPORTED_MODULE_9__["default"] : undefined,
cmcdController: true ? _controller_cmcd_controller__WEBPACK_IMPORTED_MODULE_10__["default"] : undefined
});
function timelineConfig() {
return {
cueHandler: _utils_cues__WEBPACK_IMPORTED_MODULE_13__["default"],
// used by timeline-controller
enableCEA708Captions: true,
// used by timeline-controller
enableWebVTT: true,
// used by timeline-controller
enableIMSC1: true,
// used by timeline-controller
captionsTextTrack1Label: 'English',
// used by timeline-controller
captionsTextTrack1LanguageCode: 'en',
// used by timeline-controller
captionsTextTrack2Label: 'Spanish',
// used by timeline-controller
captionsTextTrack2LanguageCode: 'es',
// used by timeline-controller
captionsTextTrack3Label: 'Unknown CC',
// used by timeline-controller
captionsTextTrack3LanguageCode: '',
// used by timeline-controller
captionsTextTrack4Label: 'Unknown CC',
// used by timeline-controller
captionsTextTrack4LanguageCode: '',
// used by timeline-controller
renderTextTracksNatively: true
};
}
function mergeConfig(defaultConfig, userConfig) {
if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
}
if (userConfig.liveMaxLatencyDurationCount !== undefined && (userConfig.liveSyncDurationCount === undefined || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {
throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
}
if (userConfig.liveMaxLatencyDuration !== undefined && (userConfig.liveSyncDuration === undefined || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {
throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
}
return _extends({}, defaultConfig, userConfig);
}
function enableStreamingMode(config) {
var currentLoader = config.loader;
if (currentLoader !== _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_12__["default"] && currentLoader !== _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_11__["default"]) {
// If a developer has configured their own loader, respect that choice
_utils_logger__WEBPACK_IMPORTED_MODULE_15__["logger"].log('[config]: Custom loader detected, cannot enable progressive streaming');
config.progressive = false;
} else {
var canStreamProgressively = Object(_utils_fetch_loader__WEBPACK_IMPORTED_MODULE_12__["fetchSupported"])();
if (canStreamProgressively) {
config.loader = _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_12__["default"];
config.progressive = true;
config.enableSoftwareAES = true;
_utils_logger__WEBPACK_IMPORTED_MODULE_15__["logger"].log('[config]: Progressive streaming enabled, using FetchLoader');
}
}
}
/***/ }),
/***/ "./src/controller/abr-controller.ts":
/*!******************************************!*\
!*** ./src/controller/abr-controller.ts ***!
\******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _utils_ewma_bandwidth_estimator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/ewma-bandwidth-estimator */ "./src/utils/ewma-bandwidth-estimator.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
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); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var AbrController = /*#__PURE__*/function () {
function AbrController(hls) {
this.hls = void 0;
this.lastLoadedFragLevel = 0;
this._nextAutoLevel = -1;
this.timer = void 0;
this.onCheck = this._abandonRulesCheck.bind(this);
this.fragCurrent = null;
this.partCurrent = null;
this.bitrateTestDelay = 0;
this.bwEstimator = void 0;
this.hls = hls;
var config = hls.config;
this.bwEstimator = new _utils_ewma_bandwidth_estimator__WEBPACK_IMPORTED_MODULE_1__["default"](config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate);
this.registerListeners();
}
var _proto = AbrController.prototype;
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADING, this.onFragLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADED, this.onFragLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this);
};
_proto.unregisterListeners = function unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADING, this.onFragLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADED, this.onFragLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this);
};
_proto.destroy = function destroy() {
this.unregisterListeners();
this.clearTimer(); // @ts-ignore
this.hls = this.onCheck = null;
this.fragCurrent = this.partCurrent = null;
};
_proto.onFragLoading = function onFragLoading(event, data) {
var frag = data.frag;
if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_5__["PlaylistLevelType"].MAIN) {
if (!this.timer) {
var _data$part;
this.fragCurrent = frag;
this.partCurrent = (_data$part = data.part) != null ? _data$part : null;
this.timer = self.setInterval(this.onCheck, 100);
}
}
};
_proto.onLevelLoaded = function onLevelLoaded(event, data) {
var config = this.hls.config;
if (data.details.live) {
this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);
} else {
this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);
}
}
/*
This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load
quickly enough to prevent underbuffering
*/
;
_proto._abandonRulesCheck = function _abandonRulesCheck() {
var frag = this.fragCurrent,
part = this.partCurrent,
hls = this.hls;
var autoLevelEnabled = hls.autoLevelEnabled,
config = hls.config,
media = hls.media;
if (!frag || !media) {
return;
}
var stats = part ? part.stats : frag.stats;
var duration = part ? part.duration : frag.duration; // If loading has been aborted and not in lowLatencyMode, stop timer and return
if (stats.aborted) {
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn('frag loader destroy or aborted, disarm abandonRules');
this.clearTimer(); // reset forced auto level value so that next level will be selected
this._nextAutoLevel = -1;
return;
} // This check only runs if we're in ABR mode and actually playing
if (!autoLevelEnabled || media.paused || !media.playbackRate || !media.readyState) {
return;
}
var requestDelay = performance.now() - stats.loading.start;
var playbackRate = Math.abs(media.playbackRate); // In order to work with a stable bandwidth, only begin monitoring bandwidth after half of the fragment has been loaded
if (requestDelay <= 500 * duration / playbackRate) {
return;
}
var levels = hls.levels,
minAutoLevel = hls.minAutoLevel;
var level = levels[frag.level];
var expectedLen = stats.total || Math.max(stats.loaded, Math.round(duration * level.maxBitrate / 8));
var loadRate = Math.max(1, stats.bwEstimate ? stats.bwEstimate / 8 : stats.loaded * 1000 / requestDelay); // fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the entire fragment
var fragLoadedDelay = (expectedLen - stats.loaded) / loadRate;
var pos = media.currentTime; // bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer
var bufferStarvationDelay = (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(media, pos, config.maxBufferHole).end - pos) / playbackRate; // Attempt an emergency downswitch only if less than 2 fragment lengths are buffered, and the time to finish loading
// the current fragment is greater than the amount of buffer we have left
if (bufferStarvationDelay >= 2 * duration / playbackRate || fragLoadedDelay <= bufferStarvationDelay) {
return;
}
var fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;
var nextLoadLevel; // Iterate through lower level and try to find the largest one that avoids rebuffering
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].maxBitrate;
fragLevelNextLoadedDelay = duration * levelNextBitrate / (8 * 0.8 * loadRate);
if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
break;
}
} // Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing
// to load the current one
if (fragLevelNextLoadedDelay >= fragLoadedDelay) {
return;
}
var bwEstimate = this.bwEstimator.getEstimate();
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn("Fragment " + frag.sn + (part ? ' part ' + part.index : '') + " of level " + frag.level + " is loading too slowly and will cause an underbuffer; aborting and switching to level " + nextLoadLevel + "\n Current BW estimate: " + (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(bwEstimate) ? (bwEstimate / 1024).toFixed(3) : 'Unknown') + " Kb/s\n Estimated load time for current fragment: " + fragLoadedDelay.toFixed(3) + " s\n Estimated load time for the next fragment: " + fragLevelNextLoadedDelay.toFixed(3) + " s\n Time to underbuffer: " + bufferStarvationDelay.toFixed(3) + " s");
hls.nextLoadLevel = nextLoadLevel;
this.bwEstimator.sample(requestDelay, stats.loaded);
this.clearTimer();
if (frag.loader) {
this.fragCurrent = this.partCurrent = null;
frag.loader.abort();
}
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOAD_EMERGENCY_ABORTED, {
frag: frag,
part: part,
stats: stats
});
};
_proto.onFragLoaded = function onFragLoaded(event, _ref) {
var frag = _ref.frag,
part = _ref.part;
if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_5__["PlaylistLevelType"].MAIN && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.sn)) {
var stats = part ? part.stats : frag.stats;
var duration = part ? part.duration : frag.duration; // 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) + stats.loaded;
var loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration;
level.loaded = {
bytes: loadedBytes,
duration: loadedDuration
};
level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
}
if (frag.bitrateTest) {
var fragBufferedData = {
stats: stats,
frag: frag,
part: part,
id: frag.type
};
this.onFragBuffered(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, fragBufferedData);
frag.bitrateTest = false;
}
}
};
_proto.onFragBuffered = function onFragBuffered(event, data) {
var frag = data.frag,
part = data.part;
var stats = part ? part.stats : frag.stats;
if (stats.aborted) {
return;
} // Only count non-alt-audio frags which were actually buffered in our BW calculations
if (frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_5__["PlaylistLevelType"].MAIN || frag.sn === 'initSegment') {
return;
} // Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing;
// rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch
// is used. If we used buffering in that case, our BW estimate sample will be very large.
var processingMs = stats.parsing.end - stats.loading.start;
this.bwEstimator.sample(processingMs, stats.loaded);
stats.bwEstimate = this.bwEstimator.getEstimate();
if (frag.bitrateTest) {
this.bitrateTestDelay = processingMs / 1000;
} else {
this.bitrateTestDelay = 0;
}
};
_proto.onError = function onError(event, data) {
// stop timer in case of frag loading error
switch (data.details) {
case _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].FRAG_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].FRAG_LOAD_TIMEOUT:
this.clearTimer();
break;
default:
break;
}
};
_proto.clearTimer = function clearTimer() {
self.clearInterval(this.timer);
this.timer = undefined;
} // return next auto level
;
_proto.getNextABRAutoLevel = function getNextABRAutoLevel() {
var fragCurrent = this.fragCurrent,
partCurrent = this.partCurrent,
hls = this.hls;
var maxAutoLevel = hls.maxAutoLevel,
config = hls.config,
minAutoLevel = hls.minAutoLevel,
media = hls.media;
var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
var pos = media ? media.currentTime : 0; // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as
// if we're playing back at the normal rate.
var playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0;
var avgbw = this.bwEstimator ? this.bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate; // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
var bufferStarvationDelay = (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(media, 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(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor);
if (bestLevel >= 0) {
return bestLevel;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].trace((bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty') + ", finding optimal quality level"); // 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;
var bwFactor = config.abrBandWidthFactor;
var bwUpFactor = config.abrBandWidthUpFactor;
if (!bufferStarvationDelay) {
// 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;
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["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(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor);
return Math.max(bestLevel, 0);
};
_proto.findBestLevel = function findBestLevel(currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor) {
var _level$details;
var fragCurrent = this.fragCurrent,
partCurrent = this.partCurrent,
currentLevel = this.lastLoadedFragLevel;
var levels = this.hls.levels;
var level = levels[currentLevel];
var live = !!(level !== null && level !== void 0 && (_level$details = level.details) !== null && _level$details !== void 0 && _level$details.live);
var currentCodecSet = level === null || level === void 0 ? void 0 : level.codecSet;
var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
for (var i = maxAutoLevel; i >= minAutoLevel; i--) {
var levelInfo = levels[i];
if (!levelInfo || currentCodecSet && levelInfo.codecSet !== currentCodecSet) {
continue;
}
var levelDetails = levelInfo.details;
var avgDuration = (partCurrent ? levelDetails === null || levelDetails === void 0 ? void 0 : levelDetails.partTarget : levelDetails === null || levelDetails === void 0 ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;
var 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].maxBitrate;
var fetchDuration = bitrate * avgDuration / adjustedbw;
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["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;
};
_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.getNextABRAutoLevel(); // 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;
}
}]);
return AbrController;
}();
/* harmony default export */ __webpack_exports__["default"] = (AbrController);
/***/ }),
/***/ "./src/controller/audio-stream-controller.ts":
/*!***************************************************!*\
!*** ./src/controller/audio-stream-controller.ts ***!
\***************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base-stream-controller */ "./src/controller/base-stream-controller.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts");
/* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
/* harmony import */ var _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../demux/chunk-cache */ "./src/demux/chunk-cache.ts");
/* harmony import */ var _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../demux/transmuxer-interface */ "./src/demux/transmuxer-interface.ts");
/* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../types/transmuxer */ "./src/types/transmuxer.ts");
/* harmony import */ var _fragment_finders__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./fragment-finders */ "./src/controller/fragment-finders.ts");
/* harmony import */ var _utils_discontinuities__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/discontinuities */ "./src/utils/discontinuities.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var TICK_INTERVAL = 100; // how often to tick in ms
var AudioStreamController = /*#__PURE__*/function (_BaseStreamController) {
_inheritsLoose(AudioStreamController, _BaseStreamController);
function AudioStreamController(hls, fragmentTracker) {
var _this;
_this = _BaseStreamController.call(this, hls, fragmentTracker, '[audio-stream-controller]') || this;
_this.videoBuffer = null;
_this.videoTrackCC = -1;
_this.waitingVideoCC = -1;
_this.audioSwitch = false;
_this.trackId = -1;
_this.waitingData = null;
_this.mainDetails = null;
_this.bufferFlushed = false;
_this._registerListeners();
return _this;
}
var _proto = AudioStreamController.prototype;
_proto.onHandlerDestroying = function onHandlerDestroying() {
this._unregisterListeners();
this.mainDetails = null;
};
_proto._registerListeners = function _registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_RESET, this.onBufferReset, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_CREATED, this.onBufferCreated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].INIT_PTS_FOUND, this.onInitPtsFound, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_RESET, this.onBufferReset, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_CREATED, this.onBufferCreated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].INIT_PTS_FOUND, this.onInitPtsFound, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
} // INIT_PTS_FOUND is triggered when the video track parsed in the stream-controller has a new PTS value
;
_proto.onInitPtsFound = function onInitPtsFound(event, _ref) {
var frag = _ref.frag,
id = _ref.id,
initPTS = _ref.initPTS;
// Always update the new INIT PTS
// Can change due level switch
if (id === 'main') {
var cc = frag.cc;
this.initPTS[frag.cc] = initPTS;
this.log("InitPTS for cc: " + cc + " found from main: " + initPTS);
this.videoTrackCC = cc; // If we are waiting, tick immediately to unblock audio fragment transmuxing
if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS) {
this.tick();
}
}
};
_proto.startLoad = function startLoad(startPosition) {
if (!this.levels) {
this.startPosition = startPosition;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].STOPPED;
return;
}
var lastCurrentTime = this.lastCurrentTime;
this.stopLoad();
this.setInterval(TICK_INTERVAL);
this.fragLoadError = 0;
if (lastCurrentTime > 0 && startPosition === -1) {
this.log("Override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3));
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
} else {
this.loadedmetadata = false;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_TRACK;
}
this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
this.tick();
};
_proto.doTick = function doTick() {
switch (this.state) {
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE:
this.doTickIdle();
break;
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_TRACK:
{
var _levels$trackId;
var levels = this.levels,
trackId = this.trackId;
var details = levels === null || levels === void 0 ? void 0 : (_levels$trackId = levels[trackId]) === null || _levels$trackId === void 0 ? void 0 : _levels$trackId.details;
if (details) {
if (this.waitForCdnTuneIn(details)) {
break;
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS;
}
break;
}
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING_WAITING_RETRY:
{
var _this$media;
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) !== null && _this$media !== void 0 && _this$media.seeking) {
this.log('RetryDate reached, switch back to IDLE state');
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
break;
}
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS:
{
// Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS
var waitingData = this.waitingData;
if (waitingData) {
var frag = waitingData.frag,
part = waitingData.part,
cache = waitingData.cache,
complete = waitingData.complete;
if (this.initPTS[frag.cc] !== undefined) {
this.waitingData = null;
this.waitingVideoCC = -1;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING;
var payload = cache.flush();
var data = {
frag: frag,
part: part,
payload: payload,
networkDetails: null
};
this._handleFragmentLoadProgress(data);
if (complete) {
_BaseStreamController.prototype._handleFragmentLoadComplete.call(this, data);
}
} else if (this.videoTrackCC !== this.waitingVideoCC) {
// Drop waiting fragment if videoTrackCC has changed since waitingFragment was set and initPTS was not found
_utils_logger__WEBPACK_IMPORTED_MODULE_14__["logger"].log("Waiting fragment cc (" + frag.cc + ") cancelled because video is at cc " + this.videoTrackCC);
this.clearWaitingFragment();
} else {
// Drop waiting fragment if an earlier fragment is needed
var pos = this.getLoadPosition();
var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(this.mediaBuffer, pos, this.config.maxBufferHole);
var waitingFragmentAtPosition = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_11__["fragmentWithinToleranceTest"])(bufferInfo.end, this.config.maxFragLookUpTolerance, frag);
if (waitingFragmentAtPosition < 0) {
_utils_logger__WEBPACK_IMPORTED_MODULE_14__["logger"].log("Waiting fragment cc (" + frag.cc + ") @ " + frag.start + " cancelled because another fragment at " + bufferInfo.end + " is needed");
this.clearWaitingFragment();
}
}
} else {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
}
}
this.onTickEnd();
};
_proto.clearWaitingFragment = function clearWaitingFragment() {
var waitingData = this.waitingData;
if (waitingData) {
this.fragmentTracker.removeFragment(waitingData.frag);
this.waitingData = null;
this.waitingVideoCC = -1;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
};
_proto.onTickEnd = function onTickEnd() {
var media = this.media;
if (!media || !media.readyState) {
// Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)
return;
}
var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;
var buffered = mediaBuffer.buffered;
if (!this.loadedmetadata && buffered.length) {
this.loadedmetadata = true;
}
this.lastCurrentTime = media.currentTime;
};
_proto.doTickIdle = function doTickIdle() {
var _frag$decryptdata, _frag$decryptdata2;
var hls = this.hls,
levels = this.levels,
media = this.media,
trackId = this.trackId;
var config = hls.config;
if (!levels || !levels[trackId]) {
return;
} // if video not attached AND
// start fragment already requested OR start frag prefetch not enabled
// exit loop
// => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop
if (!media && (this.startFragRequested || !config.startFragPrefetch)) {
return;
}
var levelInfo = levels[trackId];
var trackDetails = levelInfo.details;
if (!trackDetails || trackDetails.live && this.levelLastLoaded !== trackId || this.waitForCdnTuneIn(trackDetails)) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_TRACK;
return;
}
if (this.bufferFlushed) {
this.bufferFlushed = false;
this.afterBufferFlushed(this.mediaBuffer ? this.mediaBuffer : this.media, _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO);
}
var bufferInfo = this.getFwdBufferInfo(this.mediaBuffer ? this.mediaBuffer : this.media, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO);
if (bufferInfo === null) {
return;
}
var bufferLen = bufferInfo.len;
var maxBufLen = this.getMaxBufferLength();
var audioSwitch = this.audioSwitch; // if buffer length is less than maxBufLen try to load a new fragment
if (bufferLen >= maxBufLen && !audioSwitch) {
return;
}
if (!audioSwitch && this._streamEnded(bufferInfo, trackDetails)) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_EOS, {
type: 'audio'
});
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ENDED;
return;
}
var fragments = trackDetails.fragments;
var start = fragments[0].start;
var targetBufferTime = bufferInfo.end;
if (audioSwitch) {
var pos = this.getLoadPosition();
targetBufferTime = pos; // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime
if (trackDetails.PTSKnown && pos < start) {
// if everything is buffered from pos to start or if audio buffer upfront, let's seek to start
if (bufferInfo.end > start || bufferInfo.nextStart) {
this.log('Alt audio track ahead of main track, seek to start of alt audio track');
media.currentTime = start + 0.05;
}
}
}
var frag = this.getNextFragment(targetBufferTime, trackDetails);
if (!frag) {
this.bufferFlushed = true;
return;
}
if (((_frag$decryptdata = frag.decryptdata) === null || _frag$decryptdata === void 0 ? void 0 : _frag$decryptdata.keyFormat) === 'identity' && !((_frag$decryptdata2 = frag.decryptdata) !== null && _frag$decryptdata2 !== void 0 && _frag$decryptdata2.key)) {
this.loadKey(frag, trackDetails);
} else {
this.loadFragment(frag, trackDetails, targetBufferTime);
}
};
_proto.getMaxBufferLength = function getMaxBufferLength() {
var maxConfigBuffer = _BaseStreamController.prototype.getMaxBufferLength.call(this);
var mainBufferInfo = this.getFwdBufferInfo(this.videoBuffer ? this.videoBuffer : this.media, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN);
if (mainBufferInfo === null) {
return maxConfigBuffer;
}
return Math.max(maxConfigBuffer, mainBufferInfo.len);
};
_proto.onMediaDetaching = function onMediaDetaching() {
this.videoBuffer = null;
_BaseStreamController.prototype.onMediaDetaching.call(this);
};
_proto.onAudioTracksUpdated = function onAudioTracksUpdated(event, _ref2) {
var audioTracks = _ref2.audioTracks;
this.resetTransmuxer();
this.levels = audioTracks.map(function (mediaPlaylist) {
return new _types_level__WEBPACK_IMPORTED_MODULE_5__["Level"](mediaPlaylist);
});
};
_proto.onAudioTrackSwitching = function onAudioTrackSwitching(event, data) {
// if any URL found on new audio track, it is an alternate audio track
var altAudio = !!data.url;
this.trackId = data.id;
var fragCurrent = this.fragCurrent;
if (fragCurrent !== null && fragCurrent !== void 0 && fragCurrent.loader) {
fragCurrent.loader.abort();
}
this.fragCurrent = null;
this.clearWaitingFragment(); // destroy useless transmuxer when switching audio to main
if (!altAudio) {
this.resetTransmuxer();
} else {
// switching to audio track, start timer if not already started
this.setInterval(TICK_INTERVAL);
} // should we switch tracks ?
if (altAudio) {
this.audioSwitch = true; // main audio track are handled by stream-controller, just do something if switching to alt audio track
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
} else {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].STOPPED;
}
this.tick();
};
_proto.onManifestLoading = function onManifestLoading() {
this.mainDetails = null;
this.fragmentTracker.removeAllFragments();
this.startPosition = this.lastCurrentTime = 0;
this.bufferFlushed = false;
};
_proto.onLevelLoaded = function onLevelLoaded(event, data) {
this.mainDetails = data.details;
};
_proto.onAudioTrackLoaded = function onAudioTrackLoaded(event, data) {
var _track$details;
var levels = this.levels;
var newDetails = data.details,
trackId = data.id;
if (!levels) {
this.warn("Audio tracks were reset while loading level " + trackId);
return;
}
this.log("Track " + trackId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "],duration:" + newDetails.totalduration);
var track = levels[trackId];
var sliding = 0;
if (newDetails.live || (_track$details = track.details) !== null && _track$details !== void 0 && _track$details.live) {
var mainDetails = this.mainDetails;
if (!newDetails.fragments[0]) {
newDetails.deltaUpdateFailed = true;
}
if (newDetails.deltaUpdateFailed || !mainDetails) {
return;
}
if (!track.details && newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) {
// Make sure our audio rendition is aligned with the "main" rendition, using
// pdt as our reference times.
Object(_utils_discontinuities__WEBPACK_IMPORTED_MODULE_12__["alignMediaPlaylistByPDT"])(newDetails, mainDetails);
sliding = newDetails.fragments[0].start;
} else {
sliding = this.alignPlaylists(newDetails, track.details);
}
}
track.details = newDetails;
this.levelLastLoaded = trackId; // compute start position if we are aligned with the main playlist
if (!this.startFragRequested && (this.mainDetails || !newDetails.live)) {
this.setStartPosition(track.details, sliding);
} // only switch back to IDLE state if we were waiting for track to start downloading a new fragment
if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_TRACK && !this.waitForCdnTuneIn(newDetails)) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
} // trigger handler right now
this.tick();
};
_proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(data) {
var _frag$initSegment;
var frag = data.frag,
part = data.part,
payload = data.payload;
var config = this.config,
trackId = this.trackId,
levels = this.levels;
if (!levels) {
this.warn("Audio tracks were reset while fragment load was in progress. Fragment " + frag.sn + " of level " + frag.level + " will not be buffered");
return;
}
var track = levels[trackId];
console.assert(track, 'Audio track is defined on fragment load progress');
var details = track.details;
console.assert(details, 'Audio track details are defined on fragment load progress');
var audioCodec = config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2';
var transmuxer = this.transmuxer;
if (!transmuxer) {
transmuxer = this.transmuxer = new _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_9__["default"](this.hls, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
} // Check if we have video initPTS
// If not we need to wait for it
var initPTS = this.initPTS[frag.cc];
var initSegmentData = (_frag$initSegment = frag.initSegment) === null || _frag$initSegment === void 0 ? void 0 : _frag$initSegment.data;
if (initPTS !== undefined) {
// this.log(`Transmuxing ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);
// time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
var accurateTimeOffset = false; // details.PTSKnown || !details.live;
var partIndex = part ? part.index : -1;
var partial = partIndex !== -1;
var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_10__["ChunkMetadata"](frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
transmuxer.push(payload, initSegmentData, audioCodec, '', frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_14__["logger"].log("Unknown video PTS for cc " + frag.cc + ", waiting for video PTS before demuxing audio frag " + frag.sn + " of [" + details.startSN + " ," + details.endSN + "],track " + trackId);
var _this$waitingData = this.waitingData = this.waitingData || {
frag: frag,
part: part,
cache: new _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_8__["default"](),
complete: false
},
cache = _this$waitingData.cache;
cache.push(new Uint8Array(payload));
this.waitingVideoCC = this.videoTrackCC;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS;
}
};
_proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedData) {
if (this.waitingData) {
this.waitingData.complete = true;
return;
}
_BaseStreamController.prototype._handleFragmentLoadComplete.call(this, fragLoadedData);
};
_proto.onBufferReset = function
/* event: Events.BUFFER_RESET */
onBufferReset() {
// reset reference to sourcebuffers
this.mediaBuffer = this.videoBuffer = null;
this.loadedmetadata = false;
};
_proto.onBufferCreated = function onBufferCreated(event, data) {
var audioTrack = data.tracks.audio;
if (audioTrack) {
this.mediaBuffer = audioTrack.buffer;
}
if (data.tracks.video) {
this.videoBuffer = data.tracks.video.buffer;
}
};
_proto.onFragBuffered = function onFragBuffered(event, data) {
var frag = data.frag,
part = data.part;
if (frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO) {
return;
}
if (this.fragContextChanged(frag)) {
// If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
// Avoid setting state back to IDLE or concluding the audio switch; otherwise, the switched-to track will not buffer
this.warn("Fragment " + frag.sn + (part ? ' p: ' + part.index : '') + " of level " + frag.level + " finished buffering, but was aborted. state: " + this.state + ", audioSwitch: " + this.audioSwitch);
return;
}
if (frag.sn !== 'initSegment') {
this.fragPrevious = frag;
if (this.audioSwitch) {
this.audioSwitch = false;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_SWITCHED, {
id: this.trackId
});
}
}
this.fragBufferedComplete(frag, part);
};
_proto.onError = function onError(event, data) {
switch (data.details) {
case _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].FRAG_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].FRAG_LOAD_TIMEOUT:
case _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].KEY_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].KEY_LOAD_TIMEOUT:
// TODO: Skip fragments that do not belong to this.fragCurrent audio-group id
this.onFragmentOrKeyLoadError(_types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO, data);
break;
case _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].AUDIO_TRACK_LOAD_TIMEOUT:
// when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received
if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR && this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].STOPPED) {
// if fatal error, stop processing, otherwise move to IDLE to retry loading
this.state = data.fatal ? _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR : _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
this.warn(data.details + " while loading frag, switching to " + this.state + " state");
}
break;
case _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].BUFFER_FULL_ERROR:
// if in appending state
if (data.parent === 'audio' && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSED)) {
var flushBuffer = true;
var bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO); // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
// reduce max buf len if current position is buffered
if (bufferedInfo && bufferedInfo.len > 0.5) {
flushBuffer = !this.reduceMaxBufferLength(bufferedInfo.len);
}
if (flushBuffer) {
// 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 audio buffer to recover
this.warn('Buffer full error also media.currentTime is not buffered, flush audio buffer');
this.fragCurrent = null;
_BaseStreamController.prototype.flushMainBuffer.call(this, 0, Number.POSITIVE_INFINITY, 'audio');
}
this.resetLoadingState();
}
break;
default:
break;
}
};
_proto.onBufferFlushed = function onBufferFlushed(event, _ref3) {
var type = _ref3.type;
if (type === _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO) {
this.bufferFlushed = true;
}
};
_proto._handleTransmuxComplete = function _handleTransmuxComplete(transmuxResult) {
var _id3$samples;
var id = 'audio';
var hls = this.hls;
var remuxResult = transmuxResult.remuxResult,
chunkMeta = transmuxResult.chunkMeta;
var context = this.getCurrentContext(chunkMeta);
if (!context) {
this.warn("The loading context changed while buffering fragment " + chunkMeta.sn + " of level " + chunkMeta.level + ". This chunk will not be buffered.");
this.resetLiveStartWhenNotLoaded(chunkMeta.level);
return;
}
var frag = context.frag,
part = context.part;
var audio = remuxResult.audio,
text = remuxResult.text,
id3 = remuxResult.id3,
initSegment = remuxResult.initSegment; // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
// If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
if (this.fragContextChanged(frag)) {
return;
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING;
if (this.audioSwitch && audio) {
this.completeAudioSwitch();
}
if (initSegment !== null && initSegment !== void 0 && initSegment.tracks) {
this._bufferInitSegment(initSegment.tracks, frag, chunkMeta);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_PARSING_INIT_SEGMENT, {
frag: frag,
id: id,
tracks: initSegment.tracks
}); // Only flush audio from old audio tracks when PTS is known on new audio track
}
if (audio) {
var startPTS = audio.startPTS,
endPTS = audio.endPTS,
startDTS = audio.startDTS,
endDTS = audio.endDTS;
if (part) {
part.elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO] = {
startPTS: startPTS,
endPTS: endPTS,
startDTS: startDTS,
endDTS: endDTS
};
}
frag.setElementaryStreamInfo(_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO, startPTS, endPTS, startDTS, endDTS);
this.bufferFragmentData(audio, frag, part, chunkMeta);
}
if (id3 !== null && id3 !== void 0 && (_id3$samples = id3.samples) !== null && _id3$samples !== void 0 && _id3$samples.length) {
var emittedID3 = _extends({
frag: frag,
id: id
}, id3);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_PARSING_METADATA, emittedID3);
}
if (text) {
var emittedText = _extends({
frag: frag,
id: id
}, text);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_PARSING_USERDATA, emittedText);
}
};
_proto._bufferInitSegment = function _bufferInitSegment(tracks, frag, chunkMeta) {
if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING) {
return;
} // delete any video track found on audio transmuxer
if (tracks.video) {
delete tracks.video;
} // include levelCodec in audio and video tracks
var track = tracks.audio;
if (!track) {
return;
}
track.levelCodec = track.codec;
track.id = 'audio';
this.log("Init audio buffer, container:" + track.container + ", codecs[parsed]=[" + track.codec + "]");
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_CODECS, tracks);
var initSegment = track.initSegment;
if (initSegment !== null && initSegment !== void 0 && initSegment.byteLength) {
var segment = {
type: 'audio',
frag: frag,
part: null,
chunkMeta: chunkMeta,
parent: frag.type,
data: initSegment
};
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_APPENDING, segment);
} // trigger handler right now
this.tick();
};
_proto.loadFragment = function loadFragment(frag, trackDetails, targetBufferTime) {
// only load if fragment is not loaded or if in audio switch
var fragState = this.fragmentTracker.getState(frag);
this.fragCurrent = frag; // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch
if (this.audioSwitch || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_4__["FragmentState"].NOT_LOADED || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_4__["FragmentState"].PARTIAL) {
if (frag.sn === 'initSegment') {
this._loadInitSegment(frag);
} else if (trackDetails.live && !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.initPTS[frag.cc])) {
this.log("Waiting for video PTS in continuity counter " + frag.cc + " of live stream before loading audio fragment " + frag.sn + " of level " + this.trackId);
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS;
} else {
this.startFragRequested = true;
_BaseStreamController.prototype.loadFragment.call(this, frag, trackDetails, targetBufferTime);
}
}
};
_proto.completeAudioSwitch = function completeAudioSwitch() {
var hls = this.hls,
media = this.media,
trackId = this.trackId;
if (media) {
this.log('Switching audio track : flushing all audio');
_BaseStreamController.prototype.flushMainBuffer.call(this, 0, Number.POSITIVE_INFINITY, 'audio');
}
this.audioSwitch = false;
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_SWITCHED, {
id: trackId
});
};
return AudioStreamController;
}(_base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["default"]);
/* harmony default export */ __webpack_exports__["default"] = (AudioStreamController);
/***/ }),
/***/ "./src/controller/audio-track-controller.ts":
/*!**************************************************!*\
!*** ./src/controller/audio-track-controller.ts ***!
\**************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base-playlist-controller */ "./src/controller/base-playlist-controller.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
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); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var AudioTrackController = /*#__PURE__*/function (_BasePlaylistControll) {
_inheritsLoose(AudioTrackController, _BasePlaylistControll);
function AudioTrackController(hls) {
var _this;
_this = _BasePlaylistControll.call(this, hls, '[audio-track-controller]') || this;
_this.tracks = [];
_this.groupId = null;
_this.tracksInGroup = [];
_this.trackId = -1;
_this.trackName = '';
_this.selectDefaultTrack = true;
_this.registerListeners();
return _this;
}
var _proto = AudioTrackController.prototype;
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_SWITCHING, this.onLevelSwitching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
};
_proto.unregisterListeners = function unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_SWITCHING, this.onLevelSwitching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
};
_proto.destroy = function destroy() {
this.unregisterListeners();
this.tracks.length = 0;
this.tracksInGroup.length = 0;
_BasePlaylistControll.prototype.destroy.call(this);
};
_proto.onManifestLoading = function onManifestLoading() {
this.tracks = [];
this.groupId = null;
this.tracksInGroup = [];
this.trackId = -1;
this.trackName = '';
this.selectDefaultTrack = true;
};
_proto.onManifestParsed = function onManifestParsed(event, data) {
this.tracks = data.audioTracks || [];
};
_proto.onAudioTrackLoaded = function onAudioTrackLoaded(event, data) {
var id = data.id,
details = data.details;
var currentTrack = this.tracksInGroup[id];
if (!currentTrack) {
this.warn("Invalid audio track id " + id);
return;
}
var curDetails = currentTrack.details;
currentTrack.details = data.details;
this.log("audioTrack " + id + " loaded [" + details.startSN + "-" + details.endSN + "]");
if (id === this.trackId) {
this.retryCount = 0;
this.playlistLoaded(id, data, curDetails);
}
};
_proto.onLevelLoading = function onLevelLoading(event, data) {
this.switchLevel(data.level);
};
_proto.onLevelSwitching = function onLevelSwitching(event, data) {
this.switchLevel(data.level);
};
_proto.switchLevel = function switchLevel(levelIndex) {
var levelInfo = this.hls.levels[levelIndex];
if (!(levelInfo !== null && levelInfo !== void 0 && levelInfo.audioGroupIds)) {
return;
}
var audioGroupId = levelInfo.audioGroupIds[levelInfo.urlId];
if (this.groupId !== audioGroupId) {
this.groupId = audioGroupId;
var audioTracks = this.tracks.filter(function (track) {
return !audioGroupId || track.groupId === audioGroupId;
}); // Disable selectDefaultTrack if there are no default tracks
if (this.selectDefaultTrack && !audioTracks.some(function (track) {
return track.default;
})) {
this.selectDefaultTrack = false;
}
this.tracksInGroup = audioTracks;
var audioTracksUpdated = {
audioTracks: audioTracks
};
this.log("Updating audio tracks, " + audioTracks.length + " track(s) found in \"" + audioGroupId + "\" group-id");
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACKS_UPDATED, audioTracksUpdated);
this.selectInitialTrack();
}
};
_proto.onError = function onError(event, data) {
_BasePlaylistControll.prototype.onError.call(this, event, data);
if (data.fatal || !data.context) {
return;
}
if (data.context.type === _types_loader__WEBPACK_IMPORTED_MODULE_3__["PlaylistContextType"].AUDIO_TRACK && data.context.id === this.trackId && data.context.groupId === this.groupId) {
this.retryLoadingOrFail(data);
}
};
_proto.setAudioTrack = function setAudioTrack(newId) {
var tracks = this.tracksInGroup; // check if level idx is valid
if (newId < 0 || newId >= tracks.length) {
this.warn('Invalid id passed to audio-track controller');
return;
} // stopping live reloading timer if any
this.clearTimer();
var lastTrack = tracks[this.trackId];
this.log("Now switching to audio-track index " + newId);
var track = tracks[newId];
var id = track.id,
_track$groupId = track.groupId,
groupId = _track$groupId === void 0 ? '' : _track$groupId,
name = track.name,
type = track.type,
url = track.url;
this.trackId = newId;
this.trackName = name;
this.selectDefaultTrack = false;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACK_SWITCHING, {
id: id,
groupId: groupId,
name: name,
type: type,
url: url
}); // Do not reload track unless live
if (track.details && !track.details.live) {
return;
}
var hlsUrlParameters = this.switchParams(track.url, lastTrack === null || lastTrack === void 0 ? void 0 : lastTrack.details);
this.loadPlaylist(hlsUrlParameters);
};
_proto.selectInitialTrack = function selectInitialTrack() {
var audioTracks = this.tracksInGroup;
console.assert(audioTracks.length, 'Initial audio track should be selected when tracks are known');
var currentAudioTrackName = this.trackName;
var trackId = this.findTrackId(currentAudioTrackName) || this.findTrackId();
if (trackId !== -1) {
this.setAudioTrack(trackId);
} else {
this.warn("No track found for running audio group-ID: " + this.groupId);
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR,
fatal: true
});
}
};
_proto.findTrackId = function findTrackId(name) {
var audioTracks = this.tracksInGroup;
for (var i = 0; i < audioTracks.length; i++) {
var track = audioTracks[i];
if (!this.selectDefaultTrack || track.default) {
if (!name || name === track.name) {
return track.id;
}
}
}
return -1;
};
_proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
var audioTrack = this.tracksInGroup[this.trackId];
if (this.shouldLoadTrack(audioTrack)) {
var id = audioTrack.id;
var groupId = audioTrack.groupId;
var url = audioTrack.url;
if (hlsUrlParameters) {
try {
url = hlsUrlParameters.addDirectives(url);
} catch (error) {
this.warn("Could not construct new URL with HLS Delivery Directives: " + error);
}
} // track not retrieved yet, or live playlist we need to (re)load it
this.log("loading audio-track playlist for id: " + id);
this.clearTimer();
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACK_LOADING, {
url: url,
id: id,
groupId: groupId,
deliveryDirectives: hlsUrlParameters || null
});
}
};
_createClass(AudioTrackController, [{
key: "audioTracks",
get: function get() {
return this.tracksInGroup;
}
}, {
key: "audioTrack",
get: function get() {
return this.trackId;
},
set: function set(newId) {
// If audio track is selected from API then don't choose from the manifest default track
this.selectDefaultTrack = false;
this.setAudioTrack(newId);
}
}]);
return AudioTrackController;
}(_base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__["default"]);
/* harmony default export */ __webpack_exports__["default"] = (AudioTrackController);
/***/ }),
/***/ "./src/controller/base-playlist-controller.ts":
/*!****************************************************!*\
!*** ./src/controller/base-playlist-controller.ts ***!
\****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BasePlaylistController; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts");
/* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
var BasePlaylistController = /*#__PURE__*/function () {
function BasePlaylistController(hls, logPrefix) {
this.hls = void 0;
this.timer = -1;
this.canLoad = false;
this.retryCount = 0;
this.log = void 0;
this.warn = void 0;
this.log = _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"], logPrefix + ":");
this.warn = _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"], logPrefix + ":");
this.hls = hls;
}
var _proto = BasePlaylistController.prototype;
_proto.destroy = function destroy() {
this.clearTimer(); // @ts-ignore
this.hls = this.log = this.warn = null;
};
_proto.onError = function onError(event, data) {
if (data.fatal && data.type === _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].NETWORK_ERROR) {
this.clearTimer();
}
};
_proto.clearTimer = function clearTimer() {
clearTimeout(this.timer);
this.timer = -1;
};
_proto.startLoad = function startLoad() {
this.canLoad = true;
this.retryCount = 0;
this.loadPlaylist();
};
_proto.stopLoad = function stopLoad() {
this.canLoad = false;
this.clearTimer();
};
_proto.switchParams = function switchParams(playlistUri, previous) {
var renditionReports = previous === null || previous === void 0 ? void 0 : previous.renditionReports;
if (renditionReports) {
for (var i = 0; i < renditionReports.length; i++) {
var attr = renditionReports[i];
var uri = '' + attr.URI;
if (uri === playlistUri.substr(-uri.length)) {
var msn = parseInt(attr['LAST-MSN']);
var part = parseInt(attr['LAST-PART']);
if (previous && this.hls.config.lowLatencyMode) {
var currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);
if (part !== undefined && currentGoal > previous.partTarget) {
part += 1;
}
}
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(msn)) {
return new _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsUrlParameters"](msn, Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(part) ? part : undefined, _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsSkip"].No);
}
}
}
}
};
_proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {};
_proto.shouldLoadTrack = function shouldLoadTrack(track) {
return this.canLoad && track && !!track.url && (!track.details || track.details.live);
};
_proto.playlistLoaded = function playlistLoaded(index, data, previousDetails) {
var _this = this;
var details = data.details,
stats = data.stats; // Set last updated date-time
var elapsed = stats.loading.end ? Math.max(0, self.performance.now() - stats.loading.end) : 0;
details.advancedDateTime = Date.now() - elapsed; // if current playlist is a live playlist, arm a timer to reload it
if (details.live || previousDetails !== null && previousDetails !== void 0 && previousDetails.live) {
details.reloaded(previousDetails);
if (previousDetails) {
this.log("live playlist " + index + " " + (details.advanced ? 'REFRESHED ' + details.lastPartSn + '-' + details.lastPartIndex : 'MISSED'));
} // Merge live playlists to adjust fragment starts and fill in delta playlist skipped segments
if (previousDetails && details.fragments.length > 0) {
Object(_level_helper__WEBPACK_IMPORTED_MODULE_2__["mergeDetails"])(previousDetails, details);
}
if (!this.canLoad || !details.live) {
return;
}
var deliveryDirectives;
var msn = undefined;
var part = undefined;
if (details.canBlockReload && details.endSN && details.advanced) {
// Load level with LL-HLS delivery directives
var lowLatencyMode = this.hls.config.lowLatencyMode;
var lastPartSn = details.lastPartSn;
var endSn = details.endSN;
var lastPartIndex = details.lastPartIndex;
var hasParts = lastPartIndex !== -1;
var lastPart = lastPartSn === endSn; // When low latency mode is disabled, we'll skip part requests once the last part index is found
var nextSnStartIndex = lowLatencyMode ? 0 : lastPartIndex;
if (hasParts) {
msn = lastPart ? endSn + 1 : lastPartSn;
part = lastPart ? nextSnStartIndex : lastPartIndex + 1;
} else {
msn = endSn + 1;
} // Low-Latency CDN Tune-in: "age" header and time since load indicates we're behind by more than one part
// Update directives to obtain the Playlist that has the estimated additional duration of media
var lastAdvanced = details.age;
var cdnAge = lastAdvanced + details.ageHeader;
var currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);
if (currentGoal > 0) {
if (previousDetails && currentGoal > previousDetails.tuneInGoal) {
// If we attempted to get the next or latest playlist update, but currentGoal increased,
// then we either can't catchup, or the "age" header cannot be trusted.
this.warn("CDN Tune-in goal increased from: " + previousDetails.tuneInGoal + " to: " + currentGoal + " with playlist age: " + details.age);
currentGoal = 0;
} else {
var segments = Math.floor(currentGoal / details.targetduration);
msn += segments;
if (part !== undefined) {
var parts = Math.round(currentGoal % details.targetduration / details.partTarget);
part += parts;
}
this.log("CDN Tune-in age: " + details.ageHeader + "s last advanced " + lastAdvanced.toFixed(2) + "s goal: " + currentGoal + " skip sn " + segments + " to part " + part);
}
details.tuneInGoal = currentGoal;
}
deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
if (lowLatencyMode || !lastPart) {
this.loadPlaylist(deliveryDirectives);
return;
}
} else {
deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
}
var reloadInterval = Object(_level_helper__WEBPACK_IMPORTED_MODULE_2__["computeReloadInterval"])(details, stats);
if (msn !== undefined && details.canBlockReload) {
reloadInterval -= details.partTarget || 1;
}
this.log("reload live playlist " + index + " in " + Math.round(reloadInterval) + " ms");
this.timer = self.setTimeout(function () {
return _this.loadPlaylist(deliveryDirectives);
}, reloadInterval);
} else {
this.clearTimer();
}
};
_proto.getDeliveryDirectives = function getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) {
var skip = Object(_types_level__WEBPACK_IMPORTED_MODULE_1__["getSkipValue"])(details, msn);
if (previousDeliveryDirectives !== null && previousDeliveryDirectives !== void 0 && previousDeliveryDirectives.skip && details.deltaUpdateFailed) {
msn = previousDeliveryDirectives.msn;
part = previousDeliveryDirectives.part;
skip = _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsSkip"].No;
}
return new _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsUrlParameters"](msn, part, skip);
};
_proto.retryLoadingOrFail = function retryLoadingOrFail(errorEvent) {
var _this2 = this;
var config = this.hls.config;
var retry = this.retryCount < config.levelLoadingMaxRetry;
if (retry) {
var _errorEvent$context;
this.retryCount++;
if (errorEvent.details.indexOf('LoadTimeOut') > -1 && (_errorEvent$context = errorEvent.context) !== null && _errorEvent$context !== void 0 && _errorEvent$context.deliveryDirectives) {
// The LL-HLS request already timed out so retry immediately
this.warn("retry playlist loading #" + this.retryCount + " after \"" + errorEvent.details + "\"");
this.loadPlaylist();
} else {
// exponential backoff capped to max retry timeout
var delay = Math.min(Math.pow(2, this.retryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout); // Schedule level/track reload
this.timer = self.setTimeout(function () {
return _this2.loadPlaylist();
}, delay);
this.warn("retry playlist loading #" + this.retryCount + " in " + delay + " ms after \"" + errorEvent.details + "\"");
}
} else {
this.warn("cannot recover from error \"" + errorEvent.details + "\""); // stopping live reloading timer if any
this.clearTimer(); // switch error to fatal
errorEvent.fatal = true;
}
return retry;
};
return BasePlaylistController;
}();
/***/ }),
/***/ "./src/controller/base-stream-controller.ts":
/*!**************************************************!*\
!*** ./src/controller/base-stream-controller.ts ***!
\**************************************************/
/*! exports provided: State, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "State", function() { return State; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BaseStreamController; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _task_loop__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../task-loop */ "./src/task-loop.ts");
/* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../types/transmuxer */ "./src/types/transmuxer.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _utils_discontinuities__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/discontinuities */ "./src/utils/discontinuities.ts");
/* harmony import */ var _fragment_finders__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./fragment-finders */ "./src/controller/fragment-finders.ts");
/* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts");
/* harmony import */ var _loader_fragment_loader__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../loader/fragment-loader */ "./src/loader/fragment-loader.ts");
/* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts");
/* harmony import */ var _utils_time_ranges__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/time-ranges */ "./src/utils/time-ranges.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
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); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var State = {
STOPPED: 'STOPPED',
IDLE: 'IDLE',
KEY_LOADING: 'KEY_LOADING',
FRAG_LOADING: 'FRAG_LOADING',
FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
WAITING_TRACK: 'WAITING_TRACK',
PARSING: 'PARSING',
PARSED: 'PARSED',
BACKTRACKING: 'BACKTRACKING',
ENDED: 'ENDED',
ERROR: 'ERROR',
WAITING_INIT_PTS: 'WAITING_INIT_PTS',
WAITING_LEVEL: 'WAITING_LEVEL'
};
var BaseStreamController = /*#__PURE__*/function (_TaskLoop) {
_inheritsLoose(BaseStreamController, _TaskLoop);
function BaseStreamController(hls, fragmentTracker, logPrefix) {
var _this;
_this = _TaskLoop.call(this) || this;
_this.hls = void 0;
_this.fragPrevious = null;
_this.fragCurrent = null;
_this.fragmentTracker = void 0;
_this.transmuxer = null;
_this._state = State.STOPPED;
_this.media = void 0;
_this.mediaBuffer = void 0;
_this.config = void 0;
_this.bitrateTest = false;
_this.lastCurrentTime = 0;
_this.nextLoadPosition = 0;
_this.startPosition = 0;
_this.loadedmetadata = false;
_this.fragLoadError = 0;
_this.retryDate = 0;
_this.levels = null;
_this.fragmentLoader = void 0;
_this.levelLastLoaded = null;
_this.startFragRequested = false;
_this.decrypter = void 0;
_this.initPTS = [];
_this.onvseeking = null;
_this.onvended = null;
_this.logPrefix = '';
_this.log = void 0;
_this.warn = void 0;
_this.logPrefix = logPrefix;
_this.log = _utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"].log.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"], logPrefix + ":");
_this.warn = _utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"].warn.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"], logPrefix + ":");
_this.hls = hls;
_this.fragmentLoader = new _loader_fragment_loader__WEBPACK_IMPORTED_MODULE_12__["default"](hls.config);
_this.fragmentTracker = fragmentTracker;
_this.config = hls.config;
_this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_13__["default"](hls, hls.config);
hls.on(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].KEY_LOADED, _this.onKeyLoaded, _assertThisInitialized(_this));
return _this;
}
var _proto = BaseStreamController.prototype;
_proto.doTick = function doTick() {
this.onTickEnd();
};
_proto.onTickEnd = function onTickEnd() {} // eslint-disable-next-line @typescript-eslint/no-unused-vars
;
_proto.startLoad = function startLoad(startPosition) {};
_proto.stopLoad = function stopLoad() {
this.fragmentLoader.abort();
var frag = this.fragCurrent;
if (frag) {
this.fragmentTracker.removeFragment(frag);
}
this.resetTransmuxer();
this.fragCurrent = null;
this.fragPrevious = null;
this.clearInterval();
this.clearNextTick();
this.state = State.STOPPED;
};
_proto._streamEnded = function _streamEnded(bufferInfo, levelDetails) {
var fragCurrent = this.fragCurrent,
fragmentTracker = this.fragmentTracker; // 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
if (!levelDetails.live && fragCurrent && fragCurrent.sn === levelDetails.endSN && !bufferInfo.nextStart) {
var fragState = fragmentTracker.getState(fragCurrent);
return fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].PARTIAL || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].OK;
}
return false;
};
_proto.onMediaAttached = function onMediaAttached(event, data) {
var media = this.media = this.mediaBuffer = data.media;
this.onvseeking = this.onMediaSeeking.bind(this);
this.onvended = this.onMediaEnded.bind(this);
media.addEventListener('seeking', this.onvseeking);
media.addEventListener('ended', this.onvended);
var config = this.config;
if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {
this.startLoad(config.startPosition);
}
};
_proto.onMediaDetaching = function onMediaDetaching() {
var media = this.media;
if (media !== null && media !== void 0 && media.ended) {
this.log('MSE detaching and video ended, reset startPosition');
this.startPosition = this.lastCurrentTime = 0;
} // remove video listeners
if (media) {
media.removeEventListener('seeking', this.onvseeking);
media.removeEventListener('ended', this.onvended);
this.onvseeking = this.onvended = null;
}
this.media = this.mediaBuffer = null;
this.loadedmetadata = false;
this.fragmentTracker.removeAllFragments();
this.stopLoad();
};
_proto.onMediaSeeking = function onMediaSeeking() {
var config = this.config,
fragCurrent = this.fragCurrent,
media = this.media,
mediaBuffer = this.mediaBuffer,
state = this.state;
var currentTime = media ? media.currentTime : 0;
var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(mediaBuffer || media, currentTime, config.maxBufferHole);
this.log("media seeking to " + (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(currentTime) ? currentTime.toFixed(3) : currentTime) + ", state: " + state);
if (state === State.ENDED) {
this.resetLoadingState();
} else if (fragCurrent && !bufferInfo.len) {
// check if we are seeking to a unbuffered area AND if frag loading is in progress
var tolerance = config.maxFragLookUpTolerance;
var fragStartOffset = fragCurrent.start - tolerance;
var fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
var pastFragment = currentTime > fragEndOffset; // check if the seek position is past current fragment, and if so abort loading
if (currentTime < fragStartOffset || pastFragment) {
if (pastFragment && fragCurrent.loader) {
this.log('seeking outside of buffer while fragment load in progress, cancel fragment load');
fragCurrent.loader.abort();
}
this.resetLoadingState();
}
}
if (media) {
this.lastCurrentTime = currentTime;
} // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
if (!this.loadedmetadata && !bufferInfo.len) {
this.nextLoadPosition = this.startPosition = currentTime;
} // Async tick to speed up processing
this.tickImmediate();
};
_proto.onMediaEnded = function onMediaEnded() {
// reset startPosition and lastCurrentTime to restart playback @ stream beginning
this.startPosition = this.lastCurrentTime = 0;
};
_proto.onKeyLoaded = function onKeyLoaded(event, data) {
if (this.state !== State.KEY_LOADING || data.frag !== this.fragCurrent || !this.levels) {
return;
}
this.state = State.IDLE;
var levelDetails = this.levels[data.frag.level].details;
if (levelDetails) {
this.loadFragment(data.frag, levelDetails, data.frag.start);
}
};
_proto.onHandlerDestroying = function onHandlerDestroying() {
this.stopLoad();
_TaskLoop.prototype.onHandlerDestroying.call(this);
};
_proto.onHandlerDestroyed = function onHandlerDestroyed() {
this.state = State.STOPPED;
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].KEY_LOADED, this.onKeyLoaded, this);
if (this.fragmentLoader) {
this.fragmentLoader.destroy();
}
if (this.decrypter) {
this.decrypter.destroy();
}
this.hls = this.log = this.warn = this.decrypter = this.fragmentLoader = this.fragmentTracker = null;
_TaskLoop.prototype.onHandlerDestroyed.call(this);
};
_proto.loadKey = function loadKey(frag, details) {
this.log("Loading key for " + frag.sn + " of [" + details.startSN + "-" + details.endSN + "], " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + " " + frag.level);
this.state = State.KEY_LOADING;
this.fragCurrent = frag;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].KEY_LOADING, {
frag: frag
});
};
_proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) {
this._loadFragForPlayback(frag, levelDetails, targetBufferTime);
};
_proto._loadFragForPlayback = function _loadFragForPlayback(frag, levelDetails, targetBufferTime) {
var _this2 = this;
var progressCallback = function progressCallback(data) {
if (_this2.fragContextChanged(frag)) {
_this2.warn("Fragment " + frag.sn + (data.part ? ' p: ' + data.part.index : '') + " of level " + frag.level + " was dropped during download.");
_this2.fragmentTracker.removeFragment(frag);
return;
}
frag.stats.chunkCount++;
_this2._handleFragmentLoadProgress(data);
};
this._doFragLoad(frag, levelDetails, targetBufferTime, progressCallback).then(function (data) {
if (!data) {
// if we're here we probably needed to backtrack or are waiting for more parts
return;
}
_this2.fragLoadError = 0;
var state = _this2.state;
if (_this2.fragContextChanged(frag)) {
if (state === State.FRAG_LOADING || state === State.BACKTRACKING || !_this2.fragCurrent && state === State.PARSING) {
_this2.fragmentTracker.removeFragment(frag);
_this2.state = State.IDLE;
}
return;
}
if ('payload' in data) {
_this2.log("Loaded fragment " + frag.sn + " of level " + frag.level);
_this2.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADED, data); // Tracker backtrack must be called after onFragLoaded to update the fragment entity state to BACKTRACKED
// This happens after handleTransmuxComplete when the worker or progressive is disabled
if (_this2.state === State.BACKTRACKING) {
_this2.fragmentTracker.backtrack(frag, data);
_this2.resetFragmentLoading(frag);
return;
}
} // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback
_this2._handleFragmentLoadComplete(data);
}).catch(function (reason) {
_this2.warn(reason);
_this2.resetFragmentLoading(frag);
});
};
_proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset, type) {
if (type === void 0) {
type = null;
}
if (!(startOffset - endOffset)) {
return;
} // When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise,
// passing a null type flushes both buffers
var flushScope = {
startOffset: startOffset,
endOffset: endOffset,
type: type
}; // Reset load errors on flush
this.fragLoadError = 0;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].BUFFER_FLUSHING, flushScope);
};
_proto._loadInitSegment = function _loadInitSegment(frag) {
var _this3 = this;
this._doFragLoad(frag).then(function (data) {
if (!data || _this3.fragContextChanged(frag) || !_this3.levels) {
throw new Error('init load aborted');
}
return data;
}).then(function (data) {
var hls = _this3.hls;
var payload = data.payload;
var decryptData = frag.decryptdata; // check to see if the payload needs to be decrypted
if (payload && payload.byteLength > 0 && decryptData && decryptData.key && decryptData.iv && decryptData.method === 'AES-128') {
var startTime = self.performance.now(); // decrypt the subtitles
return _this3.decrypter.webCryptoDecrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).then(function (decryptedData) {
var endTime = self.performance.now();
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_DECRYPTED, {
frag: frag,
payload: decryptedData,
stats: {
tstart: startTime,
tdecrypt: endTime
}
});
data.payload = decryptedData;
return data;
});
}
return data;
}).then(function (data) {
var fragCurrent = _this3.fragCurrent,
hls = _this3.hls,
levels = _this3.levels;
if (!levels) {
throw new Error('init load aborted, missing levels');
}
var details = levels[frag.level].details;
console.assert(details, 'Level details are defined when init segment is loaded');
var stats = frag.stats;
_this3.state = State.IDLE;
_this3.fragLoadError = 0;
frag.data = new Uint8Array(data.payload);
stats.parsing.start = stats.buffering.start = self.performance.now();
stats.parsing.end = stats.buffering.end = self.performance.now(); // Silence FRAG_BUFFERED event if fragCurrent is null
if (data.frag === fragCurrent) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_BUFFERED, {
stats: stats,
frag: fragCurrent,
part: null,
id: frag.type
});
}
_this3.tick();
}).catch(function (reason) {
_this3.warn(reason);
_this3.resetFragmentLoading(frag);
});
};
_proto.fragContextChanged = function fragContextChanged(frag) {
var fragCurrent = this.fragCurrent;
return !frag || !fragCurrent || frag.level !== fragCurrent.level || frag.sn !== fragCurrent.sn || frag.urlId !== fragCurrent.urlId;
};
_proto.fragBufferedComplete = function fragBufferedComplete(frag, part) {
var media = this.mediaBuffer ? this.mediaBuffer : this.media;
this.log("Buffered " + frag.type + " sn: " + frag.sn + (part ? ' part: ' + part.index : '') + " of " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + " " + frag.level + " " + _utils_time_ranges__WEBPACK_IMPORTED_MODULE_14__["default"].toString(_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].getBuffered(media)));
this.state = State.IDLE;
this.tick();
};
_proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedEndData) {
var transmuxer = this.transmuxer;
if (!transmuxer) {
return;
}
var frag = fragLoadedEndData.frag,
part = fragLoadedEndData.part,
partsLoaded = fragLoadedEndData.partsLoaded; // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data
var complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some(function (fragLoaded) {
return !fragLoaded;
});
var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_7__["ChunkMetadata"](frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);
transmuxer.flush(chunkMeta);
} // eslint-disable-next-line @typescript-eslint/no-unused-vars
;
_proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(frag) {};
_proto._doFragLoad = function _doFragLoad(frag, details, targetBufferTime, progressCallback) {
var _this4 = this;
if (targetBufferTime === void 0) {
targetBufferTime = null;
}
if (!this.levels) {
throw new Error('frag load aborted, missing levels');
}
targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
if (this.config.lowLatencyMode && details) {
var partList = details.partList;
if (partList && progressCallback) {
if (targetBufferTime > frag.end && details.fragmentHint) {
frag = details.fragmentHint;
}
var partIndex = this.getNextPart(partList, frag, targetBufferTime);
if (partIndex > -1) {
var part = partList[partIndex];
this.log("Loading part sn: " + frag.sn + " p: " + part.index + " cc: " + frag.cc + " of playlist [" + details.startSN + "-" + details.endSN + "] parts [0-" + partIndex + "-" + (partList.length - 1) + "] " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + ": " + frag.level + ", target: " + parseFloat(targetBufferTime.toFixed(3)));
this.nextLoadPosition = part.start + part.duration;
this.state = State.FRAG_LOADING;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADING, {
frag: frag,
part: partList[partIndex],
targetBufferTime: targetBufferTime
});
return this.doFragPartsLoad(frag, partList, partIndex, progressCallback).catch(function (error) {
return _this4.handleFragLoadError(error);
});
} else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {
// Fragment hint has no parts
return Promise.resolve(null);
}
}
}
this.log("Loading fragment " + frag.sn + " cc: " + frag.cc + " " + (details ? 'of [' + details.startSN + '-' + details.endSN + '] ' : '') + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + ": " + frag.level + ", target: " + parseFloat(targetBufferTime.toFixed(3))); // Don't update nextLoadPosition for fragments which are not buffered
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.sn) && !this.bitrateTest) {
this.nextLoadPosition = frag.start + frag.duration;
}
this.state = State.FRAG_LOADING;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADING, {
frag: frag,
targetBufferTime: targetBufferTime
});
return this.fragmentLoader.load(frag, progressCallback).catch(function (error) {
return _this4.handleFragLoadError(error);
});
};
_proto.doFragPartsLoad = function doFragPartsLoad(frag, partList, partIndex, progressCallback) {
var _this5 = this;
return new Promise(function (resolve, reject) {
var partsLoaded = [];
var loadPartIndex = function loadPartIndex(index) {
var part = partList[index];
_this5.fragmentLoader.loadPart(frag, part, progressCallback).then(function (partLoadedData) {
partsLoaded[part.index] = partLoadedData;
var loadedPart = partLoadedData.part;
_this5.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADED, partLoadedData);
var nextPart = partList[index + 1];
if (nextPart && nextPart.fragment === frag) {
loadPartIndex(index + 1);
} else {
return resolve({
frag: frag,
part: loadedPart,
partsLoaded: partsLoaded
});
}
}).catch(reject);
};
loadPartIndex(partIndex);
});
};
_proto.handleFragLoadError = function handleFragLoadError(_ref) {
var data = _ref.data;
if (data && data.details === _errors__WEBPACK_IMPORTED_MODULE_6__["ErrorDetails"].INTERNAL_ABORTED) {
this.handleFragLoadAborted(data.frag, data.part);
} else {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, data);
}
return null;
};
_proto._handleTransmuxerFlush = function _handleTransmuxerFlush(chunkMeta) {
var context = this.getCurrentContext(chunkMeta);
if (!context || this.state !== State.PARSING) {
if (!this.fragCurrent) {
this.state = State.IDLE;
}
return;
}
var frag = context.frag,
part = context.part,
level = context.level;
var now = self.performance.now();
frag.stats.parsing.end = now;
if (part) {
part.stats.parsing.end = now;
}
this.updateLevelTiming(frag, part, level, chunkMeta.partial);
};
_proto.getCurrentContext = function getCurrentContext(chunkMeta) {
var levels = this.levels;
var levelIndex = chunkMeta.level,
sn = chunkMeta.sn,
partIndex = chunkMeta.part;
if (!levels || !levels[levelIndex]) {
this.warn("Levels object was unset while buffering fragment " + sn + " of level " + levelIndex + ". The current chunk will not be buffered.");
return null;
}
var level = levels[levelIndex];
var part = partIndex > -1 ? Object(_level_helper__WEBPACK_IMPORTED_MODULE_11__["getPartWith"])(level, sn, partIndex) : null;
var frag = part ? part.fragment : Object(_level_helper__WEBPACK_IMPORTED_MODULE_11__["getFragmentWithSN"])(level, sn, this.fragCurrent);
if (!frag) {
return null;
}
return {
frag: frag,
part: part,
level: level
};
};
_proto.bufferFragmentData = function bufferFragmentData(data, frag, part, chunkMeta) {
if (!data || this.state !== State.PARSING) {
return;
}
var data1 = data.data1,
data2 = data.data2;
var buffer = data1;
if (data1 && data2) {
// Combine the moof + mdat so that we buffer with a single append
buffer = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_8__["appendUint8Array"])(data1, data2);
}
if (!buffer || !buffer.length) {
return;
}
var segment = {
type: data.type,
frag: frag,
part: part,
chunkMeta: chunkMeta,
parent: frag.type,
data: buffer
};
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].BUFFER_APPENDING, segment);
if (data.dropped && data.independent && !part) {
// Clear buffer so that we reload previous segments sequentially if required
this.flushBufferGap(frag);
}
};
_proto.flushBufferGap = function flushBufferGap(frag) {
var media = this.media;
if (!media) {
return;
} // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed
if (!_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].isBuffered(media, media.currentTime)) {
this.flushMainBuffer(0, frag.start);
return;
} // Remove back-buffer without interrupting playback to allow back tracking
var currentTime = media.currentTime;
var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(media, currentTime, 0);
var fragDuration = frag.duration;
var segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);
var start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);
if (frag.start - start > segmentFraction) {
this.flushMainBuffer(start, frag.start);
}
};
_proto.getFwdBufferInfo = function getFwdBufferInfo(bufferable, type) {
var config = this.config;
var pos = this.getLoadPosition();
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(pos)) {
return null;
}
var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(bufferable, pos, config.maxBufferHole); // Workaround flaw in getting forward buffer when maxBufferHole is smaller than gap at current pos
if (bufferInfo.len === 0 && bufferInfo.nextStart !== undefined) {
var bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);
if (bufferedFragAtPos && bufferInfo.nextStart < bufferedFragAtPos.end) {
return _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(bufferable, pos, Math.max(bufferInfo.nextStart, config.maxBufferHole));
}
}
return bufferInfo;
};
_proto.getMaxBufferLength = function getMaxBufferLength(levelBitrate) {
var config = this.config;
var maxBufLen;
if (levelBitrate) {
maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
} else {
maxBufLen = config.maxBufferLength;
}
return Math.min(maxBufLen, config.maxMaxBufferLength);
};
_proto.reduceMaxBufferLength = function reduceMaxBufferLength(threshold) {
var config = this.config;
var minLength = threshold || config.maxBufferLength;
if (config.maxMaxBufferLength >= minLength) {
// reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
config.maxMaxBufferLength /= 2;
this.warn("Reduce max buffer length to " + config.maxMaxBufferLength + "s");
return true;
}
return false;
};
_proto.getNextFragment = function getNextFragment(pos, levelDetails) {
var _frag, _frag2;
var fragments = levelDetails.fragments;
var fragLen = fragments.length;
if (!fragLen) {
return null;
} // find fragment index, contiguous with end of buffer position
var config = this.config;
var start = fragments[0].start;
var frag;
if (levelDetails.live) {
var initialLiveManifestSize = config.initialLiveManifestSize;
if (fragLen < initialLiveManifestSize) {
this.warn("Not enough fragments to start playback (have: " + fragLen + ", need: " + initialLiveManifestSize + ")");
return null;
} // The real fragment start times for a live stream are only known after the PTS range for that level is known.
// In order to discover the range, we load the best matching fragment for that level and demux it.
// Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that
// we get the fragment matching that start time
if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1) {
frag = this.getInitialLiveFragment(levelDetails, fragments);
this.startPosition = frag ? this.hls.liveSyncPosition || frag.start : pos;
}
} else if (pos <= start) {
// VoD playlist: if loadPosition before start of playlist, load first fragment
frag = fragments[0];
} // If we haven't run into any special cases already, just load the fragment most closely matching the requested position
if (!frag) {
var end = config.lowLatencyMode ? levelDetails.partEnd : levelDetails.fragmentEnd;
frag = this.getFragmentAtPosition(pos, end, levelDetails);
} // If an initSegment is present, it must be buffered first
if ((_frag = frag) !== null && _frag !== void 0 && _frag.initSegment && !((_frag2 = frag) !== null && _frag2 !== void 0 && _frag2.initSegment.data) && !this.bitrateTest) {
frag = frag.initSegment;
}
return frag;
};
_proto.getNextPart = function getNextPart(partList, frag, targetBufferTime) {
var nextPart = -1;
var contiguous = false;
var independentAttrOmitted = true;
for (var i = 0, len = partList.length; i < len; i++) {
var part = partList[i];
independentAttrOmitted = independentAttrOmitted && !part.independent;
if (nextPart > -1 && targetBufferTime < part.start) {
break;
}
var loaded = part.loaded;
if (!loaded && (contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) {
nextPart = i;
}
contiguous = loaded;
}
return nextPart;
};
_proto.loadedEndOfParts = function loadedEndOfParts(partList, targetBufferTime) {
var lastPart = partList[partList.length - 1];
return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;
}
/*
This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the
"sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real
start and end times for each fragment in the playlist (after which this method will not need to be called).
*/
;
_proto.getInitialLiveFragment = function getInitialLiveFragment(levelDetails, fragments) {
var fragPrevious = this.fragPrevious;
var frag = null;
if (fragPrevious) {
if (levelDetails.hasProgramDateTime) {
// Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding
this.log("Live playlist, switching playlist, load frag with same PDT: " + fragPrevious.programDateTime);
frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_10__["findFragmentByPDT"])(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);
}
if (!frag) {
// SN does not need to be accurate between renditions, but depending on the packaging it may be so.
var targetSN = fragPrevious.sn + 1;
if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
var fragNext = fragments[targetSN - levelDetails.startSN]; // Ensure that we're staying within the continuity range, since PTS resets upon a new range
if (fragPrevious.cc === fragNext.cc) {
frag = fragNext;
this.log("Live playlist, switching playlist, load frag with next SN: " + frag.sn);
}
} // It's important to stay within the continuity range if available; otherwise the fragments in the playlist
// will have the wrong start times
if (!frag) {
frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_10__["findFragWithCC"])(fragments, fragPrevious.cc);
if (frag) {
this.log("Live playlist, switching playlist, load frag with same CC: " + frag.sn);
}
}
}
} else {
// Find a new start fragment when fragPrevious is null
var liveStart = this.hls.liveSyncPosition;
if (liveStart !== null) {
frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);
}
}
return frag;
}
/*
This method finds the best matching fragment given the provided position.
*/
;
_proto.getFragmentAtPosition = function getFragmentAtPosition(bufferEnd, end, levelDetails) {
var config = this.config,
fragPrevious = this.fragPrevious;
var fragments = levelDetails.fragments,
endSN = levelDetails.endSN;
var fragmentHint = levelDetails.fragmentHint;
var tolerance = config.maxFragLookUpTolerance;
var loadingParts = !!(config.lowLatencyMode && levelDetails.partList && fragmentHint);
if (loadingParts && fragmentHint && !this.bitrateTest) {
// Include incomplete fragment with parts at end
fragments = fragments.concat(fragmentHint);
endSN = fragmentHint.sn;
}
var frag;
if (bufferEnd < end) {
var lookupTolerance = bufferEnd > end - tolerance ? 0 : tolerance; // Remove the tolerance if it would put the bufferEnd past the actual end of stream
// Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_10__["findFragmentByPTS"])(fragPrevious, fragments, bufferEnd, lookupTolerance);
} else {
// reach end of playlist
frag = fragments[fragments.length - 1];
}
if (frag) {
var curSNIdx = frag.sn - levelDetails.startSN;
var sameLevel = fragPrevious && frag.level === fragPrevious.level;
var nextFrag = fragments[curSNIdx + 1];
var fragState = this.fragmentTracker.getState(frag);
if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].BACKTRACKED) {
frag = null;
var i = curSNIdx;
while (fragments[i] && this.fragmentTracker.getState(fragments[i]) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].BACKTRACKED) {
// When fragPrevious is null, backtrack to first the first fragment is not BACKTRACKED for loading
// When fragPrevious is set, we want the first BACKTRACKED fragment for parsing and buffering
if (!fragPrevious) {
frag = fragments[--i];
} else {
frag = fragments[i--];
}
}
if (!frag) {
frag = nextFrag;
}
} else if (fragPrevious && frag.sn === fragPrevious.sn && !loadingParts) {
// Force the next fragment to load if the previous one was already selected. This can occasionally happen with
// non-uniform fragment durations
if (sameLevel) {
if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].OK) {
this.log("SN " + frag.sn + " just loaded, load next one: " + nextFrag.sn);
frag = nextFrag;
} else {
frag = null;
}
}
}
}
return frag;
};
_proto.synchronizeToLiveEdge = function synchronizeToLiveEdge(levelDetails) {
var config = this.config,
media = this.media;
if (!media) {
return;
}
var liveSyncPosition = this.hls.liveSyncPosition;
var currentTime = media.currentTime;
var start = levelDetails.fragments[0].start;
var end = levelDetails.edge;
var withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end; // Continue if we can seek forward to sync position or if current time is outside of sliding window
if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) {
// Continue if buffer is starving or if current time is behind max latency
var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) {
if (!this.loadedmetadata) {
this.nextLoadPosition = liveSyncPosition;
} // Only seek if ready and there is not a significant forward buffer available for playback
if (media.readyState) {
this.warn("Playback: " + currentTime.toFixed(3) + " is located too far from the end of live sliding playlist: " + end + ", reset currentTime to : " + liveSyncPosition.toFixed(3));
media.currentTime = liveSyncPosition;
}
}
}
};
_proto.alignPlaylists = function alignPlaylists(details, previousDetails) {
var levels = this.levels,
levelLastLoaded = this.levelLastLoaded,
fragPrevious = this.fragPrevious;
var lastLevel = levelLastLoaded !== null ? levels[levelLastLoaded] : null; // FIXME: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc,
// this could all go in level-helper mergeDetails()
var length = details.fragments.length;
if (!length) {
this.warn("No fragments in live playlist");
return 0;
}
var slidingStart = details.fragments[0].start;
var firstLevelLoad = !previousDetails;
var aligned = details.alignedSliding && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(slidingStart);
if (firstLevelLoad || !aligned && !slidingStart) {
Object(_utils_discontinuities__WEBPACK_IMPORTED_MODULE_9__["alignStream"])(fragPrevious, lastLevel, details);
var alignedSlidingStart = details.fragments[0].start;
this.log("Live playlist sliding: " + alignedSlidingStart.toFixed(2) + " start-sn: " + (previousDetails ? previousDetails.startSN : 'na') + "->" + details.startSN + " prev-sn: " + (fragPrevious ? fragPrevious.sn : 'na') + " fragments: " + length);
return alignedSlidingStart;
}
return slidingStart;
};
_proto.waitForCdnTuneIn = function waitForCdnTuneIn(details) {
// Wait for Low-Latency CDN Tune-in to get an updated playlist
var advancePartLimit = 3;
return details.live && details.canBlockReload && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);
};
_proto.setStartPosition = function setStartPosition(details, sliding) {
// compute start position if set to -1. use it straight away if value is defined
var startPosition = this.startPosition;
if (startPosition < sliding) {
startPosition = -1;
}
if (startPosition === -1 || this.lastCurrentTime === -1) {
// first, check if start time offset has been set in playlist, if yes, use this value
var startTimeOffset = details.startTimeOffset;
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(startTimeOffset)) {
startPosition = sliding + startTimeOffset;
if (startTimeOffset < 0) {
startPosition += details.totalduration;
}
startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration);
this.log("Start time offset " + startTimeOffset + " found in playlist, adjust startPosition to " + startPosition);
this.startPosition = startPosition;
} else if (details.live) {
// Leave this.startPosition at -1, so that we can use `getInitialLiveFragment` logic when startPosition has
// not been specified via the config or an as an argument to startLoad (#3736).
startPosition = this.hls.liveSyncPosition || sliding;
} else {
this.startPosition = startPosition = 0;
}
this.lastCurrentTime = startPosition;
}
this.nextLoadPosition = startPosition;
};
_proto.getLoadPosition = function getLoadPosition() {
var media = this.media; // if we have not yet loaded any fragment, start loading from start position
var pos = 0;
if (this.loadedmetadata && media) {
pos = media.currentTime;
} else if (this.nextLoadPosition) {
pos = this.nextLoadPosition;
}
return pos;
};
_proto.handleFragLoadAborted = function handleFragLoadAborted(frag, part) {
if (this.transmuxer && frag.sn !== 'initSegment' && frag.stats.aborted) {
this.warn("Fragment " + frag.sn + (part ? ' part' + part.index : '') + " of level " + frag.level + " was aborted");
this.resetFragmentLoading(frag);
}
};
_proto.resetFragmentLoading = function resetFragmentLoading(frag) {
if (!this.fragCurrent || !this.fragContextChanged(frag)) {
this.state = State.IDLE;
}
};
_proto.onFragmentOrKeyLoadError = function onFragmentOrKeyLoadError(filterType, data) {
if (data.fatal) {
return;
}
var frag = data.frag; // Handle frag error related to caller's filterType
if (!frag || frag.type !== filterType) {
return;
}
var fragCurrent = this.fragCurrent;
console.assert(fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level && frag.urlId === fragCurrent.urlId, 'Frag load error must match current frag to retry');
var config = this.config; // keep retrying until the limit will be reached
if (this.fragLoadError + 1 <= config.fragLoadingMaxRetry) {
if (this.resetLiveStartWhenNotLoaded(frag.level)) {
return;
} // exponential backoff capped to config.fragLoadingMaxRetryTimeout
var delay = Math.min(Math.pow(2, this.fragLoadError) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout);
this.warn("Fragment " + frag.sn + " of " + filterType + " " + frag.level + " failed to load, retrying in " + delay + "ms");
this.retryDate = self.performance.now() + delay;
this.fragLoadError++;
this.state = State.FRAG_LOADING_WAITING_RETRY;
} else if (data.levelRetry) {
if (filterType === _types_loader__WEBPACK_IMPORTED_MODULE_15__["PlaylistLevelType"].AUDIO) {
// Reset current fragment since audio track audio is essential and may not have a fail-over track
this.fragCurrent = null;
} // Fragment errors that result in a level switch or redundant fail-over
// should reset the stream controller state to idle
this.fragLoadError = 0;
this.state = State.IDLE;
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"].error(data.details + " reaches max retry, redispatch as fatal ..."); // switch error to fatal
data.fatal = true;
this.hls.stopLoad();
this.state = State.ERROR;
}
};
_proto.afterBufferFlushed = function afterBufferFlushed(media, bufferType, playlistType) {
if (!media) {
return;
} // 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 bufferedTimeRanges = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].getBuffered(media);
this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType);
if (this.state === State.ENDED) {
this.resetLoadingState();
}
};
_proto.resetLoadingState = function resetLoadingState() {
this.fragCurrent = null;
this.fragPrevious = null;
this.state = State.IDLE;
};
_proto.resetLiveStartWhenNotLoaded = function resetLiveStartWhenNotLoaded(level) {
// 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;
var details = this.levels ? this.levels[level].details : null;
if (details !== null && details !== void 0 && details.live) {
// We can't afford to retry after a delay in a live scenario. Update the start position and return to IDLE.
this.startPosition = -1;
this.setStartPosition(details, 0);
this.resetLoadingState();
return true;
}
this.nextLoadPosition = this.startPosition;
}
return false;
};
_proto.updateLevelTiming = function updateLevelTiming(frag, part, level, partial) {
var _this6 = this;
var details = level.details;
console.assert(!!details, 'level.details must be defined');
var parsed = Object.keys(frag.elementaryStreams).reduce(function (result, type) {
var info = frag.elementaryStreams[type];
if (info) {
var parsedDuration = info.endPTS - info.startPTS;
if (parsedDuration <= 0) {
// Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0.
// The new transmuxer will be configured with a time offset matching the next fragment start,
// preventing the timeline from shifting.
_this6.warn("Could not parse fragment " + frag.sn + " " + type + " duration reliably (" + parsedDuration + ") resetting transmuxer to fallback to playlist timing");
_this6.resetTransmuxer();
return result || false;
}
var drift = partial ? 0 : Object(_level_helper__WEBPACK_IMPORTED_MODULE_11__["updateFragPTSDTS"])(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS);
_this6.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].LEVEL_PTS_UPDATED, {
details: details,
level: level,
drift: drift,
type: type,
frag: frag,
start: info.startPTS,
end: info.endPTS
});
return true;
}
return result;
}, false);
if (parsed) {
this.state = State.PARSED;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_PARSED, {
frag: frag,
part: part
});
} else {
this.resetLoadingState();
}
};
_proto.resetTransmuxer = function resetTransmuxer() {
if (this.transmuxer) {
this.transmuxer.destroy();
this.transmuxer = null;
}
};
_createClass(BaseStreamController, [{
key: "state",
get: function get() {
return this._state;
},
set: function set(nextState) {
var previousState = this._state;
if (previousState !== nextState) {
this._state = nextState;
this.log(previousState + "->" + nextState);
}
}
}]);
return BaseStreamController;
}(_task_loop__WEBPACK_IMPORTED_MODULE_1__["default"]);
/***/ }),
/***/ "./src/controller/buffer-controller.ts":
/*!*********************************************!*\
!*** ./src/controller/buffer-controller.ts ***!
\*********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BufferController; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/mediasource-helper */ "./src/utils/mediasource-helper.ts");
/* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
/* harmony import */ var _buffer_operation_queue__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./buffer-operation-queue */ "./src/controller/buffer-operation-queue.ts");
var MediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__["getMediaSource"])();
var VIDEO_CODEC_PROFILE_REPACE = /([ha]vc.)(?:\.[^.,]+)+/;
var BufferController = /*#__PURE__*/function () {
// The level details used to determine duration, target-duration and live
// cache the self generated object url to detect hijack of video tag
// A queue of buffer operations which require the SourceBuffer to not be updating upon execution
// References to event listeners for each SourceBuffer, so that they can be referenced for event removal
// The number of BUFFER_CODEC events received before any sourceBuffers are created
// The total number of BUFFER_CODEC events received
// A reference to the attached media element
// A reference to the active media source
// counters
function BufferController(_hls) {
var _this = this;
this.details = null;
this._objectUrl = null;
this.operationQueue = void 0;
this.listeners = void 0;
this.hls = void 0;
this.bufferCodecEventsExpected = 0;
this._bufferCodecEventsTotal = 0;
this.media = null;
this.mediaSource = null;
this.appendError = 0;
this.tracks = {};
this.pendingTracks = {};
this.sourceBuffer = void 0;
this._onMediaSourceOpen = function () {
var hls = _this.hls,
media = _this.media,
mediaSource = _this.mediaSource;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media source opened');
if (media) {
_this.updateMediaElementDuration();
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHED, {
media: media
});
}
if (mediaSource) {
// once received, don't listen anymore to sourceopen event
mediaSource.removeEventListener('sourceopen', _this._onMediaSourceOpen);
}
_this.checkPendingTracks();
};
this._onMediaSourceClose = function () {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media source closed');
};
this._onMediaSourceEnded = function () {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media source ended');
};
this.hls = _hls;
this._initSourceBuffer();
this.registerListeners();
}
var _proto = BufferController.prototype;
_proto.hasSourceTypes = function hasSourceTypes() {
return this.getSourceBufferTypes().length > 0 || Object.keys(this.pendingTracks).length > 0;
};
_proto.destroy = function destroy() {
this.unregisterListeners();
this.details = null;
};
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_RESET, this.onBufferReset, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_APPENDING, this.onBufferAppending, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_CODECS, this.onBufferCodecs, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_EOS, this.onBufferEos, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSED, this.onFragParsed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_CHANGED, this.onFragChanged, this);
};
_proto.unregisterListeners = function unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_RESET, this.onBufferReset, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_APPENDING, this.onBufferAppending, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_CODECS, this.onBufferCodecs, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_EOS, this.onBufferEos, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSED, this.onFragParsed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_CHANGED, this.onFragChanged, this);
};
_proto._initSourceBuffer = function _initSourceBuffer() {
this.sourceBuffer = {};
this.operationQueue = new _buffer_operation_queue__WEBPACK_IMPORTED_MODULE_7__["default"](this.sourceBuffer);
this.listeners = {
audio: [],
video: [],
audiovideo: []
};
};
_proto.onManifestParsed = function onManifestParsed(event, data) {
// 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
var codecEvents = 2;
if (data.audio && !data.video || !data.altAudio) {
codecEvents = 1;
}
this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents;
this.details = null;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log(this.bufferCodecEventsExpected + " bufferCodec event(s) expected");
};
_proto.onMediaAttaching = function onMediaAttaching(event, data) {
var media = this.media = data.media;
if (media && MediaSource) {
var ms = this.mediaSource = new MediaSource(); // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound
ms.addEventListener('sourceopen', this._onMediaSourceOpen);
ms.addEventListener('sourceended', this._onMediaSourceEnded);
ms.addEventListener('sourceclose', this._onMediaSourceClose); // link video and media Source
media.src = self.URL.createObjectURL(ms); // cache the locally generated object url
this._objectUrl = media.src;
}
};
_proto.onMediaDetaching = function onMediaDetaching() {
var media = this.media,
mediaSource = this.mediaSource,
_objectUrl = this._objectUrl;
if (mediaSource) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: media source detaching');
if (mediaSource.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
mediaSource.endOfStream();
} catch (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: onMediaDetaching: " + err.message + " while calling endOfStream");
}
} // Clean up the SourceBuffers by invoking onBufferReset
this.onBufferReset();
mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);
mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded);
mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose); // Detach properly the MediaSource from the HTMLMediaElement as
// suggested in https://github.com/w3c/media-source/issues/53.
if (media) {
if (_objectUrl) {
self.URL.revokeObjectURL(_objectUrl);
} // clean up video tag src only if it's our own url. some external libraries might
// hijack the video tag and change its 'src' without destroying the Hls instance first
if (media.src === _objectUrl) {
media.removeAttribute('src');
media.load();
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('[buffer-controller]: media.src was changed by a third party - skip cleanup');
}
}
this.mediaSource = null;
this.media = null;
this._objectUrl = null;
this.bufferCodecEventsExpected = this._bufferCodecEventsTotal;
this.pendingTracks = {};
this.tracks = {};
}
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHED, undefined);
};
_proto.onBufferReset = function onBufferReset() {
var _this2 = this;
this.getSourceBufferTypes().forEach(function (type) {
var sb = _this2.sourceBuffer[type];
try {
if (sb) {
_this2.removeBufferListeners(type);
if (_this2.mediaSource) {
_this2.mediaSource.removeSourceBuffer(sb);
} // Synchronously remove the SB from the map before the next call in order to prevent an async function from
// accessing it
_this2.sourceBuffer[type] = undefined;
}
} catch (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Failed to reset the " + type + " buffer", err);
}
});
this._initSourceBuffer();
};
_proto.onBufferCodecs = function onBufferCodecs(event, data) {
var _this3 = this;
var sourceBufferCount = this.getSourceBufferTypes().length;
Object.keys(data).forEach(function (trackName) {
if (sourceBufferCount) {
// check if SourceBuffer codec needs to change
var track = _this3.tracks[trackName];
if (track && typeof track.buffer.changeType === 'function') {
var _data$trackName = data[trackName],
codec = _data$trackName.codec,
levelCodec = _data$trackName.levelCodec,
container = _data$trackName.container;
var currentCodec = (track.levelCodec || track.codec).replace(VIDEO_CODEC_PROFILE_REPACE, '$1');
var nextCodec = (levelCodec || codec).replace(VIDEO_CODEC_PROFILE_REPACE, '$1');
if (currentCodec !== nextCodec) {
var mimeType = container + ";codecs=" + (levelCodec || codec);
_this3.appendChangeType(trackName, mimeType);
}
}
} else {
// if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks
_this3.pendingTracks[trackName] = data[trackName];
}
}); // if sourcebuffers already created, do nothing ...
if (sourceBufferCount) {
return;
}
this.bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);
if (this.mediaSource && this.mediaSource.readyState === 'open') {
this.checkPendingTracks();
}
};
_proto.appendChangeType = function appendChangeType(type, mimeType) {
var _this4 = this;
var operationQueue = this.operationQueue;
var operation = {
execute: function execute() {
var sb = _this4.sourceBuffer[type];
if (sb) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: changing " + type + " sourceBuffer type to " + mimeType);
sb.changeType(mimeType);
}
operationQueue.shiftAndExecuteNext(type);
},
onStart: function onStart() {},
onComplete: function onComplete() {},
onError: function onError(e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Failed to change " + type + " SourceBuffer type", e);
}
};
operationQueue.append(operation, type);
};
_proto.onBufferAppending = function onBufferAppending(event, eventData) {
var _this5 = this;
var hls = this.hls,
operationQueue = this.operationQueue,
tracks = this.tracks;
var data = eventData.data,
type = eventData.type,
frag = eventData.frag,
part = eventData.part,
chunkMeta = eventData.chunkMeta;
var chunkStats = chunkMeta.buffering[type];
var bufferAppendingStart = self.performance.now();
chunkStats.start = bufferAppendingStart;
var fragBuffering = frag.stats.buffering;
var partBuffering = part ? part.stats.buffering : null;
if (fragBuffering.start === 0) {
fragBuffering.start = bufferAppendingStart;
}
if (partBuffering && partBuffering.start === 0) {
partBuffering.start = bufferAppendingStart;
} // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended
// 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).
// More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
var audioTrack = tracks.audio;
var checkTimestampOffset = type === 'audio' && chunkMeta.id === 1 && (audioTrack === null || audioTrack === void 0 ? void 0 : audioTrack.container) === 'audio/mpeg';
var operation = {
execute: function execute() {
chunkStats.executeStart = self.performance.now();
if (checkTimestampOffset) {
var sb = _this5.sourceBuffer[type];
if (sb) {
var delta = frag.start - sb.timestampOffset;
if (Math.abs(delta) >= 0.1) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: Updating audio SourceBuffer timestampOffset to " + frag.start + " (delta: " + delta + ") sn: " + frag.sn + ")");
sb.timestampOffset = frag.start;
}
}
}
_this5.appendExecutor(data, type);
},
onStart: function onStart() {// logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`);
},
onComplete: function onComplete() {
// logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`);
var end = self.performance.now();
chunkStats.executeEnd = chunkStats.end = end;
if (fragBuffering.first === 0) {
fragBuffering.first = end;
}
if (partBuffering && partBuffering.first === 0) {
partBuffering.first = end;
}
var sourceBuffer = _this5.sourceBuffer;
var timeRanges = {};
for (var _type in sourceBuffer) {
timeRanges[_type] = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(sourceBuffer[_type]);
}
_this5.appendError = 0;
_this5.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_APPENDED, {
type: type,
frag: frag,
part: part,
chunkMeta: chunkMeta,
parent: frag.type,
timeRanges: timeRanges
});
},
onError: function onError(err) {
// in case any error occured while appending, put back segment in segments table
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: Error encountered while trying to append to the " + type + " SourceBuffer", err);
var event = {
type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR,
parent: frag.type,
details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_APPEND_ERROR,
err: err,
fatal: false
};
if (err.code === DOMException.QUOTA_EXCEEDED_ERR) {
// QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
// let's stop appending any segments, and report BUFFER_FULL_ERROR error
event.details = _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_FULL_ERROR;
} else {
_this5.appendError++;
event.details = _errors__WEBPACK_IMPORTED_MODULE_3__["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 can help recover.
*/
if (_this5.appendError > hls.config.appendErrorMaxRetry) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: Failed " + hls.config.appendErrorMaxRetry + " times to append segment in sourceBuffer");
event.fatal = true;
}
}
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, event);
}
};
operationQueue.append(operation, type);
};
_proto.onBufferFlushing = function onBufferFlushing(event, data) {
var _this6 = this;
var operationQueue = this.operationQueue;
var flushOperation = function flushOperation(type) {
return {
execute: _this6.removeExecutor.bind(_this6, type, data.startOffset, data.endOffset),
onStart: function onStart() {// logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
},
onComplete: function onComplete() {
// logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
_this6.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHED, {
type: type
});
},
onError: function onError(e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Failed to remove from " + type + " SourceBuffer", e);
}
};
};
if (data.type) {
operationQueue.append(flushOperation(data.type), data.type);
} else {
this.getSourceBufferTypes().forEach(function (type) {
operationQueue.append(flushOperation(type), type);
});
}
};
_proto.onFragParsed = function onFragParsed(event, data) {
var _this7 = this;
var frag = data.frag,
part = data.part;
var buffersAppendedTo = [];
var elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;
if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__["ElementaryStreamTypes"].AUDIOVIDEO]) {
buffersAppendedTo.push('audiovideo');
} else {
if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__["ElementaryStreamTypes"].AUDIO]) {
buffersAppendedTo.push('audio');
}
if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__["ElementaryStreamTypes"].VIDEO]) {
buffersAppendedTo.push('video');
}
}
var onUnblocked = function onUnblocked() {
var now = self.performance.now();
frag.stats.buffering.end = now;
if (part) {
part.stats.buffering.end = now;
}
var stats = part ? part.stats : frag.stats;
_this7.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_BUFFERED, {
frag: frag,
part: part,
stats: stats,
id: frag.type
});
};
if (buffersAppendedTo.length === 0) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("Fragments must have at least one ElementaryStreamType set. type: " + frag.type + " level: " + frag.level + " sn: " + frag.sn);
}
this.blockBuffers(onUnblocked, buffersAppendedTo);
};
_proto.onFragChanged = function onFragChanged(event, data) {
this.flushBackBuffer();
} // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()
// an undefined data.type will mark all buffers as EOS.
;
_proto.onBufferEos = function onBufferEos(event, data) {
var _this8 = this;
var ended = this.getSourceBufferTypes().reduce(function (acc, type) {
var sb = _this8.sourceBuffer[type];
if (!data.type || data.type === type) {
if (sb && !sb.ended) {
sb.ended = true;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: " + type + " sourceBuffer now EOS");
}
}
return acc && !!(!sb || sb.ended);
}, true);
if (ended) {
this.blockBuffers(function () {
var mediaSource = _this8.mediaSource;
if (!mediaSource || mediaSource.readyState !== 'open') {
return;
} // Allow this to throw and be caught by the enqueueing function
mediaSource.endOfStream();
});
}
};
_proto.onLevelUpdated = function onLevelUpdated(event, _ref) {
var details = _ref.details;
if (!details.fragments.length) {
return;
}
this.details = details;
if (this.getSourceBufferTypes().length) {
this.blockBuffers(this.updateMediaElementDuration.bind(this));
} else {
this.updateMediaElementDuration();
}
};
_proto.flushBackBuffer = function flushBackBuffer() {
var hls = this.hls,
details = this.details,
media = this.media,
sourceBuffer = this.sourceBuffer;
if (!media || details === null) {
return;
}
var sourceBufferTypes = this.getSourceBufferTypes();
if (!sourceBufferTypes.length) {
return;
} // Support for deprecated liveBackBufferLength
var backBufferLength = details.live && hls.config.liveBackBufferLength !== null ? hls.config.liveBackBufferLength : hls.config.backBufferLength;
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(backBufferLength) || backBufferLength < 0) {
return;
}
var currentTime = media.currentTime;
var targetDuration = details.levelTargetDuration;
var maxBackBufferLength = Math.max(backBufferLength, targetDuration);
var targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;
sourceBufferTypes.forEach(function (type) {
var sb = sourceBuffer[type];
if (sb) {
var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(sb); // when target buffer start exceeds actual buffer start
if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BACK_BUFFER_REACHED, {
bufferEnd: targetBackBufferPosition
}); // Support for deprecated event:
if (details.live) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LIVE_BACK_BUFFER_REACHED, {
bufferEnd: targetBackBufferPosition
});
}
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, {
startOffset: 0,
endOffset: targetBackBufferPosition,
type: type
});
}
}
});
}
/**
* Update Media Source duration to current level duration or override to Infinity if configuration parameter
* 'liveDurationInfinity` is set to `true`
* More details: https://github.com/video-dev/hls.js/issues/355
*/
;
_proto.updateMediaElementDuration = function updateMediaElementDuration() {
if (!this.details || !this.media || !this.mediaSource || this.mediaSource.readyState !== 'open') {
return;
}
var details = this.details,
hls = this.hls,
media = this.media,
mediaSource = this.mediaSource;
var levelDuration = details.fragments[0].start + details.totalduration;
var mediaDuration = media.duration;
var msDuration = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mediaSource.duration) ? mediaSource.duration : 0;
if (details.live && hls.config.liveDurationInfinity) {
// Override duration to Infinity
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media Source duration is set to Infinity');
mediaSource.duration = Infinity;
this.updateSeekableRange(details);
} else if (levelDuration > msDuration && levelDuration > mediaDuration || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mediaDuration)) {
// levelDuration was the last value we set.
// not using mediaSource.duration as the browser may tweak this value
// only update Media Source duration if its value increase, this is to avoid
// flushing already buffered portion when switching between quality level
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: Updating Media Source duration to " + levelDuration.toFixed(3));
mediaSource.duration = levelDuration;
}
};
_proto.updateSeekableRange = function updateSeekableRange(levelDetails) {
var mediaSource = this.mediaSource;
var fragments = levelDetails.fragments;
var len = fragments.length;
if (len && levelDetails.live && mediaSource !== null && mediaSource !== void 0 && mediaSource.setLiveSeekableRange) {
var start = Math.max(0, fragments[0].start);
var end = Math.max(start, start + levelDetails.totalduration);
mediaSource.setLiveSeekableRange(start, end);
}
};
_proto.checkPendingTracks = function checkPendingTracks() {
var bufferCodecEventsExpected = this.bufferCodecEventsExpected,
operationQueue = this.operationQueue,
pendingTracks = this.pendingTracks; // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.
// This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after
// data has been appended to existing ones.
// 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.
var pendingTracksCount = Object.keys(pendingTracks).length;
if (pendingTracksCount && !bufferCodecEventsExpected || pendingTracksCount === 2) {
// ok, let's create them now !
this.createSourceBuffers(pendingTracks);
this.pendingTracks = {}; // append any pending segments now !
var buffers = this.getSourceBufferTypes();
if (buffers.length === 0) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_INCOMPATIBLE_CODECS_ERROR,
fatal: true,
reason: 'could not create source buffer for media codec(s)'
});
return;
}
buffers.forEach(function (type) {
operationQueue.executeNext(type);
});
}
};
_proto.createSourceBuffers = function createSourceBuffers(tracks) {
var sourceBuffer = this.sourceBuffer,
mediaSource = this.mediaSource;
if (!mediaSource) {
throw Error('createSourceBuffers called when mediaSource was null');
}
var tracksCreated = 0;
for (var trackName in tracks) {
if (!sourceBuffer[trackName]) {
var track = tracks[trackName];
if (!track) {
throw Error("source buffer exists for track " + trackName + ", however track does not");
} // use levelCodec as first priority
var codec = track.levelCodec || track.codec;
var mimeType = track.container + ";codecs=" + codec;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: creating sourceBuffer(" + mimeType + ")");
try {
var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
var sbName = trackName;
this.addBufferListener(sbName, 'updatestart', this._onSBUpdateStart);
this.addBufferListener(sbName, 'updateend', this._onSBUpdateEnd);
this.addBufferListener(sbName, 'error', this._onSBUpdateError);
this.tracks[trackName] = {
buffer: sb,
codec: codec,
container: track.container,
levelCodec: track.levelCodec,
id: track.id
};
tracksCreated++;
} catch (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: error while trying to add sourceBuffer: " + err.message);
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_ADD_CODEC_ERROR,
fatal: false,
error: err,
mimeType: mimeType
});
}
}
}
if (tracksCreated) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_CREATED, {
tracks: this.tracks
});
}
} // Keep as arrow functions so that we can directly reference these functions directly as event listeners
;
_proto._onSBUpdateStart = function _onSBUpdateStart(type) {
var operationQueue = this.operationQueue;
var operation = operationQueue.current(type);
operation.onStart();
};
_proto._onSBUpdateEnd = function _onSBUpdateEnd(type) {
var operationQueue = this.operationQueue;
var operation = operationQueue.current(type);
operation.onComplete();
operationQueue.shiftAndExecuteNext(type);
};
_proto._onSBUpdateError = function _onSBUpdateError(type, event) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: " + type + " SourceBuffer error", event); // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
// SourceBuffer errors are not necessarily fatal; if so, the HTMLMediaElement will fire an error event
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_APPENDING_ERROR,
fatal: false
}); // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue
var operation = this.operationQueue.current(type);
if (operation) {
operation.onError(event);
}
} // This method must result in an updateend event; if remove is not called, _onSBUpdateEnd must be called manually
;
_proto.removeExecutor = function removeExecutor(type, startOffset, endOffset) {
var media = this.media,
mediaSource = this.mediaSource,
operationQueue = this.operationQueue,
sourceBuffer = this.sourceBuffer;
var sb = sourceBuffer[type];
if (!media || !mediaSource || !sb) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Attempting to remove from the " + type + " SourceBuffer, but it does not exist");
operationQueue.shiftAndExecuteNext(type);
return;
}
var mediaDuration = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(media.duration) ? media.duration : Infinity;
var msDuration = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mediaSource.duration) ? mediaSource.duration : Infinity;
var removeStart = Math.max(0, startOffset);
var removeEnd = Math.min(endOffset, mediaDuration, msDuration);
if (removeEnd > removeStart) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: Removing [" + removeStart + "," + removeEnd + "] from the " + type + " SourceBuffer");
console.assert(!sb.updating, type + " sourceBuffer must not be updating");
sb.remove(removeStart, removeEnd);
} else {
// Cycle the queue
operationQueue.shiftAndExecuteNext(type);
}
} // This method must result in an updateend event; if append is not called, _onSBUpdateEnd must be called manually
;
_proto.appendExecutor = function appendExecutor(data, type) {
var operationQueue = this.operationQueue,
sourceBuffer = this.sourceBuffer;
var sb = sourceBuffer[type];
if (!sb) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Attempting to append to the " + type + " SourceBuffer, but it does not exist");
operationQueue.shiftAndExecuteNext(type);
return;
}
sb.ended = false;
console.assert(!sb.updating, type + " sourceBuffer must not be updating");
sb.appendBuffer(data);
} // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises
// resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue
// upon completion, since we already do it here
;
_proto.blockBuffers = function blockBuffers(onUnblocked, buffers) {
var _this9 = this;
if (buffers === void 0) {
buffers = this.getSourceBufferTypes();
}
if (!buffers.length) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Blocking operation requested, but no SourceBuffers exist');
Promise.resolve(onUnblocked);
return;
}
var operationQueue = this.operationQueue; // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`);
var blockingOperations = buffers.map(function (type) {
return operationQueue.appendBlocker(type);
});
Promise.all(blockingOperations).then(function () {
// logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`);
onUnblocked();
buffers.forEach(function (type) {
var sb = _this9.sourceBuffer[type]; // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to
// true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration)
// While this is a workaround, it's probably useful to have around
if (!sb || !sb.updating) {
operationQueue.shiftAndExecuteNext(type);
}
});
});
};
_proto.getSourceBufferTypes = function getSourceBufferTypes() {
return Object.keys(this.sourceBuffer);
};
_proto.addBufferListener = function addBufferListener(type, event, fn) {
var buffer = this.sourceBuffer[type];
if (!buffer) {
return;
}
var listener = fn.bind(this, type);
this.listeners[type].push({
event: event,
listener: listener
});
buffer.addEventListener(event, listener);
};
_proto.removeBufferListeners = function removeBufferListeners(type) {
var buffer = this.sourceBuffer[type];
if (!buffer) {
return;
}
this.listeners[type].forEach(function (l) {
buffer.removeEventListener(l.event, l.listener);
});
};
return BufferController;
}();
/***/ }),
/***/ "./src/controller/buffer-operation-queue.ts":
/*!**************************************************!*\
!*** ./src/controller/buffer-operation-queue.ts ***!
\**************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BufferOperationQueue; });
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var BufferOperationQueue = /*#__PURE__*/function () {
function BufferOperationQueue(sourceBufferReference) {
this.buffers = void 0;
this.queues = {
video: [],
audio: [],
audiovideo: []
};
this.buffers = sourceBufferReference;
}
var _proto = BufferOperationQueue.prototype;
_proto.append = function append(operation, type) {
var queue = this.queues[type];
queue.push(operation);
if (queue.length === 1 && this.buffers[type]) {
this.executeNext(type);
}
};
_proto.insertAbort = function insertAbort(operation, type) {
var queue = this.queues[type];
queue.unshift(operation);
this.executeNext(type);
};
_proto.appendBlocker = function appendBlocker(type) {
var execute;
var promise = new Promise(function (resolve) {
execute = resolve;
});
var operation = {
execute: execute,
onStart: function onStart() {},
onComplete: function onComplete() {},
onError: function onError() {}
};
this.append(operation, type);
return promise;
};
_proto.executeNext = function executeNext(type) {
var buffers = this.buffers,
queues = this.queues;
var sb = buffers[type];
var queue = queues[type];
if (queue.length) {
var operation = queue[0];
try {
// Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations
// which do not end with this event must call _onSBUpdateEnd manually
operation.execute();
} catch (e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].warn('[buffer-operation-queue]: Unhandled exception executing the current operation');
operation.onError(e); // Only shift the current operation off, otherwise the updateend handler will do this for us
if (!sb || !sb.updating) {
queue.shift();
this.executeNext(type);
}
}
}
};
_proto.shiftAndExecuteNext = function shiftAndExecuteNext(type) {
this.queues[type].shift();
this.executeNext(type);
};
_proto.current = function current(type) {
return this.queues[type][0];
};
return BufferOperationQueue;
}();
/***/ }),
/***/ "./src/controller/cap-level-controller.ts":
/*!************************************************!*\
!*** ./src/controller/cap-level-controller.ts ***!
\************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
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); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
/*
* cap stream level to media size dimension controller
*/
var CapLevelController = /*#__PURE__*/function () {
function CapLevelController(hls) {
this.autoLevelCapping = void 0;
this.firstLevel = void 0;
this.media = void 0;
this.restrictedLevels = void 0;
this.timer = void 0;
this.hls = void 0;
this.streamController = void 0;
this.clientRect = void 0;
this.hls = hls;
this.autoLevelCapping = Number.POSITIVE_INFINITY;
this.firstLevel = -1;
this.media = null;
this.restrictedLevels = [];
this.timer = undefined;
this.clientRect = null;
this.registerListeners();
}
var _proto = CapLevelController.prototype;
_proto.setStreamController = function setStreamController(streamController) {
this.streamController = streamController;
};
_proto.destroy = function destroy() {
this.unregisterListener();
if (this.hls.config.capLevelToPlayerSize) {
this.stopCapping();
}
this.media = null;
this.clientRect = null; // @ts-ignore
this.hls = this.streamController = null;
};
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_CODECS, this.onBufferCodecs, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
};
_proto.unregisterListener = function unregisterListener() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_CODECS, this.onBufferCodecs, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
};
_proto.onFpsDropLevelCapping = function onFpsDropLevelCapping(event, data) {
// Don't add a restricted level more than once
if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) {
this.restrictedLevels.push(data.droppedLevel);
}
};
_proto.onMediaAttaching = function onMediaAttaching(event, data) {
this.media = data.media instanceof HTMLVideoElement ? data.media : null;
};
_proto.onManifestParsed = function onManifestParsed(event, data) {
var hls = this.hls;
this.restrictedLevels = [];
this.firstLevel = data.firstLevel;
if (hls.config.capLevelToPlayerSize && data.video) {
// Start capping immediately if the manifest has signaled video codecs
this.startCapping();
}
} // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
// to the first level
;
_proto.onBufferCodecs = function onBufferCodecs(event, data) {
var hls = this.hls;
if (hls.config.capLevelToPlayerSize && data.video) {
// If the manifest did not signal a video codec capping has been deferred until we're certain video is present
this.startCapping();
}
};
_proto.onMediaDetaching = function onMediaDetaching() {
this.stopCapping();
};
_proto.detectPlayerSize = function detectPlayerSize() {
if (this.media && this.mediaHeight > 0 && this.mediaWidth > 0) {
var levels = this.hls.levels;
if (levels.length) {
var hls = this.hls;
hls.autoLevelCapping = this.getMaxLevel(levels.length - 1);
if (hls.autoLevelCapping > this.autoLevelCapping && this.streamController) {
// 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.
this.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)
*/
;
_proto.getMaxLevel = function getMaxLevel(capLevelIndex) {
var _this = this;
var levels = this.hls.levels;
if (!levels.length) {
return -1;
}
var validLevels = levels.filter(function (level, index) {
return CapLevelController.isLevelAllowed(index, _this.restrictedLevels) && index <= capLevelIndex;
});
this.clientRect = null;
return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
};
_proto.startCapping = function startCapping() {
if (this.timer) {
// Don't reset capping if started twice; this can happen if the manifest signals a video codec
return;
}
this.autoLevelCapping = Number.POSITIVE_INFINITY;
this.hls.firstLevel = this.getMaxLevel(this.firstLevel);
self.clearInterval(this.timer);
this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000);
this.detectPlayerSize();
};
_proto.stopCapping = function stopCapping() {
this.restrictedLevels = [];
this.firstLevel = -1;
this.autoLevelCapping = Number.POSITIVE_INFINITY;
if (this.timer) {
self.clearInterval(this.timer);
this.timer = undefined;
}
};
_proto.getDimensions = function getDimensions() {
if (this.clientRect) {
return this.clientRect;
}
var media = this.media;
var boundsRect = {
width: 0,
height: 0
};
if (media) {
var clientRect = media.getBoundingClientRect();
boundsRect.width = clientRect.width;
boundsRect.height = clientRect.height;
if (!boundsRect.width && !boundsRect.height) {
// When the media element has no width or height (equivalent to not being in the DOM),
// then use its width and height attributes (media.width, media.height)
boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
}
}
this.clientRect = boundsRect;
return boundsRect;
};
CapLevelController.isLevelAllowed = function isLevelAllowed(level, restrictedLevels) {
if (restrictedLevels === void 0) {
restrictedLevels = [];
}
return restrictedLevels.indexOf(level) === -1;
};
CapLevelController.getMaxLevelByMediaSize = function getMaxLevelByMediaSize(levels, width, height) {
if (!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;
};
_createClass(CapLevelController, [{
key: "mediaWidth",
get: function get() {
return this.getDimensions().width * CapLevelController.contentScaleFactor;
}
}, {
key: "mediaHeight",
get: function get() {
return this.getDimensions().height * CapLevelController.contentScaleFactor;
}
}], [{
key: "contentScaleFactor",
get: function get() {
var pixelRatio = 1;
try {
pixelRatio = self.devicePixelRatio;
} catch (e) {
/* no-op */
}
return pixelRatio;
}
}]);
return CapLevelController;
}();
/* harmony default export */ __webpack_exports__["default"] = (CapLevelController);
/***/ }),
/***/ "./src/controller/cmcd-controller.ts":
/*!*******************************************!*\
!*** ./src/controller/cmcd-controller.ts ***!
\*******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CMCDController; });
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _types_cmcd__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/cmcd */ "./src/types/cmcd.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
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); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
/**
* Controller to deal with Common Media Client Data (CMCD)
* @see https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf
*/
var CMCDController = /*#__PURE__*/function () {
// eslint-disable-line no-restricted-globals
// eslint-disable-line no-restricted-globals
function CMCDController(hls) {
var _this = this;
this.hls = void 0;
this.config = void 0;
this.media = void 0;
this.sid = void 0;
this.cid = void 0;
this.useHeaders = false;
this.initialized = false;
this.starved = false;
this.buffering = true;
this.audioBuffer = void 0;
this.videoBuffer = void 0;
this.onWaiting = function () {
if (_this.initialized) {
_this.starved = true;
}
_this.buffering = true;
};
this.onPlaying = function () {
if (!_this.initialized) {
_this.initialized = true;
}
_this.buffering = false;
};
this.applyPlaylistData = function (context) {
try {
_this.apply(context, {
ot: _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].MANIFEST,
su: !_this.initialized
});
} catch (error) {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Could not generate manifest CMCD data.', error);
}
};
this.applyFragmentData = function (context) {
try {
var fragment = context.frag;
var level = _this.hls.levels[fragment.level];
var ot = _this.getObjectType(fragment);
var data = {
d: fragment.duration * 1000,
ot: ot
};
if (ot === _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].VIDEO || ot === _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].AUDIO || ot == _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].MUXED) {
data.br = level.bitrate / 1000;
data.tb = _this.getTopBandwidth(ot);
data.bl = _this.getBufferLength(ot);
}
_this.apply(context, data);
} catch (error) {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Could not generate segment CMCD data.', error);
}
};
this.hls = hls;
var config = this.config = hls.config;
var cmcd = config.cmcd;
if (cmcd != null) {
config.pLoader = this.createPlaylistLoader();
config.fLoader = this.createFragmentLoader();
this.sid = cmcd.sessionId || CMCDController.uuid();
this.cid = cmcd.contentId;
this.useHeaders = cmcd.useHeaders === true;
this.registerListeners();
}
}
var _proto = CMCDController.prototype;
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHED, this.onMediaDetached, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_CREATED, this.onBufferCreated, this);
};
_proto.unregisterListeners = function unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHED, this.onMediaDetached, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_CREATED, this.onBufferCreated, this);
this.onMediaDetached();
};
_proto.destroy = function destroy() {
this.unregisterListeners(); // @ts-ignore
this.hls = this.config = this.audioBuffer = this.videoBuffer = null;
};
_proto.onMediaAttached = function onMediaAttached(event, data) {
this.media = data.media;
this.media.addEventListener('waiting', this.onWaiting);
this.media.addEventListener('playing', this.onPlaying);
};
_proto.onMediaDetached = function onMediaDetached() {
if (!this.media) {
return;
}
this.media.removeEventListener('waiting', this.onWaiting);
this.media.removeEventListener('playing', this.onPlaying); // @ts-ignore
this.media = null;
};
_proto.onBufferCreated = function onBufferCreated(event, data) {
var _data$tracks$audio, _data$tracks$video;
this.audioBuffer = (_data$tracks$audio = data.tracks.audio) === null || _data$tracks$audio === void 0 ? void 0 : _data$tracks$audio.buffer;
this.videoBuffer = (_data$tracks$video = data.tracks.video) === null || _data$tracks$video === void 0 ? void 0 : _data$tracks$video.buffer;
};
/**
* Create baseline CMCD data
*/
_proto.createData = function createData() {
var _this$media;
return {
v: _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDVersion"],
sf: _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDStreamingFormat"].HLS,
sid: this.sid,
cid: this.cid,
pr: (_this$media = this.media) === null || _this$media === void 0 ? void 0 : _this$media.playbackRate,
mtp: this.hls.bandwidthEstimate / 1000
};
}
/**
* Apply CMCD data to a request.
*/
;
_proto.apply = function apply(context, data) {
if (data === void 0) {
data = {};
}
// apply baseline data
_extends(data, this.createData());
var isVideo = data.ot === _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].INIT || data.ot === _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].VIDEO || data.ot === _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].MUXED;
if (this.starved && isVideo) {
data.bs = true;
data.su = true;
this.starved = false;
}
if (data.su == null) {
data.su = this.buffering;
} // TODO: Implement rtp, nrr, nor, dl
if (this.useHeaders) {
var headers = CMCDController.toHeaders(data);
if (!Object.keys(headers).length) {
return;
}
if (!context.headers) {
context.headers = {};
}
_extends(context.headers, headers);
} else {
var query = CMCDController.toQuery(data);
if (!query) {
return;
}
context.url = CMCDController.appendQueryToUri(context.url, query);
}
}
/**
* Apply CMCD data to a manifest request.
*/
;
/**
* The CMCD object type.
*/
_proto.getObjectType = function getObjectType(fragment) {
var type = fragment.type;
if (type === 'subtitle') {
return _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].TIMED_TEXT;
}
if (fragment.sn === 'initSegment') {
return _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].INIT;
}
if (type === 'audio') {
return _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].AUDIO;
}
if (type === 'main') {
if (!this.hls.audioTracks.length) {
return _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].MUXED;
}
return _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].VIDEO;
}
return undefined;
}
/**
* Get the highest bitrate.
*/
;
_proto.getTopBandwidth = function getTopBandwidth(type) {
var bitrate = 0;
var levels = type === _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].AUDIO ? this.hls.audioTracks : this.hls.levels;
for (var _iterator = _createForOfIteratorHelperLoose(levels), _step; !(_step = _iterator()).done;) {
var level = _step.value;
if (level.bitrate > bitrate) {
bitrate = level.bitrate;
}
}
return bitrate > 0 ? bitrate : NaN;
}
/**
* Get the buffer length for a media type in milliseconds
*/
;
_proto.getBufferLength = function getBufferLength(type) {
var media = this.hls.media;
var buffer = type === _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].AUDIO ? this.audioBuffer : this.videoBuffer;
if (!buffer || !media) {
return NaN;
}
var info = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_2__["BufferHelper"].bufferInfo(buffer, media.currentTime, this.config.maxBufferHole);
return info.len * 1000;
}
/**
* Create a playlist loader
*/
;
_proto.createPlaylistLoader = function createPlaylistLoader() {
var pLoader = this.config.pLoader;
var apply = this.applyPlaylistData;
var Ctor = pLoader || this.config.loader;
return /*#__PURE__*/function () {
function CmcdPlaylistLoader(config) {
this.loader = void 0;
this.loader = new Ctor(config);
}
var _proto2 = CmcdPlaylistLoader.prototype;
_proto2.destroy = function destroy() {
this.loader.destroy();
};
_proto2.abort = function abort() {
this.loader.abort();
};
_proto2.load = function load(context, config, callbacks) {
apply(context);
this.loader.load(context, config, callbacks);
};
_createClass(CmcdPlaylistLoader, [{
key: "stats",
get: function get() {
return this.loader.stats;
}
}, {
key: "context",
get: function get() {
return this.loader.context;
}
}]);
return CmcdPlaylistLoader;
}();
}
/**
* Create a playlist loader
*/
;
_proto.createFragmentLoader = function createFragmentLoader() {
var fLoader = this.config.fLoader;
var apply = this.applyFragmentData;
var Ctor = fLoader || this.config.loader;
return /*#__PURE__*/function () {
function CmcdFragmentLoader(config) {
this.loader = void 0;
this.loader = new Ctor(config);
}
var _proto3 = CmcdFragmentLoader.prototype;
_proto3.destroy = function destroy() {
this.loader.destroy();
};
_proto3.abort = function abort() {
this.loader.abort();
};
_proto3.load = function load(context, config, callbacks) {
apply(context);
this.loader.load(context, config, callbacks);
};
_createClass(CmcdFragmentLoader, [{
key: "stats",
get: function get() {
return this.loader.stats;
}
}, {
key: "context",
get: function get() {
return this.loader.context;
}
}]);
return CmcdFragmentLoader;
}();
}
/**
* Generate a random v4 UUI
*
* @returns {string}
*/
;
CMCDController.uuid = function uuid() {
var url = URL.createObjectURL(new Blob());
var uuid = url.toString();
URL.revokeObjectURL(url);
return uuid.substr(uuid.lastIndexOf('/') + 1);
}
/**
* Serialize a CMCD data object according to the rules defined in the
* section 3.2 of
* [CTA-5004](https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf).
*/
;
CMCDController.serialize = function serialize(data) {
var results = [];
var isValid = function isValid(value) {
return !Number.isNaN(value) && value != null && value !== '' && value !== false;
};
var toRounded = function toRounded(value) {
return Math.round(value);
};
var toHundred = function toHundred(value) {
return toRounded(value / 100) * 100;
};
var toUrlSafe = function toUrlSafe(value) {
return encodeURIComponent(value);
};
var formatters = {
br: toRounded,
d: toRounded,
bl: toHundred,
dl: toHundred,
mtp: toHundred,
nor: toUrlSafe,
rtp: toHundred,
tb: toRounded
};
var keys = Object.keys(data || {}).sort();
for (var _iterator2 = _createForOfIteratorHelperLoose(keys), _step2; !(_step2 = _iterator2()).done;) {
var key = _step2.value;
var value = data[key]; // ignore invalid values
if (!isValid(value)) {
continue;
} // Version should only be reported if not equal to 1.
if (key === 'v' && value === 1) {
continue;
} // Playback rate should only be sent if not equal to 1.
if (key == 'pr' && value === 1) {
continue;
} // Certain values require special formatting
var formatter = formatters[key];
if (formatter) {
value = formatter(value);
} // Serialize the key/value pair
var type = typeof value;
var result = void 0;
if (key === 'ot' || key === 'sf' || key === 'st') {
result = key + "=" + value;
} else if (type === 'boolean') {
result = key;
} else if (type === 'number') {
result = key + "=" + value;
} else {
result = key + "=" + JSON.stringify(value);
}
results.push(result);
}
return results.join(',');
}
/**
* Convert a CMCD data object to request headers according to the rules
* defined in the section 2.1 and 3.2 of
* [CTA-5004](https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf).
*/
;
CMCDController.toHeaders = function toHeaders(data) {
var keys = Object.keys(data);
var headers = {};
var headerNames = ['Object', 'Request', 'Session', 'Status'];
var headerGroups = [{}, {}, {}, {}];
var headerMap = {
br: 0,
d: 0,
ot: 0,
tb: 0,
bl: 1,
dl: 1,
mtp: 1,
nor: 1,
nrr: 1,
su: 1,
cid: 2,
pr: 2,
sf: 2,
sid: 2,
st: 2,
v: 2,
bs: 3,
rtp: 3
};
for (var _i = 0, _keys = keys; _i < _keys.length; _i++) {
var key = _keys[_i];
// Unmapped fields are mapped to the Request header
var index = headerMap[key] != null ? headerMap[key] : 1;
headerGroups[index][key] = data[key];
}
for (var i = 0; i < headerGroups.length; i++) {
var value = CMCDController.serialize(headerGroups[i]);
if (value) {
headers["CMCD-" + headerNames[i]] = value;
}
}
return headers;
}
/**
* Convert a CMCD data object to query args according to the rules
* defined in the section 2.2 and 3.2 of
* [CTA-5004](https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf).
*/
;
CMCDController.toQuery = function toQuery(data) {
return "CMCD=" + encodeURIComponent(CMCDController.serialize(data));
}
/**
* Append query args to a uri.
*/
;
CMCDController.appendQueryToUri = function appendQueryToUri(uri, query) {
if (!query) {
return uri;
}
var separator = uri.includes('?') ? '&' : '?';
return "" + uri + separator + query;
};
return CMCDController;
}();
/***/ }),
/***/ "./src/controller/eme-controller.ts":
/*!******************************************!*\
!*** ./src/controller/eme-controller.ts ***!
\******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/mediakeys-helper */ "./src/utils/mediakeys-helper.ts");
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); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
/**
* @author Stephan Hesse <[email protected]> | <[email protected]>
*
* DRM support for Hls.js
*/
var MAX_LICENSE_REQUEST_FAILURES = 3;
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration
* @param {Array<string>} audioCodecs List of required audio codecs to support
* @param {Array<string>} videoCodecs List of required video codecs to support
* @param {object} drmSystemOptions Optional parameters/requirements for the key-system
* @returns {Array<MediaSystemConfiguration>} An array of supported configurations
*/
var createWidevineMediaKeySystemConfigurations = function createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions) {
/* jshint ignore:line */
var baseConfig = {
// initDataTypes: ['keyids', 'mp4'],
// label: "",
// persistentState: "not-allowed", // or "required" ?
// distinctiveIdentifier: "not-allowed", // or "required" ?
// sessionTypes: ['temporary'],
audioCapabilities: [],
// { contentType: 'audio/mp4; codecs="mp4a.40.2"' }
videoCapabilities: [] // { contentType: 'video/mp4; codecs="avc1.42E01E"' }
};
audioCodecs.forEach(function (codec) {
baseConfig.audioCapabilities.push({
contentType: "audio/mp4; codecs=\"" + codec + "\"",
robustness: drmSystemOptions.audioRobustness || ''
});
});
videoCodecs.forEach(function (codec) {
baseConfig.videoCapabilities.push({
contentType: "video/mp4; codecs=\"" + codec + "\"",
robustness: drmSystemOptions.videoRobustness || ''
});
});
return [baseConfig];
};
/**
* The idea here is to handle key-system (and their respective platforms) specific configuration differences
* in order to work with the local requestMediaKeySystemAccess method.
*
* We can also rule-out platform-related key-system support at this point by throwing an error.
*
* @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
* @param {Array<string>} audioCodecs List of required audio codecs to support
* @param {Array<string>} videoCodecs List of required video codecs to support
* @throws will throw an error if a unknown key system is passed
* @returns {Array<MediaSystemConfiguration>} A non-empty Array of MediaKeySystemConfiguration objects
*/
var getSupportedMediaKeySystemConfigurations = function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, drmSystemOptions) {
switch (keySystem) {
case _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__["KeySystems"].WIDEVINE:
return createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions);
default:
throw new Error("Unknown key-system: " + keySystem);
}
};
/**
* Controller to deal with encrypted media extensions (EME)
* @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API
*
* @class
* @constructor
*/
var EMEController = /*#__PURE__*/function () {
/**
* @constructs
* @param {Hls} hls Our Hls.js instance
*/
function EMEController(hls) {
this.hls = void 0;
this._widevineLicenseUrl = void 0;
this._licenseXhrSetup = void 0;
this._licenseResponseCallback = void 0;
this._emeEnabled = void 0;
this._requestMediaKeySystemAccess = void 0;
this._drmSystemOptions = void 0;
this._config = void 0;
this._mediaKeysList = [];
this._media = null;
this._hasSetMediaKeys = false;
this._requestLicenseFailureCount = 0;
this.mediaKeysPromise = null;
this._onMediaEncrypted = this.onMediaEncrypted.bind(this);
this.hls = hls;
this._config = hls.config;
this._widevineLicenseUrl = this._config.widevineLicenseUrl;
this._licenseXhrSetup = this._config.licenseXhrSetup;
this._licenseResponseCallback = this._config.licenseResponseCallback;
this._emeEnabled = this._config.emeEnabled;
this._requestMediaKeySystemAccess = this._config.requestMediaKeySystemAccessFunc;
this._drmSystemOptions = this._config.drmSystemOptions;
this._registerListeners();
}
var _proto = EMEController.prototype;
_proto.destroy = function destroy() {
this._unregisterListeners(); // @ts-ignore
this.hls = this._onMediaEncrypted = null;
this._requestMediaKeySystemAccess = null;
};
_proto._registerListeners = function _registerListeners() {
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHED, this.onMediaDetached, this);
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHED, this.onMediaDetached, this);
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
}
/**
* @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
* @returns {string} License server URL for key-system (if any configured, otherwise causes error)
* @throws if a unsupported keysystem is passed
*/
;
_proto.getLicenseServerUrl = function getLicenseServerUrl(keySystem) {
switch (keySystem) {
case _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__["KeySystems"].WIDEVINE:
if (!this._widevineLicenseUrl) {
break;
}
return this._widevineLicenseUrl;
}
throw new Error("no license server URL configured for key-system \"" + keySystem + "\"");
}
/**
* Requests access object and adds it to our list upon success
* @private
* @param {string} keySystem System ID (see `KeySystems`)
* @param {Array<string>} audioCodecs List of required audio codecs to support
* @param {Array<string>} videoCodecs List of required video codecs to support
* @throws When a unsupported KeySystem is passed
*/
;
_proto._attemptKeySystemAccess = function _attemptKeySystemAccess(keySystem, audioCodecs, videoCodecs) {
var _this = this;
// This can throw, but is caught in event handler callpath
var mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, this._drmSystemOptions);
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('Requesting encrypted media key-system access'); // expecting interface like window.navigator.requestMediaKeySystemAccess
var keySystemAccessPromise = this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs);
this.mediaKeysPromise = keySystemAccessPromise.then(function (mediaKeySystemAccess) {
return _this._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess);
});
keySystemAccessPromise.catch(function (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("Failed to obtain key-system \"" + keySystem + "\" access:", err);
});
};
/**
* Handles obtaining access to a key-system
* @private
* @param {string} keySystem
* @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess
*/
_proto._onMediaKeySystemAccessObtained = function _onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess) {
var _this2 = this;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Access for key-system \"" + keySystem + "\" obtained");
var mediaKeysListItem = {
mediaKeysSessionInitialized: false,
mediaKeySystemAccess: mediaKeySystemAccess,
mediaKeySystemDomain: keySystem
};
this._mediaKeysList.push(mediaKeysListItem);
var mediaKeysPromise = Promise.resolve().then(function () {
return mediaKeySystemAccess.createMediaKeys();
}).then(function (mediaKeys) {
mediaKeysListItem.mediaKeys = mediaKeys;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Media-keys created for key-system \"" + keySystem + "\"");
_this2._onMediaKeysCreated();
return mediaKeys;
});
mediaKeysPromise.catch(function (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Failed to create media-keys:', err);
});
return mediaKeysPromise;
}
/**
* Handles key-creation (represents access to CDM). We are going to create key-sessions upon this
* for all existing keys where no session exists yet.
*
* @private
*/
;
_proto._onMediaKeysCreated = function _onMediaKeysCreated() {
var _this3 = this;
// check for all key-list items if a session exists, otherwise, create one
this._mediaKeysList.forEach(function (mediaKeysListItem) {
if (!mediaKeysListItem.mediaKeysSession) {
// mediaKeys is definitely initialized here
mediaKeysListItem.mediaKeysSession = mediaKeysListItem.mediaKeys.createSession();
_this3._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession);
}
});
}
/**
* @private
* @param {*} keySession
*/
;
_proto._onNewMediaKeySession = function _onNewMediaKeySession(keySession) {
var _this4 = this;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("New key-system session " + keySession.sessionId);
keySession.addEventListener('message', function (event) {
_this4._onKeySessionMessage(keySession, event.message);
}, false);
}
/**
* @private
* @param {MediaKeySession} keySession
* @param {ArrayBuffer} message
*/
;
_proto._onKeySessionMessage = function _onKeySessionMessage(keySession, message) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('Got EME message event, creating license request');
this._requestLicense(message, function (data) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Received license data (length: " + (data ? data.byteLength : data) + "), updating key-session");
keySession.update(data);
});
}
/**
* @private
* @param e {MediaEncryptedEvent}
*/
;
_proto.onMediaEncrypted = function onMediaEncrypted(e) {
var _this5 = this;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Media is encrypted using \"" + e.initDataType + "\" init data type");
if (!this.mediaKeysPromise) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal: Media is encrypted but no CDM access or no keys have been requested');
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_KEYS,
fatal: true
});
return;
}
var finallySetKeyAndStartSession = function finallySetKeyAndStartSession(mediaKeys) {
if (!_this5._media) {
return;
}
_this5._attemptSetMediaKeys(mediaKeys);
_this5._generateRequestWithPreferredKeySession(e.initDataType, e.initData);
}; // Could use `Promise.finally` but some Promise polyfills are missing it
this.mediaKeysPromise.then(finallySetKeyAndStartSession).catch(finallySetKeyAndStartSession);
}
/**
* @private
*/
;
_proto._attemptSetMediaKeys = function _attemptSetMediaKeys(mediaKeys) {
if (!this._media) {
throw new Error('Attempted to set mediaKeys without first attaching a media element');
}
if (!this._hasSetMediaKeys) {
// FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
var keysListItem = this._mediaKeysList[0];
if (!keysListItem || !keysListItem.mediaKeys) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal: Media is encrypted but no CDM access or no keys have been obtained yet');
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_KEYS,
fatal: true
});
return;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('Setting keys for encrypted media');
this._media.setMediaKeys(keysListItem.mediaKeys);
this._hasSetMediaKeys = true;
}
}
/**
* @private
*/
;
_proto._generateRequestWithPreferredKeySession = function _generateRequestWithPreferredKeySession(initDataType, initData) {
var _this6 = this;
// FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
var keysListItem = this._mediaKeysList[0];
if (!keysListItem) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal: Media is encrypted but not any key-system access has been obtained yet');
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_ACCESS,
fatal: true
});
return;
}
if (keysListItem.mediaKeysSessionInitialized) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('Key-Session already initialized but requested again');
return;
}
var keySession = keysListItem.mediaKeysSession;
if (!keySession) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal: Media is encrypted but no key-session existing');
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_SESSION,
fatal: true
});
return;
} // initData is null if the media is not CORS-same-origin
if (!initData) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('Fatal: initData required for generating a key session is null');
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_INIT_DATA,
fatal: true
});
return;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Generating key-session request for \"" + initDataType + "\" init data type");
keysListItem.mediaKeysSessionInitialized = true;
keySession.generateRequest(initDataType, initData).then(function () {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].debug('Key-session generation succeeded');
}).catch(function (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Error generating key-session request:', err);
_this6.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_SESSION,
fatal: false
});
});
}
/**
* @private
* @param {string} url License server URL
* @param {ArrayBuffer} keyMessage Message data issued by key-system
* @param {function} callback Called when XHR has succeeded
* @returns {XMLHttpRequest} Unsent (but opened state) XHR object
* @throws if XMLHttpRequest construction failed
*/
;
_proto._createLicenseXhr = function _createLicenseXhr(url, keyMessage, callback) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = this._onLicenseRequestReadyStageChange.bind(this, xhr, url, keyMessage, callback);
var licenseXhrSetup = this._licenseXhrSetup;
if (licenseXhrSetup) {
try {
licenseXhrSetup.call(this.hls, xhr, url);
licenseXhrSetup = undefined;
} catch (e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error(e);
}
}
try {
// if licenseXhrSetup did not yet call open, let's do it now
if (!xhr.readyState) {
xhr.open('POST', url, true);
}
if (licenseXhrSetup) {
licenseXhrSetup.call(this.hls, xhr, url);
}
} catch (e) {
// IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
throw new Error("issue setting up KeySystem license XHR " + e);
}
return xhr;
}
/**
* @private
* @param {XMLHttpRequest} xhr
* @param {string} url License server URL
* @param {ArrayBuffer} keyMessage Message data issued by key-system
* @param {function} callback Called when XHR has succeeded
*/
;
_proto._onLicenseRequestReadyStageChange = function _onLicenseRequestReadyStageChange(xhr, url, keyMessage, callback) {
switch (xhr.readyState) {
case 4:
if (xhr.status === 200) {
this._requestLicenseFailureCount = 0;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('License request succeeded');
var _data = xhr.response;
var licenseResponseCallback = this._licenseResponseCallback;
if (licenseResponseCallback) {
try {
_data = licenseResponseCallback.call(this.hls, xhr, url);
} catch (e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error(e);
}
}
callback(_data);
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("License Request XHR failed (" + url + "). Status: " + xhr.status + " (" + xhr.statusText + ")");
this._requestLicenseFailureCount++;
if (this._requestLicenseFailureCount > MAX_LICENSE_REQUEST_FAILURES) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_LICENSE_REQUEST_FAILED,
fatal: true
});
return;
}
var attemptsLeft = MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("Retrying license request, " + attemptsLeft + " attempts left");
this._requestLicense(keyMessage, callback);
}
break;
}
}
/**
* @private
* @param {MediaKeysListItem} keysListItem
* @param {ArrayBuffer} keyMessage
* @returns {ArrayBuffer} Challenge data posted to license server
* @throws if KeySystem is unsupported
*/
;
_proto._generateLicenseRequestChallenge = function _generateLicenseRequestChallenge(keysListItem, keyMessage) {
switch (keysListItem.mediaKeySystemDomain) {
// case KeySystems.PLAYREADY:
// from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js
/*
if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) {
// For PlayReady CDMs, we need to dig the Challenge out of the XML.
var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml');
if (keyMessageXml.getElementsByTagName('Challenge')[0]) {
challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue);
} else {
throw 'Cannot find <Challenge> in key message';
}
var headerNames = keyMessageXml.getElementsByTagName('name');
var headerValues = keyMessageXml.getElementsByTagName('value');
if (headerNames.length !== headerValues.length) {
throw 'Mismatched header <name>/<value> pair in key message';
}
for (var i = 0; i < headerNames.length; i++) {
xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue);
}
}
break;
*/
case _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__["KeySystems"].WIDEVINE:
// For Widevine CDMs, the challenge is the keyMessage.
return keyMessage;
}
throw new Error("unsupported key-system: " + keysListItem.mediaKeySystemDomain);
}
/**
* @private
* @param keyMessage
* @param callback
*/
;
_proto._requestLicense = function _requestLicense(keyMessage, callback) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('Requesting content license for key-system');
var keysListItem = this._mediaKeysList[0];
if (!keysListItem) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal error: Media is encrypted but no key-system access has been obtained yet');
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_ACCESS,
fatal: true
});
return;
}
try {
var _url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain);
var _xhr = this._createLicenseXhr(_url, keyMessage, callback);
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Sending license request to URL: " + _url);
var challenge = this._generateLicenseRequestChallenge(keysListItem, keyMessage);
_xhr.send(challenge);
} catch (e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("Failure requesting DRM license: " + e);
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_LICENSE_REQUEST_FAILED,
fatal: true
});
}
};
_proto.onMediaAttached = function onMediaAttached(event, data) {
if (!this._emeEnabled) {
return;
}
var media = data.media; // keep reference of media
this._media = media;
media.addEventListener('encrypted', this._onMediaEncrypted);
};
_proto.onMediaDetached = function onMediaDetached() {
var media = this._media;
var mediaKeysList = this._mediaKeysList;
if (!media) {
return;
}
media.removeEventListener('encrypted', this._onMediaEncrypted);
this._media = null;
this._mediaKeysList = []; // Close all sessions and remove media keys from the video element.
Promise.all(mediaKeysList.map(function (mediaKeysListItem) {
if (mediaKeysListItem.mediaKeysSession) {
return mediaKeysListItem.mediaKeysSession.close().catch(function () {// Ignore errors when closing the sessions. Closing a session that
// generated no key requests will throw an error.
});
}
})).then(function () {
return media.setMediaKeys(null);
}).catch(function () {// Ignore any failures while removing media keys from the video element.
});
};
_proto.onManifestParsed = function onManifestParsed(event, data) {
if (!this._emeEnabled) {
return;
}
var audioCodecs = data.levels.map(function (level) {
return level.audioCodec;
}).filter(function (audioCodec) {
return !!audioCodec;
});
var videoCodecs = data.levels.map(function (level) {
return level.videoCodec;
}).filter(function (videoCodec) {
return !!videoCodec;
});
this._attemptKeySystemAccess(_utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__["KeySystems"].WIDEVINE, audioCodecs, videoCodecs);
};
_createClass(EMEController, [{
key: "requestMediaKeySystemAccess",
get: function get() {
if (!this._requestMediaKeySystemAccess) {
throw new Error('No requestMediaKeySystemAccess function configured');
}
return this._requestMediaKeySystemAccess;
}
}]);
return EMEController;
}();
/* harmony default export */ __webpack_exports__["default"] = (EMEController);
/***/ }),
/***/ "./src/controller/fps-controller.ts":
/*!******************************************!*\
!*** ./src/controller/fps-controller.ts ***!
\******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var FPSController = /*#__PURE__*/function () {
// stream controller must be provided as a dependency!
function FPSController(hls) {
this.hls = void 0;
this.isVideoPlaybackQualityAvailable = false;
this.timer = void 0;
this.media = null;
this.lastTime = void 0;
this.lastDroppedFrames = 0;
this.lastDecodedFrames = 0;
this.streamController = void 0;
this.hls = hls;
this.registerListeners();
}
var _proto = FPSController.prototype;
_proto.setStreamController = function setStreamController(streamController) {
this.streamController = streamController;
};
_proto.registerListeners = function registerListeners() {
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
};
_proto.unregisterListeners = function unregisterListeners() {
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching);
};
_proto.destroy = function destroy() {
if (this.timer) {
clearInterval(this.timer);
}
this.unregisterListeners();
this.isVideoPlaybackQualityAvailable = false;
this.media = null;
};
_proto.onMediaAttaching = function onMediaAttaching(event, data) {
var config = this.hls.config;
if (config.capLevelOnFPSDrop) {
var media = data.media instanceof self.HTMLVideoElement ? data.media : null;
this.media = media;
if (media && typeof media.getVideoPlaybackQuality === 'function') {
this.isVideoPlaybackQualityAvailable = true;
}
self.clearInterval(this.timer);
this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
}
};
_proto.checkFPS = function checkFPS(video, decodedFrames, droppedFrames) {
var currentTime = performance.now();
if (decodedFrames) {
if (this.lastTime) {
var currentPeriod = currentTime - this.lastTime;
var currentDropped = droppedFrames - this.lastDroppedFrames;
var currentDecoded = decodedFrames - this.lastDecodedFrames;
var droppedFPS = 1000 * currentDropped / currentPeriod;
var hls = this.hls;
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].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;
_utils_logger__WEBPACK_IMPORTED_MODULE_1__["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__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP_LEVEL_CAPPING, {
level: currentLevel,
droppedLevel: hls.currentLevel
});
hls.autoLevelCapping = currentLevel;
this.streamController.nextLevelSwitch();
}
}
}
}
this.lastTime = currentTime;
this.lastDroppedFrames = droppedFrames;
this.lastDecodedFrames = decodedFrames;
}
};
_proto.checkFPSInterval = function checkFPSInterval() {
var video = this.media;
if (video) {
if (this.isVideoPlaybackQualityAvailable) {
var videoPlaybackQuality = video.getVideoPlaybackQuality();
this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
} else {
// HTMLVideoElement doesn't include the webkit types
this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
}
}
};
return FPSController;
}();
/* harmony default export */ __webpack_exports__["default"] = (FPSController);
/***/ }),
/***/ "./src/controller/fragment-finders.ts":
/*!********************************************!*\
!*** ./src/controller/fragment-finders.ts ***!
\********************************************/
/*! exports provided: findFragmentByPDT, findFragmentByPTS, fragmentWithinToleranceTest, pdtWithinToleranceTest, findFragWithCC */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFragmentByPDT", function() { return findFragmentByPDT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFragmentByPTS", function() { return findFragmentByPTS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fragmentWithinToleranceTest", function() { return fragmentWithinToleranceTest; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pdtWithinToleranceTest", function() { return pdtWithinToleranceTest; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFragWithCC", function() { return findFragWithCC; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/binary-search */ "./src/utils/binary-search.ts");
/**
* Returns first fragment whose endPdt value exceeds the given PDT.
* @param {Array<Fragment>} fragments - The array of candidate fragments
* @param {number|null} [PDTValue = null] - The PDT value which must be exceeded
* @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start/end can be within in order to be considered contiguous
* @returns {*|null} fragment - The best matching fragment
*/
function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(PDTValue)) {
return null;
} // if less than start
var startPDT = fragments[0].programDateTime;
if (PDTValue < (startPDT || 0)) {
return null;
}
var endPDT = fragments[fragments.length - 1].endProgramDateTime;
if (PDTValue >= (endPDT || 0)) {
return null;
}
maxFragLookUpTolerance = maxFragLookUpTolerance || 0;
for (var seg = 0; seg < fragments.length; ++seg) {
var frag = fragments[seg];
if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
return frag;
}
}
return null;
}
/**
* Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
* This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
* breaking any traps which would cause the same fragment to be continuously selected within a small range.
* @param {*} fragPrevious - The last frag successfully appended
* @param {Array} fragments - The array of candidate fragments
* @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within
* @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
* @returns {*} foundFrag - The best matching fragment
*/
function findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance) {
if (bufferEnd === void 0) {
bufferEnd = 0;
}
if (maxFragLookUpTolerance === void 0) {
maxFragLookUpTolerance = 0;
}
var fragNext = null;
if (fragPrevious) {
fragNext = fragments[fragPrevious.sn - fragments[0].sn + 1] || null;
} else if (bufferEnd === 0 && fragments[0].start === 0) {
fragNext = fragments[0];
} // Prefer the next fragment if it's within tolerance
if (fragNext && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0) {
return fragNext;
} // We might be seeking past the tolerance so find the best match
var foundFragment = _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__["default"].search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
if (foundFragment) {
return foundFragment;
} // If no match was found return the next fragment after fragPrevious, or null
return fragNext;
}
/**
* The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
* @param {*} candidate - The fragment to test
* @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within
* @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
* @returns {number} - 0 if it matches, 1 if too low, -1 if too high
*/
function fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, candidate) {
if (bufferEnd === void 0) {
bufferEnd = 0;
}
if (maxFragLookUpTolerance === void 0) {
maxFragLookUpTolerance = 0;
}
// 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;
} else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
// if maxFragLookUpTolerance will have negative value then don't return -1 for first element
return -1;
}
return 0;
}
/**
* The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.
* This function tests the candidate's program date time values, as represented in Unix time
* @param {*} candidate - The fragment to test
* @param {number} [pdtBufferEnd = 0] - The Unix time representing the end of the current buffered range
* @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
* @returns {boolean} True if contiguous, false otherwise
*/
function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000; // endProgramDateTime can be null, default to zero
var endProgramDateTime = candidate.endProgramDateTime || 0;
return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
}
function findFragWithCC(fragments, cc) {
return _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__["default"].search(fragments, function (candidate) {
if (candidate.cc < cc) {
return 1;
} else if (candidate.cc > cc) {
return -1;
} else {
return 0;
}
});
}
/***/ }),
/***/ "./src/controller/fragment-tracker.ts":
/*!********************************************!*\
!*** ./src/controller/fragment-tracker.ts ***!
\********************************************/
/*! exports provided: FragmentState, FragmentTracker */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FragmentState", function() { return FragmentState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FragmentTracker", function() { return FragmentTracker; });
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
var FragmentState;
(function (FragmentState) {
FragmentState["NOT_LOADED"] = "NOT_LOADED";
FragmentState["BACKTRACKED"] = "BACKTRACKED";
FragmentState["APPENDING"] = "APPENDING";
FragmentState["PARTIAL"] = "PARTIAL";
FragmentState["OK"] = "OK";
})(FragmentState || (FragmentState = {}));
var FragmentTracker = /*#__PURE__*/function () {
function FragmentTracker(hls) {
this.activeFragment = null;
this.activeParts = null;
this.fragments = Object.create(null);
this.timeRanges = Object.create(null);
this.bufferPadding = 0.2;
this.hls = void 0;
this.hls = hls;
this._registerListeners();
}
var _proto = FragmentTracker.prototype;
_proto._registerListeners = function _registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_APPENDED, this.onBufferAppended, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_LOADED, this.onFragLoaded, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_APPENDED, this.onBufferAppended, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_LOADED, this.onFragLoaded, this);
};
_proto.destroy = function destroy() {
this._unregisterListeners(); // @ts-ignore
this.fragments = this.timeRanges = null;
}
/**
* Return a Fragment with an appended range that matches the position and levelType.
* If not found any Fragment, return null
*/
;
_proto.getAppendedFrag = function getAppendedFrag(position, levelType) {
if (levelType === _types_loader__WEBPACK_IMPORTED_MODULE_1__["PlaylistLevelType"].MAIN) {
var activeFragment = this.activeFragment,
activeParts = this.activeParts;
if (!activeFragment) {
return null;
}
if (activeParts) {
for (var i = activeParts.length; i--;) {
var activePart = activeParts[i];
var appendedPTS = activePart ? activePart.end : activeFragment.appendedPTS;
if (activePart.start <= position && appendedPTS !== undefined && position <= appendedPTS) {
// 9 is a magic number. remove parts from lookup after a match but keep some short seeks back.
if (i > 9) {
this.activeParts = activeParts.slice(i - 9);
}
return activePart;
}
}
} else if (activeFragment.start <= position && activeFragment.appendedPTS !== undefined && position <= activeFragment.appendedPTS) {
return activeFragment;
}
}
return this.getBufferedFrag(position, levelType);
}
/**
* Return a buffered Fragment that matches the position and levelType.
* A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted).
* If not found any Fragment, return null
*/
;
_proto.getBufferedFrag = function getBufferedFrag(position, levelType) {
var fragments = this.fragments;
var keys = Object.keys(fragments);
for (var i = keys.length; i--;) {
var fragmentEntity = fragments[keys[i]];
if ((fragmentEntity === null || fragmentEntity === void 0 ? void 0 : fragmentEntity.body.type) === levelType && fragmentEntity.buffered) {
var frag = fragmentEntity.body;
if (frag.start <= position && position <= frag.end) {
return frag;
}
}
}
return null;
}
/**
* Partial fragments effected by coded frame eviction will be removed
* The browser will unload parts of the buffer to free up memory for new buffer data
* Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)
*/
;
_proto.detectEvictedFragments = function detectEvictedFragments(elementaryStream, timeRange, playlistType) {
var _this = this;
// Check if any flagged fragments have been unloaded
Object.keys(this.fragments).forEach(function (key) {
var fragmentEntity = _this.fragments[key];
if (!fragmentEntity) {
return;
}
if (!fragmentEntity.buffered) {
if (fragmentEntity.body.type === playlistType) {
_this.removeFragment(fragmentEntity.body);
}
return;
}
var esData = fragmentEntity.range[elementaryStream];
if (!esData) {
return;
}
esData.time.some(function (time) {
var isNotBuffered = !_this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);
if (isNotBuffered) {
// Unregister partial fragment as it needs to load again to be reused
_this.removeFragment(fragmentEntity.body);
}
return isNotBuffered;
});
});
}
/**
* Checks if the fragment passed in is loaded in the buffer properly
* Partially loaded fragments will be registered as a partial fragment
*/
;
_proto.detectPartialFragments = function detectPartialFragments(data) {
var _this2 = this;
var timeRanges = this.timeRanges;
var frag = data.frag,
part = data.part;
if (!timeRanges || frag.sn === 'initSegment') {
return;
}
var fragKey = getFragmentKey(frag);
var fragmentEntity = this.fragments[fragKey];
if (!fragmentEntity) {
return;
}
Object.keys(timeRanges).forEach(function (elementaryStream) {
var streamInfo = frag.elementaryStreams[elementaryStream];
if (!streamInfo) {
return;
}
var timeRange = timeRanges[elementaryStream];
var partial = part !== null || streamInfo.partial === true;
fragmentEntity.range[elementaryStream] = _this2.getBufferedTimes(frag, part, partial, timeRange);
});
fragmentEntity.backtrack = fragmentEntity.loaded = null;
if (Object.keys(fragmentEntity.range).length) {
fragmentEntity.buffered = true;
} else {
// remove fragment if nothing was appended
this.removeFragment(fragmentEntity.body);
}
};
_proto.fragBuffered = function fragBuffered(frag) {
var fragKey = getFragmentKey(frag);
var fragmentEntity = this.fragments[fragKey];
if (fragmentEntity) {
fragmentEntity.backtrack = fragmentEntity.loaded = null;
fragmentEntity.buffered = true;
}
};
_proto.getBufferedTimes = function getBufferedTimes(fragment, part, partial, timeRange) {
var buffered = {
time: [],
partial: partial
};
var startPTS = part ? part.start : fragment.start;
var endPTS = part ? part.end : fragment.end;
var minEndPTS = fragment.minEndPTS || endPTS;
var maxStartPTS = fragment.maxStartPTS || startPTS;
for (var i = 0; i < timeRange.length; i++) {
var startTime = timeRange.start(i) - this.bufferPadding;
var endTime = timeRange.end(i) + this.bufferPadding;
if (maxStartPTS >= startTime && minEndPTS <= endTime) {
// Fragment is entirely contained in buffer
// No need to check the other timeRange times since it's completely playable
buffered.time.push({
startPTS: Math.max(startPTS, timeRange.start(i)),
endPTS: Math.min(endPTS, timeRange.end(i))
});
break;
} else if (startPTS < endTime && endPTS > startTime) {
buffered.partial = true; // Check for intersection with buffer
// Get playable sections of the fragment
buffered.time.push({
startPTS: Math.max(startPTS, timeRange.start(i)),
endPTS: Math.min(endPTS, timeRange.end(i))
});
} else if (endPTS <= startTime) {
// No need to check the rest of the timeRange as it is in order
break;
}
}
return buffered;
}
/**
* Gets the partial fragment for a certain time
*/
;
_proto.getPartialFragment = function getPartialFragment(time) {
var bestFragment = null;
var timePadding;
var startTime;
var endTime;
var bestOverlap = 0;
var bufferPadding = this.bufferPadding,
fragments = this.fragments;
Object.keys(fragments).forEach(function (key) {
var fragmentEntity = fragments[key];
if (!fragmentEntity) {
return;
}
if (isPartial(fragmentEntity)) {
startTime = fragmentEntity.body.start - bufferPadding;
endTime = fragmentEntity.body.end + bufferPadding;
if (time >= startTime && time <= endTime) {
// Use the fragment that has the most padding from start and end time
timePadding = Math.min(time - startTime, endTime - time);
if (bestOverlap <= timePadding) {
bestFragment = fragmentEntity.body;
bestOverlap = timePadding;
}
}
}
});
return bestFragment;
};
_proto.getState = function getState(fragment) {
var fragKey = getFragmentKey(fragment);
var fragmentEntity = this.fragments[fragKey];
if (fragmentEntity) {
if (!fragmentEntity.buffered) {
if (fragmentEntity.backtrack) {
return FragmentState.BACKTRACKED;
}
return FragmentState.APPENDING;
} else if (isPartial(fragmentEntity)) {
return FragmentState.PARTIAL;
} else {
return FragmentState.OK;
}
}
return FragmentState.NOT_LOADED;
};
_proto.backtrack = function backtrack(frag, data) {
var fragKey = getFragmentKey(frag);
var fragmentEntity = this.fragments[fragKey];
if (!fragmentEntity || fragmentEntity.backtrack) {
return null;
}
var backtrack = fragmentEntity.backtrack = data ? data : fragmentEntity.loaded;
fragmentEntity.loaded = null;
return backtrack;
};
_proto.getBacktrackData = function getBacktrackData(fragment) {
var fragKey = getFragmentKey(fragment);
var fragmentEntity = this.fragments[fragKey];
if (fragmentEntity) {
var _backtrack$payload;
var backtrack = fragmentEntity.backtrack; // If data was already sent to Worker it is detached no longer available
if (backtrack !== null && backtrack !== void 0 && (_backtrack$payload = backtrack.payload) !== null && _backtrack$payload !== void 0 && _backtrack$payload.byteLength) {
return backtrack;
} else {
this.removeFragment(fragment);
}
}
return null;
};
_proto.isTimeBuffered = function isTimeBuffered(startPTS, endPTS, timeRange) {
var startTime;
var endTime;
for (var i = 0; i < timeRange.length; i++) {
startTime = timeRange.start(i) - this.bufferPadding;
endTime = timeRange.end(i) + this.bufferPadding;
if (startPTS >= startTime && endPTS <= endTime) {
return true;
}
if (endPTS <= startTime) {
// No need to check the rest of the timeRange as it is in order
return false;
}
}
return false;
};
_proto.onFragLoaded = function onFragLoaded(event, data) {
var frag = data.frag,
part = data.part; // don't track initsegment (for which sn is not a number)
// don't track frags used for bitrateTest, they're irrelevant.
// don't track parts for memory efficiency
if (frag.sn === 'initSegment' || frag.bitrateTest || part) {
return;
}
var fragKey = getFragmentKey(frag);
this.fragments[fragKey] = {
body: frag,
loaded: data,
backtrack: null,
buffered: false,
range: Object.create(null)
};
};
_proto.onBufferAppended = function onBufferAppended(event, data) {
var _this3 = this;
var frag = data.frag,
part = data.part,
timeRanges = data.timeRanges;
if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_1__["PlaylistLevelType"].MAIN) {
this.activeFragment = frag;
if (part) {
var activeParts = this.activeParts;
if (!activeParts) {
this.activeParts = activeParts = [];
}
activeParts.push(part);
} else {
this.activeParts = null;
}
} // Store the latest timeRanges loaded in the buffer
this.timeRanges = timeRanges;
Object.keys(timeRanges).forEach(function (elementaryStream) {
var timeRange = timeRanges[elementaryStream];
_this3.detectEvictedFragments(elementaryStream, timeRange);
if (!part) {
for (var i = 0; i < timeRange.length; i++) {
frag.appendedPTS = Math.max(timeRange.end(i), frag.appendedPTS || 0);
}
}
});
};
_proto.onFragBuffered = function onFragBuffered(event, data) {
this.detectPartialFragments(data);
};
_proto.hasFragment = function hasFragment(fragment) {
var fragKey = getFragmentKey(fragment);
return !!this.fragments[fragKey];
};
_proto.removeFragmentsInRange = function removeFragmentsInRange(start, end, playlistType) {
var _this4 = this;
Object.keys(this.fragments).forEach(function (key) {
var fragmentEntity = _this4.fragments[key];
if (!fragmentEntity) {
return;
}
if (fragmentEntity.buffered) {
var frag = fragmentEntity.body;
if (frag.type === playlistType && frag.start < end && frag.end > start) {
_this4.removeFragment(frag);
}
}
});
};
_proto.removeFragment = function removeFragment(fragment) {
var fragKey = getFragmentKey(fragment);
fragment.stats.loaded = 0;
fragment.clearElementaryStreamInfo();
delete this.fragments[fragKey];
};
_proto.removeAllFragments = function removeAllFragments() {
this.fragments = Object.create(null);
this.activeFragment = null;
this.activeParts = null;
};
return FragmentTracker;
}();
function isPartial(fragmentEntity) {
var _fragmentEntity$range, _fragmentEntity$range2;
return fragmentEntity.buffered && (((_fragmentEntity$range = fragmentEntity.range.video) === null || _fragmentEntity$range === void 0 ? void 0 : _fragmentEntity$range.partial) || ((_fragmentEntity$range2 = fragmentEntity.range.audio) === null || _fragmentEntity$range2 === void 0 ? void 0 : _fragmentEntity$range2.partial));
}
function getFragmentKey(fragment) {
return fragment.type + "_" + fragment.level + "_" + fragment.urlId + "_" + fragment.sn;
}
/***/ }),
/***/ "./src/controller/gap-controller.ts":
/*!******************************************!*\
!*** ./src/controller/gap-controller.ts ***!
\******************************************/
/*! exports provided: STALL_MINIMUM_DURATION_MS, MAX_START_GAP_JUMP, SKIP_BUFFER_HOLE_STEP_SECONDS, SKIP_BUFFER_RANGE_START, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STALL_MINIMUM_DURATION_MS", function() { return STALL_MINIMUM_DURATION_MS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MAX_START_GAP_JUMP", function() { return MAX_START_GAP_JUMP; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SKIP_BUFFER_HOLE_STEP_SECONDS", function() { return SKIP_BUFFER_HOLE_STEP_SECONDS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SKIP_BUFFER_RANGE_START", function() { return SKIP_BUFFER_RANGE_START; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return GapController; });
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var STALL_MINIMUM_DURATION_MS = 250;
var MAX_START_GAP_JUMP = 2.0;
var SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
var SKIP_BUFFER_RANGE_START = 0.05;
var GapController = /*#__PURE__*/function () {
function GapController(config, media, fragmentTracker, hls) {
this.config = void 0;
this.media = void 0;
this.fragmentTracker = void 0;
this.hls = void 0;
this.nudgeRetry = 0;
this.stallReported = false;
this.stalled = null;
this.moved = false;
this.seeking = false;
this.config = config;
this.media = media;
this.fragmentTracker = fragmentTracker;
this.hls = hls;
}
var _proto = GapController.prototype;
_proto.destroy = function destroy() {
// @ts-ignore
this.hls = this.fragmentTracker = this.media = null;
}
/**
* Checks if the playhead is stuck within a gap, and if so, attempts to free it.
* A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
*
* @param {number} lastCurrentTime Previously read playhead position
*/
;
_proto.poll = function poll(lastCurrentTime) {
var config = this.config,
media = this.media,
stalled = this.stalled;
var currentTime = media.currentTime,
seeking = media.seeking;
var seeked = this.seeking && !seeking;
var beginSeek = !this.seeking && seeking;
this.seeking = seeking; // The playhead is moving, no-op
if (currentTime !== lastCurrentTime) {
this.moved = true;
if (stalled !== null) {
// The playhead is now moving, but was previously stalled
if (this.stallReported) {
var _stalledDuration = self.performance.now() - stalled;
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("playback not stuck anymore @" + currentTime + ", after " + Math.round(_stalledDuration) + "ms");
this.stallReported = false;
}
this.stalled = null;
this.nudgeRetry = 0;
}
return;
} // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek
if (beginSeek || seeked) {
this.stalled = null;
} // The playhead should not be moving
if (media.paused || media.ended || media.playbackRate === 0 || !_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].getBuffered(media).length) {
return;
}
var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].bufferInfo(media, currentTime, 0);
var isBuffered = bufferInfo.len > 0;
var nextStart = bufferInfo.nextStart || 0; // There is no playable buffer (seeked, waiting for buffer)
if (!isBuffered && !nextStart) {
return;
}
if (seeking) {
// Waiting for seeking in a buffered range to complete
var hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP; // Next buffered range is too far ahead to jump to while still seeking
var noBufferGap = !nextStart || nextStart - currentTime > MAX_START_GAP_JUMP && !this.fragmentTracker.getPartialFragment(currentTime);
if (hasEnoughBuffer || noBufferGap) {
return;
} // Reset moved state when seeking to a point in or before a gap
this.moved = false;
} // Skip start gaps if we haven't played, but the last poll detected the start of a stall
// The addition poll gives the browser a chance to jump the gap for us
if (!this.moved && this.stalled !== null) {
var _level$details;
// Jump start gaps within jump threshold
var startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime; // When joining a live stream with audio tracks, account for live playlist window sliding by allowing
// a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment
// that begins over 1 target duration after the video start position.
var level = this.hls.levels ? this.hls.levels[this.hls.currentLevel] : null;
var isLive = level === null || level === void 0 ? void 0 : (_level$details = level.details) === null || _level$details === void 0 ? void 0 : _level$details.live;
var maxStartGapJump = isLive ? level.details.targetduration * 2 : MAX_START_GAP_JUMP;
if (startJump > 0 && startJump <= maxStartGapJump) {
this._trySkipBufferHole(null);
return;
}
} // Start tracking stall time
var tnow = self.performance.now();
if (stalled === null) {
this.stalled = tnow;
return;
}
var stalledDuration = tnow - stalled;
if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) {
// Report stalling after trying to fix
this._reportStall(bufferInfo.len);
}
var bufferedWithHoles = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].bufferInfo(media, currentTime, config.maxBufferHole);
this._tryFixBufferStall(bufferedWithHoles, stalledDuration);
}
/**
* Detects and attempts to fix known buffer stalling issues.
* @param bufferInfo - The properties of the current buffer.
* @param stalledDurationMs - The amount of time Hls.js has been stalling for.
* @private
*/
;
_proto._tryFixBufferStall = function _tryFixBufferStall(bufferInfo, stalledDurationMs) {
var config = this.config,
fragmentTracker = this.fragmentTracker,
media = this.media;
var currentTime = media.currentTime;
var partial = fragmentTracker.getPartialFragment(currentTime);
if (partial) {
// Try to skip over the buffer hole caused by a partial fragment
// This method isn't limited by the size of the gap between buffered ranges
var targetTime = this._trySkipBufferHole(partial); // we return here in this case, meaning
// the branch below only executes when we don't handle a partial fragment
if (targetTime) {
return;
}
} // if we haven't had to skip over a buffer hole of a partial fragment
// we may just have to "nudge" the playlist as the browser decoding/rendering engine
// needs to cross some sort of threshold covering all source-buffers content
// to start playing properly.
if (bufferInfo.len > config.maxBufferHole && stalledDurationMs > config.highBufferWatchdogPeriod * 1000) {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Trying to nudge playhead over buffer-hole'); // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
// We only try to jump the hole if it's under the configured size
// Reset stalled so to rearm watchdog timer
this.stalled = null;
this._tryNudgeBuffer();
}
}
/**
* Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
* @param bufferLen - The playhead distance from the end of the current buffer segment.
* @private
*/
;
_proto._reportStall = function _reportStall(bufferLen) {
var hls = this.hls,
media = this.media,
stallReported = this.stallReported;
if (!stallReported) {
// Report stalled error once
this.stallReported = true;
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("Playback stalling at @" + media.currentTime + " due to low buffer (buffer=" + bufferLen + ")");
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_STALLED_ERROR,
fatal: false,
buffer: bufferLen
});
}
}
/**
* Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
* @param partial - The partial fragment found at the current time (where playback is stalling).
* @private
*/
;
_proto._trySkipBufferHole = function _trySkipBufferHole(partial) {
var config = this.config,
hls = this.hls,
media = this.media;
var currentTime = media.currentTime;
var lastEndTime = 0; // Check if currentTime is between unbuffered regions of partial fragments
var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].getBuffered(media);
for (var i = 0; i < buffered.length; i++) {
var startTime = buffered.start(i);
if (currentTime + config.maxBufferHole >= lastEndTime && currentTime < startTime) {
var targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, media.currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("skipping hole, adjusting currentTime from " + currentTime + " to " + targetTime);
this.moved = true;
this.stalled = null;
media.currentTime = targetTime;
if (partial) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_SEEK_OVER_HOLE,
fatal: false,
reason: "fragment loaded with buffer holes, seeking from " + currentTime + " to " + targetTime,
frag: partial
});
}
return targetTime;
}
lastEndTime = buffered.end(i);
}
return 0;
}
/**
* Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
* @private
*/
;
_proto._tryNudgeBuffer = function _tryNudgeBuffer() {
var config = this.config,
hls = this.hls,
media = this.media;
var currentTime = media.currentTime;
var nudgeRetry = (this.nudgeRetry || 0) + 1;
this.nudgeRetry = nudgeRetry;
if (nudgeRetry < config.nudgeMaxRetry) {
var targetTime = currentTime + nudgeRetry * config.nudgeOffset; // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("Nudging 'currentTime' from " + currentTime + " to " + targetTime);
media.currentTime = targetTime;
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_NUDGE_ON_STALL,
fatal: false
});
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].error("Playhead still not moving while enough data buffered @" + currentTime + " after " + config.nudgeMaxRetry + " nudges");
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_STALLED_ERROR,
fatal: true
});
}
};
return GapController;
}();
/***/ }),
/***/ "./src/controller/id3-track-controller.ts":
/*!************************************************!*\
!*** ./src/controller/id3-track-controller.ts ***!
\************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/texttrack-utils */ "./src/utils/texttrack-utils.ts");
/* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
var MIN_CUE_DURATION = 0.25;
var ID3TrackController = /*#__PURE__*/function () {
function ID3TrackController(hls) {
this.hls = void 0;
this.id3Track = null;
this.media = null;
this.hls = hls;
this._registerListeners();
}
var _proto = ID3TrackController.prototype;
_proto.destroy = function destroy() {
this._unregisterListeners();
};
_proto._registerListeners = function _registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
} // Add ID3 metatadata text track.
;
_proto.onMediaAttached = function onMediaAttached(event, data) {
this.media = data.media;
};
_proto.onMediaDetaching = function onMediaDetaching() {
if (!this.id3Track) {
return;
}
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["clearCurrentCues"])(this.id3Track);
this.id3Track = null;
this.media = null;
};
_proto.getID3Track = function getID3Track(textTracks) {
if (!this.media) {
return;
}
for (var i = 0; i < textTracks.length; i++) {
var textTrack = textTracks[i];
if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {
// send 'addtrack' when reusing the textTrack for metadata,
// same as what we do for captions
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["sendAddTrackEvent"])(textTrack, this.media);
return textTrack;
}
}
return this.media.addTextTrack('metadata', 'id3');
};
_proto.onFragParsingMetadata = function onFragParsingMetadata(event, data) {
if (!this.media) {
return;
}
var fragment = data.frag;
var samples = data.samples; // create track dynamically
if (!this.id3Track) {
this.id3Track = this.getID3Track(this.media.textTracks);
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 = self.WebKitDataCue || self.VTTCue || self.TextTrackCue;
for (var i = 0; i < samples.length; i++) {
var frames = _demux_id3__WEBPACK_IMPORTED_MODULE_2__["getID3Frames"](samples[i].data);
if (frames) {
var startTime = samples[i].pts;
var endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.end;
var timeDiff = endTime - startTime;
if (timeDiff <= 0) {
endTime = startTime + MIN_CUE_DURATION;
}
for (var j = 0; j < frames.length; j++) {
var frame = frames[j]; // Safari doesn't put the timestamp frame in the TextTrack
if (!_demux_id3__WEBPACK_IMPORTED_MODULE_2__["isTimeStampFrame"](frame)) {
var cue = new Cue(startTime, endTime, '');
cue.value = frame;
this.id3Track.addCue(cue);
}
}
}
}
};
_proto.onBufferFlushing = function onBufferFlushing(event, _ref) {
var startOffset = _ref.startOffset,
endOffset = _ref.endOffset,
type = _ref.type;
if (!type || type === 'audio') {
// id3 cues come from parsed audio only remove cues when audio buffer is cleared
var id3Track = this.id3Track;
if (id3Track) {
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["removeCuesInRange"])(id3Track, startOffset, endOffset);
}
}
};
return ID3TrackController;
}();
/* harmony default export */ __webpack_exports__["default"] = (ID3TrackController);
/***/ }),
/***/ "./src/controller/latency-controller.ts":
/*!**********************************************!*\
!*** ./src/controller/latency-controller.ts ***!
\**********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return LatencyController; });
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
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); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var LatencyController = /*#__PURE__*/function () {
function LatencyController(hls) {
var _this = this;
this.hls = void 0;
this.config = void 0;
this.media = null;
this.levelDetails = null;
this.currentTime = 0;
this.stallCount = 0;
this._latency = null;
this.timeupdateHandler = function () {
return _this.timeupdate();
};
this.hls = hls;
this.config = hls.config;
this.registerListeners();
}
var _proto = LatencyController.prototype;
_proto.destroy = function destroy() {
this.unregisterListeners();
this.onMediaDetaching();
this.levelDetails = null; // @ts-ignore
this.hls = this.timeupdateHandler = null;
};
_proto.registerListeners = function registerListeners() {
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated, this);
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError, this);
};
_proto.unregisterListeners = function unregisterListeners() {
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHED, this.onMediaAttached);
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching);
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading);
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated);
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError);
};
_proto.onMediaAttached = function onMediaAttached(event, data) {
this.media = data.media;
this.media.addEventListener('timeupdate', this.timeupdateHandler);
};
_proto.onMediaDetaching = function onMediaDetaching() {
if (this.media) {
this.media.removeEventListener('timeupdate', this.timeupdateHandler);
this.media = null;
}
};
_proto.onManifestLoading = function onManifestLoading() {
this.levelDetails = null;
this._latency = null;
this.stallCount = 0;
};
_proto.onLevelUpdated = function onLevelUpdated(event, _ref) {
var details = _ref.details;
this.levelDetails = details;
if (details.advanced) {
this.timeupdate();
}
if (!details.live && this.media) {
this.media.removeEventListener('timeupdate', this.timeupdateHandler);
}
};
_proto.onError = function onError(event, data) {
if (data.details !== _errors__WEBPACK_IMPORTED_MODULE_0__["ErrorDetails"].BUFFER_STALLED_ERROR) {
return;
}
this.stallCount++;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('[playback-rate-controller]: Stall detected, adjusting target latency');
};
_proto.timeupdate = function timeupdate() {
var media = this.media,
levelDetails = this.levelDetails;
if (!media || !levelDetails) {
return;
}
this.currentTime = media.currentTime;
var latency = this.computeLatency();
if (latency === null) {
return;
}
this._latency = latency; // Adapt playbackRate to meet target latency in low-latency mode
var _this$config = this.config,
lowLatencyMode = _this$config.lowLatencyMode,
maxLiveSyncPlaybackRate = _this$config.maxLiveSyncPlaybackRate;
if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1) {
return;
}
var targetLatency = this.targetLatency;
if (targetLatency === null) {
return;
}
var distanceFromTarget = latency - targetLatency; // Only adjust playbackRate when within one target duration of targetLatency
// and more than one second from under-buffering.
// Playback further than one target duration from target can be considered DVR playback.
var liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration);
var inLiveRange = distanceFromTarget < liveMinLatencyDuration;
if (levelDetails.live && inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) {
var max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate));
var rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20;
media.playbackRate = Math.min(max, Math.max(1, rate));
} else if (media.playbackRate !== 1 && media.playbackRate !== 0) {
media.playbackRate = 1;
}
};
_proto.estimateLiveEdge = function estimateLiveEdge() {
var levelDetails = this.levelDetails;
if (levelDetails === null) {
return null;
}
return levelDetails.edge + levelDetails.age;
};
_proto.computeLatency = function computeLatency() {
var liveEdge = this.estimateLiveEdge();
if (liveEdge === null) {
return null;
}
return liveEdge - this.currentTime;
};
_createClass(LatencyController, [{
key: "latency",
get: function get() {
return this._latency || 0;
}
}, {
key: "maxLatency",
get: function get() {
var config = this.config,
levelDetails = this.levelDetails;
if (config.liveMaxLatencyDuration !== undefined) {
return config.liveMaxLatencyDuration;
}
return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;
}
}, {
key: "targetLatency",
get: function get() {
var levelDetails = this.levelDetails;
if (levelDetails === null) {
return null;
}
var holdBack = levelDetails.holdBack,
partHoldBack = levelDetails.partHoldBack,
targetduration = levelDetails.targetduration;
var _this$config2 = this.config,
liveSyncDuration = _this$config2.liveSyncDuration,
liveSyncDurationCount = _this$config2.liveSyncDurationCount,
lowLatencyMode = _this$config2.lowLatencyMode;
var userConfig = this.hls.userConfig;
var targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;
if (userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {
targetLatency = liveSyncDuration !== undefined ? liveSyncDuration : liveSyncDurationCount * targetduration;
}
var maxLiveSyncOnStallIncrease = targetduration;
var liveSyncOnStallIncrease = 1.0;
return targetLatency + Math.min(this.stallCount * liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);
}
}, {
key: "liveSyncPosition",
get: function get() {
var liveEdge = this.estimateLiveEdge();
var targetLatency = this.targetLatency;
var levelDetails = this.levelDetails;
if (liveEdge === null || targetLatency === null || levelDetails === null) {
return null;
}
var edge = levelDetails.edge;
var syncPosition = liveEdge - targetLatency - this.edgeStalled;
var min = edge - levelDetails.totalduration;
var max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration);
return Math.min(Math.max(min, syncPosition), max);
}
}, {
key: "drift",
get: function get() {
var levelDetails = this.levelDetails;
if (levelDetails === null) {
return 1;
}
return levelDetails.drift;
}
}, {
key: "edgeStalled",
get: function get() {
var levelDetails = this.levelDetails;
if (levelDetails === null) {
return 0;
}
var maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3;
return Math.max(levelDetails.age - maxLevelUpdateAge, 0);
}
}, {
key: "forwardBufferLength",
get: function get() {
var media = this.media,
levelDetails = this.levelDetails;
if (!media || !levelDetails) {
return 0;
}
var bufferedRanges = media.buffered.length;
return bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge - this.currentTime;
}
}]);
return LatencyController;
}();
/***/ }),
/***/ "./src/controller/level-controller.ts":
/*!********************************************!*\
!*** ./src/controller/level-controller.ts ***!
\********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return LevelController; });
/* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_codecs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/codecs */ "./src/utils/codecs.ts");
/* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts");
/* harmony import */ var _base_playlist_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./base-playlist-controller */ "./src/controller/base-playlist-controller.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
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); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
/*
* Level Controller
*/
var chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());
var LevelController = /*#__PURE__*/function (_BasePlaylistControll) {
_inheritsLoose(LevelController, _BasePlaylistControll);
function LevelController(hls) {
var _this;
_this = _BasePlaylistControll.call(this, hls, '[level-controller]') || this;
_this._levels = [];
_this._firstLevel = -1;
_this._startLevel = void 0;
_this.currentLevelIndex = -1;
_this.manualLevelIndex = -1;
_this.onParsedComplete = void 0;
_this._registerListeners();
return _this;
}
var _proto = LevelController.prototype;
_proto._registerListeners = function _registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError, this);
};
_proto.destroy = function destroy() {
this._unregisterListeners();
this.manualLevelIndex = -1;
this._levels.length = 0;
_BasePlaylistControll.prototype.destroy.call(this);
};
_proto.startLoad = function startLoad() {
var levels = this._levels; // clean up live level details to force reload them, and reset load errors
levels.forEach(function (level) {
level.loadError = 0;
});
_BasePlaylistControll.prototype.startLoad.call(this);
};
_proto.onManifestLoaded = function onManifestLoaded(event, data) {
var levels = [];
var audioTracks = [];
var subtitleTracks = [];
var bitrateStart;
var levelSet = {};
var levelFromSet;
var resolutionFound = false;
var videoCodecFound = false;
var audioCodecFound = false; // regroup redundant levels together
data.levels.forEach(function (levelParsed) {
var attributes = levelParsed.attrs;
resolutionFound = resolutionFound || !!(levelParsed.width && levelParsed.height);
videoCodecFound = videoCodecFound || !!levelParsed.videoCodec;
audioCodecFound = audioCodecFound || !!levelParsed.audioCodec; // erase audio codec info if browser does not support mp4a.40.34.
// demuxer will autodetect codec and fallback to mpeg/audio
if (chromeOrFirefox && levelParsed.audioCodec && levelParsed.audioCodec.indexOf('mp4a.40.34') !== -1) {
levelParsed.audioCodec = undefined;
}
var levelKey = levelParsed.bitrate + "-" + levelParsed.attrs.RESOLUTION + "-" + levelParsed.attrs.CODECS;
levelFromSet = levelSet[levelKey];
if (!levelFromSet) {
levelFromSet = new _types_level__WEBPACK_IMPORTED_MODULE_0__["Level"](levelParsed);
levelSet[levelKey] = levelFromSet;
levels.push(levelFromSet);
} else {
levelFromSet.url.push(levelParsed.url);
}
if (attributes) {
if (attributes.AUDIO) {
Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["addGroupId"])(levelFromSet, 'audio', attributes.AUDIO);
}
if (attributes.SUBTITLES) {
Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["addGroupId"])(levelFromSet, 'text', attributes.SUBTITLES);
}
}
}); // remove audio-only level if we also have levels with video codecs or RESOLUTION signalled
if ((resolutionFound || videoCodecFound) && audioCodecFound) {
levels = levels.filter(function (_ref) {
var videoCodec = _ref.videoCodec,
width = _ref.width,
height = _ref.height;
return !!videoCodec || !!(width && height);
});
} // only keep levels with supported audio/video codecs
levels = levels.filter(function (_ref2) {
var audioCodec = _ref2.audioCodec,
videoCodec = _ref2.videoCodec;
return (!audioCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__["isCodecSupportedInMp4"])(audioCodec, 'audio')) && (!videoCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__["isCodecSupportedInMp4"])(videoCodec, 'video'));
});
if (data.audioTracks) {
audioTracks = data.audioTracks.filter(function (track) {
return !track.audioCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__["isCodecSupportedInMp4"])(track.audioCodec, 'audio');
}); // Assign ids after filtering as array indices by group-id
Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["assignTrackIdsByGroup"])(audioTracks);
}
if (data.subtitles) {
subtitleTracks = data.subtitles;
Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["assignTrackIdsByGroup"])(subtitleTracks);
}
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;
this.log("manifest loaded, " + levels.length + " level(s) found, first bitrate: " + bitrateStart);
break;
}
} // Audio is only alternate if manifest include a URI along with the audio group tag,
// and this is not an audio-only stream where levels contain audio-only
var audioOnly = audioCodecFound && !videoCodecFound;
var edata = {
levels: levels,
audioTracks: audioTracks,
subtitleTracks: subtitleTracks,
firstLevel: this._firstLevel,
stats: data.stats,
audio: audioCodecFound,
video: videoCodecFound,
altAudio: !audioOnly && audioTracks.some(function (t) {
return !!t.url;
})
};
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_PARSED, edata); // Initiate loading after all controllers have received MANIFEST_PARSED
if (this.hls.config.autoStartLoad || this.hls.forceStartLoad) {
this.hls.startLoad(this.hls.config.startPosition);
}
} else {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_INCOMPATIBLE_CODECS_ERROR,
fatal: true,
url: data.url,
reason: 'no level with compatible codecs found in manifest'
});
}
};
_proto.onError = function onError(event, data) {
_BasePlaylistControll.prototype.onError.call(this, event, data);
if (data.fatal) {
return;
} // Switch to redundant level when track fails to load
var context = data.context;
var level = this._levels[this.currentLevelIndex];
if (context && (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK && level.audioGroupIds && context.groupId === level.audioGroupIds[level.urlId] || context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK && level.textGroupIds && context.groupId === level.textGroupIds[level.urlId])) {
this.redundantFailover(this.currentLevelIndex);
return;
}
var levelError = false;
var levelSwitch = true;
var levelIndex; // try to recover not fatal errors
switch (data.details) {
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].FRAG_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].FRAG_LOAD_TIMEOUT:
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].KEY_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].KEY_LOAD_TIMEOUT:
if (data.frag) {
var _level = this._levels[data.frag.level]; // Set levelIndex when we're out of fragment retries
if (_level) {
_level.fragmentError++;
if (_level.fragmentError > this.hls.config.fragLoadingMaxRetry) {
levelIndex = data.frag.level;
}
} else {
levelIndex = data.frag.level;
}
}
break;
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_TIMEOUT:
// Do not perform level switch if an error occurred using delivery directives
// Attempt to reload level without directives first
if (context) {
if (context.deliveryDirectives) {
levelSwitch = false;
}
levelIndex = context.level;
}
levelError = true;
break;
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].REMUX_ALLOC_ERROR:
levelIndex = data.level;
levelError = true;
break;
}
if (levelIndex !== undefined) {
this.recoverLevel(data, levelIndex, levelError, levelSwitch);
}
}
/**
* Switch to a redundant stream if any available.
* If redundant stream is not available, emergency switch down if ABR mode is enabled.
*/
;
_proto.recoverLevel = function recoverLevel(errorEvent, levelIndex, levelError, levelSwitch) {
var errorDetails = errorEvent.details;
var level = this._levels[levelIndex];
level.loadError++;
if (levelError) {
var retrying = this.retryLoadingOrFail(errorEvent);
if (retrying) {
// boolean used to inform stream controller not to switch back to IDLE on non fatal error
errorEvent.levelRetry = true;
} else {
this.currentLevelIndex = -1;
return;
}
}
if (levelSwitch) {
var redundantLevels = level.url.length; // Try redundant fail-over until level.loadError reaches redundantLevels
if (redundantLevels > 1 && level.loadError < redundantLevels) {
errorEvent.levelRetry = true;
this.redundantFailover(levelIndex);
} else if (this.manualLevelIndex === -1) {
// Search for available level in auto level selection mode, cycling from highest to lowest bitrate
var nextLevel = levelIndex === 0 ? this._levels.length - 1 : levelIndex - 1;
if (this.currentLevelIndex !== nextLevel && this._levels[nextLevel].loadError === 0) {
this.warn(errorDetails + ": switch to " + nextLevel);
errorEvent.levelRetry = true;
this.hls.nextAutoLevel = nextLevel;
}
}
}
};
_proto.redundantFailover = function redundantFailover(levelIndex) {
var level = this._levels[levelIndex];
var redundantLevels = level.url.length;
if (redundantLevels > 1) {
// Update the url id of all levels so that we stay on the same set of variants when level switching
var newUrlId = (level.urlId + 1) % redundantLevels;
this.warn("Switching to redundant URL-id " + newUrlId);
this._levels.forEach(function (level) {
level.urlId = newUrlId;
});
this.level = levelIndex;
}
} // reset errors on the successful load of a fragment
;
_proto.onFragLoaded = function onFragLoaded(event, _ref3) {
var frag = _ref3.frag;
if (frag !== undefined && frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN) {
var level = this._levels[frag.level];
if (level !== undefined) {
level.fragmentError = 0;
level.loadError = 0;
}
}
};
_proto.onLevelLoaded = function onLevelLoaded(event, data) {
var _data$deliveryDirecti2;
var level = data.level,
details = data.details;
var curLevel = this._levels[level];
if (!curLevel) {
var _data$deliveryDirecti;
this.warn("Invalid level index " + level);
if ((_data$deliveryDirecti = data.deliveryDirectives) !== null && _data$deliveryDirecti !== void 0 && _data$deliveryDirecti.skip) {
details.deltaUpdateFailed = true;
}
return;
} // only process level loaded events matching with expected level
if (level === this.currentLevelIndex) {
// reset level load error counter on successful level loaded only if there is no issues with fragments
if (curLevel.fragmentError === 0) {
curLevel.loadError = 0;
this.retryCount = 0;
}
this.playlistLoaded(level, data, curLevel.details);
} else if ((_data$deliveryDirecti2 = data.deliveryDirectives) !== null && _data$deliveryDirecti2 !== void 0 && _data$deliveryDirecti2.skip) {
// received a delta playlist update that cannot be merged
details.deltaUpdateFailed = true;
}
};
_proto.onAudioTrackSwitched = function onAudioTrackSwitched(event, data) {
var currentLevel = this.hls.levels[this.currentLevelIndex];
if (!currentLevel) {
return;
}
if (currentLevel.audioGroupIds) {
var urlId = -1;
var audioGroupId = this.hls.audioTracks[data.id].groupId;
for (var i = 0; i < currentLevel.audioGroupIds.length; i++) {
if (currentLevel.audioGroupIds[i] === audioGroupId) {
urlId = i;
break;
}
}
if (urlId !== currentLevel.urlId) {
currentLevel.urlId = urlId;
this.startLoad();
}
}
};
_proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
var level = this.currentLevelIndex;
var currentLevel = this._levels[level];
if (this.canLoad && currentLevel && currentLevel.url.length > 0) {
var id = currentLevel.urlId;
var url = currentLevel.url[id];
if (hlsUrlParameters) {
try {
url = hlsUrlParameters.addDirectives(url);
} catch (error) {
this.warn("Could not construct new URL with HLS Delivery Directives: " + error);
}
}
this.log("Attempt loading level index " + level + (hlsUrlParameters ? ' at sn ' + hlsUrlParameters.msn + ' part ' + hlsUrlParameters.part : '') + " with URL-id " + id + " " + url); // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
// console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);
this.clearTimer();
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADING, {
url: url,
level: level,
id: id,
deliveryDirectives: hlsUrlParameters || null
});
}
};
_proto.removeLevel = function removeLevel(levelIndex, urlId) {
var filterLevelAndGroupByIdIndex = function filterLevelAndGroupByIdIndex(url, id) {
return id !== urlId;
};
var levels = this._levels.filter(function (level, index) {
if (index !== levelIndex) {
return true;
}
if (level.url.length > 1 && urlId !== undefined) {
level.url = level.url.filter(filterLevelAndGroupByIdIndex);
if (level.audioGroupIds) {
level.audioGroupIds = level.audioGroupIds.filter(filterLevelAndGroupByIdIndex);
}
if (level.textGroupIds) {
level.textGroupIds = level.textGroupIds.filter(filterLevelAndGroupByIdIndex);
}
level.urlId = 0;
return true;
}
return false;
}).map(function (level, index) {
var details = level.details;
if (details !== null && details !== void 0 && details.fragments) {
details.fragments.forEach(function (fragment) {
fragment.level = index;
});
}
return level;
});
this._levels = levels;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVELS_UPDATED, {
levels: levels
});
};
_createClass(LevelController, [{
key: "levels",
get: function get() {
if (this._levels.length === 0) {
return null;
}
return this._levels;
}
}, {
key: "level",
get: function get() {
return this.currentLevelIndex;
},
set: function set(newLevel) {
var _levels$newLevel;
var levels = this._levels;
if (levels.length === 0) {
return;
}
if (this.currentLevelIndex === newLevel && (_levels$newLevel = levels[newLevel]) !== null && _levels$newLevel !== void 0 && _levels$newLevel.details) {
return;
} // check if level idx is valid
if (newLevel < 0 || newLevel >= levels.length) {
// invalid level id given, trigger error
var fatal = newLevel < 0;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].OTHER_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_SWITCH_ERROR,
level: newLevel,
fatal: fatal,
reason: 'invalid level idx'
});
if (fatal) {
return;
}
newLevel = Math.min(newLevel, levels.length - 1);
} // stopping live reloading timer if any
this.clearTimer();
var lastLevelIndex = this.currentLevelIndex;
var lastLevel = levels[lastLevelIndex];
var level = levels[newLevel];
this.log("switching to level " + newLevel + " from " + lastLevelIndex);
this.currentLevelIndex = newLevel;
var levelSwitchingData = _extends({}, level, {
level: newLevel,
maxBitrate: level.maxBitrate,
uri: level.uri,
urlId: level.urlId
}); // @ts-ignore
delete levelSwitchingData._urlId;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_SWITCHING, levelSwitchingData); // check if we need to load playlist for this level
var levelDetails = level.details;
if (!levelDetails || levelDetails.live) {
// level not retrieved yet, or live playlist we need to (re)load it
var hlsUrlParameters = this.switchParams(level.uri, lastLevel === null || lastLevel === void 0 ? void 0 : lastLevel.details);
this.loadPlaylist(hlsUrlParameters);
}
}
}, {
key: "manualLevel",
get: function get() {
return this.manualLevelIndex;
},
set: function set(newLevel) {
this.manualLevelIndex = 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.manualLevelIndex !== -1) {
return this.manualLevelIndex;
} else {
return this.hls.nextAutoLevel;
}
},
set: function set(nextLevel) {
this.level = nextLevel;
if (this.manualLevelIndex === -1) {
this.hls.nextAutoLevel = nextLevel;
}
}
}]);
return LevelController;
}(_base_playlist_controller__WEBPACK_IMPORTED_MODULE_5__["default"]);
/***/ }),
/***/ "./src/controller/level-helper.ts":
/*!****************************************!*\
!*** ./src/controller/level-helper.ts ***!
\****************************************/
/*! exports provided: addGroupId, assignTrackIdsByGroup, updatePTS, updateFragPTSDTS, mergeDetails, mapPartIntersection, mapFragmentIntersection, adjustSliding, addSliding, computeReloadInterval, getFragmentWithSN, getPartWith */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addGroupId", function() { return addGroupId; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "assignTrackIdsByGroup", function() { return assignTrackIdsByGroup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updatePTS", function() { return updatePTS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateFragPTSDTS", function() { return updateFragPTSDTS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeDetails", function() { return mergeDetails; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapPartIntersection", function() { return mapPartIntersection; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapFragmentIntersection", function() { return mapFragmentIntersection; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "adjustSliding", function() { return adjustSliding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addSliding", function() { return addSliding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "computeReloadInterval", function() { return computeReloadInterval; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFragmentWithSN", function() { return getFragmentWithSN; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPartWith", function() { return getPartWith; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/**
* @module LevelHelper
* Providing methods dealing with playlist sliding and drift
* */
function addGroupId(level, type, id) {
switch (type) {
case 'audio':
if (!level.audioGroupIds) {
level.audioGroupIds = [];
}
level.audioGroupIds.push(id);
break;
case 'text':
if (!level.textGroupIds) {
level.textGroupIds = [];
}
level.textGroupIds.push(id);
break;
}
}
function assignTrackIdsByGroup(tracks) {
var groups = {};
tracks.forEach(function (track) {
var groupId = track.groupId || '';
track.id = groups[groupId] = groups[groupId] || 0;
groups[groupId]++;
});
}
function updatePTS(fragments, fromIdx, toIdx) {
var fragFrom = fragments[fromIdx];
var fragTo = fragments[toIdx];
updateFromToPTS(fragFrom, fragTo);
}
function updateFromToPTS(fragFrom, fragTo) {
var fragToPTS = fragTo.startPTS; // if we know startPTS[toIdx]
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(fragToPTS)) {
// update fragment duration.
// it helps to fix drifts between playlist reported duration and fragment real duration
var duration = 0;
var frag;
if (fragTo.sn > fragFrom.sn) {
duration = fragToPTS - fragFrom.start;
frag = fragFrom;
} else {
duration = fragFrom.start - fragToPTS;
frag = fragTo;
} // TODO? Drift can go either way, or the playlist could be completely accurate
// console.assert(duration > 0,
// `duration of ${duration} computed for frag ${frag.sn}, level ${frag.level}, there should be some duration drift between playlist and fragment!`);
if (frag.duration !== duration) {
frag.duration = duration;
} // we dont know startPTS[toIdx]
} else if (fragTo.sn > fragFrom.sn) {
var contiguous = fragFrom.cc === fragTo.cc; // TODO: With part-loading end/durations we need to confirm the whole fragment is loaded before using (or setting) minEndPTS
if (contiguous && fragFrom.minEndPTS) {
fragTo.start = fragFrom.start + (fragFrom.minEndPTS - fragFrom.start);
} else {
fragTo.start = fragFrom.start + fragFrom.duration;
}
} else {
fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);
}
}
function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
var parsedMediaDuration = endPTS - startPTS;
if (parsedMediaDuration <= 0) {
_utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('Fragment should have a positive duration', frag);
endPTS = startPTS + frag.duration;
endDTS = startDTS + frag.duration;
}
var maxStartPTS = startPTS;
var minEndPTS = endPTS;
var fragStartPts = frag.startPTS;
var fragEndPts = frag.endPTS;
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(fragStartPts)) {
// delta PTS between audio and video
var deltaPTS = Math.abs(fragStartPts - startPTS);
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.deltaPTS)) {
frag.deltaPTS = deltaPTS;
} else {
frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
}
maxStartPTS = Math.max(startPTS, fragStartPts);
startPTS = Math.min(startPTS, fragStartPts);
startDTS = Math.min(startDTS, frag.startDTS);
minEndPTS = Math.min(endPTS, fragEndPts);
endPTS = Math.max(endPTS, fragEndPts);
endDTS = Math.max(endDTS, frag.endDTS);
}
frag.duration = endPTS - startPTS;
var drift = startPTS - frag.start;
frag.appendedPTS = endPTS;
frag.start = frag.startPTS = startPTS;
frag.maxStartPTS = maxStartPTS;
frag.startDTS = startDTS;
frag.endPTS = endPTS;
frag.minEndPTS = minEndPTS;
frag.endDTS = endDTS;
var sn = frag.sn; // 'initSegment'
// exit if sn out of range
if (!details || sn < details.startSN || sn > details.endSN) {
return 0;
}
var i;
var fragIdx = sn - details.startSN;
var fragments = details.fragments; // update frag reference in fragments array
// rationale is that fragments array might not contain this frag object.
// this will happen 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--) {
updateFromToPTS(fragments[i], fragments[i - 1]);
} // adjust fragment PTS/duration from seqnum to last frag
for (i = fragIdx; i < fragments.length - 1; i++) {
updateFromToPTS(fragments[i], fragments[i + 1]);
}
if (details.fragmentHint) {
updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);
}
details.PTSKnown = details.alignedSliding = true;
return drift;
}
function mergeDetails(oldDetails, newDetails) {
// Track the last initSegment processed. Initialize it to the last one on the timeline.
var currentInitSegment = null;
var oldFragments = oldDetails.fragments;
for (var i = oldFragments.length - 1; i >= 0; i--) {
var oldInit = oldFragments[i].initSegment;
if (oldInit) {
currentInitSegment = oldInit;
break;
}
}
if (oldDetails.fragmentHint) {
// prevent PTS and duration from being adjusted on the next hint
delete oldDetails.fragmentHint.endPTS;
} // check if old/new playlists have fragments in common
// loop through overlapping SN and update startPTS , cc, and duration if any found
var ccOffset = 0;
var PTSFrag;
mapFragmentIntersection(oldDetails, newDetails, function (oldFrag, newFrag) {
var _currentInitSegment;
if (oldFrag.relurl) {
// Do not compare CC if the old fragment has no url. This is a level.fragmentHint used by LL-HLS parts.
// It maybe be off by 1 if it was created before any parts or discontinuity tags were appended to the end
// of the playlist.
ccOffset = oldFrag.cc - newFrag.cc;
}
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(oldFrag.startPTS) && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(oldFrag.endPTS)) {
newFrag.start = newFrag.startPTS = oldFrag.startPTS;
newFrag.startDTS = oldFrag.startDTS;
newFrag.appendedPTS = oldFrag.appendedPTS;
newFrag.maxStartPTS = oldFrag.maxStartPTS;
newFrag.endPTS = oldFrag.endPTS;
newFrag.endDTS = oldFrag.endDTS;
newFrag.minEndPTS = oldFrag.minEndPTS;
newFrag.duration = oldFrag.endPTS - oldFrag.startPTS;
if (newFrag.duration) {
PTSFrag = newFrag;
} // PTS is known when any segment has startPTS and endPTS
newDetails.PTSKnown = newDetails.alignedSliding = true;
}
newFrag.elementaryStreams = oldFrag.elementaryStreams;
newFrag.loader = oldFrag.loader;
newFrag.stats = oldFrag.stats;
newFrag.urlId = oldFrag.urlId;
if (oldFrag.initSegment) {
newFrag.initSegment = oldFrag.initSegment;
currentInitSegment = oldFrag.initSegment;
} else if (!newFrag.initSegment || newFrag.initSegment.relurl == ((_currentInitSegment = currentInitSegment) === null || _currentInitSegment === void 0 ? void 0 : _currentInitSegment.relurl)) {
newFrag.initSegment = currentInitSegment;
}
});
if (newDetails.skippedSegments) {
newDetails.deltaUpdateFailed = newDetails.fragments.some(function (frag) {
return !frag;
});
if (newDetails.deltaUpdateFailed) {
_utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('[level-helper] Previous playlist missing segments skipped in delta playlist');
for (var _i = newDetails.skippedSegments; _i--;) {
newDetails.fragments.shift();
}
newDetails.startSN = newDetails.fragments[0].sn;
newDetails.startCC = newDetails.fragments[0].cc;
}
}
var newFragments = newDetails.fragments;
if (ccOffset) {
_utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('discontinuity sliding from playlist, take drift into account');
for (var _i2 = 0; _i2 < newFragments.length; _i2++) {
newFragments[_i2].cc += ccOffset;
}
}
if (newDetails.skippedSegments) {
newDetails.startCC = newDetails.fragments[0].cc;
} // Merge parts
mapPartIntersection(oldDetails.partList, newDetails.partList, function (oldPart, newPart) {
newPart.elementaryStreams = oldPart.elementaryStreams;
newPart.stats = oldPart.stats;
}); // 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
adjustSliding(oldDetails, newDetails);
}
if (newFragments.length) {
newDetails.totalduration = newDetails.edge - newFragments[0].start;
}
newDetails.driftStartTime = oldDetails.driftStartTime;
newDetails.driftStart = oldDetails.driftStart;
var advancedDateTime = newDetails.advancedDateTime;
if (newDetails.advanced && advancedDateTime) {
var edge = newDetails.edge;
if (!newDetails.driftStart) {
newDetails.driftStartTime = advancedDateTime;
newDetails.driftStart = edge;
}
newDetails.driftEndTime = advancedDateTime;
newDetails.driftEnd = edge;
} else {
newDetails.driftEndTime = oldDetails.driftEndTime;
newDetails.driftEnd = oldDetails.driftEnd;
newDetails.advancedDateTime = oldDetails.advancedDateTime;
}
}
function mapPartIntersection(oldParts, newParts, intersectionFn) {
if (oldParts && newParts) {
var delta = 0;
for (var i = 0, len = oldParts.length; i <= len; i++) {
var _oldPart = oldParts[i];
var _newPart = newParts[i + delta];
if (_oldPart && _newPart && _oldPart.index === _newPart.index && _oldPart.fragment.sn === _newPart.fragment.sn) {
intersectionFn(_oldPart, _newPart);
} else {
delta--;
}
}
}
}
function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {
var skippedSegments = newDetails.skippedSegments;
var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;
var end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;
var delta = newDetails.startSN - oldDetails.startSN;
var newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
var oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;
for (var i = start; i <= end; i++) {
var _oldFrag = oldFrags[delta + i];
var _newFrag = newFrags[i];
if (skippedSegments && !_newFrag && i < skippedSegments) {
// Fill in skipped segments in delta playlist
_newFrag = newDetails.fragments[i] = _oldFrag;
}
if (_oldFrag && _newFrag) {
intersectionFn(_oldFrag, _newFrag);
}
}
}
function adjustSliding(oldDetails, newDetails) {
var delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;
var oldFragments = oldDetails.fragments;
if (delta < 0 || delta >= oldFragments.length) {
return;
}
addSliding(newDetails, oldFragments[delta].start);
}
function addSliding(details, start) {
if (start) {
var fragments = details.fragments;
for (var i = details.skippedSegments; i < fragments.length; i++) {
fragments[i].start += start;
}
if (details.fragmentHint) {
details.fragmentHint.start += start;
}
}
}
function computeReloadInterval(newDetails, stats) {
var reloadInterval = 1000 * newDetails.levelTargetDuration;
var reloadIntervalAfterMiss = reloadInterval / 2;
var timeSinceLastModified = newDetails.age;
var useLastModified = timeSinceLastModified > 0 && timeSinceLastModified < reloadInterval * 3;
var roundTrip = stats.loading.end - stats.loading.start;
var estimatedTimeUntilUpdate;
var availabilityDelay = newDetails.availabilityDelay; // let estimate = 'average';
if (newDetails.updated === false) {
if (useLastModified) {
// estimate = 'miss round trip';
// We should have had a hit so try again in the time it takes to get a response,
// but no less than 1/3 second.
var minRetry = 333 * newDetails.misses;
estimatedTimeUntilUpdate = Math.max(Math.min(reloadIntervalAfterMiss, roundTrip * 2), minRetry);
newDetails.availabilityDelay = (newDetails.availabilityDelay || 0) + estimatedTimeUntilUpdate;
} else {
// estimate = 'miss half average';
// 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.
estimatedTimeUntilUpdate = reloadIntervalAfterMiss;
}
} else if (useLastModified) {
// estimate = 'next modified date';
// Get the closest we've been to timeSinceLastModified on update
availabilityDelay = Math.min(availabilityDelay || reloadInterval / 2, timeSinceLastModified);
newDetails.availabilityDelay = availabilityDelay;
estimatedTimeUntilUpdate = availabilityDelay + reloadInterval - timeSinceLastModified;
} else {
estimatedTimeUntilUpdate = reloadInterval - roundTrip;
} // console.log(`[computeReloadInterval] live reload ${newDetails.updated ? 'REFRESHED' : 'MISSED'}`,
// '\n method', estimate,
// '\n estimated time until update =>', estimatedTimeUntilUpdate,
// '\n average target duration', reloadInterval,
// '\n time since modified', timeSinceLastModified,
// '\n time round trip', roundTrip,
// '\n availability delay', availabilityDelay);
return Math.round(estimatedTimeUntilUpdate);
}
function getFragmentWithSN(level, sn, fragCurrent) {
if (!level || !level.details) {
return null;
}
var levelDetails = level.details;
var fragment = levelDetails.fragments[sn - levelDetails.startSN];
if (fragment) {
return fragment;
}
fragment = levelDetails.fragmentHint;
if (fragment && fragment.sn === sn) {
return fragment;
}
if (sn < levelDetails.startSN && fragCurrent && fragCurrent.sn === sn) {
return fragCurrent;
}
return null;
}
function getPartWith(level, sn, partIndex) {
if (!level || !level.details) {
return null;
}
var partList = level.details.partList;
if (partList) {
for (var i = partList.length; i--;) {
var part = partList[i];
if (part.index === partIndex && part.fragment.sn === sn) {
return part;
}
}
}
return null;
}
/***/ }),
/***/ "./src/controller/stream-controller.ts":
/*!*********************************************!*\
!*** ./src/controller/stream-controller.ts ***!
\*********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return StreamController; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base-stream-controller */ "./src/controller/base-stream-controller.ts");
/* harmony import */ var _is_supported__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../is-supported */ "./src/is-supported.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
/* harmony import */ var _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../demux/transmuxer-interface */ "./src/demux/transmuxer-interface.ts");
/* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../types/transmuxer */ "./src/types/transmuxer.ts");
/* harmony import */ var _gap_controller__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./gap-controller */ "./src/controller/gap-controller.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
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); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var TICK_INTERVAL = 100; // how often to tick in ms
var StreamController = /*#__PURE__*/function (_BaseStreamController) {
_inheritsLoose(StreamController, _BaseStreamController);
function StreamController(hls, fragmentTracker) {
var _this;
_this = _BaseStreamController.call(this, hls, fragmentTracker, '[stream-controller]') || this;
_this.audioCodecSwap = false;
_this.gapController = null;
_this.level = -1;
_this._forceStartLoad = false;
_this.altAudio = false;
_this.audioOnly = false;
_this.fragPlaying = null;
_this.onvplaying = null;
_this.onvseeked = null;
_this.fragLastKbps = 0;
_this.stalled = false;
_this.couldBacktrack = false;
_this.audioCodecSwitch = false;
_this.videoBuffer = null;
_this._registerListeners();
return _this;
}
var _proto = StreamController.prototype;
_proto._registerListeners = function _registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, this.onError, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_CREATED, this.onBufferCreated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVELS_UPDATED, this.onLevelsUpdated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, this.onError, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_CREATED, this.onBufferCreated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVELS_UPDATED, this.onLevelsUpdated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
};
_proto.onHandlerDestroying = function onHandlerDestroying() {
this._unregisterListeners();
this.onMediaDetaching();
};
_proto.startLoad = function startLoad(startPosition) {
if (this.levels) {
var lastCurrentTime = this.lastCurrentTime,
hls = this.hls;
this.stopLoad();
this.setInterval(TICK_INTERVAL);
this.level = -1;
this.fragLoadError = 0;
if (!this.startFragRequested) {
// determine load level
var startLevel = hls.startLevel;
if (startLevel === -1) {
if (hls.config.testBandwidth) {
// -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
startLevel = 0;
this.bitrateTest = true;
} else {
startLevel = hls.nextAutoLevel;
}
} // 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) {
this.log("Override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3));
startPosition = lastCurrentTime;
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
this.tick();
} else {
this._forceStartLoad = true;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].STOPPED;
}
};
_proto.stopLoad = function stopLoad() {
this._forceStartLoad = false;
_BaseStreamController.prototype.stopLoad.call(this);
};
_proto.doTick = function doTick() {
switch (this.state) {
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE:
this.doTickIdle();
break;
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL:
{
var _levels$level;
var levels = this.levels,
level = this.level;
var details = levels === null || levels === void 0 ? void 0 : (_levels$level = levels[level]) === null || _levels$level === void 0 ? void 0 : _levels$level.details;
if (details && (!details.live || this.levelLastLoaded === this.level)) {
if (this.waitForCdnTuneIn(details)) {
break;
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
break;
}
break;
}
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING_WAITING_RETRY:
{
var _this$media;
var now = self.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) !== null && _this$media !== void 0 && _this$media.seeking) {
this.log('retryDate reached, switch back to IDLE state');
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
}
break;
default:
break;
} // check buffer
// check/update current fragment
this.onTickEnd();
};
_proto.onTickEnd = function onTickEnd() {
_BaseStreamController.prototype.onTickEnd.call(this);
this.checkBuffer();
this.checkFragmentChanged();
};
_proto.doTickIdle = function doTickIdle() {
var _frag$decryptdata, _frag$decryptdata2;
var hls = this.hls,
levelLastLoaded = this.levelLastLoaded,
levels = this.levels,
media = this.media;
var config = hls.config,
level = hls.nextLoadLevel; // if start level not parsed yet OR
// if video not attached AND start fragment already requested OR start frag prefetch not enabled
// exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
if (levelLastLoaded === null || !media && (this.startFragRequested || !config.startFragPrefetch)) {
return;
} // If the "main" level is audio-only but we are loading an alternate track in the same group, do not load anything
if (this.altAudio && this.audioOnly) {
return;
}
if (!levels || !levels[level]) {
return;
}
var levelInfo = levels[level]; // if buffer length is less than maxBufLen try to load a new fragment
// 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 (!levelDetails || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL || levelDetails.live && this.levelLastLoaded !== level) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL;
return;
}
var bufferInfo = this.getFwdBufferInfo(this.mediaBuffer ? this.mediaBuffer : media, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN);
if (bufferInfo === null) {
return;
}
var bufferLen = bufferInfo.len; // 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
var maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate); // Stay idle if we are still with buffer margins
if (bufferLen >= maxBufLen) {
return;
}
if (this._streamEnded(bufferInfo, levelDetails)) {
var data = {};
if (this.altAudio) {
data.type = 'video';
}
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_EOS, data);
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ENDED;
return;
}
var targetBufferTime = bufferInfo.end;
var frag = this.getNextFragment(targetBufferTime, levelDetails); // Avoid backtracking after seeking or switching by loading an earlier segment in streams that could backtrack
if (this.couldBacktrack && !this.fragPrevious && frag && frag.sn !== 'initSegment') {
var fragIdx = frag.sn - levelDetails.startSN;
if (fragIdx > 1) {
frag = levelDetails.fragments[fragIdx - 1];
this.fragmentTracker.removeFragment(frag);
}
} // Avoid loop loading by using nextLoadPosition set for backtracking
if (frag && this.fragmentTracker.getState(frag) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].OK && this.nextLoadPosition > targetBufferTime) {
// Cleanup the fragment tracker before trying to find the next unbuffered fragment
var type = this.audioOnly && !this.altAudio ? _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO : _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].VIDEO;
this.afterBufferFlushed(media, type, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN);
frag = this.getNextFragment(this.nextLoadPosition, levelDetails);
}
if (!frag) {
return;
}
if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {
frag = frag.initSegment;
} // We want to load the key if we're dealing with an identity key, because we will decrypt
// this content using the key we fetch. Other keys will be handled by the DRM CDM via EME.
if (((_frag$decryptdata = frag.decryptdata) === null || _frag$decryptdata === void 0 ? void 0 : _frag$decryptdata.keyFormat) === 'identity' && !((_frag$decryptdata2 = frag.decryptdata) !== null && _frag$decryptdata2 !== void 0 && _frag$decryptdata2.key)) {
this.loadKey(frag, levelDetails);
} else {
this.loadFragment(frag, levelDetails, targetBufferTime);
}
};
_proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) {
var _this$media2;
// Check if fragment is not loaded
var fragState = this.fragmentTracker.getState(frag);
this.fragCurrent = frag; // Use data from loaded backtracked fragment if available
if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].BACKTRACKED) {
var data = this.fragmentTracker.getBacktrackData(frag);
if (data) {
this._handleFragmentLoadProgress(data);
this._handleFragmentLoadComplete(data);
return;
} else {
fragState = _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].NOT_LOADED;
}
}
if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].NOT_LOADED || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].PARTIAL) {
if (frag.sn === 'initSegment') {
this._loadInitSegment(frag);
} else if (this.bitrateTest) {
frag.bitrateTest = true;
this.log("Fragment " + frag.sn + " of level " + frag.level + " is being downloaded to test bitrate and will not be buffered");
this._loadBitrateTestFrag(frag);
} else {
this.startFragRequested = true;
_BaseStreamController.prototype.loadFragment.call(this, frag, levelDetails, targetBufferTime);
}
} else if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].APPENDING) {
// Lower the buffer size and try again
if (this.reduceMaxBufferLength(frag.duration)) {
this.fragmentTracker.removeFragment(frag);
}
} else if (((_this$media2 = this.media) === null || _this$media2 === void 0 ? void 0 : _this$media2.buffered.length) === 0) {
// Stop gap for bad tracker / buffer flush behavior
this.fragmentTracker.removeAllFragments();
}
};
_proto.getAppendedFrag = function getAppendedFrag(position) {
var fragOrPart = this.fragmentTracker.getAppendedFrag(position, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN);
if (fragOrPart && 'fragment' in fragOrPart) {
return fragOrPart.fragment;
}
return fragOrPart;
};
_proto.getBufferedFrag = function getBufferedFrag(position) {
return this.fragmentTracker.getBufferedFrag(position, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN);
};
_proto.followingBufferedFrag = function followingBufferedFrag(frag) {
if (frag) {
// try to get range of next fragment (500ms after this range)
return this.getBufferedFrag(frag.end + 0.5);
}
return null;
}
/*
on immediate level switch :
- pause playback if playing
- cancel any pending load request
- and trigger a buffer flush
*/
;
_proto.immediateLevelSwitch = function immediateLevelSwitch() {
this.abortCurrentFrag();
this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
}
/**
* 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
*/
;
_proto.nextLevelSwitch = function nextLevelSwitch() {
var levels = this.levels,
media = this.media; // ensure that media is defined and that metadata are available (to retrieve currentTime)
if (media !== null && media !== void 0 && media.readyState) {
var fetchdelay;
var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
if (fragPlayingCurrent && fragPlayingCurrent.start > 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.start - 1);
}
if (!media.paused && levels) {
// add a safety delay of 1s
var nextLevelId = this.hls.nextLoadLevel;
var nextLevel = levels[nextLevelId];
var fragLastKbps = this.fragLastKbps;
if (fragLastKbps && this.fragCurrent) {
fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1000 * fragLastKbps) + 1;
} else {
fetchdelay = 0;
}
} else {
fetchdelay = 0;
} // this.log('fetchdelay:'+fetchdelay);
// find buffer range that will be reached once new fragment will be fetched
var bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
if (bufferedFrag) {
// we can flush buffer range following this one without stalling playback
var nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
if (nextBufferedFrag) {
// if we are here, we can also cancel any loading/demuxing in progress, as they are useless
this.abortCurrentFrag(); // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback.
var maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;
var fragDuration = nextBufferedFrag.duration;
var startPts = Math.max(bufferedFrag.end, maxStart + Math.min(Math.max(fragDuration - this.config.maxFragLookUpTolerance, fragDuration * 0.5), fragDuration * 0.75));
this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
}
}
}
};
_proto.abortCurrentFrag = function abortCurrentFrag() {
var fragCurrent = this.fragCurrent;
this.fragCurrent = null;
if (fragCurrent !== null && fragCurrent !== void 0 && fragCurrent.loader) {
fragCurrent.loader.abort();
}
if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].KEY_LOADING) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
this.nextLoadPosition = this.getLoadPosition();
};
_proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset) {
_BaseStreamController.prototype.flushMainBuffer.call(this, startOffset, endOffset, this.altAudio ? 'video' : null);
};
_proto.onMediaAttached = function onMediaAttached(event, data) {
_BaseStreamController.prototype.onMediaAttached.call(this, event, data);
var media = data.media;
this.onvplaying = this.onMediaPlaying.bind(this);
this.onvseeked = this.onMediaSeeked.bind(this);
media.addEventListener('playing', this.onvplaying);
media.addEventListener('seeked', this.onvseeked);
this.gapController = new _gap_controller__WEBPACK_IMPORTED_MODULE_10__["default"](this.config, media, this.fragmentTracker, this.hls);
};
_proto.onMediaDetaching = function onMediaDetaching() {
var media = this.media;
if (media) {
media.removeEventListener('playing', this.onvplaying);
media.removeEventListener('seeked', this.onvseeked);
this.onvplaying = this.onvseeked = null;
this.videoBuffer = null;
}
this.fragPlaying = null;
if (this.gapController) {
this.gapController.destroy();
this.gapController = null;
}
_BaseStreamController.prototype.onMediaDetaching.call(this);
};
_proto.onMediaPlaying = function onMediaPlaying() {
// tick to speed up FRAG_CHANGED triggering
this.tick();
};
_proto.onMediaSeeked = function onMediaSeeked() {
var media = this.media;
var currentTime = media ? media.currentTime : null;
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(currentTime)) {
this.log("Media seeked to " + currentTime.toFixed(3));
} // tick to speed up FRAG_CHANGED triggering
this.tick();
};
_proto.onManifestLoading = function onManifestLoading() {
// reset buffer on manifest loading
this.log('Trigger BUFFER_RESET');
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_RESET, undefined);
this.fragmentTracker.removeAllFragments();
this.couldBacktrack = this.stalled = false;
this.startPosition = this.lastCurrentTime = 0;
this.fragPlaying = null;
};
_proto.onManifestParsed = function onManifestParsed(event, data) {
var aac = false;
var heaac = false;
var 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 && !Object(_is_supported__WEBPACK_IMPORTED_MODULE_2__["changeTypeSupported"])();
if (this.audioCodecSwitch) {
this.log('Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
}
this.levels = data.levels;
this.startFragRequested = false;
};
_proto.onLevelLoading = function onLevelLoading(event, data) {
var levels = this.levels;
if (!levels || this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE) {
return;
}
var level = levels[data.level];
if (!level.details || level.details.live && this.levelLastLoaded !== data.level || this.waitForCdnTuneIn(level.details)) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL;
}
};
_proto.onLevelLoaded = function onLevelLoaded(event, data) {
var _curLevel$details;
var levels = this.levels;
var newLevelId = data.level;
var newDetails = data.details;
var duration = newDetails.totalduration;
if (!levels) {
this.warn("Levels were reset while loading level " + newLevelId);
return;
}
this.log("Level " + newLevelId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "], cc [" + newDetails.startCC + ", " + newDetails.endCC + "] duration:" + duration);
var fragCurrent = this.fragCurrent;
if (fragCurrent && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING_WAITING_RETRY)) {
if (fragCurrent.level !== data.level && fragCurrent.loader) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
fragCurrent.loader.abort();
}
}
var curLevel = levels[newLevelId];
var sliding = 0;
if (newDetails.live || (_curLevel$details = curLevel.details) !== null && _curLevel$details !== void 0 && _curLevel$details.live) {
if (!newDetails.fragments[0]) {
newDetails.deltaUpdateFailed = true;
}
if (newDetails.deltaUpdateFailed) {
return;
}
sliding = this.alignPlaylists(newDetails, curLevel.details);
} // override level info
curLevel.details = newDetails;
this.levelLastLoaded = newLevelId;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_UPDATED, {
details: newDetails,
level: newLevelId
}); // only switch back to IDLE state if we were waiting for level to start downloading a new fragment
if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL) {
if (this.waitForCdnTuneIn(newDetails)) {
// Wait for Low-Latency CDN Tune-in
return;
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
if (!this.startFragRequested) {
this.setStartPosition(newDetails, sliding);
} else if (newDetails.live) {
this.synchronizeToLiveEdge(newDetails);
} // trigger handler right now
this.tick();
};
_proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(data) {
var _frag$initSegment;
var frag = data.frag,
part = data.part,
payload = data.payload;
var levels = this.levels;
if (!levels) {
this.warn("Levels were reset while fragment load was in progress. Fragment " + frag.sn + " of level " + frag.level + " will not be buffered");
return;
}
var currentLevel = levels[frag.level];
var details = currentLevel.details;
if (!details) {
this.warn("Dropping fragment " + frag.sn + " of level " + frag.level + " after level details were reset");
return;
}
var videoCodec = currentLevel.videoCodec; // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
var accurateTimeOffset = details.PTSKnown || !details.live;
var initSegmentData = (_frag$initSegment = frag.initSegment) === null || _frag$initSegment === void 0 ? void 0 : _frag$initSegment.data;
var audioCodec = this._getAudioCodec(currentLevel); // transmux the MPEG-TS data to ISO-BMFF segments
// this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`);
var transmuxer = this.transmuxer = this.transmuxer || new _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_8__["default"](this.hls, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
var partIndex = part ? part.index : -1;
var partial = partIndex !== -1;
var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_9__["ChunkMetadata"](frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
var initPTS = this.initPTS[frag.cc];
transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
};
_proto.onAudioTrackSwitching = function onAudioTrackSwitching(event, data) {
// if any URL found on new audio track, it is an alternate audio track
var fromAltAudio = this.altAudio;
var altAudio = !!data.url;
var 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) {
this.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 !== null && fragCurrent !== void 0 && fragCurrent.loader) {
this.log('Switching to main audio track, cancel main fragment load');
fragCurrent.loader.abort();
} // destroy transmuxer to force init segment generation (following audio switch)
this.resetTransmuxer(); // switch to IDLE state to load new fragment
this.resetLoadingState();
} else if (this.audioOnly) {
// Reset audio transmuxer so when switching back to main audio we're not still appending where we left off
this.resetTransmuxer();
}
var hls = this.hls; // If switching from alt to main audio, flush all audio and trigger track switched
if (fromAltAudio) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_FLUSHING, {
startOffset: 0,
endOffset: Number.POSITIVE_INFINITY,
type: 'audio'
});
}
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHED, {
id: trackId
});
}
};
_proto.onAudioTrackSwitched = function onAudioTrackSwitched(event, data) {
var trackId = data.id;
var 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) {
this.log('Switching on alternate audio, use video.buffered to schedule main fragment loading');
this.mediaBuffer = videoBuffer;
}
}
this.altAudio = altAudio;
this.tick();
};
_proto.onBufferCreated = function onBufferCreated(event, data) {
var tracks = data.tracks;
var mediaTrack;
var name;
var 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') {
var videoTrack = tracks[type];
if (videoTrack) {
this.videoBuffer = videoTrack.buffer;
}
}
} else {
alternate = true;
}
}
if (alternate && mediaTrack) {
this.log("Alternate track found, use " + name + ".buffered to schedule main fragment loading");
this.mediaBuffer = mediaTrack.buffer;
} else {
this.mediaBuffer = this.media;
}
};
_proto.onFragBuffered = function onFragBuffered(event, data) {
var frag = data.frag,
part = data.part;
if (frag && frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN) {
return;
}
if (this.fragContextChanged(frag)) {
// If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
// Avoid setting state back to IDLE, since that will interfere with a level switch
this.warn("Fragment " + frag.sn + (part ? ' p: ' + part.index : '') + " of level " + frag.level + " finished buffering, but was aborted. state: " + this.state);
if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSED) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
return;
}
var stats = part ? part.stats : frag.stats;
this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first));
if (frag.sn !== 'initSegment') {
this.fragPrevious = frag;
}
this.fragBufferedComplete(frag, part);
};
_proto.onError = function onError(event, data) {
switch (data.details) {
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].FRAG_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].FRAG_LOAD_TIMEOUT:
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].KEY_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].KEY_LOAD_TIMEOUT:
this.onFragmentOrKeyLoadError(_types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN, data);
break;
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].LEVEL_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].LEVEL_LOAD_TIMEOUT:
if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR) {
if (data.fatal) {
// if fatal error, stop processing
this.warn("" + data.details);
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR;
} 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 === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
}
}
break;
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].BUFFER_FULL_ERROR:
// if in appending state
if (data.parent === 'main' && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSED)) {
var flushBuffer = true;
var bufferedInfo = this.getFwdBufferInfo(this.media, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN); // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
// reduce max buf len if current position is buffered
if (bufferedInfo && bufferedInfo.len > 0.5) {
flushBuffer = !this.reduceMaxBufferLength(bufferedInfo.len);
}
if (flushBuffer) {
// 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
this.warn('buffer full error also media.currentTime is not buffered, flush main'); // flush main buffer
this.immediateLevelSwitch();
}
this.resetLoadingState();
}
break;
default:
break;
}
} // Checks the health of the buffer and attempts to resolve playback stalls.
;
_proto.checkBuffer = function checkBuffer() {
var media = this.media,
gapController = this.gapController;
if (!media || !gapController || !media.readyState) {
// Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)
return;
} // Check combined buffer
var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(media);
if (!this.loadedmetadata && buffered.length) {
this.loadedmetadata = true;
this.seekToStartPos();
} else {
// Resolve gaps using the main buffer, whose ranges are the intersections of the A/V sourcebuffers
gapController.poll(this.lastCurrentTime);
}
this.lastCurrentTime = media.currentTime;
};
_proto.onFragLoadEmergencyAborted = function onFragLoadEmergencyAborted() {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["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.tickImmediate();
};
_proto.onBufferFlushed = function onBufferFlushed(event, _ref) {
var type = _ref.type;
if (type !== _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO || this.audioOnly && !this.altAudio) {
var media = (type === _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
this.afterBufferFlushed(media, type, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN);
}
};
_proto.onLevelsUpdated = function onLevelsUpdated(event, data) {
this.levels = data.levels;
};
_proto.swapAudioCodec = function swapAudioCodec() {
this.audioCodecSwap = !this.audioCodecSwap;
}
/**
* Seeks to the set startPosition if not equal to the mediaElement's current time.
* @private
*/
;
_proto.seekToStartPos = function seekToStartPos() {
var media = this.media;
var currentTime = media.currentTime;
var startPosition = this.startPosition; // 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
if (startPosition >= 0 && currentTime < startPosition) {
if (media.seeking) {
_utils_logger__WEBPACK_IMPORTED_MODULE_12__["logger"].log("could not seek to " + startPosition + ", already seeking at " + currentTime);
return;
}
var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(media);
var bufferStart = buffered.length ? buffered.start(0) : 0;
var delta = bufferStart - startPosition;
if (delta > 0 && (delta < this.config.maxBufferHole || delta < this.config.maxFragLookUpTolerance)) {
_utils_logger__WEBPACK_IMPORTED_MODULE_12__["logger"].log("adjusting start position by " + delta + " to match buffer start");
startPosition += delta;
this.startPosition = startPosition;
}
this.log("seek to target start position " + startPosition + " from current time " + currentTime);
media.currentTime = startPosition;
}
};
_proto._getAudioCodec = function _getAudioCodec(currentLevel) {
var audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
if (this.audioCodecSwap && audioCodec) {
this.log('Swapping audio codec');
if (audioCodec.indexOf('mp4a.40.5') !== -1) {
audioCodec = 'mp4a.40.2';
} else {
audioCodec = 'mp4a.40.5';
}
}
return audioCodec;
};
_proto._loadBitrateTestFrag = function _loadBitrateTestFrag(frag) {
var _this2 = this;
this._doFragLoad(frag).then(function (data) {
var hls = _this2.hls;
if (!data || hls.nextLoadLevel || _this2.fragContextChanged(frag)) {
return;
}
_this2.fragLoadError = 0;
_this2.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
_this2.startFragRequested = false;
_this2.bitrateTest = false;
var stats = frag.stats; // Bitrate tests fragments are neither parsed nor buffered
stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_LOADED, data);
});
};
_proto._handleTransmuxComplete = function _handleTransmuxComplete(transmuxResult) {
var _id3$samples;
var id = 'main';
var hls = this.hls;
var remuxResult = transmuxResult.remuxResult,
chunkMeta = transmuxResult.chunkMeta;
var context = this.getCurrentContext(chunkMeta);
if (!context) {
this.warn("The loading context changed while buffering fragment " + chunkMeta.sn + " of level " + chunkMeta.level + ". This chunk will not be buffered.");
this.resetLiveStartWhenNotLoaded(chunkMeta.level);
return;
}
var frag = context.frag,
part = context.part,
level = context.level;
var video = remuxResult.video,
text = remuxResult.text,
id3 = remuxResult.id3,
initSegment = remuxResult.initSegment; // The audio-stream-controller handles audio buffering if Hls.js is playing an alternate audio track
var audio = this.altAudio ? undefined : remuxResult.audio; // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
// If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
if (this.fragContextChanged(frag)) {
return;
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING;
if (initSegment) {
if (initSegment.tracks) {
this._bufferInitSegment(level, initSegment.tracks, frag, chunkMeta);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_PARSING_INIT_SEGMENT, {
frag: frag,
id: id,
tracks: initSegment.tracks
});
} // This would be nice if Number.isFinite acted as a typeguard, but it doesn't. See: https://github.com/Microsoft/TypeScript/issues/10038
var initPTS = initSegment.initPTS;
var timescale = initSegment.timescale;
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(initPTS)) {
this.initPTS[frag.cc] = initPTS;
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].INIT_PTS_FOUND, {
frag: frag,
id: id,
initPTS: initPTS,
timescale: timescale
});
}
} // Avoid buffering if backtracking this fragment
if (video && remuxResult.independent !== false) {
if (level.details) {
var startPTS = video.startPTS,
endPTS = video.endPTS,
startDTS = video.startDTS,
endDTS = video.endDTS;
if (part) {
part.elementaryStreams[video.type] = {
startPTS: startPTS,
endPTS: endPTS,
startDTS: startDTS,
endDTS: endDTS
};
} else {
if (video.firstKeyFrame && video.independent) {
this.couldBacktrack = true;
}
if (video.dropped && video.independent) {
// Backtrack if dropped frames create a gap after currentTime
var pos = this.getLoadPosition() + this.config.maxBufferHole;
if (pos < startPTS) {
this.backtrack(frag);
return;
} // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial
frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true);
}
}
frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS);
this.bufferFragmentData(video, frag, part, chunkMeta);
}
} else if (remuxResult.independent === false) {
this.backtrack(frag);
return;
}
if (audio) {
var _startPTS = audio.startPTS,
_endPTS = audio.endPTS,
_startDTS = audio.startDTS,
_endDTS = audio.endDTS;
if (part) {
part.elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO] = {
startPTS: _startPTS,
endPTS: _endPTS,
startDTS: _startDTS,
endDTS: _endDTS
};
}
frag.setElementaryStreamInfo(_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO, _startPTS, _endPTS, _startDTS, _endDTS);
this.bufferFragmentData(audio, frag, part, chunkMeta);
}
if (id3 !== null && id3 !== void 0 && (_id3$samples = id3.samples) !== null && _id3$samples !== void 0 && _id3$samples.length) {
var emittedID3 = {
frag: frag,
id: id,
samples: id3.samples
};
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_PARSING_METADATA, emittedID3);
}
if (text) {
var emittedText = {
frag: frag,
id: id,
samples: text.samples
};
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_PARSING_USERDATA, emittedText);
}
};
_proto._bufferInitSegment = function _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
var _this3 = this;
if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING) {
return;
}
this.audioOnly = !!tracks.audio && !tracks.video; // if audio track is expected to come from audio stream controller, discard any coming from main
if (this.altAudio && !this.audioOnly) {
delete tracks.audio;
} // include levelCodec in audio and video tracks
var audio = tracks.audio,
video = tracks.video,
audiovideo = tracks.audiovideo;
if (audio) {
var audioCodec = currentLevel.audioCodec;
var ua = navigator.userAgent.toLowerCase();
if (this.audioCodecSwitch) {
if (audioCodec) {
if (audioCodec.indexOf('mp4a.40.5') !== -1) {
audioCodec = 'mp4a.40.2';
} else {
audioCodec = 'mp4a.40.5';
}
} // In the case that AAC and HE-AAC audio codecs are signalled in manifest,
// force HE-AAC, as it seems that most browsers prefers it.
// don't force HE-AAC if mono stream, or in Firefox
if (audio.metadata.channelCount !== 1 && 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 && audio.container !== 'audio/mpeg') {
// Exclude mpeg audio
audioCodec = 'mp4a.40.2';
this.log("Android: force audio codec to " + audioCodec);
}
if (currentLevel.audioCodec && currentLevel.audioCodec !== audioCodec) {
this.log("Swapping manifest audio codec \"" + currentLevel.audioCodec + "\" for \"" + audioCodec + "\"");
}
audio.levelCodec = audioCodec;
audio.id = 'main';
this.log("Init audio buffer, container:" + audio.container + ", codecs[selected/level/parsed]=[" + (audioCodec || '') + "/" + (currentLevel.audioCodec || '') + "/" + audio.codec + "]");
}
if (video) {
video.levelCodec = currentLevel.videoCodec;
video.id = 'main';
this.log("Init video buffer, container:" + video.container + ", codecs[level/parsed]=[" + (currentLevel.videoCodec || '') + "/" + video.codec + "]");
}
if (audiovideo) {
this.log("Init audiovideo buffer, container:" + audiovideo.container + ", codecs[level/parsed]=[" + (currentLevel.attrs.CODECS || '') + "/" + audiovideo.codec + "]");
}
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_CODECS, tracks); // loop through tracks that are going to be provided to bufferController
Object.keys(tracks).forEach(function (trackName) {
var track = tracks[trackName];
var initSegment = track.initSegment;
if (initSegment !== null && initSegment !== void 0 && initSegment.byteLength) {
_this3.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_APPENDING, {
type: trackName,
data: initSegment,
frag: frag,
part: null,
chunkMeta: chunkMeta,
parent: frag.type
});
}
}); // trigger handler right now
this.tick();
};
_proto.backtrack = function backtrack(frag) {
this.couldBacktrack = true; // Causes findFragments to backtrack through fragments to find the keyframe
this.resetTransmuxer();
this.flushBufferGap(frag);
var data = this.fragmentTracker.backtrack(frag);
this.fragPrevious = null;
this.nextLoadPosition = frag.start;
if (data) {
this.resetFragmentLoading(frag);
} else {
// Change state to BACKTRACKING so that fragmentEntity.backtrack data can be added after _doFragLoad
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].BACKTRACKING;
}
};
_proto.checkFragmentChanged = function checkFragmentChanged() {
var video = this.media;
var fragPlayingCurrent = null;
if (video && video.readyState > 1 && video.seeking === false) {
var 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 (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].isBuffered(video, currentTime)) {
fragPlayingCurrent = this.getAppendedFrag(currentTime);
} else if (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].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.getAppendedFrag(currentTime + 0.1);
}
if (fragPlayingCurrent) {
var fragPlaying = this.fragPlaying;
var fragCurrentLevel = fragPlayingCurrent.level;
if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel || fragPlayingCurrent.urlId !== fragPlaying.urlId) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_CHANGED, {
frag: fragPlayingCurrent
});
if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_SWITCHED, {
level: fragCurrentLevel
});
}
this.fragPlaying = fragPlayingCurrent;
}
}
}
};
_createClass(StreamController, [{
key: "nextLevel",
get: function get() {
var frag = this.nextBufferedFrag;
if (frag) {
return frag.level;
} else {
return -1;
}
}
}, {
key: "currentLevel",
get: function get() {
var media = this.media;
if (media) {
var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
if (fragPlayingCurrent) {
return fragPlayingCurrent.level;
}
}
return -1;
}
}, {
key: "nextBufferedFrag",
get: function get() {
var media = this.media;
if (media) {
// first get end range of current fragment
var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
return this.followingBufferedFrag(fragPlayingCurrent);
} else {
return null;
}
}
}, {
key: "forceStartLoad",
get: function get() {
return this._forceStartLoad;
}
}]);
return StreamController;
}(_base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["default"]);
/***/ }),
/***/ "./src/controller/subtitle-stream-controller.ts":
/*!******************************************************!*\
!*** ./src/controller/subtitle-stream-controller.ts ***!
\******************************************************/
/*! exports provided: SubtitleStreamController */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubtitleStreamController", function() { return SubtitleStreamController; });
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _fragment_finders__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./fragment-finders */ "./src/controller/fragment-finders.ts");
/* harmony import */ var _utils_discontinuities__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/discontinuities */ "./src/utils/discontinuities.ts");
/* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts");
/* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts");
/* harmony import */ var _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./base-stream-controller */ "./src/controller/base-stream-controller.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts");
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); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var TICK_INTERVAL = 500; // how often to tick in ms
var SubtitleStreamController = /*#__PURE__*/function (_BaseStreamController) {
_inheritsLoose(SubtitleStreamController, _BaseStreamController);
function SubtitleStreamController(hls, fragmentTracker) {
var _this;
_this = _BaseStreamController.call(this, hls, fragmentTracker, '[subtitle-stream-controller]') || this;
_this.levels = [];
_this.currentTrackId = -1;
_this.tracksBuffered = [];
_this.mainDetails = null;
_this._registerListeners();
return _this;
}
var _proto = SubtitleStreamController.prototype;
_proto.onHandlerDestroying = function onHandlerDestroying() {
this._unregisterListeners();
this.mainDetails = null;
};
_proto._registerListeners = function _registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
};
_proto.startLoad = function startLoad() {
this.stopLoad();
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["State"].IDLE;
this.setInterval(TICK_INTERVAL);
this.tick();
};
_proto.onManifestLoading = function onManifestLoading() {
this.mainDetails = null;
this.fragmentTracker.removeAllFragments();
};
_proto.onLevelLoaded = function onLevelLoaded(event, data) {
this.mainDetails = data.details;
};
_proto.onSubtitleFragProcessed = function onSubtitleFragProcessed(event, data) {
var frag = data.frag,
success = data.success;
this.fragPrevious = frag;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["State"].IDLE;
if (!success) {
return;
}
var buffered = this.tracksBuffered[this.currentTrackId];
if (!buffered) {
return;
} // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo
// so we can re-use the logic used to detect how much has been buffered
var timeRange;
var fragStart = frag.start;
for (var i = 0; i < buffered.length; i++) {
if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {
timeRange = buffered[i];
break;
}
}
var fragEnd = frag.start + frag.duration;
if (timeRange) {
timeRange.end = fragEnd;
} else {
timeRange = {
start: fragStart,
end: fragEnd
};
buffered.push(timeRange);
}
this.fragmentTracker.fragBuffered(frag);
};
_proto.onBufferFlushing = function onBufferFlushing(event, data) {
var startOffset = data.startOffset,
endOffset = data.endOffset;
if (startOffset === 0 && endOffset !== Number.POSITIVE_INFINITY) {
var currentTrackId = this.currentTrackId,
levels = this.levels;
if (!levels.length || !levels[currentTrackId] || !levels[currentTrackId].details) {
return;
}
var trackDetails = levels[currentTrackId].details;
var targetDuration = trackDetails.targetduration;
var endOffsetSubtitles = endOffset - targetDuration;
if (endOffsetSubtitles <= 0) {
return;
}
data.endOffsetSubtitles = Math.max(0, endOffsetSubtitles);
this.tracksBuffered.forEach(function (buffered) {
for (var i = 0; i < buffered.length;) {
if (buffered[i].end <= endOffsetSubtitles) {
buffered.shift();
continue;
} else if (buffered[i].start < endOffsetSubtitles) {
buffered[i].start = endOffsetSubtitles;
} else {
break;
}
i++;
}
});
this.fragmentTracker.removeFragmentsInRange(startOffset, endOffsetSubtitles, _types_loader__WEBPACK_IMPORTED_MODULE_8__["PlaylistLevelType"].SUBTITLE);
}
} // If something goes wrong, proceed to next frag, if we were processing one.
;
_proto.onError = function onError(event, data) {
var _this$fragCurrent;
var frag = data.frag; // don't handle error not related to subtitle fragment
if (!frag || frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_8__["PlaylistLevelType"].SUBTITLE) {
return;
}
if ((_this$fragCurrent = this.fragCurrent) !== null && _this$fragCurrent !== void 0 && _this$fragCurrent.loader) {
this.fragCurrent.loader.abort();
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["State"].IDLE;
} // Got all new subtitle levels.
;
_proto.onSubtitleTracksUpdated = function onSubtitleTracksUpdated(event, _ref) {
var _this2 = this;
var subtitleTracks = _ref.subtitleTracks;
this.tracksBuffered = [];
this.levels = subtitleTracks.map(function (mediaPlaylist) {
return new _types_level__WEBPACK_IMPORTED_MODULE_9__["Level"](mediaPlaylist);
});
this.fragmentTracker.removeAllFragments();
this.fragPrevious = null;
this.levels.forEach(function (level) {
_this2.tracksBuffered[level.id] = [];
});
this.mediaBuffer = null;
};
_proto.onSubtitleTrackSwitch = function onSubtitleTrackSwitch(event, data) {
this.currentTrackId = data.id;
if (!this.levels.length || this.currentTrackId === -1) {
this.clearInterval();
return;
} // Check if track has the necessary details to load fragments
var currentTrack = this.levels[this.currentTrackId];
if (currentTrack !== null && currentTrack !== void 0 && currentTrack.details) {
this.mediaBuffer = this.mediaBufferTimeRanges;
this.setInterval(TICK_INTERVAL);
} else {
this.mediaBuffer = null;
}
} // Got a new set of subtitle fragments.
;
_proto.onSubtitleTrackLoaded = function onSubtitleTrackLoaded(event, data) {
var _track$details;
var newDetails = data.details,
trackId = data.id;
var currentTrackId = this.currentTrackId,
levels = this.levels;
if (!levels.length) {
return;
}
var track = levels[currentTrackId];
if (trackId >= levels.length || trackId !== currentTrackId || !track) {
return;
}
this.mediaBuffer = this.mediaBufferTimeRanges;
if (newDetails.live || (_track$details = track.details) !== null && _track$details !== void 0 && _track$details.live) {
var mainDetails = this.mainDetails;
if (newDetails.deltaUpdateFailed || !mainDetails) {
return;
}
var mainSlidingStartFragment = mainDetails.fragments[0];
if (!track.details) {
if (newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) {
Object(_utils_discontinuities__WEBPACK_IMPORTED_MODULE_4__["alignMediaPlaylistByPDT"])(newDetails, mainDetails);
} else if (mainSlidingStartFragment) {
// line up live playlist with main so that fragments in range are loaded
Object(_level_helper__WEBPACK_IMPORTED_MODULE_5__["addSliding"])(newDetails, mainSlidingStartFragment.start);
}
} else {
var sliding = this.alignPlaylists(newDetails, track.details);
if (sliding === 0 && mainSlidingStartFragment) {
// realign with main when there is no overlap with last refresh
Object(_level_helper__WEBPACK_IMPORTED_MODULE_5__["addSliding"])(newDetails, mainSlidingStartFragment.start);
}
}
}
track.details = newDetails;
this.levelLastLoaded = trackId; // trigger handler right now
this.tick(); // If playlist is misaligned because of bad PDT or drift, delete details to resync with main on reload
if (newDetails.live && !this.fragCurrent && this.media && this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["State"].IDLE) {
var foundFrag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_3__["findFragmentByPTS"])(null, newDetails.fragments, this.media.currentTime, 0);
if (!foundFrag) {
this.warn('Subtitle playlist not aligned with playback');
track.details = undefined;
}
}
};
_proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedData) {
var frag = fragLoadedData.frag,
payload = fragLoadedData.payload;
var decryptData = frag.decryptdata;
var hls = this.hls;
if (this.fragContextChanged(frag)) {
return;
} // check to see if the payload needs to be decrypted
if (payload && payload.byteLength > 0 && decryptData && decryptData.key && decryptData.iv && decryptData.method === 'AES-128') {
var startTime = performance.now(); // decrypt the subtitles
this.decrypter.webCryptoDecrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).then(function (decryptedData) {
var endTime = performance.now();
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_DECRYPTED, {
frag: frag,
payload: decryptedData,
stats: {
tstart: startTime,
tdecrypt: endTime
}
});
});
}
};
_proto.doTick = function doTick() {
if (!this.media) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["State"].IDLE;
return;
}
if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["State"].IDLE) {
var _foundFrag;
var currentTrackId = this.currentTrackId,
levels = this.levels;
if (!levels.length || !levels[currentTrackId] || !levels[currentTrackId].details) {
return;
} // Expand range of subs loaded by one target-duration in either direction to make up for misaligned playlists
var trackDetails = levels[currentTrackId].details;
var targetDuration = trackDetails.targetduration;
var config = this.config,
media = this.media;
var bufferedInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_2__["BufferHelper"].bufferedInfo(this.mediaBufferTimeRanges, media.currentTime - targetDuration, config.maxBufferHole);
var targetBufferTime = bufferedInfo.end,
bufferLen = bufferedInfo.len;
var maxBufLen = this.getMaxBufferLength() + targetDuration;
if (bufferLen > maxBufLen) {
return;
}
console.assert(trackDetails, 'Subtitle track details are defined on idle subtitle stream controller tick');
var fragments = trackDetails.fragments;
var fragLen = fragments.length;
var end = trackDetails.edge;
var foundFrag;
var fragPrevious = this.fragPrevious;
if (targetBufferTime < end) {
var maxFragLookUpTolerance = config.maxFragLookUpTolerance;
if (fragPrevious && trackDetails.hasProgramDateTime) {
foundFrag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_3__["findFragmentByPDT"])(fragments, fragPrevious.endProgramDateTime, maxFragLookUpTolerance);
}
if (!foundFrag) {
foundFrag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_3__["findFragmentByPTS"])(fragPrevious, fragments, targetBufferTime, maxFragLookUpTolerance);
if (!foundFrag && fragPrevious && fragPrevious.start < fragments[0].start) {
foundFrag = fragments[0];
}
}
} else {
foundFrag = fragments[fragLen - 1];
}
if ((_foundFrag = foundFrag) !== null && _foundFrag !== void 0 && _foundFrag.encrypted) {
_utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log("Loading key for " + foundFrag.sn);
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["State"].KEY_LOADING;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADING, {
frag: foundFrag
});
} else if (foundFrag && this.fragmentTracker.getState(foundFrag) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_6__["FragmentState"].NOT_LOADED) {
// only load if fragment is not loaded
this.loadFragment(foundFrag, trackDetails, targetBufferTime);
}
}
};
_proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) {
this.fragCurrent = frag;
_BaseStreamController.prototype.loadFragment.call(this, frag, levelDetails, targetBufferTime);
};
_createClass(SubtitleStreamController, [{
key: "mediaBufferTimeRanges",
get: function get() {
return this.tracksBuffered[this.currentTrackId] || [];
}
}]);
return SubtitleStreamController;
}(_base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["default"]);
/***/ }),
/***/ "./src/controller/subtitle-track-controller.ts":
/*!*****************************************************!*\
!*** ./src/controller/subtitle-track-controller.ts ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/texttrack-utils */ "./src/utils/texttrack-utils.ts");
/* harmony import */ var _base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base-playlist-controller */ "./src/controller/base-playlist-controller.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
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); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var SubtitleTrackController = /*#__PURE__*/function (_BasePlaylistControll) {
_inheritsLoose(SubtitleTrackController, _BasePlaylistControll);
// Enable/disable subtitle display rendering
function SubtitleTrackController(hls) {
var _this;
_this = _BasePlaylistControll.call(this, hls, '[subtitle-track-controller]') || this;
_this.media = null;
_this.tracks = [];
_this.groupId = null;
_this.tracksInGroup = [];
_this.trackId = -1;
_this.selectDefaultTrack = true;
_this.queuedDefaultTrack = -1;
_this.trackChangeListener = function () {
return _this.onTextTracksChanged();
};
_this.asyncPollTrackChange = function () {
return _this.pollTrackChange(0);
};
_this.useTextTrackPolling = false;
_this.subtitlePollingInterval = -1;
_this.subtitleDisplay = true;
_this.registerListeners();
return _this;
}
var _proto = SubtitleTrackController.prototype;
_proto.destroy = function destroy() {
this.unregisterListeners();
this.tracks.length = 0;
this.tracksInGroup.length = 0;
this.trackChangeListener = this.asyncPollTrackChange = null;
_BasePlaylistControll.prototype.destroy.call(this);
};
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_SWITCHING, this.onLevelSwitching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
};
_proto.unregisterListeners = function unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_SWITCHING, this.onLevelSwitching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
} // Listen for subtitle track change, then extract the current track ID.
;
_proto.onMediaAttached = function onMediaAttached(event, data) {
this.media = data.media;
if (!this.media) {
return;
}
if (this.queuedDefaultTrack > -1) {
this.subtitleTrack = this.queuedDefaultTrack;
this.queuedDefaultTrack = -1;
}
this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks);
if (this.useTextTrackPolling) {
this.pollTrackChange(500);
} else {
this.media.textTracks.addEventListener('change', this.asyncPollTrackChange);
}
};
_proto.pollTrackChange = function pollTrackChange(timeout) {
self.clearInterval(this.subtitlePollingInterval);
this.subtitlePollingInterval = self.setInterval(this.trackChangeListener, timeout);
};
_proto.onMediaDetaching = function onMediaDetaching() {
if (!this.media) {
return;
}
self.clearInterval(this.subtitlePollingInterval);
if (!this.useTextTrackPolling) {
this.media.textTracks.removeEventListener('change', this.asyncPollTrackChange);
}
if (this.trackId > -1) {
this.queuedDefaultTrack = this.trackId;
}
var textTracks = filterSubtitleTracks(this.media.textTracks); // Clear loaded cues on media detachment from tracks
textTracks.forEach(function (track) {
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["clearCurrentCues"])(track);
}); // Disable all subtitle tracks before detachment so when reattached only tracks in that content are enabled.
this.subtitleTrack = -1;
this.media = null;
};
_proto.onManifestLoading = function onManifestLoading() {
this.tracks = [];
this.groupId = null;
this.tracksInGroup = [];
this.trackId = -1;
this.selectDefaultTrack = true;
} // Fired whenever a new manifest is loaded.
;
_proto.onManifestParsed = function onManifestParsed(event, data) {
this.tracks = data.subtitleTracks;
};
_proto.onSubtitleTrackLoaded = function onSubtitleTrackLoaded(event, data) {
var id = data.id,
details = data.details;
var trackId = this.trackId;
var currentTrack = this.tracksInGroup[trackId];
if (!currentTrack) {
this.warn("Invalid subtitle track id " + id);
return;
}
var curDetails = currentTrack.details;
currentTrack.details = data.details;
this.log("subtitle track " + id + " loaded [" + details.startSN + "-" + details.endSN + "]");
if (id === this.trackId) {
this.retryCount = 0;
this.playlistLoaded(id, data, curDetails);
}
};
_proto.onLevelLoading = function onLevelLoading(event, data) {
this.switchLevel(data.level);
};
_proto.onLevelSwitching = function onLevelSwitching(event, data) {
this.switchLevel(data.level);
};
_proto.switchLevel = function switchLevel(levelIndex) {
var levelInfo = this.hls.levels[levelIndex];
if (!(levelInfo !== null && levelInfo !== void 0 && levelInfo.textGroupIds)) {
return;
}
var textGroupId = levelInfo.textGroupIds[levelInfo.urlId];
if (this.groupId !== textGroupId) {
var lastTrack = this.tracksInGroup ? this.tracksInGroup[this.trackId] : undefined;
var subtitleTracks = this.tracks.filter(function (track) {
return !textGroupId || track.groupId === textGroupId;
});
this.tracksInGroup = subtitleTracks;
var initialTrackId = this.findTrackId(lastTrack === null || lastTrack === void 0 ? void 0 : lastTrack.name) || this.findTrackId();
this.groupId = textGroupId;
var subtitleTracksUpdated = {
subtitleTracks: subtitleTracks
};
this.log("Updating subtitle tracks, " + subtitleTracks.length + " track(s) found in \"" + textGroupId + "\" group-id");
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACKS_UPDATED, subtitleTracksUpdated);
if (initialTrackId !== -1) {
this.setSubtitleTrack(initialTrackId, lastTrack);
}
}
};
_proto.findTrackId = function findTrackId(name) {
var textTracks = this.tracksInGroup;
for (var i = 0; i < textTracks.length; i++) {
var track = textTracks[i];
if (!this.selectDefaultTrack || track.default) {
if (!name || name === track.name) {
return track.id;
}
}
}
return -1;
};
_proto.onError = function onError(event, data) {
_BasePlaylistControll.prototype.onError.call(this, event, data);
if (data.fatal || !data.context) {
return;
}
if (data.context.type === _types_loader__WEBPACK_IMPORTED_MODULE_3__["PlaylistContextType"].SUBTITLE_TRACK && data.context.id === this.trackId && data.context.groupId === this.groupId) {
this.retryLoadingOrFail(data);
}
}
/** get alternate subtitle tracks list from playlist **/
;
_proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
var currentTrack = this.tracksInGroup[this.trackId];
if (this.shouldLoadTrack(currentTrack)) {
var id = currentTrack.id;
var groupId = currentTrack.groupId;
var url = currentTrack.url;
if (hlsUrlParameters) {
try {
url = hlsUrlParameters.addDirectives(url);
} catch (error) {
this.warn("Could not construct new URL with HLS Delivery Directives: " + error);
}
}
this.log("Loading subtitle playlist for id " + id);
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADING, {
url: url,
id: id,
groupId: groupId,
deliveryDirectives: hlsUrlParameters || null
});
}
}
/**
* Disables the old subtitleTrack and sets current mode on the next subtitleTrack.
* This operates on the DOM textTracks.
* A value of -1 will disable all subtitle tracks.
*/
;
_proto.toggleTrackModes = function toggleTrackModes(newId) {
var _this2 = this;
var media = this.media,
subtitleDisplay = this.subtitleDisplay,
trackId = this.trackId;
if (!media) {
return;
}
var textTracks = filterSubtitleTracks(media.textTracks);
var groupTracks = textTracks.filter(function (track) {
return track.groupId === _this2.groupId;
});
if (newId === -1) {
[].slice.call(textTracks).forEach(function (track) {
track.mode = 'disabled';
});
} else {
var oldTrack = groupTracks[trackId];
if (oldTrack) {
oldTrack.mode = 'disabled';
}
}
var nextTrack = groupTracks[newId];
if (nextTrack) {
nextTrack.mode = subtitleDisplay ? 'showing' : 'hidden';
}
}
/**
* This method is responsible for validating the subtitle index and periodically reloading if live.
* Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.
*/
;
_proto.setSubtitleTrack = function setSubtitleTrack(newId, lastTrack) {
var _tracks$newId;
var tracks = this.tracksInGroup; // setting this.subtitleTrack will trigger internal logic
// if media has not been attached yet, it will fail
// we keep a reference to the default track id
// and we'll set subtitleTrack when onMediaAttached is triggered
if (!this.media) {
this.queuedDefaultTrack = newId;
return;
}
if (this.trackId !== newId) {
this.toggleTrackModes(newId);
} // exit if track id as already set or invalid
if (this.trackId === newId && (newId === -1 || (_tracks$newId = tracks[newId]) !== null && _tracks$newId !== void 0 && _tracks$newId.details) || newId < -1 || newId >= tracks.length) {
return;
} // stopping live reloading timer if any
this.clearTimer();
var track = tracks[newId];
this.log("Switching to subtitle track " + newId);
this.trackId = newId;
if (track) {
var id = track.id,
_track$groupId = track.groupId,
groupId = _track$groupId === void 0 ? '' : _track$groupId,
name = track.name,
type = track.type,
url = track.url;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_SWITCH, {
id: id,
groupId: groupId,
name: name,
type: type,
url: url
});
var hlsUrlParameters = this.switchParams(track.url, lastTrack === null || lastTrack === void 0 ? void 0 : lastTrack.details);
this.loadPlaylist(hlsUrlParameters);
} else {
// switch to -1
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_SWITCH, {
id: newId
});
}
};
_proto.onTextTracksChanged = function onTextTracksChanged() {
if (!this.useTextTrackPolling) {
self.clearInterval(this.subtitlePollingInterval);
} // Media is undefined when switching streams via loadSource()
if (!this.media || !this.hls.config.renderTextTracksNatively) {
return;
}
var trackId = -1;
var tracks = filterSubtitleTracks(this.media.textTracks);
for (var id = 0; id < tracks.length; id++) {
if (tracks[id].mode === 'hidden') {
// Do not break in case there is a following track with showing.
trackId = id;
} else if (tracks[id].mode === 'showing') {
trackId = id;
break;
}
} // Setting current subtitleTrack will invoke code.
if (this.subtitleTrack !== trackId) {
this.subtitleTrack = trackId;
}
};
_createClass(SubtitleTrackController, [{
key: "subtitleTracks",
get: function get() {
return this.tracksInGroup;
}
/** get/set index of the selected subtitle track (based on index in subtitle track lists) **/
}, {
key: "subtitleTrack",
get: function get() {
return this.trackId;
},
set: function set(newId) {
this.selectDefaultTrack = false;
var lastTrack = this.tracksInGroup ? this.tracksInGroup[this.trackId] : undefined;
this.setSubtitleTrack(newId, lastTrack);
}
}]);
return SubtitleTrackController;
}(_base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__["default"]);
function filterSubtitleTracks(textTrackList) {
var tracks = [];
for (var i = 0; i < textTrackList.length; i++) {
var track = textTrackList[i]; // Edge adds a track without a label; we don't want to use it
if (track.kind === 'subtitles' && track.label) {
tracks.push(textTrackList[i]);
}
}
return tracks;
}
/* harmony default export */ __webpack_exports__["default"] = (SubtitleTrackController);
/***/ }),
/***/ "./src/controller/timeline-controller.ts":
/*!***********************************************!*\
!*** ./src/controller/timeline-controller.ts ***!
\***********************************************/
/*! exports provided: TimelineController */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimelineController", function() { return TimelineController; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_cea_608_parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/cea-608-parser */ "./src/utils/cea-608-parser.ts");
/* harmony import */ var _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/output-filter */ "./src/utils/output-filter.ts");
/* harmony import */ var _utils_webvtt_parser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/webvtt-parser */ "./src/utils/webvtt-parser.ts");
/* harmony import */ var _utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/texttrack-utils */ "./src/utils/texttrack-utils.ts");
/* harmony import */ var _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/imsc1-ttml-parser */ "./src/utils/imsc1-ttml-parser.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var TimelineController = /*#__PURE__*/function () {
function TimelineController(hls) {
this.hls = void 0;
this.media = null;
this.config = void 0;
this.enabled = true;
this.Cues = void 0;
this.textTracks = [];
this.tracks = [];
this.initPTS = [];
this.timescale = [];
this.unparsedVttFrags = [];
this.captionsTracks = {};
this.nonNativeCaptionsTracks = {};
this.cea608Parser1 = void 0;
this.cea608Parser2 = void 0;
this.lastSn = -1;
this.prevCC = -1;
this.vttCCs = newVTTCCs();
this.captionsProperties = void 0;
this.hls = hls;
this.config = hls.config;
this.Cues = hls.config.cueHandler;
this.captionsProperties = {
textTrack1: {
label: this.config.captionsTextTrack1Label,
languageCode: this.config.captionsTextTrack1LanguageCode
},
textTrack2: {
label: this.config.captionsTextTrack2Label,
languageCode: this.config.captionsTextTrack2LanguageCode
},
textTrack3: {
label: this.config.captionsTextTrack3Label,
languageCode: this.config.captionsTextTrack3LanguageCode
},
textTrack4: {
label: this.config.captionsTextTrack4Label,
languageCode: this.config.captionsTextTrack4LanguageCode
}
};
if (this.config.enableCEA708Captions) {
var channel1 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__["default"](this, 'textTrack1');
var channel2 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__["default"](this, 'textTrack2');
var channel3 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__["default"](this, 'textTrack3');
var channel4 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__["default"](this, 'textTrack4');
this.cea608Parser1 = new _utils_cea_608_parser__WEBPACK_IMPORTED_MODULE_2__["default"](1, channel1, channel2);
this.cea608Parser2 = new _utils_cea_608_parser__WEBPACK_IMPORTED_MODULE_2__["default"](3, channel3, channel4);
}
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADING, this.onFragLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, this.onFragDecrypted, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].INIT_PTS_FOUND, this.onInitPtsFound, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
}
var _proto = TimelineController.prototype;
_proto.destroy = function destroy() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADING, this.onFragLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, this.onFragDecrypted, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].INIT_PTS_FOUND, this.onInitPtsFound, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this); // @ts-ignore
this.hls = this.config = this.cea608Parser1 = this.cea608Parser2 = null;
};
_proto.addCues = function addCues(trackName, startTime, endTime, screen, cueRanges) {
// skip cues which overlap more than 50% with previously parsed time ranges
var merged = false;
for (var i = cueRanges.length; i--;) {
var cueRange = cueRanges[i];
var overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
if (overlap >= 0) {
cueRange[0] = Math.min(cueRange[0], startTime);
cueRange[1] = Math.max(cueRange[1], endTime);
merged = true;
if (overlap / (endTime - startTime) > 0.5) {
return;
}
}
}
if (!merged) {
cueRanges.push([startTime, endTime]);
}
if (this.config.renderTextTracksNatively) {
var track = this.captionsTracks[trackName];
this.Cues.newCue(track, startTime, endTime, screen);
} else {
var cues = this.Cues.newCue(null, startTime, endTime, screen);
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].CUES_PARSED, {
type: 'captions',
cues: cues,
track: trackName
});
}
} // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
;
_proto.onInitPtsFound = function onInitPtsFound(event, _ref) {
var _this = this;
var frag = _ref.frag,
id = _ref.id,
initPTS = _ref.initPTS,
timescale = _ref.timescale;
var unparsedVttFrags = this.unparsedVttFrags;
if (id === 'main') {
this.initPTS[frag.cc] = initPTS;
this.timescale[frag.cc] = timescale;
} // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.
// Parse any unparsed fragments upon receiving the initial PTS.
if (unparsedVttFrags.length) {
this.unparsedVttFrags = [];
unparsedVttFrags.forEach(function (frag) {
_this.onFragLoaded(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, frag);
});
}
};
_proto.getExistingTrack = function getExistingTrack(trackName) {
var media = this.media;
if (media) {
for (var i = 0; i < media.textTracks.length; i++) {
var textTrack = media.textTracks[i];
if (textTrack[trackName]) {
return textTrack;
}
}
}
return null;
};
_proto.createCaptionsTrack = function createCaptionsTrack(trackName) {
if (this.config.renderTextTracksNatively) {
this.createNativeTrack(trackName);
} else {
this.createNonNativeTrack(trackName);
}
};
_proto.createNativeTrack = function createNativeTrack(trackName) {
if (this.captionsTracks[trackName]) {
return;
}
var captionsProperties = this.captionsProperties,
captionsTracks = this.captionsTracks,
media = this.media;
var _captionsProperties$t = captionsProperties[trackName],
label = _captionsProperties$t.label,
languageCode = _captionsProperties$t.languageCode; // Enable reuse of existing text track.
var existingTrack = this.getExistingTrack(trackName);
if (!existingTrack) {
var textTrack = this.createTextTrack('captions', label, languageCode);
if (textTrack) {
// Set a special property on the track so we know it's managed by Hls.js
textTrack[trackName] = true;
captionsTracks[trackName] = textTrack;
}
} else {
captionsTracks[trackName] = existingTrack;
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["clearCurrentCues"])(captionsTracks[trackName]);
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["sendAddTrackEvent"])(captionsTracks[trackName], media);
}
};
_proto.createNonNativeTrack = function createNonNativeTrack(trackName) {
if (this.nonNativeCaptionsTracks[trackName]) {
return;
} // Create a list of a single track for the provider to consume
var trackProperties = this.captionsProperties[trackName];
if (!trackProperties) {
return;
}
var label = trackProperties.label;
var track = {
_id: trackName,
label: label,
kind: 'captions',
default: trackProperties.media ? !!trackProperties.media.default : false,
closedCaptions: trackProperties.media
};
this.nonNativeCaptionsTracks[trackName] = track;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].NON_NATIVE_TEXT_TRACKS_FOUND, {
tracks: [track]
});
};
_proto.createTextTrack = function createTextTrack(kind, label, lang) {
var media = this.media;
if (!media) {
return;
}
return media.addTextTrack(kind, label, lang);
};
_proto.onMediaAttaching = function onMediaAttaching(event, data) {
this.media = data.media;
this._cleanTracks();
};
_proto.onMediaDetaching = function onMediaDetaching() {
var captionsTracks = this.captionsTracks;
Object.keys(captionsTracks).forEach(function (trackName) {
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["clearCurrentCues"])(captionsTracks[trackName]);
delete captionsTracks[trackName];
});
this.nonNativeCaptionsTracks = {};
};
_proto.onManifestLoading = function onManifestLoading() {
this.lastSn = -1; // Detect discontinuity in fragment parsing
this.prevCC = -1;
this.vttCCs = newVTTCCs(); // Detect discontinuity in subtitle manifests
this._cleanTracks();
this.tracks = [];
this.captionsTracks = {};
this.nonNativeCaptionsTracks = {};
this.textTracks = [];
this.unparsedVttFrags = this.unparsedVttFrags || [];
this.initPTS = [];
this.timescale = [];
if (this.cea608Parser1 && this.cea608Parser2) {
this.cea608Parser1.reset();
this.cea608Parser2.reset();
}
};
_proto._cleanTracks = function _cleanTracks() {
// clear outdated subtitles
var media = this.media;
if (!media) {
return;
}
var textTracks = media.textTracks;
if (textTracks) {
for (var i = 0; i < textTracks.length; i++) {
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["clearCurrentCues"])(textTracks[i]);
}
}
};
_proto.onSubtitleTracksUpdated = function onSubtitleTracksUpdated(event, data) {
var _this2 = this;
this.textTracks = [];
var tracks = data.subtitleTracks || [];
var hasIMSC1 = tracks.some(function (track) {
return track.textCodec === _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["IMSC1_CODEC"];
});
if (this.config.enableWebVTT || hasIMSC1 && this.config.enableIMSC1) {
var sameTracks = this.tracks && tracks && this.tracks.length === tracks.length;
this.tracks = tracks || [];
if (this.config.renderTextTracksNatively) {
var inUseTracks = this.media ? this.media.textTracks : [];
this.tracks.forEach(function (track, index) {
var textTrack;
if (index < inUseTracks.length) {
var inUseTrack = null;
for (var i = 0; i < inUseTracks.length; i++) {
if (canReuseVttTextTrack(inUseTracks[i], track)) {
inUseTrack = inUseTracks[i];
break;
}
} // Reuse tracks with the same label, but do not reuse 608/708 tracks
if (inUseTrack) {
textTrack = inUseTrack;
}
}
if (textTrack) {
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["clearCurrentCues"])(textTrack);
} else {
textTrack = _this2.createTextTrack('subtitles', track.name, track.lang);
if (textTrack) {
textTrack.mode = 'disabled';
}
}
if (textTrack) {
textTrack.groupId = track.groupId;
_this2.textTracks.push(textTrack);
}
});
} else if (!sameTracks && this.tracks && this.tracks.length) {
// Create a list of tracks for the provider to consume
var tracksList = this.tracks.map(function (track) {
return {
label: track.name,
kind: track.type.toLowerCase(),
default: track.default,
subtitleTrack: track
};
});
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].NON_NATIVE_TEXT_TRACKS_FOUND, {
tracks: tracksList
});
}
}
};
_proto.onManifestLoaded = function onManifestLoaded(event, data) {
var _this3 = this;
if (this.config.enableCEA708Captions && data.captions) {
data.captions.forEach(function (captionsTrack) {
var instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId);
if (!instreamIdMatch) {
return;
}
var trackName = "textTrack" + instreamIdMatch[1];
var trackProperties = _this3.captionsProperties[trackName];
if (!trackProperties) {
return;
}
trackProperties.label = captionsTrack.name;
if (captionsTrack.lang) {
// optional attribute
trackProperties.languageCode = captionsTrack.lang;
}
trackProperties.media = captionsTrack;
});
}
};
_proto.onFragLoading = function onFragLoading(event, data) {
var cea608Parser1 = this.cea608Parser1,
cea608Parser2 = this.cea608Parser2,
lastSn = this.lastSn;
if (!this.enabled || !(cea608Parser1 && cea608Parser2)) {
return;
} // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack
if (data.frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_7__["PlaylistLevelType"].MAIN) {
var sn = data.frag.sn;
if (sn !== lastSn + 1) {
cea608Parser1.reset();
cea608Parser2.reset();
}
this.lastSn = sn;
}
};
_proto.onFragLoaded = function onFragLoaded(event, data) {
var frag = data.frag,
payload = data.payload;
var initPTS = this.initPTS,
unparsedVttFrags = this.unparsedVttFrags;
if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_7__["PlaylistLevelType"].SUBTITLE) {
// If fragment is subtitle type, parse as WebVTT.
if (payload.byteLength) {
// We need an initial synchronisation PTS. Store fragments as long as none has arrived.
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(initPTS[frag.cc])) {
unparsedVttFrags.push(data);
if (initPTS.length) {
// finish unsuccessfully, otherwise the subtitle-stream-controller could be blocked from loading new frags.
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
success: false,
frag: frag,
error: new Error('Missing initial subtitle PTS')
});
}
return;
}
var decryptData = frag.decryptdata; // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.
if (decryptData == null || decryptData.key == null || decryptData.method !== 'AES-128') {
var trackPlaylistMedia = this.tracks[frag.level];
var vttCCs = this.vttCCs;
if (!vttCCs[frag.cc]) {
vttCCs[frag.cc] = {
start: frag.start,
prevCC: this.prevCC,
new: true
};
this.prevCC = frag.cc;
}
if (trackPlaylistMedia && trackPlaylistMedia.textCodec === _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["IMSC1_CODEC"]) {
this._parseIMSC1(frag, payload);
} else {
this._parseVTTs(frag, payload, vttCCs);
}
}
} else {
// In case there is no payload, finish unsuccessfully.
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
success: false,
frag: frag,
error: new Error('Empty subtitle payload')
});
}
}
};
_proto._parseIMSC1 = function _parseIMSC1(frag, payload) {
var _this4 = this;
var hls = this.hls;
Object(_utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["parseIMSC1"])(payload, this.initPTS[frag.cc], this.timescale[frag.cc], function (cues) {
_this4._appendCues(cues, frag.level);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
success: true,
frag: frag
});
}, function (error) {
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log("Failed to parse IMSC1: " + error);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
success: false,
frag: frag,
error: error
});
});
};
_proto._parseVTTs = function _parseVTTs(frag, payload, vttCCs) {
var _this5 = this;
var hls = this.hls; // Parse the WebVTT file contents.
Object(_utils_webvtt_parser__WEBPACK_IMPORTED_MODULE_4__["parseWebVTT"])(payload, this.initPTS[frag.cc], this.timescale[frag.cc], vttCCs, frag.cc, frag.start, function (cues) {
_this5._appendCues(cues, frag.level);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
success: true,
frag: frag
});
}, function (error) {
_this5._fallbackToIMSC1(frag, payload); // Something went wrong while parsing. Trigger event with success false.
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log("Failed to parse VTT cue: " + error);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
success: false,
frag: frag,
error: error
});
});
};
_proto._fallbackToIMSC1 = function _fallbackToIMSC1(frag, payload) {
var _this6 = this;
// If textCodec is unknown, try parsing as IMSC1. Set textCodec based on the result
var trackPlaylistMedia = this.tracks[frag.level];
if (!trackPlaylistMedia.textCodec) {
Object(_utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["parseIMSC1"])(payload, this.initPTS[frag.cc], this.timescale[frag.cc], function () {
trackPlaylistMedia.textCodec = _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["IMSC1_CODEC"];
_this6._parseIMSC1(frag, payload);
}, function () {
trackPlaylistMedia.textCodec = 'wvtt';
});
}
};
_proto._appendCues = function _appendCues(cues, fragLevel) {
var hls = this.hls;
if (this.config.renderTextTracksNatively) {
var textTrack = this.textTracks[fragLevel]; // WebVTTParser.parse is an async method and if the currently selected text track mode is set to "disabled"
// before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null
// and trying to access getCueById method of cues will throw an exception
// Because we check if the mode is disabled, we can force check `cues` below. They can't be null.
if (textTrack.mode === 'disabled') {
return;
}
cues.forEach(function (cue) {
return Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["addCueToTrack"])(textTrack, cue);
});
} else {
var currentTrack = this.tracks[fragLevel];
var track = currentTrack.default ? 'default' : 'subtitles' + fragLevel;
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].CUES_PARSED, {
type: 'subtitles',
cues: cues,
track: track
});
}
};
_proto.onFragDecrypted = function onFragDecrypted(event, data) {
var frag = data.frag;
if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_7__["PlaylistLevelType"].SUBTITLE) {
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.initPTS[frag.cc])) {
this.unparsedVttFrags.push(data);
return;
}
this.onFragLoaded(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, data);
}
};
_proto.onSubtitleTracksCleared = function onSubtitleTracksCleared() {
this.tracks = [];
this.captionsTracks = {};
};
_proto.onFragParsingUserdata = function onFragParsingUserdata(event, data) {
var cea608Parser1 = this.cea608Parser1,
cea608Parser2 = this.cea608Parser2;
if (!this.enabled || !(cea608Parser1 && cea608Parser2)) {
return;
} // If the event contains captions (found in the bytes property), push all bytes into the parser immediately
// It will create the proper timestamps based on the PTS value
for (var i = 0; i < data.samples.length; i++) {
var ccBytes = data.samples[i].bytes;
if (ccBytes) {
var ccdatas = this.extractCea608Data(ccBytes);
cea608Parser1.addData(data.samples[i].pts, ccdatas[0]);
cea608Parser2.addData(data.samples[i].pts, ccdatas[1]);
}
}
};
_proto.onBufferFlushing = function onBufferFlushing(event, _ref2) {
var startOffset = _ref2.startOffset,
endOffset = _ref2.endOffset,
endOffsetSubtitles = _ref2.endOffsetSubtitles,
type = _ref2.type;
var media = this.media;
if (!media || media.currentTime < endOffset) {
return;
} // Clear 608 caption cues from the captions TextTracks when the video back buffer is flushed
// Forward cues are never removed because we can loose streamed 608 content from recent fragments
if (!type || type === 'video') {
var captionsTracks = this.captionsTracks;
Object.keys(captionsTracks).forEach(function (trackName) {
return Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["removeCuesInRange"])(captionsTracks[trackName], startOffset, endOffset);
});
}
if (this.config.renderTextTracksNatively) {
// Clear VTT/IMSC1 subtitle cues from the subtitle TextTracks when the back buffer is flushed
if (startOffset === 0 && endOffsetSubtitles !== undefined) {
var textTracks = this.textTracks;
Object.keys(textTracks).forEach(function (trackName) {
return Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["removeCuesInRange"])(textTracks[trackName], startOffset, endOffsetSubtitles);
});
}
}
};
_proto.extractCea608Data = function extractCea608Data(byteArray) {
var count = byteArray[0] & 31;
var position = 2;
var actualCCBytes = [[], []];
for (var j = 0; j < count; j++) {
var tmpByte = byteArray[position++];
var ccbyte1 = 0x7f & byteArray[position++];
var ccbyte2 = 0x7f & byteArray[position++];
var ccValid = (4 & tmpByte) !== 0;
var ccType = 3 & tmpByte;
if (ccbyte1 === 0 && ccbyte2 === 0) {
continue;
}
if (ccValid) {
if (ccType === 0 || ccType === 1) {
actualCCBytes[ccType].push(ccbyte1);
actualCCBytes[ccType].push(ccbyte2);
}
}
}
return actualCCBytes;
};
return TimelineController;
}();
function canReuseVttTextTrack(inUseTrack, manifestTrack) {
return inUseTrack && inUseTrack.label === manifestTrack.name && !(inUseTrack.textTrack1 || inUseTrack.textTrack2);
}
function intersection(x1, x2, y1, y2) {
return Math.min(x2, y2) - Math.max(x1, y1);
}
function newVTTCCs() {
return {
ccOffset: 0,
presentationOffset: 0,
0: {
start: 0,
prevCC: -1,
new: false
}
};
}
/***/ }),
/***/ "./src/crypt/aes-crypto.ts":
/*!*********************************!*\
!*** ./src/crypt/aes-crypto.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AESCrypto; });
var AESCrypto = /*#__PURE__*/function () {
function AESCrypto(subtle, iv) {
this.subtle = void 0;
this.aesIV = void 0;
this.subtle = subtle;
this.aesIV = iv;
}
var _proto = AESCrypto.prototype;
_proto.decrypt = function decrypt(data, key) {
return this.subtle.decrypt({
name: 'AES-CBC',
iv: this.aesIV
}, key, data);
};
return AESCrypto;
}();
/***/ }),
/***/ "./src/crypt/aes-decryptor.ts":
/*!************************************!*\
!*** ./src/crypt/aes-decryptor.ts ***!
\************************************/
/*! exports provided: removePadding, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removePadding", function() { return removePadding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AESDecryptor; });
/* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts");
// PKCS7
function removePadding(array) {
var outputBytes = array.byteLength;
var paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);
if (paddingBytes) {
return Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_0__["sliceUint8"])(array, 0, outputBytes - paddingBytes);
}
return array;
}
var AESDecryptor = /*#__PURE__*/function () {
function AESDecryptor() {
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);
this.key = new Uint32Array(0);
this.ksRows = 0;
this.keySize = 0;
this.keySchedule = void 0;
this.invKeySchedule = void 0;
this.initTable();
} // Using view.getUint32() also swaps the byte order.
var _proto = AESDecryptor.prototype;
_proto.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;
};
_proto.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]];
}
}
};
_proto.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;
var invKsRow;
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;
var t;
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.
;
_proto.networkToHostOrderSwap = function networkToHostOrderSwap(word) {
return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
};
_proto.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, t1, t2, t3;
var s0, s1, s2, s3;
var inputWords0, inputWords1, inputWords2, inputWords3;
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]; // 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;
};
return AESDecryptor;
}();
/***/ }),
/***/ "./src/crypt/decrypter.ts":
/*!********************************!*\
!*** ./src/crypt/decrypter.ts ***!
\********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Decrypter; });
/* harmony import */ var _aes_crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./aes-crypto */ "./src/crypt/aes-crypto.ts");
/* harmony import */ var _fast_aes_key__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./fast-aes-key */ "./src/crypt/fast-aes-key.ts");
/* harmony import */ var _aes_decryptor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./aes-decryptor */ "./src/crypt/aes-decryptor.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts");
var CHUNK_SIZE = 16; // 16 bytes, 128 bits
var Decrypter = /*#__PURE__*/function () {
function Decrypter(observer, config, _temp) {
var _ref = _temp === void 0 ? {} : _temp,
_ref$removePKCS7Paddi = _ref.removePKCS7Padding,
removePKCS7Padding = _ref$removePKCS7Paddi === void 0 ? true : _ref$removePKCS7Paddi;
this.logEnabled = true;
this.observer = void 0;
this.config = void 0;
this.removePKCS7Padding = void 0;
this.subtle = null;
this.softwareDecrypter = null;
this.key = null;
this.fastAesKey = null;
this.remainderData = null;
this.currentIV = null;
this.currentResult = null;
this.observer = observer;
this.config = config;
this.removePKCS7Padding = removePKCS7Padding; // built in decryptor expects PKCS7 padding
if (removePKCS7Padding) {
try {
var browserCrypto = self.crypto;
if (browserCrypto) {
this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
}
} catch (e) {
/* no-op */
}
}
if (this.subtle === null) {
this.config.enableSoftwareAES = true;
}
}
var _proto = Decrypter.prototype;
_proto.destroy = function destroy() {
// @ts-ignore
this.observer = null;
};
_proto.isSync = function isSync() {
return this.config.enableSoftwareAES;
};
_proto.flush = function flush() {
var currentResult = this.currentResult;
if (!currentResult) {
this.reset();
return;
}
var data = new Uint8Array(currentResult);
this.reset();
if (this.removePKCS7Padding) {
return Object(_aes_decryptor__WEBPACK_IMPORTED_MODULE_2__["removePadding"])(data);
}
return data;
};
_proto.reset = function reset() {
this.currentResult = null;
this.currentIV = null;
this.remainderData = null;
if (this.softwareDecrypter) {
this.softwareDecrypter = null;
}
};
_proto.decrypt = function decrypt(data, key, iv, callback) {
if (this.config.enableSoftwareAES) {
this.softwareDecrypt(new Uint8Array(data), key, iv);
var decryptResult = this.flush();
if (decryptResult) {
callback(decryptResult.buffer);
}
} else {
this.webCryptoDecrypt(new Uint8Array(data), key, iv).then(callback);
}
};
_proto.softwareDecrypt = function softwareDecrypt(data, key, iv) {
var currentIV = this.currentIV,
currentResult = this.currentResult,
remainderData = this.remainderData;
this.logOnce('JS AES decrypt'); // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call
// This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached
// the end on flush(), but by that time we have already received all bytes for the segment.
// Progressive decryption does not work with WebCrypto
if (remainderData) {
data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__["appendUint8Array"])(remainderData, data);
this.remainderData = null;
} // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes)
var currentChunk = this.getValidChunk(data);
if (!currentChunk.length) {
return null;
}
if (currentIV) {
iv = currentIV;
}
var softwareDecrypter = this.softwareDecrypter;
if (!softwareDecrypter) {
softwareDecrypter = this.softwareDecrypter = new _aes_decryptor__WEBPACK_IMPORTED_MODULE_2__["default"]();
}
softwareDecrypter.expandKey(key);
var result = currentResult;
this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);
this.currentIV = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__["sliceUint8"])(currentChunk, -16).buffer;
if (!result) {
return null;
}
return result;
};
_proto.webCryptoDecrypt = function webCryptoDecrypt(data, key, iv) {
var _this = this;
var subtle = this.subtle;
if (this.key !== key || !this.fastAesKey) {
this.key = key;
this.fastAesKey = new _fast_aes_key__WEBPACK_IMPORTED_MODULE_1__["default"](subtle, key);
}
return this.fastAesKey.expandKey().then(function (aesKey) {
// decrypt using web crypto
if (!subtle) {
return Promise.reject(new Error('web crypto not initialized'));
}
var crypto = new _aes_crypto__WEBPACK_IMPORTED_MODULE_0__["default"](subtle, iv);
return crypto.decrypt(data.buffer, aesKey);
}).catch(function (err) {
return _this.onWebCryptoError(err, data, key, iv);
});
};
_proto.onWebCryptoError = function onWebCryptoError(err, data, key, iv) {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('[decrypter.ts]: WebCrypto Error, disable WebCrypto API:', err);
this.config.enableSoftwareAES = true;
this.logEnabled = true;
return this.softwareDecrypt(data, key, iv);
};
_proto.getValidChunk = function getValidChunk(data) {
var currentChunk = data;
var splitPoint = data.length - data.length % CHUNK_SIZE;
if (splitPoint !== data.length) {
currentChunk = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__["sliceUint8"])(data, 0, splitPoint);
this.remainderData = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__["sliceUint8"])(data, splitPoint);
}
return currentChunk;
};
_proto.logOnce = function logOnce(msg) {
if (!this.logEnabled) {
return;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log("[decrypter.ts]: " + msg);
this.logEnabled = false;
};
return Decrypter;
}();
/***/ }),
/***/ "./src/crypt/fast-aes-key.ts":
/*!***********************************!*\
!*** ./src/crypt/fast-aes-key.ts ***!
\***********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return FastAESKey; });
var FastAESKey = /*#__PURE__*/function () {
function FastAESKey(subtle, key) {
this.subtle = void 0;
this.key = void 0;
this.subtle = subtle;
this.key = key;
}
var _proto = FastAESKey.prototype;
_proto.expandKey = function expandKey() {
return this.subtle.importKey('raw', this.key, {
name: 'AES-CBC'
}, false, ['encrypt', 'decrypt']);
};
return FastAESKey;
}();
/***/ }),
/***/ "./src/demux/aacdemuxer.ts":
/*!*********************************!*\
!*** ./src/demux/aacdemuxer.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base-audio-demuxer */ "./src/demux/base-audio-demuxer.ts");
/* harmony import */ var _adts__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./adts */ "./src/demux/adts.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
/**
* AAC demuxer
*/
var AACDemuxer = /*#__PURE__*/function (_BaseAudioDemuxer) {
_inheritsLoose(AACDemuxer, _BaseAudioDemuxer);
function AACDemuxer(observer, config) {
var _this;
_this = _BaseAudioDemuxer.call(this) || this;
_this.observer = void 0;
_this.config = void 0;
_this.observer = observer;
_this.config = config;
return _this;
}
var _proto = AACDemuxer.prototype;
_proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {
_BaseAudioDemuxer.prototype.resetInitSegment.call(this, audioCodec, videoCodec, duration);
this._audioTrack = {
container: 'audio/adts',
type: 'audio',
id: 0,
pid: -1,
sequenceNumber: 0,
isAAC: true,
samples: [],
manifestCodec: audioCodec,
duration: duration,
inputTimeScale: 90000,
dropped: 0
};
} // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS
;
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 = _demux_id3__WEBPACK_IMPORTED_MODULE_3__["getID3Data"](data, 0) || [];
var offset = id3Data.length;
for (var length = data.length; offset < length; offset++) {
if (_adts__WEBPACK_IMPORTED_MODULE_1__["probe"](data, offset)) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('ADTS sync word found !');
return true;
}
}
return false;
};
_proto.canParse = function canParse(data, offset) {
return _adts__WEBPACK_IMPORTED_MODULE_1__["canParse"](data, offset);
};
_proto.appendFrame = function appendFrame(track, data, offset) {
_adts__WEBPACK_IMPORTED_MODULE_1__["initTrackConfig"](track, this.observer, data, offset, track.manifestCodec);
var frame = _adts__WEBPACK_IMPORTED_MODULE_1__["appendFrame"](track, data, offset, this.initPTS, this.frameIndex);
if (frame && frame.missing === 0) {
return frame;
}
};
return AACDemuxer;
}(_base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__["default"]);
AACDemuxer.minProbeByteLength = 9;
/* harmony default export */ __webpack_exports__["default"] = (AACDemuxer);
/***/ }),
/***/ "./src/demux/adts.ts":
/*!***************************!*\
!*** ./src/demux/adts.ts ***!
\***************************/
/*! exports provided: getAudioConfig, isHeaderPattern, getHeaderLength, getFullFrameLength, canGetFrameLength, isHeader, canParse, probe, initTrackConfig, getFrameDuration, parseFrameHeader, appendFrame */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getAudioConfig", function() { return getAudioConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeaderPattern", function() { return isHeaderPattern; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getHeaderLength", function() { return getHeaderLength; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFullFrameLength", function() { return getFullFrameLength; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canGetFrameLength", function() { return canGetFrameLength; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeader", function() { return isHeader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canParse", function() { return canParse; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "probe", function() { return probe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initTrackConfig", function() { return initTrackConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFrameDuration", function() { return getFrameDuration; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseFrameHeader", function() { return parseFrameHeader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendFrame", function() { return appendFrame; });
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/**
* ADTS parser helper
* @link https://wiki.multimedia.cx/index.php?title=ADTS
*/
function getAudioConfig(observer, data, offset, audioCodec) {
var adtsObjectType;
var adtsExtensionSamplingIndex;
var adtsChanelConfig;
var config;
var userAgent = navigator.userAgent.toLowerCase();
var manifestCodec = audioCodec;
var adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; // byte 2
adtsObjectType = ((data[offset + 2] & 0xc0) >>> 6) + 1;
var adtsSamplingIndex = (data[offset + 2] & 0x3c) >>> 2;
if (adtsSamplingIndex > adtsSampleingRates.length - 1) {
observer.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_PARSING_ERROR,
fatal: true,
reason: "invalid ADTS sampling index:" + adtsSamplingIndex
});
return;
}
adtsChanelConfig = (data[offset + 2] & 0x01) << 2; // byte 3
adtsChanelConfig |= (data[offset + 3] & 0xc0) >>> 6;
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log("manifest codec:" + audioCodec + ", ADTS type:" + adtsObjectType + ", samplingIndex:" + adtsSamplingIndex); // firefox: freq less than 24kHz = AAC SBR (HE-AAC)
if (/firefox/i.test(userAgent)) {
if (adtsSamplingIndex >= 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)
adtsExtensionSamplingIndex = adtsSamplingIndex - 3;
} else {
adtsObjectType = 2;
config = new Array(2);
adtsExtensionSamplingIndex = adtsSamplingIndex;
} // Android : always use AAC
} else if (userAgent.indexOf('android') !== -1) {
adtsObjectType = 2;
config = new Array(2);
adtsExtensionSamplingIndex = adtsSamplingIndex;
} 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 && adtsSamplingIndex >= 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)
adtsExtensionSamplingIndex = adtsSamplingIndex - 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 && (adtsSamplingIndex >= 6 && adtsChanelConfig === 1 || /vivaldi/i.test(userAgent)) || !audioCodec && adtsChanelConfig === 1) {
adtsObjectType = 2;
config = new Array(2);
}
adtsExtensionSamplingIndex = adtsSamplingIndex;
}
}
/* 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] |= (adtsSamplingIndex & 0x0e) >> 1;
config[1] |= (adtsSamplingIndex & 0x01) << 7; // channelConfiguration
config[1] |= adtsChanelConfig << 3;
if (adtsObjectType === 5) {
// adtsExtensionSampleingIndex
config[1] |= (adtsExtensionSamplingIndex & 0x0e) >> 1;
config[2] = (adtsExtensionSamplingIndex & 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[adtsSamplingIndex],
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 canGetFrameLength(data, offset) {
return offset + 5 < data.length;
}
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
return offset + 1 < data.length && isHeaderPattern(data, offset);
}
function canParse(data, offset) {
return canGetFrameLength(data, offset) && isHeaderPattern(data, offset) && getFullFrameLength(data, offset) <= data.length - offset;
}
function probe(data, offset) {
// same as isHeader but we also check that ADTS frame follows last ADTS frame
// or end of data is reached
if (isHeader(data, offset)) {
// ADTS header Length
var headerLength = getHeaderLength(data, offset);
if (offset + headerLength >= data.length) {
return false;
} // ADTS frame Length
var frameLength = getFullFrameLength(data, offset);
if (frameLength <= headerLength) {
return false;
}
var newOffset = offset + frameLength;
return newOffset === data.length || isHeader(data, newOffset);
}
return false;
}
function initTrackConfig(track, observer, data, offset, audioCodec) {
if (!track.samplerate) {
var config = getAudioConfig(observer, data, offset, audioCodec);
if (!config) {
return;
}
track.config = config.config;
track.samplerate = config.samplerate;
track.channelCount = config.channelCount;
track.codec = config.codec;
track.manifestCodec = config.manifestCodec;
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log("parsed codec:" + track.codec + ", rate:" + config.samplerate + ", channels:" + config.channelCount);
}
}
function getFrameDuration(samplerate) {
return 1024 * 90000 / samplerate;
}
function parseFrameHeader(data, offset, pts, frameIndex, frameDuration) {
// The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
var headerLength = getHeaderLength(data, offset); // retrieve frame size
var frameLength = getFullFrameLength(data, offset);
frameLength -= headerLength;
if (frameLength > 0) {
var 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
};
}
}
function appendFrame(track, data, offset, pts, frameIndex) {
var frameDuration = getFrameDuration(track.samplerate);
var header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);
if (header) {
var frameLength = header.frameLength,
headerLength = header.headerLength,
stamp = header.stamp;
var length = headerLength + frameLength;
var missing = Math.max(0, offset + length - data.length); // logger.log(`AAC frame ${frameIndex}, pts:${stamp} length@offset/total: ${frameLength}@${offset+headerLength}/${data.byteLength} missing: ${missing}`);
var unit;
if (missing) {
unit = new Uint8Array(length - headerLength);
unit.set(data.subarray(offset + headerLength, data.length), 0);
} else {
unit = data.subarray(offset + headerLength, offset + length);
}
var sample = {
unit: unit,
pts: stamp
};
if (!missing) {
track.samples.push(sample);
}
return {
sample: sample,
length: length,
missing: missing
};
}
}
/***/ }),
/***/ "./src/demux/base-audio-demuxer.ts":
/*!*****************************************!*\
!*** ./src/demux/base-audio-demuxer.ts ***!
\*****************************************/
/*! exports provided: initPTSFn, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initPTSFn", function() { return initPTSFn; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
/* harmony import */ var _dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./dummy-demuxed-track */ "./src/demux/dummy-demuxed-track.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts");
var BaseAudioDemuxer = /*#__PURE__*/function () {
function BaseAudioDemuxer() {
this._audioTrack = void 0;
this._id3Track = void 0;
this.frameIndex = 0;
this.cachedData = null;
this.initPTS = null;
}
var _proto = BaseAudioDemuxer.prototype;
_proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {
this._id3Track = {
type: 'id3',
id: 0,
pid: -1,
inputTimeScale: 90000,
sequenceNumber: 0,
samples: [],
dropped: 0
};
};
_proto.resetTimeStamp = function resetTimeStamp() {};
_proto.resetContiguity = function resetContiguity() {};
_proto.canParse = function canParse(data, offset) {
return false;
};
_proto.appendFrame = function appendFrame(track, data, offset) {} // feed incoming data to the front of the parsing pipeline
;
_proto.demux = function demux(data, timeOffset) {
if (this.cachedData) {
data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__["appendUint8Array"])(this.cachedData, data);
this.cachedData = null;
}
var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getID3Data"](data, 0);
var offset = id3Data ? id3Data.length : 0;
var lastDataIndex;
var pts;
var track = this._audioTrack;
var id3Track = this._id3Track;
var timestamp = id3Data ? _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getTimeStamp"](id3Data) : undefined;
var length = data.length;
if (this.frameIndex === 0 || this.initPTS === null) {
this.initPTS = initPTSFn(timestamp, timeOffset);
} // more expressive than alternative: id3Data?.length
if (id3Data && id3Data.length > 0) {
id3Track.samples.push({
pts: this.initPTS,
dts: this.initPTS,
data: id3Data
});
}
pts = this.initPTS;
while (offset < length) {
if (this.canParse(data, offset)) {
var frame = this.appendFrame(track, data, offset);
if (frame) {
this.frameIndex++;
pts = frame.sample.pts;
offset += frame.length;
lastDataIndex = offset;
} else {
offset = length;
}
} else if (_demux_id3__WEBPACK_IMPORTED_MODULE_1__["canParse"](data, offset)) {
// after a ID3.canParse, a call to ID3.getID3Data *should* always returns some data
id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getID3Data"](data, offset);
id3Track.samples.push({
pts: pts,
dts: pts,
data: id3Data
});
offset += id3Data.length;
lastDataIndex = offset;
} else {
offset++;
}
if (offset === length && lastDataIndex !== length) {
var partialData = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_4__["sliceUint8"])(data, lastDataIndex);
if (this.cachedData) {
this.cachedData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__["appendUint8Array"])(this.cachedData, partialData);
} else {
this.cachedData = partialData;
}
}
}
return {
audioTrack: track,
avcTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])(),
id3Track: id3Track,
textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])()
};
};
_proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
return Promise.reject(new Error("[" + this + "] This demuxer does not support Sample-AES decryption"));
};
_proto.flush = function flush(timeOffset) {
// Parse cache in case of remaining frames.
var cachedData = this.cachedData;
if (cachedData) {
this.cachedData = null;
this.demux(cachedData, 0);
}
this.frameIndex = 0;
return {
audioTrack: this._audioTrack,
avcTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])(),
id3Track: this._id3Track,
textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])()
};
};
_proto.destroy = function destroy() {};
return BaseAudioDemuxer;
}();
/**
* Initialize PTS
* <p>
* use timestamp unless it is undefined, NaN or Infinity
* </p>
*/
var initPTSFn = function initPTSFn(timestamp, timeOffset) {
return Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(timestamp) ? timestamp * 90 : timeOffset * 90000;
};
/* harmony default export */ __webpack_exports__["default"] = (BaseAudioDemuxer);
/***/ }),
/***/ "./src/demux/chunk-cache.ts":
/*!**********************************!*\
!*** ./src/demux/chunk-cache.ts ***!
\**********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ChunkCache; });
var ChunkCache = /*#__PURE__*/function () {
function ChunkCache() {
this.chunks = [];
this.dataLength = 0;
}
var _proto = ChunkCache.prototype;
_proto.push = function push(chunk) {
this.chunks.push(chunk);
this.dataLength += chunk.length;
};
_proto.flush = function flush() {
var chunks = this.chunks,
dataLength = this.dataLength;
var result;
if (!chunks.length) {
return new Uint8Array(0);
} else if (chunks.length === 1) {
result = chunks[0];
} else {
result = concatUint8Arrays(chunks, dataLength);
}
this.reset();
return result;
};
_proto.reset = function reset() {
this.chunks.length = 0;
this.dataLength = 0;
};
return ChunkCache;
}();
function concatUint8Arrays(chunks, dataLength) {
var result = new Uint8Array(dataLength);
var offset = 0;
for (var i = 0; i < chunks.length; i++) {
var chunk = chunks[i];
result.set(chunk, offset);
offset += chunk.length;
}
return result;
}
/***/ }),
/***/ "./src/demux/dummy-demuxed-track.ts":
/*!******************************************!*\
!*** ./src/demux/dummy-demuxed-track.ts ***!
\******************************************/
/*! exports provided: dummyTrack */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dummyTrack", function() { return dummyTrack; });
function dummyTrack() {
return {
type: '',
id: -1,
pid: -1,
inputTimeScale: 90000,
sequenceNumber: -1,
samples: [],
dropped: 0
};
}
/***/ }),
/***/ "./src/demux/exp-golomb.ts":
/*!*********************************!*\
!*** ./src/demux/exp-golomb.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/**
* Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
*/
var ExpGolomb = /*#__PURE__*/function () {
function ExpGolomb(data) {
this.data = void 0;
this.bytesAvailable = void 0;
this.word = void 0;
this.bitsAvailable = void 0;
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
var _proto = ExpGolomb.prototype;
_proto.loadWord = function loadWord() {
var data = this.data;
var bytesAvailable = this.bytesAvailable;
var position = data.byteLength - bytesAvailable;
var workingBytes = new Uint8Array(4);
var 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
;
_proto.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
;
_proto.readBits = function readBits(size) {
var bits = Math.min(this.bitsAvailable, size); // :uint
var valu = this.word >>> 32 - bits; // :uint
if (size > 32) {
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["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
;
_proto.skipLZ = function skipLZ() {
var leadingZeroCount; // :uint
for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {
// 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
;
_proto.skipUEG = function skipUEG() {
this.skipBits(1 + this.skipLZ());
} // ():void
;
_proto.skipEG = function skipEG() {
this.skipBits(1 + this.skipLZ());
} // ():uint
;
_proto.readUEG = function readUEG() {
var clz = this.skipLZ(); // :uint
return this.readBits(clz + 1) - 1;
} // ():int
;
_proto.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
;
_proto.readBoolean = function readBoolean() {
return this.readBits(1) === 1;
} // ():int
;
_proto.readUByte = function readUByte() {
return this.readBits(8);
} // ():int
;
_proto.readUShort = function readUShort() {
return this.readBits(16);
} // ():int
;
_proto.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 the number of entries in this scaling list
* @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
*/
;
_proto.skipScalingList = function skipScalingList(count) {
var lastScale = 8;
var nextScale = 8;
var deltaScale;
for (var 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.
*/
;
_proto.readSPS = function readSPS() {
var frameCropLeftOffset = 0;
var frameCropRightOffset = 0;
var frameCropTopOffset = 0;
var frameCropBottomOffset = 0;
var numRefFramesInPicOrderCntCycle;
var scalingListCount;
var i;
var readUByte = this.readUByte.bind(this);
var readBits = this.readBits.bind(this);
var readUEG = this.readUEG.bind(this);
var readBoolean = this.readBoolean.bind(this);
var skipBits = this.skipBits.bind(this);
var skipEG = this.skipEG.bind(this);
var skipUEG = this.skipUEG.bind(this);
var skipScalingList = this.skipScalingList.bind(this);
readUByte();
var profileIdc = readUByte(); // profile_idc
readBits(5); // profileCompat constraint_set[0-4]_flag, u(5)
skipBits(3); // reserved_zero_3bits u(3),
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
var picWidthInMbsMinus1 = readUEG();
var picHeightInMapUnitsMinus1 = readUEG();
var 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
};
};
_proto.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 */ __webpack_exports__["default"] = (ExpGolomb);
/***/ }),
/***/ "./src/demux/id3.ts":
/*!**************************!*\
!*** ./src/demux/id3.ts ***!
\**************************/
/*! exports provided: isHeader, isFooter, getID3Data, canParse, getTimeStamp, isTimeStampFrame, getID3Frames, decodeFrame, utf8ArrayToStr, testables */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeader", function() { return isHeader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFooter", function() { return isFooter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getID3Data", function() { return getID3Data; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canParse", function() { return canParse; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTimeStamp", function() { return getTimeStamp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isTimeStampFrame", function() { return isTimeStampFrame; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getID3Frames", function() { return getID3Frames; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "decodeFrame", function() { return decodeFrame; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "utf8ArrayToStr", function() { return utf8ArrayToStr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "testables", function() { return testables; });
// breaking up those two types in order to clarify what is happening in the decoding path.
/**
* 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
*/
var 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
*/
var 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 | undefined} - The block of data containing any ID3 tags found
* or *undefined* if no header is found at the starting offset
*/
var getID3Data = function getID3Data(data, offset) {
var front = offset;
var length = 0;
while (isHeader(data, offset)) {
// ID3 header is 10 bytes
length += 10;
var size = readSize(data, offset + 6);
length += size;
if (isFooter(data, offset + 10)) {
// ID3 footer is 10 bytes
length += 10;
}
offset += length;
}
if (length > 0) {
return data.subarray(front, front + length);
}
return undefined;
};
var 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;
};
var canParse = function canParse(data, offset) {
return isHeader(data, offset) && readSize(data, offset + 6) + 10 <= data.length - offset;
};
/**
* 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 | undefined} - The timestamp
*/
var getTimeStamp = function getTimeStamp(data) {
var frames = getID3Frames(data);
for (var i = 0; i < frames.length; i++) {
var frame = frames[i];
if (isTimeStampFrame(frame)) {
return readTimeStamp(frame);
}
}
return undefined;
};
/**
* Returns true if the ID3 frame is an Elementary Stream timestamp frame
* @param {ID3 frame} frame
*/
var isTimeStampFrame = function isTimeStampFrame(frame) {
return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';
};
var 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 = 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
*/
var getID3Frames = function getID3Frames(id3Data) {
var offset = 0;
var frames = [];
while (isHeader(id3Data, offset)) {
var size = 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 = getFrameData(id3Data.subarray(offset));
var frame = decodeFrame(frameData);
if (frame) {
frames.push(frame);
} // skip frame header and frame data
offset += frameData.size + 10;
}
if (isFooter(id3Data, offset)) {
offset += 10;
}
}
return frames;
};
var decodeFrame = function decodeFrame(frame) {
if (frame.type === 'PRIV') {
return decodePrivFrame(frame);
} else if (frame.type[0] === 'W') {
return decodeURLFrame(frame);
}
return decodeTextFrame(frame);
};
var decodePrivFrame = function decodePrivFrame(frame) {
/*
Format: <text string>\0<binary data>
*/
if (frame.size < 2) {
return undefined;
}
var owner = utf8ArrayToStr(frame.data, true);
var privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
return {
key: frame.type,
info: owner,
data: privateData.buffer
};
};
var 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 = utf8ArrayToStr(frame.data.subarray(index), true);
index += description.length + 1;
var value = utf8ArrayToStr(frame.data.subarray(index));
return {
key: frame.type,
info: description,
data: value
};
}
/*
Format:
[0] = {Text Encoding}
[1-?] = {Value}
*/
var text = utf8ArrayToStr(frame.data.subarray(1));
return {
key: frame.type,
data: text
};
};
var 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 = utf8ArrayToStr(frame.data.subarray(index), true);
index += description.length + 1;
var value = utf8ArrayToStr(frame.data.subarray(index));
return {
key: frame.type,
info: description,
data: value
};
}
/*
Format:
[0-?] = {URL}
*/
var url = utf8ArrayToStr(frame.data);
return {
key: frame.type,
data: url
};
};
var 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;
}; // 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 <[email protected]>
* Version: 1.0
* LastModified: Dec 25 1999
* This library is free. You can redistribute it and/or modify it.
*/
var utf8ArrayToStr = function utf8ArrayToStr(array, exitOnNull) {
if (exitOnNull === void 0) {
exitOnNull = false;
}
var decoder = getTextDecoder();
if (decoder) {
var decoded = decoder.decode(array);
if (exitOnNull) {
// grab up to the first null
var idx = decoded.indexOf('\0');
return idx !== -1 ? decoded.substring(0, idx) : decoded;
} // remove any null characters
return decoded.replace(/\0/g, '');
}
var len = array.length;
var c;
var char2;
var char3;
var out = '';
var i = 0;
while (i < len) {
c = array[i++];
if (c === 0x00 && exitOnNull) {
return out;
} else if (c === 0x00 || c === 0x03) {
// If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it
continue;
}
switch (c >> 4) {
case 0:
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;
default:
}
}
return out;
};
var testables = {
decodeTextFrame: decodeTextFrame
};
var decoder;
function getTextDecoder() {
if (!decoder && typeof self.TextDecoder !== 'undefined') {
decoder = new self.TextDecoder('utf-8');
}
return decoder;
}
/***/ }),
/***/ "./src/demux/mp3demuxer.ts":
/*!*********************************!*\
!*** ./src/demux/mp3demuxer.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base-audio-demuxer */ "./src/demux/base-audio-demuxer.ts");
/* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _mpegaudio__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./mpegaudio */ "./src/demux/mpegaudio.ts");
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
/**
* MP3 demuxer
*/
var MP3Demuxer = /*#__PURE__*/function (_BaseAudioDemuxer) {
_inheritsLoose(MP3Demuxer, _BaseAudioDemuxer);
function MP3Demuxer() {
return _BaseAudioDemuxer.apply(this, arguments) || this;
}
var _proto = MP3Demuxer.prototype;
_proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {
_BaseAudioDemuxer.prototype.resetInitSegment.call(this, audioCodec, videoCodec, duration);
this._audioTrack = {
container: 'audio/mpeg',
type: 'audio',
id: 0,
pid: -1,
sequenceNumber: 0,
isAAC: false,
samples: [],
manifestCodec: audioCodec,
duration: duration,
inputTimeScale: 90000,
dropped: 0
};
};
MP3Demuxer.probe = function probe(data) {
if (!data) {
return false;
} // check if data contains ID3 timestamp and MPEG sync word
// 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
var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getID3Data"](data, 0) || [];
var offset = id3Data.length;
for (var length = data.length; offset < length; offset++) {
if (_mpegaudio__WEBPACK_IMPORTED_MODULE_3__["probe"](data, offset)) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('MPEG Audio sync word found !');
return true;
}
}
return false;
};
_proto.canParse = function canParse(data, offset) {
return _mpegaudio__WEBPACK_IMPORTED_MODULE_3__["canParse"](data, offset);
};
_proto.appendFrame = function appendFrame(track, data, offset) {
if (this.initPTS === null) {
return;
}
return _mpegaudio__WEBPACK_IMPORTED_MODULE_3__["appendFrame"](track, data, offset, this.initPTS, this.frameIndex);
};
return MP3Demuxer;
}(_base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__["default"]);
MP3Demuxer.minProbeByteLength = 4;
/* harmony default export */ __webpack_exports__["default"] = (MP3Demuxer);
/***/ }),
/***/ "./src/demux/mp4demuxer.ts":
/*!*********************************!*\
!*** ./src/demux/mp4demuxer.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./dummy-demuxed-track */ "./src/demux/dummy-demuxed-track.ts");
/**
* MP4 demuxer
*/
var MP4Demuxer = /*#__PURE__*/function () {
function MP4Demuxer(observer, config) {
this.remainderData = null;
this.config = void 0;
this.config = config;
}
var _proto = MP4Demuxer.prototype;
_proto.resetTimeStamp = function resetTimeStamp() {};
_proto.resetInitSegment = function resetInitSegment() {};
_proto.resetContiguity = function resetContiguity() {};
MP4Demuxer.probe = function probe(data) {
// ensure we find a moof box in the first 16 kB
return Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["findBox"])({
data: data,
start: 0,
end: Math.min(data.length, 16384)
}, ['moof']).length > 0;
};
_proto.demux = function demux(data) {
// Load all data into the avc track. The CMAF remuxer will look for the data in the samples object; the rest of the fields do not matter
var avcSamples = data;
var avcTrack = Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])();
if (this.config.progressive) {
// Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else.
// This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee
// that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception.
if (this.remainderData) {
avcSamples = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["appendUint8Array"])(this.remainderData, data);
}
var segmentedData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["segmentValidRange"])(avcSamples);
this.remainderData = segmentedData.remainder;
avcTrack.samples = segmentedData.valid || new Uint8Array();
} else {
avcTrack.samples = avcSamples;
}
return {
audioTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(),
avcTrack: avcTrack,
id3Track: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(),
textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])()
};
};
_proto.flush = function flush() {
var avcTrack = Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])();
avcTrack.samples = this.remainderData || new Uint8Array();
this.remainderData = null;
return {
audioTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(),
avcTrack: avcTrack,
id3Track: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(),
textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])()
};
};
_proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
return Promise.reject(new Error('The MP4 demuxer does not support SAMPLE-AES decryption'));
};
_proto.destroy = function destroy() {};
return MP4Demuxer;
}();
MP4Demuxer.minProbeByteLength = 1024;
/* harmony default export */ __webpack_exports__["default"] = (MP4Demuxer);
/***/ }),
/***/ "./src/demux/mpegaudio.ts":
/*!********************************!*\
!*** ./src/demux/mpegaudio.ts ***!
\********************************/
/*! exports provided: appendFrame, parseHeader, isHeaderPattern, isHeader, canParse, probe */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendFrame", function() { return appendFrame; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseHeader", function() { return parseHeader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeaderPattern", function() { return isHeaderPattern; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeader", function() { return isHeader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canParse", function() { return canParse; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "probe", function() { return probe; });
/**
* MPEG parser helper
*/
var chromeVersion = null;
var 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];
var SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000];
var SamplesCoefficients = [// MPEG 2.5
[0, // Reserved
72, // Layer3
144, // Layer2
12 // Layer1
], // Reserved
[0, // Reserved
0, // Layer3
0, // Layer2
0 // Layer1
], // MPEG 2
[0, // Reserved
72, // Layer3
144, // Layer2
12 // Layer1
], // MPEG 1
[0, // Reserved
144, // Layer3
144, // Layer2
12 // Layer1
]];
var BytesInSlot = [0, // Reserved
1, // Layer3
1, // Layer2
4 // Layer1
];
function appendFrame(track, data, offset, pts, frameIndex) {
// Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
if (offset + 24 > data.length) {
return;
}
var header = parseHeader(data, offset);
if (header && offset + header.frameLength <= data.length) {
var frameDuration = header.samplesPerFrame * 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);
return {
sample: sample,
length: header.frameLength,
missing: 0
};
}
}
function parseHeader(data, offset) {
var mpegVersion = data[offset + 1] >> 3 & 3;
var mpegLayer = data[offset + 1] >> 1 & 3;
var bitRateIndex = data[offset + 2] >> 4 & 15;
var sampleRateIndex = data[offset + 2] >> 2 & 3;
if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {
var paddingBit = data[offset + 2] >> 1 & 1;
var channelMode = data[offset + 3] >> 6;
var columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;
var bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000;
var columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;
var sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];
var channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
var sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];
var bytesInSlot = BytesInSlot[mpegLayer];
var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
var frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot;
if (chromeVersion === null) {
var userAgent = navigator.userAgent || '';
var result = userAgent.match(/Chrome\/(\d+)/i);
chromeVersion = result ? parseInt(result[1]) : 0;
}
var needChromeFix = !!chromeVersion && chromeVersion <= 87;
if (needChromeFix && mpegLayer === 2 && bitRate >= 224000 && channelMode === 0) {
// Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00)
data[offset + 3] = data[offset + 3] | 0x80;
}
return {
sampleRate: sampleRate,
channelCount: channelCount,
frameLength: frameLength,
samplesPerFrame: samplesPerFrame
};
}
}
function isHeaderPattern(data, offset) {
return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
}
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
return offset + 1 < data.length && isHeaderPattern(data, offset);
}
function canParse(data, offset) {
var headerSize = 4;
return isHeaderPattern(data, offset) && headerSize <= data.length - offset;
}
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 && isHeaderPattern(data, offset)) {
// MPEG header Length
var headerLength = 4; // MPEG frame Length
var header = parseHeader(data, offset);
var frameLength = headerLength;
if (header !== null && header !== void 0 && header.frameLength) {
frameLength = header.frameLength;
}
var newOffset = offset + frameLength;
return newOffset === data.length || isHeader(data, newOffset);
}
return false;
}
/***/ }),
/***/ "./src/demux/sample-aes.ts":
/*!*********************************!*\
!*** ./src/demux/sample-aes.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts");
/* harmony import */ var _tsdemuxer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./tsdemuxer */ "./src/demux/tsdemuxer.ts");
/**
* SAMPLE-AES decrypter
*/
var SampleAesDecrypter = /*#__PURE__*/function () {
function SampleAesDecrypter(observer, config, keyData) {
this.keyData = void 0;
this.decrypter = void 0;
this.keyData = keyData;
this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_0__["default"](observer, config, {
removePKCS7Padding: false
});
}
var _proto = SampleAesDecrypter.prototype;
_proto.decryptBuffer = function decryptBuffer(encryptedData, callback) {
this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer, callback);
} // AAC - encrypt all full 16 bytes blocks starting from offset 16
;
_proto.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 (decryptedBuffer) {
var decryptedData = new Uint8Array(decryptedBuffer);
curUnit.set(decryptedData, 16);
if (!sync) {
localthis.decryptAacSamples(samples, sampleIndex + 1, callback);
}
});
};
_proto.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
;
_proto.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;
};
_proto.getAvcDecryptedUnit = function getAvcDecryptedUnit(decodedData, decryptedData) {
var uint8DecryptedData = new Uint8Array(decryptedData);
var inputPos = 0;
for (var outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {
decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);
}
return decodedData;
};
_proto.decryptAvcSample = function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) {
var decodedData = Object(_tsdemuxer__WEBPACK_IMPORTED_MODULE_1__["discardEPB"])(curUnit.data);
var encryptedData = this.getAvcEncryptedData(decodedData);
var localthis = this;
this.decryptBuffer(encryptedData.buffer, function (decryptedBuffer) {
curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedBuffer);
if (!sync) {
localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
}
});
};
_proto.decryptAvcSamples = function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
if (samples instanceof Uint8Array) {
throw new Error('Cannot decrypt samples of type Uint8Array');
}
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.data.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 */ __webpack_exports__["default"] = (SampleAesDecrypter);
/***/ }),
/***/ "./src/demux/transmuxer-interface.ts":
/*!*******************************************!*\
!*** ./src/demux/transmuxer-interface.ts ***!
\*******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TransmuxerInterface; });
/* harmony import */ var webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! webworkify-webpack */ "./node_modules/webworkify-webpack/index.js");
/* harmony import */ var webworkify_webpack__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/transmuxer */ "./src/demux/transmuxer.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/mediasource-helper */ "./src/utils/mediasource-helper.ts");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_6__);
var MediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__["getMediaSource"])() || {
isTypeSupported: function isTypeSupported() {
return false;
}
};
var TransmuxerInterface = /*#__PURE__*/function () {
function TransmuxerInterface(hls, id, onTransmuxComplete, onFlush) {
var _this = this;
this.hls = void 0;
this.id = void 0;
this.observer = void 0;
this.frag = null;
this.part = null;
this.worker = void 0;
this.onwmsg = void 0;
this.transmuxer = null;
this.onTransmuxComplete = void 0;
this.onFlush = void 0;
this.hls = hls;
this.id = id;
this.onTransmuxComplete = onTransmuxComplete;
this.onFlush = onFlush;
var config = hls.config;
var forwardMessage = function forwardMessage(ev, data) {
data = data || {};
data.frag = _this.frag;
data.id = _this.id;
hls.trigger(ev, data);
}; // forward events to main thread
this.observer = new eventemitter3__WEBPACK_IMPORTED_MODULE_6__["EventEmitter"]();
this.observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, forwardMessage);
this.observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, forwardMessage);
var typeSupported = {
mp4: MediaSource.isTypeSupported('video/mp4'),
mpeg: MediaSource.isTypeSupported('audio/mpeg'),
mp3: 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') {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log('demuxing in webworker');
var worker;
try {
worker = this.worker = webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__(/*require.resolve*/(/*! ../demux/transmuxer-worker.ts */ "./src/demux/transmuxer-worker.ts"));
this.onwmsg = this.onWorkerMessage.bind(this);
worker.addEventListener('message', this.onwmsg);
worker.onerror = function (event) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].OTHER_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].INTERNAL_EXCEPTION,
fatal: true,
event: 'demuxerWorker',
error: new Error(event.message + " (" + event.filename + ":" + event.lineno + ")")
});
};
worker.postMessage({
cmd: 'init',
typeSupported: typeSupported,
vendor: vendor,
id: id,
config: JSON.stringify(config)
});
} catch (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Error in worker:', err);
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].error('Error while initializing DemuxerWorker, fallback to inline');
if (worker) {
// revoke the Object URL that was used to create transmuxer worker, so as not to leak it
self.URL.revokeObjectURL(worker.objectURL);
}
this.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, typeSupported, config, vendor, id);
this.worker = null;
}
} else {
this.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, typeSupported, config, vendor, id);
}
}
var _proto = TransmuxerInterface.prototype;
_proto.destroy = function destroy() {
var w = this.worker;
if (w) {
w.removeEventListener('message', this.onwmsg);
w.terminate();
this.worker = null;
} else {
var transmuxer = this.transmuxer;
if (transmuxer) {
transmuxer.destroy();
this.transmuxer = null;
}
}
var observer = this.observer;
if (observer) {
observer.removeAllListeners();
} // @ts-ignore
this.observer = null;
};
_proto.push = function push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) {
var _this2 = this;
chunkMeta.transmuxing.start = self.performance.now();
var transmuxer = this.transmuxer,
worker = this.worker;
var timeOffset = part ? part.start : frag.start;
var decryptdata = frag.decryptdata;
var lastFrag = this.frag;
var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
var trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);
var snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;
var partDiff = this.part ? chunkMeta.part - this.part.index : 1;
var contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && partDiff === 1);
var now = self.performance.now();
if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {
frag.stats.parsing.start = now;
}
if (part && (partDiff || !contiguous)) {
part.stats.parsing.start = now;
}
var state = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["TransmuxState"](discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset);
if (!contiguous || discontinuity) {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log("[transmuxer-interface, " + frag.type + "]: Starting new transmux session for sn: " + chunkMeta.sn + " p: " + chunkMeta.part + " level: " + chunkMeta.level + " id: " + chunkMeta.id + "\n discontinuity: " + discontinuity + "\n trackSwitch: " + trackSwitch + "\n contiguous: " + contiguous + "\n accurateTimeOffset: " + accurateTimeOffset + "\n timeOffset: " + timeOffset);
var config = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["TransmuxConfig"](audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS);
this.configureTransmuxer(config);
}
this.frag = frag;
this.part = part; // Frags with sn of 'initSegment' are not transmuxed
if (worker) {
// post fragment payload as transferable objects for ArrayBuffer (no copy)
worker.postMessage({
cmd: 'demux',
data: data,
decryptdata: decryptdata,
chunkMeta: chunkMeta,
state: state
}, data instanceof ArrayBuffer ? [data] : []);
} else if (transmuxer) {
var _transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);
if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["isPromise"])(_transmuxResult)) {
_transmuxResult.then(function (data) {
_this2.handleTransmuxComplete(data);
});
} else {
this.handleTransmuxComplete(_transmuxResult);
}
}
};
_proto.flush = function flush(chunkMeta) {
var _this3 = this;
chunkMeta.transmuxing.start = self.performance.now();
var transmuxer = this.transmuxer,
worker = this.worker;
if (worker) {
worker.postMessage({
cmd: 'flush',
chunkMeta: chunkMeta
});
} else if (transmuxer) {
var _transmuxResult2 = transmuxer.flush(chunkMeta);
if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["isPromise"])(_transmuxResult2)) {
_transmuxResult2.then(function (data) {
_this3.handleFlushResult(data, chunkMeta);
});
} else {
this.handleFlushResult(_transmuxResult2, chunkMeta);
}
}
};
_proto.handleFlushResult = function handleFlushResult(results, chunkMeta) {
var _this4 = this;
results.forEach(function (result) {
_this4.handleTransmuxComplete(result);
});
this.onFlush(chunkMeta);
};
_proto.onWorkerMessage = function onWorkerMessage(ev) {
var data = ev.data;
var hls = this.hls;
switch (data.event) {
case 'init':
{
// revoke the Object URL that was used to create transmuxer worker, so as not to leak it
self.URL.revokeObjectURL(this.worker.objectURL);
break;
}
case 'transmuxComplete':
{
this.handleTransmuxComplete(data.data);
break;
}
case 'flush':
{
this.onFlush(data.data);
break;
}
/* falls through */
default:
{
data.data = data.data || {};
data.data.frag = this.frag;
data.data.id = this.id;
hls.trigger(data.event, data.data);
break;
}
}
};
_proto.configureTransmuxer = function configureTransmuxer(config) {
var worker = this.worker,
transmuxer = this.transmuxer;
if (worker) {
worker.postMessage({
cmd: 'configure',
config: config
});
} else if (transmuxer) {
transmuxer.configure(config);
}
};
_proto.handleTransmuxComplete = function handleTransmuxComplete(result) {
result.chunkMeta.transmuxing.end = self.performance.now();
this.onTransmuxComplete(result);
};
return TransmuxerInterface;
}();
/***/ }),
/***/ "./src/demux/transmuxer-worker.ts":
/*!****************************************!*\
!*** ./src/demux/transmuxer-worker.ts ***!
\****************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TransmuxerWorker; });
/* harmony import */ var _demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../demux/transmuxer */ "./src/demux/transmuxer.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_3__);
function TransmuxerWorker(self) {
var observer = new eventemitter3__WEBPACK_IMPORTED_MODULE_3__["EventEmitter"]();
var forwardMessage = function forwardMessage(ev, data) {
self.postMessage({
event: ev,
data: data
});
}; // forward events to main thread
observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, forwardMessage);
observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, forwardMessage);
self.addEventListener('message', function (ev) {
var data = ev.data;
switch (data.cmd) {
case 'init':
{
var config = JSON.parse(data.config);
self.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__["default"](observer, data.typeSupported, config, data.vendor, data.id);
Object(_utils_logger__WEBPACK_IMPORTED_MODULE_2__["enableLogs"])(config.debug);
forwardMessage('init', null);
break;
}
case 'configure':
{
self.transmuxer.configure(data.config);
break;
}
case 'demux':
{
var transmuxResult = self.transmuxer.push(data.data, data.decryptdata, data.chunkMeta, data.state);
if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__["isPromise"])(transmuxResult)) {
transmuxResult.then(function (data) {
emitTransmuxComplete(self, data);
});
} else {
emitTransmuxComplete(self, transmuxResult);
}
break;
}
case 'flush':
{
var id = data.chunkMeta;
var _transmuxResult = self.transmuxer.flush(id);
if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__["isPromise"])(_transmuxResult)) {
_transmuxResult.then(function (results) {
handleFlushResult(self, results, id);
});
} else {
handleFlushResult(self, _transmuxResult, id);
}
break;
}
default:
break;
}
});
}
function emitTransmuxComplete(self, transmuxResult) {
if (isEmptyResult(transmuxResult.remuxResult)) {
return;
}
var transferable = [];
var _transmuxResult$remux = transmuxResult.remuxResult,
audio = _transmuxResult$remux.audio,
video = _transmuxResult$remux.video;
if (audio) {
addToTransferable(transferable, audio);
}
if (video) {
addToTransferable(transferable, video);
}
self.postMessage({
event: 'transmuxComplete',
data: transmuxResult
}, transferable);
} // Converts data to a transferable object https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast)
// in order to minimize message passing overhead
function addToTransferable(transferable, track) {
if (track.data1) {
transferable.push(track.data1.buffer);
}
if (track.data2) {
transferable.push(track.data2.buffer);
}
}
function handleFlushResult(self, results, chunkMeta) {
results.forEach(function (result) {
emitTransmuxComplete(self, result);
});
self.postMessage({
event: 'flush',
data: chunkMeta
});
}
function isEmptyResult(remuxResult) {
return !remuxResult.audio && !remuxResult.video && !remuxResult.text && !remuxResult.id3 && !remuxResult.initSegment;
}
/***/ }),
/***/ "./src/demux/transmuxer.ts":
/*!*********************************!*\
!*** ./src/demux/transmuxer.ts ***!
\*********************************/
/*! exports provided: default, isPromise, TransmuxConfig, TransmuxState */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Transmuxer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPromise", function() { return isPromise; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransmuxConfig", function() { return TransmuxConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransmuxState", function() { return TransmuxState; });
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts");
/* harmony import */ var _demux_aacdemuxer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/aacdemuxer */ "./src/demux/aacdemuxer.ts");
/* harmony import */ var _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../demux/mp4demuxer */ "./src/demux/mp4demuxer.ts");
/* harmony import */ var _demux_tsdemuxer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../demux/tsdemuxer */ "./src/demux/tsdemuxer.ts");
/* harmony import */ var _demux_mp3demuxer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../demux/mp3demuxer */ "./src/demux/mp3demuxer.ts");
/* harmony import */ var _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../remux/mp4-remuxer */ "./src/remux/mp4-remuxer.ts");
/* harmony import */ var _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../remux/passthrough-remuxer */ "./src/remux/passthrough-remuxer.ts");
/* harmony import */ var _chunk_cache__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./chunk-cache */ "./src/demux/chunk-cache.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var now; // performance.now() not available on WebWorker, at least on Safari Desktop
try {
now = self.performance.now.bind(self.performance);
} catch (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_11__["logger"].debug('Unable to use Performance API on this environment');
now = self.Date.now;
}
var muxConfig = [{
demux: _demux_tsdemuxer__WEBPACK_IMPORTED_MODULE_5__["default"],
remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"]
}, {
demux: _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__["default"],
remux: _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__["default"]
}, {
demux: _demux_aacdemuxer__WEBPACK_IMPORTED_MODULE_3__["default"],
remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"]
}, {
demux: _demux_mp3demuxer__WEBPACK_IMPORTED_MODULE_6__["default"],
remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"]
}];
var minProbeByteLength = 1024;
muxConfig.forEach(function (_ref) {
var demux = _ref.demux;
minProbeByteLength = Math.max(minProbeByteLength, demux.minProbeByteLength);
});
var Transmuxer = /*#__PURE__*/function () {
function Transmuxer(observer, typeSupported, config, vendor, id) {
this.observer = void 0;
this.typeSupported = void 0;
this.config = void 0;
this.vendor = void 0;
this.id = void 0;
this.demuxer = void 0;
this.remuxer = void 0;
this.decrypter = void 0;
this.probe = void 0;
this.decryptionPromise = null;
this.transmuxConfig = void 0;
this.currentTransmuxState = void 0;
this.cache = new _chunk_cache__WEBPACK_IMPORTED_MODULE_9__["default"]();
this.observer = observer;
this.typeSupported = typeSupported;
this.config = config;
this.vendor = vendor;
this.id = id;
}
var _proto = Transmuxer.prototype;
_proto.configure = function configure(transmuxConfig) {
this.transmuxConfig = transmuxConfig;
if (this.decrypter) {
this.decrypter.reset();
}
};
_proto.push = function push(data, decryptdata, chunkMeta, state) {
var _this = this;
var stats = chunkMeta.transmuxing;
stats.executeStart = now();
var uintData = new Uint8Array(data);
var cache = this.cache,
config = this.config,
currentTransmuxState = this.currentTransmuxState,
transmuxConfig = this.transmuxConfig;
if (state) {
this.currentTransmuxState = state;
}
var keyData = getEncryptionType(uintData, decryptdata);
if (keyData && keyData.method === 'AES-128') {
var decrypter = this.getDecrypter(); // Software decryption is synchronous; webCrypto is not
if (config.enableSoftwareAES) {
// Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
// data is handled in the flush() call
var decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer);
if (!decryptedData) {
stats.executeEnd = now();
return emptyResult(chunkMeta);
}
uintData = new Uint8Array(decryptedData);
} else {
this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer).then(function (decryptedData) {
// Calling push here is important; if flush() is called while this is still resolving, this ensures that
// the decrypted data has been transmuxed
var result = _this.push(decryptedData, null, chunkMeta);
_this.decryptionPromise = null;
return result;
});
return this.decryptionPromise;
}
}
var _ref2 = state || currentTransmuxState,
contiguous = _ref2.contiguous,
discontinuity = _ref2.discontinuity,
trackSwitch = _ref2.trackSwitch,
accurateTimeOffset = _ref2.accurateTimeOffset,
timeOffset = _ref2.timeOffset;
var audioCodec = transmuxConfig.audioCodec,
videoCodec = transmuxConfig.videoCodec,
defaultInitPts = transmuxConfig.defaultInitPts,
duration = transmuxConfig.duration,
initSegmentData = transmuxConfig.initSegmentData; // Reset muxers before probing to ensure that their state is clean, even if flushing occurs before a successful probe
if (discontinuity || trackSwitch) {
this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration);
}
if (discontinuity) {
this.resetInitialTimestamp(defaultInitPts);
}
if (!contiguous) {
this.resetContiguity();
}
if (this.needsProbing(uintData, discontinuity, trackSwitch)) {
if (cache.dataLength) {
var cachedData = cache.flush();
uintData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_10__["appendUint8Array"])(cachedData, uintData);
}
this.configureTransmuxer(uintData, transmuxConfig);
}
var result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);
var currentState = this.currentTransmuxState;
currentState.contiguous = true;
currentState.discontinuity = false;
currentState.trackSwitch = false;
stats.executeEnd = now();
return result;
} // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)
;
_proto.flush = function flush(chunkMeta) {
var _this2 = this;
var stats = chunkMeta.transmuxing;
stats.executeStart = now();
var decrypter = this.decrypter,
cache = this.cache,
currentTransmuxState = this.currentTransmuxState,
decryptionPromise = this.decryptionPromise;
if (decryptionPromise) {
// Upon resolution, the decryption promise calls push() and returns its TransmuxerResult up the stack. Therefore
// only flushing is required for async decryption
return decryptionPromise.then(function () {
return _this2.flush(chunkMeta);
});
}
var transmuxResults = [];
var timeOffset = currentTransmuxState.timeOffset;
if (decrypter) {
// The decrypter may have data cached, which needs to be demuxed. In this case we'll have two TransmuxResults
// This happens in the case that we receive only 1 push call for a segment (either for non-progressive downloads,
// or for progressive downloads with small segments)
var decryptedData = decrypter.flush();
if (decryptedData) {
// Push always returns a TransmuxerResult if decryptdata is null
transmuxResults.push(this.push(decryptedData, null, chunkMeta));
}
}
var bytesSeen = cache.dataLength;
cache.reset();
var demuxer = this.demuxer,
remuxer = this.remuxer;
if (!demuxer || !remuxer) {
// If probing failed, and each demuxer saw enough bytes to be able to probe, then Hls.js has been given content its not able to handle
if (bytesSeen >= minProbeByteLength) {
this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_PARSING_ERROR,
fatal: true,
reason: 'no demux matching with content found'
});
}
stats.executeEnd = now();
return [emptyResult(chunkMeta)];
}
var demuxResultOrPromise = demuxer.flush(timeOffset);
if (isPromise(demuxResultOrPromise)) {
// Decrypt final SAMPLE-AES samples
return demuxResultOrPromise.then(function (demuxResult) {
_this2.flushRemux(transmuxResults, demuxResult, chunkMeta);
return transmuxResults;
});
}
this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);
return transmuxResults;
};
_proto.flushRemux = function flushRemux(transmuxResults, demuxResult, chunkMeta) {
var audioTrack = demuxResult.audioTrack,
avcTrack = demuxResult.avcTrack,
id3Track = demuxResult.id3Track,
textTrack = demuxResult.textTrack;
var _this$currentTransmux = this.currentTransmuxState,
accurateTimeOffset = _this$currentTransmux.accurateTimeOffset,
timeOffset = _this$currentTransmux.timeOffset;
_utils_logger__WEBPACK_IMPORTED_MODULE_11__["logger"].log("[transmuxer.ts]: Flushed fragment " + chunkMeta.sn + (chunkMeta.part > -1 ? ' p: ' + chunkMeta.part : '') + " of level " + chunkMeta.level);
var remuxResult = this.remuxer.remux(audioTrack, avcTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id);
transmuxResults.push({
remuxResult: remuxResult,
chunkMeta: chunkMeta
});
chunkMeta.transmuxing.executeEnd = now();
};
_proto.resetInitialTimestamp = function resetInitialTimestamp(defaultInitPts) {
var demuxer = this.demuxer,
remuxer = this.remuxer;
if (!demuxer || !remuxer) {
return;
}
demuxer.resetTimeStamp(defaultInitPts);
remuxer.resetTimeStamp(defaultInitPts);
};
_proto.resetContiguity = function resetContiguity() {
var demuxer = this.demuxer,
remuxer = this.remuxer;
if (!demuxer || !remuxer) {
return;
}
demuxer.resetContiguity();
remuxer.resetNextTimestamp();
};
_proto.resetInitSegment = function resetInitSegment(initSegmentData, audioCodec, videoCodec, duration) {
var demuxer = this.demuxer,
remuxer = this.remuxer;
if (!demuxer || !remuxer) {
return;
}
demuxer.resetInitSegment(audioCodec, videoCodec, duration);
remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec);
};
_proto.destroy = function destroy() {
if (this.demuxer) {
this.demuxer.destroy();
this.demuxer = undefined;
}
if (this.remuxer) {
this.remuxer.destroy();
this.remuxer = undefined;
}
};
_proto.transmux = function transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {
var result;
if (keyData && keyData.method === 'SAMPLE-AES') {
result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);
} else {
result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);
}
return result;
};
_proto.transmuxUnencrypted = function transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {
var _demux = this.demuxer.demux(data, timeOffset, false, !this.config.progressive),
audioTrack = _demux.audioTrack,
avcTrack = _demux.avcTrack,
id3Track = _demux.id3Track,
textTrack = _demux.textTrack;
var remuxResult = this.remuxer.remux(audioTrack, avcTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id);
return {
remuxResult: remuxResult,
chunkMeta: chunkMeta
};
};
_proto.transmuxSampleAes = function transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {
var _this3 = this;
return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then(function (demuxResult) {
var remuxResult = _this3.remuxer.remux(demuxResult.audioTrack, demuxResult.avcTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, _this3.id);
return {
remuxResult: remuxResult,
chunkMeta: chunkMeta
};
});
};
_proto.configureTransmuxer = function configureTransmuxer(data, transmuxConfig) {
var config = this.config,
observer = this.observer,
typeSupported = this.typeSupported,
vendor = this.vendor;
var audioCodec = transmuxConfig.audioCodec,
defaultInitPts = transmuxConfig.defaultInitPts,
duration = transmuxConfig.duration,
initSegmentData = transmuxConfig.initSegmentData,
videoCodec = transmuxConfig.videoCodec; // probe for content type
var mux;
for (var i = 0, len = muxConfig.length; i < len; i++) {
if (muxConfig[i].demux.probe(data)) {
mux = muxConfig[i];
break;
}
}
if (!mux) {
// If probing previous configs fail, use mp4 passthrough
_utils_logger__WEBPACK_IMPORTED_MODULE_11__["logger"].warn('Failed to find demuxer by probing frag, treating as mp4 passthrough');
mux = {
demux: _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__["default"],
remux: _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__["default"]
};
} // so let's check that current remuxer and demuxer are still valid
var demuxer = this.demuxer;
var remuxer = this.remuxer;
var Remuxer = mux.remux;
var Demuxer = mux.demux;
if (!remuxer || !(remuxer instanceof Remuxer)) {
this.remuxer = new Remuxer(observer, config, typeSupported, vendor);
}
if (!demuxer || !(demuxer instanceof Demuxer)) {
this.demuxer = new Demuxer(observer, config, typeSupported);
this.probe = Demuxer.probe;
} // Ensure that muxers are always initialized with an initSegment
this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration);
this.resetInitialTimestamp(defaultInitPts);
};
_proto.needsProbing = function needsProbing(data, discontinuity, trackSwitch) {
// in case of continuity change, or track switch
// we might switch from content type (AAC container to TS container, or TS to fmp4 for example)
return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;
};
_proto.getDecrypter = function getDecrypter() {
var decrypter = this.decrypter;
if (!decrypter) {
decrypter = this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, this.config);
}
return decrypter;
};
return Transmuxer;
}();
function getEncryptionType(data, decryptData) {
var encryptionType = null;
if (data.byteLength > 0 && decryptData != null && decryptData.key != null && decryptData.iv !== null && decryptData.method != null) {
encryptionType = decryptData;
}
return encryptionType;
}
var emptyResult = function emptyResult(chunkMeta) {
return {
remuxResult: {},
chunkMeta: chunkMeta
};
};
function isPromise(p) {
return 'then' in p && p.then instanceof Function;
}
var TransmuxConfig = function TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) {
this.audioCodec = void 0;
this.videoCodec = void 0;
this.initSegmentData = void 0;
this.duration = void 0;
this.defaultInitPts = void 0;
this.audioCodec = audioCodec;
this.videoCodec = videoCodec;
this.initSegmentData = initSegmentData;
this.duration = duration;
this.defaultInitPts = defaultInitPts;
};
var TransmuxState = function TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset) {
this.discontinuity = void 0;
this.contiguous = void 0;
this.accurateTimeOffset = void 0;
this.trackSwitch = void 0;
this.timeOffset = void 0;
this.discontinuity = discontinuity;
this.contiguous = contiguous;
this.accurateTimeOffset = accurateTimeOffset;
this.trackSwitch = trackSwitch;
this.timeOffset = timeOffset;
};
/***/ }),
/***/ "./src/demux/tsdemuxer.ts":
/*!********************************!*\
!*** ./src/demux/tsdemuxer.ts ***!
\********************************/
/*! exports provided: discardEPB, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "discardEPB", function() { return discardEPB; });
/* harmony import */ var _adts__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./adts */ "./src/demux/adts.ts");
/* harmony import */ var _mpegaudio__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./mpegaudio */ "./src/demux/mpegaudio.ts");
/* harmony import */ var _exp_golomb__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./exp-golomb */ "./src/demux/exp-golomb.ts");
/* harmony import */ var _id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./id3 */ "./src/demux/id3.ts");
/* harmony import */ var _sample_aes__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./sample-aes */ "./src/demux/sample-aes.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/**
* 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.
*/
// We are using fixed track IDs for driving the MP4 remuxer
// instead of following the TS PIDs.
// There is no reason not to do this and some browsers/SourceBuffer-demuxers
// may not like if there are TrackID "switches"
// See https://github.com/video-dev/hls.js/issues/1331
// Here we are mapping our internal track types to constant MP4 track IDs
// With MSE currently one can only have one track of each, and we are muxing
// whatever video/audio rendition in them.
var RemuxerTrackIdConfig = {
video: 1,
audio: 2,
id3: 3,
text: 4
};
var TSDemuxer = /*#__PURE__*/function () {
function TSDemuxer(observer, config, typeSupported) {
this.observer = void 0;
this.config = void 0;
this.typeSupported = void 0;
this.sampleAes = null;
this.pmtParsed = false;
this.audioCodec = void 0;
this.videoCodec = void 0;
this._duration = 0;
this.aacLastPTS = null;
this._initPTS = null;
this._initDTS = null;
this._pmtId = -1;
this._avcTrack = void 0;
this._audioTrack = void 0;
this._id3Track = void 0;
this._txtTrack = void 0;
this.aacOverFlow = null;
this.avcSample = null;
this.remainderData = null;
this.observer = observer;
this.config = config;
this.typeSupported = typeSupported;
}
TSDemuxer.probe = function probe(data) {
var syncOffset = TSDemuxer.syncOffset(data);
if (syncOffset < 0) {
return false;
} else {
if (syncOffset) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["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;
}
/**
* Creates a track model internal to demuxer used to drive remuxing input
*
* @param type 'audio' | 'video' | 'id3' | 'text'
* @param duration
* @return TSDemuxer's internal track model
*/
;
TSDemuxer.createTrack = function createTrack(type, duration) {
return {
container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
type: type,
id: RemuxerTrackIdConfig[type],
pid: -1,
inputTimeScale: 90000,
sequenceNumber: 0,
samples: [],
dropped: 0,
duration: type === 'audio' ? duration : undefined
};
}
/**
* Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
* Resets all internal track instances of the demuxer.
*/
;
var _proto = TSDemuxer.prototype;
_proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {
this.pmtParsed = false;
this._pmtId = -1;
this._avcTrack = TSDemuxer.createTrack('video', duration);
this._audioTrack = TSDemuxer.createTrack('audio', duration);
this._id3Track = TSDemuxer.createTrack('id3', duration);
this._txtTrack = TSDemuxer.createTrack('text', duration);
this._audioTrack.isAAC = true; // flush any partial content
this.aacOverFlow = null;
this.aacLastPTS = null;
this.avcSample = null;
this.audioCodec = audioCodec;
this.videoCodec = videoCodec;
this._duration = duration;
};
_proto.resetTimeStamp = function resetTimeStamp() {};
_proto.resetContiguity = function resetContiguity() {
var _audioTrack = this._audioTrack,
_avcTrack = this._avcTrack,
_id3Track = this._id3Track;
if (_audioTrack) {
_audioTrack.pesData = null;
}
if (_avcTrack) {
_avcTrack.pesData = null;
}
if (_id3Track) {
_id3Track.pesData = null;
}
this.aacOverFlow = null;
this.aacLastPTS = null;
};
_proto.demux = function demux(data, timeOffset, isSampleAes, flush) {
if (isSampleAes === void 0) {
isSampleAes = false;
}
if (flush === void 0) {
flush = false;
}
if (!isSampleAes) {
this.sampleAes = null;
}
var pes;
var avcTrack = this._avcTrack;
var audioTrack = this._audioTrack;
var id3Track = this._id3Track;
var avcId = avcTrack.pid;
var avcData = avcTrack.pesData;
var audioId = audioTrack.pid;
var id3Id = id3Track.pid;
var audioData = audioTrack.pesData;
var id3Data = id3Track.pesData;
var unknownPIDs = false;
var pmtParsed = this.pmtParsed;
var pmtId = this._pmtId;
var len = data.length;
if (this.remainderData) {
data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_6__["appendUint8Array"])(this.remainderData, data);
len = data.length;
this.remainderData = null;
}
if (len < 188 && !flush) {
this.remainderData = data;
return {
audioTrack: audioTrack,
avcTrack: avcTrack,
id3Track: id3Track,
textTrack: this._txtTrack
};
}
var syncOffset = Math.max(0, TSDemuxer.syncOffset(data));
len -= (len + syncOffset) % 188;
if (len < data.byteLength && !flush) {
this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);
} // loop through TS packets
for (var start = syncOffset; start < len; start += 188) {
if (data[start] === 0x47) {
var stt = !!(data[start + 1] & 0x40); // pid is a 13-bit field starting at the last bit of TS[1]
var pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];
var 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.
var offset = void 0;
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))) {
this.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) {
this.parseAACPES(pes);
} else {
this.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))) {
this.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, isSampleAes); // 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
// NOTE this is only the PID of the track as found in TS,
// but we are not using this for MP4 track IDs.
avcId = parsedPIDs.avc;
if (avcId > 0) {
avcTrack.pid = avcId;
}
audioId = parsedPIDs.audio;
if (audioId > 0) {
audioTrack.pid = audioId;
audioTrack.isAAC = parsedPIDs.isAAC;
}
id3Id = parsedPIDs.id3;
if (id3Id > 0) {
id3Track.pid = id3Id;
}
if (unknownPIDs && !pmtParsed) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["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.emit(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorDetails"].FRAG_PARSING_ERROR,
fatal: false,
reason: 'TS packet did not start with 0x47'
});
}
}
avcTrack.pesData = avcData;
audioTrack.pesData = audioData;
id3Track.pesData = id3Data;
var demuxResult = {
audioTrack: audioTrack,
avcTrack: avcTrack,
id3Track: id3Track,
textTrack: this._txtTrack
};
if (flush) {
this.extractRemainingSamples(demuxResult);
}
return demuxResult;
};
_proto.flush = function flush() {
var remainderData = this.remainderData;
this.remainderData = null;
var result;
if (remainderData) {
result = this.demux(remainderData, -1, false, true);
} else {
result = {
audioTrack: this._audioTrack,
avcTrack: this._avcTrack,
textTrack: this._txtTrack,
id3Track: this._id3Track
};
}
this.extractRemainingSamples(result);
if (this.sampleAes) {
return this.decrypt(result, this.sampleAes);
}
return result;
};
_proto.extractRemainingSamples = function extractRemainingSamples(demuxResult) {
var audioTrack = demuxResult.audioTrack,
avcTrack = demuxResult.avcTrack,
id3Track = demuxResult.id3Track;
var avcData = avcTrack.pesData;
var audioData = audioTrack.pesData;
var id3Data = id3Track.pesData; // try to parse last PES packets
var pes;
if (avcData && (pes = parsePES(avcData))) {
this.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) {
this.parseAACPES(pes);
} else {
this.parseMPEGPES(pes);
}
audioTrack.pesData = null;
} else {
if (audioData !== null && audioData !== void 0 && audioData.size) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["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))) {
this.parseID3PES(pes);
id3Track.pesData = null;
} else {
// either id3Data null or PES truncated, keep it for next frag parsing
id3Track.pesData = id3Data;
}
};
_proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
var demuxResult = this.demux(data, timeOffset, true, !this.config.progressive);
var sampleAes = this.sampleAes = new _sample_aes__WEBPACK_IMPORTED_MODULE_4__["default"](this.observer, this.config, keyData);
return this.decrypt(demuxResult, sampleAes);
};
_proto.decrypt = function decrypt(demuxResult, sampleAes) {
return new Promise(function (resolve) {
var audioTrack = demuxResult.audioTrack,
avcTrack = demuxResult.avcTrack;
if (audioTrack.samples && audioTrack.isAAC) {
sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {
if (avcTrack.samples) {
sampleAes.decryptAvcSamples(avcTrack.samples, 0, 0, function () {
resolve(demuxResult);
});
} else {
resolve(demuxResult);
}
});
} else if (avcTrack.samples) {
sampleAes.decryptAvcSamples(avcTrack.samples, 0, 0, function () {
resolve(demuxResult);
});
}
});
};
_proto.destroy = function destroy() {
this._initPTS = this._initDTS = null;
this._duration = 0;
};
_proto.parseAVCPES = function parseAVCPES(pes, last) {
var _this = this;
var track = this._avcTrack;
var units = this.parseAVCNALu(pes.data);
var debug = false;
var avcSample = this.avcSample;
var push;
var spsfound = false; // 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) {
pushAccessUnit(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__WEBPACK_IMPORTED_MODULE_2__["default"](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 ';
}
var expGolombDecoder = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__["default"](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 (var i = 0; i < totalCCs; i++) {
// 3 bytes per CC
byteArray.push(expGolombDecoder.readUByte());
byteArray.push(expGolombDecoder.readUByte());
byteArray.push(expGolombDecoder.readUByte());
}
insertSampleInOrder(_this._txtTrack.samples, {
type: 3,
pts: pes.pts,
bytes: byteArray
});
}
}
}
}
} else if (payloadType === 5 && expGolombDecoder.bytesAvailable !== 0) {
endOfCaptions = true;
if (payloadSize > 16) {
var uuidStrArray = [];
for (var _i = 0; _i < 16; _i++) {
uuidStrArray.push(expGolombDecoder.readUByte().toString(16));
if (_i === 3 || _i === 5 || _i === 7 || _i === 9) {
uuidStrArray.push('-');
}
}
var length = payloadSize - 16;
var userDataPayloadBytes = new Uint8Array(length);
for (var _i2 = 0; _i2 < length; _i2++) {
userDataPayloadBytes[_i2] = expGolombDecoder.readUByte();
}
insertSampleInOrder(_this._txtTrack.samples, {
pts: pes.pts,
payloadType: payloadType,
uuid: uuidStrArray.join(''),
userData: Object(_id3__WEBPACK_IMPORTED_MODULE_3__["utf8ArrayToStr"])(userDataPayloadBytes),
userDataBytes: userDataPayloadBytes
});
}
} else if (payloadSize < expGolombDecoder.bytesAvailable) {
for (var _i3 = 0; _i3 < payloadSize; _i3++) {
expGolombDecoder.readUByte();
}
}
}
break; // SPS
}
case 7:
push = true;
spsfound = true;
if (debug && avcSample) {
avcSample.debug += 'SPS ';
}
if (!track.sps) {
var _expGolombDecoder = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__["default"](unit.data);
var config = _expGolombDecoder.readSPS();
track.width = config.width;
track.height = config.height;
track.pixelRatio = config.pixelRatio; // TODO: `track.sps` is defined as a `number[]`, but we're setting it to a `Uint8Array[]`.
track.sps = [unit.data];
track.duration = _this._duration;
var codecarray = unit.data.subarray(1, 4);
var codecstring = 'avc1.';
for (var _i4 = 0; _i4 < 3; _i4++) {
var h = codecarray[_i4].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) {
// TODO: `track.pss` is defined as a `number[]`, but we're setting it to a `Uint8Array[]`.
track.pps = [unit.data];
}
break;
// AUD
case 9:
push = false;
track.audFound = true;
if (avcSample) {
pushAccessUnit(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) {
pushAccessUnit(avcSample, track);
this.avcSample = null;
}
};
_proto.getLastNalUnit = function getLastNalUnit() {
var _avcSample;
var avcSample = this.avcSample;
var lastUnit; // try to fallback to previous sample if current one is empty
if (!avcSample || avcSample.units.length === 0) {
var samples = this._avcTrack.samples;
avcSample = samples[samples.length - 1];
}
if ((_avcSample = avcSample) !== null && _avcSample !== void 0 && _avcSample.units) {
var units = avcSample.units;
lastUnit = units[units.length - 1];
}
return lastUnit;
};
_proto.parseAVCNALu = function parseAVCNALu(array) {
var len = array.byteLength;
var track = this._avcTrack;
var state = track.naluState || 0;
var lastState = state;
var units = [];
var i = 0;
var value;
var overflow;
var unitType;
var lastUnitStart = -1;
var lastUnitType = 0; // 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) {
var 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) {
var _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;
};
_proto.parseAACPES = function parseAACPES(pes) {
var startOffset = 0;
var track = this._audioTrack;
var aacOverFlow = this.aacOverFlow;
var data = pes.data;
if (aacOverFlow) {
this.aacOverFlow = null;
var sampleLength = aacOverFlow.sample.unit.byteLength;
var frameMissingBytes = Math.min(aacOverFlow.missing, sampleLength);
var frameOverflowBytes = sampleLength - frameMissingBytes;
aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes);
track.samples.push(aacOverFlow.sample); // logger.log(`AAC: append overflowing ${frameOverflowBytes} bytes to beginning of new PES`);
startOffset = aacOverFlow.missing;
} // look for ADTS header (0xFFFx)
var offset;
var len;
for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
if (_adts__WEBPACK_IMPORTED_MODULE_0__["isHeader"](data, offset)) {
break;
}
} // if ADTS header does not start straight from the beginning of the PES payload, raise an error
if (offset !== startOffset) {
var reason;
var 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;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn("parsing error:" + reason);
this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorDetails"].FRAG_PARSING_ERROR,
fatal: fatal,
reason: reason
});
if (fatal) {
return;
}
}
_adts__WEBPACK_IMPORTED_MODULE_0__["initTrackConfig"](track, this.observer, data, offset, this.audioCodec);
var pts;
if (pes.pts !== undefined) {
pts = pes.pts;
} else if (aacOverFlow) {
// if last AAC frame is overflowing, we should ensure timestamps are contiguous:
// first sample PTS should be equal to last sample PTS + frameDuration
var frameDuration = _adts__WEBPACK_IMPORTED_MODULE_0__["getFrameDuration"](track.samplerate);
pts = aacOverFlow.sample.pts + frameDuration;
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('[tsdemuxer]: AAC PES unknown PTS');
return;
} // scan for aac samples
var frameIndex = 0;
while (offset < len) {
if (_adts__WEBPACK_IMPORTED_MODULE_0__["isHeader"](data, offset)) {
if (offset + 5 < len) {
var frame = _adts__WEBPACK_IMPORTED_MODULE_0__["appendFrame"](track, data, offset, pts, frameIndex);
if (frame) {
if (frame.missing) {
this.aacOverFlow = frame;
} else {
offset += frame.length;
frameIndex++;
continue;
}
}
} // We are at an ADTS header, but do not have enough data for a frame
// Remaining data will be added to aacOverFlow
break;
} else {
// nothing found, keep looking
offset++;
}
}
};
_proto.parseMPEGPES = function parseMPEGPES(pes) {
var data = pes.data;
var length = data.length;
var frameIndex = 0;
var offset = 0;
var pts = pes.pts;
if (pts === undefined) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('[tsdemuxer]: MPEG PES unknown PTS');
return;
}
while (offset < length) {
if (_mpegaudio__WEBPACK_IMPORTED_MODULE_1__["isHeader"](data, offset)) {
var frame = _mpegaudio__WEBPACK_IMPORTED_MODULE_1__["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++;
}
}
};
_proto.parseID3PES = function parseID3PES(pes) {
if (pes.pts === undefined) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('[tsdemuxer]: ID3 PES unknown PTS');
return;
}
this._id3Track.samples.push(pes);
};
return TSDemuxer;
}();
TSDemuxer.minProbeByteLength = 188;
function createAVCSample(key, pts, dts, debug) {
return {
key: key,
frame: false,
pts: pts,
dts: dts,
units: [],
debug: debug,
length: 0
};
}
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);
}
function parsePMT(data, offset, mpegSupported, isSampleAes) {
var result = {
audio: -1,
avc: -1,
id3: -1,
isAAC: true
};
var sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
var tableEnd = offset + 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
// long the program info descriptors are
var 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) {
var pid = (data[offset + 1] & 0x1f) << 8 | data[offset + 2];
switch (data[offset]) {
case 0xcf:
// SAMPLE-AES AAC
if (!isSampleAes) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream');
break;
}
/* falls through */
case 0x0f:
// ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
// 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) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('H.264 with AES-128-CBC slice encryption found in unencrypted stream');
break;
}
/* falls through */
case 0x1b:
// ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
// 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) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('MPEG audio found, not supported in this browser');
} else if (result.audio === -1) {
result.audio = pid;
result.isAAC = false;
}
break;
case 0x24:
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('Unsupported HEVC stream type found');
break;
default:
// logger.log('unknown 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;
}
function parsePES(stream) {
var i = 0;
var frag;
var pesLen;
var pesHdrLen;
var pesPts;
var pesDts;
var 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];
var 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;
}
var 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;
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;
if (pesPts - pesDts > 60 * 90000) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["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
var payloadStartOffset = pesHdrLen + 9;
if (stream.size <= payloadStartOffset) {
return null;
}
stream.size -= payloadStartOffset; // reassemble PES packet
var 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
};
}
return null;
}
function pushAccessUnit(avcSample, avcTrack) {
if (avcSample.units.length && avcSample.frame) {
// if sample does not have PTS/DTS, patch with last sample PTS/DTS
if (avcSample.pts === undefined) {
var samples = avcTrack.samples;
var nbSamples = samples.length;
if (nbSamples) {
var lastSample = samples[nbSamples - 1];
avcSample.pts = lastSample.pts;
avcSample.dts = lastSample.dts;
} else {
// dropping samples, no timestamp found
avcTrack.dropped++;
return;
}
}
avcTrack.samples.push(avcSample);
}
if (avcSample.debug.length) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);
}
}
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);
}
}
/**
* remove Emulation Prevention bytes from a RBSP
*/
function discardEPB(data) {
var length = data.byteLength;
var EPBPositions = [];
var i = 1; // 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
var newLength = length - EPBPositions.length;
var 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;
}
/* harmony default export */ __webpack_exports__["default"] = (TSDemuxer);
/***/ }),
/***/ "./src/errors.ts":
/*!***********************!*\
!*** ./src/errors.ts ***!
\***********************/
/*! exports provided: ErrorTypes, ErrorDetails */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorTypes", function() { return ErrorTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorDetails", function() { return ErrorDetails; });
var ErrorTypes;
/**
* @enum {ErrorDetails}
* @typedef {string} ErrorDetail
*/
(function (ErrorTypes) {
ErrorTypes["NETWORK_ERROR"] = "networkError";
ErrorTypes["MEDIA_ERROR"] = "mediaError";
ErrorTypes["KEY_SYSTEM_ERROR"] = "keySystemError";
ErrorTypes["MUX_ERROR"] = "muxError";
ErrorTypes["OTHER_ERROR"] = "otherError";
})(ErrorTypes || (ErrorTypes = {}));
var ErrorDetails;
(function (ErrorDetails) {
ErrorDetails["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys";
ErrorDetails["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess";
ErrorDetails["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession";
ErrorDetails["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed";
ErrorDetails["KEY_SYSTEM_NO_INIT_DATA"] = "keySystemNoInitData";
ErrorDetails["MANIFEST_LOAD_ERROR"] = "manifestLoadError";
ErrorDetails["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut";
ErrorDetails["MANIFEST_PARSING_ERROR"] = "manifestParsingError";
ErrorDetails["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError";
ErrorDetails["LEVEL_EMPTY_ERROR"] = "levelEmptyError";
ErrorDetails["LEVEL_LOAD_ERROR"] = "levelLoadError";
ErrorDetails["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut";
ErrorDetails["LEVEL_SWITCH_ERROR"] = "levelSwitchError";
ErrorDetails["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError";
ErrorDetails["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut";
ErrorDetails["SUBTITLE_LOAD_ERROR"] = "subtitleTrackLoadError";
ErrorDetails["SUBTITLE_TRACK_LOAD_TIMEOUT"] = "subtitleTrackLoadTimeOut";
ErrorDetails["FRAG_LOAD_ERROR"] = "fragLoadError";
ErrorDetails["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut";
ErrorDetails["FRAG_DECRYPT_ERROR"] = "fragDecryptError";
ErrorDetails["FRAG_PARSING_ERROR"] = "fragParsingError";
ErrorDetails["REMUX_ALLOC_ERROR"] = "remuxAllocError";
ErrorDetails["KEY_LOAD_ERROR"] = "keyLoadError";
ErrorDetails["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut";
ErrorDetails["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError";
ErrorDetails["BUFFER_INCOMPATIBLE_CODECS_ERROR"] = "bufferIncompatibleCodecsError";
ErrorDetails["BUFFER_APPEND_ERROR"] = "bufferAppendError";
ErrorDetails["BUFFER_APPENDING_ERROR"] = "bufferAppendingError";
ErrorDetails["BUFFER_STALLED_ERROR"] = "bufferStalledError";
ErrorDetails["BUFFER_FULL_ERROR"] = "bufferFullError";
ErrorDetails["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole";
ErrorDetails["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall";
ErrorDetails["INTERNAL_EXCEPTION"] = "internalException";
ErrorDetails["INTERNAL_ABORTED"] = "aborted";
ErrorDetails["UNKNOWN"] = "unknown";
})(ErrorDetails || (ErrorDetails = {}));
/***/ }),
/***/ "./src/events.ts":
/*!***********************!*\
!*** ./src/events.ts ***!
\***********************/
/*! exports provided: Events */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Events", function() { return Events; });
/**
* @readonly
* @enum {string}
*/
var Events;
(function (Events) {
Events["MEDIA_ATTACHING"] = "hlsMediaAttaching";
Events["MEDIA_ATTACHED"] = "hlsMediaAttached";
Events["MEDIA_DETACHING"] = "hlsMediaDetaching";
Events["MEDIA_DETACHED"] = "hlsMediaDetached";
Events["BUFFER_RESET"] = "hlsBufferReset";
Events["BUFFER_CODECS"] = "hlsBufferCodecs";
Events["BUFFER_CREATED"] = "hlsBufferCreated";
Events["BUFFER_APPENDING"] = "hlsBufferAppending";
Events["BUFFER_APPENDED"] = "hlsBufferAppended";
Events["BUFFER_EOS"] = "hlsBufferEos";
Events["BUFFER_FLUSHING"] = "hlsBufferFlushing";
Events["BUFFER_FLUSHED"] = "hlsBufferFlushed";
Events["MANIFEST_LOADING"] = "hlsManifestLoading";
Events["MANIFEST_LOADED"] = "hlsManifestLoaded";
Events["MANIFEST_PARSED"] = "hlsManifestParsed";
Events["LEVEL_SWITCHING"] = "hlsLevelSwitching";
Events["LEVEL_SWITCHED"] = "hlsLevelSwitched";
Events["LEVEL_LOADING"] = "hlsLevelLoading";
Events["LEVEL_LOADED"] = "hlsLevelLoaded";
Events["LEVEL_UPDATED"] = "hlsLevelUpdated";
Events["LEVEL_PTS_UPDATED"] = "hlsLevelPtsUpdated";
Events["LEVELS_UPDATED"] = "hlsLevelsUpdated";
Events["AUDIO_TRACKS_UPDATED"] = "hlsAudioTracksUpdated";
Events["AUDIO_TRACK_SWITCHING"] = "hlsAudioTrackSwitching";
Events["AUDIO_TRACK_SWITCHED"] = "hlsAudioTrackSwitched";
Events["AUDIO_TRACK_LOADING"] = "hlsAudioTrackLoading";
Events["AUDIO_TRACK_LOADED"] = "hlsAudioTrackLoaded";
Events["SUBTITLE_TRACKS_UPDATED"] = "hlsSubtitleTracksUpdated";
Events["SUBTITLE_TRACKS_CLEARED"] = "hlsSubtitleTracksCleared";
Events["SUBTITLE_TRACK_SWITCH"] = "hlsSubtitleTrackSwitch";
Events["SUBTITLE_TRACK_LOADING"] = "hlsSubtitleTrackLoading";
Events["SUBTITLE_TRACK_LOADED"] = "hlsSubtitleTrackLoaded";
Events["SUBTITLE_FRAG_PROCESSED"] = "hlsSubtitleFragProcessed";
Events["CUES_PARSED"] = "hlsCuesParsed";
Events["NON_NATIVE_TEXT_TRACKS_FOUND"] = "hlsNonNativeTextTracksFound";
Events["INIT_PTS_FOUND"] = "hlsInitPtsFound";
Events["FRAG_LOADING"] = "hlsFragLoading";
Events["FRAG_LOAD_EMERGENCY_ABORTED"] = "hlsFragLoadEmergencyAborted";
Events["FRAG_LOADED"] = "hlsFragLoaded";
Events["FRAG_DECRYPTED"] = "hlsFragDecrypted";
Events["FRAG_PARSING_INIT_SEGMENT"] = "hlsFragParsingInitSegment";
Events["FRAG_PARSING_USERDATA"] = "hlsFragParsingUserdata";
Events["FRAG_PARSING_METADATA"] = "hlsFragParsingMetadata";
Events["FRAG_PARSED"] = "hlsFragParsed";
Events["FRAG_BUFFERED"] = "hlsFragBuffered";
Events["FRAG_CHANGED"] = "hlsFragChanged";
Events["FPS_DROP"] = "hlsFpsDrop";
Events["FPS_DROP_LEVEL_CAPPING"] = "hlsFpsDropLevelCapping";
Events["ERROR"] = "hlsError";
Events["DESTROYING"] = "hlsDestroying";
Events["KEY_LOADING"] = "hlsKeyLoading";
Events["KEY_LOADED"] = "hlsKeyLoaded";
Events["LIVE_BACK_BUFFER_REACHED"] = "hlsLiveBackBufferReached";
Events["BACK_BUFFER_REACHED"] = "hlsBackBufferReached";
})(Events || (Events = {}));
/***/ }),
/***/ "./src/hls.ts":
/*!********************!*\
!*** ./src/hls.ts ***!
\********************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Hls; });
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _loader_playlist_loader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./loader/playlist-loader */ "./src/loader/playlist-loader.ts");
/* harmony import */ var _loader_key_loader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./loader/key-loader */ "./src/loader/key-loader.ts");
/* harmony import */ var _controller_id3_track_controller__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./controller/id3-track-controller */ "./src/controller/id3-track-controller.ts");
/* harmony import */ var _controller_latency_controller__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./controller/latency-controller */ "./src/controller/latency-controller.ts");
/* harmony import */ var _controller_level_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./controller/level-controller */ "./src/controller/level-controller.ts");
/* harmony import */ var _controller_fragment_tracker__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./controller/fragment-tracker */ "./src/controller/fragment-tracker.ts");
/* harmony import */ var _controller_stream_controller__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./controller/stream-controller */ "./src/controller/stream-controller.ts");
/* harmony import */ var _is_supported__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./is-supported */ "./src/is-supported.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./config */ "./src/config.ts");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./errors */ "./src/errors.ts");
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); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
/**
* @module Hls
* @class
* @constructor
*/
var Hls = /*#__PURE__*/function () {
Hls.isSupported = function isSupported() {
return Object(_is_supported__WEBPACK_IMPORTED_MODULE_8__["isSupported"])();
};
/**
* Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
*
* @constructs Hls
* @param {HlsConfig} config
*/
function Hls(userConfig) {
if (userConfig === void 0) {
userConfig = {};
}
this.config = void 0;
this.userConfig = void 0;
this.coreComponents = void 0;
this.networkControllers = void 0;
this._emitter = new eventemitter3__WEBPACK_IMPORTED_MODULE_11__["EventEmitter"]();
this._autoLevelCapping = void 0;
this.abrController = void 0;
this.bufferController = void 0;
this.capLevelController = void 0;
this.latencyController = void 0;
this.levelController = void 0;
this.streamController = void 0;
this.audioTrackController = void 0;
this.subtitleTrackController = void 0;
this.emeController = void 0;
this.cmcdController = void 0;
this._media = null;
this.url = null;
var config = this.config = Object(_config__WEBPACK_IMPORTED_MODULE_10__["mergeConfig"])(Hls.DefaultConfig, userConfig);
this.userConfig = userConfig;
Object(_utils_logger__WEBPACK_IMPORTED_MODULE_9__["enableLogs"])(config.debug);
this._autoLevelCapping = -1;
if (config.progressive) {
Object(_config__WEBPACK_IMPORTED_MODULE_10__["enableStreamingMode"])(config);
} // core controllers and network loaders
var ConfigAbrController = config.abrController,
ConfigBufferController = config.bufferController,
ConfigCapLevelController = config.capLevelController,
ConfigFpsController = config.fpsController;
var abrController = this.abrController = new ConfigAbrController(this);
var bufferController = this.bufferController = new ConfigBufferController(this);
var capLevelController = this.capLevelController = new ConfigCapLevelController(this);
var fpsController = new ConfigFpsController(this);
var playListLoader = new _loader_playlist_loader__WEBPACK_IMPORTED_MODULE_1__["default"](this);
var keyLoader = new _loader_key_loader__WEBPACK_IMPORTED_MODULE_2__["default"](this);
var id3TrackController = new _controller_id3_track_controller__WEBPACK_IMPORTED_MODULE_3__["default"](this); // network controllers
var levelController = this.levelController = new _controller_level_controller__WEBPACK_IMPORTED_MODULE_5__["default"](this); // FragmentTracker must be defined before StreamController because the order of event handling is important
var fragmentTracker = new _controller_fragment_tracker__WEBPACK_IMPORTED_MODULE_6__["FragmentTracker"](this);
var streamController = this.streamController = new _controller_stream_controller__WEBPACK_IMPORTED_MODULE_7__["default"](this, fragmentTracker); // Cap level controller uses streamController to flush the buffer
capLevelController.setStreamController(streamController); // fpsController uses streamController to switch when frames are being dropped
fpsController.setStreamController(streamController);
var networkControllers = [levelController, streamController];
this.networkControllers = networkControllers;
var coreComponents = [playListLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker];
this.audioTrackController = this.createController(config.audioTrackController, null, networkControllers);
this.createController(config.audioStreamController, fragmentTracker, networkControllers); // subtitleTrackController must be defined before because the order of event handling is important
this.subtitleTrackController = this.createController(config.subtitleTrackController, null, networkControllers);
this.createController(config.subtitleStreamController, fragmentTracker, networkControllers);
this.createController(config.timelineController, null, coreComponents);
this.emeController = this.createController(config.emeController, null, coreComponents);
this.cmcdController = this.createController(config.cmcdController, null, coreComponents);
this.latencyController = this.createController(_controller_latency_controller__WEBPACK_IMPORTED_MODULE_4__["default"], null, coreComponents);
this.coreComponents = coreComponents;
}
var _proto = Hls.prototype;
_proto.createController = function createController(ControllerClass, fragmentTracker, components) {
if (ControllerClass) {
var controllerInstance = fragmentTracker ? new ControllerClass(this, fragmentTracker) : new ControllerClass(this);
if (components) {
components.push(controllerInstance);
}
return controllerInstance;
}
return null;
} // Delegate the EventEmitter through the public API of Hls.js
;
_proto.on = function on(event, listener, context) {
if (context === void 0) {
context = this;
}
this._emitter.on(event, listener, context);
};
_proto.once = function once(event, listener, context) {
if (context === void 0) {
context = this;
}
this._emitter.once(event, listener, context);
};
_proto.removeAllListeners = function removeAllListeners(event) {
this._emitter.removeAllListeners(event);
};
_proto.off = function off(event, listener, context, once) {
if (context === void 0) {
context = this;
}
this._emitter.off(event, listener, context, once);
};
_proto.listeners = function listeners(event) {
return this._emitter.listeners(event);
};
_proto.emit = function emit(event, name, eventObject) {
return this._emitter.emit(event, name, eventObject);
};
_proto.trigger = function trigger(event, eventObject) {
if (this.config.debug) {
return this.emit(event, event, eventObject);
} else {
try {
return this.emit(event, event, eventObject);
} catch (e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].error('An internal error happened while handling event ' + event + '. Error message: "' + e.message + '". Here is a stacktrace:', e);
this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorTypes"].OTHER_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].INTERNAL_EXCEPTION,
fatal: false,
event: event,
error: e
});
}
}
return false;
};
_proto.listenerCount = function listenerCount(event) {
return this._emitter.listenerCount(event);
}
/**
* Dispose of the instance
*/
;
_proto.destroy = function destroy() {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('destroy');
this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].DESTROYING, undefined);
this.detachMedia();
this.removeAllListeners();
this._autoLevelCapping = -1;
this.url = null;
this.networkControllers.forEach(function (component) {
return component.destroy();
});
this.networkControllers.length = 0;
this.coreComponents.forEach(function (component) {
return component.destroy();
});
this.coreComponents.length = 0;
}
/**
* Attaches Hls.js to a media element
* @param {HTMLMediaElement} media
*/
;
_proto.attachMedia = function attachMedia(media) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('attachMedia');
this._media = media;
this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].MEDIA_ATTACHING, {
media: media
});
}
/**
* Detach Hls.js from the media
*/
;
_proto.detachMedia = function detachMedia() {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('detachMedia');
this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].MEDIA_DETACHING, undefined);
this._media = null;
}
/**
* Set the source URL. Can be relative or absolute.
* @param {string} url
*/
;
_proto.loadSource = function loadSource(url) {
this.stopLoad();
var media = this.media;
var loadedSource = this.url;
var loadingSource = this.url = url_toolkit__WEBPACK_IMPORTED_MODULE_0__["buildAbsoluteURL"](self.location.href, url, {
alwaysNormalize: true
});
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("loadSource:" + loadingSource);
if (media && loadedSource && loadedSource !== loadingSource && this.bufferController.hasSourceTypes()) {
this.detachMedia();
this.attachMedia(media);
} // when attaching to a source URL, trigger a playlist load
this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].MANIFEST_LOADING, {
url: url
});
}
/**
* Start loading data from the stream source.
* Depending on default config, client starts loading automatically when a source is set.
*
* @param {number} startPosition Set the start position to stream from
* @default -1 None (from earliest point)
*/
;
_proto.startLoad = function startLoad(startPosition) {
if (startPosition === void 0) {
startPosition = -1;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("startLoad(" + startPosition + ")");
this.networkControllers.forEach(function (controller) {
controller.startLoad(startPosition);
});
}
/**
* Stop loading of any stream data.
*/
;
_proto.stopLoad = function stopLoad() {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('stopLoad');
this.networkControllers.forEach(function (controller) {
controller.stopLoad();
});
}
/**
* Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
*/
;
_proto.swapAudioCodec = function swapAudioCodec() {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('swapAudioCodec');
this.streamController.swapAudioCodec();
}
/**
* When the media-element fails, this allows to detach and then re-attach it
* as one call (convenience method).
*
* Automatic recovery of media-errors by this process is configurable.
*/
;
_proto.recoverMediaError = function recoverMediaError() {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('recoverMediaError');
var media = this._media;
this.detachMedia();
if (media) {
this.attachMedia(media);
}
};
_proto.removeLevel = function removeLevel(levelIndex, urlId) {
if (urlId === void 0) {
urlId = 0;
}
this.levelController.removeLevel(levelIndex, urlId);
}
/**
* @type {Level[]}
*/
;
_createClass(Hls, [{
key: "levels",
get: function get() {
var levels = this.levelController.levels;
return levels ? levels : [];
}
/**
* Index of quality level currently played
* @type {number}
*/
}, {
key: "currentLevel",
get: function get() {
return this.streamController.currentLevel;
}
/**
* Set quality level index immediately .
* This will flush the current buffer to replace the quality asap.
* That means playback will interrupt at least shortly to re-buffer and re-sync eventually.
* @type {number} -1 for automatic level selection
*/
,
set: function set(newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set currentLevel:" + newLevel);
this.loadLevel = newLevel;
this.abrController.clearTimer();
this.streamController.immediateLevelSwitch();
}
/**
* Index of next quality level loaded as scheduled by stream controller.
* @type {number}
*/
}, {
key: "nextLevel",
get: function get() {
return this.streamController.nextLevel;
}
/**
* Set quality level index for next loaded data.
* This will switch the video quality asap, without interrupting playback.
* May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
* @type {number} -1 for automatic level selection
*/
,
set: function set(newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set nextLevel:" + newLevel);
this.levelController.manualLevel = newLevel;
this.streamController.nextLevelSwitch();
}
/**
* Return the quality level of the currently or last (of none is loaded currently) segment
* @type {number}
*/
}, {
key: "loadLevel",
get: function get() {
return this.levelController.level;
}
/**
* Set quality level index for next loaded data in a conservative way.
* This will switch the quality without flushing, but interrupt current loading.
* Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
* @type {number} newLevel -1 for automatic level selection
*/
,
set: function set(newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set loadLevel:" + newLevel);
this.levelController.manualLevel = newLevel;
}
/**
* get next quality level loaded
* @type {number}
*/
}, {
key: "nextLoadLevel",
get: function get() {
return this.levelController.nextLoadLevel;
}
/**
* Set quality level of next loaded segment in a fully "non-destructive" way.
* Same as `loadLevel` but will wait for next switch (until current loading is done).
* @type {number} level
*/
,
set: function set(level) {
this.levelController.nextLoadLevel = level;
}
/**
* Return "first level": like a default level, if not set,
* falls back to index of first level referenced in manifest
* @type {number}
*/
}, {
key: "firstLevel",
get: function get() {
return Math.max(this.levelController.firstLevel, this.minAutoLevel);
}
/**
* Sets "first-level", see getter.
* @type {number}
*/
,
set: function set(newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["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)
* @type {number}
*/
}, {
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)
* @type {number} newLevel
*/
,
set: function set(newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set startLevel:" + newLevel); // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
if (newLevel !== -1) {
newLevel = Math.max(newLevel, this.minAutoLevel);
}
this.levelController.startLevel = newLevel;
}
/**
* Get the current setting for capLevelToPlayerSize
*
* @type {boolean}
*/
}, {
key: "capLevelToPlayerSize",
get: function get() {
return this.config.capLevelToPlayerSize;
}
/**
* set dynamically set capLevelToPlayerSize against (`CapLevelController`)
*
* @type {boolean}
*/
,
set: function set(shouldStartCapping) {
var newCapLevelToPlayerSize = !!shouldStartCapping;
if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
if (newCapLevelToPlayerSize) {
this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.
} else {
this.capLevelController.stopCapping();
this.autoLevelCapping = -1;
this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.
}
this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
}
}
/**
* Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
* @type {number}
*/
}, {
key: "autoLevelCapping",
get: function get() {
return this._autoLevelCapping;
}
/**
* get bandwidth estimate
* @type {number}
*/
,
set:
/**
* Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
* @type {number}
*/
function set(newLevel) {
if (this._autoLevelCapping !== newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set autoLevelCapping:" + newLevel);
this._autoLevelCapping = newLevel;
}
}
/**
* True when automatic level selection enabled
* @type {boolean}
*/
}, {
key: "bandwidthEstimate",
get: function get() {
var bwEstimator = this.abrController.bwEstimator;
if (!bwEstimator) {
return NaN;
}
return bwEstimator.getEstimate();
}
}, {
key: "autoLevelEnabled",
get: function get() {
return this.levelController.manualLevel === -1;
}
/**
* Level set manually (if any)
* @type {number}
*/
}, {
key: "manualLevel",
get: function get() {
return this.levelController.manualLevel;
}
/**
* min level selectable in auto mode according to config.minAutoBitrate
* @type {number}
*/
}, {
key: "minAutoLevel",
get: function get() {
var levels = this.levels,
minAutoBitrate = this.config.minAutoBitrate;
if (!levels) return 0;
var len = levels.length;
for (var i = 0; i < len; i++) {
if (levels[i].maxBitrate > minAutoBitrate) {
return i;
}
}
return 0;
}
/**
* max level selectable in auto mode according to autoLevelCapping
* @type {number}
*/
}, {
key: "maxAutoLevel",
get: function get() {
var levels = this.levels,
autoLevelCapping = this.autoLevelCapping;
var maxAutoLevel;
if (autoLevelCapping === -1 && levels && levels.length) {
maxAutoLevel = levels.length - 1;
} else {
maxAutoLevel = autoLevelCapping;
}
return maxAutoLevel;
}
/**
* next automatically selected quality level
* @type {number}
*/
}, {
key: "nextAutoLevel",
get: function get() {
// ensure next auto level is between min and max auto level
return Math.min(Math.max(this.abrController.nextAutoLevel, this.minAutoLevel), this.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.
* @type {number}
*/
,
set: function set(nextLevel) {
this.abrController.nextAutoLevel = Math.max(this.minAutoLevel, nextLevel);
}
/**
* @type {AudioTrack[]}
*/
}, {
key: "audioTracks",
get: function get() {
var audioTrackController = this.audioTrackController;
return audioTrackController ? audioTrackController.audioTracks : [];
}
/**
* index of the selected audio track (index in audio track lists)
* @type {number}
*/
}, {
key: "audioTrack",
get: function get() {
var audioTrackController = this.audioTrackController;
return audioTrackController ? audioTrackController.audioTrack : -1;
}
/**
* selects an audio track, based on its index in audio track lists
* @type {number}
*/
,
set: function set(audioTrackId) {
var audioTrackController = this.audioTrackController;
if (audioTrackController) {
audioTrackController.audioTrack = audioTrackId;
}
}
/**
* get alternate subtitle tracks list from playlist
* @type {MediaPlaylist[]}
*/
}, {
key: "subtitleTracks",
get: function get() {
var subtitleTrackController = this.subtitleTrackController;
return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
}
/**
* index of the selected subtitle track (index in subtitle track lists)
* @type {number}
*/
}, {
key: "subtitleTrack",
get: function get() {
var subtitleTrackController = this.subtitleTrackController;
return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
},
set:
/**
* select an subtitle track, based on its index in subtitle track lists
* @type {number}
*/
function set(subtitleTrackId) {
var subtitleTrackController = this.subtitleTrackController;
if (subtitleTrackController) {
subtitleTrackController.subtitleTrack = subtitleTrackId;
}
}
/**
* @type {boolean}
*/
}, {
key: "media",
get: function get() {
return this._media;
}
}, {
key: "subtitleDisplay",
get: function get() {
var subtitleTrackController = this.subtitleTrackController;
return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
}
/**
* Enable/disable subtitle display rendering
* @type {boolean}
*/
,
set: function set(value) {
var subtitleTrackController = this.subtitleTrackController;
if (subtitleTrackController) {
subtitleTrackController.subtitleDisplay = value;
}
}
/**
* get mode for Low-Latency HLS loading
* @type {boolean}
*/
}, {
key: "lowLatencyMode",
get: function get() {
return this.config.lowLatencyMode;
}
/**
* Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.
* @type {boolean}
*/
,
set: function set(mode) {
this.config.lowLatencyMode = mode;
}
/**
* position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)
* @type {number}
*/
}, {
key: "liveSyncPosition",
get: function get() {
return this.latencyController.liveSyncPosition;
}
/**
* estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)
* returns 0 before first playlist is loaded
* @type {number}
*/
}, {
key: "latency",
get: function get() {
return this.latencyController.latency;
}
/**
* maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```
* configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```
* returns 0 before first playlist is loaded
* @type {number}
*/
}, {
key: "maxLatency",
get: function get() {
return this.latencyController.maxLatency;
}
/**
* target distance from the edge as calculated by the latency controller
* @type {number}
*/
}, {
key: "targetLatency",
get: function get() {
return this.latencyController.targetLatency;
}
/**
* the rate at which the edge of the current live playlist is advancing or 1 if there is none
* @type {number}
*/
}, {
key: "drift",
get: function get() {
return this.latencyController.drift;
}
/**
* set to true when startLoad is called before MANIFEST_PARSED event
* @type {boolean}
*/
}, {
key: "forceStartLoad",
get: function get() {
return this.streamController.forceStartLoad;
}
}], [{
key: "version",
get: function get() {
return "1.1.2-0.canary.8062";
}
}, {
key: "Events",
get: function get() {
return _events__WEBPACK_IMPORTED_MODULE_12__["Events"];
}
}, {
key: "ErrorTypes",
get: function get() {
return _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorTypes"];
}
}, {
key: "ErrorDetails",
get: function get() {
return _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"];
}
}, {
key: "DefaultConfig",
get: function get() {
if (!Hls.defaultConfig) {
return _config__WEBPACK_IMPORTED_MODULE_10__["hlsDefaultConfig"];
}
return Hls.defaultConfig;
}
/**
* @type {HlsConfig}
*/
,
set: function set(defaultConfig) {
Hls.defaultConfig = defaultConfig;
}
}]);
return Hls;
}();
Hls.defaultConfig = void 0;
/***/ }),
/***/ "./src/is-supported.ts":
/*!*****************************!*\
!*** ./src/is-supported.ts ***!
\*****************************/
/*! exports provided: isSupported, changeTypeSupported */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isSupported", function() { return isSupported; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "changeTypeSupported", function() { return changeTypeSupported; });
/* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/mediasource-helper */ "./src/utils/mediasource-helper.ts");
function getSourceBuffer() {
return self.SourceBuffer || self.WebKitSourceBuffer;
}
function isSupported() {
var mediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_0__["getMediaSource"])();
if (!mediaSource) {
return false;
}
var sourceBuffer = getSourceBuffer();
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;
}
function changeTypeSupported() {
var _sourceBuffer$prototy;
var sourceBuffer = getSourceBuffer();
return typeof (sourceBuffer === null || sourceBuffer === void 0 ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) === null || _sourceBuffer$prototy === void 0 ? void 0 : _sourceBuffer$prototy.changeType) === 'function';
}
/***/ }),
/***/ "./src/loader/fragment-loader.ts":
/*!***************************************!*\
!*** ./src/loader/fragment-loader.ts ***!
\***************************************/
/*! exports provided: default, LoadError */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return FragmentLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoadError", function() { return LoadError; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
var MIN_CHUNK_SIZE = Math.pow(2, 17); // 128kb
var FragmentLoader = /*#__PURE__*/function () {
function FragmentLoader(config) {
this.config = void 0;
this.loader = null;
this.partLoadTimeout = -1;
this.config = config;
}
var _proto = FragmentLoader.prototype;
_proto.destroy = function destroy() {
if (this.loader) {
this.loader.destroy();
this.loader = null;
}
};
_proto.abort = function abort() {
if (this.loader) {
// Abort the loader for current fragment. Only one may load at any given time
this.loader.abort();
}
};
_proto.load = function load(frag, _onProgress) {
var _this = this;
var url = frag.url;
if (!url) {
return Promise.reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_ERROR,
fatal: false,
frag: frag,
networkDetails: null
}, "Fragment does not have a " + (url ? 'part list' : 'url')));
}
this.abort();
var config = this.config;
var FragmentILoader = config.fLoader;
var DefaultILoader = config.loader;
return new Promise(function (resolve, reject) {
if (_this.loader) {
_this.loader.destroy();
}
var loader = _this.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
var loaderContext = createLoaderContext(frag);
var loaderConfig = {
timeout: config.fragLoadingTimeOut,
maxRetry: 0,
retryDelay: 0,
maxRetryDelay: config.fragLoadingMaxRetryTimeout,
highWaterMark: MIN_CHUNK_SIZE
}; // Assign frag stats to the loader's stats reference
frag.stats = loader.stats;
loader.load(loaderContext, loaderConfig, {
onSuccess: function onSuccess(response, stats, context, networkDetails) {
_this.resetLoader(frag, loader);
resolve({
frag: frag,
part: null,
payload: response.data,
networkDetails: networkDetails
});
},
onError: function onError(response, context, networkDetails) {
_this.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_ERROR,
fatal: false,
frag: frag,
response: response,
networkDetails: networkDetails
}));
},
onAbort: function onAbort(stats, context, networkDetails) {
_this.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].INTERNAL_ABORTED,
fatal: false,
frag: frag,
networkDetails: networkDetails
}));
},
onTimeout: function onTimeout(response, context, networkDetails) {
_this.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_TIMEOUT,
fatal: false,
frag: frag,
networkDetails: networkDetails
}));
},
onProgress: function onProgress(stats, context, data, networkDetails) {
if (_onProgress) {
_onProgress({
frag: frag,
part: null,
payload: data,
networkDetails: networkDetails
});
}
}
});
});
};
_proto.loadPart = function loadPart(frag, part, onProgress) {
var _this2 = this;
this.abort();
var config = this.config;
var FragmentILoader = config.fLoader;
var DefaultILoader = config.loader;
return new Promise(function (resolve, reject) {
if (_this2.loader) {
_this2.loader.destroy();
}
var loader = _this2.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
var loaderContext = createLoaderContext(frag, part);
var loaderConfig = {
timeout: config.fragLoadingTimeOut,
maxRetry: 0,
retryDelay: 0,
maxRetryDelay: config.fragLoadingMaxRetryTimeout,
highWaterMark: MIN_CHUNK_SIZE
}; // Assign part stats to the loader's stats reference
part.stats = loader.stats;
loader.load(loaderContext, loaderConfig, {
onSuccess: function onSuccess(response, stats, context, networkDetails) {
_this2.resetLoader(frag, loader);
_this2.updateStatsFromPart(frag, part);
var partLoadedData = {
frag: frag,
part: part,
payload: response.data,
networkDetails: networkDetails
};
onProgress(partLoadedData);
resolve(partLoadedData);
},
onError: function onError(response, context, networkDetails) {
_this2.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_ERROR,
fatal: false,
frag: frag,
part: part,
response: response,
networkDetails: networkDetails
}));
},
onAbort: function onAbort(stats, context, networkDetails) {
frag.stats.aborted = part.stats.aborted;
_this2.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].INTERNAL_ABORTED,
fatal: false,
frag: frag,
part: part,
networkDetails: networkDetails
}));
},
onTimeout: function onTimeout(response, context, networkDetails) {
_this2.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_TIMEOUT,
fatal: false,
frag: frag,
part: part,
networkDetails: networkDetails
}));
}
});
});
};
_proto.updateStatsFromPart = function updateStatsFromPart(frag, part) {
var fragStats = frag.stats;
var partStats = part.stats;
var partTotal = partStats.total;
fragStats.loaded += partStats.loaded;
if (partTotal) {
var estTotalParts = Math.round(frag.duration / part.duration);
var estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);
var estRemainingParts = estTotalParts - estLoadedParts;
var estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);
fragStats.total = fragStats.loaded + estRemainingBytes;
} else {
fragStats.total = Math.max(fragStats.loaded, fragStats.total);
}
var fragLoading = fragStats.loading;
var partLoading = partStats.loading;
if (fragLoading.start) {
// add to fragment loader latency
fragLoading.first += partLoading.first - partLoading.start;
} else {
fragLoading.start = partLoading.start;
fragLoading.first = partLoading.first;
}
fragLoading.end = partLoading.end;
};
_proto.resetLoader = function resetLoader(frag, loader) {
frag.loader = null;
if (this.loader === loader) {
self.clearTimeout(this.partLoadTimeout);
this.loader = null;
}
loader.destroy();
};
return FragmentLoader;
}();
function createLoaderContext(frag, part) {
if (part === void 0) {
part = null;
}
var segment = part || frag;
var loaderContext = {
frag: frag,
part: part,
responseType: 'arraybuffer',
url: segment.url,
headers: {},
rangeStart: 0,
rangeEnd: 0
};
var start = segment.byteRangeStartOffset;
var end = segment.byteRangeEndOffset;
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(start) && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(end)) {
loaderContext.rangeStart = start;
loaderContext.rangeEnd = end;
}
return loaderContext;
}
var LoadError = /*#__PURE__*/function (_Error) {
_inheritsLoose(LoadError, _Error);
function LoadError(data) {
var _this3;
for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
params[_key - 1] = arguments[_key];
}
_this3 = _Error.call.apply(_Error, [this].concat(params)) || this;
_this3.data = void 0;
_this3.data = data;
return _this3;
}
return LoadError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
/***/ }),
/***/ "./src/loader/fragment.ts":
/*!********************************!*\
!*** ./src/loader/fragment.ts ***!
\********************************/
/*! exports provided: ElementaryStreamTypes, BaseSegment, Fragment, Part */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ElementaryStreamTypes", function() { return ElementaryStreamTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BaseSegment", function() { return BaseSegment; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Fragment", function() { return Fragment; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Part", function() { return Part; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _level_key__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./level-key */ "./src/loader/level-key.ts");
/* harmony import */ var _load_stats__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./load-stats */ "./src/loader/load-stats.ts");
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
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); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var ElementaryStreamTypes;
(function (ElementaryStreamTypes) {
ElementaryStreamTypes["AUDIO"] = "audio";
ElementaryStreamTypes["VIDEO"] = "video";
ElementaryStreamTypes["AUDIOVIDEO"] = "audiovideo";
})(ElementaryStreamTypes || (ElementaryStreamTypes = {}));
var BaseSegment = /*#__PURE__*/function () {
// baseurl is the URL to the playlist
// relurl is the portion of the URL that comes from inside the playlist.
// Holds the types of data this fragment supports
function BaseSegment(baseurl) {
var _this$elementaryStrea;
this._byteRange = null;
this._url = null;
this.baseurl = void 0;
this.relurl = void 0;
this.elementaryStreams = (_this$elementaryStrea = {}, _this$elementaryStrea[ElementaryStreamTypes.AUDIO] = null, _this$elementaryStrea[ElementaryStreamTypes.VIDEO] = null, _this$elementaryStrea[ElementaryStreamTypes.AUDIOVIDEO] = null, _this$elementaryStrea);
this.baseurl = baseurl;
} // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
var _proto = BaseSegment.prototype;
_proto.setByteRange = function setByteRange(value, previous) {
var params = value.split('@', 2);
var byteRange = [];
if (params.length === 1) {
byteRange[0] = previous ? previous.byteRangeEndOffset : 0;
} else {
byteRange[0] = parseInt(params[1]);
}
byteRange[1] = parseInt(params[0]) + byteRange[0];
this._byteRange = byteRange;
};
_createClass(BaseSegment, [{
key: "byteRange",
get: function get() {
if (!this._byteRange) {
return [];
}
return this._byteRange;
}
}, {
key: "byteRangeStartOffset",
get: function get() {
return this.byteRange[0];
}
}, {
key: "byteRangeEndOffset",
get: function get() {
return this.byteRange[1];
}
}, {
key: "url",
get: function get() {
if (!this._url && this.baseurl && this.relurl) {
this._url = Object(url_toolkit__WEBPACK_IMPORTED_MODULE_1__["buildAbsoluteURL"])(this.baseurl, this.relurl, {
alwaysNormalize: true
});
}
return this._url || '';
},
set: function set(value) {
this._url = value;
}
}]);
return BaseSegment;
}();
var Fragment = /*#__PURE__*/function (_BaseSegment) {
_inheritsLoose(Fragment, _BaseSegment);
// EXTINF has to be present for a m38 to be considered valid
// sn notates the sequence number for a segment, and if set to a string can be 'initSegment'
// levelkey is the EXT-X-KEY that applies to this segment for decryption
// core difference from the private field _decryptdata is the lack of the initialized IV
// _decryptdata will set the IV for this segment based on the segment number in the fragment
// A string representing the fragment type
// A reference to the loader. Set while the fragment is loading, and removed afterwards. Used to abort fragment loading
// The level/track index to which the fragment belongs
// The continuity counter of the fragment
// The starting Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
// The ending Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
// The latest Presentation Time Stamp (PTS) appended to the buffer.
// The starting Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
// The ending Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
// The start time of the fragment, as listed in the manifest. Updated after transmux complete.
// Set by `updateFragPTSDTS` in level-helper
// The maximum starting Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
// The minimum ending Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
// Load/parse timing information
// A flag indicating whether the segment was downloaded in order to test bitrate, and was not buffered
// #EXTINF segment title
// The Media Initialization Section for this segment
function Fragment(type, baseurl) {
var _this;
_this = _BaseSegment.call(this, baseurl) || this;
_this._decryptdata = null;
_this.rawProgramDateTime = null;
_this.programDateTime = null;
_this.tagList = [];
_this.duration = 0;
_this.sn = 0;
_this.levelkey = void 0;
_this.type = void 0;
_this.loader = null;
_this.level = -1;
_this.cc = 0;
_this.startPTS = void 0;
_this.endPTS = void 0;
_this.appendedPTS = void 0;
_this.startDTS = void 0;
_this.endDTS = void 0;
_this.start = 0;
_this.deltaPTS = void 0;
_this.maxStartPTS = void 0;
_this.minEndPTS = void 0;
_this.stats = new _load_stats__WEBPACK_IMPORTED_MODULE_4__["LoadStats"]();
_this.urlId = 0;
_this.data = void 0;
_this.bitrateTest = false;
_this.title = null;
_this.initSegment = null;
_this.type = type;
return _this;
}
var _proto2 = Fragment.prototype;
/**
* Utility method for parseLevelPlaylist to create an initialization vector for a given segment
* @param {number} segmentNumber - segment number to generate IV with
* @returns {Uint8Array}
*/
_proto2.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 {LevelKey} - an object to be applied as a fragment's decryptdata
*/
;
_proto2.setDecryptDataFromLevelKey = function setDecryptDataFromLevelKey(levelkey, segmentNumber) {
var decryptdata = levelkey;
if ((levelkey === null || levelkey === void 0 ? void 0 : levelkey.method) === 'AES-128' && levelkey.uri && !levelkey.iv) {
decryptdata = _level_key__WEBPACK_IMPORTED_MODULE_3__["LevelKey"].fromURI(levelkey.uri);
decryptdata.method = levelkey.method;
decryptdata.iv = this.createInitializationVector(segmentNumber);
decryptdata.keyFormat = 'identity';
}
return decryptdata;
};
_proto2.setElementaryStreamInfo = function setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial) {
if (partial === void 0) {
partial = false;
}
var elementaryStreams = this.elementaryStreams;
var info = elementaryStreams[type];
if (!info) {
elementaryStreams[type] = {
startPTS: startPTS,
endPTS: endPTS,
startDTS: startDTS,
endDTS: endDTS,
partial: partial
};
return;
}
info.startPTS = Math.min(info.startPTS, startPTS);
info.endPTS = Math.max(info.endPTS, endPTS);
info.startDTS = Math.min(info.startDTS, startDTS);
info.endDTS = Math.max(info.endDTS, endDTS);
};
_proto2.clearElementaryStreamInfo = function clearElementaryStreamInfo() {
var elementaryStreams = this.elementaryStreams;
elementaryStreams[ElementaryStreamTypes.AUDIO] = null;
elementaryStreams[ElementaryStreamTypes.VIDEO] = null;
elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;
};
_createClass(Fragment, [{
key: "decryptdata",
get: function get() {
if (!this.levelkey && !this._decryptdata) {
return null;
}
if (!this._decryptdata && this.levelkey) {
var sn = this.sn;
if (typeof sn !== 'number') {
// We are fetching decryption data for a initialization segment
// If the segment was encrypted with AES-128
// It must have an IV defined. We cannot substitute the Segment Number in.
if (this.levelkey && this.levelkey.method === 'AES-128' && !this.levelkey.iv) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("missing IV for initialization segment with method=\"" + this.levelkey.method + "\" - compliance issue");
}
/*
Be converted to a Number.
'initSegment' will become NaN.
NaN, which when converted through ToInt32() -> +0.
---
Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.
*/
sn = 0;
}
this._decryptdata = this.setDecryptDataFromLevelKey(this.levelkey, sn);
}
return this._decryptdata;
}
}, {
key: "end",
get: function get() {
return this.start + this.duration;
}
}, {
key: "endProgramDateTime",
get: function get() {
if (this.programDateTime === null) {
return null;
}
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.programDateTime)) {
return null;
}
var duration = !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.duration) ? 0 : this.duration;
return this.programDateTime + duration * 1000;
}
}, {
key: "encrypted",
get: function get() {
var _this$decryptdata;
// At the m3u8-parser level we need to add support for manifest signalled keyformats
// when we want the fragment to start reporting that it is encrypted.
// Currently, keyFormat will only be set for identity keys
if ((_this$decryptdata = this.decryptdata) !== null && _this$decryptdata !== void 0 && _this$decryptdata.keyFormat && this.decryptdata.uri) {
return true;
}
return false;
}
}]);
return Fragment;
}(BaseSegment);
var Part = /*#__PURE__*/function (_BaseSegment2) {
_inheritsLoose(Part, _BaseSegment2);
function Part(partAttrs, frag, baseurl, index, previous) {
var _this2;
_this2 = _BaseSegment2.call(this, baseurl) || this;
_this2.fragOffset = 0;
_this2.duration = 0;
_this2.gap = false;
_this2.independent = false;
_this2.relurl = void 0;
_this2.fragment = void 0;
_this2.index = void 0;
_this2.stats = new _load_stats__WEBPACK_IMPORTED_MODULE_4__["LoadStats"]();
_this2.duration = partAttrs.decimalFloatingPoint('DURATION');
_this2.gap = partAttrs.bool('GAP');
_this2.independent = partAttrs.bool('INDEPENDENT');
_this2.relurl = partAttrs.enumeratedString('URI');
_this2.fragment = frag;
_this2.index = index;
var byteRange = partAttrs.enumeratedString('BYTERANGE');
if (byteRange) {
_this2.setByteRange(byteRange, previous);
}
if (previous) {
_this2.fragOffset = previous.fragOffset + previous.duration;
}
return _this2;
}
_createClass(Part, [{
key: "start",
get: function get() {
return this.fragment.start + this.fragOffset;
}
}, {
key: "end",
get: function get() {
return this.start + this.duration;
}
}, {
key: "loaded",
get: function get() {
var elementaryStreams = this.elementaryStreams;
return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo);
}
}]);
return Part;
}(BaseSegment);
/***/ }),
/***/ "./src/loader/key-loader.ts":
/*!**********************************!*\
!*** ./src/loader/key-loader.ts ***!
\**********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return KeyLoader; });
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/*
* Decrypt key Loader
*/
var KeyLoader = /*#__PURE__*/function () {
function KeyLoader(hls) {
this.hls = void 0;
this.loaders = {};
this.decryptkey = null;
this.decrypturl = null;
this.hls = hls;
this._registerListeners();
}
var _proto = KeyLoader.prototype;
_proto._registerListeners = function _registerListeners() {
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADING, this.onKeyLoading, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADING, this.onKeyLoading);
};
_proto.destroy = function destroy() {
this._unregisterListeners();
for (var loaderName in this.loaders) {
var loader = this.loaders[loaderName];
if (loader) {
loader.destroy();
}
}
this.loaders = {};
};
_proto.onKeyLoading = function onKeyLoading(event, data) {
var frag = data.frag;
var type = frag.type;
var loader = this.loaders[type];
if (!frag.decryptdata) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('Missing decryption data on fragment in onKeyLoading');
return;
} // Load the key if the uri is different from previous one, or if the decrypt key has not yet been retrieved
var uri = frag.decryptdata.uri;
if (uri !== this.decrypturl || this.decryptkey === null) {
var config = this.hls.config;
if (loader) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("abort previous key loader for type:" + type);
loader.abort();
}
if (!uri) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('key uri is falsy');
return;
}
var Loader = config.loader;
var fragLoader = frag.loader = this.loaders[type] = new Loader(config);
this.decrypturl = uri;
this.decryptkey = null;
var loaderContext = {
url: uri,
frag: frag,
responseType: 'arraybuffer'
}; // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
// key-loader will trigger an error and rely on stream-controller to handle retry logic.
// this will also align retry logic with fragment-loader
var loaderConfig = {
timeout: config.fragLoadingTimeOut,
maxRetry: 0,
retryDelay: config.fragLoadingRetryDelay,
maxRetryDelay: config.fragLoadingMaxRetryTimeout,
highWaterMark: 0
};
var loaderCallbacks = {
onSuccess: this.loadsuccess.bind(this),
onError: this.loaderror.bind(this),
onTimeout: this.loadtimeout.bind(this)
};
fragLoader.load(loaderContext, loaderConfig, loaderCallbacks);
} else if (this.decryptkey) {
// Return the key if it's already been loaded
frag.decryptdata.key = this.decryptkey;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADED, {
frag: frag
});
}
};
_proto.loadsuccess = function loadsuccess(response, stats, context) {
var frag = context.frag;
if (!frag.decryptdata) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('after key load, decryptdata unset');
return;
}
this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data); // detach fragment loader on load success
frag.loader = null;
delete this.loaders[frag.type];
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADED, {
frag: frag
});
};
_proto.loaderror = function loaderror(response, context) {
var frag = context.frag;
var loader = frag.loader;
if (loader) {
loader.abort();
}
delete this.loaders[frag.type];
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_LOAD_ERROR,
fatal: false,
frag: frag,
response: response
});
};
_proto.loadtimeout = function loadtimeout(stats, context) {
var frag = context.frag;
var loader = frag.loader;
if (loader) {
loader.abort();
}
delete this.loaders[frag.type];
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_LOAD_TIMEOUT,
fatal: false,
frag: frag
});
};
return KeyLoader;
}();
/***/ }),
/***/ "./src/loader/level-details.ts":
/*!*************************************!*\
!*** ./src/loader/level-details.ts ***!
\*************************************/
/*! exports provided: LevelDetails */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LevelDetails", function() { return LevelDetails; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
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); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var DEFAULT_TARGET_DURATION = 10;
var LevelDetails = /*#__PURE__*/function () {
// Manifest reload synchronization
function LevelDetails(baseUrl) {
this.PTSKnown = false;
this.alignedSliding = false;
this.averagetargetduration = void 0;
this.endCC = 0;
this.endSN = 0;
this.fragments = void 0;
this.fragmentHint = void 0;
this.partList = null;
this.live = true;
this.ageHeader = 0;
this.advancedDateTime = void 0;
this.updated = true;
this.advanced = true;
this.availabilityDelay = void 0;
this.misses = 0;
this.needSidxRanges = false;
this.startCC = 0;
this.startSN = 0;
this.startTimeOffset = null;
this.targetduration = 0;
this.totalduration = 0;
this.type = null;
this.url = void 0;
this.m3u8 = '';
this.version = null;
this.canBlockReload = false;
this.canSkipUntil = 0;
this.canSkipDateRanges = false;
this.skippedSegments = 0;
this.recentlyRemovedDateranges = void 0;
this.partHoldBack = 0;
this.holdBack = 0;
this.partTarget = 0;
this.preloadHint = void 0;
this.renditionReports = void 0;
this.tuneInGoal = 0;
this.deltaUpdateFailed = void 0;
this.driftStartTime = 0;
this.driftEndTime = 0;
this.driftStart = 0;
this.driftEnd = 0;
this.fragments = [];
this.url = baseUrl;
}
var _proto = LevelDetails.prototype;
_proto.reloaded = function reloaded(previous) {
if (!previous) {
this.advanced = true;
this.updated = true;
return;
}
var partSnDiff = this.lastPartSn - previous.lastPartSn;
var partIndexDiff = this.lastPartIndex - previous.lastPartIndex;
this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff;
this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0;
if (this.updated || this.advanced) {
this.misses = Math.floor(previous.misses * 0.6);
} else {
this.misses = previous.misses + 1;
}
this.availabilityDelay = previous.availabilityDelay;
};
_createClass(LevelDetails, [{
key: "hasProgramDateTime",
get: function get() {
if (this.fragments.length) {
return Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.fragments[this.fragments.length - 1].programDateTime);
}
return false;
}
}, {
key: "levelTargetDuration",
get: function get() {
return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION;
}
}, {
key: "drift",
get: function get() {
var runTime = this.driftEndTime - this.driftStartTime;
if (runTime > 0) {
var runDuration = this.driftEnd - this.driftStart;
return runDuration * 1000 / runTime;
}
return 1;
}
}, {
key: "edge",
get: function get() {
return this.partEnd || this.fragmentEnd;
}
}, {
key: "partEnd",
get: function get() {
var _this$partList;
if ((_this$partList = this.partList) !== null && _this$partList !== void 0 && _this$partList.length) {
return this.partList[this.partList.length - 1].end;
}
return this.fragmentEnd;
}
}, {
key: "fragmentEnd",
get: function get() {
var _this$fragments;
if ((_this$fragments = this.fragments) !== null && _this$fragments !== void 0 && _this$fragments.length) {
return this.fragments[this.fragments.length - 1].end;
}
return 0;
}
}, {
key: "age",
get: function get() {
if (this.advancedDateTime) {
return Math.max(Date.now() - this.advancedDateTime, 0) / 1000;
}
return 0;
}
}, {
key: "lastPartIndex",
get: function get() {
var _this$partList2;
if ((_this$partList2 = this.partList) !== null && _this$partList2 !== void 0 && _this$partList2.length) {
return this.partList[this.partList.length - 1].index;
}
return -1;
}
}, {
key: "lastPartSn",
get: function get() {
var _this$partList3;
if ((_this$partList3 = this.partList) !== null && _this$partList3 !== void 0 && _this$partList3.length) {
return this.partList[this.partList.length - 1].fragment.sn;
}
return this.endSN;
}
}]);
return LevelDetails;
}();
/***/ }),
/***/ "./src/loader/level-key.ts":
/*!*********************************!*\
!*** ./src/loader/level-key.ts ***!
\*********************************/
/*! exports provided: LevelKey */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LevelKey", function() { return LevelKey; });
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_0__);
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); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var LevelKey = /*#__PURE__*/function () {
LevelKey.fromURL = function fromURL(baseUrl, relativeUrl) {
return new LevelKey(baseUrl, relativeUrl);
};
LevelKey.fromURI = function fromURI(uri) {
return new LevelKey(uri);
};
function LevelKey(absoluteOrBaseURI, relativeURL) {
this._uri = null;
this.method = null;
this.keyFormat = null;
this.keyFormatVersions = null;
this.keyID = null;
this.key = null;
this.iv = null;
if (relativeURL) {
this._uri = Object(url_toolkit__WEBPACK_IMPORTED_MODULE_0__["buildAbsoluteURL"])(absoluteOrBaseURI, relativeURL, {
alwaysNormalize: true
});
} else {
this._uri = absoluteOrBaseURI;
}
}
_createClass(LevelKey, [{
key: "uri",
get: function get() {
return this._uri;
}
}]);
return LevelKey;
}();
/***/ }),
/***/ "./src/loader/load-stats.ts":
/*!**********************************!*\
!*** ./src/loader/load-stats.ts ***!
\**********************************/
/*! exports provided: LoadStats */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoadStats", function() { return LoadStats; });
var LoadStats = function LoadStats() {
this.aborted = false;
this.loaded = 0;
this.retry = 0;
this.total = 0;
this.chunkCount = 0;
this.bwEstimate = 0;
this.loading = {
start: 0,
first: 0,
end: 0
};
this.parsing = {
start: 0,
end: 0
};
this.buffering = {
start: 0,
first: 0,
end: 0
};
};
/***/ }),
/***/ "./src/loader/m3u8-parser.ts":
/*!***********************************!*\
!*** ./src/loader/m3u8-parser.ts ***!
\***********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return M3U8Parser; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _fragment__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./fragment */ "./src/loader/fragment.ts");
/* harmony import */ var _level_details__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./level-details */ "./src/loader/level-details.ts");
/* harmony import */ var _level_key__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./level-key */ "./src/loader/level-key.ts");
/* harmony import */ var _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/attr-list */ "./src/utils/attr-list.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _utils_codecs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/codecs */ "./src/utils/codecs.ts");
// https://regex101.com is your friend
var MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-SESSION-DATA:([^\r\n]*)[\r\n]+/g;
var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
/(?!#) *(\S[\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 = new RegExp([/#(EXTM3U)/.source, /#EXT-X-(PLAYLIST-TYPE):(.+)/.source, /#EXT-X-(MEDIA-SEQUENCE): *(\d+)/.source, /#EXT-X-(SKIP):(.+)/.source, /#EXT-X-(TARGETDURATION): *(\d+)/.source, /#EXT-X-(KEY):(.+)/.source, /#EXT-X-(START):(.+)/.source, /#EXT-X-(ENDLIST)/.source, /#EXT-X-(DISCONTINUITY-SEQ)UENCE: *(\d+)/.source, /#EXT-X-(DIS)CONTINUITY/.source, /#EXT-X-(VERSION):(\d+)/.source, /#EXT-X-(MAP):(.+)/.source, /#EXT-X-(SERVER-CONTROL):(.+)/.source, /#EXT-X-(PART-INF):(.+)/.source, /#EXT-X-(GAP)/.source, /#EXT-X-(BITRATE):\s*(\d+)/.source, /#EXT-X-(PART):(.+)/.source, /#EXT-X-(PRELOAD-HINT):(.+)/.source, /#EXT-X-(RENDITION-REPORT):(.+)/.source, /(#)([^:]*):(.*)/.source, /(#)(.*)(?:.*)\r?\n?/.source].join('|'));
var MP4_REGEX_SUFFIX = /\.(mp4|m4s|m4v|m4a)$/i;
function isMP4Url(url) {
var _URLToolkit$parseURL$, _URLToolkit$parseURL;
return MP4_REGEX_SUFFIX.test((_URLToolkit$parseURL$ = (_URLToolkit$parseURL = url_toolkit__WEBPACK_IMPORTED_MODULE_1__["parseURL"](url)) === null || _URLToolkit$parseURL === void 0 ? void 0 : _URLToolkit$parseURL.path) != null ? _URLToolkit$parseURL$ : '');
}
var M3U8Parser = /*#__PURE__*/function () {
function M3U8Parser() {}
M3U8Parser.findGroup = function findGroup(groups, mediaGroupId) {
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
if (group.id === mediaGroupId) {
return group;
}
}
};
M3U8Parser.convertAVC1ToAVCOTI = function convertAVC1ToAVCOTI(codec) {
// Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported
var avcdata = codec.split('.');
if (avcdata.length > 2) {
var result = avcdata.shift() + '.';
result += parseInt(avcdata.shift()).toString(16);
result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);
return result;
}
return codec;
};
M3U8Parser.resolve = function resolve(url, baseUrl) {
return url_toolkit__WEBPACK_IMPORTED_MODULE_1__["buildAbsoluteURL"](baseUrl, url, {
alwaysNormalize: true
});
};
M3U8Parser.parseMasterPlaylist = function parseMasterPlaylist(string, baseurl) {
var levels = [];
var sessionData = {};
var hasSessionData = false;
MASTER_PLAYLIST_REGEX.lastIndex = 0;
var result;
while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
if (result[1]) {
// '#EXT-X-STREAM-INF' is found, parse level tag in group 1
var attrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](result[1]);
var level = {
attrs: attrs,
bitrate: attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH'),
name: attrs.NAME,
url: M3U8Parser.resolve(result[2], baseurl)
};
var resolution = attrs.decimalResolution('RESOLUTION');
if (resolution) {
level.width = resolution.width;
level.height = resolution.height;
}
setCodecs((attrs.CODECS || '').split(/[ ,]+/).filter(function (c) {
return c;
}), level);
if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {
level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);
}
levels.push(level);
} else if (result[3]) {
// '#EXT-X-SESSION-DATA' is found, parse session data in group 3
var sessionAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](result[3]);
if (sessionAttrs['DATA-ID']) {
hasSessionData = true;
sessionData[sessionAttrs['DATA-ID']] = sessionAttrs;
}
}
}
return {
levels: levels,
sessionData: hasSessionData ? sessionData : null
};
};
M3U8Parser.parseMasterPlaylistMedia = function parseMasterPlaylistMedia(string, baseurl, type, groups) {
if (groups === void 0) {
groups = [];
}
var result;
var medias = [];
var id = 0;
MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
var attrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](result[1]);
if (attrs.TYPE === type) {
var media = {
attrs: attrs,
bitrate: 0,
id: id++,
groupId: attrs['GROUP-ID'],
instreamId: attrs['INSTREAM-ID'],
name: attrs.NAME || attrs.LANGUAGE || '',
type: type,
default: attrs.bool('DEFAULT'),
autoselect: attrs.bool('AUTOSELECT'),
forced: attrs.bool('FORCED'),
lang: attrs.LANGUAGE,
url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : ''
};
if (groups.length) {
// If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track
// If we don't find the track signalled, lets use the first audio groups codec we have
// Acting as a best guess
var groupCodec = M3U8Parser.findGroup(groups, media.groupId) || groups[0];
assignCodec(media, groupCodec, 'audioCodec');
assignCodec(media, groupCodec, 'textCodec');
}
medias.push(media);
}
}
return medias;
};
M3U8Parser.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type, levelUrlId) {
var level = new _level_details__WEBPACK_IMPORTED_MODULE_3__["LevelDetails"](baseurl);
var fragments = level.fragments; // The most recent init segment seen (applies to all subsequent segments)
var currentInitSegment = null;
var currentSN = 0;
var currentPart = 0;
var totalduration = 0;
var discontinuityCounter = 0;
var prevFrag = null;
var frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl);
var result;
var i;
var levelkey;
var firstPdtIndex = -1;
var createNextFrag = false;
LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
level.m3u8 = string;
while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
if (createNextFrag) {
createNextFrag = false;
frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl); // setup the next fragment for part loading
frag.start = totalduration;
frag.sn = currentSN;
frag.cc = discontinuityCounter;
frag.level = id;
if (currentInitSegment) {
frag.initSegment = currentInitSegment;
frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
}
}
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 || null;
frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
} else if (result[3]) {
// url
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.duration)) {
frag.start = totalduration;
if (levelkey) {
frag.levelkey = levelkey;
}
frag.sn = currentSN;
frag.level = id;
frag.cc = discontinuityCounter;
frag.urlId = levelUrlId;
fragments.push(frag); // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
frag.relurl = (' ' + result[3]).slice(1);
assignProgramDateTime(frag, prevFrag);
prevFrag = frag;
totalduration += frag.duration;
currentSN++;
currentPart = 0;
createNextFrag = true;
}
} else if (result[4]) {
// X-BYTERANGE
var data = (' ' + result[4]).slice(1);
if (prevFrag) {
frag.setByteRange(data, prevFrag);
} else {
frag.setByteRange(data);
}
} 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 (firstPdtIndex === -1) {
firstPdtIndex = fragments.length;
}
} else {
result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
if (!result) {
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn('No matches on slow regex match for level playlist!');
continue;
}
for (i = 1; i < result.length; i++) {
if (typeof result[i] !== 'undefined') {
break;
}
} // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
var tag = (' ' + result[i]).slice(1);
var value1 = (' ' + result[i + 1]).slice(1);
var value2 = result[i + 2] ? (' ' + result[i + 2]).slice(1) : '';
switch (tag) {
case 'PLAYLIST-TYPE':
level.type = value1.toUpperCase();
break;
case 'MEDIA-SEQUENCE':
currentSN = level.startSN = parseInt(value1);
break;
case 'SKIP':
{
var skipAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
var skippedSegments = skipAttrs.decimalInteger('SKIPPED-SEGMENTS');
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(skippedSegments)) {
level.skippedSegments = skippedSegments; // This will result in fragments[] containing undefined values, which we will fill in with `mergeDetails`
for (var _i = skippedSegments; _i--;) {
fragments.unshift(null);
}
currentSN += skippedSegments;
}
var recentlyRemovedDateranges = skipAttrs.enumeratedString('RECENTLY-REMOVED-DATERANGES');
if (recentlyRemovedDateranges) {
level.recentlyRemovedDateranges = recentlyRemovedDateranges.split('\t');
}
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 '#':
if (value1 || value2) {
frag.tagList.push(value2 ? [value1, value2] : [value1]);
}
break;
case 'DIS':
discontinuityCounter++;
/* falls through */
case 'GAP':
frag.tagList.push([tag]);
break;
case 'BITRATE':
frag.tagList.push([tag, value1]);
break;
case 'DISCONTINUITY-SEQ':
discontinuityCounter = parseInt(value1);
break;
case 'KEY':
{
var _keyAttrs$enumeratedS;
// https://tools.ietf.org/html/rfc8216#section-4.3.2.4
var keyAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
var decryptmethod = keyAttrs.enumeratedString('METHOD');
var decrypturi = keyAttrs.URI;
var decryptiv = keyAttrs.hexadecimalInteger('IV');
var decryptkeyformatversions = keyAttrs.enumeratedString('KEYFORMATVERSIONS');
var decryptkeyid = keyAttrs.enumeratedString('KEYID'); // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of "identity".
var decryptkeyformat = (_keyAttrs$enumeratedS = keyAttrs.enumeratedString('KEYFORMAT')) != null ? _keyAttrs$enumeratedS : 'identity';
var unsupportedKnownKeyformatsInManifest = ['com.apple.streamingkeydelivery', 'com.microsoft.playready', 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed', // widevine (v2)
'com.widevine' // earlier widevine (v1)
];
if (unsupportedKnownKeyformatsInManifest.indexOf(decryptkeyformat) > -1) {
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn("Keyformat " + decryptkeyformat + " is not supported from the manifest");
continue;
} else if (decryptkeyformat !== 'identity') {
// We are supposed to skip keys we don't understand.
// As we currently only officially support identity keys
// from the manifest we shouldn't save any other key.
continue;
} // TODO: multiple keys can be defined on a fragment, and we need to support this
// for clients that support both playready and widevine
if (decryptmethod) {
// TODO: need to determine if the level key is actually a relative URL
// if it isn't, then we should instead construct the LevelKey using fromURI.
levelkey = _level_key__WEBPACK_IMPORTED_MODULE_4__["LevelKey"].fromURL(baseurl, decrypturi);
if (decrypturi && ['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].indexOf(decryptmethod) >= 0) {
levelkey.method = decryptmethod;
levelkey.keyFormat = decryptkeyformat;
if (decryptkeyid) {
levelkey.keyID = decryptkeyid;
}
if (decryptkeyformatversions) {
levelkey.keyFormatVersions = decryptkeyformatversions;
} // Initialization Vector (IV)
levelkey.iv = decryptiv;
}
}
break;
}
case 'START':
{
var startAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET'); // TIME-OFFSET can be 0
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(startTimeOffset)) {
level.startTimeOffset = startTimeOffset;
}
break;
}
case 'MAP':
{
var mapAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
frag.relurl = mapAttrs.URI;
if (mapAttrs.BYTERANGE) {
frag.setByteRange(mapAttrs.BYTERANGE);
}
frag.level = id;
frag.sn = 'initSegment';
if (levelkey) {
frag.levelkey = levelkey;
}
frag.initSegment = null;
currentInitSegment = frag;
createNextFrag = true;
break;
}
case 'SERVER-CONTROL':
{
var serverControlAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
level.canBlockReload = serverControlAttrs.bool('CAN-BLOCK-RELOAD');
level.canSkipUntil = serverControlAttrs.optionalFloat('CAN-SKIP-UNTIL', 0);
level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool('CAN-SKIP-DATERANGES');
level.partHoldBack = serverControlAttrs.optionalFloat('PART-HOLD-BACK', 0);
level.holdBack = serverControlAttrs.optionalFloat('HOLD-BACK', 0);
break;
}
case 'PART-INF':
{
var partInfAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
level.partTarget = partInfAttrs.decimalFloatingPoint('PART-TARGET');
break;
}
case 'PART':
{
var partList = level.partList;
if (!partList) {
partList = level.partList = [];
}
var previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : undefined;
var index = currentPart++;
var part = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Part"](new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1), frag, baseurl, index, previousFragmentPart);
partList.push(part);
frag.duration += part.duration;
break;
}
case 'PRELOAD-HINT':
{
var preloadHintAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
level.preloadHint = preloadHintAttrs;
break;
}
case 'RENDITION-REPORT':
{
var renditionReportAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
level.renditionReports = level.renditionReports || [];
level.renditionReports.push(renditionReportAttrs);
break;
}
default:
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn("line parsed but not handled: " + result);
break;
}
}
}
if (prevFrag && !prevFrag.relurl) {
fragments.pop();
totalduration -= prevFrag.duration;
if (level.partList) {
level.fragmentHint = prevFrag;
}
} else if (level.partList) {
assignProgramDateTime(frag, prevFrag);
frag.cc = discontinuityCounter;
level.fragmentHint = frag;
}
var fragmentLength = fragments.length;
var firstFragment = fragments[0];
var lastFragment = fragments[fragmentLength - 1];
totalduration += level.skippedSegments * level.targetduration;
if (totalduration > 0 && fragmentLength && lastFragment) {
level.averagetargetduration = totalduration / fragmentLength;
var lastSn = lastFragment.sn;
level.endSN = lastSn !== 'initSegment' ? lastSn : 0;
if (firstFragment) {
level.startCC = firstFragment.cc;
if (!firstFragment.initSegment) {
// this is a bit lurky but HLS really has no other way to tell us
// if the fragments are TS or MP4, except if we download them :/
// but this is to be able to handle SIDX.
if (level.fragments.every(function (frag) {
return frag.relurl && isMP4Url(frag.relurl);
})) {
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');
frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl);
frag.relurl = lastFragment.relurl;
frag.level = id;
frag.sn = 'initSegment';
firstFragment.initSegment = frag;
level.needSidxRanges = true;
}
}
}
} else {
level.endSN = 0;
level.startCC = 0;
}
if (level.fragmentHint) {
totalduration += level.fragmentHint.duration;
}
level.totalduration = totalduration;
level.endCC = discontinuityCounter;
/**
* Backfill any missing PDT values
* "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
* one or more Media Segment URIs, the client SHOULD extrapolate
* backward from that tag (using EXTINF durations and/or media
* timestamps) to associate dates with those segments."
* We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
* computed.
*/
if (firstPdtIndex > 0) {
backfillProgramDateTimes(fragments, firstPdtIndex);
}
return level;
};
return M3U8Parser;
}();
function setCodecs(codecs, level) {
['video', 'audio', 'text'].forEach(function (type) {
var filtered = codecs.filter(function (codec) {
return Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_7__["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;
}
function assignCodec(media, groupItem, codecProperty) {
var codecValue = groupItem[codecProperty];
if (codecValue) {
media[codecProperty] = codecValue;
}
}
function backfillProgramDateTimes(fragments, firstPdtIndex) {
var fragPrev = fragments[firstPdtIndex];
for (var i = firstPdtIndex; i--;) {
var frag = fragments[i]; // Exit on delta-playlist skipped segments
if (!frag) {
return;
}
frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;
fragPrev = frag;
}
}
function assignProgramDateTime(frag, prevFrag) {
if (frag.rawProgramDateTime) {
frag.programDateTime = Date.parse(frag.rawProgramDateTime);
} else if (prevFrag !== null && prevFrag !== void 0 && prevFrag.programDateTime) {
frag.programDateTime = prevFrag.endProgramDateTime;
}
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.programDateTime)) {
frag.programDateTime = null;
frag.rawProgramDateTime = null;
}
}
/***/ }),
/***/ "./src/loader/playlist-loader.ts":
/*!***************************************!*\
!*** ./src/loader/playlist-loader.ts ***!
\***************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./m3u8-parser */ "./src/loader/m3u8-parser.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/attr-list */ "./src/utils/attr-list.ts");
/**
* PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.
*
* Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.
*
* Uses loader(s) set in config to do actual internal loading of resource tasks.
*
* @module
*
*/
function mapContextToLevelType(context) {
var type = context.type;
switch (type) {
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK:
return _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK:
return _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].SUBTITLE;
default:
return _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN;
}
}
function getResponseUrl(response, context) {
var url = response.url; // 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;
}
return url;
}
var PlaylistLoader = /*#__PURE__*/function () {
function PlaylistLoader(hls) {
this.hls = void 0;
this.loaders = Object.create(null);
this.hls = hls;
this.registerListeners();
}
var _proto = PlaylistLoader.prototype;
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
};
_proto.unregisterListeners = function unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
}
/**
* Returns defaults or configured loader-type overloads (pLoader and loader config params)
*/
;
_proto.createInternalLoader = function createInternalLoader(context) {
var config = this.hls.config;
var PLoader = config.pLoader;
var Loader = config.loader;
var InternalLoader = PLoader || Loader;
var loader = new InternalLoader(config);
context.loader = loader;
this.loaders[context.type] = loader;
return loader;
};
_proto.getInternalLoader = function getInternalLoader(context) {
return this.loaders[context.type];
};
_proto.resetInternalLoader = function resetInternalLoader(contextType) {
if (this.loaders[contextType]) {
delete this.loaders[contextType];
}
}
/**
* Call `destroy` on all internal loader instances mapped (one per context type)
*/
;
_proto.destroyInternalLoaders = function destroyInternalLoaders() {
for (var contextType in this.loaders) {
var loader = this.loaders[contextType];
if (loader) {
loader.destroy();
}
this.resetInternalLoader(contextType);
}
};
_proto.destroy = function destroy() {
this.unregisterListeners();
this.destroyInternalLoaders();
};
_proto.onManifestLoading = function onManifestLoading(event, data) {
var url = data.url;
this.load({
id: null,
groupId: null,
level: 0,
responseType: 'text',
type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST,
url: url,
deliveryDirectives: null
});
};
_proto.onLevelLoading = function onLevelLoading(event, data) {
var id = data.id,
level = data.level,
url = data.url,
deliveryDirectives = data.deliveryDirectives;
this.load({
id: id,
groupId: null,
level: level,
responseType: 'text',
type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL,
url: url,
deliveryDirectives: deliveryDirectives
});
};
_proto.onAudioTrackLoading = function onAudioTrackLoading(event, data) {
var id = data.id,
groupId = data.groupId,
url = data.url,
deliveryDirectives = data.deliveryDirectives;
this.load({
id: id,
groupId: groupId,
level: null,
responseType: 'text',
type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK,
url: url,
deliveryDirectives: deliveryDirectives
});
};
_proto.onSubtitleTrackLoading = function onSubtitleTrackLoading(event, data) {
var id = data.id,
groupId = data.groupId,
url = data.url,
deliveryDirectives = data.deliveryDirectives;
this.load({
id: id,
groupId: groupId,
level: null,
responseType: 'text',
type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK,
url: url,
deliveryDirectives: deliveryDirectives
});
};
_proto.load = function load(context) {
var _context$deliveryDire;
var config = this.hls.config; // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);
// Check if a loader for this context already exists
var loader = this.getInternalLoader(context);
if (loader) {
var loaderContext = loader.context;
if (loaderContext && loaderContext.url === context.url) {
// same URL can't overlap
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].trace('[playlist-loader]: playlist request ongoing');
return;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log("[playlist-loader]: aborting previous loader for type: " + context.type);
loader.abort();
}
var maxRetry;
var timeout;
var retryDelay;
var maxRetryDelay; // apply different configs for retries depending on
// context (manifest, level, audio/subs playlist)
switch (context.type) {
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST:
maxRetry = config.manifestLoadingMaxRetry;
timeout = config.manifestLoadingTimeOut;
retryDelay = config.manifestLoadingRetryDelay;
maxRetryDelay = config.manifestLoadingMaxRetryTimeout;
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL:
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK:
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK:
// Manage retries in Level/Track Controller
maxRetry = 0;
timeout = config.levelLoadingTimeOut;
break;
default:
maxRetry = config.levelLoadingMaxRetry;
timeout = config.levelLoadingTimeOut;
retryDelay = config.levelLoadingRetryDelay;
maxRetryDelay = config.levelLoadingMaxRetryTimeout;
break;
}
loader = this.createInternalLoader(context); // Override level/track timeout for LL-HLS requests
// (the default of 10000ms is counter productive to blocking playlist reload requests)
if ((_context$deliveryDire = context.deliveryDirectives) !== null && _context$deliveryDire !== void 0 && _context$deliveryDire.part) {
var levelDetails;
if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL && context.level !== null) {
levelDetails = this.hls.levels[context.level].details;
} else if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK && context.id !== null) {
levelDetails = this.hls.audioTracks[context.id].details;
} else if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK && context.id !== null) {
levelDetails = this.hls.subtitleTracks[context.id].details;
}
if (levelDetails) {
var partTarget = levelDetails.partTarget;
var targetDuration = levelDetails.targetduration;
if (partTarget && targetDuration) {
timeout = Math.min(Math.max(partTarget * 3, targetDuration * 0.8) * 1000, timeout);
}
}
}
var loaderConfig = {
timeout: timeout,
maxRetry: maxRetry,
retryDelay: retryDelay,
maxRetryDelay: maxRetryDelay,
highWaterMark: 0
};
var loaderCallbacks = {
onSuccess: this.loadsuccess.bind(this),
onError: this.loaderror.bind(this),
onTimeout: this.loadtimeout.bind(this)
}; // logger.debug(`[playlist-loader]: Calling internal loader delegate for URL: ${context.url}`);
loader.load(context, loaderConfig, loaderCallbacks);
};
_proto.loadsuccess = function loadsuccess(response, stats, context, networkDetails) {
if (networkDetails === void 0) {
networkDetails = null;
}
if (context.isSidxRequest) {
this.handleSidxRequest(response, context);
this.handlePlaylistLoaded(response, stats, context, networkDetails);
return;
}
this.resetInternalLoader(context.type);
var string = response.data; // Validate if it is an M3U8 at all
if (string.indexOf('#EXTM3U') !== 0) {
this.handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);
return;
}
stats.parsing.start = performance.now(); // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)
if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {
this.handleTrackOrLevelPlaylist(response, stats, context, networkDetails);
} else {
this.handleMasterPlaylist(response, stats, context, networkDetails);
}
};
_proto.loaderror = function loaderror(response, context, networkDetails) {
if (networkDetails === void 0) {
networkDetails = null;
}
this.handleNetworkError(context, networkDetails, false, response);
};
_proto.loadtimeout = function loadtimeout(stats, context, networkDetails) {
if (networkDetails === void 0) {
networkDetails = null;
}
this.handleNetworkError(context, networkDetails, true);
};
_proto.handleMasterPlaylist = function handleMasterPlaylist(response, stats, context, networkDetails) {
var hls = this.hls;
var string = response.data;
var url = getResponseUrl(response, context);
var _M3U8Parser$parseMast = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylist(string, url),
levels = _M3U8Parser$parseMast.levels,
sessionData = _M3U8Parser$parseMast.sessionData;
if (!levels.length) {
this.handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);
return;
} // multi level playlist, parse level info
var audioGroups = levels.map(function (level) {
return {
id: level.attrs.AUDIO,
audioCodec: level.audioCodec
};
});
var subtitleGroups = levels.map(function (level) {
return {
id: level.attrs.SUBTITLES,
textCodec: level.textCodec
};
});
var audioTracks = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);
var subtitles = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'SUBTITLES', subtitleGroups);
var captions = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'CLOSED-CAPTIONS');
if (audioTracks.length) {
// check if we have found an audio track embedded in main playlist (audio track without URI attribute)
var embeddedAudioFound = audioTracks.some(function (audioTrack) {
return !audioTrack.url;
}); // 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 && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log('[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one');
audioTracks.unshift({
type: 'main',
name: 'main',
default: false,
autoselect: false,
forced: false,
id: -1,
attrs: new _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__["AttrList"]({}),
bitrate: 0,
url: ''
});
}
}
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, {
levels: levels,
audioTracks: audioTracks,
subtitles: subtitles,
captions: captions,
url: url,
stats: stats,
networkDetails: networkDetails,
sessionData: sessionData
});
};
_proto.handleTrackOrLevelPlaylist = function handleTrackOrLevelPlaylist(response, stats, context, networkDetails) {
var hls = this.hls;
var id = context.id,
level = context.level,
type = context.type;
var url = getResponseUrl(response, context);
var levelUrlId = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(id) ? id : 0;
var levelId = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(level) ? level : levelUrlId;
var levelType = mapContextToLevelType(context);
var levelDetails = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId);
if (!levelDetails.fragments.length) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_EMPTY_ERROR,
fatal: false,
url: url,
reason: 'no fragments found in level',
level: typeof context.level === 'number' ? context.level : undefined
});
return;
} // We have done our first request (Manifest-type) and receive
// not a master playlist but a chunk-list (track/level)
// We fire the manifest-loaded event anyway with the parsed level-details
// by creating a single-level structure for it.
if (type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST) {
var singleLevel = {
attrs: new _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__["AttrList"]({}),
bitrate: 0,
details: levelDetails,
name: '',
url: url
};
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, {
levels: [singleLevel],
audioTracks: [],
url: url,
stats: stats,
networkDetails: networkDetails,
sessionData: null
});
} // save parsing time
stats.parsing.end = performance.now(); // in case we need SIDX ranges
// return early after calling load for
// the SIDX box.
if (levelDetails.needSidxRanges) {
var _levelDetails$fragmen;
var sidxUrl = (_levelDetails$fragmen = levelDetails.fragments[0].initSegment) === null || _levelDetails$fragmen === void 0 ? void 0 : _levelDetails$fragmen.url;
this.load({
url: sidxUrl,
isSidxRequest: true,
type: type,
level: level,
levelDetails: levelDetails,
id: id,
groupId: null,
rangeStart: 0,
rangeEnd: 2048,
responseType: 'arraybuffer',
deliveryDirectives: null
});
return;
} // extend the context with the new levelDetails property
context.levelDetails = levelDetails;
this.handlePlaylistLoaded(response, stats, context, networkDetails);
};
_proto.handleSidxRequest = function handleSidxRequest(response, context) {
var sidxInfo = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__["parseSegmentIndex"])(new Uint8Array(response.data)); // if provided fragment does not contain sidx, early return
if (!sidxInfo) {
return;
}
var sidxReferences = sidxInfo.references;
var levelDetails = context.levelDetails;
sidxReferences.forEach(function (segmentRef, index) {
var segRefInfo = segmentRef.info;
var frag = levelDetails.fragments[index];
if (frag.byteRange.length === 0) {
frag.setByteRange(String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start));
}
if (frag.initSegment) {
frag.initSegment.setByteRange(String(sidxInfo.moovEndOffset) + '@0');
}
});
};
_proto.handleManifestParsingError = function handleManifestParsingError(response, context, reason, networkDetails) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_PARSING_ERROR,
fatal: context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST,
url: response.url,
reason: reason,
response: response,
context: context,
networkDetails: networkDetails
});
};
_proto.handleNetworkError = function handleNetworkError(context, networkDetails, timeout, response) {
if (timeout === void 0) {
timeout = false;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("[playlist-loader]: A network " + (timeout ? 'timeout' : 'error') + " occurred while loading " + context.type + " level: " + context.level + " id: " + context.id + " group-id: \"" + context.groupId + "\"");
var details = _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].UNKNOWN;
var fatal = false;
var loader = this.getInternalLoader(context);
switch (context.type) {
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST:
details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_LOAD_ERROR;
fatal = true;
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL:
details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_ERROR;
fatal = false;
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK:
details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].AUDIO_TRACK_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR;
fatal = false;
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK:
details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].SUBTITLE_TRACK_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].SUBTITLE_LOAD_ERROR;
fatal = false;
break;
}
if (loader) {
this.resetInternalLoader(context.type);
}
var errorData = {
type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].NETWORK_ERROR,
details: details,
fatal: fatal,
url: context.url,
loader: loader,
context: context,
networkDetails: networkDetails
};
if (response) {
errorData.response = response;
}
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, errorData);
};
_proto.handlePlaylistLoaded = function handlePlaylistLoaded(response, stats, context, networkDetails) {
var type = context.type,
level = context.level,
id = context.id,
groupId = context.groupId,
loader = context.loader,
levelDetails = context.levelDetails,
deliveryDirectives = context.deliveryDirectives;
if (!(levelDetails !== null && levelDetails !== void 0 && levelDetails.targetduration)) {
this.handleManifestParsingError(response, context, 'invalid target duration', networkDetails);
return;
}
if (!loader) {
return;
}
if (levelDetails.live) {
if (loader.getCacheAge) {
levelDetails.ageHeader = loader.getCacheAge() || 0;
}
if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {
levelDetails.ageHeader = 0;
}
}
switch (type) {
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST:
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL:
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADED, {
details: levelDetails,
level: level || 0,
id: id || 0,
stats: stats,
networkDetails: networkDetails,
deliveryDirectives: deliveryDirectives
});
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK:
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_LOADED, {
details: levelDetails,
id: id || 0,
groupId: groupId || '',
stats: stats,
networkDetails: networkDetails,
deliveryDirectives: deliveryDirectives
});
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK:
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACK_LOADED, {
details: levelDetails,
id: id || 0,
groupId: groupId || '',
stats: stats,
networkDetails: networkDetails,
deliveryDirectives: deliveryDirectives
});
break;
}
};
return PlaylistLoader;
}();
/* harmony default export */ __webpack_exports__["default"] = (PlaylistLoader);
/***/ }),
/***/ "./src/polyfills/number.ts":
/*!*********************************!*\
!*** ./src/polyfills/number.ts ***!
\*********************************/
/*! exports provided: isFiniteNumber, MAX_SAFE_INTEGER */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFiniteNumber", function() { return isFiniteNumber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MAX_SAFE_INTEGER", function() { return MAX_SAFE_INTEGER; });
var isFiniteNumber = Number.isFinite || function (value) {
return typeof value === 'number' && isFinite(value);
};
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
/***/ }),
/***/ "./src/remux/aac-helper.ts":
/*!*********************************!*\
!*** ./src/remux/aac-helper.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/**
* AAC helper
*/
var AAC = /*#__PURE__*/function () {
function 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 undefined;
};
return AAC;
}();
/* harmony default export */ __webpack_exports__["default"] = (AAC);
/***/ }),
/***/ "./src/remux/mp4-generator.ts":
/*!************************************!*\
!*** ./src/remux/mp4-generator.ts ***!
\************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/**
* Generate MP4 Box
*/
var UINT32_MAX = Math.pow(2, 32) - 1;
var MP4 = /*#__PURE__*/function () {
function 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 // sample_count
]);
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 size = 8;
for (var _len = arguments.length, payload = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
payload[_key - 1] = arguments[_key];
}
var i = payload.length;
var len = i; // calculate the total size we need to allocate
while (i--) {
size += payload[i].byteLength;
}
var 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 / (UINT32_MAX + 1));
var lowerWordDuration = Math.floor(duration % (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;
var 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;
var 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 / (UINT32_MAX + 1));
var lowerWordDuration = Math.floor(duration % (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 || [];
var bytes = new Uint8Array(4 + samples.length);
var i;
var flags; // 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 = [];
var pps = [];
var i;
var data;
var 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 = sps.concat(Array.prototype.slice.call(data));
} // 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"
var width = track.width;
var height = track.height;
var hSpacing = track.pixelRatio[0];
var vSpacing = track.pixelRatio[1];
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;
var duration = track.duration * track.timescale;
var width = track.width;
var height = track.height;
var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
var lowerWordDuration = Math.floor(duration % (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);
var id = track.id;
var upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
var lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (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 || [];
var len = samples.length;
var arraylen = 12 + 16 * len;
var array = new Uint8Array(arraylen);
var i;
var sample;
var duration;
var size;
var flags;
var 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);
var result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);
result.set(MP4.FTYP);
result.set(movie, MP4.FTYP.byteLength);
return result;
};
return MP4;
}();
MP4.types = void 0;
MP4.HDLR_TYPES = void 0;
MP4.STTS = void 0;
MP4.STSC = void 0;
MP4.STCO = void 0;
MP4.STSZ = void 0;
MP4.VMHD = void 0;
MP4.SMHD = void 0;
MP4.STSD = void 0;
MP4.FTYP = void 0;
MP4.DINF = void 0;
/* harmony default export */ __webpack_exports__["default"] = (MP4);
/***/ }),
/***/ "./src/remux/mp4-remuxer.ts":
/*!**********************************!*\
!*** ./src/remux/mp4-remuxer.ts ***!
\**********************************/
/*! exports provided: default, normalizePts */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return MP4Remuxer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "normalizePts", function() { return normalizePts; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _aac_helper__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./aac-helper */ "./src/remux/aac-helper.ts");
/* harmony import */ var _mp4_generator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./mp4-generator */ "./src/remux/mp4-generator.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/timescale-conversion */ "./src/utils/timescale-conversion.ts");
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
var MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds
var AAC_SAMPLES_PER_FRAME = 1024;
var MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;
var chromeVersion = null;
var safariWebkitVersion = null;
var requiresPositiveDts = false;
var MP4Remuxer = /*#__PURE__*/function () {
function MP4Remuxer(observer, config, typeSupported, vendor) {
if (vendor === void 0) {
vendor = '';
}
this.observer = void 0;
this.config = void 0;
this.typeSupported = void 0;
this.ISGenerated = false;
this._initPTS = void 0;
this._initDTS = void 0;
this.nextAvcDts = null;
this.nextAudioPts = null;
this.isAudioContiguous = false;
this.isVideoContiguous = false;
this.observer = observer;
this.config = config;
this.typeSupported = typeSupported;
this.ISGenerated = false;
if (chromeVersion === null) {
var userAgent = navigator.userAgent || '';
var result = userAgent.match(/Chrome\/(\d+)/i);
chromeVersion = result ? parseInt(result[1]) : 0;
}
if (safariWebkitVersion === null) {
var _result = navigator.userAgent.match(/Safari\/(\d+)/i);
safariWebkitVersion = _result ? parseInt(_result[1]) : 0;
}
requiresPositiveDts = !!chromeVersion && chromeVersion < 75 || !!safariWebkitVersion && safariWebkitVersion < 600;
}
var _proto = MP4Remuxer.prototype;
_proto.destroy = function destroy() {};
_proto.resetTimeStamp = function resetTimeStamp(defaultTimeStamp) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: initPTS & initDTS reset');
this._initPTS = this._initDTS = defaultTimeStamp;
};
_proto.resetNextTimestamp = function resetNextTimestamp() {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: reset next timestamp');
this.isVideoContiguous = false;
this.isAudioContiguous = false;
};
_proto.resetInitSegment = function resetInitSegment() {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: ISGenerated flag reset');
this.ISGenerated = false;
};
_proto.getVideoStartPts = function getVideoStartPts(videoSamples) {
var rolloverDetected = false;
var startPTS = videoSamples.reduce(function (minPTS, sample) {
var delta = sample.pts - minPTS;
if (delta < -4294967296) {
// 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation
rolloverDetected = true;
return normalizePts(minPTS, sample.pts);
} else if (delta > 0) {
return minPTS;
} else {
return sample.pts;
}
}, videoSamples[0].pts);
if (rolloverDetected) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].debug('PTS rollover detected');
}
return startPTS;
};
_proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) {
var video;
var audio;
var initSegment;
var text;
var id3;
var independent;
var audioTimeOffset = timeOffset;
var videoTimeOffset = timeOffset; // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding.
// This is done to synchronize the audio and video streams. We know if the current segment will have samples if the "pid"
// parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list.
// However, if the initSegment has already been generated, or we've reached the end of a segment (flush),
// then we can remux one track without waiting for the other.
var hasAudio = audioTrack.pid > -1;
var hasVideo = videoTrack.pid > -1;
var length = videoTrack.samples.length;
var enoughAudioSamples = audioTrack.samples.length > 0;
var enoughVideoSamples = length > 1;
var canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush;
if (canRemuxAvc) {
if (!this.ISGenerated) {
initSegment = this.generateIS(audioTrack, videoTrack, timeOffset);
}
var isVideoContiguous = this.isVideoContiguous;
var firstKeyFrameIndex = -1;
if (enoughVideoSamples) {
firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);
if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {
independent = true;
if (firstKeyFrameIndex > 0) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: Dropped " + firstKeyFrameIndex + " out of " + length + " video samples due to a missing keyframe");
var startPTS = this.getVideoStartPts(videoTrack.samples);
videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);
videoTrack.dropped += firstKeyFrameIndex;
videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / (videoTrack.timescale || 90000);
} else if (firstKeyFrameIndex === -1) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: No keyframe found out of " + length + " video samples");
independent = false;
}
}
}
if (this.ISGenerated) {
if (enoughAudioSamples && enoughVideoSamples) {
// 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 _startPTS = this.getVideoStartPts(videoTrack.samples);
var tsDelta = normalizePts(audioTrack.samples[0].pts, _startPTS) - _startPTS;
var audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
} // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio.
if (enoughAudioSamples) {
// if initSegment was generated without audio samples, regenerate it again
if (!audioTrack.samplerate) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn('[mp4-remuxer]: regenerate InitSegment as audio detected');
initSegment = this.generateIS(audioTrack, videoTrack, timeOffset);
}
audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO ? videoTimeOffset : undefined);
if (enoughVideoSamples) {
var audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0; // if initSegment was generated without video samples, regenerate it again
if (!videoTrack.inputTimeScale) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn('[mp4-remuxer]: regenerate InitSegment as video detected');
initSegment = this.generateIS(audioTrack, videoTrack, timeOffset);
}
video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);
}
} else if (enoughVideoSamples) {
video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);
}
if (video) {
video.firstKeyFrame = firstKeyFrameIndex;
video.independent = firstKeyFrameIndex !== -1;
}
}
} // Allow ID3 and text to remux, even if more audio/video samples are required
if (this.ISGenerated) {
if (id3Track.samples.length) {
id3 = this.remuxID3(id3Track, timeOffset);
}
if (textTrack.samples.length) {
text = this.remuxText(textTrack, timeOffset);
}
}
return {
audio: audio,
video: video,
initSegment: initSegment,
independent: independent,
text: text,
id3: id3
};
};
_proto.generateIS = function generateIS(audioTrack, videoTrack, timeOffset) {
var audioSamples = audioTrack.samples;
var videoSamples = videoTrack.samples;
var typeSupported = this.typeSupported;
var tracks = {};
var computePTSDTS = !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this._initPTS);
var container = 'audio/mp4';
var initPTS;
var initDTS;
var timescale;
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;
if (!audioTrack.isAAC) {
if (typeSupported.mpeg) {
// Chrome and Safari
container = 'audio/mpeg';
audioTrack.codec = '';
} else if (typeSupported.mp3) {
// Firefox
audioTrack.codec = 'mp3';
}
}
tracks.audio = {
id: 'audio',
container: container,
codec: audioTrack.codec,
initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array(0) : _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].initSegment([audioTrack]),
metadata: {
channelCount: audioTrack.channelCount
}
};
if (computePTSDTS) {
timescale = audioTrack.inputTimeScale; // remember first PTS of this demuxing context. for audio, PTS = DTS
initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * 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
videoTrack.timescale = videoTrack.inputTimeScale;
tracks.video = {
id: 'main',
container: 'video/mp4',
codec: videoTrack.codec,
initSegment: _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].initSegment([videoTrack]),
metadata: {
width: videoTrack.width,
height: videoTrack.height
}
};
if (computePTSDTS) {
timescale = videoTrack.inputTimeScale;
var startPTS = this.getVideoStartPts(videoSamples);
var startOffset = Math.round(timescale * timeOffset);
initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset);
initPTS = Math.min(initPTS, startPTS - startOffset);
}
}
if (Object.keys(tracks).length) {
this.ISGenerated = true;
if (computePTSDTS) {
this._initPTS = initPTS;
this._initDTS = initDTS;
}
return {
tracks: tracks,
initPTS: initPTS,
timescale: timescale
};
}
};
_proto.remuxVideo = function remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
var timeScale = track.inputTimeScale;
var inputSamples = track.samples;
var outputSamples = [];
var nbSamples = inputSamples.length;
var initPTS = this._initPTS;
var nextAvcDts = this.nextAvcDts;
var offset = 8;
var mp4SampleDuration;
var firstDTS;
var lastDTS;
var minPTS = Number.POSITIVE_INFINITY;
var maxPTS = Number.NEGATIVE_INFINITY;
var ptsDtsShift = 0;
var sortSamples = false; // if parsed fragment is contiguous with last one, let's use last DTS value as reference
if (!contiguous || nextAvcDts === null) {
var pts = timeOffset * timeScale;
var cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts); // if not contiguous, let's use target timeOffset
nextAvcDts = pts - cts;
} // 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
for (var i = 0; i < nbSamples; i++) {
var sample = inputSamples[i];
sample.pts = normalizePts(sample.pts - initPTS, nextAvcDts);
sample.dts = normalizePts(sample.dts - initPTS, nextAvcDts);
if (sample.dts > sample.pts) {
var PTS_DTS_SHIFT_TOLERANCE_90KHZ = 90000 * 0.2;
ptsDtsShift = Math.max(Math.min(ptsDtsShift, sample.pts - sample.dts), -1 * PTS_DTS_SHIFT_TOLERANCE_90KHZ);
}
if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {
sortSamples = true;
}
} // sort video samples by DTS then PTS then demux id order
if (sortSamples) {
inputSamples.sort(function (a, b) {
var deltadts = a.dts - b.dts;
var deltapts = a.pts - b.pts;
return deltadts || deltapts;
});
} // Get first/last DTS
firstDTS = inputSamples[0].dts;
lastDTS = inputSamples[inputSamples.length - 1].dts; // 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.
var averageSampleDuration = Math.round((lastDTS - firstDTS) / (nbSamples - 1)); // handle broken streams with PTS < DTS, tolerance up 0.2 seconds
if (ptsDtsShift < 0) {
if (ptsDtsShift < averageSampleDuration * -2) {
// Fix for "CNN special report, with CC" in test-streams (including Safari browser)
// With large PTS < DTS errors such as this, we want to correct CTS while maintaining increasing DTS values
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("PTS < DTS detected in video samples, offsetting DTS from PTS by " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(-averageSampleDuration, true) + " ms");
var lastDts = ptsDtsShift;
for (var _i = 0; _i < nbSamples; _i++) {
inputSamples[_i].dts = lastDts = Math.max(lastDts, inputSamples[_i].pts - averageSampleDuration);
inputSamples[_i].pts = Math.max(lastDts, inputSamples[_i].pts);
}
} else {
// Fix for "Custom IV with bad PTS DTS" in test-streams
// With smaller PTS < DTS errors we can simply move all DTS back. This increases CTS without causing buffer gaps or decode errors in Safari
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("PTS < DTS detected in video samples, shifting DTS by " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(ptsDtsShift, true) + " ms to overcome this issue");
for (var _i2 = 0; _i2 < nbSamples; _i2++) {
inputSamples[_i2].dts = inputSamples[_i2].dts + ptsDtsShift;
}
}
firstDTS = inputSamples[0].dts;
} // if fragment are contiguous, detect hole/overlapping between fragments
if (contiguous) {
// check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)
var delta = firstDTS - nextAvcDts;
var foundHole = delta > averageSampleDuration;
var foundOverlap = delta < -1;
if (foundHole || foundOverlap) {
if (foundHole) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("AVC: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(delta, true) + " ms (" + delta + "dts) hole between fragments detected, filling it");
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("AVC: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(-delta, true) + " ms (" + delta + "dts) overlapping between fragments detected");
}
firstDTS = nextAvcDts;
var firstPTS = inputSamples[0].pts - delta;
inputSamples[0].dts = firstDTS;
inputSamples[0].pts = firstPTS;
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log("Video: First PTS/DTS adjusted: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(firstPTS, true) + "/" + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(firstDTS, true) + ", delta: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(delta, true) + " ms");
}
}
if (requiresPositiveDts) {
firstDTS = Math.max(0, firstDTS);
}
var nbNalu = 0;
var naluLen = 0;
for (var _i3 = 0; _i3 < nbSamples; _i3++) {
// compute total/avc sample length and nb of NAL units
var _sample = inputSamples[_i3];
var units = _sample.units;
var nbUnits = units.length;
var sampleLen = 0;
for (var j = 0; j < nbUnits; j++) {
sampleLen += units[j].data.length;
}
naluLen += sampleLen;
nbNalu += nbUnits;
_sample.length = sampleLen; // normalize PTS/DTS
// 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, 0);
minPTS = Math.min(_sample.pts, minPTS);
maxPTS = Math.max(_sample.pts, maxPTS);
}
lastDTS = inputSamples[nbSamples - 1].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;
var mdat;
try {
mdat = new Uint8Array(mdatSize);
} catch (err) {
this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].MUX_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_4__["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__WEBPACK_IMPORTED_MODULE_2__["default"].types.mdat, 4);
for (var _i4 = 0; _i4 < nbSamples; _i4++) {
var avcSample = inputSamples[_i4];
var avcSampleUnits = avcSample.units;
var mp4SampleLength = 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];
var unitData = unit.data;
var unitDataLen = unit.data.byteLength;
view.setUint32(offset, unitDataLen);
offset += 4;
mdat.set(unitData, offset);
offset += unitDataLen;
mp4SampleLength += 4 + unitDataLen;
} // expected sample duration is the Decoding Timestamp diff of consecutive samples
if (_i4 < nbSamples - 1) {
mp4SampleDuration = inputSamples[_i4 + 1].dts - avcSample.dts;
} else {
var config = this.config;
var lastFrameDuration = avcSample.dts - inputSamples[_i4 > 0 ? _i4 - 1 : _i4].dts;
if (config.stretchShortVideoTrack && this.nextAudioPts !== null) {
// 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 maxBufferHole.
// 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 gapTolerance = Math.floor(config.maxBufferHole * timeScale);
var deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;
if (deltaToFrameEnd > gapTolerance) {
// We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
// frame overlap. maxBufferHole should be >> lastFrameDuration anyway.
mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
if (mp4SampleDuration < 0) {
mp4SampleDuration = lastFrameDuration;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log("[mp4-remuxer]: 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;
}
}
var compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts);
outputSamples.push(new Mp4Sample(avcSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));
}
if (outputSamples.length && chromeVersion && chromeVersion < 70) {
// Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue
// https://code.google.com/p/chromium/issues/detail?id=229412
var flags = outputSamples[0].flags;
flags.dependsOn = 2;
flags.isNonSync = 0;
}
console.assert(mp4SampleDuration !== undefined, 'mp4SampleDuration must be computed'); // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
this.nextAvcDts = nextAvcDts = lastDTS + mp4SampleDuration;
this.isVideoContiguous = true;
var moof = _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].moof(track.sequenceNumber++, firstDTS, _extends({}, track, {
samples: outputSamples
}));
var type = 'video';
var data = {
data1: moof,
data2: mdat,
startPTS: minPTS / timeScale,
endPTS: (maxPTS + mp4SampleDuration) / timeScale,
startDTS: firstDTS / timeScale,
endDTS: nextAvcDts / timeScale,
type: type,
hasAudio: false,
hasVideo: true,
nb: outputSamples.length,
dropped: track.dropped
};
track.samples = [];
track.dropped = 0;
console.assert(mdat.length, 'MDAT length must not be zero');
return data;
};
_proto.remuxAudio = function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {
var inputTimeScale = track.inputTimeScale;
var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
var scaleFactor = inputTimeScale / mp4timeScale;
var mp4SampleDuration = track.isAAC ? AAC_SAMPLES_PER_FRAME : MPEG_AUDIO_SAMPLE_PER_FRAME;
var inputSampleDuration = mp4SampleDuration * scaleFactor;
var initPTS = this._initPTS;
var rawMPEG = !track.isAAC && this.typeSupported.mpeg;
var outputSamples = [];
var inputSamples = track.samples;
var offset = rawMPEG ? 0 : 8;
var nextAudioPts = this.nextAudioPts || -1; // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]);
// 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
var timeOffsetMpegTS = timeOffset * inputTimeScale;
this.isAudioContiguous = contiguous = contiguous || inputSamples.length && nextAudioPts > 0 && (accurateTimeOffset && Math.abs(timeOffsetMpegTS - nextAudioPts) < 9000 || Math.abs(normalizePts(inputSamples[0].pts - initPTS, timeOffsetMpegTS) - nextAudioPts) < 20 * inputSampleDuration); // compute normalized PTS
inputSamples.forEach(function (sample) {
sample.pts = normalizePts(sample.pts - initPTS, timeOffsetMpegTS);
});
if (!contiguous || nextAudioPts < 0) {
// filter out sample with negative PTS that are not playable anyway
// if we don't remove these negative samples, they will shift all audio samples forward.
// leading to audio overlap between current / next fragment
inputSamples = inputSamples.filter(function (sample) {
return sample.pts >= 0;
}); // in case all samples have negative PTS, and have been filtered out, return now
if (!inputSamples.length) {
return;
}
if (videoTimeOffset === 0) {
// Set the start to 0 to match video so that start gaps larger than inputSampleDuration are filled with silence
nextAudioPts = 0;
} else if (accurateTimeOffset) {
// When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS
nextAudioPts = Math.max(0, timeOffsetMpegTS);
} else {
// if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
nextAudioPts = inputSamples[0].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.
if (track.isAAC) {
var alignedWithVideo = videoTimeOffset !== undefined;
var maxAudioFramesDrift = this.config.maxAudioFramesDrift;
for (var i = 0, nextPts = nextAudioPts; i < inputSamples.length; i++) {
// First, let's see how far off this frame is from where we expect it to be
var sample = inputSamples[i];
var pts = sample.pts;
var delta = pts - nextPts;
var duration = Math.abs(1000 * delta / inputTimeScale); // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync
if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) {
if (i === 0) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("Audio frame @ " + (pts / inputTimeScale).toFixed(3) + "s overlaps nextAudioPts by " + Math.round(1000 * delta / inputTimeScale) + " ms.");
this.nextAudioPts = nextAudioPts = nextPts = pts;
}
} // eslint-disable-line brace-style
// 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
// 4: remuxing with video (videoTimeOffset !== undefined)
else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) {
var missing = Math.round(delta / inputSampleDuration); // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from
// later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration.
nextPts = pts - missing * inputSampleDuration;
if (nextPts < 0) {
missing--;
nextPts += inputSampleDuration;
}
if (i === 0) {
this.nextAudioPts = nextAudioPts = nextPts;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: 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);
var fillFrame = _aac_helper__WEBPACK_IMPORTED_MODULE_1__["default"].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
if (!fillFrame) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: 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
});
nextPts += inputSampleDuration;
i++;
}
}
sample.pts = nextPts;
nextPts += inputSampleDuration;
}
}
var firstPTS = null;
var lastPTS = null;
var mdat;
var mdatSize = 0;
var sampleLength = inputSamples.length;
while (sampleLength--) {
mdatSize += inputSamples[sampleLength].unit.byteLength;
}
for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) {
var audioSample = inputSamples[_j2];
var unit = audioSample.unit;
var _pts = audioSample.pts;
if (lastPTS !== null) {
// If we have more than one sample, set the duration of the sample to the "real" duration; the PTS diff with
// the previous sample
var prevSample = outputSamples[_j2 - 1];
prevSample.duration = Math.round((_pts - lastPTS) / scaleFactor);
} else {
if (contiguous && track.isAAC) {
// set PTS/DTS to expected PTS/DTS
_pts = nextAudioPts;
} // remember first PTS of our audioSamples
firstPTS = _pts;
if (mdatSize > 0) {
/* concatenate the audio data and construct the mdat in place
(need 8 more bytes to fill length and mdat type) */
mdatSize += offset;
try {
mdat = new Uint8Array(mdatSize);
} catch (err) {
this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].MUX_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_4__["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__WEBPACK_IMPORTED_MODULE_2__["default"].types.mdat, 4);
}
} else {
// no audio samples
return;
}
}
mdat.set(unit, offset);
var unitLen = unit.byteLength;
offset += unitLen; // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG
// In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration
// becomes the PTS diff with the previous sample
outputSamples.push(new Mp4Sample(true, mp4SampleDuration, unitLen, 0));
lastPTS = _pts;
} // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones
var nbSamples = outputSamples.length;
if (!nbSamples) {
return;
} // The next audio sample PTS should be equal to last sample PTS + duration
var lastSample = outputSamples[outputSamples.length - 1];
this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSample.duration; // Set the track samples from inputSamples to outputSamples before remuxing
var moof = rawMPEG ? new Uint8Array(0) : _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, {
samples: outputSamples
})); // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared
track.samples = [];
var start = firstPTS / inputTimeScale;
var end = nextAudioPts / inputTimeScale;
var type = 'audio';
var audioData = {
data1: moof,
data2: mdat,
startPTS: start,
endPTS: end,
startDTS: start,
endDTS: end,
type: type,
hasAudio: true,
hasVideo: false,
nb: nbSamples
};
this.isAudioContiguous = true;
console.assert(mdat.length, 'MDAT length must not be zero');
return audioData;
};
_proto.remuxEmptyAudio = function remuxEmptyAudio(track, timeOffset, contiguous, videoData) {
var inputTimeScale = track.inputTimeScale;
var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
var scaleFactor = inputTimeScale / mp4timeScale;
var nextAudioPts = this.nextAudioPts; // sync with video's timestamp
var startDTS = (nextAudioPts !== null ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS;
var endDTS = videoData.endDTS * inputTimeScale + this._initDTS; // one sample's duration value
var frameDuration = scaleFactor * AAC_SAMPLES_PER_FRAME; // samples count of this segment's duration
var nbSamples = Math.ceil((endDTS - startDTS) / frameDuration); // silent frame
var silentFrame = _aac_helper__WEBPACK_IMPORTED_MODULE_1__["default"].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn('[mp4-remuxer]: remux empty Audio'); // Can't remux if we can't generate a silent frame...
if (!silentFrame) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].trace('[mp4-remuxer]: 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.samples = samples;
return this.remuxAudio(track, timeOffset, contiguous, false);
};
_proto.remuxID3 = function remuxID3(track, timeOffset) {
var length = track.samples.length;
if (!length) {
return;
}
var inputTimeScale = track.inputTimeScale;
var initPTS = this._initPTS;
var initDTS = this._initDTS;
for (var index = 0; index < length; index++) {
var sample = track.samples[index]; // setting id3 pts, dts to relative time
// using this._initPTS and this._initDTS to calculate relative time
sample.pts = normalizePts(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;
sample.dts = normalizePts(sample.dts - initDTS, timeOffset * inputTimeScale) / inputTimeScale;
}
var samples = track.samples;
track.samples = [];
return {
samples: samples
};
};
_proto.remuxText = function remuxText(track, timeOffset) {
var length = track.samples.length;
if (!length) {
return;
}
var inputTimeScale = track.inputTimeScale;
var initPTS = this._initPTS;
for (var index = 0; index < length; index++) {
var sample = track.samples[index]; // setting text pts, dts to relative time
// using this._initPTS and this._initDTS to calculate relative time
sample.pts = normalizePts(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;
}
track.samples.sort(function (a, b) {
return a.pts - b.pts;
});
var samples = track.samples;
track.samples = [];
return {
samples: samples
};
};
return MP4Remuxer;
}();
function normalizePts(value, reference) {
var offset;
if (reference === null) {
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;
}
function findKeyframeIndex(samples) {
for (var i = 0; i < samples.length; i++) {
if (samples[i].key) {
return i;
}
}
return -1;
}
var Mp4Sample = function Mp4Sample(isKeyframe, duration, size, cts) {
this.size = void 0;
this.duration = void 0;
this.cts = void 0;
this.flags = void 0;
this.duration = duration;
this.size = size;
this.cts = cts;
this.flags = new Mp4SampleFlags(isKeyframe);
};
var Mp4SampleFlags = function Mp4SampleFlags(isKeyframe) {
this.isLeading = 0;
this.isDependedOn = 0;
this.hasRedundancy = 0;
this.degradPrio = 0;
this.dependsOn = 1;
this.isNonSync = 1;
this.dependsOn = isKeyframe ? 2 : 1;
this.isNonSync = isKeyframe ? 0 : 1;
};
/***/ }),
/***/ "./src/remux/passthrough-remuxer.ts":
/*!******************************************!*\
!*** ./src/remux/passthrough-remuxer.ts ***!
\******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var PassThroughRemuxer = /*#__PURE__*/function () {
function PassThroughRemuxer() {
this.emitInitSegment = false;
this.audioCodec = void 0;
this.videoCodec = void 0;
this.initData = void 0;
this.initPTS = void 0;
this.initTracks = void 0;
this.lastEndDTS = null;
}
var _proto = PassThroughRemuxer.prototype;
_proto.destroy = function destroy() {};
_proto.resetTimeStamp = function resetTimeStamp(defaultInitPTS) {
this.initPTS = defaultInitPTS;
this.lastEndDTS = null;
};
_proto.resetNextTimestamp = function resetNextTimestamp() {
this.lastEndDTS = null;
};
_proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec) {
this.audioCodec = audioCodec;
this.videoCodec = videoCodec;
this.generateInitSegment(initSegment);
this.emitInitSegment = true;
};
_proto.generateInitSegment = function generateInitSegment(initSegment) {
var audioCodec = this.audioCodec,
videoCodec = this.videoCodec;
if (!initSegment || !initSegment.byteLength) {
this.initTracks = undefined;
this.initData = undefined;
return;
}
var initData = this.initData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["parseInitSegment"])(initSegment); // Get codec from initSegment or fallback to default
if (!audioCodec) {
audioCodec = getParsedTrackCodec(initData.audio, _loader_fragment__WEBPACK_IMPORTED_MODULE_2__["ElementaryStreamTypes"].AUDIO);
}
if (!videoCodec) {
videoCodec = getParsedTrackCodec(initData.video, _loader_fragment__WEBPACK_IMPORTED_MODULE_2__["ElementaryStreamTypes"].VIDEO);
}
var tracks = {};
if (initData.audio && initData.video) {
tracks.audiovideo = {
container: 'video/mp4',
codec: audioCodec + ',' + videoCodec,
initSegment: initSegment,
id: 'main'
};
} else if (initData.audio) {
tracks.audio = {
container: 'audio/mp4',
codec: audioCodec,
initSegment: initSegment,
id: 'audio'
};
} else if (initData.video) {
tracks.video = {
container: 'video/mp4',
codec: videoCodec,
initSegment: initSegment,
id: 'main'
};
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes.');
}
this.initTracks = tracks;
};
_proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset) {
var initPTS = this.initPTS,
lastEndDTS = this.lastEndDTS;
var result = {
audio: undefined,
video: undefined,
text: textTrack,
id3: id3Track,
initSegment: undefined
}; // If we haven't yet set a lastEndDTS, or it was reset, set it to the provided timeOffset. We want to use the
// lastEndDTS over timeOffset whenever possible; during progressive playback, the media source will not update
// the media duration (which is what timeOffset is provided as) before we need to process the next chunk.
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(lastEndDTS)) {
lastEndDTS = this.lastEndDTS = timeOffset || 0;
} // The binary segment data is added to the videoTrack in the mp4demuxer. We don't check to see if the data is only
// audio or video (or both); adding it to video was an arbitrary choice.
var data = videoTrack.samples;
if (!data || !data.length) {
return result;
}
var initSegment = {
initPTS: undefined,
timescale: 1
};
var initData = this.initData;
if (!initData || !initData.length) {
this.generateInitSegment(data);
initData = this.initData;
}
if (!initData || !initData.length) {
// We can't remux if the initSegment could not be generated
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('[passthrough-remuxer.ts]: Failed to generate initSegment.');
return result;
}
if (this.emitInitSegment) {
initSegment.tracks = this.initTracks;
this.emitInitSegment = false;
}
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(initPTS)) {
this.initPTS = initSegment.initPTS = initPTS = computeInitPTS(initData, data, lastEndDTS);
}
var duration = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["getDuration"])(data, initData);
var startDTS = lastEndDTS;
var endDTS = duration + startDTS;
Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["offsetStartDTS"])(initData, data, initPTS);
if (duration > 0) {
this.lastEndDTS = endDTS;
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Duration parsed from mp4 should be greater than zero');
this.resetNextTimestamp();
}
var hasAudio = !!initData.audio;
var hasVideo = !!initData.video;
var type = '';
if (hasAudio) {
type += 'audio';
}
if (hasVideo) {
type += 'video';
}
var track = {
data1: data,
startPTS: startDTS,
startDTS: startDTS,
endPTS: endDTS,
endDTS: endDTS,
type: type,
hasAudio: hasAudio,
hasVideo: hasVideo,
nb: 1,
dropped: 0
};
result.audio = track.type === 'audio' ? track : undefined;
result.video = track.type !== 'audio' ? track : undefined;
result.text = textTrack;
result.id3 = id3Track;
result.initSegment = initSegment;
return result;
};
return PassThroughRemuxer;
}();
var computeInitPTS = function computeInitPTS(initData, data, timeOffset) {
return Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["getStartDTS"])(initData, data) - timeOffset;
};
function getParsedTrackCodec(track, type) {
var parsedCodec = track === null || track === void 0 ? void 0 : track.codec;
if (parsedCodec && parsedCodec.length > 4) {
return parsedCodec;
} // Since mp4-tools cannot parse full codec string (see 'TODO: Parse codec details'... in mp4-tools)
// Provide defaults based on codec type
// This allows for some playback of some fmp4 playlists without CODECS defined in manifest
if (parsedCodec === 'hvc1') {
return 'hvc1.1.c.L120.90';
}
if (parsedCodec === 'av01') {
return 'av01.0.04M.08';
}
if (parsedCodec === 'avc1' || type === _loader_fragment__WEBPACK_IMPORTED_MODULE_2__["ElementaryStreamTypes"].VIDEO) {
return 'avc1.42e01e';
}
return 'mp4a.40.5';
}
/* harmony default export */ __webpack_exports__["default"] = (PassThroughRemuxer);
/***/ }),
/***/ "./src/task-loop.ts":
/*!**************************!*\
!*** ./src/task-loop.ts ***!
\**************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TaskLoop; });
/**
* Sub-class specialization of EventHandler base class.
*
* TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,
* scheduled asynchroneously, avoiding recursive calls in the same tick.
*
* The task itself is implemented in `doTick`. It can be requested and called for single execution
* using the `tick` method.
*
* It will be assured that the task execution method (`tick`) only gets called once per main loop "tick",
* no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.
*
* If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,
* and cancelled with `clearNextTick`.
*
* The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).
*
* Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.
*
* Further explanations:
*
* The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously
* only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.
*
* When the task execution (`tick` method) is called in re-entrant way this is detected and
* we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further
* task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo).
*/
var TaskLoop = /*#__PURE__*/function () {
function TaskLoop() {
this._boundTick = void 0;
this._tickTimer = null;
this._tickInterval = null;
this._tickCallCount = 0;
this._boundTick = this.tick.bind(this);
}
var _proto = TaskLoop.prototype;
_proto.destroy = function destroy() {
this.onHandlerDestroying();
this.onHandlerDestroyed();
};
_proto.onHandlerDestroying = function onHandlerDestroying() {
// clear all timers before unregistering from event bus
this.clearNextTick();
this.clearInterval();
};
_proto.onHandlerDestroyed = function onHandlerDestroyed() {}
/**
* @returns {boolean}
*/
;
_proto.hasInterval = function hasInterval() {
return !!this._tickInterval;
}
/**
* @returns {boolean}
*/
;
_proto.hasNextTick = function hasNextTick() {
return !!this._tickTimer;
}
/**
* @param {number} millis Interval time (ms)
* @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)
*/
;
_proto.setInterval = function setInterval(millis) {
if (!this._tickInterval) {
this._tickInterval = self.setInterval(this._boundTick, millis);
return true;
}
return false;
}
/**
* @returns {boolean} True when interval was cleared, false when none was set (no effect)
*/
;
_proto.clearInterval = function clearInterval() {
if (this._tickInterval) {
self.clearInterval(this._tickInterval);
this._tickInterval = null;
return true;
}
return false;
}
/**
* @returns {boolean} True when timeout was cleared, false when none was set (no effect)
*/
;
_proto.clearNextTick = function clearNextTick() {
if (this._tickTimer) {
self.clearTimeout(this._tickTimer);
this._tickTimer = null;
return true;
}
return false;
}
/**
* Will call the subclass doTick implementation in this main loop tick
* or in the next one (via setTimeout(,0)) in case it has already been called
* in this tick (in case this is a re-entrant call).
*/
;
_proto.tick = function tick() {
this._tickCallCount++;
if (this._tickCallCount === 1) {
this.doTick(); // re-entrant call to tick from previous doTick call stack
// -> schedule a call on the next main loop iteration to process this task processing request
if (this._tickCallCount > 1) {
// make sure only one timer exists at any time at max
this.tickImmediate();
}
this._tickCallCount = 0;
}
};
_proto.tickImmediate = function tickImmediate() {
this.clearNextTick();
this._tickTimer = self.setTimeout(this._boundTick, 0);
}
/**
* For subclass to implement task logic
* @abstract
*/
;
_proto.doTick = function doTick() {};
return TaskLoop;
}();
/***/ }),
/***/ "./src/types/cmcd.ts":
/*!***************************!*\
!*** ./src/types/cmcd.ts ***!
\***************************/
/*! exports provided: CMCDVersion, CMCDObjectType, CMCDStreamingFormat, CMCDStreamType */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CMCDVersion", function() { return CMCDVersion; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CMCDObjectType", function() { return CMCDObjectType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CMCDStreamingFormat", function() { return CMCDStreamingFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CMCDStreamType", function() { return CMCDStreamType; });
/**
* CMCD spec version
*/
var CMCDVersion = 1;
/**
* CMCD Object Type
*/
var CMCDObjectType;
/**
* CMCD Streaming Format
*/
(function (CMCDObjectType) {
CMCDObjectType["MANIFEST"] = "m";
CMCDObjectType["AUDIO"] = "a";
CMCDObjectType["VIDEO"] = "v";
CMCDObjectType["MUXED"] = "av";
CMCDObjectType["INIT"] = "i";
CMCDObjectType["CAPTION"] = "c";
CMCDObjectType["TIMED_TEXT"] = "tt";
CMCDObjectType["KEY"] = "k";
CMCDObjectType["OTHER"] = "o";
})(CMCDObjectType || (CMCDObjectType = {}));
var CMCDStreamingFormat;
/**
* CMCD Streaming Type
*/
(function (CMCDStreamingFormat) {
CMCDStreamingFormat["DASH"] = "d";
CMCDStreamingFormat["HLS"] = "h";
CMCDStreamingFormat["SMOOTH"] = "s";
CMCDStreamingFormat["OTHER"] = "o";
})(CMCDStreamingFormat || (CMCDStreamingFormat = {}));
var CMCDStreamType;
/**
* CMCD Headers
*/
(function (CMCDStreamType) {
CMCDStreamType["VOD"] = "v";
CMCDStreamType["LIVE"] = "l";
})(CMCDStreamType || (CMCDStreamType = {}));
/***/ }),
/***/ "./src/types/level.ts":
/*!****************************!*\
!*** ./src/types/level.ts ***!
\****************************/
/*! exports provided: HlsSkip, getSkipValue, HlsUrlParameters, Level */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HlsSkip", function() { return HlsSkip; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getSkipValue", function() { return getSkipValue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HlsUrlParameters", function() { return HlsUrlParameters; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Level", function() { return Level; });
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); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var HlsSkip;
(function (HlsSkip) {
HlsSkip["No"] = "";
HlsSkip["Yes"] = "YES";
HlsSkip["v2"] = "v2";
})(HlsSkip || (HlsSkip = {}));
function getSkipValue(details, msn) {
var canSkipUntil = details.canSkipUntil,
canSkipDateRanges = details.canSkipDateRanges,
endSN = details.endSN;
var snChangeGoal = msn !== undefined ? msn - endSN : 0;
if (canSkipUntil && snChangeGoal < canSkipUntil) {
if (canSkipDateRanges) {
return HlsSkip.v2;
}
return HlsSkip.Yes;
}
return HlsSkip.No;
}
var HlsUrlParameters = /*#__PURE__*/function () {
function HlsUrlParameters(msn, part, skip) {
this.msn = void 0;
this.part = void 0;
this.skip = void 0;
this.msn = msn;
this.part = part;
this.skip = skip;
}
var _proto = HlsUrlParameters.prototype;
_proto.addDirectives = function addDirectives(uri) {
var url = new self.URL(uri);
if (this.msn !== undefined) {
url.searchParams.set('_HLS_msn', this.msn.toString());
}
if (this.part !== undefined) {
url.searchParams.set('_HLS_part', this.part.toString());
}
if (this.skip) {
url.searchParams.set('_HLS_skip', this.skip);
}
return url.toString();
};
return HlsUrlParameters;
}();
var Level = /*#__PURE__*/function () {
function Level(data) {
this.attrs = void 0;
this.audioCodec = void 0;
this.bitrate = void 0;
this.codecSet = void 0;
this.height = void 0;
this.id = void 0;
this.name = void 0;
this.videoCodec = void 0;
this.width = void 0;
this.unknownCodecs = void 0;
this.audioGroupIds = void 0;
this.details = void 0;
this.fragmentError = 0;
this.loadError = 0;
this.loaded = void 0;
this.realBitrate = 0;
this.textGroupIds = void 0;
this.url = void 0;
this._urlId = 0;
this.url = [data.url];
this.attrs = data.attrs;
this.bitrate = data.bitrate;
if (data.details) {
this.details = data.details;
}
this.id = data.id || 0;
this.name = data.name;
this.width = data.width || 0;
this.height = data.height || 0;
this.audioCodec = data.audioCodec;
this.videoCodec = data.videoCodec;
this.unknownCodecs = data.unknownCodecs;
this.codecSet = [data.videoCodec, data.audioCodec].filter(function (c) {
return c;
}).join(',').replace(/\.[^.,]+/g, '');
}
_createClass(Level, [{
key: "maxBitrate",
get: function get() {
return Math.max(this.realBitrate, this.bitrate);
}
}, {
key: "uri",
get: function get() {
return this.url[this._urlId] || '';
}
}, {
key: "urlId",
get: function get() {
return this._urlId;
},
set: function set(value) {
var newValue = value % this.url.length;
if (this._urlId !== newValue) {
this.details = undefined;
this._urlId = newValue;
}
}
}]);
return Level;
}();
/***/ }),
/***/ "./src/types/loader.ts":
/*!*****************************!*\
!*** ./src/types/loader.ts ***!
\*****************************/
/*! exports provided: PlaylistContextType, PlaylistLevelType */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaylistContextType", function() { return PlaylistContextType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaylistLevelType", function() { return PlaylistLevelType; });
var PlaylistContextType;
(function (PlaylistContextType) {
PlaylistContextType["MANIFEST"] = "manifest";
PlaylistContextType["LEVEL"] = "level";
PlaylistContextType["AUDIO_TRACK"] = "audioTrack";
PlaylistContextType["SUBTITLE_TRACK"] = "subtitleTrack";
})(PlaylistContextType || (PlaylistContextType = {}));
var PlaylistLevelType;
(function (PlaylistLevelType) {
PlaylistLevelType["MAIN"] = "main";
PlaylistLevelType["AUDIO"] = "audio";
PlaylistLevelType["SUBTITLE"] = "subtitle";
})(PlaylistLevelType || (PlaylistLevelType = {}));
/***/ }),
/***/ "./src/types/transmuxer.ts":
/*!*********************************!*\
!*** ./src/types/transmuxer.ts ***!
\*********************************/
/*! exports provided: ChunkMetadata */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ChunkMetadata", function() { return ChunkMetadata; });
var ChunkMetadata = function ChunkMetadata(level, sn, id, size, part, partial) {
if (size === void 0) {
size = 0;
}
if (part === void 0) {
part = -1;
}
if (partial === void 0) {
partial = false;
}
this.level = void 0;
this.sn = void 0;
this.part = void 0;
this.id = void 0;
this.size = void 0;
this.partial = void 0;
this.transmuxing = getNewPerformanceTiming();
this.buffering = {
audio: getNewPerformanceTiming(),
video: getNewPerformanceTiming(),
audiovideo: getNewPerformanceTiming()
};
this.level = level;
this.sn = sn;
this.id = id;
this.size = size;
this.part = part;
this.partial = partial;
};
function getNewPerformanceTiming() {
return {
start: 0,
executeStart: 0,
executeEnd: 0,
end: 0
};
}
/***/ }),
/***/ "./src/utils/attr-list.ts":
/*!********************************!*\
!*** ./src/utils/attr-list.ts ***!
\********************************/
/*! exports provided: AttrList */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AttrList", function() { return AttrList; });
var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/; // eslint-disable-line no-useless-escape
var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape
// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
var AttrList = /*#__PURE__*/function () {
function AttrList(attrs) {
if (typeof attrs === 'string') {
attrs = AttrList.parseAttrList(attrs);
}
for (var attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
this[attr] = attrs[attr];
}
}
}
var _proto = AttrList.prototype;
_proto.decimalInteger = function decimalInteger(attrName) {
var intValue = parseInt(this[attrName], 10);
if (intValue > Number.MAX_SAFE_INTEGER) {
return Infinity;
}
return intValue;
};
_proto.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;
}
};
_proto.hexadecimalIntegerAsNumber = function hexadecimalIntegerAsNumber(attrName) {
var intValue = parseInt(this[attrName], 16);
if (intValue > Number.MAX_SAFE_INTEGER) {
return Infinity;
}
return intValue;
};
_proto.decimalFloatingPoint = function decimalFloatingPoint(attrName) {
return parseFloat(this[attrName]);
};
_proto.optionalFloat = function optionalFloat(attrName, defaultValue) {
var value = this[attrName];
return value ? parseFloat(value) : defaultValue;
};
_proto.enumeratedString = function enumeratedString(attrName) {
return this[attrName];
};
_proto.bool = function bool(attrName) {
return this[attrName] === 'YES';
};
_proto.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;
var attrs = {};
var quote = '"';
ATTR_LIST_REGEX.lastIndex = 0;
while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
var value = match[2];
if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {
value = value.slice(1, -1);
}
attrs[match[1]] = value;
}
return attrs;
};
return AttrList;
}();
/***/ }),
/***/ "./src/utils/binary-search.ts":
/*!************************************!*\
!*** ./src/utils/binary-search.ts ***!
\************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
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<T>} list The array to search.
* @param {BinarySearchComparison<T>} comparisonFn
* 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 {T | null} The object if it is found or null otherwise.
*/
search: function search(list, comparisonFn) {
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 = comparisonFn(currentElement);
if (comparisonResult > 0) {
minIndex = currentIndex + 1;
} else if (comparisonResult < 0) {
maxIndex = currentIndex - 1;
} else {
return currentElement;
}
}
return null;
}
};
/* harmony default export */ __webpack_exports__["default"] = (BinarySearch);
/***/ }),
/***/ "./src/utils/buffer-helper.ts":
/*!************************************!*\
!*** ./src/utils/buffer-helper.ts ***!
\************************************/
/*! exports provided: BufferHelper */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BufferHelper", function() { return BufferHelper; });
/* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./logger */ "./src/utils/logger.ts");
/**
* @module BufferHelper
*
* Providing methods dealing with buffer length retrieval for example.
*
* In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.
*
* Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered
*/
var noopBuffered = {
length: 0,
start: function start() {
return 0;
},
end: function end() {
return 0;
}
};
var BufferHelper = /*#__PURE__*/function () {
function BufferHelper() {}
/**
* Return true if `media`'s buffered include `position`
* @param {Bufferable} media
* @param {number} position
* @returns {boolean}
*/
BufferHelper.isBuffered = function isBuffered(media, position) {
try {
if (media) {
var buffered = BufferHelper.getBuffered(media);
for (var i = 0; i < buffered.length; i++) {
if (position >= buffered.start(i) && position <= buffered.end(i)) {
return true;
}
}
}
} catch (error) {// this is to catch
// InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
// This SourceBuffer has been removed from the parent media source
}
return false;
};
BufferHelper.bufferInfo = function bufferInfo(media, pos, maxHoleDuration) {
try {
if (media) {
var vbuffered = BufferHelper.getBuffered(media);
var buffered = [];
var i;
for (i = 0; i < vbuffered.length; i++) {
buffered.push({
start: vbuffered.start(i),
end: vbuffered.end(i)
});
}
return this.bufferedInfo(buffered, pos, maxHoleDuration);
}
} catch (error) {// this is to catch
// InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
// This SourceBuffer has been removed from the parent media source
}
return {
len: 0,
start: pos,
end: pos,
nextStart: undefined
};
};
BufferHelper.bufferedInfo = function bufferedInfo(buffered, pos, maxHoleDuration) {
pos = Math.max(0, pos); // 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;
}
});
var buffered2 = [];
if (maxHoleDuration) {
// 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 (var 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]);
}
}
} else {
buffered2 = buffered;
}
var bufferLen = 0; // bufferStartNext can possibly be undefined based on the conditional logic below
var bufferStartNext; // bufferStart and bufferEnd are buffer boundaries around current video position
var bufferStart = pos;
var bufferEnd = pos;
for (var _i = 0; _i < buffered2.length; _i++) {
var start = buffered2[_i].start;
var 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 || 0,
end: bufferEnd || 0,
nextStart: bufferStartNext
};
}
/**
* Safe method to get buffered property.
* SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
*/
;
BufferHelper.getBuffered = function getBuffered(media) {
try {
return media.buffered;
} catch (e) {
_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log('failed to get media.buffered', e);
return noopBuffered;
}
};
return BufferHelper;
}();
/***/ }),
/***/ "./src/utils/cea-608-parser.ts":
/*!*************************************!*\
!*** ./src/utils/cea-608-parser.ts ***!
\*************************************/
/*! exports provided: Row, CaptionScreen, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Row", function() { return Row; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CaptionScreen", function() { return CaptionScreen; });
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/**
*
* This code was ported from the dash.js project at:
* https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js
* https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2
*
* The original copyright appears below:
*
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2015-2016, DASH Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * 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.
* 2. Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes
*/
var specialCea608CharsCodes = {
0x2a: 0xe1,
// lowercase a, acute accent
0x5c: 0xe9,
// lowercase e, acute accent
0x5e: 0xed,
// lowercase i, acute accent
0x5f: 0xf3,
// lowercase o, acute accent
0x60: 0xfa,
// lowercase u, acute accent
0x7b: 0xe7,
// lowercase c with cedilla
0x7c: 0xf7,
// division symbol
0x7d: 0xd1,
// uppercase N tilde
0x7e: 0xf1,
// lowercase n tilde
0x7f: 0x2588,
// Full block
// THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
// THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
// THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
0x80: 0xae,
// Registered symbol (R)
0x81: 0xb0,
// degree sign
0x82: 0xbd,
// 1/2 symbol
0x83: 0xbf,
// Inverted (open) question mark
0x84: 0x2122,
// Trademark symbol (TM)
0x85: 0xa2,
// Cents symbol
0x86: 0xa3,
// Pounds sterling
0x87: 0x266a,
// Music 8'th note
0x88: 0xe0,
// lowercase a, grave accent
0x89: 0x20,
// transparent space (regular)
0x8a: 0xe8,
// lowercase e, grave accent
0x8b: 0xe2,
// lowercase a, circumflex accent
0x8c: 0xea,
// lowercase e, circumflex accent
0x8d: 0xee,
// lowercase i, circumflex accent
0x8e: 0xf4,
// lowercase o, circumflex accent
0x8f: 0xfb,
// lowercase u, circumflex accent
// THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
// THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
0x90: 0xc1,
// capital letter A with acute
0x91: 0xc9,
// capital letter E with acute
0x92: 0xd3,
// capital letter O with acute
0x93: 0xda,
// capital letter U with acute
0x94: 0xdc,
// capital letter U with diaresis
0x95: 0xfc,
// lowercase letter U with diaeresis
0x96: 0x2018,
// opening single quote
0x97: 0xa1,
// inverted exclamation mark
0x98: 0x2a,
// asterisk
0x99: 0x2019,
// closing single quote
0x9a: 0x2501,
// box drawings heavy horizontal
0x9b: 0xa9,
// copyright sign
0x9c: 0x2120,
// Service mark
0x9d: 0x2022,
// (round) bullet
0x9e: 0x201c,
// Left double quotation mark
0x9f: 0x201d,
// Right double quotation mark
0xa0: 0xc0,
// uppercase A, grave accent
0xa1: 0xc2,
// uppercase A, circumflex
0xa2: 0xc7,
// uppercase C with cedilla
0xa3: 0xc8,
// uppercase E, grave accent
0xa4: 0xca,
// uppercase E, circumflex
0xa5: 0xcb,
// capital letter E with diaresis
0xa6: 0xeb,
// lowercase letter e with diaresis
0xa7: 0xce,
// uppercase I, circumflex
0xa8: 0xcf,
// uppercase I, with diaresis
0xa9: 0xef,
// lowercase i, with diaresis
0xaa: 0xd4,
// uppercase O, circumflex
0xab: 0xd9,
// uppercase U, grave accent
0xac: 0xf9,
// lowercase u, grave accent
0xad: 0xdb,
// uppercase U, circumflex
0xae: 0xab,
// left-pointing double angle quotation mark
0xaf: 0xbb,
// right-pointing double angle quotation mark
// THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
// THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
0xb0: 0xc3,
// Uppercase A, tilde
0xb1: 0xe3,
// Lowercase a, tilde
0xb2: 0xcd,
// Uppercase I, acute accent
0xb3: 0xcc,
// Uppercase I, grave accent
0xb4: 0xec,
// Lowercase i, grave accent
0xb5: 0xd2,
// Uppercase O, grave accent
0xb6: 0xf2,
// Lowercase o, grave accent
0xb7: 0xd5,
// Uppercase O, tilde
0xb8: 0xf5,
// Lowercase o, tilde
0xb9: 0x7b,
// Open curly brace
0xba: 0x7d,
// Closing curly brace
0xbb: 0x5c,
// Backslash
0xbc: 0x5e,
// Caret
0xbd: 0x5f,
// Underscore
0xbe: 0x7c,
// Pipe (vertical line)
0xbf: 0x223c,
// Tilde operator
0xc0: 0xc4,
// Uppercase A, umlaut
0xc1: 0xe4,
// Lowercase A, umlaut
0xc2: 0xd6,
// Uppercase O, umlaut
0xc3: 0xf6,
// Lowercase o, umlaut
0xc4: 0xdf,
// Esszett (sharp S)
0xc5: 0xa5,
// Yen symbol
0xc6: 0xa4,
// Generic currency sign
0xc7: 0x2503,
// Box drawings heavy vertical
0xc8: 0xc5,
// Uppercase A, ring
0xc9: 0xe5,
// Lowercase A, ring
0xca: 0xd8,
// Uppercase O, stroke
0xcb: 0xf8,
// Lowercase o, strok
0xcc: 0x250f,
// Box drawings heavy down and right
0xcd: 0x2513,
// Box drawings heavy down and left
0xce: 0x2517,
// Box drawings heavy up and right
0xcf: 0x251b // Box drawings heavy up and left
};
/**
* Utils
*/
var getCharForByte = function getCharForByte(_byte) {
var charCode = _byte;
if (specialCea608CharsCodes.hasOwnProperty(_byte)) {
charCode = specialCea608CharsCodes[_byte];
}
return String.fromCharCode(charCode);
};
var NR_ROWS = 15;
var NR_COLS = 100; // Tables to look up row from PAC data
var rowsLowCh1 = {
0x11: 1,
0x12: 3,
0x15: 5,
0x16: 7,
0x17: 9,
0x10: 11,
0x13: 12,
0x14: 14
};
var rowsHighCh1 = {
0x11: 2,
0x12: 4,
0x15: 6,
0x16: 8,
0x17: 10,
0x13: 13,
0x14: 15
};
var rowsLowCh2 = {
0x19: 1,
0x1a: 3,
0x1d: 5,
0x1e: 7,
0x1f: 9,
0x18: 11,
0x1b: 12,
0x1c: 14
};
var rowsHighCh2 = {
0x19: 2,
0x1a: 4,
0x1d: 6,
0x1e: 8,
0x1f: 10,
0x1b: 13,
0x1c: 15
};
var backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];
var VerboseLevel;
(function (VerboseLevel) {
VerboseLevel[VerboseLevel["ERROR"] = 0] = "ERROR";
VerboseLevel[VerboseLevel["TEXT"] = 1] = "TEXT";
VerboseLevel[VerboseLevel["WARNING"] = 2] = "WARNING";
VerboseLevel[VerboseLevel["INFO"] = 2] = "INFO";
VerboseLevel[VerboseLevel["DEBUG"] = 3] = "DEBUG";
VerboseLevel[VerboseLevel["DATA"] = 3] = "DATA";
})(VerboseLevel || (VerboseLevel = {}));
var CaptionsLogger = /*#__PURE__*/function () {
function CaptionsLogger() {
this.time = null;
this.verboseLevel = VerboseLevel.ERROR;
}
var _proto = CaptionsLogger.prototype;
_proto.log = function log(severity, msg) {
if (this.verboseLevel >= severity) {
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log(this.time + " [" + severity + "] " + msg);
}
};
return CaptionsLogger;
}();
var numArrayToHexArray = function numArrayToHexArray(numArray) {
var hexArray = [];
for (var j = 0; j < numArray.length; j++) {
hexArray.push(numArray[j].toString(16));
}
return hexArray;
};
var PenState = /*#__PURE__*/function () {
function PenState(foreground, underline, italics, background, flash) {
this.foreground = void 0;
this.underline = void 0;
this.italics = void 0;
this.background = void 0;
this.flash = void 0;
this.foreground = foreground || 'white';
this.underline = underline || false;
this.italics = italics || false;
this.background = background || 'black';
this.flash = flash || false;
}
var _proto2 = PenState.prototype;
_proto2.reset = function reset() {
this.foreground = 'white';
this.underline = false;
this.italics = false;
this.background = 'black';
this.flash = false;
};
_proto2.setStyles = function setStyles(styles) {
var attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];
for (var i = 0; i < attribs.length; i++) {
var style = attribs[i];
if (styles.hasOwnProperty(style)) {
this[style] = styles[style];
}
}
};
_proto2.isDefault = function isDefault() {
return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash;
};
_proto2.equals = function equals(other) {
return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
};
_proto2.copy = function copy(newPenState) {
this.foreground = newPenState.foreground;
this.underline = newPenState.underline;
this.italics = newPenState.italics;
this.background = newPenState.background;
this.flash = newPenState.flash;
};
_proto2.toString = function toString() {
return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash;
};
return PenState;
}();
/**
* Unicode character with styling and background.
* @constructor
*/
var StyledUnicodeChar = /*#__PURE__*/function () {
function StyledUnicodeChar(uchar, foreground, underline, italics, background, flash) {
this.uchar = void 0;
this.penState = void 0;
this.uchar = uchar || ' '; // unicode character
this.penState = new PenState(foreground, underline, italics, background, flash);
}
var _proto3 = StyledUnicodeChar.prototype;
_proto3.reset = function reset() {
this.uchar = ' ';
this.penState.reset();
};
_proto3.setChar = function setChar(uchar, newPenState) {
this.uchar = uchar;
this.penState.copy(newPenState);
};
_proto3.setPenState = function setPenState(newPenState) {
this.penState.copy(newPenState);
};
_proto3.equals = function equals(other) {
return this.uchar === other.uchar && this.penState.equals(other.penState);
};
_proto3.copy = function copy(newChar) {
this.uchar = newChar.uchar;
this.penState.copy(newChar.penState);
};
_proto3.isEmpty = function isEmpty() {
return this.uchar === ' ' && this.penState.isDefault();
};
return StyledUnicodeChar;
}();
/**
* CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.
* @constructor
*/
var Row = /*#__PURE__*/function () {
function Row(logger) {
this.chars = void 0;
this.pos = void 0;
this.currPenState = void 0;
this.cueStartTime = void 0;
this.logger = void 0;
this.chars = [];
for (var i = 0; i < NR_COLS; i++) {
this.chars.push(new StyledUnicodeChar());
}
this.logger = logger;
this.pos = 0;
this.currPenState = new PenState();
}
var _proto4 = Row.prototype;
_proto4.equals = function equals(other) {
var equal = true;
for (var i = 0; i < NR_COLS; i++) {
if (!this.chars[i].equals(other.chars[i])) {
equal = false;
break;
}
}
return equal;
};
_proto4.copy = function copy(other) {
for (var i = 0; i < NR_COLS; i++) {
this.chars[i].copy(other.chars[i]);
}
};
_proto4.isEmpty = function isEmpty() {
var empty = true;
for (var i = 0; i < NR_COLS; i++) {
if (!this.chars[i].isEmpty()) {
empty = false;
break;
}
}
return empty;
}
/**
* Set the cursor to a valid column.
*/
;
_proto4.setCursor = function setCursor(absPos) {
if (this.pos !== absPos) {
this.pos = absPos;
}
if (this.pos < 0) {
this.logger.log(VerboseLevel.DEBUG, 'Negative cursor position ' + this.pos);
this.pos = 0;
} else if (this.pos > NR_COLS) {
this.logger.log(VerboseLevel.DEBUG, 'Too large cursor position ' + this.pos);
this.pos = NR_COLS;
}
}
/**
* Move the cursor relative to current position.
*/
;
_proto4.moveCursor = function moveCursor(relPos) {
var newPos = this.pos + relPos;
if (relPos > 1) {
for (var i = this.pos + 1; i < newPos + 1; i++) {
this.chars[i].setPenState(this.currPenState);
}
}
this.setCursor(newPos);
}
/**
* Backspace, move one step back and clear character.
*/
;
_proto4.backSpace = function backSpace() {
this.moveCursor(-1);
this.chars[this.pos].setChar(' ', this.currPenState);
};
_proto4.insertChar = function insertChar(_byte2) {
if (_byte2 >= 0x90) {
// Extended char
this.backSpace();
}
var _char = getCharForByte(_byte2);
if (this.pos >= NR_COLS) {
this.logger.log(VerboseLevel.ERROR, 'Cannot insert ' + _byte2.toString(16) + ' (' + _char + ') at position ' + this.pos + '. Skipping it!');
return;
}
this.chars[this.pos].setChar(_char, this.currPenState);
this.moveCursor(1);
};
_proto4.clearFromPos = function clearFromPos(startPos) {
var i;
for (i = startPos; i < NR_COLS; i++) {
this.chars[i].reset();
}
};
_proto4.clear = function clear() {
this.clearFromPos(0);
this.pos = 0;
this.currPenState.reset();
};
_proto4.clearToEndOfRow = function clearToEndOfRow() {
this.clearFromPos(this.pos);
};
_proto4.getTextString = function getTextString() {
var chars = [];
var empty = true;
for (var i = 0; i < NR_COLS; i++) {
var _char2 = this.chars[i].uchar;
if (_char2 !== ' ') {
empty = false;
}
chars.push(_char2);
}
if (empty) {
return '';
} else {
return chars.join('');
}
};
_proto4.setPenStyles = function setPenStyles(styles) {
this.currPenState.setStyles(styles);
var currChar = this.chars[this.pos];
currChar.setPenState(this.currPenState);
};
return Row;
}();
/**
* Keep a CEA-608 screen of 32x15 styled characters
* @constructor
*/
var CaptionScreen = /*#__PURE__*/function () {
function CaptionScreen(logger) {
this.rows = void 0;
this.currRow = void 0;
this.nrRollUpRows = void 0;
this.lastOutputScreen = void 0;
this.logger = void 0;
this.rows = [];
for (var i = 0; i < NR_ROWS; i++) {
this.rows.push(new Row(logger));
} // Note that we use zero-based numbering (0-14)
this.logger = logger;
this.currRow = NR_ROWS - 1;
this.nrRollUpRows = null;
this.lastOutputScreen = null;
this.reset();
}
var _proto5 = CaptionScreen.prototype;
_proto5.reset = function reset() {
for (var i = 0; i < NR_ROWS; i++) {
this.rows[i].clear();
}
this.currRow = NR_ROWS - 1;
};
_proto5.equals = function equals(other) {
var equal = true;
for (var i = 0; i < NR_ROWS; i++) {
if (!this.rows[i].equals(other.rows[i])) {
equal = false;
break;
}
}
return equal;
};
_proto5.copy = function copy(other) {
for (var i = 0; i < NR_ROWS; i++) {
this.rows[i].copy(other.rows[i]);
}
};
_proto5.isEmpty = function isEmpty() {
var empty = true;
for (var i = 0; i < NR_ROWS; i++) {
if (!this.rows[i].isEmpty()) {
empty = false;
break;
}
}
return empty;
};
_proto5.backSpace = function backSpace() {
var row = this.rows[this.currRow];
row.backSpace();
};
_proto5.clearToEndOfRow = function clearToEndOfRow() {
var row = this.rows[this.currRow];
row.clearToEndOfRow();
}
/**
* Insert a character (without styling) in the current row.
*/
;
_proto5.insertChar = function insertChar(_char3) {
var row = this.rows[this.currRow];
row.insertChar(_char3);
};
_proto5.setPen = function setPen(styles) {
var row = this.rows[this.currRow];
row.setPenStyles(styles);
};
_proto5.moveCursor = function moveCursor(relPos) {
var row = this.rows[this.currRow];
row.moveCursor(relPos);
};
_proto5.setCursor = function setCursor(absPos) {
this.logger.log(VerboseLevel.INFO, 'setCursor: ' + absPos);
var row = this.rows[this.currRow];
row.setCursor(absPos);
};
_proto5.setPAC = function setPAC(pacData) {
this.logger.log(VerboseLevel.INFO, 'pacData = ' + JSON.stringify(pacData));
var newRow = pacData.row - 1;
if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
newRow = this.nrRollUpRows - 1;
} // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows
if (this.nrRollUpRows && this.currRow !== newRow) {
// clear all rows first
for (var i = 0; i < NR_ROWS; i++) {
this.rows[i].clear();
} // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location
// topRowIndex - the start of rows to copy (inclusive index)
var topRowIndex = this.currRow + 1 - this.nrRollUpRows; // We only copy if the last position was already shown.
// We use the cueStartTime value to check this.
var lastOutputScreen = this.lastOutputScreen;
if (lastOutputScreen) {
var prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;
var time = this.logger.time;
if (prevLineTime && time !== null && prevLineTime < time) {
for (var _i = 0; _i < this.nrRollUpRows; _i++) {
this.rows[newRow - this.nrRollUpRows + _i + 1].copy(lastOutputScreen.rows[topRowIndex + _i]);
}
}
}
}
this.currRow = newRow;
var row = this.rows[this.currRow];
if (pacData.indent !== null) {
var indent = pacData.indent;
var prevPos = Math.max(indent - 1, 0);
row.setCursor(pacData.indent);
pacData.color = row.chars[prevPos].penState.foreground;
}
var styles = {
foreground: pacData.color,
underline: pacData.underline,
italics: pacData.italics,
background: 'black',
flash: false
};
this.setPen(styles);
}
/**
* Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
*/
;
_proto5.setBkgData = function setBkgData(bkgData) {
this.logger.log(VerboseLevel.INFO, 'bkgData = ' + JSON.stringify(bkgData));
this.backSpace();
this.setPen(bkgData);
this.insertChar(0x20); // Space
};
_proto5.setRollUpRows = function setRollUpRows(nrRows) {
this.nrRollUpRows = nrRows;
};
_proto5.rollUp = function rollUp() {
if (this.nrRollUpRows === null) {
this.logger.log(VerboseLevel.DEBUG, 'roll_up but nrRollUpRows not set yet');
return; // Not properly setup
}
this.logger.log(VerboseLevel.TEXT, this.getDisplayText());
var topRowIndex = this.currRow + 1 - this.nrRollUpRows;
var topRow = this.rows.splice(topRowIndex, 1)[0];
topRow.clear();
this.rows.splice(this.currRow, 0, topRow);
this.logger.log(VerboseLevel.INFO, 'Rolling up'); // this.logger.log(VerboseLevel.TEXT, this.get_display_text())
}
/**
* Get all non-empty rows with as unicode text.
*/
;
_proto5.getDisplayText = function getDisplayText(asOneRow) {
asOneRow = asOneRow || false;
var displayText = [];
var text = '';
var rowNr = -1;
for (var i = 0; i < NR_ROWS; i++) {
var rowText = this.rows[i].getTextString();
if (rowText) {
rowNr = i + 1;
if (asOneRow) {
displayText.push('Row ' + rowNr + ": '" + rowText + "'");
} else {
displayText.push(rowText.trim());
}
}
}
if (displayText.length > 0) {
if (asOneRow) {
text = '[' + displayText.join(' | ') + ']';
} else {
text = displayText.join('\n');
}
}
return text;
};
_proto5.getTextAndFormat = function getTextAndFormat() {
return this.rows;
};
return CaptionScreen;
}(); // var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];
var Cea608Channel = /*#__PURE__*/function () {
function Cea608Channel(channelNumber, outputFilter, logger) {
this.chNr = void 0;
this.outputFilter = void 0;
this.mode = void 0;
this.verbose = void 0;
this.displayedMemory = void 0;
this.nonDisplayedMemory = void 0;
this.lastOutputScreen = void 0;
this.currRollUpRow = void 0;
this.writeScreen = void 0;
this.cueStartTime = void 0;
this.logger = void 0;
this.chNr = channelNumber;
this.outputFilter = outputFilter;
this.mode = null;
this.verbose = 0;
this.displayedMemory = new CaptionScreen(logger);
this.nonDisplayedMemory = new CaptionScreen(logger);
this.lastOutputScreen = new CaptionScreen(logger);
this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
this.writeScreen = this.displayedMemory;
this.mode = null;
this.cueStartTime = null; // Keeps track of where a cue started.
this.logger = logger;
}
var _proto6 = Cea608Channel.prototype;
_proto6.reset = function reset() {
this.mode = null;
this.displayedMemory.reset();
this.nonDisplayedMemory.reset();
this.lastOutputScreen.reset();
this.outputFilter.reset();
this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
this.writeScreen = this.displayedMemory;
this.mode = null;
this.cueStartTime = null;
};
_proto6.getHandler = function getHandler() {
return this.outputFilter;
};
_proto6.setHandler = function setHandler(newHandler) {
this.outputFilter = newHandler;
};
_proto6.setPAC = function setPAC(pacData) {
this.writeScreen.setPAC(pacData);
};
_proto6.setBkgData = function setBkgData(bkgData) {
this.writeScreen.setBkgData(bkgData);
};
_proto6.setMode = function setMode(newMode) {
if (newMode === this.mode) {
return;
}
this.mode = newMode;
this.logger.log(VerboseLevel.INFO, 'MODE=' + newMode);
if (this.mode === 'MODE_POP-ON') {
this.writeScreen = this.nonDisplayedMemory;
} else {
this.writeScreen = this.displayedMemory;
this.writeScreen.reset();
}
if (this.mode !== 'MODE_ROLL-UP') {
this.displayedMemory.nrRollUpRows = null;
this.nonDisplayedMemory.nrRollUpRows = null;
}
this.mode = newMode;
};
_proto6.insertChars = function insertChars(chars) {
for (var i = 0; i < chars.length; i++) {
this.writeScreen.insertChar(chars[i]);
}
var screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';
this.logger.log(VerboseLevel.INFO, screen + ': ' + this.writeScreen.getDisplayText(true));
if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {
this.logger.log(VerboseLevel.TEXT, 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));
this.outputDataUpdate();
}
};
_proto6.ccRCL = function ccRCL() {
// Resume Caption Loading (switch mode to Pop On)
this.logger.log(VerboseLevel.INFO, 'RCL - Resume Caption Loading');
this.setMode('MODE_POP-ON');
};
_proto6.ccBS = function ccBS() {
// BackSpace
this.logger.log(VerboseLevel.INFO, 'BS - BackSpace');
if (this.mode === 'MODE_TEXT') {
return;
}
this.writeScreen.backSpace();
if (this.writeScreen === this.displayedMemory) {
this.outputDataUpdate();
}
};
_proto6.ccAOF = function ccAOF() {// Reserved (formerly Alarm Off)
};
_proto6.ccAON = function ccAON() {// Reserved (formerly Alarm On)
};
_proto6.ccDER = function ccDER() {
// Delete to End of Row
this.logger.log(VerboseLevel.INFO, 'DER- Delete to End of Row');
this.writeScreen.clearToEndOfRow();
this.outputDataUpdate();
};
_proto6.ccRU = function ccRU(nrRows) {
// Roll-Up Captions-2,3,or 4 Rows
this.logger.log(VerboseLevel.INFO, 'RU(' + nrRows + ') - Roll Up');
this.writeScreen = this.displayedMemory;
this.setMode('MODE_ROLL-UP');
this.writeScreen.setRollUpRows(nrRows);
};
_proto6.ccFON = function ccFON() {
// Flash On
this.logger.log(VerboseLevel.INFO, 'FON - Flash On');
this.writeScreen.setPen({
flash: true
});
};
_proto6.ccRDC = function ccRDC() {
// Resume Direct Captioning (switch mode to PaintOn)
this.logger.log(VerboseLevel.INFO, 'RDC - Resume Direct Captioning');
this.setMode('MODE_PAINT-ON');
};
_proto6.ccTR = function ccTR() {
// Text Restart in text mode (not supported, however)
this.logger.log(VerboseLevel.INFO, 'TR');
this.setMode('MODE_TEXT');
};
_proto6.ccRTD = function ccRTD() {
// Resume Text Display in Text mode (not supported, however)
this.logger.log(VerboseLevel.INFO, 'RTD');
this.setMode('MODE_TEXT');
};
_proto6.ccEDM = function ccEDM() {
// Erase Displayed Memory
this.logger.log(VerboseLevel.INFO, 'EDM - Erase Displayed Memory');
this.displayedMemory.reset();
this.outputDataUpdate(true);
};
_proto6.ccCR = function ccCR() {
// Carriage Return
this.logger.log(VerboseLevel.INFO, 'CR - Carriage Return');
this.writeScreen.rollUp();
this.outputDataUpdate(true);
};
_proto6.ccENM = function ccENM() {
// Erase Non-Displayed Memory
this.logger.log(VerboseLevel.INFO, 'ENM - Erase Non-displayed Memory');
this.nonDisplayedMemory.reset();
};
_proto6.ccEOC = function ccEOC() {
// End of Caption (Flip Memories)
this.logger.log(VerboseLevel.INFO, 'EOC - End Of Caption');
if (this.mode === 'MODE_POP-ON') {
var tmp = this.displayedMemory;
this.displayedMemory = this.nonDisplayedMemory;
this.nonDisplayedMemory = tmp;
this.writeScreen = this.nonDisplayedMemory;
this.logger.log(VerboseLevel.TEXT, 'DISP: ' + this.displayedMemory.getDisplayText());
}
this.outputDataUpdate(true);
};
_proto6.ccTO = function ccTO(nrCols) {
// Tab Offset 1,2, or 3 columns
this.logger.log(VerboseLevel.INFO, 'TO(' + nrCols + ') - Tab Offset');
this.writeScreen.moveCursor(nrCols);
};
_proto6.ccMIDROW = function ccMIDROW(secondByte) {
// Parse MIDROW command
var styles = {
flash: false
};
styles.underline = secondByte % 2 === 1;
styles.italics = secondByte >= 0x2e;
if (!styles.italics) {
var colorIndex = Math.floor(secondByte / 2) - 0x10;
var colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];
styles.foreground = colors[colorIndex];
} else {
styles.foreground = 'white';
}
this.logger.log(VerboseLevel.INFO, 'MIDROW: ' + JSON.stringify(styles));
this.writeScreen.setPen(styles);
};
_proto6.outputDataUpdate = function outputDataUpdate(dispatch) {
if (dispatch === void 0) {
dispatch = false;
}
var time = this.logger.time;
if (time === null) {
return;
}
if (this.outputFilter) {
if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
// Start of a new cue
this.cueStartTime = time;
} else {
if (!this.displayedMemory.equals(this.lastOutputScreen)) {
this.outputFilter.newCue(this.cueStartTime, time, this.lastOutputScreen);
if (dispatch && this.outputFilter.dispatchCue) {
this.outputFilter.dispatchCue();
}
this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;
}
}
this.lastOutputScreen.copy(this.displayedMemory);
}
};
_proto6.cueSplitAtTime = function cueSplitAtTime(t) {
if (this.outputFilter) {
if (!this.displayedMemory.isEmpty()) {
if (this.outputFilter.newCue) {
this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);
}
this.cueStartTime = t;
}
}
};
return Cea608Channel;
}();
var Cea608Parser = /*#__PURE__*/function () {
function Cea608Parser(field, out1, out2) {
this.channels = void 0;
this.currentChannel = 0;
this.cmdHistory = void 0;
this.logger = void 0;
var logger = new CaptionsLogger();
this.channels = [null, new Cea608Channel(field, out1, logger), new Cea608Channel(field + 1, out2, logger)];
this.cmdHistory = createCmdHistory();
this.logger = logger;
}
var _proto7 = Cea608Parser.prototype;
_proto7.getHandler = function getHandler(channel) {
return this.channels[channel].getHandler();
};
_proto7.setHandler = function setHandler(channel, newHandler) {
this.channels[channel].setHandler(newHandler);
}
/**
* Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
*/
;
_proto7.addData = function addData(time, byteList) {
var cmdFound;
var a;
var b;
var charsFound = false;
this.logger.time = time;
for (var i = 0; i < byteList.length; i += 2) {
a = byteList[i] & 0x7f;
b = byteList[i + 1] & 0x7f;
if (a === 0 && b === 0) {
continue;
} else {
this.logger.log(VerboseLevel.DATA, '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')');
}
cmdFound = this.parseCmd(a, b);
if (!cmdFound) {
cmdFound = this.parseMidrow(a, b);
}
if (!cmdFound) {
cmdFound = this.parsePAC(a, b);
}
if (!cmdFound) {
cmdFound = this.parseBackgroundAttributes(a, b);
}
if (!cmdFound) {
charsFound = this.parseChars(a, b);
if (charsFound) {
var currChNr = this.currentChannel;
if (currChNr && currChNr > 0) {
var channel = this.channels[currChNr];
channel.insertChars(charsFound);
} else {
this.logger.log(VerboseLevel.WARNING, 'No channel found yet. TEXT-MODE?');
}
}
}
if (!cmdFound && !charsFound) {
this.logger.log(VerboseLevel.WARNING, "Couldn't parse cleaned data " + numArrayToHexArray([a, b]) + ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]]));
}
}
}
/**
* Parse Command.
* @returns {Boolean} Tells if a command was found
*/
;
_proto7.parseCmd = function parseCmd(a, b) {
var cmdHistory = this.cmdHistory;
var cond1 = (a === 0x14 || a === 0x1c || a === 0x15 || a === 0x1d) && b >= 0x20 && b <= 0x2f;
var cond2 = (a === 0x17 || a === 0x1f) && b >= 0x21 && b <= 0x23;
if (!(cond1 || cond2)) {
return false;
}
if (hasCmdRepeated(a, b, cmdHistory)) {
setLastCmd(null, null, cmdHistory);
this.logger.log(VerboseLevel.DEBUG, 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');
return true;
}
var chNr = a === 0x14 || a === 0x15 || a === 0x17 ? 1 : 2;
var channel = this.channels[chNr];
if (a === 0x14 || a === 0x15 || a === 0x1c || a === 0x1d) {
if (b === 0x20) {
channel.ccRCL();
} else if (b === 0x21) {
channel.ccBS();
} else if (b === 0x22) {
channel.ccAOF();
} else if (b === 0x23) {
channel.ccAON();
} else if (b === 0x24) {
channel.ccDER();
} else if (b === 0x25) {
channel.ccRU(2);
} else if (b === 0x26) {
channel.ccRU(3);
} else if (b === 0x27) {
channel.ccRU(4);
} else if (b === 0x28) {
channel.ccFON();
} else if (b === 0x29) {
channel.ccRDC();
} else if (b === 0x2a) {
channel.ccTR();
} else if (b === 0x2b) {
channel.ccRTD();
} else if (b === 0x2c) {
channel.ccEDM();
} else if (b === 0x2d) {
channel.ccCR();
} else if (b === 0x2e) {
channel.ccENM();
} else if (b === 0x2f) {
channel.ccEOC();
}
} else {
// a == 0x17 || a == 0x1F
channel.ccTO(b - 0x20);
}
setLastCmd(a, b, cmdHistory);
this.currentChannel = chNr;
return true;
}
/**
* Parse midrow styling command
* @returns {Boolean}
*/
;
_proto7.parseMidrow = function parseMidrow(a, b) {
var chNr = 0;
if ((a === 0x11 || a === 0x19) && b >= 0x20 && b <= 0x2f) {
if (a === 0x11) {
chNr = 1;
} else {
chNr = 2;
}
if (chNr !== this.currentChannel) {
this.logger.log(VerboseLevel.ERROR, 'Mismatch channel in midrow parsing');
return false;
}
var channel = this.channels[chNr];
if (!channel) {
return false;
}
channel.ccMIDROW(b);
this.logger.log(VerboseLevel.DEBUG, 'MIDROW (' + numArrayToHexArray([a, b]) + ')');
return true;
}
return false;
}
/**
* Parse Preable Access Codes (Table 53).
* @returns {Boolean} Tells if PAC found
*/
;
_proto7.parsePAC = function parsePAC(a, b) {
var row;
var cmdHistory = this.cmdHistory;
var case1 = (a >= 0x11 && a <= 0x17 || a >= 0x19 && a <= 0x1f) && b >= 0x40 && b <= 0x7f;
var case2 = (a === 0x10 || a === 0x18) && b >= 0x40 && b <= 0x5f;
if (!(case1 || case2)) {
return false;
}
if (hasCmdRepeated(a, b, cmdHistory)) {
setLastCmd(null, null, cmdHistory);
return true; // Repeated commands are dropped (once)
}
var chNr = a <= 0x17 ? 1 : 2;
if (b >= 0x40 && b <= 0x5f) {
row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];
} else {
// 0x60 <= b <= 0x7F
row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];
}
var channel = this.channels[chNr];
if (!channel) {
return false;
}
channel.setPAC(this.interpretPAC(row, b));
setLastCmd(a, b, cmdHistory);
this.currentChannel = chNr;
return true;
}
/**
* Interpret the second byte of the pac, and return the information.
* @returns {Object} pacData with style parameters.
*/
;
_proto7.interpretPAC = function interpretPAC(row, _byte3) {
var pacIndex;
var pacData = {
color: null,
italics: false,
indent: null,
underline: false,
row: row
};
if (_byte3 > 0x5f) {
pacIndex = _byte3 - 0x60;
} else {
pacIndex = _byte3 - 0x40;
}
pacData.underline = (pacIndex & 1) === 1;
if (pacIndex <= 0xd) {
pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)];
} else if (pacIndex <= 0xf) {
pacData.italics = true;
pacData.color = 'white';
} else {
pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4;
}
return pacData; // Note that row has zero offset. The spec uses 1.
}
/**
* Parse characters.
* @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
*/
;
_proto7.parseChars = function parseChars(a, b) {
var channelNr;
var charCodes = null;
var charCode1 = null;
if (a >= 0x19) {
channelNr = 2;
charCode1 = a - 8;
} else {
channelNr = 1;
charCode1 = a;
}
if (charCode1 >= 0x11 && charCode1 <= 0x13) {
// Special character
var oneCode;
if (charCode1 === 0x11) {
oneCode = b + 0x50;
} else if (charCode1 === 0x12) {
oneCode = b + 0x70;
} else {
oneCode = b + 0x90;
}
this.logger.log(VerboseLevel.INFO, "Special char '" + getCharForByte(oneCode) + "' in channel " + channelNr);
charCodes = [oneCode];
} else if (a >= 0x20 && a <= 0x7f) {
charCodes = b === 0 ? [a] : [a, b];
}
if (charCodes) {
var hexCodes = numArrayToHexArray(charCodes);
this.logger.log(VerboseLevel.DEBUG, 'Char codes = ' + hexCodes.join(','));
setLastCmd(a, b, this.cmdHistory);
}
return charCodes;
}
/**
* Parse extended background attributes as well as new foreground color black.
* @returns {Boolean} Tells if background attributes are found
*/
;
_proto7.parseBackgroundAttributes = function parseBackgroundAttributes(a, b) {
var case1 = (a === 0x10 || a === 0x18) && b >= 0x20 && b <= 0x2f;
var case2 = (a === 0x17 || a === 0x1f) && b >= 0x2d && b <= 0x2f;
if (!(case1 || case2)) {
return false;
}
var index;
var bkgData = {};
if (a === 0x10 || a === 0x18) {
index = Math.floor((b - 0x20) / 2);
bkgData.background = backgroundColors[index];
if (b % 2 === 1) {
bkgData.background = bkgData.background + '_semi';
}
} else if (b === 0x2d) {
bkgData.background = 'transparent';
} else {
bkgData.foreground = 'black';
if (b === 0x2f) {
bkgData.underline = true;
}
}
var chNr = a <= 0x17 ? 1 : 2;
var channel = this.channels[chNr];
channel.setBkgData(bkgData);
setLastCmd(a, b, this.cmdHistory);
return true;
}
/**
* Reset state of parser and its channels.
*/
;
_proto7.reset = function reset() {
for (var i = 0; i < Object.keys(this.channels).length; i++) {
var channel = this.channels[i];
if (channel) {
channel.reset();
}
}
this.cmdHistory = createCmdHistory();
}
/**
* Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
*/
;
_proto7.cueSplitAtTime = function cueSplitAtTime(t) {
for (var i = 0; i < this.channels.length; i++) {
var channel = this.channels[i];
if (channel) {
channel.cueSplitAtTime(t);
}
}
};
return Cea608Parser;
}();
function setLastCmd(a, b, cmdHistory) {
cmdHistory.a = a;
cmdHistory.b = b;
}
function hasCmdRepeated(a, b, cmdHistory) {
return cmdHistory.a === a && cmdHistory.b === b;
}
function createCmdHistory() {
return {
a: null,
b: null
};
}
/* harmony default export */ __webpack_exports__["default"] = (Cea608Parser);
/***/ }),
/***/ "./src/utils/codecs.ts":
/*!*****************************!*\
!*** ./src/utils/codecs.ts ***!
\*****************************/
/*! exports provided: isCodecType, isCodecSupportedInMp4 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCodecType", function() { return isCodecType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCodecSupportedInMp4", function() { return isCodecSupportedInMp4; });
// 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,
av01: 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
},
text: {
stpp: true,
wvtt: true
}
};
function isCodecType(codec, type) {
var typeCodes = sampleEntryCodesISO[type];
return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;
}
function isCodecSupportedInMp4(codec, type) {
return MediaSource.isTypeSupported((type || 'video') + "/mp4;codecs=\"" + codec + "\"");
}
/***/ }),
/***/ "./src/utils/cues.ts":
/*!***************************!*\
!*** ./src/utils/cues.ts ***!
\***************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _vttparser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vttparser */ "./src/utils/vttparser.ts");
/* harmony import */ var _webvtt_parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./webvtt-parser */ "./src/utils/webvtt-parser.ts");
/* harmony import */ var _texttrack_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./texttrack-utils */ "./src/utils/texttrack-utils.ts");
var WHITESPACE_CHAR = /\s/;
var Cues = {
newCue: function newCue(track, startTime, endTime, captionScreen) {
var result = [];
var row; // the type data states this is VTTCue, but it can potentially be a TextTrackCue on old browsers
var cue;
var indenting;
var indent;
var text;
var Cue = self.VTTCue || self.TextTrackCue;
for (var r = 0; r < captionScreen.rows.length; r++) {
row = captionScreen.rows[r];
indenting = true;
indent = 0;
text = '';
if (!row.isEmpty()) {
for (var c = 0; c < row.chars.length; c++) {
if (WHITESPACE_CHAR.test(row.chars[c].uchar) && indenting) {
indent++;
} else {
text += row.chars[c].uchar;
indenting = false;
}
} // To be used for cleaning-up orphaned roll-up captions
row.cueStartTime = startTime; // 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;
}
if (indent >= 16) {
indent--;
} else {
indent++;
}
var cueText = Object(_vttparser__WEBPACK_IMPORTED_MODULE_0__["fixLineBreaks"])(text.trim());
var id = Object(_webvtt_parser__WEBPACK_IMPORTED_MODULE_1__["generateCueId"])(startTime, endTime, cueText); // If this cue already exists in the track do not push it
if (!track || !track.cues || !track.cues.getCueById(id)) {
cue = new Cue(startTime, endTime, cueText);
cue.id = id;
cue.line = r + 1;
cue.align = 'left'; // Clamp the position between 10 and 80 percent (CEA-608 PAC indent code)
// https://dvcs.w3.org/hg/text-tracks/raw-file/default/608toVTT/608toVTT.html#positioning-in-cea-608
// Firefox throws an exception and captions break with out of bounds 0-100 values
cue.position = 10 + Math.min(80, Math.floor(indent * 8 / 32) * 10);
result.push(cue);
}
}
}
if (track && result.length) {
// Sort bottom cues in reverse order so that they render in line order when overlapping in Chrome
result.sort(function (cueA, cueB) {
if (cueA.line === 'auto' || cueB.line === 'auto') {
return 0;
}
if (cueA.line > 8 && cueB.line > 8) {
return cueB.line - cueA.line;
}
return cueA.line - cueB.line;
});
result.forEach(function (cue) {
return Object(_texttrack_utils__WEBPACK_IMPORTED_MODULE_2__["addCueToTrack"])(track, cue);
});
}
return result;
}
};
/* harmony default export */ __webpack_exports__["default"] = (Cues);
/***/ }),
/***/ "./src/utils/discontinuities.ts":
/*!**************************************!*\
!*** ./src/utils/discontinuities.ts ***!
\**************************************/
/*! exports provided: findFirstFragWithCC, shouldAlignOnDiscontinuities, findDiscontinuousReferenceFrag, adjustSlidingStart, alignStream, alignPDT, alignFragmentByPDTDelta, alignMediaPlaylistByPDT */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFirstFragWithCC", function() { return findFirstFragWithCC; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "shouldAlignOnDiscontinuities", function() { return shouldAlignOnDiscontinuities; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findDiscontinuousReferenceFrag", function() { return findDiscontinuousReferenceFrag; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "adjustSlidingStart", function() { return adjustSlidingStart; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignStream", function() { return alignStream; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignPDT", function() { return alignPDT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignFragmentByPDTDelta", function() { return alignFragmentByPDTDelta; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignMediaPlaylistByPDT", function() { return alignMediaPlaylistByPDT; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./logger */ "./src/utils/logger.ts");
/* harmony import */ var _controller_level_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../controller/level-helper */ "./src/controller/level-helper.ts");
function findFirstFragWithCC(fragments, cc) {
var firstFrag = null;
for (var i = 0, len = fragments.length; i < len; i++) {
var currentFrag = fragments[i];
if (currentFrag && currentFrag.cc === cc) {
firstFrag = currentFrag;
break;
}
}
return firstFrag;
}
function shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) {
if (lastLevel.details) {
if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) {
return true;
}
}
return false;
} // 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__WEBPACK_IMPORTED_MODULE_1__["logger"].log('No fragments to align');
return;
}
var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);
if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) {
_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log('No frag in previous level to align on');
return;
}
return prevStartFrag;
}
function adjustFragmentStart(frag, sliding) {
if (frag) {
var start = frag.start + sliding;
frag.start = frag.startPTS = start;
frag.endPTS = start + frag.duration;
}
}
function adjustSlidingStart(sliding, details) {
// Update segments
var fragments = details.fragments;
for (var i = 0, len = fragments.length; i < len; i++) {
adjustFragmentStart(fragments[i], sliding);
} // Update LL-HLS parts at the end of the playlist
if (details.fragmentHint) {
adjustFragmentStart(details.fragmentHint, sliding);
}
details.alignedSliding = true;
}
/**
* Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
* contiguous stream with the last fragments.
* The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
* download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
* and an extra download.
* @param lastFrag
* @param lastLevel
* @param details
*/
function alignStream(lastFrag, lastLevel, details) {
if (!lastLevel) {
return;
}
alignDiscontinuities(lastFrag, details, lastLevel);
if (!details.alignedSliding && lastLevel.details) {
// If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
// Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
// discontinuity sequence.
alignPDT(details, lastLevel.details);
}
if (!details.alignedSliding && lastLevel.details && !details.skippedSegments) {
// Try to align on sn so that we pick a better start fragment.
// Do not perform this on playlists with delta updates as this is only to align levels on switch
// and adjustSliding only adjusts fragments after skippedSegments.
Object(_controller_level_helper__WEBPACK_IMPORTED_MODULE_2__["adjustSliding"])(lastLevel.details, details);
}
}
/**
* Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same
* discontinuity sequence.
* @param lastFrag - The last Fragment which shares the same discontinuity sequence
* @param lastLevel - The details of the last loaded level
* @param details - The details of the new level
*/
function alignDiscontinuities(lastFrag, details, lastLevel) {
if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {
var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);
if (referenceFrag && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(referenceFrag.start)) {
_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log("Adjusting PTS using last level due to CC increase within current level " + details.url);
adjustSlidingStart(referenceFrag.start, details);
}
}
}
/**
* Computes the PTS of a new level's fragments using the difference in Program Date Time from the last level.
* @param details - The details of the new level
* @param lastDetails - The details of the last loaded level
*/
function alignPDT(details, lastDetails) {
// This check protects the unsafe "!" usage below for null program date time access.
if (!lastDetails.fragments.length || !details.hasProgramDateTime || !lastDetails.hasProgramDateTime) {
return;
} // 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 = lastDetails.fragments[0].programDateTime; // hasProgramDateTime check above makes this safe.
var newPDT = details.fragments[0].programDateTime; // date diff is in ms. frag.start is in seconds
var sliding = (newPDT - lastPDT) / 1000 + lastDetails.fragments[0].start;
if (sliding && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(sliding)) {
_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log("Adjusting PTS using programDateTime delta " + (newPDT - lastPDT) + "ms, sliding:" + sliding.toFixed(3) + " " + details.url + " ");
adjustSlidingStart(sliding, details);
}
}
function alignFragmentByPDTDelta(frag, delta) {
var programDateTime = frag.programDateTime;
if (!programDateTime) return;
var start = (programDateTime - delta) / 1000;
frag.start = frag.startPTS = start;
frag.endPTS = start + frag.duration;
}
/**
* Ensures appropriate time-alignment between renditions based on PDT. Unlike `alignPDT`, which adjusts
* the timeline based on the delta between PDTs of the 0th fragment of two playlists/`LevelDetails`,
* this function assumes the timelines represented in `refDetails` are accurate, including the PDTs,
* and uses the "wallclock"/PDT timeline as a cross-reference to `details`, adjusting the presentation
* times/timelines of `details` accordingly.
* Given the asynchronous nature of fetches and initial loads of live `main` and audio/subtitle tracks,
* the primary purpose of this function is to ensure the "local timelines" of audio/subtitle tracks
* are aligned to the main/video timeline, using PDT as the cross-reference/"anchor" that should
* be consistent across playlists, per the HLS spec.
* @param details - The details of the rendition you'd like to time-align (e.g. an audio rendition).
* @param refDetails - The details of the reference rendition with start and PDT times for alignment.
*/
function alignMediaPlaylistByPDT(details, refDetails) {
// This check protects the unsafe "!" usage below for null program date time access.
if (!refDetails.fragments.length || !details.hasProgramDateTime || !refDetails.hasProgramDateTime) {
return;
}
var refPDT = refDetails.fragments[0].programDateTime; // hasProgramDateTime check above makes this safe.
var refStart = refDetails.fragments[0].start; // Use the delta between the reference details' presentation timeline's start time and its PDT
// to align the other rendtion's timeline.
var delta = refPDT - refStart * 1000; // Per spec: "If any Media Playlist in a Master Playlist contains an EXT-X-PROGRAM-DATE-TIME tag, then all
// Media Playlists in that Master Playlist MUST contain EXT-X-PROGRAM-DATE-TIME tags with consistent mappings
// of date and time to media timestamps."
// So we should be able to use each rendition's PDT as a reference time and use the delta to compute our relevant
// start and end times.
// NOTE: This code assumes each level/details timelines have already been made "internally consistent"
details.fragments.forEach(function (frag) {
alignFragmentByPDTDelta(frag, delta);
});
if (details.fragmentHint) {
alignFragmentByPDTDelta(details.fragmentHint, delta);
}
details.alignedSliding = true;
}
/***/ }),
/***/ "./src/utils/ewma-bandwidth-estimator.ts":
/*!***********************************************!*\
!*** ./src/utils/ewma-bandwidth-estimator.ts ***!
\***********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _utils_ewma__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/ewma */ "./src/utils/ewma.ts");
/*
* 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 EwmaBandWidthEstimator = /*#__PURE__*/function () {
function EwmaBandWidthEstimator(slow, fast, defaultEstimate) {
this.defaultEstimate_ = void 0;
this.minWeight_ = void 0;
this.minDelayMs_ = void 0;
this.slow_ = void 0;
this.fast_ = void 0;
this.defaultEstimate_ = defaultEstimate;
this.minWeight_ = 0.001;
this.minDelayMs_ = 50;
this.slow_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](slow);
this.fast_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](fast);
}
var _proto = EwmaBandWidthEstimator.prototype;
_proto.update = function update(slow, fast) {
var slow_ = this.slow_,
fast_ = this.fast_;
if (this.slow_.halfLife !== slow) {
this.slow_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](slow, slow_.getEstimate(), slow_.getTotalWeight());
}
if (this.fast_.halfLife !== fast) {
this.fast_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](fast, fast_.getEstimate(), fast_.getTotalWeight());
}
};
_proto.sample = function sample(durationMs, numBytes) {
durationMs = Math.max(durationMs, this.minDelayMs_);
var numBits = 8 * numBytes; // weight is duration in seconds
var durationS = durationMs / 1000; // value is bandwidth in bits/s
var bandwidthInBps = numBits / durationS;
this.fast_.sample(durationS, bandwidthInBps);
this.slow_.sample(durationS, bandwidthInBps);
};
_proto.canEstimate = function canEstimate() {
var fast = this.fast_;
return fast && fast.getTotalWeight() >= this.minWeight_;
};
_proto.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_;
}
};
_proto.destroy = function destroy() {};
return EwmaBandWidthEstimator;
}();
/* harmony default export */ __webpack_exports__["default"] = (EwmaBandWidthEstimator);
/***/ }),
/***/ "./src/utils/ewma.ts":
/*!***************************!*\
!*** ./src/utils/ewma.ts ***!
\***************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/*
* compute an Exponential Weighted moving average
* - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
* - heavily inspired from shaka-player
*/
var EWMA = /*#__PURE__*/function () {
// About half of the estimated value will be from the last |halfLife| samples by weight.
function EWMA(halfLife, estimate, weight) {
if (estimate === void 0) {
estimate = 0;
}
if (weight === void 0) {
weight = 0;
}
this.halfLife = void 0;
this.alpha_ = void 0;
this.estimate_ = void 0;
this.totalWeight_ = void 0;
this.halfLife = halfLife; // Larger values of alpha expire historical data more slowly.
this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
this.estimate_ = estimate;
this.totalWeight_ = weight;
}
var _proto = EWMA.prototype;
_proto.sample = function sample(weight, value) {
var adjAlpha = Math.pow(this.alpha_, weight);
this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
this.totalWeight_ += weight;
};
_proto.getTotalWeight = function getTotalWeight() {
return this.totalWeight_;
};
_proto.getEstimate = function getEstimate() {
if (this.alpha_) {
var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
if (zeroFactor) {
return this.estimate_ / zeroFactor;
}
}
return this.estimate_;
};
return EWMA;
}();
/* harmony default export */ __webpack_exports__["default"] = (EWMA);
/***/ }),
/***/ "./src/utils/fetch-loader.ts":
/*!***********************************!*\
!*** ./src/utils/fetch-loader.ts ***!
\***********************************/
/*! exports provided: fetchSupported, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fetchSupported", function() { return fetchSupported; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/load-stats */ "./src/loader/load-stats.ts");
/* harmony import */ var _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/chunk-cache */ "./src/demux/chunk-cache.ts");
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function fetchSupported() {
if ( // @ts-ignore
self.fetch && self.AbortController && self.ReadableStream && self.Request) {
try {
new self.ReadableStream({}); // eslint-disable-line no-new
return true;
} catch (e) {
/* noop */
}
}
return false;
}
var FetchLoader = /*#__PURE__*/function () {
function FetchLoader(config
/* HlsConfig */
) {
this.fetchSetup = void 0;
this.requestTimeout = void 0;
this.request = void 0;
this.response = void 0;
this.controller = void 0;
this.context = void 0;
this.config = null;
this.callbacks = null;
this.stats = void 0;
this.loader = null;
this.fetchSetup = config.fetchSetup || getRequest;
this.controller = new self.AbortController();
this.stats = new _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__["LoadStats"]();
}
var _proto = FetchLoader.prototype;
_proto.destroy = function destroy() {
this.loader = this.callbacks = null;
this.abortInternal();
};
_proto.abortInternal = function abortInternal() {
var response = this.response;
if (!response || !response.ok) {
this.stats.aborted = true;
this.controller.abort();
}
};
_proto.abort = function abort() {
var _this$callbacks;
this.abortInternal();
if ((_this$callbacks = this.callbacks) !== null && _this$callbacks !== void 0 && _this$callbacks.onAbort) {
this.callbacks.onAbort(this.stats, this.context, this.response);
}
};
_proto.load = function load(context, config, callbacks) {
var _this = this;
var stats = this.stats;
if (stats.loading.start) {
throw new Error('Loader can only be used once.');
}
stats.loading.start = self.performance.now();
var initParams = getRequestParameters(context, this.controller.signal);
var onProgress = callbacks.onProgress;
var isArrayBuffer = context.responseType === 'arraybuffer';
var LENGTH = isArrayBuffer ? 'byteLength' : 'length';
this.context = context;
this.config = config;
this.callbacks = callbacks;
this.request = this.fetchSetup(context, initParams);
self.clearTimeout(this.requestTimeout);
this.requestTimeout = self.setTimeout(function () {
_this.abortInternal();
callbacks.onTimeout(stats, context, _this.response);
}, config.timeout);
self.fetch(this.request).then(function (response) {
_this.response = _this.loader = response;
if (!response.ok) {
var status = response.status,
statusText = response.statusText;
throw new FetchError(statusText || 'fetch, bad network response', status, response);
}
stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
stats.total = parseInt(response.headers.get('Content-Length') || '0');
if (onProgress && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(config.highWaterMark)) {
return _this.loadProgressively(response, stats, context, config.highWaterMark, onProgress);
}
if (isArrayBuffer) {
return response.arrayBuffer();
}
return response.text();
}).then(function (responseData) {
var response = _this.response;
self.clearTimeout(_this.requestTimeout);
stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
stats.loaded = stats.total = responseData[LENGTH];
var loaderResponse = {
url: response.url,
data: responseData
};
if (onProgress && !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(config.highWaterMark)) {
onProgress(stats, context, responseData, response);
}
callbacks.onSuccess(loaderResponse, stats, context, response);
}).catch(function (error) {
self.clearTimeout(_this.requestTimeout);
if (stats.aborted) {
return;
} // CORS errors result in an undefined code. Set it to 0 here to align with XHR's behavior
var code = error.code || 0;
callbacks.onError({
code: code,
text: error.message
}, context, error.details);
});
};
_proto.getCacheAge = function getCacheAge() {
var result = null;
if (this.response) {
var ageHeader = this.response.headers.get('age');
result = ageHeader ? parseFloat(ageHeader) : null;
}
return result;
};
_proto.loadProgressively = function loadProgressively(response, stats, context, highWaterMark, onProgress) {
if (highWaterMark === void 0) {
highWaterMark = 0;
}
var chunkCache = new _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_2__["default"]();
var reader = response.body.getReader();
var pump = function pump() {
return reader.read().then(function (data) {
if (data.done) {
if (chunkCache.dataLength) {
onProgress(stats, context, chunkCache.flush(), response);
}
return Promise.resolve(new ArrayBuffer(0));
}
var chunk = data.value;
var len = chunk.length;
stats.loaded += len;
if (len < highWaterMark || chunkCache.dataLength) {
// The current chunk is too small to to be emitted or the cache already has data
// Push it to the cache
chunkCache.push(chunk);
if (chunkCache.dataLength >= highWaterMark) {
// flush in order to join the typed arrays
onProgress(stats, context, chunkCache.flush(), response);
}
} else {
// If there's nothing cached already, and the chache is large enough
// just emit the progress event
onProgress(stats, context, chunk, response);
}
return pump();
}).catch(function () {
/* aborted */
return Promise.reject();
});
};
return pump();
};
return FetchLoader;
}();
function getRequestParameters(context, signal) {
var initParams = {
method: 'GET',
mode: 'cors',
credentials: 'same-origin',
signal: signal,
headers: new self.Headers(_extends({}, context.headers))
};
if (context.rangeEnd) {
initParams.headers.set('Range', 'bytes=' + context.rangeStart + '-' + String(context.rangeEnd - 1));
}
return initParams;
}
function getRequest(context, initParams) {
return new self.Request(context.url, initParams);
}
var FetchError = /*#__PURE__*/function (_Error) {
_inheritsLoose(FetchError, _Error);
function FetchError(message, code, details) {
var _this2;
_this2 = _Error.call(this, message) || this;
_this2.code = void 0;
_this2.details = void 0;
_this2.code = code;
_this2.details = details;
return _this2;
}
return FetchError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
/* harmony default export */ __webpack_exports__["default"] = (FetchLoader);
/***/ }),
/***/ "./src/utils/imsc1-ttml-parser.ts":
/*!****************************************!*\
!*** ./src/utils/imsc1-ttml-parser.ts ***!
\****************************************/
/*! exports provided: IMSC1_CODEC, parseIMSC1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IMSC1_CODEC", function() { return IMSC1_CODEC; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseIMSC1", function() { return parseIMSC1; });
/* harmony import */ var _mp4_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _vttparser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vttparser */ "./src/utils/vttparser.ts");
/* harmony import */ var _vttcue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./vttcue */ "./src/utils/vttcue.ts");
/* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
/* harmony import */ var _timescale_conversion__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./timescale-conversion */ "./src/utils/timescale-conversion.ts");
/* harmony import */ var _webvtt_parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./webvtt-parser */ "./src/utils/webvtt-parser.ts");
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
var IMSC1_CODEC = 'stpp.ttml.im1t'; // Time format: h:m:s:frames(.subframes)
var HMSF_REGEX = /^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/; // Time format: hours, minutes, seconds, milliseconds, frames, ticks
var TIME_UNIT_REGEX = /^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/;
var textAlignToLineAlign = {
left: 'start',
center: 'center',
right: 'end',
start: 'start',
end: 'end'
};
function parseIMSC1(payload, initPTS, timescale, callBack, errorCallBack) {
var results = Object(_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["findBox"])(new Uint8Array(payload), ['mdat']);
if (results.length === 0) {
errorCallBack(new Error('Could not parse IMSC1 mdat'));
return;
}
var mdat = results[0];
var ttml = Object(_demux_id3__WEBPACK_IMPORTED_MODULE_3__["utf8ArrayToStr"])(new Uint8Array(payload, mdat.start, mdat.end - mdat.start));
var syncTime = Object(_timescale_conversion__WEBPACK_IMPORTED_MODULE_4__["toTimescaleFromScale"])(initPTS, 1, timescale);
try {
callBack(parseTTML(ttml, syncTime));
} catch (error) {
errorCallBack(error);
}
}
function parseTTML(ttml, syncTime) {
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(ttml, 'text/xml');
var tt = xmlDoc.getElementsByTagName('tt')[0];
if (!tt) {
throw new Error('Invalid ttml');
}
var defaultRateInfo = {
frameRate: 30,
subFrameRate: 1,
frameRateMultiplier: 0,
tickRate: 0
};
var rateInfo = Object.keys(defaultRateInfo).reduce(function (result, key) {
result[key] = tt.getAttribute("ttp:" + key) || defaultRateInfo[key];
return result;
}, {});
var trim = tt.getAttribute('xml:space') !== 'preserve';
var styleElements = collectionToDictionary(getElementCollection(tt, 'styling', 'style'));
var regionElements = collectionToDictionary(getElementCollection(tt, 'layout', 'region'));
var cueElements = getElementCollection(tt, 'body', '[begin]');
return [].map.call(cueElements, function (cueElement) {
var cueText = getTextContent(cueElement, trim);
if (!cueText || !cueElement.hasAttribute('begin')) {
return null;
}
var startTime = parseTtmlTime(cueElement.getAttribute('begin'), rateInfo);
var duration = parseTtmlTime(cueElement.getAttribute('dur'), rateInfo);
var endTime = parseTtmlTime(cueElement.getAttribute('end'), rateInfo);
if (startTime === null) {
throw timestampParsingError(cueElement);
}
if (endTime === null) {
if (duration === null) {
throw timestampParsingError(cueElement);
}
endTime = startTime + duration;
}
var cue = new _vttcue__WEBPACK_IMPORTED_MODULE_2__["default"](startTime - syncTime, endTime - syncTime, cueText);
cue.id = Object(_webvtt_parser__WEBPACK_IMPORTED_MODULE_5__["generateCueId"])(cue.startTime, cue.endTime, cue.text);
var region = regionElements[cueElement.getAttribute('region')];
var style = styleElements[cueElement.getAttribute('style')]; // TODO: Add regions to track and cue (origin and extend)
// These values are hard-coded (for now) to simulate region settings in the demo
cue.position = 10;
cue.size = 80; // Apply styles to cue
var styles = getTtmlStyles(region, style);
var textAlign = styles.textAlign;
if (textAlign) {
// cue.positionAlign not settable in FF~2016
var lineAlign = textAlignToLineAlign[textAlign];
if (lineAlign) {
cue.lineAlign = lineAlign;
}
cue.align = textAlign;
}
_extends(cue, styles);
return cue;
}).filter(function (cue) {
return cue !== null;
});
}
function getElementCollection(fromElement, parentName, childName) {
var parent = fromElement.getElementsByTagName(parentName)[0];
if (parent) {
return [].slice.call(parent.querySelectorAll(childName));
}
return [];
}
function collectionToDictionary(elementsWithId) {
return elementsWithId.reduce(function (dict, element) {
var id = element.getAttribute('xml:id');
if (id) {
dict[id] = element;
}
return dict;
}, {});
}
function getTextContent(element, trim) {
return [].slice.call(element.childNodes).reduce(function (str, node, i) {
var _node$childNodes;
if (node.nodeName === 'br' && i) {
return str + '\n';
}
if ((_node$childNodes = node.childNodes) !== null && _node$childNodes !== void 0 && _node$childNodes.length) {
return getTextContent(node, trim);
} else if (trim) {
return str + node.textContent.trim().replace(/\s+/g, ' ');
}
return str + node.textContent;
}, '');
}
function getTtmlStyles(region, style) {
var ttsNs = 'http://www.w3.org/ns/ttml#styling';
var styleAttributes = ['displayAlign', 'textAlign', 'color', 'backgroundColor', 'fontSize', 'fontFamily' // 'fontWeight',
// 'lineHeight',
// 'wrapOption',
// 'fontStyle',
// 'direction',
// 'writingMode'
];
return styleAttributes.reduce(function (styles, name) {
var value = getAttributeNS(style, ttsNs, name) || getAttributeNS(region, ttsNs, name);
if (value) {
styles[name] = value;
}
return styles;
}, {});
}
function getAttributeNS(element, ns, name) {
return element.hasAttributeNS(ns, name) ? element.getAttributeNS(ns, name) : null;
}
function timestampParsingError(node) {
return new Error("Could not parse ttml timestamp " + node);
}
function parseTtmlTime(timeAttributeValue, rateInfo) {
if (!timeAttributeValue) {
return null;
}
var seconds = Object(_vttparser__WEBPACK_IMPORTED_MODULE_1__["parseTimeStamp"])(timeAttributeValue);
if (seconds === null) {
if (HMSF_REGEX.test(timeAttributeValue)) {
seconds = parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo);
} else if (TIME_UNIT_REGEX.test(timeAttributeValue)) {
seconds = parseTimeUnits(timeAttributeValue, rateInfo);
}
}
return seconds;
}
function parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo) {
var m = HMSF_REGEX.exec(timeAttributeValue);
var frames = (m[4] | 0) + (m[5] | 0) / rateInfo.subFrameRate;
return (m[1] | 0) * 3600 + (m[2] | 0) * 60 + (m[3] | 0) + frames / rateInfo.frameRate;
}
function parseTimeUnits(timeAttributeValue, rateInfo) {
var m = TIME_UNIT_REGEX.exec(timeAttributeValue);
var value = Number(m[1]);
var unit = m[2];
switch (unit) {
case 'h':
return value * 3600;
case 'm':
return value * 60;
case 'ms':
return value * 1000;
case 'f':
return value / rateInfo.frameRate;
case 't':
return value / rateInfo.tickRate;
}
return value;
}
/***/ }),
/***/ "./src/utils/logger.ts":
/*!*****************************!*\
!*** ./src/utils/logger.ts ***!
\*****************************/
/*! exports provided: enableLogs, logger */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableLogs", function() { return enableLogs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logger", function() { return logger; });
var noop = function noop() {};
var fakeLogger = {
trace: noop,
debug: noop,
log: noop,
warn: noop,
info: noop,
error: noop
};
var exportedLogger = fakeLogger; // 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 consolePrintFn(type) {
var func = self.console[type];
if (func) {
return func.bind(self.console, "[" + type + "] >");
}
return noop;
}
function exportLoggerFunctions(debugConfig) {
for (var _len = arguments.length, functions = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
functions[_key - 1] = arguments[_key];
}
functions.forEach(function (type) {
exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);
});
}
function enableLogs(debugConfig) {
// check that console is available
if (self.console && debugConfig === true || 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;
/***/ }),
/***/ "./src/utils/mediakeys-helper.ts":
/*!***************************************!*\
!*** ./src/utils/mediakeys-helper.ts ***!
\***************************************/
/*! exports provided: KeySystems, requestMediaKeySystemAccess */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeySystems", function() { return KeySystems; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "requestMediaKeySystemAccess", function() { return requestMediaKeySystemAccess; });
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess
*/
var KeySystems;
(function (KeySystems) {
KeySystems["WIDEVINE"] = "com.widevine.alpha";
KeySystems["PLAYREADY"] = "com.microsoft.playready";
})(KeySystems || (KeySystems = {}));
var requestMediaKeySystemAccess = function () {
if (typeof self !== 'undefined' && self.navigator && self.navigator.requestMediaKeySystemAccess) {
return self.navigator.requestMediaKeySystemAccess.bind(self.navigator);
} else {
return null;
}
}();
/***/ }),
/***/ "./src/utils/mediasource-helper.ts":
/*!*****************************************!*\
!*** ./src/utils/mediasource-helper.ts ***!
\*****************************************/
/*! exports provided: getMediaSource */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMediaSource", function() { return getMediaSource; });
/**
* MediaSource helper
*/
function getMediaSource() {
return self.MediaSource || self.WebKitMediaSource;
}
/***/ }),
/***/ "./src/utils/mp4-tools.ts":
/*!********************************!*\
!*** ./src/utils/mp4-tools.ts ***!
\********************************/
/*! exports provided: bin2str, readUint16, readUint32, writeUint32, findBox, parseSegmentIndex, parseInitSegment, getStartDTS, getDuration, computeRawDurationFromSamples, offsetStartDTS, segmentValidRange, appendUint8Array */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bin2str", function() { return bin2str; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readUint16", function() { return readUint16; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readUint32", function() { return readUint32; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "writeUint32", function() { return writeUint32; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findBox", function() { return findBox; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseSegmentIndex", function() { return parseSegmentIndex; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseInitSegment", function() { return parseInitSegment; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getStartDTS", function() { return getStartDTS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDuration", function() { return getDuration; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "computeRawDurationFromSamples", function() { return computeRawDurationFromSamples; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "offsetStartDTS", function() { return offsetStartDTS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "segmentValidRange", function() { return segmentValidRange; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendUint8Array", function() { return appendUint8Array; });
/* harmony import */ var _typed_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./typed-array */ "./src/utils/typed-array.ts");
/* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
var UINT32_MAX = Math.pow(2, 32) - 1;
var push = [].push;
function bin2str(data) {
return String.fromCharCode.apply(null, data);
}
function readUint16(buffer, offset) {
if ('data' in buffer) {
offset += buffer.start;
buffer = buffer.data;
}
var val = buffer[offset] << 8 | buffer[offset + 1];
return val < 0 ? 65536 + val : val;
}
function readUint32(buffer, offset) {
if ('data' in buffer) {
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;
}
function writeUint32(buffer, offset, value) {
if ('data' in buffer) {
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
function findBox(input, path) {
var results = [];
if (!path.length) {
// short-circuit the search for empty paths
return results;
}
var data;
var start;
var end;
if ('data' in input) {
data = input.data;
start = input.start;
end = input.end;
} else {
data = input;
start = 0;
end = data.byteLength;
}
for (var i = start; i < end;) {
var size = readUint32(data, i);
var type = bin2str(data.subarray(i + 4, i + 8));
var 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
var subresults = findBox({
data: data,
start: i + 8,
end: endbox
}, path.slice(1));
if (subresults.length) {
push.apply(results, subresults);
}
}
}
i = endbox;
} // we've finished searching all of data
return results;
}
function parseSegmentIndex(initSegment) {
var moovBox = findBox(initSegment, ['moov']);
var moov = moovBox[0];
var moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data
var sidxBox = findBox(initSegment, ['sidx']);
if (!sidxBox || !sidxBox[0]) {
return null;
}
var references = [];
var sidx = sidxBox[0];
var version = sidx.data[0]; // set initial offset, we skip the reference ID (not needed)
var index = version === 0 ? 8 : 16;
var timescale = readUint32(sidx, index);
index += 4; // TODO: parse earliestPresentationTime and firstOffset
// usually zero in our case
var earliestPresentationTime = 0;
var firstOffset = 0;
if (version === 0) {
index += 8;
} else {
index += 16;
} // skip reserved
index += 2;
var startByte = sidx.end + firstOffset;
var referencesCount = readUint16(sidx, index);
index += 2;
for (var i = 0; i < referencesCount; i++) {
var referenceIndex = index;
var referenceInfo = readUint32(sidx, referenceIndex);
referenceIndex += 4;
var referenceSize = referenceInfo & 0x7fffffff;
var referenceType = (referenceInfo & 0x80000000) >>> 31;
if (referenceType === 1) {
// eslint-disable-next-line no-console
console.warn('SIDX has hierarchical references (not supported)');
return null;
}
var subsegmentDuration = readUint32(sidx, referenceIndex);
referenceIndex += 4;
references.push({
referenceSize: referenceSize,
subsegmentDuration: subsegmentDuration,
// unscaled
info: {
duration: subsegmentDuration / timescale,
start: startByte,
end: startByte + referenceSize - 1
}
});
startByte += referenceSize; // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits
// for |sapDelta|.
referenceIndex += 4; // skip to next ref
index = referenceIndex;
}
return {
earliestPresentationTime: earliestPresentationTime,
timescale: timescale,
version: version,
referencesCount: referencesCount,
references: references,
moovEndOffset: moovEndOffset
};
}
/**
* 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 initSegment {Uint8Array} the bytes of the init segment
* @return {InitData} a hash of track type to timescale values or null if
* the init segment is malformed.
*/
function parseInitSegment(initSegment) {
var result = [];
var traks = findBox(initSegment, ['moov', 'trak']);
for (var i = 0; i < traks.length; i++) {
var trak = traks[i];
var tkhd = findBox(trak, ['tkhd'])[0];
if (tkhd) {
var version = tkhd.data[tkhd.start];
var _index = version === 0 ? 12 : 20;
var trackId = readUint32(tkhd, _index);
var mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
if (mdhd) {
version = mdhd.data[mdhd.start];
_index = version === 0 ? 12 : 20;
var timescale = readUint32(mdhd, _index);
var hdlr = findBox(trak, ['mdia', 'hdlr'])[0];
if (hdlr) {
var hdlrType = bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12));
var type = {
soun: _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].AUDIO,
vide: _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].VIDEO
}[hdlrType];
if (type) {
// Parse codec details
var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
var codec = void 0;
if (stsd) {
codec = bin2str(stsd.data.subarray(stsd.start + 12, stsd.start + 16)); // TODO: Parse codec details to be able to build MIME type.
// stsd.start += 8;
// const codecBox = findBox(stsd, [codec])[0];
// if (codecBox) {
// TODO: Codec parsing support for avc1, mp4a, hevc, av01...
// }
}
result[trackId] = {
timescale: timescale,
type: type
};
result[type] = {
timescale: timescale,
id: trackId,
codec: codec
};
}
}
}
}
}
var trex = findBox(initSegment, ['moov', 'mvex', 'trex']);
trex.forEach(function (trex) {
var trackId = readUint32(trex, 4);
var track = result[trackId];
if (track) {
track.default = {
duration: readUint32(trex, 12),
flags: readUint32(trex, 20)
};
}
});
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 initData {InitData} a hash of track type to timescale values
* @param fmp4 {Uint8Array} the bytes of the mp4 fragment
* @return {number} the earliest base media decode start time for the
* fragment, in seconds
*/
function getStartDTS(initData, fmp4) {
// we need info from two children of each track fragment box
return findBox(fmp4, ['moof', 'traf']).reduce(function (result, traf) {
var tfdt = findBox(traf, ['tfdt'])[0];
var version = tfdt.data[tfdt.start];
var start = findBox(traf, ['tfhd']).reduce(function (result, tfhd) {
// get the track id from the tfhd
var id = readUint32(tfhd, 4);
var track = initData[id];
if (track) {
var baseTime = readUint32(tfdt, 4);
if (version === 1) {
baseTime *= Math.pow(2, 32);
baseTime += readUint32(tfdt, 8);
} // assume a 90kHz clock if no timescale was specified
var scale = track.timescale || 90e3; // convert base time to seconds
var startTime = baseTime / scale;
if (isFinite(startTime) && (result === null || startTime < result)) {
return startTime;
}
}
return result;
}, null);
if (start !== null && isFinite(start) && (result === null || start < result)) {
return start;
}
return result;
}, null) || 0;
}
/*
For Reference:
aligned(8) class TrackFragmentHeaderBox
extends FullBox(‘tfhd’, 0, tf_flags){
unsigned int(32) track_ID;
// all the following are optional fields
unsigned int(64) base_data_offset;
unsigned int(32) sample_description_index;
unsigned int(32) default_sample_duration;
unsigned int(32) default_sample_size;
unsigned int(32) default_sample_flags
}
*/
function getDuration(data, initData) {
var rawDuration = 0;
var videoDuration = 0;
var audioDuration = 0;
var trafs = findBox(data, ['moof', 'traf']);
for (var i = 0; i < trafs.length; i++) {
var traf = trafs[i]; // There is only one tfhd & trun per traf
// This is true for CMAF style content, and we should perhaps check the ftyp
// and only look for a single trun then, but for ISOBMFF we should check
// for multiple track runs.
var tfhd = findBox(traf, ['tfhd'])[0]; // get the track id from the tfhd
var id = readUint32(tfhd, 4);
var track = initData[id];
if (!track) {
continue;
}
var trackDefault = track.default;
var tfhdFlags = readUint32(tfhd, 0) | (trackDefault === null || trackDefault === void 0 ? void 0 : trackDefault.flags);
var sampleDuration = trackDefault === null || trackDefault === void 0 ? void 0 : trackDefault.duration;
if (tfhdFlags & 0x000008) {
// 0x000008 indicates the presence of the default_sample_duration field
if (tfhdFlags & 0x000002) {
// 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration
// If present, the default_sample_duration exists at byte offset 12
sampleDuration = readUint32(tfhd, 12);
} else {
// Otherwise, the duration is at byte offset 8
sampleDuration = readUint32(tfhd, 8);
}
} // assume a 90kHz clock if no timescale was specified
var timescale = track.timescale || 90e3;
var truns = findBox(traf, ['trun']);
for (var j = 0; j < truns.length; j++) {
if (sampleDuration) {
var sampleCount = readUint32(truns[j], 4);
rawDuration = sampleDuration * sampleCount;
} else {
rawDuration = computeRawDurationFromSamples(truns[j]);
}
if (track.type === _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].VIDEO) {
videoDuration += rawDuration / timescale;
} else if (track.type === _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].AUDIO) {
audioDuration += rawDuration / timescale;
}
}
}
if (videoDuration === 0 && audioDuration === 0) {
// If duration samples are not available in the traf use sidx subsegment_duration
var sidx = parseSegmentIndex(data);
if (sidx !== null && sidx !== void 0 && sidx.references) {
return sidx.references.reduce(function (dur, ref) {
return dur + ref.info.duration || 0;
}, 0);
}
}
if (videoDuration) {
return videoDuration;
}
return audioDuration;
}
/*
For Reference:
aligned(8) class TrackRunBox
extends FullBox(‘trun’, version, tr_flags) {
unsigned int(32) sample_count;
// the following are optional fields
signed int(32) data_offset;
unsigned int(32) first_sample_flags;
// all fields in the following array are optional
{
unsigned int(32) sample_duration;
unsigned int(32) sample_size;
unsigned int(32) sample_flags
if (version == 0)
{ unsigned int(32)
else
{ signed int(32)
}[ sample_count ]
}
*/
function computeRawDurationFromSamples(trun) {
var flags = readUint32(trun, 0); // Flags are at offset 0, non-optional sample_count is at offset 4. Therefore we start 8 bytes in.
// Each field is an int32, which is 4 bytes
var offset = 8; // data-offset-present flag
if (flags & 0x000001) {
offset += 4;
} // first-sample-flags-present flag
if (flags & 0x000004) {
offset += 4;
}
var duration = 0;
var sampleCount = readUint32(trun, 4);
for (var i = 0; i < sampleCount; i++) {
// sample-duration-present flag
if (flags & 0x000100) {
var sampleDuration = readUint32(trun, offset);
duration += sampleDuration;
offset += 4;
} // sample-size-present flag
if (flags & 0x000200) {
offset += 4;
} // sample-flags-present flag
if (flags & 0x000400) {
offset += 4;
} // sample-composition-time-offsets-present flag
if (flags & 0x000800) {
offset += 4;
}
}
return duration;
}
function offsetStartDTS(initData, fmp4, timeOffset) {
findBox(fmp4, ['moof', 'traf']).forEach(function (traf) {
findBox(traf, ['tfhd']).forEach(function (tfhd) {
// get the track id from the tfhd
var id = readUint32(tfhd, 4);
var track = initData[id];
if (!track) {
return;
} // assume a 90kHz clock if no timescale was specified
var timescale = track.timescale || 90e3; // get the base media decode time from the tfdt
findBox(traf, ['tfdt']).forEach(function (tfdt) {
var version = tfdt.data[tfdt.start];
var baseMediaDecodeTime = readUint32(tfdt, 4);
if (version === 0) {
writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset * timescale);
} else {
baseMediaDecodeTime *= Math.pow(2, 32);
baseMediaDecodeTime += 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));
writeUint32(tfdt, 4, upper);
writeUint32(tfdt, 8, lower);
}
});
});
});
} // TODO: Check if the last moof+mdat pair is part of the valid range
function segmentValidRange(data) {
var segmentedRange = {
valid: null,
remainder: null
};
var moofs = findBox(data, ['moof']);
if (!moofs) {
return segmentedRange;
} else if (moofs.length < 2) {
segmentedRange.remainder = data;
return segmentedRange;
}
var last = moofs[moofs.length - 1]; // Offset by 8 bytes; findBox offsets the start by as much
segmentedRange.valid = Object(_typed_array__WEBPACK_IMPORTED_MODULE_0__["sliceUint8"])(data, 0, last.start - 8);
segmentedRange.remainder = Object(_typed_array__WEBPACK_IMPORTED_MODULE_0__["sliceUint8"])(data, last.start - 8);
return segmentedRange;
}
function appendUint8Array(data1, data2) {
var temp = new Uint8Array(data1.length + data2.length);
temp.set(data1);
temp.set(data2, data1.length);
return temp;
}
/***/ }),
/***/ "./src/utils/output-filter.ts":
/*!************************************!*\
!*** ./src/utils/output-filter.ts ***!
\************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return OutputFilter; });
var OutputFilter = /*#__PURE__*/function () {
function OutputFilter(timelineController, trackName) {
this.timelineController = void 0;
this.cueRanges = [];
this.trackName = void 0;
this.startTime = null;
this.endTime = null;
this.screen = null;
this.timelineController = timelineController;
this.trackName = trackName;
}
var _proto = OutputFilter.prototype;
_proto.dispatchCue = function dispatchCue() {
if (this.startTime === null) {
return;
}
this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen, this.cueRanges);
this.startTime = null;
};
_proto.newCue = function newCue(startTime, endTime, screen) {
if (this.startTime === null || this.startTime > startTime) {
this.startTime = startTime;
}
this.endTime = endTime;
this.screen = screen;
this.timelineController.createCaptionsTrack(this.trackName);
};
_proto.reset = function reset() {
this.cueRanges = [];
};
return OutputFilter;
}();
/***/ }),
/***/ "./src/utils/texttrack-utils.ts":
/*!**************************************!*\
!*** ./src/utils/texttrack-utils.ts ***!
\**************************************/
/*! exports provided: sendAddTrackEvent, addCueToTrack, clearCurrentCues, removeCuesInRange, getCuesInRange */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sendAddTrackEvent", function() { return sendAddTrackEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addCueToTrack", function() { return addCueToTrack; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearCurrentCues", function() { return clearCurrentCues; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeCuesInRange", function() { return removeCuesInRange; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCuesInRange", function() { return getCuesInRange; });
/* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./logger */ "./src/utils/logger.ts");
function sendAddTrackEvent(track, videoEl) {
var event;
try {
event = new Event('addtrack');
} catch (err) {
// for IE11
event = document.createEvent('Event');
event.initEvent('addtrack', false, false);
}
event.track = track;
videoEl.dispatchEvent(event);
}
function addCueToTrack(track, cue) {
// Sometimes there are cue overlaps on segmented vtts so the same
// cue can appear more than once in different vtt files.
// This avoid showing duplicated cues with same timecode and text.
var mode = track.mode;
if (mode === 'disabled') {
track.mode = 'hidden';
}
if (track.cues && !track.cues.getCueById(cue.id)) {
try {
track.addCue(cue);
if (!track.cues.getCueById(cue.id)) {
throw new Error("addCue is failed for: " + cue);
}
} catch (err) {
_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].debug("[texttrack-utils]: " + err);
var textTrackCue = new self.TextTrackCue(cue.startTime, cue.endTime, cue.text);
textTrackCue.id = cue.id;
track.addCue(textTrackCue);
}
}
if (mode === 'disabled') {
track.mode = mode;
}
}
function clearCurrentCues(track) {
// When track.mode is disabled, track.cues will be null.
// To guarantee the removal of cues, we need to temporarily
// change the mode to hidden
var mode = track.mode;
if (mode === 'disabled') {
track.mode = 'hidden';
}
if (track.cues) {
for (var i = track.cues.length; i--;) {
track.removeCue(track.cues[i]);
}
}
if (mode === 'disabled') {
track.mode = mode;
}
}
function removeCuesInRange(track, start, end) {
var mode = track.mode;
if (mode === 'disabled') {
track.mode = 'hidden';
}
if (track.cues && track.cues.length > 0) {
var cues = getCuesInRange(track.cues, start, end);
for (var i = 0; i < cues.length; i++) {
track.removeCue(cues[i]);
}
}
if (mode === 'disabled') {
track.mode = mode;
}
} // Find first cue starting after given time.
// Modified version of binary search O(log(n)).
function getFirstCueIndexAfterTime(cues, time) {
// If first cue starts after time, start there
if (time < cues[0].startTime) {
return 0;
} // If the last cue ends before time there is no overlap
var len = cues.length - 1;
if (time > cues[len].endTime) {
return -1;
}
var left = 0;
var right = len;
while (left <= right) {
var mid = Math.floor((right + left) / 2);
if (time < cues[mid].startTime) {
right = mid - 1;
} else if (time > cues[mid].startTime && left < len) {
left = mid + 1;
} else {
// If it's not lower or higher, it must be equal.
return mid;
}
} // At this point, left and right have swapped.
// No direct match was found, left or right element must be the closest. Check which one has the smallest diff.
return cues[left].startTime - time < time - cues[right].startTime ? left : right;
}
function getCuesInRange(cues, start, end) {
var cuesFound = [];
var firstCueInRange = getFirstCueIndexAfterTime(cues, start);
if (firstCueInRange > -1) {
for (var i = firstCueInRange, len = cues.length; i < len; i++) {
var cue = cues[i];
if (cue.startTime >= start && cue.endTime <= end) {
cuesFound.push(cue);
} else if (cue.startTime > end) {
return cuesFound;
}
}
}
return cuesFound;
}
/***/ }),
/***/ "./src/utils/time-ranges.ts":
/*!**********************************!*\
!*** ./src/utils/time-ranges.ts ***!
\**********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/**
* TimeRanges to string helper
*/
var TimeRanges = {
toString: function toString(r) {
var log = '';
var 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 */ __webpack_exports__["default"] = (TimeRanges);
/***/ }),
/***/ "./src/utils/timescale-conversion.ts":
/*!*******************************************!*\
!*** ./src/utils/timescale-conversion.ts ***!
\*******************************************/
/*! exports provided: toTimescaleFromBase, toTimescaleFromScale, toMsFromMpegTsClock, toMpegTsClockFromTimescale */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toTimescaleFromBase", function() { return toTimescaleFromBase; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toTimescaleFromScale", function() { return toTimescaleFromScale; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toMsFromMpegTsClock", function() { return toMsFromMpegTsClock; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toMpegTsClockFromTimescale", function() { return toMpegTsClockFromTimescale; });
var MPEG_TS_CLOCK_FREQ_HZ = 90000;
function toTimescaleFromBase(value, destScale, srcBase, round) {
if (srcBase === void 0) {
srcBase = 1;
}
if (round === void 0) {
round = false;
}
var result = value * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`
return round ? Math.round(result) : result;
}
function toTimescaleFromScale(value, destScale, srcScale, round) {
if (srcScale === void 0) {
srcScale = 1;
}
if (round === void 0) {
round = false;
}
return toTimescaleFromBase(value, destScale, 1 / srcScale, round);
}
function toMsFromMpegTsClock(value, round) {
if (round === void 0) {
round = false;
}
return toTimescaleFromBase(value, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);
}
function toMpegTsClockFromTimescale(value, srcScale) {
if (srcScale === void 0) {
srcScale = 1;
}
return toTimescaleFromBase(value, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);
}
/***/ }),
/***/ "./src/utils/typed-array.ts":
/*!**********************************!*\
!*** ./src/utils/typed-array.ts ***!
\**********************************/
/*! exports provided: sliceUint8 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sliceUint8", function() { return sliceUint8; });
function sliceUint8(array, start, end) {
// @ts-expect-error This polyfills IE11 usage of Uint8Array slice.
// It always exists in the TypeScript definition so fails, but it fails at runtime on IE11.
return Uint8Array.prototype.slice ? array.slice(start, end) : new Uint8Array(Array.prototype.slice.call(array, start, end));
}
/***/ }),
/***/ "./src/utils/vttcue.ts":
/*!*****************************!*\
!*** ./src/utils/vttcue.ts ***!
\*****************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/**
* Copyright 2013 vtt.js 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.
*/
/* harmony default export */ __webpack_exports__["default"] = ((function () {
if (typeof self !== 'undefined' && self.VTTCue) {
return self.VTTCue;
}
var AllowedDirections = ['', 'lr', 'rl'];
var AllowedAlignments = ['start', 'middle', 'end', 'left', 'right'];
function isAllowedValue(allowed, value) {
if (typeof value !== 'string') {
return false;
} // necessary for assuring the generic conforms to the Array interface
if (!Array.isArray(allowed)) {
return false;
} // reset the type so that the next narrowing works well
var lcValue = value.toLowerCase(); // use the allow list to narrow the type to a specific subset of strings
if (~allowed.indexOf(lcValue)) {
return lcValue;
}
return false;
}
function findDirectionSetting(value) {
return isAllowedValue(AllowedDirections, value);
}
function findAlignSetting(value) {
return isAllowedValue(AllowedAlignments, value);
}
function extend(obj) {
for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
rest[_key - 1] = arguments[_key];
}
var i = 1;
for (; i < arguments.length; i++) {
var cobj = arguments[i];
for (var p in cobj) {
obj[p] = cobj[p];
}
}
return obj;
}
function VTTCue(startTime, endTime, text) {
var cue = this;
var baseObj = {
enumerable: true
};
/**
* Shim implementation specific properties. These properties are not in
* the spec.
*/
// Lets us know when the VTTCue's data has changed in such a way that we need
// to recompute its display state. This lets us compute its display state
// lazily.
cue.hasBeenReset = false;
/**
* VTTCue and TextTrackCue properties
* http://dev.w3.org/html5/webvtt/#vttcue-interface
*/
var _id = '';
var _pauseOnExit = false;
var _startTime = startTime;
var _endTime = endTime;
var _text = text;
var _region = null;
var _vertical = '';
var _snapToLines = true;
var _line = 'auto';
var _lineAlign = 'start';
var _position = 50;
var _positionAlign = 'middle';
var _size = 50;
var _align = 'middle';
Object.defineProperty(cue, 'id', extend({}, baseObj, {
get: function get() {
return _id;
},
set: function set(value) {
_id = '' + value;
}
}));
Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {
get: function get() {
return _pauseOnExit;
},
set: function set(value) {
_pauseOnExit = !!value;
}
}));
Object.defineProperty(cue, 'startTime', extend({}, baseObj, {
get: function get() {
return _startTime;
},
set: function set(value) {
if (typeof value !== 'number') {
throw new TypeError('Start time must be set to a number.');
}
_startTime = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'endTime', extend({}, baseObj, {
get: function get() {
return _endTime;
},
set: function set(value) {
if (typeof value !== 'number') {
throw new TypeError('End time must be set to a number.');
}
_endTime = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'text', extend({}, baseObj, {
get: function get() {
return _text;
},
set: function set(value) {
_text = '' + value;
this.hasBeenReset = true;
}
})); // todo: implement VTTRegion polyfill?
Object.defineProperty(cue, 'region', extend({}, baseObj, {
get: function get() {
return _region;
},
set: function set(value) {
_region = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'vertical', extend({}, baseObj, {
get: function get() {
return _vertical;
},
set: function set(value) {
var setting = findDirectionSetting(value); // Have to check for false because the setting an be an empty string.
if (setting === false) {
throw new SyntaxError('An invalid or illegal string was specified.');
}
_vertical = setting;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {
get: function get() {
return _snapToLines;
},
set: function set(value) {
_snapToLines = !!value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'line', extend({}, baseObj, {
get: function get() {
return _line;
},
set: function set(value) {
if (typeof value !== 'number' && value !== 'auto') {
throw new SyntaxError('An invalid number or illegal string was specified.');
}
_line = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {
get: function get() {
return _lineAlign;
},
set: function set(value) {
var setting = findAlignSetting(value);
if (!setting) {
throw new SyntaxError('An invalid or illegal string was specified.');
}
_lineAlign = setting;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'position', extend({}, baseObj, {
get: function get() {
return _position;
},
set: function set(value) {
if (value < 0 || value > 100) {
throw new Error('Position must be between 0 and 100.');
}
_position = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {
get: function get() {
return _positionAlign;
},
set: function set(value) {
var setting = findAlignSetting(value);
if (!setting) {
throw new SyntaxError('An invalid or illegal string was specified.');
}
_positionAlign = setting;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'size', extend({}, baseObj, {
get: function get() {
return _size;
},
set: function set(value) {
if (value < 0 || value > 100) {
throw new Error('Size must be between 0 and 100.');
}
_size = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'align', extend({}, baseObj, {
get: function get() {
return _align;
},
set: function set(value) {
var setting = findAlignSetting(value);
if (!setting) {
throw new SyntaxError('An invalid or illegal string was specified.');
}
_align = setting;
this.hasBeenReset = true;
}
}));
/**
* Other <track> spec defined properties
*/
// http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
cue.displayState = undefined;
}
/**
* VTTCue methods
*/
VTTCue.prototype.getCueAsHTML = function () {
// Assume WebVTT.convertCueToDOMTree is on the global.
var WebVTT = self.WebVTT;
return WebVTT.convertCueToDOMTree(self, this.text);
}; // this is a polyfill hack
return VTTCue;
})());
/***/ }),
/***/ "./src/utils/vttparser.ts":
/*!********************************!*\
!*** ./src/utils/vttparser.ts ***!
\********************************/
/*! exports provided: parseTimeStamp, fixLineBreaks, VTTParser */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseTimeStamp", function() { return parseTimeStamp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fixLineBreaks", function() { return fixLineBreaks; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VTTParser", function() { return VTTParser; });
/* harmony import */ var _vttcue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vttcue */ "./src/utils/vttcue.ts");
/*
* Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js
*/
var StringDecoder = /*#__PURE__*/function () {
function StringDecoder() {}
var _proto = StringDecoder.prototype;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_proto.decode = function decode(data, options) {
if (!data) {
return '';
}
if (typeof data !== 'string') {
throw new Error('Error - expected string data.');
}
return decodeURIComponent(encodeURIComponent(data));
};
return StringDecoder;
}(); // Try to parse input as a time stamp.
function parseTimeStamp(input) {
function computeSeconds(h, m, s, f) {
return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + parseFloat(f || 0);
}
var m = input.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);
if (!m) {
return null;
}
if (parseFloat(m[2]) > 59) {
// Timestamp takes the form of [hours]:[minutes].[milliseconds]
// First position is hours as it's over 59.
return computeSeconds(m[2], m[3], 0, m[4]);
} // Timestamp takes the form of [hours (optional)]:[minutes]:[seconds].[milliseconds]
return computeSeconds(m[1], m[2], m[3], m[4]);
} // A settings object holds key/value pairs and will ignore anything but the first
// assignment to a specific key.
var Settings = /*#__PURE__*/function () {
function Settings() {
this.values = Object.create(null);
}
var _proto2 = Settings.prototype;
// Only accept the first assignment to any key.
_proto2.set = function set(k, v) {
if (!this.get(k) && v !== '') {
this.values[k] = v;
}
} // Return the value for a key, or a default value.
// If 'defaultKey' is passed then 'dflt' is assumed to be an object with
// a number of possible default values as properties where 'defaultKey' is
// the key of the property that will be chosen; otherwise it's assumed to be
// a single value.
;
_proto2.get = function get(k, dflt, defaultKey) {
if (defaultKey) {
return this.has(k) ? this.values[k] : dflt[defaultKey];
}
return this.has(k) ? this.values[k] : dflt;
} // Check whether we have a value for a key.
;
_proto2.has = function has(k) {
return k in this.values;
} // Accept a setting if its one of the given alternatives.
;
_proto2.alt = function alt(k, v, a) {
for (var n = 0; n < a.length; ++n) {
if (v === a[n]) {
this.set(k, v);
break;
}
}
} // Accept a setting if its a valid (signed) integer.
;
_proto2.integer = function integer(k, v) {
if (/^-?\d+$/.test(v)) {
// integer
this.set(k, parseInt(v, 10));
}
} // Accept a setting if its a valid percentage.
;
_proto2.percent = function percent(k, v) {
if (/^([\d]{1,3})(\.[\d]*)?%$/.test(v)) {
var percent = parseFloat(v);
if (percent >= 0 && percent <= 100) {
this.set(k, percent);
return true;
}
}
return false;
};
return Settings;
}(); // Helper function to parse input into groups separated by 'groupDelim', and
// interpret each group as a key/value pair separated by 'keyValueDelim'.
function parseOptions(input, callback, keyValueDelim, groupDelim) {
var groups = groupDelim ? input.split(groupDelim) : [input];
for (var i in groups) {
if (typeof groups[i] !== 'string') {
continue;
}
var kv = groups[i].split(keyValueDelim);
if (kv.length !== 2) {
continue;
}
var _k = kv[0];
var _v = kv[1];
callback(_k, _v);
}
}
var defaults = new _vttcue__WEBPACK_IMPORTED_MODULE_0__["default"](0, 0, ''); // 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244
// Safari doesn't yet support this change, but FF and Chrome do.
var center = defaults.align === 'middle' ? 'middle' : 'center';
function parseCue(input, cue, regionList) {
// Remember the original input if we need to throw an error.
var oInput = input; // 4.1 WebVTT timestamp
function consumeTimeStamp() {
var ts = parseTimeStamp(input);
if (ts === null) {
throw new Error('Malformed timestamp: ' + oInput);
} // Remove time stamp from input.
input = input.replace(/^[^\sa-zA-Z-]+/, '');
return ts;
} // 4.4.2 WebVTT cue settings
function consumeCueSettings(input, cue) {
var settings = new Settings();
parseOptions(input, function (k, v) {
var vals;
switch (k) {
case 'region':
// Find the last region we parsed with the same region id.
for (var i = regionList.length - 1; i >= 0; i--) {
if (regionList[i].id === v) {
settings.set(k, regionList[i].region);
break;
}
}
break;
case 'vertical':
settings.alt(k, v, ['rl', 'lr']);
break;
case 'line':
vals = v.split(',');
settings.integer(k, vals[0]);
if (settings.percent(k, vals[0])) {
settings.set('snapToLines', false);
}
settings.alt(k, vals[0], ['auto']);
if (vals.length === 2) {
settings.alt('lineAlign', vals[1], ['start', center, 'end']);
}
break;
case 'position':
vals = v.split(',');
settings.percent(k, vals[0]);
if (vals.length === 2) {
settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']);
}
break;
case 'size':
settings.percent(k, v);
break;
case 'align':
settings.alt(k, v, ['start', center, 'end', 'left', 'right']);
break;
}
}, /:/, /\s/); // Apply default values for any missing fields.
cue.region = settings.get('region', null);
cue.vertical = settings.get('vertical', '');
var line = settings.get('line', 'auto');
if (line === 'auto' && defaults.line === -1) {
// set numeric line number for Safari
line = -1;
}
cue.line = line;
cue.lineAlign = settings.get('lineAlign', 'start');
cue.snapToLines = settings.get('snapToLines', true);
cue.size = settings.get('size', 100);
cue.align = settings.get('align', center);
var position = settings.get('position', 'auto');
if (position === 'auto' && defaults.position === 50) {
// set numeric position for Safari
position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50;
}
cue.position = position;
}
function skipWhitespace() {
input = input.replace(/^\s+/, '');
} // 4.1 WebVTT cue timings.
skipWhitespace();
cue.startTime = consumeTimeStamp(); // (1) collect cue start time
skipWhitespace();
if (input.substr(0, 3) !== '-->') {
// (3) next characters must match '-->'
throw new Error("Malformed time stamp (time stamps must be separated by '-->'): " + oInput);
}
input = input.substr(3);
skipWhitespace();
cue.endTime = consumeTimeStamp(); // (5) collect cue end time
// 4.1 WebVTT cue settings list.
skipWhitespace();
consumeCueSettings(input, cue);
}
function fixLineBreaks(input) {
return input.replace(/<br(?: \/)?>/gi, '\n');
}
var VTTParser = /*#__PURE__*/function () {
function VTTParser() {
this.state = 'INITIAL';
this.buffer = '';
this.decoder = new StringDecoder();
this.regionList = [];
this.cue = null;
this.oncue = void 0;
this.onparsingerror = void 0;
this.onflush = void 0;
}
var _proto3 = VTTParser.prototype;
_proto3.parse = function parse(data) {
var _this = this; // If there is no data then we won't decode it, but will just try to parse
// whatever is in buffer already. This may occur in circumstances, for
// example when flush() is called.
if (data) {
// Try to decode the data that we received.
_this.buffer += _this.decoder.decode(data, {
stream: true
});
}
function collectNextLine() {
var buffer = _this.buffer;
var pos = 0;
buffer = fixLineBreaks(buffer);
while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
++pos;
}
var line = buffer.substr(0, pos); // Advance the buffer early in case we fail below.
if (buffer[pos] === '\r') {
++pos;
}
if (buffer[pos] === '\n') {
++pos;
}
_this.buffer = buffer.substr(pos);
return line;
} // 3.2 WebVTT metadata header syntax
function parseHeader(input) {
parseOptions(input, function (k, v) {// switch (k) {
// case 'region':
// 3.3 WebVTT region metadata header syntax
// console.log('parse region', v);
// parseRegion(v);
// break;
// }
}, /:/);
} // 5.1 WebVTT file parsing.
try {
var line = '';
if (_this.state === 'INITIAL') {
// We can't start parsing until we have the first line.
if (!/\r\n|\n/.test(_this.buffer)) {
return this;
}
line = collectNextLine(); // strip of UTF-8 BOM if any
// https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
var m = line.match(/^()?WEBVTT([ \t].*)?$/);
if (!m || !m[0]) {
throw new Error('Malformed WebVTT signature.');
}
_this.state = 'HEADER';
}
var alreadyCollectedLine = false;
while (_this.buffer) {
// We can't parse a line until we have the full line.
if (!/\r\n|\n/.test(_this.buffer)) {
return this;
}
if (!alreadyCollectedLine) {
line = collectNextLine();
} else {
alreadyCollectedLine = false;
}
switch (_this.state) {
case 'HEADER':
// 13-18 - Allow a header (metadata) under the WEBVTT line.
if (/:/.test(line)) {
parseHeader(line);
} else if (!line) {
// An empty line terminates the header and starts the body (cues).
_this.state = 'ID';
}
continue;
case 'NOTE':
// Ignore NOTE blocks.
if (!line) {
_this.state = 'ID';
}
continue;
case 'ID':
// Check for the start of NOTE blocks.
if (/^NOTE($|[ \t])/.test(line)) {
_this.state = 'NOTE';
break;
} // 19-29 - Allow any number of line terminators, then initialize new cue values.
if (!line) {
continue;
}
_this.cue = new _vttcue__WEBPACK_IMPORTED_MODULE_0__["default"](0, 0, '');
_this.state = 'CUE'; // 30-39 - Check if self line contains an optional identifier or timing data.
if (line.indexOf('-->') === -1) {
_this.cue.id = line;
continue;
}
// Process line as start of a cue.
/* falls through */
case 'CUE':
// 40 - Collect cue timings and settings.
if (!_this.cue) {
_this.state = 'BADCUE';
continue;
}
try {
parseCue(line, _this.cue, _this.regionList);
} catch (e) {
// In case of an error ignore rest of the cue.
_this.cue = null;
_this.state = 'BADCUE';
continue;
}
_this.state = 'CUETEXT';
continue;
case 'CUETEXT':
{
var hasSubstring = line.indexOf('-->') !== -1; // 34 - If we have an empty line then report the cue.
// 35 - If we have the special substring '-->' then report the cue,
// but do not collect the line as we need to process the current
// one as a new cue.
if (!line || hasSubstring && (alreadyCollectedLine = true)) {
// We are done parsing self cue.
if (_this.oncue && _this.cue) {
_this.oncue(_this.cue);
}
_this.cue = null;
_this.state = 'ID';
continue;
}
if (_this.cue === null) {
continue;
}
if (_this.cue.text) {
_this.cue.text += '\n';
}
_this.cue.text += line;
}
continue;
case 'BADCUE':
// 54-62 - Collect and discard the remaining cue.
if (!line) {
_this.state = 'ID';
}
}
}
} catch (e) {
// If we are currently parsing a cue, report what we have.
if (_this.state === 'CUETEXT' && _this.cue && _this.oncue) {
_this.oncue(_this.cue);
}
_this.cue = null; // Enter BADWEBVTT state if header was not parsed correctly otherwise
// another exception occurred so enter BADCUE state.
_this.state = _this.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';
}
return this;
};
_proto3.flush = function flush() {
var _this = this;
try {
// Finish decoding the stream.
// _this.buffer += _this.decoder.decode();
// Synthesize the end of the current cue or region.
if (_this.cue || _this.state === 'HEADER') {
_this.buffer += '\n\n';
_this.parse();
} // If we've flushed, parsed, and we're still on the INITIAL state then
// that means we don't have enough of the stream to parse the first
// line.
if (_this.state === 'INITIAL' || _this.state === 'BADWEBVTT') {
throw new Error('Malformed WebVTT signature.');
}
} catch (e) {
if (_this.onparsingerror) {
_this.onparsingerror(e);
}
}
if (_this.onflush) {
_this.onflush();
}
return this;
};
return VTTParser;
}();
/***/ }),
/***/ "./src/utils/webvtt-parser.ts":
/*!************************************!*\
!*** ./src/utils/webvtt-parser.ts ***!
\************************************/
/*! exports provided: generateCueId, parseWebVTT */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "generateCueId", function() { return generateCueId; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseWebVTT", function() { return parseWebVTT; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _vttparser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vttparser */ "./src/utils/vttparser.ts");
/* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
/* harmony import */ var _timescale_conversion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./timescale-conversion */ "./src/utils/timescale-conversion.ts");
/* harmony import */ var _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../remux/mp4-remuxer */ "./src/remux/mp4-remuxer.ts");
var LINEBREAKS = /\r\n|\n\r|\n|\r/g; // String.prototype.startsWith is not supported in IE11
var startsWith = function startsWith(inputString, searchString, position) {
if (position === void 0) {
position = 0;
}
return inputString.substr(position, searchString.length) === searchString;
};
var cueString2millis = function cueString2millis(timeString) {
var ts = parseInt(timeString.substr(-3));
var secs = parseInt(timeString.substr(-6, 2));
var mins = parseInt(timeString.substr(-9, 2));
var hours = timeString.length > 9 ? parseInt(timeString.substr(0, timeString.indexOf(':'))) : 0;
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(ts) || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(secs) || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mins) || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(hours)) {
throw Error("Malformed X-TIMESTAMP-MAP: Local:" + timeString);
}
ts += 1000 * secs;
ts += 60 * 1000 * mins;
ts += 60 * 60 * 1000 * hours;
return ts;
}; // From https://github.com/darkskyapp/string-hash
var hash = function hash(text) {
var hash = 5381;
var i = text.length;
while (i) {
hash = hash * 33 ^ text.charCodeAt(--i);
}
return (hash >>> 0).toString();
}; // Create a unique hash id for a cue based on start/end times and text.
// This helps timeline-controller to avoid showing repeated captions.
function generateCueId(startTime, endTime, text) {
return hash(startTime.toString()) + hash(endTime.toString()) + hash(text);
}
var calculateOffset = function calculateOffset(vttCCs, cc, presentationTime) {
var currCC = vttCCs[cc];
var prevCC = vttCCs[currCC.prevCC]; // This is the first discontinuity or cues have been processed since the last discontinuity
// Offset = current discontinuity time
if (!prevCC || !prevCC.new && currCC.new) {
vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
currCC.new = false;
return;
} // There have been discontinuities since cues were last parsed.
// Offset = time elapsed
while ((_prevCC = prevCC) !== null && _prevCC !== void 0 && _prevCC.new) {
var _prevCC;
vttCCs.ccOffset += currCC.start - prevCC.start;
currCC.new = false;
currCC = prevCC;
prevCC = vttCCs[currCC.prevCC];
}
vttCCs.presentationOffset = presentationTime;
};
function parseWebVTT(vttByteArray, initPTS, timescale, vttCCs, cc, timeOffset, callBack, errorCallBack) {
var parser = new _vttparser__WEBPACK_IMPORTED_MODULE_1__["VTTParser"](); // Convert byteArray into string, replacing any somewhat exotic linefeeds with "\n", then split on that character.
// Uint8Array.prototype.reduce is not implemented in IE11
var vttLines = Object(_demux_id3__WEBPACK_IMPORTED_MODULE_2__["utf8ArrayToStr"])(new Uint8Array(vttByteArray)).trim().replace(LINEBREAKS, '\n').split('\n');
var cues = [];
var initPTS90Hz = Object(_timescale_conversion__WEBPACK_IMPORTED_MODULE_3__["toMpegTsClockFromTimescale"])(initPTS, timescale);
var cueTime = '00:00.000';
var timestampMapMPEGTS = 0;
var timestampMapLOCAL = 0;
var parsingError;
var inHeader = true;
var timestampMap = false;
parser.oncue = function (cue) {
// Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.
var currCC = vttCCs[cc];
var cueOffset = vttCCs.ccOffset; // Calculate subtitle PTS offset
var webVttMpegTsMapOffset = (timestampMapMPEGTS - initPTS90Hz) / 90000; // Update offsets for new discontinuities
if (currCC !== null && currCC !== void 0 && currCC.new) {
if (timestampMapLOCAL !== undefined) {
// When local time is provided, offset = discontinuity start time - local time
cueOffset = vttCCs.ccOffset = currCC.start;
} else {
calculateOffset(vttCCs, cc, webVttMpegTsMapOffset);
}
}
if (webVttMpegTsMapOffset) {
// If we have MPEGTS, offset = presentation time + discontinuity offset
cueOffset = webVttMpegTsMapOffset - vttCCs.presentationOffset;
}
if (timestampMap) {
var duration = cue.endTime - cue.startTime;
var startTime = Object(_remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_4__["normalizePts"])((cue.startTime + cueOffset - timestampMapLOCAL) * 90000, timeOffset * 90000) / 90000;
cue.startTime = startTime;
cue.endTime = startTime + duration;
} //trim trailing webvtt block whitespaces
var text = cue.text.trim(); // Fix encoding of special characters
cue.text = decodeURIComponent(encodeURIComponent(text)); // If the cue was not assigned an id from the VTT file (line above the content), create one.
if (!cue.id) {
cue.id = generateCueId(cue.startTime, cue.endTime, text);
}
if (cue.endTime > 0) {
cues.push(cue);
}
};
parser.onparsingerror = function (error) {
parsingError = error;
};
parser.onflush = function () {
if (parsingError) {
errorCallBack(parsingError);
return;
}
callBack(cues);
}; // Go through contents line by line.
vttLines.forEach(function (line) {
if (inHeader) {
// Look for X-TIMESTAMP-MAP in header.
if (startsWith(line, 'X-TIMESTAMP-MAP=')) {
// Once found, no more are allowed anyway, so stop searching.
inHeader = false;
timestampMap = true; // Extract LOCAL and MPEGTS.
line.substr(16).split(',').forEach(function (timestamp) {
if (startsWith(timestamp, 'LOCAL:')) {
cueTime = timestamp.substr(6);
} else if (startsWith(timestamp, 'MPEGTS:')) {
timestampMapMPEGTS = parseInt(timestamp.substr(7));
}
});
try {
// Convert cue time to seconds
timestampMapLOCAL = cueString2millis(cueTime) / 1000;
} catch (error) {
timestampMap = false;
parsingError = error;
} // Return without parsing X-TIMESTAMP-MAP line.
return;
} else if (line === '') {
inHeader = false;
}
} // Parse line by default.
parser.parse(line + '\n');
});
parser.flush();
}
/***/ }),
/***/ "./src/utils/xhr-loader.ts":
/*!*********************************!*\
!*** ./src/utils/xhr-loader.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/load-stats */ "./src/loader/load-stats.ts");
var AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/m;
var XhrLoader = /*#__PURE__*/function () {
function XhrLoader(config
/* HlsConfig */
) {
this.xhrSetup = void 0;
this.requestTimeout = void 0;
this.retryTimeout = void 0;
this.retryDelay = void 0;
this.config = null;
this.callbacks = null;
this.context = void 0;
this.loader = null;
this.stats = void 0;
this.xhrSetup = config ? config.xhrSetup : null;
this.stats = new _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__["LoadStats"]();
this.retryDelay = 0;
}
var _proto = XhrLoader.prototype;
_proto.destroy = function destroy() {
this.callbacks = null;
this.abortInternal();
this.loader = null;
this.config = null;
};
_proto.abortInternal = function abortInternal() {
var loader = this.loader;
self.clearTimeout(this.requestTimeout);
self.clearTimeout(this.retryTimeout);
if (loader) {
loader.onreadystatechange = null;
loader.onprogress = null;
if (loader.readyState !== 4) {
this.stats.aborted = true;
loader.abort();
}
}
};
_proto.abort = function abort() {
var _this$callbacks;
this.abortInternal();
if ((_this$callbacks = this.callbacks) !== null && _this$callbacks !== void 0 && _this$callbacks.onAbort) {
this.callbacks.onAbort(this.stats, this.context, this.loader);
}
};
_proto.load = function load(context, config, callbacks) {
if (this.stats.loading.start) {
throw new Error('Loader can only be used once.');
}
this.stats.loading.start = self.performance.now();
this.context = context;
this.config = config;
this.callbacks = callbacks;
this.retryDelay = config.retryDelay;
this.loadInternal();
};
_proto.loadInternal = function loadInternal() {
var config = this.config,
context = this.context;
if (!config) {
return;
}
var xhr = this.loader = new self.XMLHttpRequest();
var stats = this.stats;
stats.loading.first = 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);
}
var headers = this.context.headers;
if (headers) {
for (var header in headers) {
xhr.setRequestHeader(header, headers[header]);
}
}
} 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
self.clearTimeout(this.requestTimeout);
this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
xhr.send();
};
_proto.readystatechange = function readystatechange() {
var context = this.context,
xhr = this.loader,
stats = this.stats;
if (!context || !xhr) {
return;
}
var readyState = xhr.readyState;
var 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
self.clearTimeout(this.requestTimeout);
if (stats.loading.first === 0) {
stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
}
if (readyState === 4) {
xhr.onreadystatechange = null;
xhr.onprogress = null;
var status = xhr.status; // http status between 200 to 299 are all successful
if (status >= 200 && status < 300) {
stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
var data;
var len;
if (context.responseType === 'arraybuffer') {
data = xhr.response;
len = data.byteLength;
} else {
data = xhr.responseText;
len = data.length;
}
stats.loaded = stats.total = len;
if (!this.callbacks) {
return;
}
var onProgress = this.callbacks.onProgress;
if (onProgress) {
onProgress(stats, context, data, xhr);
}
if (!this.callbacks) {
return;
}
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) {
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].error(status + " while loading " + context.url);
this.callbacks.onError({
code: status,
text: xhr.statusText
}, context, xhr);
} else {
// retry
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].warn(status + " while loading " + context.url + ", retrying in " + this.retryDelay + "..."); // abort and reset internal state
this.abortInternal();
this.loader = null; // schedule retry
self.clearTimeout(this.retryTimeout);
this.retryTimeout = self.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
self.clearTimeout(this.requestTimeout);
this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
}
}
};
_proto.loadtimeout = function loadtimeout() {
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].warn("timeout while loading " + this.context.url);
var callbacks = this.callbacks;
if (callbacks) {
this.abortInternal();
callbacks.onTimeout(this.stats, this.context, this.loader);
}
};
_proto.loadprogress = function loadprogress(event) {
var stats = this.stats;
stats.loaded = event.loaded;
if (event.lengthComputable) {
stats.total = event.total;
}
};
_proto.getCacheAge = function getCacheAge() {
var result = null;
if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) {
var ageHeader = this.loader.getResponseHeader('age');
result = ageHeader ? parseFloat(ageHeader) : null;
}
return result;
};
return XhrLoader;
}();
/* harmony default export */ __webpack_exports__["default"] = (XhrLoader);
/***/ })
/******/ })["default"];
});
//# sourceMappingURL=hls.js.map | mit |
cdnjs/cdnjs | ajax/libs/buefy/0.9.14/esm/progress.js | 6567 | import { _ as _defineProperty } from './chunk-2452e3d3.js';
import './helpers.js';
import { c as config } from './chunk-8cad1844.js';
import { _ as __vue_normalize__, r as registerComponent, u as use } from './chunk-cca88db8.js';
import { P as ProviderParentMixin, I as InjectedChildMixin } from './chunk-91404fa9.js';
var script = {
name: 'BProgress',
mixins: [ProviderParentMixin('progress')],
props: {
type: {
type: [String, Object],
default: 'is-darkgrey'
},
size: String,
rounded: {
type: Boolean,
default: true
},
value: {
type: Number,
default: undefined
},
max: {
type: Number,
default: 100
},
showValue: {
type: Boolean,
default: false
},
format: {
type: String,
default: 'raw',
validator: function validator(value) {
return ['raw', 'percent'].indexOf(value) >= 0;
}
},
precision: {
type: Number,
default: 2
},
keepTrailingZeroes: {
type: Boolean,
default: false
},
locale: {
type: [String, Array],
default: function _default() {
return config.defaultLocale;
}
}
},
computed: {
isIndeterminate: function isIndeterminate() {
return this.value === undefined || this.value === null;
},
newType: function newType() {
return [this.size, this.type, {
'is-more-than-half': this.value && this.value > this.max / 2
}];
},
newValue: function newValue() {
return this.calculateValue(this.value);
},
isNative: function isNative() {
return this.$slots.bar === undefined;
},
wrapperClasses: function wrapperClasses() {
return _defineProperty({
'is-not-native': !this.isNative
}, this.size, !this.isNative);
}
},
watch: {
/**
* When value is changed back to undefined, value of native progress get reset to 0.
* Need to add and remove the value attribute to have the indeterminate or not.
*/
isIndeterminate: function isIndeterminate(indeterminate) {
var _this = this;
this.$nextTick(function () {
if (_this.$refs.progress) {
if (indeterminate) {
_this.$refs.progress.removeAttribute('value');
} else {
_this.$refs.progress.setAttribute('value', _this.value);
}
}
});
}
},
methods: {
calculateValue: function calculateValue(value) {
if (value === undefined || value === null || isNaN(value)) {
return undefined;
}
var minimumFractionDigits = this.keepTrailingZeroes ? this.precision : 0;
var maximumFractionDigits = this.precision;
if (this.format === 'percent') {
return new Intl.NumberFormat(this.locale, {
style: 'percent',
minimumFractionDigits: minimumFractionDigits,
maximumFractionDigits: maximumFractionDigits
}).format(value / this.max);
}
return new Intl.NumberFormat(this.locale, {
minimumFractionDigits: minimumFractionDigits,
maximumFractionDigits: maximumFractionDigits
}).format(value);
}
}
};
/* script */
const __vue_script__ = script;
/* template */
var __vue_render__ = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"progress-wrapper",class:[_vm.wrapperClasses, { 'is-squared': !_vm.rounded }]},[(_vm.isNative)?_c('progress',{ref:"progress",staticClass:"progress",class:[_vm.newType, { 'is-squared': !_vm.rounded }],attrs:{"max":_vm.max},domProps:{"value":_vm.value}},[_vm._v(_vm._s(_vm.newValue))]):_vm._t("bar"),(_vm.isNative && _vm.showValue)?_c('p',{staticClass:"progress-value"},[_vm._t("default",[_vm._v(_vm._s(_vm.newValue))])],2):_vm._e()],2)};
var __vue_staticRenderFns__ = [];
/* style */
const __vue_inject_styles__ = undefined;
/* scoped */
const __vue_scope_id__ = undefined;
/* module identifier */
const __vue_module_identifier__ = undefined;
/* functional template */
const __vue_is_functional_template__ = false;
/* style inject */
/* style inject SSR */
var Progress = __vue_normalize__(
{ render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ },
__vue_inject_styles__,
__vue_script__,
__vue_scope_id__,
__vue_is_functional_template__,
__vue_module_identifier__,
undefined,
undefined
);
//
var script$1 = {
name: 'BProgressBar',
mixins: [InjectedChildMixin('progress')],
props: {
type: {
type: [String, Object],
default: undefined
},
value: {
type: Number,
default: undefined
},
showValue: {
type: Boolean,
default: false
}
},
computed: {
newType: function newType() {
return [this.parent.size, this.type || this.parent.type];
},
newShowValue: function newShowValue() {
return this.showValue || this.parent.showValue;
},
newValue: function newValue() {
return this.parent.calculateValue(this.value);
},
barWidth: function barWidth() {
return "".concat(this.value * 100 / this.parent.max, "%");
}
}
};
/* script */
const __vue_script__$1 = script$1;
/* template */
var __vue_render__$1 = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"progress-bar",class:_vm.newType,style:({width: _vm.barWidth}),attrs:{"role":"progressbar","aria-valuenow":_vm.value,"aria-valuemax":_vm.parent.max,"aria-valuemin":"0"}},[(_vm.newShowValue)?_c('p',{staticClass:"progress-value"},[_vm._t("default",[_vm._v(_vm._s(_vm.newValue))])],2):_vm._e()])};
var __vue_staticRenderFns__$1 = [];
/* style */
const __vue_inject_styles__$1 = undefined;
/* scoped */
const __vue_scope_id__$1 = undefined;
/* module identifier */
const __vue_module_identifier__$1 = undefined;
/* functional template */
const __vue_is_functional_template__$1 = false;
/* style inject */
/* style inject SSR */
var ProgressBar = __vue_normalize__(
{ render: __vue_render__$1, staticRenderFns: __vue_staticRenderFns__$1 },
__vue_inject_styles__$1,
__vue_script__$1,
__vue_scope_id__$1,
__vue_is_functional_template__$1,
__vue_module_identifier__$1,
undefined,
undefined
);
var Plugin = {
install: function install(Vue) {
registerComponent(Vue, Progress);
registerComponent(Vue, ProgressBar);
}
};
use(Plugin);
export default Plugin;
export { Progress as BProgress, ProgressBar as BProgressBar };
| mit |
cdnjs/cdnjs | ajax/libs/json-editor/1.0.0/jsoneditor.js | 287278 | /*! JSON Editor v0.7.28 - JSON Schema -> HTML Editor
* By Jeremy Dorn - https://github.com/jdorn/json-editor/
* Released under the MIT license
*
* Date: 2016-08-07
*/
/**
* See README.md for requirements and usage info
*/
(function() {
/*jshint loopfunc: true */
/* Simple JavaScript Inheritance
* By John Resig http://ejohn.org/
* MIT Licensed.
*/
// Inspired by base2 and Prototype
var Class;
(function(){
var initializing = false, fnTest = /xyz/.test(function(){window.postMessage("xyz");}) ? /\b_super\b/ : /.*/;
// The base Class implementation (does nothing)
Class = function(){};
// Create a new Class that inherits from this class
Class.extend = function extend(prop) {
var _super = this.prototype;
// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
var prototype = new this();
initializing = false;
// Copy the properties over onto the new prototype
for (var name in prop) {
// Check if we're overwriting an existing function
prototype[name] = typeof prop[name] == "function" &&
typeof _super[name] == "function" && fnTest.test(prop[name]) ?
(function(name, fn){
return function() {
var tmp = this._super;
// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];
// The method only need to be bound temporarily, so we
// remove it when we're done executing
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, prop[name]) :
prop[name];
}
// The dummy class constructor
function Class() {
// All construction is actually done in the init method
if ( !initializing && this.init )
this.init.apply(this, arguments);
}
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;
// And make this class extendable
Class.extend = extend;
return Class;
};
return Class;
})();
// CustomEvent constructor polyfill
// From MDN
(function () {
function CustomEvent ( event, params ) {
params = params || { bubbles: false, cancelable: false, detail: undefined };
var evt = document.createEvent( 'CustomEvent' );
evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
return evt;
}
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
})();
// requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
// MIT license
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] ||
window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
// Array.isArray polyfill
// From MDN
(function() {
if(!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
}());
/**
* Taken from jQuery 2.1.3
*
* @param obj
* @returns {boolean}
*/
var $isplainobject = function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if (typeof obj !== "object" || obj.nodeType || (obj !== null && obj === obj.window)) {
return false;
}
if (obj.constructor && !Object.prototype.hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf")) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
};
var $extend = function(destination) {
var source, i,property;
for(i=1; i<arguments.length; i++) {
source = arguments[i];
for (property in source) {
if(!source.hasOwnProperty(property)) continue;
if(source[property] && $isplainobject(source[property])) {
if(!destination.hasOwnProperty(property)) destination[property] = {};
$extend(destination[property], source[property]);
}
else {
destination[property] = source[property];
}
}
}
return destination;
};
var $each = function(obj,callback) {
if(!obj || typeof obj !== "object") return;
var i;
if(Array.isArray(obj) || (typeof obj.length === 'number' && obj.length > 0 && (obj.length - 1) in obj)) {
for(i=0; i<obj.length; i++) {
if(callback(i,obj[i])===false) return;
}
}
else {
if (Object.keys) {
var keys = Object.keys(obj);
for(i=0; i<keys.length; i++) {
if(callback(keys[i],obj[keys[i]])===false) return;
}
}
else {
for(i in obj) {
if(!obj.hasOwnProperty(i)) continue;
if(callback(i,obj[i])===false) return;
}
}
}
};
var $trigger = function(el,event) {
var e = document.createEvent('HTMLEvents');
e.initEvent(event, true, true);
el.dispatchEvent(e);
};
var $triggerc = function(el,event) {
var e = new CustomEvent(event,{
bubbles: true,
cancelable: true
});
el.dispatchEvent(e);
};
var JSONEditor = function(element,options) {
if (!(element instanceof Element)) {
throw new Error('element should be an instance of Element');
}
options = $extend({},JSONEditor.defaults.options,options||{});
this.element = element;
this.options = options;
this.init();
};
JSONEditor.prototype = {
// necessary since we remove the ctor property by doing a literal assignment. Without this
// the $isplainobject function will think that this is a plain object.
constructor: JSONEditor,
init: function() {
var self = this;
this.ready = false;
this.copyClipboard = null;
var theme_class = JSONEditor.defaults.themes[this.options.theme || JSONEditor.defaults.theme];
if(!theme_class) throw "Unknown theme " + (this.options.theme || JSONEditor.defaults.theme);
this.schema = this.options.schema;
this.theme = new theme_class();
this.template = this.options.template;
this.refs = this.options.refs || {};
this.uuid = 0;
this.__data = {};
var icon_class = JSONEditor.defaults.iconlibs[this.options.iconlib || JSONEditor.defaults.iconlib];
if(icon_class) this.iconlib = new icon_class();
this.root_container = this.theme.getContainer();
this.element.appendChild(this.root_container);
this.translate = this.options.translate || JSONEditor.defaults.translate;
// Fetch all external refs via ajax
this._loadExternalRefs(this.schema, function() {
self._getDefinitions(self.schema);
// Validator options
var validator_options = {};
if(self.options.custom_validators) {
validator_options.custom_validators = self.options.custom_validators;
}
self.validator = new JSONEditor.Validator(self,null,validator_options);
// Create the root editor
var schema = self.expandRefs(self.schema);
var editor_class = self.getEditorClass(schema);
self.root = self.createEditor(editor_class, {
jsoneditor: self,
schema: schema,
required: true,
container: self.root_container
});
self.root.preBuild();
self.root.build();
self.root.postBuild();
// Starting data
if(self.options.hasOwnProperty('startval')) self.root.setValue(self.options.startval);
self.validation_results = self.validator.validate(self.root.getValue());
self.root.showValidationErrors(self.validation_results);
self.ready = true;
// Fire ready event asynchronously
window.requestAnimationFrame(function() {
if(!self.ready) return;
self.validation_results = self.validator.validate(self.root.getValue());
self.root.showValidationErrors(self.validation_results);
self.trigger('ready');
self.trigger('change');
});
});
},
getValue: function() {
if(!this.ready) throw "JSON Editor not ready yet. Listen for 'ready' event before getting the value";
return this.root.getValue();
},
setValue: function(value) {
if(!this.ready) throw "JSON Editor not ready yet. Listen for 'ready' event before setting the value";
this.root.setValue(value);
return this;
},
validate: function(value) {
if(!this.ready) throw "JSON Editor not ready yet. Listen for 'ready' event before validating";
// Custom value
if(arguments.length === 1) {
return this.validator.validate(value);
}
// Current value (use cached result)
else {
return this.validation_results;
}
},
destroy: function() {
if(this.destroyed) return;
if(!this.ready) return;
this.schema = null;
this.options = null;
this.root.destroy();
this.root = null;
this.root_container = null;
this.validator = null;
this.validation_results = null;
this.theme = null;
this.iconlib = null;
this.template = null;
this.__data = null;
this.ready = false;
this.element.innerHTML = '';
this.destroyed = true;
},
on: function(event, callback) {
this.callbacks = this.callbacks || {};
this.callbacks[event] = this.callbacks[event] || [];
this.callbacks[event].push(callback);
return this;
},
off: function(event, callback) {
// Specific callback
if(event && callback) {
this.callbacks = this.callbacks || {};
this.callbacks[event] = this.callbacks[event] || [];
var newcallbacks = [];
for(var i=0; i<this.callbacks[event].length; i++) {
if(this.callbacks[event][i]===callback) continue;
newcallbacks.push(this.callbacks[event][i]);
}
this.callbacks[event] = newcallbacks;
}
// All callbacks for a specific event
else if(event) {
this.callbacks = this.callbacks || {};
this.callbacks[event] = [];
}
// All callbacks for all events
else {
this.callbacks = {};
}
return this;
},
trigger: function(event) {
if(this.callbacks && this.callbacks[event] && this.callbacks[event].length) {
for(var i=0; i<this.callbacks[event].length; i++) {
this.callbacks[event][i]();
}
}
return this;
},
setOption: function(option, value) {
if(option === "show_errors") {
this.options.show_errors = value;
this.onChange();
}
// Only the `show_errors` option is supported for now
else {
throw "Option "+option+" must be set during instantiation and cannot be changed later";
}
return this;
},
getEditorClass: function(schema) {
var classname;
schema = this.expandSchema(schema);
$each(JSONEditor.defaults.resolvers,function(i,resolver) {
var tmp = resolver(schema);
if(tmp) {
if(JSONEditor.defaults.editors[tmp]) {
classname = tmp;
return false;
}
}
});
if(!classname) throw "Unknown editor for schema "+JSON.stringify(schema);
if(!JSONEditor.defaults.editors[classname]) throw "Unknown editor "+classname;
return JSONEditor.defaults.editors[classname];
},
createEditor: function(editor_class, options) {
options = $extend({},editor_class.options||{},options);
return new editor_class(options);
},
onChange: function() {
if(!this.ready) return;
if(this.firing_change) return;
this.firing_change = true;
var self = this;
window.requestAnimationFrame(function() {
self.firing_change = false;
if(!self.ready) return;
// Validate and cache results
self.validation_results = self.validator.validate(self.root.getValue());
if(self.options.show_errors !== "never") {
self.root.showValidationErrors(self.validation_results);
}
else {
self.root.showValidationErrors([]);
}
// Fire change event
self.trigger('change');
});
return this;
},
compileTemplate: function(template, name) {
name = name || JSONEditor.defaults.template;
var engine;
// Specifying a preset engine
if(typeof name === 'string') {
if(!JSONEditor.defaults.templates[name]) throw "Unknown template engine "+name;
engine = JSONEditor.defaults.templates[name]();
if(!engine) throw "Template engine "+name+" missing required library.";
}
// Specifying a custom engine
else {
engine = name;
}
if(!engine) throw "No template engine set";
if(!engine.compile) throw "Invalid template engine set";
return engine.compile(template);
},
_data: function(el,key,value) {
// Setting data
if(arguments.length === 3) {
var uuid;
if(el.hasAttribute('data-jsoneditor-'+key)) {
uuid = el.getAttribute('data-jsoneditor-'+key);
}
else {
uuid = this.uuid++;
el.setAttribute('data-jsoneditor-'+key,uuid);
}
this.__data[uuid] = value;
}
// Getting data
else {
// No data stored
if(!el.hasAttribute('data-jsoneditor-'+key)) return null;
return this.__data[el.getAttribute('data-jsoneditor-'+key)];
}
},
registerEditor: function(editor) {
this.editors = this.editors || {};
this.editors[editor.path] = editor;
return this;
},
unregisterEditor: function(editor) {
this.editors = this.editors || {};
this.editors[editor.path] = null;
return this;
},
getEditor: function(path) {
if(!this.editors) return;
return this.editors[path];
},
watch: function(path,callback) {
this.watchlist = this.watchlist || {};
this.watchlist[path] = this.watchlist[path] || [];
this.watchlist[path].push(callback);
return this;
},
unwatch: function(path,callback) {
if(!this.watchlist || !this.watchlist[path]) return this;
// If removing all callbacks for a path
if(!callback) {
this.watchlist[path] = null;
return this;
}
var newlist = [];
for(var i=0; i<this.watchlist[path].length; i++) {
if(this.watchlist[path][i] === callback) continue;
else newlist.push(this.watchlist[path][i]);
}
this.watchlist[path] = newlist.length? newlist : null;
return this;
},
notifyWatchers: function(path) {
if(!this.watchlist || !this.watchlist[path]) return this;
for(var i=0; i<this.watchlist[path].length; i++) {
this.watchlist[path][i]();
}
},
isEnabled: function() {
return !this.root || this.root.isEnabled();
},
enable: function() {
this.root.enable();
},
disable: function() {
this.root.disable();
},
_getDefinitions: function(schema,path) {
path = path || '#/definitions/';
if(schema.definitions) {
for(var i in schema.definitions) {
if(!schema.definitions.hasOwnProperty(i)) continue;
this.refs[path+i] = schema.definitions[i];
if(schema.definitions[i].definitions) {
this._getDefinitions(schema.definitions[i],path+i+'/definitions/');
}
}
}
},
_getExternalRefs: function(schema) {
var refs = {};
var merge_refs = function(newrefs) {
for(var i in newrefs) {
if(newrefs.hasOwnProperty(i)) {
refs[i] = true;
}
}
};
if(schema.$ref && typeof schema.$ref !== "object" && schema.$ref.substr(0,1) !== "#" && !this.refs[schema.$ref]) {
refs[schema.$ref] = true;
}
for(var i in schema) {
if(!schema.hasOwnProperty(i)) continue;
if(schema[i] && typeof schema[i] === "object" && Array.isArray(schema[i])) {
for(var j=0; j<schema[i].length; j++) {
if(schema[i][j] && typeof schema[i][j]==="object") {
merge_refs(this._getExternalRefs(schema[i][j]));
}
}
}
else if(schema[i] && typeof schema[i] === "object") {
merge_refs(this._getExternalRefs(schema[i]));
}
}
return refs;
},
_loadExternalRefs: function(schema, callback) {
var self = this;
var refs = this._getExternalRefs(schema);
var done = 0, waiting = 0, callback_fired = false;
$each(refs,function(url) {
if(self.refs[url]) return;
if(!self.options.ajax) throw "Must set ajax option to true to load external ref "+url;
self.refs[url] = 'loading';
waiting++;
var fetchUrl=url;
if( self.options.ajaxBase && self.options.ajaxBase!=url.substr(0,self.options.ajaxBase.length) && "http"!=url.substr(0,4)) fetchUrl=self.options.ajaxBase+url;
var r = new XMLHttpRequest();
r.open("GET", fetchUrl, true);
if(self.options.ajaxCredentials) r.withCredentials=self.options.ajaxCredentials;
r.onreadystatechange = function () {
if (r.readyState != 4) return;
// Request succeeded
if(r.status === 200) {
var response;
try {
response = JSON.parse(r.responseText);
}
catch(e) {
window.console.log(e);
throw "Failed to parse external ref "+fetchUrl;
}
if(!response || typeof response !== "object") throw "External ref does not contain a valid schema - "+fetchUrl;
self.refs[url] = response;
self._loadExternalRefs(response,function() {
done++;
if(done >= waiting && !callback_fired) {
callback_fired = true;
callback();
}
});
}
// Request failed
else {
window.console.log(r);
throw "Failed to fetch ref via ajax- "+url;
}
};
r.send();
});
if(!waiting) {
callback();
}
},
expandRefs: function(schema) {
schema = $extend({},schema);
while (schema.$ref) {
var ref = schema.$ref;
delete schema.$ref;
if(!this.refs[ref]) ref = decodeURIComponent(ref);
schema = this.extendSchemas(schema,this.refs[ref]);
}
return schema;
},
expandSchema: function(schema) {
var self = this;
var extended = $extend({},schema);
var i;
// Version 3 `type`
if(typeof schema.type === 'object') {
// Array of types
if(Array.isArray(schema.type)) {
$each(schema.type, function(key,value) {
// Schema
if(typeof value === 'object') {
schema.type[key] = self.expandSchema(value);
}
});
}
// Schema
else {
schema.type = self.expandSchema(schema.type);
}
}
// Version 3 `disallow`
if(typeof schema.disallow === 'object') {
// Array of types
if(Array.isArray(schema.disallow)) {
$each(schema.disallow, function(key,value) {
// Schema
if(typeof value === 'object') {
schema.disallow[key] = self.expandSchema(value);
}
});
}
// Schema
else {
schema.disallow = self.expandSchema(schema.disallow);
}
}
// Version 4 `anyOf`
if(schema.anyOf) {
$each(schema.anyOf, function(key,value) {
schema.anyOf[key] = self.expandSchema(value);
});
}
// Version 4 `dependencies` (schema dependencies)
if(schema.dependencies) {
$each(schema.dependencies,function(key,value) {
if(typeof value === "object" && !(Array.isArray(value))) {
schema.dependencies[key] = self.expandSchema(value);
}
});
}
// Version 4 `not`
if(schema.not) {
schema.not = this.expandSchema(schema.not);
}
// allOf schemas should be merged into the parent
if(schema.allOf) {
for(i=0; i<schema.allOf.length; i++) {
extended = this.extendSchemas(extended,this.expandSchema(schema.allOf[i]));
}
delete extended.allOf;
}
// extends schemas should be merged into parent
if(schema["extends"]) {
// If extends is a schema
if(!(Array.isArray(schema["extends"]))) {
extended = this.extendSchemas(extended,this.expandSchema(schema["extends"]));
}
// If extends is an array of schemas
else {
for(i=0; i<schema["extends"].length; i++) {
extended = this.extendSchemas(extended,this.expandSchema(schema["extends"][i]));
}
}
delete extended["extends"];
}
// parent should be merged into oneOf schemas
if(schema.oneOf) {
var tmp = $extend({},extended);
delete tmp.oneOf;
for(i=0; i<schema.oneOf.length; i++) {
extended.oneOf[i] = this.extendSchemas(this.expandSchema(schema.oneOf[i]),tmp);
}
}
return this.expandRefs(extended);
},
extendSchemas: function(obj1, obj2) {
obj1 = $extend({},obj1);
obj2 = $extend({},obj2);
var self = this;
var extended = {};
$each(obj1, function(prop,val) {
// If this key is also defined in obj2, merge them
if(typeof obj2[prop] !== "undefined") {
// Required and defaultProperties arrays should be unioned together
if((prop === 'required'||prop === 'defaultProperties') && typeof val === "object" && Array.isArray(val)) {
// Union arrays and unique
extended[prop] = val.concat(obj2[prop]).reduce(function(p, c) {
if (p.indexOf(c) < 0) p.push(c);
return p;
}, []);
}
// Type should be intersected and is either an array or string
else if(prop === 'type' && (typeof val === "string" || Array.isArray(val))) {
// Make sure we're dealing with arrays
if(typeof val === "string") val = [val];
if(typeof obj2.type === "string") obj2.type = [obj2.type];
// If type is only defined in the first schema, keep it
if(!obj2.type || !obj2.type.length) {
extended.type = val;
}
// If type is defined in both schemas, do an intersect
else {
extended.type = val.filter(function(n) {
return obj2.type.indexOf(n) !== -1;
});
}
// If there's only 1 type and it's a primitive, use a string instead of array
if(extended.type.length === 1 && typeof extended.type[0] === "string") {
extended.type = extended.type[0];
}
// Remove the type property if it's empty
else if(extended.type.length === 0) {
delete extended.type;
}
}
// All other arrays should be intersected (enum, etc.)
else if(typeof val === "object" && Array.isArray(val)){
extended[prop] = val.filter(function(n) {
return obj2[prop].indexOf(n) !== -1;
});
}
// Objects should be recursively merged
else if(typeof val === "object" && val !== null) {
extended[prop] = self.extendSchemas(val,obj2[prop]);
}
// Otherwise, use the first value
else {
extended[prop] = val;
}
}
// Otherwise, just use the one in obj1
else {
extended[prop] = val;
}
});
// Properties in obj2 that aren't in obj1
$each(obj2, function(prop,val) {
if(typeof obj1[prop] === "undefined") {
extended[prop] = val;
}
});
return extended;
},
setCopyClipboardContents: function(value) {
this.copyClipboard = value;
},
getCopyClipboardContents: function() {
return this.copyClipboard;
}
};
JSONEditor.defaults = {
themes: {},
templates: {},
iconlibs: {},
editors: {},
languages: {},
resolvers: [],
custom_validators: []
};
JSONEditor.Validator = Class.extend({
init: function(jsoneditor,schema,options) {
this.jsoneditor = jsoneditor;
this.schema = schema || this.jsoneditor.schema;
this.options = options || {};
this.translate = this.jsoneditor.translate || JSONEditor.defaults.translate;
},
validate: function(value) {
return this._validateSchema(this.schema, value);
},
_validateSchema: function(schema,value,path) {
var self = this;
var errors = [];
var valid, i, j;
var stringified = JSON.stringify(value);
path = path || 'root';
// Work on a copy of the schema
schema = $extend({},this.jsoneditor.expandRefs(schema));
/*
* Type Agnostic Validation
*/
// Version 3 `required` and `required_by_default`
if(typeof value === "undefined") {
if((typeof schema.required !== "undefined" && schema.required === true) || (typeof schema.required === "undefined" && this.jsoneditor.options.required_by_default === true)) {
errors.push({
path: path,
property: 'required',
message: this.translate("error_notset")
});
}
return errors;
}
// `enum`
if(schema["enum"]) {
valid = false;
for(i=0; i<schema["enum"].length; i++) {
if(stringified === JSON.stringify(schema["enum"][i])) valid = true;
}
if(!valid) {
errors.push({
path: path,
property: 'enum',
message: this.translate("error_enum")
});
}
}
// `extends` (version 3)
if(schema["extends"]) {
for(i=0; i<schema["extends"].length; i++) {
errors = errors.concat(this._validateSchema(schema["extends"][i],value,path));
}
}
// `allOf`
if(schema.allOf) {
for(i=0; i<schema.allOf.length; i++) {
errors = errors.concat(this._validateSchema(schema.allOf[i],value,path));
}
}
// `anyOf`
if(schema.anyOf) {
valid = false;
for(i=0; i<schema.anyOf.length; i++) {
if(!this._validateSchema(schema.anyOf[i],value,path).length) {
valid = true;
break;
}
}
if(!valid) {
errors.push({
path: path,
property: 'anyOf',
message: this.translate('error_anyOf')
});
}
}
// `oneOf`
if(schema.oneOf) {
valid = 0;
var oneof_errors = [];
for(i=0; i<schema.oneOf.length; i++) {
// Set the error paths to be path.oneOf[i].rest.of.path
var tmp = this._validateSchema(schema.oneOf[i],value,path);
if(!tmp.length) {
valid++;
}
for(j=0; j<tmp.length; j++) {
tmp[j].path = path+'.oneOf['+i+']'+tmp[j].path.substr(path.length);
}
oneof_errors = oneof_errors.concat(tmp);
}
if(valid !== 1) {
errors.push({
path: path,
property: 'oneOf',
message: this.translate('error_oneOf', [valid])
});
errors = errors.concat(oneof_errors);
}
}
// `not`
if(schema.not) {
if(!this._validateSchema(schema.not,value,path).length) {
errors.push({
path: path,
property: 'not',
message: this.translate('error_not')
});
}
}
// `type` (both Version 3 and Version 4 support)
if(schema.type) {
// Union type
if(Array.isArray(schema.type)) {
valid = false;
for(i=0;i<schema.type.length;i++) {
if(this._checkType(schema.type[i], value)) {
valid = true;
break;
}
}
if(!valid) {
errors.push({
path: path,
property: 'type',
message: this.translate('error_type_union')
});
}
}
// Simple type
else {
if(!this._checkType(schema.type, value)) {
errors.push({
path: path,
property: 'type',
message: this.translate('error_type', [schema.type])
});
}
}
}
// `disallow` (version 3)
if(schema.disallow) {
// Union type
if(Array.isArray(schema.disallow)) {
valid = true;
for(i=0;i<schema.disallow.length;i++) {
if(this._checkType(schema.disallow[i], value)) {
valid = false;
break;
}
}
if(!valid) {
errors.push({
path: path,
property: 'disallow',
message: this.translate('error_disallow_union')
});
}
}
// Simple type
else {
if(this._checkType(schema.disallow, value)) {
errors.push({
path: path,
property: 'disallow',
message: this.translate('error_disallow', [schema.disallow])
});
}
}
}
/*
* Type Specific Validation
*/
// Number Specific Validation
if(typeof value === "number") {
// `multipleOf` and `divisibleBy`
if(schema.multipleOf || schema.divisibleBy) {
var divisor = schema.multipleOf || schema.divisibleBy;
// Vanilla JS, prone to floating point rounding errors (e.g. 1.14 / .01 == 113.99999)
valid = (value/divisor === Math.floor(value/divisor));
// Use math.js is available
if(window.math) {
valid = window.math.mod(window.math.bignumber(value), window.math.bignumber(divisor)).equals(0);
}
// Use decimal.js is available
else if(window.Decimal) {
valid = (new window.Decimal(value)).mod(new window.Decimal(divisor)).equals(0);
}
if(!valid) {
errors.push({
path: path,
property: schema.multipleOf? 'multipleOf' : 'divisibleBy',
message: this.translate('error_multipleOf', [divisor])
});
}
}
// `maximum`
if(schema.hasOwnProperty('maximum')) {
// Vanilla JS, prone to floating point rounding errors (e.g. .999999999999999 == 1)
valid = schema.exclusiveMaximum? (value < schema.maximum) : (value <= schema.maximum);
// Use math.js is available
if(window.math) {
valid = window.math[schema.exclusiveMaximum?'smaller':'smallerEq'](
window.math.bignumber(value),
window.math.bignumber(schema.maximum)
);
}
// Use Decimal.js if available
else if(window.Decimal) {
valid = (new window.Decimal(value))[schema.exclusiveMaximum?'lt':'lte'](new window.Decimal(schema.maximum));
}
if(!valid) {
errors.push({
path: path,
property: 'maximum',
message: this.translate(
(schema.exclusiveMaximum?'error_maximum_excl':'error_maximum_incl'),
[schema.maximum]
)
});
}
}
// `minimum`
if(schema.hasOwnProperty('minimum')) {
// Vanilla JS, prone to floating point rounding errors (e.g. .999999999999999 == 1)
valid = schema.exclusiveMinimum? (value > schema.minimum) : (value >= schema.minimum);
// Use math.js is available
if(window.math) {
valid = window.math[schema.exclusiveMinimum?'larger':'largerEq'](
window.math.bignumber(value),
window.math.bignumber(schema.minimum)
);
}
// Use Decimal.js if available
else if(window.Decimal) {
valid = (new window.Decimal(value))[schema.exclusiveMinimum?'gt':'gte'](new window.Decimal(schema.minimum));
}
if(!valid) {
errors.push({
path: path,
property: 'minimum',
message: this.translate(
(schema.exclusiveMinimum?'error_minimum_excl':'error_minimum_incl'),
[schema.minimum]
)
});
}
}
}
// String specific validation
else if(typeof value === "string") {
// `maxLength`
if(schema.maxLength) {
if((value+"").length > schema.maxLength) {
errors.push({
path: path,
property: 'maxLength',
message: this.translate('error_maxLength', [schema.maxLength])
});
}
}
// `minLength`
if(schema.minLength) {
if((value+"").length < schema.minLength) {
errors.push({
path: path,
property: 'minLength',
message: this.translate((schema.minLength===1?'error_notempty':'error_minLength'), [schema.minLength])
});
}
}
// `pattern`
if(schema.pattern) {
if(!(new RegExp(schema.pattern)).test(value)) {
errors.push({
path: path,
property: 'pattern',
message: this.translate('error_pattern', [schema.pattern])
});
}
}
}
// Array specific validation
else if(typeof value === "object" && value !== null && Array.isArray(value)) {
// `items` and `additionalItems`
if(schema.items) {
// `items` is an array
if(Array.isArray(schema.items)) {
for(i=0; i<value.length; i++) {
// If this item has a specific schema tied to it
// Validate against it
if(schema.items[i]) {
errors = errors.concat(this._validateSchema(schema.items[i],value[i],path+'.'+i));
}
// If all additional items are allowed
else if(schema.additionalItems === true) {
break;
}
// If additional items is a schema
// TODO: Incompatibility between version 3 and 4 of the spec
else if(schema.additionalItems) {
errors = errors.concat(this._validateSchema(schema.additionalItems,value[i],path+'.'+i));
}
// If no additional items are allowed
else if(schema.additionalItems === false) {
errors.push({
path: path,
property: 'additionalItems',
message: this.translate('error_additionalItems')
});
break;
}
// Default for `additionalItems` is an empty schema
else {
break;
}
}
}
// `items` is a schema
else {
// Each item in the array must validate against the schema
for(i=0; i<value.length; i++) {
errors = errors.concat(this._validateSchema(schema.items,value[i],path+'.'+i));
}
}
}
// `maxItems`
if(schema.maxItems) {
if(value.length > schema.maxItems) {
errors.push({
path: path,
property: 'maxItems',
message: this.translate('error_maxItems', [schema.maxItems])
});
}
}
// `minItems`
if(schema.minItems) {
if(value.length < schema.minItems) {
errors.push({
path: path,
property: 'minItems',
message: this.translate('error_minItems', [schema.minItems])
});
}
}
// `uniqueItems`
if(schema.uniqueItems) {
var seen = {};
for(i=0; i<value.length; i++) {
valid = JSON.stringify(value[i]);
if(seen[valid]) {
errors.push({
path: path,
property: 'uniqueItems',
message: this.translate('error_uniqueItems')
});
break;
}
seen[valid] = true;
}
}
}
// Object specific validation
else if(typeof value === "object" && value !== null) {
// `maxProperties`
if(schema.maxProperties) {
valid = 0;
for(i in value) {
if(!value.hasOwnProperty(i)) continue;
valid++;
}
if(valid > schema.maxProperties) {
errors.push({
path: path,
property: 'maxProperties',
message: this.translate('error_maxProperties', [schema.maxProperties])
});
}
}
// `minProperties`
if(schema.minProperties) {
valid = 0;
for(i in value) {
if(!value.hasOwnProperty(i)) continue;
valid++;
}
if(valid < schema.minProperties) {
errors.push({
path: path,
property: 'minProperties',
message: this.translate('error_minProperties', [schema.minProperties])
});
}
}
// Version 4 `required`
if(typeof schema.required !== "undefined" && Array.isArray(schema.required)) {
for(i=0; i<schema.required.length; i++) {
if(typeof value[schema.required[i]] === "undefined") {
errors.push({
path: path,
property: 'required',
message: this.translate('error_required', [schema.required[i]])
});
}
}
}
// `properties`
var validated_properties = {};
if(schema.properties) {
if(typeof schema.required !== "undefined" && Array.isArray(schema.required)) {
for(i=0; i<schema.required.length; i++) {
var property = schema.required[i];
validated_properties[property] = true;
errors = errors.concat(this._validateSchema(schema.properties[property],value[property],path+'.'+property));
}
} else {
for(i in schema.properties) {
if(!schema.properties.hasOwnProperty(i)) continue;
validated_properties[i] = true;
errors = errors.concat(this._validateSchema(schema.properties[i],value[i],path+'.'+i));
}
}
}
// `patternProperties`
if(schema.patternProperties) {
for(i in schema.patternProperties) {
if(!schema.patternProperties.hasOwnProperty(i)) continue;
var regex = new RegExp(i);
// Check which properties match
for(j in value) {
if(!value.hasOwnProperty(j)) continue;
if(regex.test(j)) {
validated_properties[j] = true;
errors = errors.concat(this._validateSchema(schema.patternProperties[i],value[j],path+'.'+j));
}
}
}
}
// The no_additional_properties option currently doesn't work with extended schemas that use oneOf or anyOf
if(typeof schema.additionalProperties === "undefined" && this.jsoneditor.options.no_additional_properties && !schema.oneOf && !schema.anyOf) {
schema.additionalProperties = false;
}
// `additionalProperties`
if(typeof schema.additionalProperties !== "undefined") {
for(i in value) {
if(!value.hasOwnProperty(i)) continue;
if(!validated_properties[i]) {
// No extra properties allowed
if(!schema.additionalProperties) {
errors.push({
path: path,
property: 'additionalProperties',
message: this.translate('error_additional_properties', [i])
});
break;
}
// Allowed
else if(schema.additionalProperties === true) {
break;
}
// Must match schema
// TODO: incompatibility between version 3 and 4 of the spec
else {
errors = errors.concat(this._validateSchema(schema.additionalProperties,value[i],path+'.'+i));
}
}
}
}
// `dependencies`
if(schema.dependencies) {
for(i in schema.dependencies) {
if(!schema.dependencies.hasOwnProperty(i)) continue;
// Doesn't need to meet the dependency
if(typeof value[i] === "undefined") continue;
// Property dependency
if(Array.isArray(schema.dependencies[i])) {
for(j=0; j<schema.dependencies[i].length; j++) {
if(typeof value[schema.dependencies[i][j]] === "undefined") {
errors.push({
path: path,
property: 'dependencies',
message: this.translate('error_dependency', [schema.dependencies[i][j]])
});
}
}
}
// Schema dependency
else {
errors = errors.concat(this._validateSchema(schema.dependencies[i],value,path));
}
}
}
}
// Custom type validation (global)
$each(JSONEditor.defaults.custom_validators,function(i,validator) {
errors = errors.concat(validator.call(self,schema,value,path));
});
// Custom type validation (instance specific)
if(this.options.custom_validators) {
$each(this.options.custom_validators,function(i,validator) {
errors = errors.concat(validator.call(self,schema,value,path));
});
}
return errors;
},
_checkType: function(type, value) {
// Simple types
if(typeof type === "string") {
if(type==="string") return typeof value === "string";
else if(type==="number") return typeof value === "number";
else if(type==="integer") return typeof value === "number" && value === Math.floor(value);
else if(type==="boolean") return typeof value === "boolean";
else if(type==="array") return Array.isArray(value);
else if(type === "object") return value !== null && !(Array.isArray(value)) && typeof value === "object";
else if(type === "null") return value === null;
else return true;
}
// Schema
else {
return !this._validateSchema(type,value).length;
}
}
});
/**
* All editors should extend from this class
*/
JSONEditor.AbstractEditor = Class.extend({
onChildEditorChange: function(editor) {
this.onChange(true);
},
notify: function() {
if(this.path) this.jsoneditor.notifyWatchers(this.path);
},
change: function() {
if(this.parent) this.parent.onChildEditorChange(this);
else if(this.jsoneditor) this.jsoneditor.onChange();
},
onChange: function(bubble) {
this.notify();
if(this.watch_listener) this.watch_listener();
if(bubble) this.change();
},
register: function() {
this.jsoneditor.registerEditor(this);
this.onChange();
},
unregister: function() {
if(!this.jsoneditor) return;
this.jsoneditor.unregisterEditor(this);
},
getNumColumns: function() {
return 12;
},
init: function(options) {
this.jsoneditor = options.jsoneditor;
this.theme = this.jsoneditor.theme;
this.template_engine = this.jsoneditor.template;
this.iconlib = this.jsoneditor.iconlib;
this.translate = this.jsoneditor.translate || JSONEditor.defaults.translate;
this.original_schema = options.schema;
this.schema = this.jsoneditor.expandSchema(this.original_schema);
this.options = $extend({}, (this.options || {}), (this.schema.options || {}), (options.schema.options || {}), options);
if(!options.path && !this.schema.id) this.schema.id = 'root';
this.path = options.path || 'root';
this.formname = options.formname || this.path.replace(/\.([^.]+)/g,'[$1]');
if(this.jsoneditor.options.form_name_root) this.formname = this.formname.replace(/^root\[/,this.jsoneditor.options.form_name_root+'[');
this.key = this.path.split('.').pop();
this.parent = options.parent;
this.link_watchers = [];
if(options.container) this.setContainer(options.container);
this.registerDependencies();
},
registerDependencies: function() {
this.dependenciesFulfilled = true;
var deps = this.options.dependencies;
if (!deps) {
return;
}
var self = this;
Object.keys(deps).forEach(function(dependency) {
var path = self.path.split('.');
path[path.length - 1] = dependency;
path = path.join('.');
var choices = deps[dependency];
self.jsoneditor.watch(path, function() {
self.checkDependency(path, choices);
});
});
},
checkDependency: function(path, choices) {
var wrapper = this.control || this.container;
if (this.path === path || !wrapper) {
return;
}
var self = this;
var editor = this.jsoneditor.getEditor(path);
var value = editor ? editor.getValue() : undefined;
var previousStatus = this.dependenciesFulfilled;
this.dependenciesFulfilled = false;
if (!editor || !editor.dependenciesFulfilled) {
this.dependenciesFulfilled = false;
} else if (Array.isArray(choices)) {
choices.some(function(choice) {
if (value === choice) {
self.dependenciesFulfilled = true;
return true;
}
});
} else if (typeof choices === 'object') {
if (typeof value !== 'object') {
this.dependenciesFulfilled = choices === value;
} else {
Object.keys(choices).some(function(key) {
if (!choices.hasOwnProperty(key)) {
return false;
}
if (!value.hasOwnProperty(key) || choices[key] !== value[key]) {
self.dependenciesFulfilled = false;
return true;
}
self.dependenciesFulfilled = true;
});
}
} else if (typeof choices === 'string' || typeof choices === 'number') {
this.dependenciesFulfilled = value === choices;
} else if (typeof choices === 'boolean') {
if (choices) {
this.dependenciesFulfilled = value && value.length > 0;
} else {
this.dependenciesFulfilled = !value || value.length === 0;
}
}
if (this.dependenciesFulfilled !== previousStatus) {
this.notify();
}
if (this.dependenciesFulfilled) {
wrapper.style.display = 'block';
} else {
wrapper.style.display = 'none';
}
},
setContainer: function(container) {
this.container = container;
if(this.schema.id) this.container.setAttribute('data-schemaid',this.schema.id);
if(this.schema.type && typeof this.schema.type === "string") this.container.setAttribute('data-schematype',this.schema.type);
this.container.setAttribute('data-schemapath',this.path);
},
preBuild: function() {
},
build: function() {
},
postBuild: function() {
this.setupWatchListeners();
this.addLinks();
this.setValue(this.getDefault(), true);
this.updateHeaderText();
this.register();
this.onWatchedFieldChange();
},
setupWatchListeners: function() {
var self = this;
// Watched fields
this.watched = {};
if(this.schema.vars) this.schema.watch = this.schema.vars;
this.watched_values = {};
this.watch_listener = function() {
if(self.refreshWatchedFieldValues()) {
self.onWatchedFieldChange();
}
};
if(this.schema.hasOwnProperty('watch')) {
var path,path_parts,first,root,adjusted_path;
for(var name in this.schema.watch) {
if(!this.schema.watch.hasOwnProperty(name)) continue;
path = this.schema.watch[name];
if(Array.isArray(path)) {
if(path.length<2) continue;
path_parts = [path[0]].concat(path[1].split('.'));
}
else {
path_parts = path.split('.');
if(!self.theme.closest(self.container,'[data-schemaid="'+path_parts[0]+'"]')) path_parts.unshift('#');
}
first = path_parts.shift();
if(first === '#') first = self.jsoneditor.schema.id || 'root';
// Find the root node for this template variable
root = self.theme.closest(self.container,'[data-schemaid="'+first+'"]');
if(!root) throw "Could not find ancestor node with id "+first;
// Keep track of the root node and path for use when rendering the template
adjusted_path = root.getAttribute('data-schemapath') + '.' + path_parts.join('.');
self.jsoneditor.watch(adjusted_path,self.watch_listener);
self.watched[name] = adjusted_path;
}
}
// Dynamic header
if(this.schema.headerTemplate) {
this.header_template = this.jsoneditor.compileTemplate(this.schema.headerTemplate, this.template_engine);
}
},
addLinks: function() {
// Add links
if(!this.no_link_holder) {
this.link_holder = this.theme.getLinksHolder();
this.container.appendChild(this.link_holder);
if(this.schema.links) {
for(var i=0; i<this.schema.links.length; i++) {
this.addLink(this.getLink(this.schema.links[i]));
}
}
}
},
getButton: function(text, icon, title) {
var btnClass = 'json-editor-btn-'+icon;
if(!this.iconlib) icon = null;
else icon = this.iconlib.getIcon(icon);
if(!icon && title) {
text = title;
title = null;
}
var btn = this.theme.getButton(text, icon, title);
btn.className += ' ' + btnClass + ' ';
return btn;
},
setButtonText: function(button, text, icon, title) {
if(!this.iconlib) icon = null;
else icon = this.iconlib.getIcon(icon);
if(!icon && title) {
text = title;
title = null;
}
return this.theme.setButtonText(button, text, icon, title);
},
addLink: function(link) {
if(this.link_holder) this.link_holder.appendChild(link);
},
getLink: function(data) {
var holder, link;
// Get mime type of the link
var mime = data.mediaType || 'application/javascript';
var type = mime.split('/')[0];
// Template to generate the link href
var href = this.jsoneditor.compileTemplate(data.href,this.template_engine);
var relTemplate = this.jsoneditor.compileTemplate(data.rel ? data.rel : data.href,this.template_engine);
// Template to generate the link's download attribute
var download = null;
if(data.download) download = data.download;
if(download && download !== true) {
download = this.jsoneditor.compileTemplate(download, this.template_engine);
}
// Image links
if(type === 'image') {
holder = this.theme.getBlockLinkHolder();
link = document.createElement('a');
link.setAttribute('target','_blank');
var image = document.createElement('img');
this.theme.createImageLink(holder,link,image);
// When a watched field changes, update the url
this.link_watchers.push(function(vars) {
var url = href(vars);
var rel = relTemplate(vars);
link.setAttribute('href',url);
link.setAttribute('title',rel || url);
image.setAttribute('src',url);
});
}
// Audio/Video links
else if(['audio','video'].indexOf(type) >=0) {
holder = this.theme.getBlockLinkHolder();
link = this.theme.getBlockLink();
link.setAttribute('target','_blank');
var media = document.createElement(type);
media.setAttribute('controls','controls');
this.theme.createMediaLink(holder,link,media);
// When a watched field changes, update the url
this.link_watchers.push(function(vars) {
var url = href(vars);
var rel = relTemplate(vars);
link.setAttribute('href',url);
link.textContent = rel || url;
media.setAttribute('src',url);
});
}
// Text links
else {
link = holder = this.theme.getBlockLink();
holder.setAttribute('target','_blank');
holder.textContent = data.rel;
// When a watched field changes, update the url
this.link_watchers.push(function(vars) {
var url = href(vars);
var rel = relTemplate(vars);
holder.setAttribute('href',url);
holder.textContent = rel || url;
});
}
if(download && link) {
if(download === true) {
link.setAttribute('download','');
}
else {
this.link_watchers.push(function(vars) {
link.setAttribute('download',download(vars));
});
}
}
if(data.class) link.className = link.className + ' ' + data.class;
return holder;
},
refreshWatchedFieldValues: function() {
if(!this.watched_values) return;
var watched = {};
var changed = false;
var self = this;
if(this.watched) {
var val,editor;
for(var name in this.watched) {
if(!this.watched.hasOwnProperty(name)) continue;
editor = self.jsoneditor.getEditor(this.watched[name]);
val = editor? editor.getValue() : null;
if(self.watched_values[name] !== val) changed = true;
watched[name] = val;
}
}
watched.self = this.getValue();
if(this.watched_values.self !== watched.self) changed = true;
this.watched_values = watched;
return changed;
},
getWatchedFieldValues: function() {
return this.watched_values;
},
updateHeaderText: function() {
if(this.header) {
// If the header has children, only update the text node's value
if(this.header.children.length) {
for(var i=0; i<this.header.childNodes.length; i++) {
if(this.header.childNodes[i].nodeType===3) {
this.header.childNodes[i].nodeValue = this.getHeaderText();
break;
}
}
}
// Otherwise, just update the entire node
else {
this.header.textContent = this.getHeaderText();
}
}
},
getHeaderText: function(title_only) {
if(this.header_text) return this.header_text;
else if(title_only) return this.schema.title;
else return this.getTitle();
},
onWatchedFieldChange: function() {
var vars;
if(this.header_template) {
vars = $extend(this.getWatchedFieldValues(),{
key: this.key,
i: this.key,
i0: (this.key*1),
i1: (this.key*1+1),
title: this.getTitle()
});
var header_text = this.header_template(vars);
if(header_text !== this.header_text) {
this.header_text = header_text;
this.updateHeaderText();
this.notify();
//this.fireChangeHeaderEvent();
}
}
if(this.link_watchers.length) {
vars = this.getWatchedFieldValues();
for(var i=0; i<this.link_watchers.length; i++) {
this.link_watchers[i](vars);
}
}
},
setValue: function(value) {
this.value = value;
},
getValue: function() {
if (!this.dependenciesFulfilled) {
return undefined;
}
return this.value;
},
refreshValue: function() {
},
getChildEditors: function() {
return false;
},
destroy: function() {
var self = this;
this.unregister(this);
$each(this.watched,function(name,adjusted_path) {
self.jsoneditor.unwatch(adjusted_path,self.watch_listener);
});
this.watched = null;
this.watched_values = null;
this.watch_listener = null;
this.header_text = null;
this.header_template = null;
this.value = null;
if(this.container && this.container.parentNode) this.container.parentNode.removeChild(this.container);
this.container = null;
this.jsoneditor = null;
this.schema = null;
this.path = null;
this.key = null;
this.parent = null;
},
getDefault: function() {
if(this.schema["default"]) return this.schema["default"];
if(this.schema["enum"]) return this.schema["enum"][0];
var type = this.schema.type || this.schema.oneOf;
if(type && Array.isArray(type)) type = type[0];
if(type && typeof type === "object") type = type.type;
if(type && Array.isArray(type)) type = type[0];
if(typeof type === "string") {
if(type === "number") return 0.0;
if(type === "boolean") return false;
if(type === "integer") return 0;
if(type === "string") return "";
if(type === "object") return {};
if(type === "array") return [];
}
return null;
},
getTitle: function() {
return this.schema.title || this.key;
},
enable: function() {
this.disabled = false;
},
disable: function() {
this.disabled = true;
},
isEnabled: function() {
return !this.disabled;
},
isRequired: function() {
if(typeof this.schema.required === "boolean") return this.schema.required;
else if(this.parent && this.parent.schema && Array.isArray(this.parent.schema.required)) return this.parent.schema.required.indexOf(this.key) > -1;
else if(this.jsoneditor.options.required_by_default) return true;
else return false;
},
getDisplayText: function(arr) {
var disp = [];
var used = {};
// Determine how many times each attribute name is used.
// This helps us pick the most distinct display text for the schemas.
$each(arr,function(i,el) {
if(el.title) {
used[el.title] = used[el.title] || 0;
used[el.title]++;
}
if(el.description) {
used[el.description] = used[el.description] || 0;
used[el.description]++;
}
if(el.format) {
used[el.format] = used[el.format] || 0;
used[el.format]++;
}
if(el.type) {
used[el.type] = used[el.type] || 0;
used[el.type]++;
}
});
// Determine display text for each element of the array
$each(arr,function(i,el) {
var name;
// If it's a simple string
if(typeof el === "string") name = el;
// Object
else if(el.title && used[el.title]<=1) name = el.title;
else if(el.format && used[el.format]<=1) name = el.format;
else if(el.type && used[el.type]<=1) name = el.type;
else if(el.description && used[el.description]<=1) name = el.descripton;
else if(el.title) name = el.title;
else if(el.format) name = el.format;
else if(el.type) name = el.type;
else if(el.description) name = el.description;
else if(JSON.stringify(el).length < 50) name = JSON.stringify(el);
else name = "type";
disp.push(name);
});
// Replace identical display text with "text 1", "text 2", etc.
var inc = {};
$each(disp,function(i,name) {
inc[name] = inc[name] || 0;
inc[name]++;
if(used[name] > 1) disp[i] = name + " " + inc[name];
});
return disp;
},
getOption: function(key) {
try {
throw "getOption is deprecated";
}
catch(e) {
window.console.error(e);
}
return this.options[key];
},
showValidationErrors: function(errors) {
}
});
JSONEditor.defaults.editors["null"] = JSONEditor.AbstractEditor.extend({
getValue: function() {
if (!this.dependenciesFulfilled) {
return undefined;
}
return null;
},
setValue: function() {
this.onChange();
},
getNumColumns: function() {
return 2;
}
});
JSONEditor.defaults.editors.string = JSONEditor.AbstractEditor.extend({
register: function() {
this._super();
if(!this.input) return;
this.input.setAttribute('name',this.formname);
},
unregister: function() {
this._super();
if(!this.input) return;
this.input.removeAttribute('name');
},
setValue: function(value,initial,from_template) {
var self = this;
if(this.template && !from_template) {
return;
}
if(value === null || typeof value === 'undefined') value = "";
else if(typeof value === "object") value = JSON.stringify(value);
else if(typeof value !== "string") value = ""+value;
if(value === this.serialized) return;
// Sanitize value before setting it
var sanitized = this.sanitize(value);
if(this.input.value === sanitized) {
return;
}
this.input.value = sanitized;
// If using SCEditor, update the WYSIWYG
if(this.sceditor_instance) {
this.sceditor_instance.val(sanitized);
}
else if(this.SimpleMDE) {
this.SimpleMDE.value(sanitized);
}
else if(this.ace_editor) {
this.ace_editor.setValue(sanitized);
}
var changed = from_template || this.getValue() !== value;
this.refreshValue();
if(initial) this.is_dirty = false;
else if(this.jsoneditor.options.show_errors === "change") this.is_dirty = true;
if(this.adjust_height) this.adjust_height(this.input);
// Bubble this setValue to parents if the value changed
this.onChange(changed);
},
getNumColumns: function() {
var min = Math.ceil(Math.max(this.getTitle().length,this.schema.maxLength||0,this.schema.minLength||0)/5);
var num;
if(this.input_type === 'textarea') num = 6;
else if(['text','email'].indexOf(this.input_type) >= 0) num = 4;
else num = 2;
return Math.min(12,Math.max(min,num));
},
build: function() {
var self = this, i;
if(!this.options.compact) this.header = this.label = this.theme.getFormInputLabel(this.getTitle());
if(this.schema.description) this.description = this.theme.getFormInputDescription(this.schema.description);
if(this.options.infoText) this.infoButton = this.theme.getInfoButton(this.options.infoText);
this.format = this.schema.format;
if(!this.format && this.schema.media && this.schema.media.type) {
this.format = this.schema.media.type.replace(/(^(application|text)\/(x-)?(script\.)?)|(-source$)/g,'');
}
if(!this.format && this.options.default_format) {
this.format = this.options.default_format;
}
if(this.options.format) {
this.format = this.options.format;
}
// Specific format
if(this.format) {
// Text Area
if(this.format === 'textarea') {
this.input_type = 'textarea';
this.input = this.theme.getTextareaInput();
}
// Range Input
else if(this.format === 'range') {
this.input_type = 'range';
var min = this.schema.minimum || 0;
var max = this.schema.maximum || Math.max(100,min+1);
var step = 1;
if(this.schema.multipleOf) {
if(min%this.schema.multipleOf) min = Math.ceil(min/this.schema.multipleOf)*this.schema.multipleOf;
if(max%this.schema.multipleOf) max = Math.floor(max/this.schema.multipleOf)*this.schema.multipleOf;
step = this.schema.multipleOf;
}
this.input = this.theme.getRangeInput(min,max,step);
}
// Source Code
else if([
'actionscript',
'batchfile',
'bbcode',
'c',
'c++',
'cpp',
'coffee',
'csharp',
'css',
'dart',
'django',
'ejs',
'erlang',
'golang',
'groovy',
'handlebars',
'haskell',
'haxe',
'html',
'ini',
'jade',
'java',
'javascript',
'json',
'less',
'lisp',
'lua',
'makefile',
'markdown',
'matlab',
'mysql',
'objectivec',
'pascal',
'perl',
'pgsql',
'php',
'python',
'r',
'ruby',
'sass',
'scala',
'scss',
'smarty',
'sql',
'stylus',
'svg',
'twig',
'vbscript',
'xml',
'yaml'
].indexOf(this.format) >= 0
) {
this.input_type = this.format;
this.source_code = true;
this.input = this.theme.getTextareaInput();
}
// HTML5 Input type
else {
this.input_type = this.format;
this.input = this.theme.getFormInputField(this.input_type);
}
}
// Normal text input
else {
this.input_type = 'text';
this.input = this.theme.getFormInputField(this.input_type);
}
// minLength, maxLength, and pattern
if(typeof this.schema.maxLength !== "undefined") this.input.setAttribute('maxlength',this.schema.maxLength);
if(typeof this.schema.pattern !== "undefined") this.input.setAttribute('pattern',this.schema.pattern);
else if(typeof this.schema.minLength !== "undefined") this.input.setAttribute('pattern','.{'+this.schema.minLength+',}');
if(this.options.compact) {
this.container.className += ' compact';
}
else {
if(this.options.input_width) this.input.style.width = this.options.input_width;
}
if(this.schema.readOnly || this.schema.readonly || this.schema.template) {
this.always_disabled = true;
this.input.disabled = true;
}
this.input
.addEventListener('change',function(e) {
e.preventDefault();
e.stopPropagation();
// Don't allow changing if this field is a template
if(self.schema.template) {
this.value = self.value;
return;
}
var val = this.value;
// sanitize value
var sanitized = self.sanitize(val);
if(val !== sanitized) {
this.value = sanitized;
}
self.is_dirty = true;
self.refreshValue();
self.onChange(true);
});
if(this.options.input_height) this.input.style.height = this.options.input_height;
if(this.options.expand_height) {
this.adjust_height = function(el) {
if(!el) return;
var i, ch=el.offsetHeight;
// Input too short
if(el.offsetHeight < el.scrollHeight) {
i=0;
while(el.offsetHeight < el.scrollHeight+3) {
if(i>100) break;
i++;
ch++;
el.style.height = ch+'px';
}
}
else {
i=0;
while(el.offsetHeight >= el.scrollHeight+3) {
if(i>100) break;
i++;
ch--;
el.style.height = ch+'px';
}
el.style.height = (ch+1)+'px';
}
};
this.input.addEventListener('keyup',function(e) {
self.adjust_height(this);
});
this.input.addEventListener('change',function(e) {
self.adjust_height(this);
});
this.adjust_height();
}
if(this.format) this.input.setAttribute('data-schemaformat',this.format);
this.control = this.theme.getFormControl(this.label, this.input, this.description, this.infoButton);
this.container.appendChild(this.control);
// Any special formatting that needs to happen after the input is added to the dom
window.requestAnimationFrame(function() {
// Skip in case the input is only a temporary editor,
// otherwise, in the case of an ace_editor creation,
// it will generate an error trying to append it to the missing parentNode
if(self.input.parentNode) self.afterInputReady();
if(self.adjust_height) self.adjust_height(self.input);
});
// Compile and store the template
if(this.schema.template) {
this.template = this.jsoneditor.compileTemplate(this.schema.template, this.template_engine);
this.refreshValue();
}
else {
this.refreshValue();
}
},
enable: function() {
if(!this.always_disabled) {
this.input.disabled = false;
// TODO: WYSIWYG and Markdown editors
this._super();
}
},
disable: function(always_disabled) {
if(always_disabled) this.always_disabled = true;
this.input.disabled = true;
// TODO: WYSIWYG and Markdown editors
this._super();
},
afterInputReady: function() {
var self = this, options;
// Code editor
if(this.source_code) {
// WYSIWYG html and bbcode editor
if(this.options.wysiwyg &&
['html','bbcode'].indexOf(this.input_type) >= 0 &&
window.jQuery && window.jQuery.fn && window.jQuery.fn.sceditor
) {
options = $extend({},{
plugins: self.input_type==='html'? 'xhtml' : 'bbcode',
emoticonsEnabled: false,
width: '100%',
height: 300
},JSONEditor.plugins.sceditor,self.options.sceditor_options||{});
window.jQuery(self.input).sceditor(options);
self.sceditor_instance = window.jQuery(self.input).sceditor('instance');
self.sceditor_instance.blur(function() {
// Get editor's value
var val = window.jQuery("<div>"+self.sceditor_instance.val()+"</div>");
// Remove sceditor spans/divs
window.jQuery('#sceditor-start-marker,#sceditor-end-marker,.sceditor-nlf',val).remove();
// Set the value and update
self.input.value = val.html();
self.value = self.input.value;
self.is_dirty = true;
self.onChange(true);
});
}
// SimpleMDE for markdown (if it's loaded)
else if (this.input_type === 'markdown' && window.SimpleMDE) {
options = $extend({},JSONEditor.plugins.SimpleMDE,{
element: this.input
});
this.SimpleMDE = new window.SimpleMDE((options));
this.SimpleMDE.codemirror.on("change",function() {
self.value = self.SimpleMDE.value();
self.is_dirty = true;
self.onChange(true);
});
}
// ACE editor for everything else
else if(window.ace) {
var mode = this.input_type;
// aliases for c/cpp
if(mode === 'cpp' || mode === 'c++' || mode === 'c') {
mode = 'c_cpp';
}
this.ace_container = document.createElement('div');
this.ace_container.style.width = '100%';
this.ace_container.style.position = 'relative';
this.ace_container.style.height = '400px';
this.input.parentNode.insertBefore(this.ace_container,this.input);
this.input.style.display = 'none';
this.ace_editor = window.ace.edit(this.ace_container);
this.ace_editor.setValue(this.getValue());
// The theme
if(JSONEditor.plugins.ace.theme) this.ace_editor.setTheme('ace/theme/'+JSONEditor.plugins.ace.theme);
// The mode
mode = window.ace.require("ace/mode/"+mode);
if(mode) this.ace_editor.getSession().setMode(new mode.Mode());
// Listen for changes
this.ace_editor.on('change',function() {
var val = self.ace_editor.getValue();
self.input.value = val;
self.refreshValue();
self.is_dirty = true;
self.onChange(true);
});
}
}
self.theme.afterInputReady(self.input);
},
refreshValue: function() {
this.value = this.input.value;
if(typeof this.value !== "string") this.value = '';
this.serialized = this.value;
},
destroy: function() {
// If using SCEditor, destroy the editor instance
if(this.sceditor_instance) {
this.sceditor_instance.destroy();
}
else if(this.SimpleMDE) {
this.SimpleMDE.destroy();
}
else if(this.ace_editor) {
this.ace_editor.destroy();
}
this.template = null;
if(this.input && this.input.parentNode) this.input.parentNode.removeChild(this.input);
if(this.label && this.label.parentNode) this.label.parentNode.removeChild(this.label);
if(this.description && this.description.parentNode) this.description.parentNode.removeChild(this.description);
this._super();
},
/**
* This is overridden in derivative editors
*/
sanitize: function(value) {
return value;
},
/**
* Re-calculates the value if needed
*/
onWatchedFieldChange: function() {
var self = this, vars, j;
// If this editor needs to be rendered by a macro template
if(this.template) {
vars = this.getWatchedFieldValues();
this.setValue(this.template(vars),false,true);
}
this._super();
},
showValidationErrors: function(errors) {
var self = this;
if(this.jsoneditor.options.show_errors === "always") {}
else if(!this.is_dirty && this.previous_error_setting===this.jsoneditor.options.show_errors) return;
this.previous_error_setting = this.jsoneditor.options.show_errors;
var messages = [];
$each(errors,function(i,error) {
if(error.path === self.path) {
messages.push(error.message);
}
});
if(messages.length) {
this.theme.addInputError(this.input, messages.join('. ')+'.');
}
else {
this.theme.removeInputError(this.input);
}
}
});
/**
* Created by Mehmet Baker on 12.04.2017
*/
JSONEditor.defaults.editors.hidden = JSONEditor.AbstractEditor.extend({
register: function () {
this._super();
if (!this.input) return;
this.input.setAttribute('name', this.formname);
},
unregister: function () {
this._super();
if (!this.input) return;
this.input.removeAttribute('name');
},
setValue: function (value, initial, from_template) {
var self = this;
if(this.template && !from_template) {
return;
}
if(value === null || typeof value === 'undefined') value = "";
else if(typeof value === "object") value = JSON.stringify(value);
else if(typeof value !== "string") value = ""+value;
if(value === this.serialized) return;
// Sanitize value before setting it
var sanitized = this.sanitize(value);
if(this.input.value === sanitized) {
return;
}
this.input.value = sanitized;
var changed = from_template || this.getValue() !== value;
this.refreshValue();
if(initial) this.is_dirty = false;
else if(this.jsoneditor.options.show_errors === "change") this.is_dirty = true;
if(this.adjust_height) this.adjust_height(this.input);
// Bubble this setValue to parents if the value changed
this.onChange(changed);
},
getNumColumns: function () {
return 2;
},
enable: function () {
this._super();
},
disable: function () {
this._super();
},
refreshValue: function () {
this.value = this.input.value;
if (typeof this.value !== "string") this.value = '';
this.serialized = this.value;
},
destroy: function () {
this.template = null;
if (this.input && this.input.parentNode) this.input.parentNode.removeChild(this.input);
if (this.label && this.label.parentNode) this.label.parentNode.removeChild(this.label);
if (this.description && this.description.parentNode) this.description.parentNode.removeChild(this.description);
this._super();
},
/**
* This is overridden in derivative editors
*/
sanitize: function (value) {
return value;
},
/**
* Re-calculates the value if needed
*/
onWatchedFieldChange: function () {
var self = this, vars, j;
// If this editor needs to be rendered by a macro template
if (this.template) {
vars = this.getWatchedFieldValues();
this.setValue(this.template(vars), false, true);
}
this._super();
},
build: function () {
var self = this;
this.format = this.schema.format;
if (!this.format && this.options.default_format) {
this.format = this.options.default_format;
}
if (this.options.format) {
this.format = this.options.format;
}
this.input_type = 'hidden';
this.input = this.theme.getFormInputField(this.input_type);
if (this.format) this.input.setAttribute('data-schemaformat', this.format);
this.container.appendChild(this.input);
// Compile and store the template
if (this.schema.template) {
this.template = this.jsoneditor.compileTemplate(this.schema.template, this.template_engine);
this.refreshValue();
}
else {
this.refreshValue();
}
}
});
JSONEditor.defaults.editors.number = JSONEditor.defaults.editors.string.extend({
build: function() {
this._super();
if (typeof this.schema.minimum !== "undefined") {
var minimum = this.schema.minimum;
if (typeof this.schema.exclusiveMinimum !== "undefined") {
minimum += 1;
}
this.input.setAttribute("min", minimum);
}
if (typeof this.schema.maximum !== "undefined") {
var maximum = this.schema.maximum;
if (typeof this.schema.exclusiveMaximum !== "undefined") {
maximum -= 1;
}
this.input.setAttribute("max", maximum);
}
},
sanitize: function(value) {
return (value+"").replace(/[^0-9\.\-eE]/g,'');
},
getNumColumns: function() {
return 2;
},
getValue: function() {
if (!this.dependenciesFulfilled) {
return undefined;
}
return this.value===''?undefined:this.value*1;
}
});
JSONEditor.defaults.editors.integer = JSONEditor.defaults.editors.number.extend({
sanitize: function(value) {
value = value + "";
return value.replace(/[^0-9\-]/g,'');
},
getNumColumns: function() {
return 2;
}
});
JSONEditor.defaults.editors.rating = JSONEditor.defaults.editors.integer.extend({
build: function() {
var self = this, i;
if(!this.options.compact) this.header = this.label = this.theme.getFormInputLabel(this.getTitle());
if(this.schema.description) this.description = this.theme.getFormInputDescription(this.schema.description);
// Dynamically add the required CSS the first time this editor is used
var styleId = 'json-editor-style-rating';
var styles = document.getElementById(styleId);
if (!styles) {
var style = document.createElement('style');
style.id = styleId;
style.type = 'text/css';
style.innerHTML =
' .rating-container {' +
' display: inline-block;' +
' clear: both;' +
' }' +
' ' +
' .rating {' +
' float:left;' +
' }' +
' ' +
' /* :not(:checked) is a filter, so that browsers that don’t support :checked don’t' +
' follow these rules. Every browser that supports :checked also supports :not(), so' +
' it doesn’t make the test unnecessarily selective */' +
' .rating:not(:checked) > input {' +
' position:absolute;' +
' top:-9999px;' +
' clip:rect(0,0,0,0);' +
' }' +
' ' +
' .rating:not(:checked) > label {' +
' float:right;' +
' width:1em;' +
' padding:0 .1em;' +
' overflow:hidden;' +
' white-space:nowrap;' +
' cursor:pointer;' +
' color:#ddd;' +
' }' +
' ' +
' .rating:not(:checked) > label:before {' +
' content: \'★ \';' +
' }' +
' ' +
' .rating > input:checked ~ label {' +
' color: #FFB200;' +
' }' +
' ' +
' .rating:not([readOnly]):not(:checked) > label:hover,' +
' .rating:not([readOnly]):not(:checked) > label:hover ~ label {' +
' color: #FFDA00;' +
' }' +
' ' +
' .rating:not([readOnly]) > input:checked + label:hover,' +
' .rating:not([readOnly]) > input:checked + label:hover ~ label,' +
' .rating:not([readOnly]) > input:checked ~ label:hover,' +
' .rating:not([readOnly]) > input:checked ~ label:hover ~ label,' +
' .rating:not([readOnly]) > label:hover ~ input:checked ~ label {' +
' color: #FF8C0D;' +
' }' +
' ' +
' .rating:not([readOnly]) > label:active {' +
' position:relative;' +
' top:2px;' +
' left:2px;' +
' }';
document.getElementsByTagName('head')[0].appendChild(style);
}
this.input = this.theme.getFormInputField('hidden');
this.container.appendChild(this.input);
// Required to keep height
var ratingContainer = document.createElement('div');
ratingContainer.className = 'rating-container';
// Contains options for rating
var group = document.createElement('div');
group.setAttribute('name', this.formname);
group.className = 'rating';
ratingContainer.appendChild(group);
if(this.options.compact) this.container.setAttribute('class',this.container.getAttribute('class')+' compact');
var max = this.schema.maximum ? this.schema.maximum : 5;
if (this.schema.exclusiveMaximum) max--;
this.inputs = [];
for(i=max; i>0; i--) {
var id = this.formname + i;
var radioInput = this.theme.getFormInputField('radio');
radioInput.setAttribute('id', id);
radioInput.setAttribute('value', i);
radioInput.setAttribute('name', this.formname);
group.appendChild(radioInput);
this.inputs.push(radioInput);
var label = document.createElement('label');
label.setAttribute('for', id);
label.appendChild(document.createTextNode(i + (i == 1 ? ' star' : ' stars')));
group.appendChild(label);
}
if(this.schema.readOnly || this.schema.readonly) {
this.always_disabled = true;
$each(this.inputs,function(i,input) {
group.setAttribute("readOnly", "readOnly");
input.disabled = true;
});
}
ratingContainer
.addEventListener('change',function(e) {
e.preventDefault();
e.stopPropagation();
self.input.value = e.srcElement.value;
self.is_dirty = true;
self.refreshValue();
self.watch_listener();
self.jsoneditor.notifyWatchers(self.path);
if(self.parent) self.parent.onChildEditorChange(self);
else self.jsoneditor.onChange();
});
this.control = this.theme.getFormControl(this.label, ratingContainer, this.description);
this.container.appendChild(this.control);
this.refreshValue();
},
setValue: function(val) {
var sanitized = this.sanitize(val);
if(this.value === sanitized) {
return;
}
var self = this;
$each(this.inputs,function(i,input) {
if (input.value === sanitized) {
input.checked = true;
self.value = sanitized;
self.input.value = self.value;
self.watch_listener();
self.jsoneditor.notifyWatchers(self.path);
return false;
}
});
}
});
JSONEditor.defaults.editors.object = JSONEditor.AbstractEditor.extend({
getDefault: function() {
return $extend({},this.schema["default"] || {});
},
getChildEditors: function() {
return this.editors;
},
register: function() {
this._super();
if(this.editors) {
for(var i in this.editors) {
if(!this.editors.hasOwnProperty(i)) continue;
this.editors[i].register();
}
}
},
unregister: function() {
this._super();
if(this.editors) {
for(var i in this.editors) {
if(!this.editors.hasOwnProperty(i)) continue;
this.editors[i].unregister();
}
}
},
getNumColumns: function() {
return Math.max(Math.min(12,this.maxwidth),3);
},
enable: function() {
if(!this.always_disabled) {
if(this.editjson_button) this.editjson_button.disabled = false;
if(this.addproperty_button) this.addproperty_button.disabled = false;
this._super();
if(this.editors) {
for(var i in this.editors) {
if(!this.editors.hasOwnProperty(i)) continue;
this.editors[i].enable();
}
}
}
},
disable: function(always_disabled) {
if(always_disabled) this.always_disabled = true;
if(this.editjson_button) this.editjson_button.disabled = true;
if(this.addproperty_button) this.addproperty_button.disabled = true;
this.hideEditJSON();
this._super();
if(this.editors) {
for(var i in this.editors) {
if(!this.editors.hasOwnProperty(i)) continue;
this.editors[i].disable(always_disabled);
}
}
},
layoutEditors: function() {
var self = this, i, j;
if(!this.row_container) return;
// Sort editors by propertyOrder
this.property_order = Object.keys(this.editors);
this.property_order = this.property_order.sort(function(a,b) {
var ordera = self.editors[a].schema.propertyOrder;
var orderb = self.editors[b].schema.propertyOrder;
if(typeof ordera !== "number") ordera = 1000;
if(typeof orderb !== "number") orderb = 1000;
return ordera - orderb;
});
var container;
if(this.format === 'grid') {
var rows = [];
$each(this.property_order, function(j,key) {
var editor = self.editors[key];
if(editor.property_removed) return;
var found = false;
var width = editor.options.hidden? 0 : (editor.options.grid_columns || editor.getNumColumns());
var height = editor.options.hidden? 0 : editor.container.offsetHeight;
// See if the editor will fit in any of the existing rows first
for(var i=0; i<rows.length; i++) {
// If the editor will fit in the row horizontally
if(rows[i].width + width <= 12) {
// If the editor is close to the other elements in height
// i.e. Don't put a really tall editor in an otherwise short row or vice versa
if(!height || (rows[i].minh*0.5 < height && rows[i].maxh*2 > height)) {
found = i;
}
}
}
// If there isn't a spot in any of the existing rows, start a new row
if(found === false) {
rows.push({
width: 0,
minh: 999999,
maxh: 0,
editors: []
});
found = rows.length-1;
}
rows[found].editors.push({
key: key,
//editor: editor,
width: width,
height: height
});
rows[found].width += width;
rows[found].minh = Math.min(rows[found].minh,height);
rows[found].maxh = Math.max(rows[found].maxh,height);
});
// Make almost full rows width 12
// Do this by increasing all editors' sizes proprotionately
// Any left over space goes to the biggest editor
// Don't touch rows with a width of 6 or less
for(i=0; i<rows.length; i++) {
if(rows[i].width < 12) {
var biggest = false;
var new_width = 0;
for(j=0; j<rows[i].editors.length; j++) {
if(biggest === false) biggest = j;
else if(rows[i].editors[j].width > rows[i].editors[biggest].width) biggest = j;
rows[i].editors[j].width *= 12/rows[i].width;
rows[i].editors[j].width = Math.floor(rows[i].editors[j].width);
new_width += rows[i].editors[j].width;
}
if(new_width < 12) rows[i].editors[biggest].width += 12-new_width;
rows[i].width = 12;
}
}
// layout hasn't changed
if(this.layout === JSON.stringify(rows)) return false;
this.layout = JSON.stringify(rows);
// Layout the form
container = document.createElement('div');
for(i=0; i<rows.length; i++) {
var row = this.theme.getGridRow();
container.appendChild(row);
for(j=0; j<rows[i].editors.length; j++) {
var key = rows[i].editors[j].key;
var editor = this.editors[key];
if(editor.options.hidden) editor.container.style.display = 'none';
else this.theme.setGridColumnSize(editor.container,rows[i].editors[j].width);
row.appendChild(editor.container);
}
}
}
// Normal layout
else {
container = document.createElement('div');
$each(this.property_order, function(i,key) {
var editor = self.editors[key];
if(editor.property_removed) return;
var row = self.theme.getGridRow();
container.appendChild(row);
if(editor.options.hidden) editor.container.style.display = 'none';
else self.theme.setGridColumnSize(editor.container,12);
row.appendChild(editor.container);
});
}
while (this.row_container.firstChild) {
this.row_container.removeChild(this.row_container.firstChild);
}
this.row_container.appendChild(container);
},
getPropertySchema: function(key) {
// Schema declared directly in properties
var schema = this.schema.properties[key] || {};
schema = $extend({},schema);
var matched = this.schema.properties[key]? true : false;
// Any matching patternProperties should be merged in
if(this.schema.patternProperties) {
for(var i in this.schema.patternProperties) {
if(!this.schema.patternProperties.hasOwnProperty(i)) continue;
var regex = new RegExp(i);
if(regex.test(key)) {
schema.allOf = schema.allOf || [];
schema.allOf.push(this.schema.patternProperties[i]);
matched = true;
}
}
}
// Hasn't matched other rules, use additionalProperties schema
if(!matched && this.schema.additionalProperties && typeof this.schema.additionalProperties === "object") {
schema = $extend({},this.schema.additionalProperties);
}
return schema;
},
preBuild: function() {
this._super();
this.editors = {};
this.cached_editors = {};
var self = this;
this.format = this.options.layout || this.options.object_layout || this.schema.format || this.jsoneditor.options.object_layout || 'normal';
this.schema.properties = this.schema.properties || {};
this.minwidth = 0;
this.maxwidth = 0;
// If the object should be rendered as a table row
if(this.options.table_row) {
$each(this.schema.properties, function(key,schema) {
var editor = self.jsoneditor.getEditorClass(schema);
self.editors[key] = self.jsoneditor.createEditor(editor,{
jsoneditor: self.jsoneditor,
schema: schema,
path: self.path+'.'+key,
parent: self,
compact: true,
required: true
});
self.editors[key].preBuild();
var width = self.editors[key].options.hidden? 0 : (self.editors[key].options.grid_columns || self.editors[key].getNumColumns());
self.minwidth += width;
self.maxwidth += width;
});
this.no_link_holder = true;
}
// If the object should be rendered as a table
else if(this.options.table) {
// TODO: table display format
throw "Not supported yet";
}
// If the object should be rendered as a div
else {
if(!this.schema.defaultProperties) {
if(this.jsoneditor.options.display_required_only || this.options.display_required_only) {
this.schema.defaultProperties = [];
$each(this.schema.properties, function(k,s) {
if(self.isRequired({key: k, schema: s})) {
self.schema.defaultProperties.push(k);
}
});
}
else {
self.schema.defaultProperties = Object.keys(self.schema.properties);
}
}
// Increase the grid width to account for padding
self.maxwidth += 1;
$each(this.schema.defaultProperties, function(i,key) {
self.addObjectProperty(key, true);
if(self.editors[key]) {
self.minwidth = Math.max(self.minwidth,(self.editors[key].options.grid_columns || self.editors[key].getNumColumns()));
self.maxwidth += (self.editors[key].options.grid_columns || self.editors[key].getNumColumns());
}
});
}
// Sort editors by propertyOrder
this.property_order = Object.keys(this.editors);
this.property_order = this.property_order.sort(function(a,b) {
var ordera = self.editors[a].schema.propertyOrder;
var orderb = self.editors[b].schema.propertyOrder;
if(typeof ordera !== "number") ordera = 1000;
if(typeof orderb !== "number") orderb = 1000;
return ordera - orderb;
});
},
build: function() {
var self = this;
// If the object should be rendered as a table row
if(this.options.table_row) {
this.editor_holder = this.container;
$each(this.editors, function(key,editor) {
var holder = self.theme.getTableCell();
self.editor_holder.appendChild(holder);
editor.setContainer(holder);
editor.build();
editor.postBuild();
if(self.editors[key].options.hidden) {
holder.style.display = 'none';
}
if(self.editors[key].options.input_width) {
holder.style.width = self.editors[key].options.input_width;
}
});
}
// If the object should be rendered as a table
else if(this.options.table) {
// TODO: table display format
throw "Not supported yet";
}
// If the object should be rendered as a div
else {
this.header = document.createElement('span');
this.header.textContent = this.getTitle();
this.title = this.theme.getHeader(this.header);
this.container.appendChild(this.title);
this.container.style.position = 'relative';
// Edit JSON modal
this.editjson_holder = this.theme.getModal();
this.editjson_textarea = this.theme.getTextareaInput();
this.editjson_textarea.style.height = '170px';
this.editjson_textarea.style.width = '300px';
this.editjson_textarea.style.display = 'block';
this.editjson_save = this.getButton('Save','save','Save');
this.editjson_save.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
self.saveJSON();
});
this.editjson_cancel = this.getButton('Cancel','cancel','Cancel');
this.editjson_cancel.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
self.hideEditJSON();
});
this.editjson_holder.appendChild(this.editjson_textarea);
this.editjson_holder.appendChild(this.editjson_save);
this.editjson_holder.appendChild(this.editjson_cancel);
// Manage Properties modal
this.addproperty_holder = this.theme.getModal();
this.addproperty_list = document.createElement('div');
this.addproperty_list.style.width = '295px';
this.addproperty_list.style.maxHeight = '160px';
this.addproperty_list.style.padding = '5px 0';
this.addproperty_list.style.overflowY = 'auto';
this.addproperty_list.style.overflowX = 'hidden';
this.addproperty_list.style.paddingLeft = '5px';
this.addproperty_list.setAttribute('class', 'property-selector');
this.addproperty_add = this.getButton('add','add','add');
this.addproperty_input = this.theme.getFormInputField('text');
this.addproperty_input.setAttribute('placeholder','Property name...');
this.addproperty_input.style.width = '220px';
this.addproperty_input.style.marginBottom = '0';
this.addproperty_input.style.display = 'inline-block';
this.addproperty_add.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
if(self.addproperty_input.value) {
if(self.editors[self.addproperty_input.value]) {
window.alert('there is already a property with that name');
return;
}
self.addObjectProperty(self.addproperty_input.value);
if(self.editors[self.addproperty_input.value]) {
self.editors[self.addproperty_input.value].disable();
}
self.onChange(true);
}
});
this.addproperty_holder.appendChild(this.addproperty_list);
this.addproperty_holder.appendChild(this.addproperty_input);
this.addproperty_holder.appendChild(this.addproperty_add);
var spacer = document.createElement('div');
spacer.style.clear = 'both';
this.addproperty_holder.appendChild(spacer);
// Description
if(this.schema.description) {
this.description = this.theme.getDescription(this.schema.description);
this.container.appendChild(this.description);
}
// Validation error placeholder area
this.error_holder = document.createElement('div');
this.container.appendChild(this.error_holder);
// Container for child editor area
this.editor_holder = this.theme.getIndentedPanel();
this.container.appendChild(this.editor_holder);
// Container for rows of child editors
this.row_container = this.theme.getGridContainer();
this.editor_holder.appendChild(this.row_container);
$each(this.editors, function(key,editor) {
var holder = self.theme.getGridColumn();
self.row_container.appendChild(holder);
editor.setContainer(holder);
editor.build();
editor.postBuild();
});
// Control buttons
this.title_controls = this.theme.getHeaderButtonHolder();
this.editjson_controls = this.theme.getHeaderButtonHolder();
this.addproperty_controls = this.theme.getHeaderButtonHolder();
this.title.appendChild(this.title_controls);
this.title.appendChild(this.editjson_controls);
this.title.appendChild(this.addproperty_controls);
// Show/Hide button
this.collapsed = false;
this.toggle_button = this.getButton('', 'collapse', this.translate('button_collapse'));
this.title_controls.appendChild(this.toggle_button);
this.toggle_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
if(self.collapsed) {
self.editor_holder.style.display = '';
self.collapsed = false;
self.setButtonText(self.toggle_button,'','collapse',self.translate('button_collapse'));
}
else {
self.editor_holder.style.display = 'none';
self.collapsed = true;
self.setButtonText(self.toggle_button,'','expand',self.translate('button_expand'));
}
});
// If it should start collapsed
if(this.options.collapsed) {
$trigger(this.toggle_button,'click');
}
// Collapse button disabled
if(this.schema.options && typeof this.schema.options.disable_collapse !== "undefined") {
if(this.schema.options.disable_collapse) this.toggle_button.style.display = 'none';
}
else if(this.jsoneditor.options.disable_collapse) {
this.toggle_button.style.display = 'none';
}
// Edit JSON Button
this.editjson_button = this.getButton('JSON','edit','Edit JSON');
this.editjson_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
self.toggleEditJSON();
});
this.editjson_controls.appendChild(this.editjson_button);
this.editjson_controls.appendChild(this.editjson_holder);
// Edit JSON Buttton disabled
if(this.schema.options && typeof this.schema.options.disable_edit_json !== "undefined") {
if(this.schema.options.disable_edit_json) this.editjson_button.style.display = 'none';
}
else if(this.jsoneditor.options.disable_edit_json) {
this.editjson_button.style.display = 'none';
}
// Object Properties Button
this.addproperty_button = this.getButton('Properties','edit','Object Properties');
this.addproperty_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
self.toggleAddProperty();
});
this.addproperty_controls.appendChild(this.addproperty_button);
this.addproperty_controls.appendChild(this.addproperty_holder);
this.refreshAddProperties();
}
// Fix table cell ordering
if(this.options.table_row) {
this.editor_holder = this.container;
$each(this.property_order,function(i,key) {
self.editor_holder.appendChild(self.editors[key].container);
});
}
// Layout object editors in grid if needed
else {
// Initial layout
this.layoutEditors();
// Do it again now that we know the approximate heights of elements
this.layoutEditors();
}
},
showEditJSON: function() {
if(!this.editjson_holder) return;
this.hideAddProperty();
// Position the form directly beneath the button
// TODO: edge detection
this.editjson_holder.style.left = this.editjson_button.offsetLeft+"px";
this.editjson_holder.style.top = this.editjson_button.offsetTop + this.editjson_button.offsetHeight+"px";
// Start the textarea with the current value
this.editjson_textarea.value = JSON.stringify(this.getValue(),null,2);
// Disable the rest of the form while editing JSON
this.disable();
this.editjson_holder.style.display = '';
this.editjson_button.disabled = false;
this.editing_json = true;
},
hideEditJSON: function() {
if(!this.editjson_holder) return;
if(!this.editing_json) return;
this.editjson_holder.style.display = 'none';
this.enable();
this.editing_json = false;
},
saveJSON: function() {
if(!this.editjson_holder) return;
try {
var json = JSON.parse(this.editjson_textarea.value);
this.setValue(json);
this.hideEditJSON();
}
catch(e) {
window.alert('invalid JSON');
throw e;
}
},
toggleEditJSON: function() {
if(this.editing_json) this.hideEditJSON();
else this.showEditJSON();
},
insertPropertyControlUsingPropertyOrder: function (property, control, container) {
var propertyOrder;
if (this.schema.properties[property])
propertyOrder = this.schema.properties[property].propertyOrder;
if (typeof propertyOrder !== "number") propertyOrder = 1000;
control.propertyOrder = propertyOrder;
for (var i = 0; i < container.childNodes.length; i++) {
var child = container.childNodes[i];
if (control.propertyOrder < child.propertyOrder) {
this.addproperty_list.insertBefore(control, child);
control = null;
break;
}
}
if (control) {
this.addproperty_list.appendChild(control);
}
},
addPropertyCheckbox: function(key) {
var self = this;
var checkbox, label, labelText, control;
checkbox = self.theme.getCheckbox();
checkbox.style.width = 'auto';
if (this.schema.properties[key] && this.schema.properties[key].title)
labelText = this.schema.properties[key].title;
else
labelText = key;
label = self.theme.getCheckboxLabel(labelText);
control = self.theme.getFormControl(label,checkbox);
control.style.paddingBottom = control.style.marginBottom = control.style.paddingTop = control.style.marginTop = 0;
control.style.height = 'auto';
//control.style.overflowY = 'hidden';
this.insertPropertyControlUsingPropertyOrder(key, control, this.addproperty_list);
checkbox.checked = key in this.editors;
checkbox.addEventListener('change',function() {
if(checkbox.checked) {
self.addObjectProperty(key);
}
else {
self.removeObjectProperty(key);
}
self.onChange(true);
});
self.addproperty_checkboxes[key] = checkbox;
return checkbox;
},
showAddProperty: function() {
if(!this.addproperty_holder) return;
this.hideEditJSON();
// Position the form directly beneath the button
// TODO: edge detection
this.addproperty_holder.style.left = this.addproperty_button.offsetLeft+"px";
this.addproperty_holder.style.top = this.addproperty_button.offsetTop + this.addproperty_button.offsetHeight+"px";
// Disable the rest of the form while editing JSON
this.disable();
this.adding_property = true;
this.addproperty_button.disabled = false;
this.addproperty_holder.style.display = '';
this.refreshAddProperties();
},
hideAddProperty: function() {
if(!this.addproperty_holder) return;
if(!this.adding_property) return;
this.addproperty_holder.style.display = 'none';
this.enable();
this.adding_property = false;
},
toggleAddProperty: function() {
if(this.adding_property) this.hideAddProperty();
else this.showAddProperty();
},
removeObjectProperty: function(property) {
if(this.editors[property]) {
this.editors[property].unregister();
delete this.editors[property];
this.refreshValue();
this.layoutEditors();
}
},
addObjectProperty: function(name, prebuild_only) {
var self = this;
// Property is already added
if(this.editors[name]) return;
// Property was added before and is cached
if(this.cached_editors[name]) {
this.editors[name] = this.cached_editors[name];
if(prebuild_only) return;
this.editors[name].register();
}
// New property
else {
if(!this.canHaveAdditionalProperties() && (!this.schema.properties || !this.schema.properties[name])) {
return;
}
var schema = self.getPropertySchema(name);
// Add the property
var editor = self.jsoneditor.getEditorClass(schema);
self.editors[name] = self.jsoneditor.createEditor(editor,{
jsoneditor: self.jsoneditor,
schema: schema,
path: self.path+'.'+name,
parent: self
});
self.editors[name].preBuild();
if(!prebuild_only) {
var holder = self.theme.getChildEditorHolder();
self.editor_holder.appendChild(holder);
self.editors[name].setContainer(holder);
self.editors[name].build();
self.editors[name].postBuild();
}
self.cached_editors[name] = self.editors[name];
}
// If we're only prebuilding the editors, don't refresh values
if(!prebuild_only) {
self.refreshValue();
self.layoutEditors();
}
},
onChildEditorChange: function(editor) {
this.refreshValue();
this._super(editor);
},
canHaveAdditionalProperties: function() {
if (typeof this.schema.additionalProperties === "boolean") {
return this.schema.additionalProperties;
}
return !this.jsoneditor.options.no_additional_properties;
},
destroy: function() {
$each(this.cached_editors, function(i,el) {
el.destroy();
});
if(this.editor_holder) this.editor_holder.innerHTML = '';
if(this.title && this.title.parentNode) this.title.parentNode.removeChild(this.title);
if(this.error_holder && this.error_holder.parentNode) this.error_holder.parentNode.removeChild(this.error_holder);
this.editors = null;
this.cached_editors = null;
if(this.editor_holder && this.editor_holder.parentNode) this.editor_holder.parentNode.removeChild(this.editor_holder);
this.editor_holder = null;
this._super();
},
getValue: function() {
if (!this.dependenciesFulfilled) {
return undefined;
}
var result = this._super();
if(this.jsoneditor.options.remove_empty_properties || this.options.remove_empty_properties) {
for (var i in result) {
if (result.hasOwnProperty(i)) {
if (typeof result[i] === 'undefined' || result[i] === '' || Object.keys(result[i]).length == 0 && result[i].constructor == Object) delete result[i];
}
}
}
return result;
},
refreshValue: function() {
this.value = {};
var self = this;
for(var i in this.editors) {
if(!this.editors.hasOwnProperty(i)) continue;
this.value[i] = this.editors[i].getValue();
}
if(this.adding_property) this.refreshAddProperties();
},
refreshAddProperties: function() {
if(this.options.disable_properties || (this.options.disable_properties !== false && this.jsoneditor.options.disable_properties)) {
this.addproperty_controls.style.display = 'none';
return;
}
var can_add = false, can_remove = false, num_props = 0, i, show_modal = false;
// Get number of editors
for(i in this.editors) {
if(!this.editors.hasOwnProperty(i)) continue;
num_props++;
}
// Determine if we can add back removed properties
can_add = this.canHaveAdditionalProperties() && !(typeof this.schema.maxProperties !== "undefined" && num_props >= this.schema.maxProperties);
if(this.addproperty_checkboxes) {
this.addproperty_list.innerHTML = '';
}
this.addproperty_checkboxes = {};
// Check for which editors can't be removed or added back
for(i in this.cached_editors) {
if(!this.cached_editors.hasOwnProperty(i)) continue;
this.addPropertyCheckbox(i);
if(this.isRequired(this.cached_editors[i]) && i in this.editors) {
this.addproperty_checkboxes[i].disabled = true;
}
if(typeof this.schema.minProperties !== "undefined" && num_props <= this.schema.minProperties) {
this.addproperty_checkboxes[i].disabled = this.addproperty_checkboxes[i].checked;
if(!this.addproperty_checkboxes[i].checked) show_modal = true;
}
else if(!(i in this.editors)) {
if(!can_add && !this.schema.properties.hasOwnProperty(i)) {
this.addproperty_checkboxes[i].disabled = true;
}
else {
this.addproperty_checkboxes[i].disabled = false;
show_modal = true;
}
}
else {
show_modal = true;
can_remove = true;
}
}
if(this.canHaveAdditionalProperties()) {
show_modal = true;
}
// Additional addproperty checkboxes not tied to a current editor
for(i in this.schema.properties) {
if(!this.schema.properties.hasOwnProperty(i)) continue;
if(this.cached_editors[i]) continue;
show_modal = true;
this.addPropertyCheckbox(i);
}
// If no editors can be added or removed, hide the modal button
if(!show_modal) {
this.hideAddProperty();
this.addproperty_controls.style.display = 'none';
}
// If additional properties are disabled
else if(!this.canHaveAdditionalProperties()) {
this.addproperty_add.style.display = 'none';
this.addproperty_input.style.display = 'none';
}
// If no new properties can be added
else if(!can_add) {
this.addproperty_add.disabled = true;
}
// If new properties can be added
else {
this.addproperty_add.disabled = false;
}
},
isRequired: function(editor) {
if(typeof editor.schema.required === "boolean") return editor.schema.required;
else if(Array.isArray(this.schema.required)) return this.schema.required.indexOf(editor.key) > -1;
else if(this.jsoneditor.options.required_by_default) return true;
else return false;
},
setValue: function(value, initial) {
var self = this;
value = value || {};
if(typeof value !== "object" || Array.isArray(value)) value = {};
// First, set the values for all of the defined properties
$each(this.cached_editors, function(i,editor) {
// Value explicitly set
if(typeof value[i] !== "undefined") {
self.addObjectProperty(i);
editor.setValue(value[i],initial);
}
// Otherwise, remove value unless this is the initial set or it's required
else if(!initial && !self.isRequired(editor)) {
self.removeObjectProperty(i);
}
// Otherwise, set the value to the default
else {
editor.setValue(editor.getDefault(),initial);
}
});
$each(value, function(i,val) {
if(!self.cached_editors[i]) {
self.addObjectProperty(i);
if(self.editors[i]) self.editors[i].setValue(val,initial);
}
});
this.refreshValue();
this.layoutEditors();
this.onChange();
},
showValidationErrors: function(errors) {
var self = this;
// Get all the errors that pertain to this editor
var my_errors = [];
var other_errors = [];
$each(errors, function(i,error) {
if(error.path === self.path) {
my_errors.push(error);
}
else {
other_errors.push(error);
}
});
// Show errors for this editor
if(this.error_holder) {
if(my_errors.length) {
var message = [];
this.error_holder.innerHTML = '';
this.error_holder.style.display = '';
$each(my_errors, function(i,error) {
self.error_holder.appendChild(self.theme.getErrorMessage(error.message));
});
}
// Hide error area
else {
this.error_holder.style.display = 'none';
}
}
// Show error for the table row if this is inside a table
if(this.options.table_row) {
if(my_errors.length) {
this.theme.addTableRowError(this.container);
}
else {
this.theme.removeTableRowError(this.container);
}
}
// Show errors for child editors
$each(this.editors, function(i,editor) {
editor.showValidationErrors(other_errors);
});
}
});
JSONEditor.defaults.editors.array = JSONEditor.AbstractEditor.extend({
getDefault: function() {
return this.schema["default"] || [];
},
register: function() {
this._super();
if(this.rows) {
for(var i=0; i<this.rows.length; i++) {
this.rows[i].register();
}
}
},
unregister: function() {
this._super();
if(this.rows) {
for(var i=0; i<this.rows.length; i++) {
this.rows[i].unregister();
}
}
},
getNumColumns: function() {
var info = this.getItemInfo(0);
// Tabs require extra horizontal space
if(this.tabs_holder) {
return Math.max(Math.min(12,info.width+2),4);
}
else {
return info.width;
}
},
enable: function() {
if(!this.always_disabled) {
if(this.add_row_button) this.add_row_button.disabled = false;
if(this.remove_all_rows_button) this.remove_all_rows_button.disabled = false;
if(this.delete_last_row_button) this.delete_last_row_button.disabled = false;
if(this.rows) {
for(var i=0; i<this.rows.length; i++) {
this.rows[i].enable();
if(this.rows[i].moveup_button) this.rows[i].moveup_button.disabled = false;
if(this.rows[i].movedown_button) this.rows[i].movedown_button.disabled = false;
if(this.rows[i].delete_button) this.rows[i].delete_button.disabled = false;
}
}
this._super();
}
},
disable: function(always_disabled) {
if(always_disabled) this.always_disabled = true;
if(this.add_row_button) this.add_row_button.disabled = true;
if(this.remove_all_rows_button) this.remove_all_rows_button.disabled = true;
if(this.delete_last_row_button) this.delete_last_row_button.disabled = true;
if(this.rows) {
for(var i=0; i<this.rows.length; i++) {
this.rows[i].disable(always_disabled);
if(this.rows[i].moveup_button) this.rows[i].moveup_button.disabled = true;
if(this.rows[i].movedown_button) this.rows[i].movedown_button.disabled = true;
if(this.rows[i].delete_button) this.rows[i].delete_button.disabled = true;
}
}
this._super();
},
preBuild: function() {
this._super();
this.rows = [];
this.row_cache = [];
this.hide_delete_buttons = this.options.disable_array_delete || this.jsoneditor.options.disable_array_delete;
this.hide_delete_all_rows_buttons = this.hide_delete_buttons || this.options.disable_array_delete_all_rows || this.jsoneditor.options.disable_array_delete_all_rows;
this.hide_delete_last_row_buttons = this.hide_delete_buttons || this.options.disable_array_delete_last_row || this.jsoneditor.options.disable_array_delete_last_row;
this.hide_move_buttons = this.options.disable_array_reorder || this.jsoneditor.options.disable_array_reorder;
this.hide_add_button = this.options.disable_array_add || this.jsoneditor.options.disable_array_add;
this.show_copy_button = this.options.enable_array_copy || this.jsoneditor.options.enable_array_copy;
},
build: function() {
var self = this;
if(!this.options.compact) {
this.header = document.createElement('span');
this.header.textContent = this.getTitle();
this.title = this.theme.getHeader(this.header);
this.container.appendChild(this.title);
this.title_controls = this.theme.getHeaderButtonHolder();
this.title.appendChild(this.title_controls);
if(this.schema.description) {
this.description = this.theme.getDescription(this.schema.description);
this.container.appendChild(this.description);
}
this.error_holder = document.createElement('div');
this.container.appendChild(this.error_holder);
if(this.schema.format === 'tabs') {
this.controls = this.theme.getHeaderButtonHolder();
this.title.appendChild(this.controls);
this.tabs_holder = this.theme.getTabHolder();
this.container.appendChild(this.tabs_holder);
this.row_holder = this.theme.getTabContentHolder(this.tabs_holder);
this.active_tab = null;
}
else {
this.panel = this.theme.getIndentedPanel();
this.container.appendChild(this.panel);
this.row_holder = document.createElement('div');
this.panel.appendChild(this.row_holder);
this.controls = this.theme.getButtonHolder();
this.panel.appendChild(this.controls);
}
}
else {
this.panel = this.theme.getIndentedPanel();
this.container.appendChild(this.panel);
this.controls = this.theme.getButtonHolder();
this.panel.appendChild(this.controls);
this.row_holder = document.createElement('div');
this.panel.appendChild(this.row_holder);
}
// Add controls
this.addControls();
},
onChildEditorChange: function(editor) {
this.refreshValue();
this.refreshTabs(true);
this._super(editor);
},
getItemTitle: function() {
if(!this.item_title) {
if(this.schema.items && !Array.isArray(this.schema.items)) {
var tmp = this.jsoneditor.expandRefs(this.schema.items);
this.item_title = tmp.title || 'item';
}
else {
this.item_title = 'item';
}
}
return this.item_title;
},
getItemSchema: function(i) {
if(Array.isArray(this.schema.items)) {
if(i >= this.schema.items.length) {
if(this.schema.additionalItems===true) {
return {};
}
else if(this.schema.additionalItems) {
return $extend({},this.schema.additionalItems);
}
}
else {
return $extend({},this.schema.items[i]);
}
}
else if(this.schema.items) {
return $extend({},this.schema.items);
}
else {
return {};
}
},
getItemInfo: function(i) {
var schema = this.getItemSchema(i);
// Check if it's cached
this.item_info = this.item_info || {};
var stringified = JSON.stringify(schema);
if(typeof this.item_info[stringified] !== "undefined") return this.item_info[stringified];
// Get the schema for this item
schema = this.jsoneditor.expandRefs(schema);
this.item_info[stringified] = {
title: schema.title || "item",
'default': schema["default"],
width: 12,
child_editors: schema.properties || schema.items
};
return this.item_info[stringified];
},
getElementEditor: function(i) {
var item_info = this.getItemInfo(i);
var schema = this.getItemSchema(i);
schema = this.jsoneditor.expandRefs(schema);
schema.title = item_info.title+' '+(i+1);
var editor = this.jsoneditor.getEditorClass(schema);
var holder;
if(this.tabs_holder) {
holder = this.theme.getTabContent();
}
else if(item_info.child_editors) {
holder = this.theme.getChildEditorHolder();
}
else {
holder = this.theme.getIndentedPanel();
}
this.row_holder.appendChild(holder);
var ret = this.jsoneditor.createEditor(editor,{
jsoneditor: this.jsoneditor,
schema: schema,
container: holder,
path: this.path+'.'+i,
parent: this,
required: true
});
ret.preBuild();
ret.build();
ret.postBuild();
if(!ret.title_controls) {
ret.array_controls = this.theme.getButtonHolder();
holder.appendChild(ret.array_controls);
}
return ret;
},
destroy: function() {
this.empty(true);
if(this.title && this.title.parentNode) this.title.parentNode.removeChild(this.title);
if(this.description && this.description.parentNode) this.description.parentNode.removeChild(this.description);
if(this.row_holder && this.row_holder.parentNode) this.row_holder.parentNode.removeChild(this.row_holder);
if(this.controls && this.controls.parentNode) this.controls.parentNode.removeChild(this.controls);
if(this.panel && this.panel.parentNode) this.panel.parentNode.removeChild(this.panel);
this.rows = this.row_cache = this.title = this.description = this.row_holder = this.panel = this.controls = null;
this._super();
},
empty: function(hard) {
if(!this.rows) return;
var self = this;
$each(this.rows,function(i,row) {
if(hard) {
if(row.tab && row.tab.parentNode) row.tab.parentNode.removeChild(row.tab);
self.destroyRow(row,true);
self.row_cache[i] = null;
}
self.rows[i] = null;
});
self.rows = [];
if(hard) self.row_cache = [];
},
destroyRow: function(row,hard) {
var holder = row.container;
if(hard) {
row.destroy();
if(holder.parentNode) holder.parentNode.removeChild(holder);
if(row.tab && row.tab.parentNode) row.tab.parentNode.removeChild(row.tab);
}
else {
if(row.tab) row.tab.style.display = 'none';
holder.style.display = 'none';
row.unregister();
}
},
getMax: function() {
if((Array.isArray(this.schema.items)) && this.schema.additionalItems === false) {
return Math.min(this.schema.items.length,this.schema.maxItems || Infinity);
}
else {
return this.schema.maxItems || Infinity;
}
},
refreshTabs: function(refresh_headers) {
var self = this;
$each(this.rows, function(i,row) {
if(!row.tab) return;
if(refresh_headers) {
row.tab_text.textContent = row.getHeaderText();
}
else {
if(row.tab === self.active_tab) {
self.theme.markTabActive(row.tab);
row.container.style.display = '';
}
else {
self.theme.markTabInactive(row.tab);
row.container.style.display = 'none';
}
}
});
},
setValue: function(value, initial) {
// Update the array's value, adding/removing rows when necessary
value = value || [];
if(!(Array.isArray(value))) value = [value];
var serialized = JSON.stringify(value);
if(serialized === this.serialized) return;
// Make sure value has between minItems and maxItems items in it
if(this.schema.minItems) {
while(value.length < this.schema.minItems) {
value.push(this.getItemInfo(value.length)["default"]);
}
}
if(this.getMax() && value.length > this.getMax()) {
value = value.slice(0,this.getMax());
}
var self = this;
$each(value,function(i,val) {
if(self.rows[i]) {
// TODO: don't set the row's value if it hasn't changed
self.rows[i].setValue(val,initial);
}
else if(self.row_cache[i]) {
self.rows[i] = self.row_cache[i];
self.rows[i].setValue(val,initial);
self.rows[i].container.style.display = '';
if(self.rows[i].tab) self.rows[i].tab.style.display = '';
self.rows[i].register();
}
else {
self.addRow(val,initial);
}
});
for(var j=value.length; j<self.rows.length; j++) {
self.destroyRow(self.rows[j]);
self.rows[j] = null;
}
self.rows = self.rows.slice(0,value.length);
// Set the active tab
var new_active_tab = null;
$each(self.rows, function(i,row) {
if(row.tab === self.active_tab) {
new_active_tab = row.tab;
return false;
}
});
if(!new_active_tab && self.rows.length) new_active_tab = self.rows[0].tab;
self.active_tab = new_active_tab;
self.refreshValue(initial);
self.refreshTabs(true);
self.refreshTabs();
self.onChange();
// TODO: sortable
},
refreshValue: function(force) {
var self = this;
var oldi = this.value? this.value.length : 0;
this.value = [];
$each(this.rows,function(i,editor) {
// Get the value for this editor
self.value[i] = editor.getValue();
});
if(oldi !== this.value.length || force) {
// If we currently have minItems items in the array
var minItems = this.schema.minItems && this.schema.minItems >= this.rows.length;
$each(this.rows,function(i,editor) {
// Hide the move down button for the last row
if(editor.movedown_button) {
if(i === self.rows.length - 1) {
editor.movedown_button.style.display = 'none';
}
else {
editor.movedown_button.style.display = '';
}
}
// Hide the delete button if we have minItems items
if(editor.delete_button) {
if(minItems) {
editor.delete_button.style.display = 'none';
}
else {
editor.delete_button.style.display = '';
}
}
// Get the value for this editor
self.value[i] = editor.getValue();
});
var controls_needed = false;
if(!this.value.length) {
this.delete_last_row_button.style.display = 'none';
this.remove_all_rows_button.style.display = 'none';
}
else if(this.value.length === 1) {
this.remove_all_rows_button.style.display = 'none';
// If there are minItems items in the array, or configured to hide the delete_last_row button, hide the delete button beneath the rows
if(minItems || this.hide_delete_last_row_buttons) {
this.delete_last_row_button.style.display = 'none';
}
else {
this.delete_last_row_button.style.display = '';
controls_needed = true;
}
}
else {
if(minItems || this.hide_delete_last_row_buttons) {
this.delete_last_row_button.style.display = 'none';
}
else {
this.delete_last_row_button.style.display = '';
controls_needed = true;
}
if(minItems || this.hide_delete_all_rows_buttons) {
this.remove_all_rows_button.style.display = 'none';
}
else {
this.remove_all_rows_button.style.display = '';
controls_needed = true;
}
}
// If there are maxItems in the array, hide the add button beneath the rows
if((this.getMax() && this.getMax() <= this.rows.length) || this.hide_add_button){
this.add_row_button.style.display = 'none';
}
else {
this.add_row_button.style.display = '';
controls_needed = true;
}
if(!this.collapsed && controls_needed) {
this.controls.style.display = 'inline-block';
}
else {
this.controls.style.display = 'none';
}
}
},
addRow: function(value, initial) {
var self = this;
var i = this.rows.length;
self.rows[i] = this.getElementEditor(i);
self.row_cache[i] = self.rows[i];
if(self.tabs_holder) {
self.rows[i].tab_text = document.createElement('span');
self.rows[i].tab_text.textContent = self.rows[i].getHeaderText();
self.rows[i].tab = self.theme.getTab(self.rows[i].tab_text);
self.rows[i].tab.addEventListener('click', function(e) {
self.active_tab = self.rows[i].tab;
self.refreshTabs();
e.preventDefault();
e.stopPropagation();
});
self.theme.addTab(self.tabs_holder, self.rows[i].tab);
}
var controls_holder = self.rows[i].title_controls || self.rows[i].array_controls;
// Buttons to delete row, move row up, and move row down
if(!self.hide_delete_buttons) {
self.rows[i].delete_button = this.getButton(self.getItemTitle(),'delete',this.translate('button_delete_row_title',[self.getItemTitle()]));
self.rows[i].delete_button.className += ' delete';
self.rows[i].delete_button.setAttribute('data-i',i);
self.rows[i].delete_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
var i = this.getAttribute('data-i')*1;
var value = self.getValue();
var newval = [];
var new_active_tab = null;
$each(value,function(j,row) {
if(j===i) {
// If the one we're deleting is the active tab
if(self.rows[j].tab === self.active_tab) {
// Make the next tab active if there is one
// Note: the next tab is going to be the current tab after deletion
if(self.rows[j+1]) new_active_tab = self.rows[j].tab;
// Otherwise, make the previous tab active if there is one
else if(j) new_active_tab = self.rows[j-1].tab;
}
return; // If this is the one we're deleting
}
newval.push(row);
});
self.setValue(newval);
if(new_active_tab) {
self.active_tab = new_active_tab;
self.refreshTabs();
}
self.onChange(true);
});
if(controls_holder) {
controls_holder.appendChild(self.rows[i].delete_button);
}
}
//Button to copy an array element and add it as last element
if(self.show_copy_button){
self.rows[i].copy_button = this.getButton(self.getItemTitle(),'copy','Copy '+self.getItemTitle());
self.rows[i].copy_button.className += ' copy';
self.rows[i].copy_button.setAttribute('data-i',i);
self.rows[i].copy_button.addEventListener('click',function(e) {
var value = self.getValue();
e.preventDefault();
e.stopPropagation();
var i = this.getAttribute('data-i')*1;
$each(value,function(j,row) {
if(j===i) {
value.push(row);
return;
}
});
self.setValue(value);
self.refreshValue(true);
self.onChange(true);
});
controls_holder.appendChild(self.rows[i].copy_button);
}
if(i && !self.hide_move_buttons) {
self.rows[i].moveup_button = this.getButton('','moveup',this.translate('button_move_up_title'));
self.rows[i].moveup_button.className += ' moveup';
self.rows[i].moveup_button.setAttribute('data-i',i);
self.rows[i].moveup_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
var i = this.getAttribute('data-i')*1;
if(i<=0) return;
var rows = self.getValue();
var tmp = rows[i-1];
rows[i-1] = rows[i];
rows[i] = tmp;
self.setValue(rows);
self.active_tab = self.rows[i-1].tab;
self.refreshTabs();
self.onChange(true);
});
if(controls_holder) {
controls_holder.appendChild(self.rows[i].moveup_button);
}
}
if(!self.hide_move_buttons) {
self.rows[i].movedown_button = this.getButton('','movedown',this.translate('button_move_down_title'));
self.rows[i].movedown_button.className += ' movedown';
self.rows[i].movedown_button.setAttribute('data-i',i);
self.rows[i].movedown_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
var i = this.getAttribute('data-i')*1;
var rows = self.getValue();
if(i>=rows.length-1) return;
var tmp = rows[i+1];
rows[i+1] = rows[i];
rows[i] = tmp;
self.setValue(rows);
self.active_tab = self.rows[i+1].tab;
self.refreshTabs();
self.onChange(true);
});
if(controls_holder) {
controls_holder.appendChild(self.rows[i].movedown_button);
}
}
if(value) self.rows[i].setValue(value, initial);
self.refreshTabs();
},
addControls: function() {
var self = this;
this.collapsed = false;
this.toggle_button = this.getButton('','collapse',this.translate('button_collapse'));
this.title_controls.appendChild(this.toggle_button);
var row_holder_display = self.row_holder.style.display;
var controls_display = self.controls.style.display;
this.toggle_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
if(self.collapsed) {
self.collapsed = false;
if(self.panel) self.panel.style.display = '';
self.row_holder.style.display = row_holder_display;
if(self.tabs_holder) self.tabs_holder.style.display = '';
self.controls.style.display = controls_display;
self.setButtonText(this,'','collapse',self.translate('button_collapse'));
}
else {
self.collapsed = true;
self.row_holder.style.display = 'none';
if(self.tabs_holder) self.tabs_holder.style.display = 'none';
self.controls.style.display = 'none';
if(self.panel) self.panel.style.display = 'none';
self.setButtonText(this,'','expand',self.translate('button_expand'));
}
});
// If it should start collapsed
if(this.options.collapsed) {
$trigger(this.toggle_button,'click');
}
// Collapse button disabled
if(this.schema.options && typeof this.schema.options.disable_collapse !== "undefined") {
if(this.schema.options.disable_collapse) this.toggle_button.style.display = 'none';
}
else if(this.jsoneditor.options.disable_collapse) {
this.toggle_button.style.display = 'none';
}
// Add "new row" and "delete last" buttons below editor
this.add_row_button = this.getButton(this.getItemTitle(),'add',this.translate('button_add_row_title',[this.getItemTitle()]));
this.add_row_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
var i = self.rows.length;
if(self.row_cache[i]) {
self.rows[i] = self.row_cache[i];
self.rows[i].setValue(self.rows[i].getDefault(), true);
self.rows[i].container.style.display = '';
if(self.rows[i].tab) self.rows[i].tab.style.display = '';
self.rows[i].register();
}
else {
self.addRow();
}
self.active_tab = self.rows[i].tab;
self.refreshTabs();
self.refreshValue();
self.onChange(true);
});
self.controls.appendChild(this.add_row_button);
this.delete_last_row_button = this.getButton(this.translate('button_delete_last',[this.getItemTitle()]),'delete',this.translate('button_delete_last_title',[this.getItemTitle()]));
this.delete_last_row_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
var rows = self.getValue();
var new_active_tab = null;
if(self.rows.length > 1 && self.rows[self.rows.length-1].tab === self.active_tab) new_active_tab = self.rows[self.rows.length-2].tab;
rows.pop();
self.setValue(rows);
if(new_active_tab) {
self.active_tab = new_active_tab;
self.refreshTabs();
}
self.onChange(true);
});
self.controls.appendChild(this.delete_last_row_button);
this.remove_all_rows_button = this.getButton(this.translate('button_delete_all'),'delete',this.translate('button_delete_all_title'));
this.remove_all_rows_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
self.setValue([]);
self.onChange(true);
});
self.controls.appendChild(this.remove_all_rows_button);
if(self.tabs) {
this.add_row_button.style.width = '100%';
this.add_row_button.style.textAlign = 'left';
this.add_row_button.style.marginBottom = '3px';
this.delete_last_row_button.style.width = '100%';
this.delete_last_row_button.style.textAlign = 'left';
this.delete_last_row_button.style.marginBottom = '3px';
this.remove_all_rows_button.style.width = '100%';
this.remove_all_rows_button.style.textAlign = 'left';
this.remove_all_rows_button.style.marginBottom = '3px';
}
},
showValidationErrors: function(errors) {
var self = this;
// Get all the errors that pertain to this editor
var my_errors = [];
var other_errors = [];
$each(errors, function(i,error) {
if(error.path === self.path) {
my_errors.push(error);
}
else {
other_errors.push(error);
}
});
// Show errors for this editor
if(this.error_holder) {
if(my_errors.length) {
var message = [];
this.error_holder.innerHTML = '';
this.error_holder.style.display = '';
$each(my_errors, function(i,error) {
self.error_holder.appendChild(self.theme.getErrorMessage(error.message));
});
}
// Hide error area
else {
this.error_holder.style.display = 'none';
}
}
// Show errors for child editors
$each(this.rows, function(i,row) {
row.showValidationErrors(other_errors);
});
}
});
JSONEditor.defaults.editors.table = JSONEditor.defaults.editors.array.extend({
register: function() {
this._super();
if(this.rows) {
for(var i=0; i<this.rows.length; i++) {
this.rows[i].register();
}
}
},
unregister: function() {
this._super();
if(this.rows) {
for(var i=0; i<this.rows.length; i++) {
this.rows[i].unregister();
}
}
},
getNumColumns: function() {
return Math.max(Math.min(12,this.width),3);
},
preBuild: function() {
var item_schema = this.jsoneditor.expandRefs(this.schema.items || {});
this.item_title = item_schema.title || 'row';
this.item_default = item_schema["default"] || null;
this.item_has_child_editors = item_schema.properties || item_schema.items;
this.width = 12;
this._super();
},
build: function() {
var self = this;
this.table = this.theme.getTable();
this.container.appendChild(this.table);
this.thead = this.theme.getTableHead();
this.table.appendChild(this.thead);
this.header_row = this.theme.getTableRow();
this.thead.appendChild(this.header_row);
this.row_holder = this.theme.getTableBody();
this.table.appendChild(this.row_holder);
// Determine the default value of array element
var tmp = this.getElementEditor(0,true);
this.item_default = tmp.getDefault();
this.width = tmp.getNumColumns() + 2;
if(!this.options.compact) {
this.title = this.theme.getHeader(this.getTitle());
this.container.appendChild(this.title);
this.title_controls = this.theme.getHeaderButtonHolder();
this.title.appendChild(this.title_controls);
if(this.schema.description) {
this.description = this.theme.getDescription(this.schema.description);
this.container.appendChild(this.description);
}
this.panel = this.theme.getIndentedPanel();
this.container.appendChild(this.panel);
this.error_holder = document.createElement('div');
this.panel.appendChild(this.error_holder);
}
else {
this.panel = document.createElement('div');
this.container.appendChild(this.panel);
}
this.panel.appendChild(this.table);
this.controls = this.theme.getButtonHolder();
this.panel.appendChild(this.controls);
if(this.item_has_child_editors) {
var ce = tmp.getChildEditors();
var order = tmp.property_order || Object.keys(ce);
for(var i=0; i<order.length; i++) {
var th = self.theme.getTableHeaderCell(ce[order[i]].getTitle());
if(ce[order[i]].options.hidden) th.style.display = 'none';
self.header_row.appendChild(th);
}
}
else {
self.header_row.appendChild(self.theme.getTableHeaderCell(this.item_title));
}
tmp.destroy();
this.row_holder.innerHTML = '';
// Row Controls column
this.controls_header_cell = self.theme.getTableHeaderCell(" ");
self.header_row.appendChild(this.controls_header_cell);
// Add controls
this.addControls();
},
onChildEditorChange: function(editor) {
this.refreshValue();
this._super();
},
getItemDefault: function() {
return $extend({},{"default":this.item_default})["default"];
},
getItemTitle: function() {
return this.item_title;
},
getElementEditor: function(i,ignore) {
var schema_copy = $extend({},this.schema.items);
var editor = this.jsoneditor.getEditorClass(schema_copy, this.jsoneditor);
var row = this.row_holder.appendChild(this.theme.getTableRow());
var holder = row;
if(!this.item_has_child_editors) {
holder = this.theme.getTableCell();
row.appendChild(holder);
}
var ret = this.jsoneditor.createEditor(editor,{
jsoneditor: this.jsoneditor,
schema: schema_copy,
container: holder,
path: this.path+'.'+i,
parent: this,
compact: true,
table_row: true
});
ret.preBuild();
if(!ignore) {
ret.build();
ret.postBuild();
ret.controls_cell = row.appendChild(this.theme.getTableCell());
ret.row = row;
ret.table_controls = this.theme.getButtonHolder();
ret.controls_cell.appendChild(ret.table_controls);
ret.table_controls.style.margin = 0;
ret.table_controls.style.padding = 0;
}
return ret;
},
destroy: function() {
this.innerHTML = '';
if(this.title && this.title.parentNode) this.title.parentNode.removeChild(this.title);
if(this.description && this.description.parentNode) this.description.parentNode.removeChild(this.description);
if(this.row_holder && this.row_holder.parentNode) this.row_holder.parentNode.removeChild(this.row_holder);
if(this.table && this.table.parentNode) this.table.parentNode.removeChild(this.table);
if(this.panel && this.panel.parentNode) this.panel.parentNode.removeChild(this.panel);
this.rows = this.title = this.description = this.row_holder = this.table = this.panel = null;
this._super();
},
setValue: function(value, initial) {
// Update the array's value, adding/removing rows when necessary
value = value || [];
// Make sure value has between minItems and maxItems items in it
if(this.schema.minItems) {
while(value.length < this.schema.minItems) {
value.push(this.getItemDefault());
}
}
if(this.schema.maxItems && value.length > this.schema.maxItems) {
value = value.slice(0,this.schema.maxItems);
}
var serialized = JSON.stringify(value);
if(serialized === this.serialized) return;
var numrows_changed = false;
var self = this;
$each(value,function(i,val) {
if(self.rows[i]) {
// TODO: don't set the row's value if it hasn't changed
self.rows[i].setValue(val);
}
else {
self.addRow(val);
numrows_changed = true;
}
});
for(var j=value.length; j<self.rows.length; j++) {
var holder = self.rows[j].container;
if(!self.item_has_child_editors) {
self.rows[j].row.parentNode.removeChild(self.rows[j].row);
}
self.rows[j].destroy();
if(holder.parentNode) holder.parentNode.removeChild(holder);
self.rows[j] = null;
numrows_changed = true;
}
self.rows = self.rows.slice(0,value.length);
self.refreshValue();
if(numrows_changed || initial) self.refreshRowButtons();
self.onChange();
// TODO: sortable
},
refreshRowButtons: function() {
var self = this;
// If we currently have minItems items in the array
var minItems = this.schema.minItems && this.schema.minItems >= this.rows.length;
var need_row_buttons = false;
$each(this.rows,function(i,editor) {
// Hide the move down button for the last row
if(editor.movedown_button) {
if(i === self.rows.length - 1) {
editor.movedown_button.style.display = 'none';
}
else {
need_row_buttons = true;
editor.movedown_button.style.display = '';
}
}
// Hide the delete button if we have minItems items
if(editor.delete_button) {
if(minItems) {
editor.delete_button.style.display = 'none';
}
else {
need_row_buttons = true;
editor.delete_button.style.display = '';
}
}
if(editor.moveup_button) {
need_row_buttons = true;
}
});
// Show/hide controls column in table
$each(this.rows,function(i,editor) {
if(need_row_buttons) {
editor.controls_cell.style.display = '';
}
else {
editor.controls_cell.style.display = 'none';
}
});
if(need_row_buttons) {
this.controls_header_cell.style.display = '';
}
else {
this.controls_header_cell.style.display = 'none';
}
var controls_needed = false;
if(!this.value.length) {
this.delete_last_row_button.style.display = 'none';
this.remove_all_rows_button.style.display = 'none';
this.table.style.display = 'none';
}
else if(this.value.length === 1) {
this.table.style.display = '';
this.remove_all_rows_button.style.display = 'none';
// If there are minItems items in the array, or configured to hide the delete_last_row button, hide the delete button beneath the rows
if(minItems || this.hide_delete_last_row_buttons) {
this.delete_last_row_button.style.display = 'none';
}
else {
this.delete_last_row_button.style.display = '';
controls_needed = true;
}
}
else {
this.table.style.display = '';
if(minItems || this.hide_delete_last_row_buttons) {
this.delete_last_row_button.style.display = 'none';
}
else {
this.delete_last_row_button.style.display = '';
controls_needed = true;
}
if(minItems || this.hide_delete_all_rows_buttons) {
this.remove_all_rows_button.style.display = 'none';
}
else {
this.remove_all_rows_button.style.display = '';
controls_needed = true;
}
}
// If there are maxItems in the array, hide the add button beneath the rows
if((this.schema.maxItems && this.schema.maxItems <= this.rows.length) || this.hide_add_button) {
this.add_row_button.style.display = 'none';
}
else {
this.add_row_button.style.display = '';
controls_needed = true;
}
if(!controls_needed) {
this.controls.style.display = 'none';
}
else {
this.controls.style.display = '';
}
},
refreshValue: function() {
var self = this;
this.value = [];
$each(this.rows,function(i,editor) {
// Get the value for this editor
self.value[i] = editor.getValue();
});
this.serialized = JSON.stringify(this.value);
},
addRow: function(value) {
var self = this;
var i = this.rows.length;
self.rows[i] = this.getElementEditor(i);
var controls_holder = self.rows[i].table_controls;
// Buttons to delete row, move row up, and move row down
if(!this.hide_delete_buttons) {
self.rows[i].delete_button = this.getButton('','delete',this.translate('button_delete_row_title_short'));
self.rows[i].delete_button.className += ' delete';
self.rows[i].delete_button.setAttribute('data-i',i);
self.rows[i].delete_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
var i = this.getAttribute('data-i')*1;
var value = self.getValue();
var newval = [];
$each(value,function(j,row) {
if(j===i) return; // If this is the one we're deleting
newval.push(row);
});
self.setValue(newval);
self.onChange(true);
});
controls_holder.appendChild(self.rows[i].delete_button);
}
if(i && !this.hide_move_buttons) {
self.rows[i].moveup_button = this.getButton('','moveup',this.translate('button_move_up_title'));
self.rows[i].moveup_button.className += ' moveup';
self.rows[i].moveup_button.setAttribute('data-i',i);
self.rows[i].moveup_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
var i = this.getAttribute('data-i')*1;
if(i<=0) return;
var rows = self.getValue();
var tmp = rows[i-1];
rows[i-1] = rows[i];
rows[i] = tmp;
self.setValue(rows);
self.onChange(true);
});
controls_holder.appendChild(self.rows[i].moveup_button);
}
if(!this.hide_move_buttons) {
self.rows[i].movedown_button = this.getButton('','movedown',this.translate('button_move_down_title'));
self.rows[i].movedown_button.className += ' movedown';
self.rows[i].movedown_button.setAttribute('data-i',i);
self.rows[i].movedown_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
var i = this.getAttribute('data-i')*1;
var rows = self.getValue();
if(i>=rows.length-1) return;
var tmp = rows[i+1];
rows[i+1] = rows[i];
rows[i] = tmp;
self.setValue(rows);
self.onChange(true);
});
controls_holder.appendChild(self.rows[i].movedown_button);
}
if(value) self.rows[i].setValue(value);
},
addControls: function() {
var self = this;
this.collapsed = false;
this.toggle_button = this.getButton('','collapse',this.translate('button_collapse'));
if(this.title_controls) {
this.title_controls.appendChild(this.toggle_button);
this.toggle_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
if(self.collapsed) {
self.collapsed = false;
self.panel.style.display = '';
self.setButtonText(this,'','collapse',self.translate('button_collapse'));
}
else {
self.collapsed = true;
self.panel.style.display = 'none';
self.setButtonText(this,'','expand',self.translate('button_expand'));
}
});
// If it should start collapsed
if(this.options.collapsed) {
$trigger(this.toggle_button,'click');
}
// Collapse button disabled
if(this.schema.options && typeof this.schema.options.disable_collapse !== "undefined") {
if(this.schema.options.disable_collapse) this.toggle_button.style.display = 'none';
}
else if(this.jsoneditor.options.disable_collapse) {
this.toggle_button.style.display = 'none';
}
}
// Add "new row" and "delete last" buttons below editor
this.add_row_button = this.getButton(this.getItemTitle(),'add',this.translate('button_add_row_title',[this.getItemTitle()]));
this.add_row_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
self.addRow();
self.refreshValue();
self.refreshRowButtons();
self.onChange(true);
});
self.controls.appendChild(this.add_row_button);
this.delete_last_row_button = this.getButton(this.translate('button_delete_last',[this.getItemTitle()]),'delete',this.translate('button_delete_last_title',[this.getItemTitle()]));
this.delete_last_row_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
var rows = self.getValue();
rows.pop();
self.setValue(rows);
self.onChange(true);
});
self.controls.appendChild(this.delete_last_row_button);
this.remove_all_rows_button = this.getButton(this.translate('button_delete_all'),'delete',this.translate('button_delete_all_title'));
this.remove_all_rows_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
self.setValue([]);
self.onChange(true);
});
self.controls.appendChild(this.remove_all_rows_button);
}
});
// Multiple Editor (for when `type` is an array, also when `oneOf` is present)
JSONEditor.defaults.editors.multiple = JSONEditor.AbstractEditor.extend({
register: function() {
if(this.editors) {
for(var i=0; i<this.editors.length; i++) {
if(!this.editors[i]) continue;
this.editors[i].unregister();
}
if(this.editors[this.type]) this.editors[this.type].register();
}
this._super();
},
unregister: function() {
this._super();
if(this.editors) {
for(var i=0; i<this.editors.length; i++) {
if(!this.editors[i]) continue;
this.editors[i].unregister();
}
}
},
getNumColumns: function() {
if(!this.editors[this.type]) return 4;
return Math.max(this.editors[this.type].getNumColumns(),4);
},
enable: function() {
if(!this.always_disabled) {
if(this.editors) {
for(var i=0; i<this.editors.length; i++) {
if(!this.editors[i]) continue;
this.editors[i].enable();
}
}
this.switcher.disabled = false;
this._super();
}
},
disable: function(always_disabled) {
if(always_disabled) this.always_disabled = true;
if(this.editors) {
for(var i=0; i<this.editors.length; i++) {
if(!this.editors[i]) continue;
this.editors[i].disable(always_disabled);
}
}
this.switcher.disabled = true;
this._super();
},
switchEditor: function(i) {
var self = this;
if(!this.editors[i]) {
this.buildChildEditor(i);
}
var current_value = self.getValue();
self.type = i;
self.register();
$each(self.editors,function(type,editor) {
if(!editor) return;
if(self.type === type) {
if(self.keep_values) editor.setValue(current_value,true);
editor.container.style.display = '';
}
else editor.container.style.display = 'none';
});
self.refreshValue();
self.refreshHeaderText();
},
buildChildEditor: function(i) {
var self = this;
var type = this.types[i];
var holder = self.theme.getChildEditorHolder();
self.editor_holder.appendChild(holder);
var schema;
if(typeof type === "string") {
schema = $extend({},self.schema);
schema.type = type;
}
else {
schema = $extend({},self.schema,type);
schema = self.jsoneditor.expandRefs(schema);
// If we need to merge `required` arrays
if(type && type.required && Array.isArray(type.required) && self.schema.required && Array.isArray(self.schema.required)) {
schema.required = self.schema.required.concat(type.required);
}
}
var editor = self.jsoneditor.getEditorClass(schema);
self.editors[i] = self.jsoneditor.createEditor(editor,{
jsoneditor: self.jsoneditor,
schema: schema,
container: holder,
path: self.path,
parent: self,
required: true
});
self.editors[i].preBuild();
self.editors[i].build();
self.editors[i].postBuild();
if(self.editors[i].header) self.editors[i].header.style.display = 'none';
self.editors[i].option = self.switcher_options[i];
holder.addEventListener('change_header_text',function() {
self.refreshHeaderText();
});
if(i !== self.type) holder.style.display = 'none';
},
preBuild: function() {
var self = this;
this.types = [];
this.type = 0;
this.editors = [];
this.validators = [];
this.keep_values = true;
if(typeof this.jsoneditor.options.keep_oneof_values !== "undefined") this.keep_values = this.jsoneditor.options.keep_oneof_values;
if(typeof this.options.keep_oneof_values !== "undefined") this.keep_values = this.options.keep_oneof_values;
if(this.schema.oneOf) {
this.oneOf = true;
this.types = this.schema.oneOf;
delete this.schema.oneOf;
}
else if(this.schema.anyOf) {
this.anyOf = true;
this.types = this.schema.anyOf;
delete this.schema.anyOf;
}
else {
if(!this.schema.type || this.schema.type === "any") {
this.types = ['string','number','integer','boolean','object','array','null'];
// If any of these primitive types are disallowed
if(this.schema.disallow) {
var disallow = this.schema.disallow;
if(typeof disallow !== 'object' || !(Array.isArray(disallow))) {
disallow = [disallow];
}
var allowed_types = [];
$each(this.types,function(i,type) {
if(disallow.indexOf(type) === -1) allowed_types.push(type);
});
this.types = allowed_types;
}
}
else if(Array.isArray(this.schema.type)) {
this.types = this.schema.type;
}
else {
this.types = [this.schema.type];
}
delete this.schema.type;
}
this.display_text = this.getDisplayText(this.types);
},
build: function() {
var self = this;
var container = this.container;
this.header = this.label = this.theme.getFormInputLabel(this.getTitle());
this.container.appendChild(this.header);
this.switcher = this.theme.getSwitcher(this.display_text);
container.appendChild(this.switcher);
this.switcher.addEventListener('change',function(e) {
e.preventDefault();
e.stopPropagation();
self.switchEditor(self.display_text.indexOf(this.value));
self.onChange(true);
});
this.editor_holder = document.createElement('div');
container.appendChild(this.editor_holder);
var validator_options = {};
if(self.jsoneditor.options.custom_validators) {
validator_options.custom_validators = self.jsoneditor.options.custom_validators;
}
this.switcher_options = this.theme.getSwitcherOptions(this.switcher);
$each(this.types,function(i,type) {
self.editors[i] = false;
var schema;
if(typeof type === "string") {
schema = $extend({},self.schema);
schema.type = type;
}
else {
schema = $extend({},self.schema,type);
// If we need to merge `required` arrays
if(type.required && Array.isArray(type.required) && self.schema.required && Array.isArray(self.schema.required)) {
schema.required = self.schema.required.concat(type.required);
}
}
self.validators[i] = new JSONEditor.Validator(self.jsoneditor,schema,validator_options);
});
this.switchEditor(0);
},
onChildEditorChange: function(editor) {
if(this.editors[this.type]) {
this.refreshValue();
this.refreshHeaderText();
}
this._super();
},
refreshHeaderText: function() {
var display_text = this.getDisplayText(this.types);
$each(this.switcher_options, function(i,option) {
option.textContent = display_text[i];
});
},
refreshValue: function() {
this.value = this.editors[this.type].getValue();
},
setValue: function(val,initial) {
// Determine type by getting the first one that validates
var self = this;
var prev_type = this.type;
$each(this.validators, function(i,validator) {
if(!validator.validate(val).length) {
self.type = i;
self.switcher.value = self.display_text[i];
return false;
}
});
var type_changed = this.type != prev_type;
if (type_changed) {
this.switchEditor(this.type);
}
this.editors[this.type].setValue(val,initial);
this.refreshValue();
self.onChange(type_changed);
},
destroy: function() {
$each(this.editors, function(type,editor) {
if(editor) editor.destroy();
});
if(this.editor_holder && this.editor_holder.parentNode) this.editor_holder.parentNode.removeChild(this.editor_holder);
if(this.switcher && this.switcher.parentNode) this.switcher.parentNode.removeChild(this.switcher);
this._super();
},
showValidationErrors: function(errors) {
var self = this;
// oneOf and anyOf error paths need to remove the oneOf[i] part before passing to child editors
if(this.oneOf || this.anyOf) {
var check_part = this.oneOf? 'oneOf' : 'anyOf';
$each(this.editors,function(i,editor) {
if(!editor) return;
var check = self.path+'.'+check_part+'['+i+']';
var new_errors = [];
$each(errors, function(j,error) {
if(error.path.substr(0,check.length)===check) {
var new_error = $extend({},error);
new_error.path = self.path+new_error.path.substr(check.length);
new_errors.push(new_error);
}
});
editor.showValidationErrors(new_errors);
});
}
else {
$each(this.editors,function(type,editor) {
if(!editor) return;
editor.showValidationErrors(errors);
});
}
}
});
// Enum Editor (used for objects and arrays with enumerated values)
JSONEditor.defaults.editors["enum"] = JSONEditor.AbstractEditor.extend({
getNumColumns: function() {
return 4;
},
build: function() {
var container = this.container;
this.title = this.header = this.label = this.theme.getFormInputLabel(this.getTitle());
this.container.appendChild(this.title);
this.options.enum_titles = this.options.enum_titles || [];
this["enum"] = this.schema["enum"];
this.selected = 0;
this.select_options = [];
this.html_values = [];
var self = this;
for(var i=0; i<this["enum"].length; i++) {
this.select_options[i] = this.options.enum_titles[i] || "Value "+(i+1);
this.html_values[i] = this.getHTML(this["enum"][i]);
}
// Switcher
this.switcher = this.theme.getSwitcher(this.select_options);
this.container.appendChild(this.switcher);
// Display area
this.display_area = this.theme.getIndentedPanel();
this.container.appendChild(this.display_area);
if(this.options.hide_display) this.display_area.style.display = "none";
this.switcher.addEventListener('change',function() {
self.selected = self.select_options.indexOf(this.value);
self.value = self["enum"][self.selected];
self.refreshValue();
self.onChange(true);
});
this.value = this["enum"][0];
this.refreshValue();
if(this["enum"].length === 1) this.switcher.style.display = 'none';
},
refreshValue: function() {
var self = this;
self.selected = -1;
var stringified = JSON.stringify(this.value);
$each(this["enum"], function(i, el) {
if(stringified === JSON.stringify(el)) {
self.selected = i;
return false;
}
});
if(self.selected<0) {
self.setValue(self["enum"][0]);
return;
}
this.switcher.value = this.select_options[this.selected];
this.display_area.innerHTML = this.html_values[this.selected];
},
enable: function() {
if(!this.always_disabled) {
this.switcher.disabled = false;
this._super();
}
},
disable: function(always_disabled) {
if(always_disabled) this.always_disabled = true;
this.switcher.disabled = true;
this._super();
},
getHTML: function(el) {
var self = this;
if(el === null) {
return '<em>null</em>';
}
// Array or Object
else if(typeof el === "object") {
// TODO: use theme
var ret = '';
$each(el,function(i,child) {
var html = self.getHTML(child);
// Add the keys to object children
if(!(Array.isArray(el))) {
// TODO: use theme
html = '<div><em>'+i+'</em>: '+html+'</div>';
}
// TODO: use theme
ret += '<li>'+html+'</li>';
});
if(Array.isArray(el)) ret = '<ol>'+ret+'</ol>';
else ret = "<ul style='margin-top:0;margin-bottom:0;padding-top:0;padding-bottom:0;'>"+ret+'</ul>';
return ret;
}
// Boolean
else if(typeof el === "boolean") {
return el? 'true' : 'false';
}
// String
else if(typeof el === "string") {
return el.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
// Number
else {
return el;
}
},
setValue: function(val) {
if(this.value !== val) {
this.value = val;
this.refreshValue();
this.onChange();
}
},
destroy: function() {
if(this.display_area && this.display_area.parentNode) this.display_area.parentNode.removeChild(this.display_area);
if(this.title && this.title.parentNode) this.title.parentNode.removeChild(this.title);
if(this.switcher && this.switcher.parentNode) this.switcher.parentNode.removeChild(this.switcher);
this._super();
}
});
JSONEditor.defaults.editors.select = JSONEditor.AbstractEditor.extend({
setValue: function(value,initial) {
value = this.typecast(value||'');
// Sanitize value before setting it
var sanitized = value;
if(this.enum_values.indexOf(sanitized) < 0) {
sanitized = this.enum_values[0];
}
if(this.value === sanitized) {
return;
}
this.input.value = this.enum_options[this.enum_values.indexOf(sanitized)];
if(this.select2) {
if(this.select2v4)
this.select2.val(this.input.value).trigger("change");
else
this.select2.select2('val',this.input.value);
}
this.value = sanitized;
this.onChange();
this.change();
},
register: function() {
this._super();
if(!this.input) return;
this.input.setAttribute('name',this.formname);
},
unregister: function() {
this._super();
if(!this.input) return;
this.input.removeAttribute('name');
},
getNumColumns: function() {
if(!this.enum_options) return 3;
var longest_text = this.getTitle().length;
for(var i=0; i<this.enum_options.length; i++) {
longest_text = Math.max(longest_text,this.enum_options[i].length+4);
}
return Math.min(12,Math.max(longest_text/7,2));
},
typecast: function(value) {
if(this.schema.type === "boolean") {
return !!value;
}
else if(this.schema.type === "number") {
return 1*value;
}
else if(this.schema.type === "integer") {
return Math.floor(value*1);
}
else {
return ""+value;
}
},
getValue: function() {
if (!this.dependenciesFulfilled) {
return undefined;
}
return this.typecast(this.value);
},
preBuild: function() {
var self = this;
this.input_type = 'select';
this.enum_options = [];
this.enum_values = [];
this.enum_display = [];
var i;
// Enum options enumerated
if(this.schema["enum"]) {
var display = this.schema.options && this.schema.options.enum_titles || [];
$each(this.schema["enum"],function(i,option) {
self.enum_options[i] = ""+option;
self.enum_display[i] = ""+(display[i] || option);
self.enum_values[i] = self.typecast(option);
});
if(!this.isRequired()){
self.enum_display.unshift(' ');
self.enum_options.unshift('undefined');
self.enum_values.unshift(undefined);
}
}
// Boolean
else if(this.schema.type === "boolean") {
self.enum_display = this.schema.options && this.schema.options.enum_titles || ['true','false'];
self.enum_options = ['1',''];
self.enum_values = [true,false];
if(!this.isRequired()){
self.enum_display.unshift(' ');
self.enum_options.unshift('undefined');
self.enum_values.unshift(undefined);
}
}
// Dynamic Enum
else if(this.schema.enumSource) {
this.enumSource = [];
this.enum_display = [];
this.enum_options = [];
this.enum_values = [];
// Shortcut declaration for using a single array
if(!(Array.isArray(this.schema.enumSource))) {
if(this.schema.enumValue) {
this.enumSource = [
{
source: this.schema.enumSource,
value: this.schema.enumValue
}
];
}
else {
this.enumSource = [
{
source: this.schema.enumSource
}
];
}
}
else {
for(i=0; i<this.schema.enumSource.length; i++) {
// Shorthand for watched variable
if(typeof this.schema.enumSource[i] === "string") {
this.enumSource[i] = {
source: this.schema.enumSource[i]
};
}
// Make a copy of the schema
else if(!(Array.isArray(this.schema.enumSource[i]))) {
this.enumSource[i] = $extend({},this.schema.enumSource[i]);
}
else {
this.enumSource[i] = this.schema.enumSource[i];
}
}
}
// Now, enumSource is an array of sources
// Walk through this array and fix up the values
for(i=0; i<this.enumSource.length; i++) {
if(this.enumSource[i].value) {
this.enumSource[i].value = this.jsoneditor.compileTemplate(this.enumSource[i].value, this.template_engine);
}
if(this.enumSource[i].title) {
this.enumSource[i].title = this.jsoneditor.compileTemplate(this.enumSource[i].title, this.template_engine);
}
if(this.enumSource[i].filter) {
this.enumSource[i].filter = this.jsoneditor.compileTemplate(this.enumSource[i].filter, this.template_engine);
}
}
}
// Other, not supported
else {
throw "'select' editor requires the enum property to be set.";
}
},
build: function() {
var self = this;
if(!this.options.compact) this.header = this.label = this.theme.getFormInputLabel(this.getTitle());
if(this.schema.description) this.description = this.theme.getFormInputDescription(this.schema.description);
if(this.options.infoText) this.infoButton = this.theme.getInfoButton(this.options.infoText);
if(this.options.compact) this.container.className += ' compact';
this.input = this.theme.getSelectInput(this.enum_options);
this.theme.setSelectOptions(this.input,this.enum_options,this.enum_display);
if(this.schema.readOnly || this.schema.readonly) {
this.always_disabled = true;
this.input.disabled = true;
}
this.input.addEventListener('change',function(e) {
e.preventDefault();
e.stopPropagation();
self.onInputChange();
});
this.control = this.theme.getFormControl(this.label, this.input, this.description, this.infoButton);
this.container.appendChild(this.control);
this.value = this.enum_values[0];
},
onInputChange: function() {
var val = this.typecast(this.input.value);
var new_val;
// Invalid option, use first option instead
if(this.enum_options.indexOf(val) === -1) {
new_val = this.enum_values[0];
}
else {
new_val = this.enum_values[this.enum_options.indexOf(val)];
}
// If valid hasn't changed
if(new_val === this.value) return;
// Store new value and propogate change event
this.value = new_val;
this.onChange(true);
},
setupSelect2: function() {
// If the Select2 library is loaded use it when we have lots of items
if(window.jQuery && window.jQuery.fn && window.jQuery.fn.select2 && (this.enum_options.length > 2 || (this.enum_options.length && this.enumSource))) {
var options = $extend({},JSONEditor.plugins.select2);
if(this.schema.options && this.schema.options.select2_options) options = $extend(options,this.schema.options.select2_options);
this.select2 = window.jQuery(this.input).select2(options);
this.select2v4 = this.select2.select2.hasOwnProperty("amd");
var self = this;
this.select2.on('select2-blur',function() {
if(self.select2v4)
self.input.value = self.select2.val();
else
self.input.value = self.select2.select2('val');
self.onInputChange();
});
this.select2.on('change',function() {
if(self.select2v4)
self.input.value = self.select2.val();
else
self.input.value = self.select2.select2('val');
self.onInputChange();
});
}
else {
this.select2 = null;
}
},
postBuild: function() {
this._super();
this.theme.afterInputReady(this.input);
this.setupSelect2();
},
onWatchedFieldChange: function() {
var self = this, vars, j;
// If this editor uses a dynamic select box
if(this.enumSource) {
vars = this.getWatchedFieldValues();
var select_options = [];
var select_titles = [];
for(var i=0; i<this.enumSource.length; i++) {
// Constant values
if(Array.isArray(this.enumSource[i])) {
select_options = select_options.concat(this.enumSource[i]);
select_titles = select_titles.concat(this.enumSource[i]);
}
else {
var items = [];
// Static list of items
if(Array.isArray(this.enumSource[i].source)) {
items = this.enumSource[i].source;
// A watched field
} else {
items = vars[this.enumSource[i].source];
}
if(items) {
// Only use a predefined part of the array
if(this.enumSource[i].slice) {
items = Array.prototype.slice.apply(items,this.enumSource[i].slice);
}
// Filter the items
if(this.enumSource[i].filter) {
var new_items = [];
for(j=0; j<items.length; j++) {
if(this.enumSource[i].filter({i:j,item:items[j],watched:vars})) new_items.push(items[j]);
}
items = new_items;
}
var item_titles = [];
var item_values = [];
for(j=0; j<items.length; j++) {
var item = items[j];
// Rendered value
if(this.enumSource[i].value) {
item_values[j] = this.enumSource[i].value({
i: j,
item: item
});
}
// Use value directly
else {
item_values[j] = items[j];
}
// Rendered title
if(this.enumSource[i].title) {
item_titles[j] = this.enumSource[i].title({
i: j,
item: item
});
}
// Use value as the title also
else {
item_titles[j] = item_values[j];
}
}
// TODO: sort
select_options = select_options.concat(item_values);
select_titles = select_titles.concat(item_titles);
}
}
}
var prev_value = this.value;
this.theme.setSelectOptions(this.input, select_options, select_titles);
this.enum_options = select_options;
this.enum_display = select_titles;
this.enum_values = select_options;
if(this.select2) {
this.select2.select2('destroy');
}
// If the previous value is still in the new select options, stick with it
if(select_options.indexOf(prev_value) !== -1) {
this.input.value = prev_value;
this.value = prev_value;
}
// Otherwise, set the value to the first select option
else {
this.input.value = select_options[0];
this.value = this.typecast(select_options[0] || "");
if(this.parent) this.parent.onChildEditorChange(this);
else this.jsoneditor.onChange();
this.jsoneditor.notifyWatchers(this.path);
}
this.setupSelect2();
}
this._super();
},
enable: function() {
if(!this.always_disabled) {
this.input.disabled = false;
if(this.select2) {
if(this.select2v4)
this.select2.prop("disabled",false);
else
this.select2.select2("enable",true);
}
}
this._super();
},
disable: function(always_disabled) {
if(always_disabled) this.always_disabled = true;
this.input.disabled = true;
if(this.select2) {
if(this.select2v4)
this.select2.prop("disabled",true);
else
this.select2.select2("enable",false);
}
this._super();
},
destroy: function() {
if(this.label && this.label.parentNode) this.label.parentNode.removeChild(this.label);
if(this.description && this.description.parentNode) this.description.parentNode.removeChild(this.description);
if(this.input && this.input.parentNode) this.input.parentNode.removeChild(this.input);
if(this.select2) {
this.select2.select2('destroy');
this.select2 = null;
}
this._super();
}
});
JSONEditor.defaults.editors.selectize = JSONEditor.AbstractEditor.extend({
setValue: function(value,initial) {
value = this.typecast(value||'');
// Sanitize value before setting it
var sanitized = value;
if(this.enum_values.indexOf(sanitized) < 0) {
sanitized = this.enum_values[0];
}
if(this.value === sanitized) {
return;
}
this.input.value = this.enum_options[this.enum_values.indexOf(sanitized)];
if(this.selectize) {
this.selectize[0].selectize.addItem(sanitized);
}
this.value = sanitized;
this.onChange();
},
register: function() {
this._super();
if(!this.input) return;
this.input.setAttribute('name',this.formname);
},
unregister: function() {
this._super();
if(!this.input) return;
this.input.removeAttribute('name');
},
getNumColumns: function() {
if(!this.enum_options) return 3;
var longest_text = this.getTitle().length;
for(var i=0; i<this.enum_options.length; i++) {
longest_text = Math.max(longest_text,this.enum_options[i].length+4);
}
return Math.min(12,Math.max(longest_text/7,2));
},
typecast: function(value) {
if(this.schema.type === "boolean") {
return !!value;
}
else if(this.schema.type === "number") {
return 1*value;
}
else if(this.schema.type === "integer") {
return Math.floor(value*1);
}
else {
return ""+value;
}
},
getValue: function() {
if (!this.dependenciesFulfilled) {
return undefined;
}
return this.value;
},
preBuild: function() {
var self = this;
this.input_type = 'select';
this.enum_options = [];
this.enum_values = [];
this.enum_display = [];
var i;
// Enum options enumerated
if(this.schema.enum) {
var display = this.schema.options && this.schema.options.enum_titles || [];
$each(this.schema.enum,function(i,option) {
self.enum_options[i] = ""+option;
self.enum_display[i] = ""+(display[i] || option);
self.enum_values[i] = self.typecast(option);
});
}
// Boolean
else if(this.schema.type === "boolean") {
self.enum_display = this.schema.options && this.schema.options.enum_titles || ['true','false'];
self.enum_options = ['1','0'];
self.enum_values = [true,false];
}
// Dynamic Enum
else if(this.schema.enumSource) {
this.enumSource = [];
this.enum_display = [];
this.enum_options = [];
this.enum_values = [];
// Shortcut declaration for using a single array
if(!(Array.isArray(this.schema.enumSource))) {
if(this.schema.enumValue) {
this.enumSource = [
{
source: this.schema.enumSource,
value: this.schema.enumValue
}
];
}
else {
this.enumSource = [
{
source: this.schema.enumSource
}
];
}
}
else {
for(i=0; i<this.schema.enumSource.length; i++) {
// Shorthand for watched variable
if(typeof this.schema.enumSource[i] === "string") {
this.enumSource[i] = {
source: this.schema.enumSource[i]
};
}
// Make a copy of the schema
else if(!(Array.isArray(this.schema.enumSource[i]))) {
this.enumSource[i] = $extend({},this.schema.enumSource[i]);
}
else {
this.enumSource[i] = this.schema.enumSource[i];
}
}
}
// Now, enumSource is an array of sources
// Walk through this array and fix up the values
for(i=0; i<this.enumSource.length; i++) {
if(this.enumSource[i].value) {
this.enumSource[i].value = this.jsoneditor.compileTemplate(this.enumSource[i].value, this.template_engine);
}
if(this.enumSource[i].title) {
this.enumSource[i].title = this.jsoneditor.compileTemplate(this.enumSource[i].title, this.template_engine);
}
if(this.enumSource[i].filter) {
this.enumSource[i].filter = this.jsoneditor.compileTemplate(this.enumSource[i].filter, this.template_engine);
}
}
}
// Other, not supported
else {
throw "'select' editor requires the enum property to be set.";
}
},
build: function() {
var self = this;
if(!this.options.compact) this.header = this.label = this.theme.getFormInputLabel(this.getTitle());
if(this.schema.description) this.description = this.theme.getFormInputDescription(this.schema.description);
if(this.options.infoText) this.infoButton = this.theme.getInfoButton(this.options.infoText);
if(this.options.compact) this.container.className += ' compact';
this.input = this.theme.getSelectInput(this.enum_options);
this.theme.setSelectOptions(this.input,this.enum_options,this.enum_display);
if(this.schema.readOnly || this.schema.readonly) {
this.always_disabled = true;
this.input.disabled = true;
}
this.input.addEventListener('change',function(e) {
e.preventDefault();
e.stopPropagation();
self.onInputChange();
});
this.control = this.theme.getFormControl(this.label, this.input, this.description, this.infoButton);
this.container.appendChild(this.control);
this.value = this.enum_values[0];
},
onInputChange: function() {
//console.log("onInputChange");
var val = this.input.value;
var sanitized = val;
if(this.enum_options.indexOf(val) === -1) {
sanitized = this.enum_options[0];
}
//this.value = this.enum_values[this.enum_options.indexOf(val)];
this.value = val;
this.onChange(true);
},
setupSelectize: function() {
// If the Selectize library is loaded use it when we have lots of items
var self = this;
if(window.jQuery && window.jQuery.fn && window.jQuery.fn.selectize && (this.enum_options.length >= 2 || (this.enum_options.length && this.enumSource))) {
var options = $extend({},JSONEditor.plugins.selectize);
if(this.schema.options && this.schema.options.selectize_options) options = $extend(options,this.schema.options.selectize_options);
this.selectize = window.jQuery(this.input).selectize($extend(options,
{
// set the create option to true by default, or to the user specified value if defined
create: ( options.create === undefined ? true : options.create),
onChange : function() {
self.onInputChange();
}
}));
}
else {
this.selectize = null;
}
},
postBuild: function() {
this._super();
this.theme.afterInputReady(this.input);
this.setupSelectize();
},
onWatchedFieldChange: function() {
var self = this, vars, j;
// If this editor uses a dynamic select box
if(this.enumSource) {
vars = this.getWatchedFieldValues();
var select_options = [];
var select_titles = [];
for(var i=0; i<this.enumSource.length; i++) {
// Constant values
if(Array.isArray(this.enumSource[i])) {
select_options = select_options.concat(this.enumSource[i]);
select_titles = select_titles.concat(this.enumSource[i]);
}
// A watched field
else if(vars[this.enumSource[i].source]) {
var items = vars[this.enumSource[i].source];
// Only use a predefined part of the array
if(this.enumSource[i].slice) {
items = Array.prototype.slice.apply(items,this.enumSource[i].slice);
}
// Filter the items
if(this.enumSource[i].filter) {
var new_items = [];
for(j=0; j<items.length; j++) {
if(this.enumSource[i].filter({i:j,item:items[j]})) new_items.push(items[j]);
}
items = new_items;
}
var item_titles = [];
var item_values = [];
for(j=0; j<items.length; j++) {
var item = items[j];
// Rendered value
if(this.enumSource[i].value) {
item_values[j] = this.enumSource[i].value({
i: j,
item: item
});
}
// Use value directly
else {
item_values[j] = items[j];
}
// Rendered title
if(this.enumSource[i].title) {
item_titles[j] = this.enumSource[i].title({
i: j,
item: item
});
}
// Use value as the title also
else {
item_titles[j] = item_values[j];
}
}
// TODO: sort
select_options = select_options.concat(item_values);
select_titles = select_titles.concat(item_titles);
}
}
var prev_value = this.value;
// Check to see if this item is in the list
// Note: We have to skip empty string for watch lists to work properly
if ((prev_value !== undefined) && (prev_value !== "") && (select_options.indexOf(prev_value) === -1)) {
// item is not in the list. Add it.
select_options = select_options.concat(prev_value);
select_titles = select_titles.concat(prev_value);
}
this.theme.setSelectOptions(this.input, select_options, select_titles);
this.enum_options = select_options;
this.enum_display = select_titles;
this.enum_values = select_options;
// If the previous value is still in the new select options, stick with it
if(select_options.indexOf(prev_value) !== -1) {
this.input.value = prev_value;
this.value = prev_value;
}
// Otherwise, set the value to the first select option
else {
this.input.value = select_options[0];
this.value = select_options[0] || "";
if(this.parent) this.parent.onChildEditorChange(this);
else this.jsoneditor.onChange();
this.jsoneditor.notifyWatchers(this.path);
}
if(this.selectize) {
// Update the Selectize options
this.updateSelectizeOptions(select_options);
}
else {
this.setupSelectize();
}
this._super();
}
},
updateSelectizeOptions: function(select_options) {
var selectized = this.selectize[0].selectize,
self = this;
selectized.off();
selectized.clearOptions();
for(var n in select_options) {
selectized.addOption({value:select_options[n],text:select_options[n]});
}
selectized.addItem(this.value);
selectized.on('change',function() {
self.onInputChange();
});
},
enable: function() {
if(!this.always_disabled) {
this.input.disabled = false;
if(this.selectize) {
this.selectize[0].selectize.unlock();
}
this._super();
}
},
disable: function(always_disabled) {
if(always_disabled) this.always_disabled = true;
this.input.disabled = true;
if(this.selectize) {
this.selectize[0].selectize.lock();
}
this._super();
},
destroy: function() {
if(this.label && this.label.parentNode) this.label.parentNode.removeChild(this.label);
if(this.description && this.description.parentNode) this.description.parentNode.removeChild(this.description);
if(this.input && this.input.parentNode) this.input.parentNode.removeChild(this.input);
if(this.selectize) {
this.selectize[0].selectize.destroy();
this.selectize = null;
}
this._super();
}
});
JSONEditor.defaults.editors.multiselect = JSONEditor.AbstractEditor.extend({
preBuild: function() {
this._super();
var i;
this.select_options = {};
this.select_values = {};
var items_schema = this.jsoneditor.expandRefs(this.schema.items || {});
var e = items_schema["enum"] || [];
var t = items_schema.options? items_schema.options.enum_titles || [] : [];
this.option_keys = [];
this.option_titles = [];
for(i=0; i<e.length; i++) {
// If the sanitized value is different from the enum value, don't include it
if(this.sanitize(e[i]) !== e[i]) continue;
this.option_keys.push(e[i]+"");
this.option_titles.push((t[i]||e[i])+"");
this.select_values[e[i]+""] = e[i];
}
},
build: function() {
var self = this, i;
if(!this.options.compact) this.header = this.label = this.theme.getFormInputLabel(this.getTitle());
if(this.schema.description) this.description = this.theme.getFormInputDescription(this.schema.description);
if((!this.schema.format && this.option_keys.length < 8) || this.schema.format === "checkbox") {
this.input_type = 'checkboxes';
this.inputs = {};
this.controls = {};
for(i=0; i<this.option_keys.length; i++) {
this.inputs[this.option_keys[i]] = this.theme.getCheckbox();
this.select_options[this.option_keys[i]] = this.inputs[this.option_keys[i]];
var label = this.theme.getCheckboxLabel(this.option_titles[i]);
this.controls[this.option_keys[i]] = this.theme.getFormControl(label, this.inputs[this.option_keys[i]]);
}
this.control = this.theme.getMultiCheckboxHolder(this.controls,this.label,this.description);
}
else {
this.input_type = 'select';
this.input = this.theme.getSelectInput(this.option_keys);
this.theme.setSelectOptions(this.input,this.option_keys,this.option_titles);
this.input.multiple = true;
this.input.size = Math.min(10,this.option_keys.length);
for(i=0; i<this.option_keys.length; i++) {
this.select_options[this.option_keys[i]] = this.input.children[i];
}
if(this.schema.readOnly || this.schema.readonly) {
this.always_disabled = true;
this.input.disabled = true;
}
this.control = this.theme.getFormControl(this.label, this.input, this.description);
}
this.container.appendChild(this.control);
this.control.addEventListener('change',function(e) {
e.preventDefault();
e.stopPropagation();
var new_value = [];
for(i = 0; i<self.option_keys.length; i++) {
if(self.select_options[self.option_keys[i]].selected || self.select_options[self.option_keys[i]].checked) new_value.push(self.select_values[self.option_keys[i]]);
}
self.updateValue(new_value);
self.onChange(true);
});
},
setValue: function(value, initial) {
var i;
value = value || [];
if(typeof value !== "object") value = [value];
else if(!(Array.isArray(value))) value = [];
// Make sure we are dealing with an array of strings so we can check for strict equality
for(i=0; i<value.length; i++) {
if(typeof value[i] !== "string") value[i] += "";
}
// Update selected status of options
for(i in this.select_options) {
if(!this.select_options.hasOwnProperty(i)) continue;
this.select_options[i][this.input_type === "select"? "selected" : "checked"] = (value.indexOf(i) !== -1);
}
this.updateValue(value);
this.onChange();
},
setupSelect2: function() {
if(window.jQuery && window.jQuery.fn && window.jQuery.fn.select2) {
var options = window.jQuery.extend({},JSONEditor.plugins.select2);
if(this.schema.options && this.schema.options.select2_options) options = $extend(options,this.schema.options.select2_options);
this.select2 = window.jQuery(this.input).select2(options);
this.select2v4 = this.select2.select2.hasOwnProperty("amd");
var self = this;
this.select2.on('select2-blur',function() {
if(self.select2v4)
self.value = self.select2.val();
else
self.value = self.select2.select2('val');
self.onChange(true);
});
this.select2.on('change',function() {
if(self.select2v4)
self.value = self.select2.val();
else
self.value = self.select2.select2('val');
self.onChange(true);
});
}
else {
this.select2 = null;
}
},
onInputChange: function() {
this.value = this.input.value;
this.onChange(true);
},
postBuild: function() {
this._super();
this.setupSelect2();
},
register: function() {
this._super();
if(!this.input) return;
this.input.setAttribute('name',this.formname);
},
unregister: function() {
this._super();
if(!this.input) return;
this.input.removeAttribute('name');
},
getNumColumns: function() {
var longest_text = this.getTitle().length;
for(var i in this.select_values) {
if(!this.select_values.hasOwnProperty(i)) continue;
longest_text = Math.max(longest_text,(this.select_values[i]+"").length+4);
}
return Math.min(12,Math.max(longest_text/7,2));
},
updateValue: function(value) {
var changed = false;
var new_value = [];
for(var i=0; i<value.length; i++) {
if(!this.select_options[value[i]+""]) {
changed = true;
continue;
}
var sanitized = this.sanitize(this.select_values[value[i]]);
new_value.push(sanitized);
if(sanitized !== value[i]) changed = true;
}
this.value = new_value;
if(this.select2) {
if(this.select2v4)
this.select2.val(this.value).trigger("change");
else
this.select2.select2('val',this.value);
}
return changed;
},
sanitize: function(value) {
if(this.schema.items.type === "number") {
return 1*value;
}
else if(this.schema.items.type === "integer") {
return Math.floor(value*1);
}
else {
return ""+value;
}
},
enable: function() {
if(!this.always_disabled) {
if(this.input) {
this.input.disabled = false;
}
else if(this.inputs) {
for(var i in this.inputs) {
if(!this.inputs.hasOwnProperty(i)) continue;
this.inputs[i].disabled = false;
}
}
if(this.select2) {
if(this.select2v4)
this.select2.prop("disabled",false);
else
this.select2.select2("enable",true);
}
this._super();
}
},
disable: function(always_disabled) {
if(always_disabled) this.always_disabled = true;
if(this.input) {
this.input.disabled = true;
}
else if(this.inputs) {
for(var i in this.inputs) {
if(!this.inputs.hasOwnProperty(i)) continue;
this.inputs[i].disabled = true;
}
}
if(this.select2) {
if(this.select2v4)
this.select2.prop("disabled",true);
else
this.select2.select2("enable",false);
}
this._super();
},
destroy: function() {
if(this.select2) {
this.select2.select2('destroy');
this.select2 = null;
}
this._super();
}
});
JSONEditor.defaults.editors.base64 = JSONEditor.AbstractEditor.extend({
getNumColumns: function() {
return 4;
},
build: function() {
var self = this;
this.title = this.header = this.label = this.theme.getFormInputLabel(this.getTitle());
if(this.options.infoText) this.infoButton = this.theme.getInfoButton(this.options.infoText);
// Input that holds the base64 string
this.input = this.theme.getFormInputField('hidden');
this.container.appendChild(this.input);
// Don't show uploader if this is readonly
if(!this.schema.readOnly && !this.schema.readonly) {
if(!window.FileReader) throw "FileReader required for base64 editor";
// File uploader
this.uploader = this.theme.getFormInputField('file');
this.uploader.addEventListener('change',function(e) {
e.preventDefault();
e.stopPropagation();
if(this.files && this.files.length) {
var fr = new FileReader();
fr.onload = function(evt) {
self.value = evt.target.result;
self.refreshPreview();
self.onChange(true);
fr = null;
};
fr.readAsDataURL(this.files[0]);
}
});
}
this.preview = this.theme.getFormInputDescription(this.schema.description);
this.container.appendChild(this.preview);
this.control = this.theme.getFormControl(this.label, this.uploader||this.input, this.preview, this.infoButton);
this.container.appendChild(this.control);
},
refreshPreview: function() {
if(this.last_preview === this.value) return;
this.last_preview = this.value;
this.preview.innerHTML = '';
if(!this.value) return;
var mime = this.value.match(/^data:([^;,]+)[;,]/);
if(mime) mime = mime[1];
if(!mime) {
this.preview.innerHTML = '<em>Invalid data URI</em>';
}
else {
this.preview.innerHTML = '<strong>Type:</strong> '+mime+', <strong>Size:</strong> '+Math.floor((this.value.length-this.value.split(',')[0].length-1)/1.33333)+' bytes';
if(mime.substr(0,5)==="image") {
this.preview.innerHTML += '<br>';
var img = document.createElement('img');
img.style.maxWidth = '100%';
img.style.maxHeight = '100px';
img.src = this.value;
this.preview.appendChild(img);
}
}
},
enable: function() {
if(!this.always_disabled) {
if(this.uploader) this.uploader.disabled = false;
this._super();
}
},
disable: function(always_disabled) {
if(always_disabled) this.always_disabled = true;
if(this.uploader) this.uploader.disabled = true;
this._super();
},
setValue: function(val) {
if(this.value !== val) {
this.value = val;
this.input.value = this.value;
this.refreshPreview();
this.onChange();
}
},
destroy: function() {
if(this.preview && this.preview.parentNode) this.preview.parentNode.removeChild(this.preview);
if(this.title && this.title.parentNode) this.title.parentNode.removeChild(this.title);
if(this.input && this.input.parentNode) this.input.parentNode.removeChild(this.input);
if(this.uploader && this.uploader.parentNode) this.uploader.parentNode.removeChild(this.uploader);
this._super();
}
});
JSONEditor.defaults.editors.upload = JSONEditor.AbstractEditor.extend({
getNumColumns: function() {
return 4;
},
build: function() {
var self = this;
this.title = this.header = this.label = this.theme.getFormInputLabel(this.getTitle());
// Input that holds the base64 string
this.input = this.theme.getFormInputField('hidden');
this.container.appendChild(this.input);
// Don't show uploader if this is readonly
if(!this.schema.readOnly && !this.schema.readonly) {
if(!this.jsoneditor.options.upload) throw "Upload handler required for upload editor";
// File uploader
this.uploader = this.theme.getFormInputField('file');
this.uploader.addEventListener('change',function(e) {
e.preventDefault();
e.stopPropagation();
if(this.files && this.files.length) {
var fr = new FileReader();
fr.onload = function(evt) {
self.preview_value = evt.target.result;
self.refreshPreview();
self.onChange(true);
fr = null;
};
fr.readAsDataURL(this.files[0]);
}
});
}
var description = this.schema.description;
if (!description) description = '';
this.preview = this.theme.getFormInputDescription(description);
this.container.appendChild(this.preview);
this.control = this.theme.getFormControl(this.label, this.uploader||this.input, this.preview);
this.container.appendChild(this.control);
},
refreshPreview: function() {
if(this.last_preview === this.preview_value) return;
this.last_preview = this.preview_value;
this.preview.innerHTML = '';
if(!this.preview_value) return;
var self = this;
var mime = this.preview_value.match(/^data:([^;,]+)[;,]/);
if(mime) mime = mime[1];
if(!mime) mime = 'unknown';
var file = this.uploader.files[0];
this.preview.innerHTML = '<strong>Type:</strong> '+mime+', <strong>Size:</strong> '+file.size+' bytes';
if(mime.substr(0,5)==="image") {
this.preview.innerHTML += '<br>';
var img = document.createElement('img');
img.style.maxWidth = '100%';
img.style.maxHeight = '100px';
img.src = this.preview_value;
this.preview.appendChild(img);
}
this.preview.innerHTML += '<br>';
var uploadButton = this.getButton('Upload', 'upload', 'Upload');
this.preview.appendChild(uploadButton);
uploadButton.addEventListener('click',function(event) {
event.preventDefault();
uploadButton.setAttribute("disabled", "disabled");
self.theme.removeInputError(self.uploader);
if (self.theme.getProgressBar) {
self.progressBar = self.theme.getProgressBar();
self.preview.appendChild(self.progressBar);
}
self.jsoneditor.options.upload(self.path, file, {
success: function(url) {
self.setValue(url);
if(self.parent) self.parent.onChildEditorChange(self);
else self.jsoneditor.onChange();
if (self.progressBar) self.preview.removeChild(self.progressBar);
uploadButton.removeAttribute("disabled");
},
failure: function(error) {
self.theme.addInputError(self.uploader, error);
if (self.progressBar) self.preview.removeChild(self.progressBar);
uploadButton.removeAttribute("disabled");
},
updateProgress: function(progress) {
if (self.progressBar) {
if (progress) self.theme.updateProgressBar(self.progressBar, progress);
else self.theme.updateProgressBarUnknown(self.progressBar);
}
}
});
});
if(this.jsoneditor.options.auto_upload || this.schema.options.auto_upload) {
uploadButton.dispatchEvent(new MouseEvent('click'));
this.preview.removeChild(uploadButton);
}
},
enable: function() {
if(!this.always_disabled) {
if(this.uploader) this.uploader.disabled = false;
this._super();
}
},
disable: function(always_disabled) {
if(always_disabled) this.always_disabled = true;
if(this.uploader) this.uploader.disabled = true;
this._super();
},
setValue: function(val) {
if(this.value !== val) {
this.value = val;
this.input.value = this.value;
this.onChange();
}
},
destroy: function() {
if(this.preview && this.preview.parentNode) this.preview.parentNode.removeChild(this.preview);
if(this.title && this.title.parentNode) this.title.parentNode.removeChild(this.title);
if(this.input && this.input.parentNode) this.input.parentNode.removeChild(this.input);
if(this.uploader && this.uploader.parentNode) this.uploader.parentNode.removeChild(this.uploader);
this._super();
}
});
JSONEditor.defaults.editors.checkbox = JSONEditor.AbstractEditor.extend({
setValue: function(value,initial) {
this.value = !!value;
this.input.checked = this.value;
this.onChange();
},
register: function() {
this._super();
if(!this.input) return;
this.input.setAttribute('name',this.formname);
},
unregister: function() {
this._super();
if(!this.input) return;
this.input.removeAttribute('name');
},
getNumColumns: function() {
return Math.min(12,Math.max(this.getTitle().length/7,2));
},
build: function() {
var self = this;
if(!this.options.compact) {
this.label = this.header = this.theme.getCheckboxLabel(this.getTitle());
}
if(this.schema.description) this.description = this.theme.getFormInputDescription(this.schema.description);
if(this.options.infoText) this.infoButton = this.theme.getInfoButton(this.options.infoText);
if(this.options.compact) this.container.className += ' compact';
this.input = this.theme.getCheckbox();
this.control = this.theme.getFormControl(this.label, this.input, this.description, this.infoButton);
if(this.schema.readOnly || this.schema.readonly) {
this.always_disabled = true;
this.input.disabled = true;
}
this.input.addEventListener('change',function(e) {
e.preventDefault();
e.stopPropagation();
self.value = this.checked;
self.onChange(true);
});
this.container.appendChild(this.control);
},
enable: function() {
if(!this.always_disabled) {
this.input.disabled = false;
this._super();
}
},
disable: function(always_disabled) {
if(always_disabled) this.always_disabled = true;
this.input.disabled = true;
this._super();
},
destroy: function() {
if(this.label && this.label.parentNode) this.label.parentNode.removeChild(this.label);
if(this.description && this.description.parentNode) this.description.parentNode.removeChild(this.description);
if(this.input && this.input.parentNode) this.input.parentNode.removeChild(this.input);
this._super();
}
});
JSONEditor.defaults.editors.arraySelectize = JSONEditor.AbstractEditor.extend({
build: function() {
this.title = this.theme.getFormInputLabel(this.getTitle());
this.title_controls = this.theme.getHeaderButtonHolder();
this.title.appendChild(this.title_controls);
this.error_holder = document.createElement('div');
if(this.schema.description) {
this.description = this.theme.getDescription(this.schema.description);
}
this.input = document.createElement('select');
this.input.setAttribute('multiple', 'multiple');
var group = this.theme.getFormControl(this.title, this.input, this.description);
this.container.appendChild(group);
this.container.appendChild(this.error_holder);
window.jQuery(this.input).selectize({
delimiter: false,
createOnBlur: true,
create: true
});
},
postBuild: function() {
var self = this;
this.input.selectize.on('change', function(event) {
self.refreshValue();
self.onChange(true);
});
},
destroy: function() {
this.empty(true);
if(this.title && this.title.parentNode) this.title.parentNode.removeChild(this.title);
if(this.description && this.description.parentNode) this.description.parentNode.removeChild(this.description);
if(this.input && this.input.parentNode) this.input.parentNode.removeChild(this.input);
this._super();
},
empty: function(hard) {},
setValue: function(value, initial) {
var self = this;
// Update the array's value, adding/removing rows when necessary
value = value || [];
if(!(Array.isArray(value))) value = [value];
this.input.selectize.clearOptions();
this.input.selectize.clear(true);
value.forEach(function(item) {
self.input.selectize.addOption({text: item, value: item});
});
this.input.selectize.setValue(value);
this.refreshValue(initial);
},
refreshValue: function(force) {
this.value = this.input.selectize.getValue();
},
showValidationErrors: function(errors) {
var self = this;
// Get all the errors that pertain to this editor
var my_errors = [];
var other_errors = [];
$each(errors, function(i,error) {
if(error.path === self.path) {
my_errors.push(error);
}
else {
other_errors.push(error);
}
});
// Show errors for this editor
if(this.error_holder) {
if(my_errors.length) {
var message = [];
this.error_holder.innerHTML = '';
this.error_holder.style.display = '';
$each(my_errors, function(i,error) {
self.error_holder.appendChild(self.theme.getErrorMessage(error.message));
});
}
// Hide error area
else {
this.error_holder.style.display = 'none';
}
}
}
});
var matchKey = (function () {
var elem = document.documentElement;
if (elem.matches) return 'matches';
else if (elem.webkitMatchesSelector) return 'webkitMatchesSelector';
else if (elem.mozMatchesSelector) return 'mozMatchesSelector';
else if (elem.msMatchesSelector) return 'msMatchesSelector';
else if (elem.oMatchesSelector) return 'oMatchesSelector';
})();
JSONEditor.AbstractTheme = Class.extend({
getContainer: function() {
return document.createElement('div');
},
getFloatRightLinkHolder: function() {
var el = document.createElement('div');
el.style = el.style || {};
el.style.cssFloat = 'right';
el.style.marginLeft = '10px';
return el;
},
getModal: function() {
var el = document.createElement('div');
el.style.backgroundColor = 'white';
el.style.border = '1px solid black';
el.style.boxShadow = '3px 3px black';
el.style.position = 'absolute';
el.style.zIndex = '10';
el.style.display = 'none';
return el;
},
getGridContainer: function() {
var el = document.createElement('div');
return el;
},
getGridRow: function() {
var el = document.createElement('div');
el.className = 'row';
return el;
},
getGridColumn: function() {
var el = document.createElement('div');
return el;
},
setGridColumnSize: function(el,size) {
},
getLink: function(text) {
var el = document.createElement('a');
el.setAttribute('href','#');
el.appendChild(document.createTextNode(text));
return el;
},
disableHeader: function(header) {
header.style.color = '#ccc';
},
disableLabel: function(label) {
label.style.color = '#ccc';
},
enableHeader: function(header) {
header.style.color = '';
},
enableLabel: function(label) {
label.style.color = '';
},
getInfoButton: function(text) {
var icon = document.createElement('span');
icon.innerText = "ⓘ";
icon.style.fontSize = "16px";
icon.style.fontWeight = "bold";
icon.style.padding = ".25rem";
icon.style.position = "relative";
icon.style.display = "inline-block";
var tooltip = document.createElement('span');
tooltip.style.fontSize = "12px";
icon.style.fontWeight = "normal";
tooltip.style["font-family"] = "sans-serif";
tooltip.style.visibility = "hidden";
tooltip.style["background-color"] = "rgba(50, 50, 50, .75)";
tooltip.style.margin = "0 .25rem";
tooltip.style.color = "#FAFAFA";
tooltip.style.padding = ".5rem 1rem";
tooltip.style["border-radius"] = ".25rem";
tooltip.style.width = "20rem";
tooltip.style.position = "absolute";
tooltip.innerText = text;
icon.onmouseover = function() {
tooltip.style.visibility = "visible";
};
icon.onmouseleave = function() {
tooltip.style.visibility = "hidden";
};
icon.appendChild(tooltip);
return icon;
},
getFormInputLabel: function(text) {
var el = document.createElement('label');
el.appendChild(document.createTextNode(text));
return el;
},
getCheckboxLabel: function(text) {
var el = this.getFormInputLabel(text);
el.style.fontWeight = 'normal';
return el;
},
getHeader: function(text) {
var el = document.createElement('h3');
if(typeof text === "string") {
el.textContent = text;
}
else {
el.appendChild(text);
}
return el;
},
getCheckbox: function() {
var el = this.getFormInputField('checkbox');
el.style.display = 'inline-block';
el.style.width = 'auto';
return el;
},
getMultiCheckboxHolder: function(controls,label,description) {
var el = document.createElement('div');
if(label) {
label.style.display = 'block';
el.appendChild(label);
}
for(var i in controls) {
if(!controls.hasOwnProperty(i)) continue;
controls[i].style.display = 'inline-block';
controls[i].style.marginRight = '20px';
el.appendChild(controls[i]);
}
if(description) el.appendChild(description);
return el;
},
getSelectInput: function(options) {
var select = document.createElement('select');
if(options) this.setSelectOptions(select, options);
return select;
},
getSwitcher: function(options) {
var switcher = this.getSelectInput(options);
switcher.style.backgroundColor = 'transparent';
switcher.style.display = 'inline-block';
switcher.style.fontStyle = 'italic';
switcher.style.fontWeight = 'normal';
switcher.style.height = 'auto';
switcher.style.marginBottom = 0;
switcher.style.marginLeft = '5px';
switcher.style.padding = '0 0 0 3px';
switcher.style.width = 'auto';
return switcher;
},
getSwitcherOptions: function(switcher) {
return switcher.getElementsByTagName('option');
},
setSwitcherOptions: function(switcher, options, titles) {
this.setSelectOptions(switcher, options, titles);
},
setSelectOptions: function(select, options, titles) {
titles = titles || [];
select.innerHTML = '';
for(var i=0; i<options.length; i++) {
var option = document.createElement('option');
option.setAttribute('value',options[i]);
option.textContent = titles[i] || options[i];
select.appendChild(option);
}
},
getTextareaInput: function() {
var el = document.createElement('textarea');
el.style = el.style || {};
el.style.width = '100%';
el.style.height = '300px';
el.style.boxSizing = 'border-box';
return el;
},
getRangeInput: function(min,max,step) {
var el = this.getFormInputField('range');
el.setAttribute('min',min);
el.setAttribute('max',max);
el.setAttribute('step',step);
return el;
},
getFormInputField: function(type) {
var el = document.createElement('input');
el.setAttribute('type',type);
return el;
},
afterInputReady: function(input) {
},
getFormControl: function(label, input, description, infoText) {
var el = document.createElement('div');
el.className = 'form-control';
if(label) el.appendChild(label);
if(input.type === 'checkbox' && label) {
label.insertBefore(input,label.firstChild);
if(infoText) label.appendChild(infoText);
}
else {
if(infoText) label.appendChild(infoText);
el.appendChild(input);
}
if(description) el.appendChild(description);
return el;
},
getIndentedPanel: function() {
var el = document.createElement('div');
el.style = el.style || {};
el.style.paddingLeft = '10px';
el.style.marginLeft = '10px';
el.style.borderLeft = '1px solid #ccc';
return el;
},
getChildEditorHolder: function() {
return document.createElement('div');
},
getDescription: function(text) {
var el = document.createElement('p');
el.innerHTML = text;
return el;
},
getCheckboxDescription: function(text) {
return this.getDescription(text);
},
getFormInputDescription: function(text) {
return this.getDescription(text);
},
getHeaderButtonHolder: function() {
return this.getButtonHolder();
},
getButtonHolder: function() {
return document.createElement('div');
},
getButton: function(text, icon, title) {
var el = document.createElement('button');
el.type = 'button';
this.setButtonText(el,text,icon,title);
return el;
},
setButtonText: function(button, text, icon, title) {
button.innerHTML = '';
if(icon) {
button.appendChild(icon);
button.innerHTML += ' ';
}
button.appendChild(document.createTextNode(text));
if(title) button.setAttribute('title',title);
},
getTable: function() {
return document.createElement('table');
},
getTableRow: function() {
return document.createElement('tr');
},
getTableHead: function() {
return document.createElement('thead');
},
getTableBody: function() {
return document.createElement('tbody');
},
getTableHeaderCell: function(text) {
var el = document.createElement('th');
el.textContent = text;
return el;
},
getTableCell: function() {
var el = document.createElement('td');
return el;
},
getErrorMessage: function(text) {
var el = document.createElement('p');
el.style = el.style || {};
el.style.color = 'red';
el.appendChild(document.createTextNode(text));
return el;
},
addInputError: function(input, text) {
},
removeInputError: function(input) {
},
addTableRowError: function(row) {
},
removeTableRowError: function(row) {
},
getTabHolder: function() {
var el = document.createElement('div');
el.innerHTML = "<div style='float: left; width: 130px;' class='tabs'></div><div class='content' style='margin-left: 130px;'></div><div style='clear:both;'></div>";
return el;
},
applyStyles: function(el,styles) {
el.style = el.style || {};
for(var i in styles) {
if(!styles.hasOwnProperty(i)) continue;
el.style[i] = styles[i];
}
},
closest: function(elem, selector) {
while (elem && elem !== document) {
if (elem[matchKey]) {
if (elem[matchKey](selector)) {
return elem;
} else {
elem = elem.parentNode;
}
}
else {
return false;
}
}
return false;
},
getTab: function(span) {
var el = document.createElement('div');
el.appendChild(span);
el.style = el.style || {};
this.applyStyles(el,{
border: '1px solid #ccc',
borderWidth: '1px 0 1px 1px',
textAlign: 'center',
lineHeight: '30px',
borderRadius: '5px',
borderBottomRightRadius: 0,
borderTopRightRadius: 0,
fontWeight: 'bold',
cursor: 'pointer'
});
return el;
},
getTabContentHolder: function(tab_holder) {
return tab_holder.children[1];
},
getTabContent: function() {
return this.getIndentedPanel();
},
markTabActive: function(tab) {
this.applyStyles(tab,{
opacity: 1,
background: 'white'
});
},
markTabInactive: function(tab) {
this.applyStyles(tab,{
opacity:0.5,
background: ''
});
},
addTab: function(holder, tab) {
holder.children[0].appendChild(tab);
},
getBlockLink: function() {
var link = document.createElement('a');
link.style.display = 'block';
return link;
},
getBlockLinkHolder: function() {
var el = document.createElement('div');
return el;
},
getLinksHolder: function() {
var el = document.createElement('div');
return el;
},
createMediaLink: function(holder,link,media) {
holder.appendChild(link);
media.style.width='100%';
holder.appendChild(media);
},
createImageLink: function(holder,link,image) {
holder.appendChild(link);
link.appendChild(image);
}
});
JSONEditor.defaults.themes.bootstrap2 = JSONEditor.AbstractTheme.extend({
getRangeInput: function(min, max, step) {
// TODO: use bootstrap slider
return this._super(min, max, step);
},
getGridContainer: function() {
var el = document.createElement('div');
el.className = 'container-fluid';
return el;
},
getGridRow: function() {
var el = document.createElement('div');
el.className = 'row-fluid';
return el;
},
getFormInputLabel: function(text) {
var el = this._super(text);
el.style.display = 'inline-block';
el.style.fontWeight = 'bold';
return el;
},
setGridColumnSize: function(el,size) {
el.className = 'span'+size;
},
getSelectInput: function(options) {
var input = this._super(options);
input.style.width = 'auto';
input.style.maxWidth = '98%';
return input;
},
getFormInputField: function(type) {
var el = this._super(type);
el.style.width = '98%';
return el;
},
afterInputReady: function(input) {
if(input.controlgroup) return;
input.controlgroup = this.closest(input,'.control-group');
input.controls = this.closest(input,'.controls');
if(this.closest(input,'.compact')) {
input.controlgroup.className = input.controlgroup.className.replace(/control-group/g,'').replace(/[ ]{2,}/g,' ');
input.controls.className = input.controlgroup.className.replace(/controls/g,'').replace(/[ ]{2,}/g,' ');
input.style.marginBottom = 0;
}
if (this.queuedInputErrorText) {
var text = this.queuedInputErrorText;
delete this.queuedInputErrorText;
this.addInputError(input,text);
}
// TODO: use bootstrap slider
},
getIndentedPanel: function() {
var el = document.createElement('div');
el.className = 'well well-small';
el.style.paddingBottom = 0;
return el;
},
getInfoButton: function(text) {
var icon = document.createElement('span');
icon.className = "icon-info-sign pull-right";
icon.style.padding = ".25rem";
icon.style.position = "relative";
icon.style.display = "inline-block";
var tooltip = document.createElement('span');
tooltip.style["font-family"] = "sans-serif";
tooltip.style.visibility = "hidden";
tooltip.style["background-color"] = "rgba(50, 50, 50, .75)";
tooltip.style.margin = "0 .25rem";
tooltip.style.color = "#FAFAFA";
tooltip.style.padding = ".5rem 1rem";
tooltip.style["border-radius"] = ".25rem";
tooltip.style.width = "25rem";
tooltip.style.transform = "translateX(-27rem) translateY(-.5rem)";
tooltip.style.position = "absolute";
tooltip.innerText = text;
icon.onmouseover = function() {
tooltip.style.visibility = "visible";
};
icon.onmouseleave = function() {
tooltip.style.visibility = "hidden";
};
icon.appendChild(tooltip);
return icon;
},
getFormInputDescription: function(text) {
var el = document.createElement('p');
el.className = 'help-inline';
el.textContent = text;
return el;
},
getFormControl: function(label, input, description, infoText) {
var ret = document.createElement('div');
ret.className = 'control-group';
var controls = document.createElement('div');
controls.className = 'controls';
if(label && input.getAttribute('type') === 'checkbox') {
ret.appendChild(controls);
label.className += ' checkbox';
label.appendChild(input);
controls.appendChild(label);
if(infoText) controls.appendChild(infoText);
controls.style.height = '30px';
}
else {
if(label) {
label.className += ' control-label';
ret.appendChild(label);
}
if(infoText) controls.appendChild(infoText);
controls.appendChild(input);
ret.appendChild(controls);
}
if(description) controls.appendChild(description);
return ret;
},
getHeaderButtonHolder: function() {
var el = this.getButtonHolder();
el.style.marginLeft = '10px';
return el;
},
getButtonHolder: function() {
var el = document.createElement('div');
el.className = 'btn-group';
return el;
},
getButton: function(text, icon, title) {
var el = this._super(text, icon, title);
el.className += ' btn btn-default';
return el;
},
getTable: function() {
var el = document.createElement('table');
el.className = 'table table-bordered';
el.style.width = 'auto';
el.style.maxWidth = 'none';
return el;
},
addInputError: function(input,text) {
if(!input.controlgroup) {
this.queuedInputErrorText = text;
return;
}
if(!input.controlgroup || !input.controls) return;
input.controlgroup.className += ' error';
if(!input.errmsg) {
input.errmsg = document.createElement('p');
input.errmsg.className = 'help-block errormsg';
input.controls.appendChild(input.errmsg);
}
else {
input.errmsg.style.display = '';
}
input.errmsg.textContent = text;
},
removeInputError: function(input) {
if(!input.controlgroup) {
delete this.queuedInputErrorText;
}
if(!input.errmsg) return;
input.errmsg.style.display = 'none';
input.controlgroup.className = input.controlgroup.className.replace(/\s?error/g,'');
},
getTabHolder: function() {
var el = document.createElement('div');
el.className = 'tabbable tabs-left';
el.innerHTML = "<ul class='nav nav-tabs span2' style='margin-right: 0;'></ul><div class='tab-content span10' style='overflow:visible;'></div>";
return el;
},
getTab: function(text) {
var el = document.createElement('li');
var a = document.createElement('a');
a.setAttribute('href','#');
a.appendChild(text);
el.appendChild(a);
return el;
},
getTabContentHolder: function(tab_holder) {
return tab_holder.children[1];
},
getTabContent: function() {
var el = document.createElement('div');
el.className = 'tab-pane active';
return el;
},
markTabActive: function(tab) {
tab.className += ' active';
},
markTabInactive: function(tab) {
tab.className = tab.className.replace(/\s?active/g,'');
},
addTab: function(holder, tab) {
holder.children[0].appendChild(tab);
},
getProgressBar: function() {
var container = document.createElement('div');
container.className = 'progress';
var bar = document.createElement('div');
bar.className = 'bar';
bar.style.width = '0%';
container.appendChild(bar);
return container;
},
updateProgressBar: function(progressBar, progress) {
if (!progressBar) return;
progressBar.firstChild.style.width = progress + "%";
},
updateProgressBarUnknown: function(progressBar) {
if (!progressBar) return;
progressBar.className = 'progress progress-striped active';
progressBar.firstChild.style.width = '100%';
}
});
JSONEditor.defaults.themes.bootstrap3 = JSONEditor.AbstractTheme.extend({
getSelectInput: function(options) {
var el = this._super(options);
el.className += 'form-control';
//el.style.width = 'auto';
return el;
},
setGridColumnSize: function(el,size) {
el.className = 'col-md-'+size;
},
afterInputReady: function(input) {
if(input.controlgroup) return;
input.controlgroup = this.closest(input,'.form-group');
if(this.closest(input,'.compact')) {
input.controlgroup.style.marginBottom = 0;
}
if (this.queuedInputErrorText) {
var text = this.queuedInputErrorText;
delete this.queuedInputErrorText;
this.addInputError(input,text);
}
// TODO: use bootstrap slider
},
getTextareaInput: function() {
var el = document.createElement('textarea');
el.className = 'form-control';
return el;
},
getRangeInput: function(min, max, step) {
// TODO: use better slider
return this._super(min, max, step);
},
getFormInputField: function(type) {
var el = this._super(type);
if(type !== 'checkbox') {
el.className += 'form-control';
}
return el;
},
getFormControl: function(label, input, description, infoText) {
var group = document.createElement('div');
if(label && input.type === 'checkbox') {
group.className += ' checkbox';
label.appendChild(input);
label.style.fontSize = '14px';
group.style.marginTop = '0';
if(infoText) group.appendChild(infoText);
group.appendChild(label);
input.style.position = 'relative';
input.style.cssFloat = 'left';
}
else {
group.className += ' form-group';
if(label) {
label.className += ' control-label';
group.appendChild(label);
}
if(infoText) group.appendChild(infoText);
group.appendChild(input);
}
if(description) group.appendChild(description);
return group;
},
getIndentedPanel: function() {
var el = document.createElement('div');
el.className = 'well well-sm';
el.style.paddingBottom = 0;
return el;
},
getInfoButton: function(text) {
var icon = document.createElement('span');
icon.className = "glyphicon glyphicon-info-sign pull-right";
icon.style.padding = ".25rem";
icon.style.position = "relative";
icon.style.display = "inline-block";
var tooltip = document.createElement('span');
tooltip.style["font-family"] = "sans-serif";
tooltip.style.visibility = "hidden";
tooltip.style["background-color"] = "rgba(50, 50, 50, .75)";
tooltip.style.margin = "0 .25rem";
tooltip.style.color = "#FAFAFA";
tooltip.style.padding = ".5rem 1rem";
tooltip.style["border-radius"] = ".25rem";
tooltip.style.width = "25rem";
tooltip.style.transform = "translateX(-27rem) translateY(-.5rem)";
tooltip.style.position = "absolute";
tooltip.innerText = text;
icon.onmouseover = function() {
tooltip.style.visibility = "visible";
};
icon.onmouseleave = function() {
tooltip.style.visibility = "hidden";
};
icon.appendChild(tooltip);
return icon;
},
getFormInputDescription: function(text) {
var el = document.createElement('p');
el.className = 'help-block';
el.innerHTML = text;
return el;
},
getHeaderButtonHolder: function() {
var el = this.getButtonHolder();
el.style.marginLeft = '10px';
return el;
},
getButtonHolder: function() {
var el = document.createElement('div');
el.className = 'btn-group';
return el;
},
getButton: function(text, icon, title) {
var el = this._super(text, icon, title);
el.className += 'btn btn-default';
return el;
},
getTable: function() {
var el = document.createElement('table');
el.className = 'table table-bordered';
el.style.width = 'auto';
el.style.maxWidth = 'none';
return el;
},
addInputError: function(input,text) {
if(!input.controlgroup) {
this.queuedInputErrorText = text;
return;
}
input.controlgroup.className += ' has-error';
if(!input.errmsg) {
input.errmsg = document.createElement('p');
input.errmsg.className = 'help-block errormsg';
input.controlgroup.appendChild(input.errmsg);
}
else {
input.errmsg.style.display = '';
}
input.errmsg.textContent = text;
},
removeInputError: function(input) {
if(!input.controlgroup) {
delete this.queuedInputErrorText;
}
if(!input.errmsg) return;
input.errmsg.style.display = 'none';
input.controlgroup.className = input.controlgroup.className.replace(/\s?has-error/g,'');
},
getTabHolder: function() {
var el = document.createElement('div');
el.innerHTML = "<div class='tabs list-group col-md-2'></div><div class='col-md-10'></div>";
el.className = 'rows';
return el;
},
getTab: function(text) {
var el = document.createElement('a');
el.className = 'list-group-item';
el.setAttribute('href','#');
el.appendChild(text);
return el;
},
markTabActive: function(tab) {
tab.className += ' active';
},
markTabInactive: function(tab) {
tab.className = tab.className.replace(/\s?active/g,'');
},
getProgressBar: function() {
var min = 0, max = 100, start = 0;
var container = document.createElement('div');
container.className = 'progress';
var bar = document.createElement('div');
bar.className = 'progress-bar';
bar.setAttribute('role', 'progressbar');
bar.setAttribute('aria-valuenow', start);
bar.setAttribute('aria-valuemin', min);
bar.setAttribute('aria-valuenax', max);
bar.innerHTML = start + "%";
container.appendChild(bar);
return container;
},
updateProgressBar: function(progressBar, progress) {
if (!progressBar) return;
var bar = progressBar.firstChild;
var percentage = progress + "%";
bar.setAttribute('aria-valuenow', progress);
bar.style.width = percentage;
bar.innerHTML = percentage;
},
updateProgressBarUnknown: function(progressBar) {
if (!progressBar) return;
var bar = progressBar.firstChild;
progressBar.className = 'progress progress-striped active';
bar.removeAttribute('aria-valuenow');
bar.style.width = '100%';
bar.innerHTML = '';
}
});
JSONEditor.defaults.themes.bootstrap4 = JSONEditor.AbstractTheme.extend({
getSelectInput: function(options) {
var el = this._super(options);
el.className += "form-control";
//el.style.width = 'auto';
return el;
},
setGridColumnSize: function(el, size) {
el.className = "col-md-" + size;
},
afterInputReady: function(input) {
if (input.controlgroup) return;
input.controlgroup = this.closest(input, ".form-group");
if (this.closest(input, ".compact")) {
input.controlgroup.style.marginBottom = 0;
}
// TODO: use bootstrap slider
},
getTextareaInput: function() {
var el = document.createElement("textarea");
el.className = "form-control";
return el;
},
getRangeInput: function(min, max, step) {
// TODO: use better slider
return this._super(min, max, step);
},
getFormInputField: function(type) {
var el = this._super(type);
if (type !== "checkbox") {
el.className += "form-control";
}
return el;
},
getFormControl: function(label, input, description) {
var group = document.createElement("div");
if (label && input.type === "checkbox") {
group.className += " checkbox";
label.appendChild(input);
label.style.fontSize = "14px";
group.style.marginTop = "0";
group.appendChild(label);
input.style.position = "relative";
input.style.cssFloat = "left";
} else {
group.className += " form-group";
if (label) {
label.className += " form-control-label";
group.appendChild(label);
}
group.appendChild(input);
}
if (description) group.appendChild(description);
return group;
},
getIndentedPanel: function() {
var el = document.createElement("div");
el.className = "card card-block bg-faded";
el.style.paddingBottom = 0;
return el;
},
getFormInputDescription: function(text) {
var el = document.createElement("p");
el.className = "form-text";
el.innerHTML = text;
return el;
},
getHeaderButtonHolder: function() {
var el = this.getButtonHolder();
el.style.marginLeft = "10px";
return el;
},
getButtonHolder: function() {
var el = document.createElement("div");
el.className = "btn-group";
return el;
},
getButton: function(text, icon, title) {
var el = this._super(text, icon, title);
el.className += "btn btn-secondary";
return el;
},
getTable: function() {
var el = document.createElement("table");
el.className = "table-bordered table-sm";
el.style.width = "auto";
el.style.maxWidth = "none";
return el;
},
addInputError: function(input, text) {
if (!input.controlgroup) return;
input.controlgroup.className += " has-error";
if (!input.errmsg) {
input.errmsg = document.createElement("p");
input.errmsg.className = "form-text errormsg";
input.controlgroup.appendChild(input.errmsg);
} else {
input.errmsg.style.display = "";
}
input.errmsg.textContent = text;
},
removeInputError: function(input) {
if (!input.errmsg) return;
input.errmsg.style.display = "none";
input.controlgroup.className = input.controlgroup.className.replace(
/\s?has-error/g,
""
);
},
getTabHolder: function() {
var el = document.createElement("div");
el.innerHTML =
"<div class='tabs list-group col-md-2'></div><div class='col-md-10'></div>";
el.className = "rows";
return el;
},
getTab: function(text) {
var el = document.createElement("a");
el.className = "list-group-item-action";
el.setAttribute("href", "#");
el.appendChild(text);
return el;
},
markTabActive: function(tab) {
tab.className += " active";
},
markTabInactive: function(tab) {
tab.className = tab.className.replace(/\s?active/g, "");
},
getProgressBar: function() {
var min = 0,
max = 100,
start = 0;
var container = document.createElement("div");
container.className = "progress";
var bar = document.createElement("div");
bar.className = "progress-bar";
bar.setAttribute("role", "progressbar");
bar.setAttribute("aria-valuenow", start);
bar.setAttribute("aria-valuemin", min);
bar.setAttribute("aria-valuenax", max);
bar.innerHTML = start + "%";
container.appendChild(bar);
return container;
},
updateProgressBar: function(progressBar, progress) {
if (!progressBar) return;
var bar = progressBar.firstChild;
var percentage = progress + "%";
bar.setAttribute("aria-valuenow", progress);
bar.style.width = percentage;
bar.innerHTML = percentage;
},
updateProgressBarUnknown: function(progressBar) {
if (!progressBar) return;
var bar = progressBar.firstChild;
progressBar.className = "progress progress-striped active";
bar.removeAttribute("aria-valuenow");
bar.style.width = "100%";
bar.innerHTML = "";
}
});
// Base Foundation theme
JSONEditor.defaults.themes.foundation = JSONEditor.AbstractTheme.extend({
getChildEditorHolder: function() {
var el = document.createElement('div');
el.style.marginBottom = '15px';
return el;
},
getSelectInput: function(options) {
var el = this._super(options);
el.style.minWidth = 'none';
el.style.padding = '5px';
el.style.marginTop = '3px';
return el;
},
getSwitcher: function(options) {
var el = this._super(options);
el.style.paddingRight = '8px';
return el;
},
afterInputReady: function(input) {
if(input.group) return;
if(this.closest(input,'.compact')) {
input.style.marginBottom = 0;
}
input.group = this.closest(input,'.form-control');
if (this.queuedInputErrorText) {
var text = this.queuedInputErrorText;
delete this.queuedInputErrorText;
this.addInputError(input,text);
}
},
getFormInputLabel: function(text) {
var el = this._super(text);
el.style.display = 'inline-block';
return el;
},
getFormInputField: function(type) {
var el = this._super(type);
el.style.width = '100%';
el.style.marginBottom = type==='checkbox'? '0' : '12px';
return el;
},
getFormInputDescription: function(text) {
var el = document.createElement('p');
el.textContent = text;
el.style.marginTop = '-10px';
el.style.fontStyle = 'italic';
return el;
},
getIndentedPanel: function() {
var el = document.createElement('div');
el.className = 'panel';
el.style.paddingBottom = 0;
return el;
},
getHeaderButtonHolder: function() {
var el = this.getButtonHolder();
el.style.display = 'inline-block';
el.style.marginLeft = '10px';
el.style.verticalAlign = 'middle';
return el;
},
getButtonHolder: function() {
var el = document.createElement('div');
el.className = 'button-group';
return el;
},
getButton: function(text, icon, title) {
var el = this._super(text, icon, title);
el.className += ' small button';
return el;
},
addInputError: function(input,text) {
if(!input.group) {
this.queuedInputErrorText = text;
return;
}
input.group.className += ' error';
if(!input.errmsg) {
input.insertAdjacentHTML('afterend','<small class="error"></small>');
input.errmsg = input.parentNode.getElementsByClassName('error')[0];
}
else {
input.errmsg.style.display = '';
}
input.errmsg.textContent = text;
},
removeInputError: function(input) {
if(!input.group) {
delete this.queuedInputErrorText;
}
if(!input.errmsg) return;
input.group.className = input.group.className.replace(/ error/g,'');
input.errmsg.style.display = 'none';
},
getProgressBar: function() {
var progressBar = document.createElement('div');
progressBar.className = 'progress';
var meter = document.createElement('span');
meter.className = 'meter';
meter.style.width = '0%';
progressBar.appendChild(meter);
return progressBar;
},
updateProgressBar: function(progressBar, progress) {
if (!progressBar) return;
progressBar.firstChild.style.width = progress + '%';
},
updateProgressBarUnknown: function(progressBar) {
if (!progressBar) return;
progressBar.firstChild.style.width = '100%';
}
});
// Foundation 3 Specific Theme
JSONEditor.defaults.themes.foundation3 = JSONEditor.defaults.themes.foundation.extend({
getHeaderButtonHolder: function() {
var el = this._super();
el.style.fontSize = '.6em';
return el;
},
getFormInputLabel: function(text) {
var el = this._super(text);
el.style.fontWeight = 'bold';
return el;
},
getTabHolder: function() {
var el = document.createElement('div');
el.className = 'row';
el.innerHTML = "<dl class='tabs vertical two columns'></dl><div class='tabs-content ten columns'></div>";
return el;
},
setGridColumnSize: function(el,size) {
var sizes = ['zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve'];
el.className = 'columns '+sizes[size];
},
getTab: function(text) {
var el = document.createElement('dd');
var a = document.createElement('a');
a.setAttribute('href','#');
a.appendChild(text);
el.appendChild(a);
return el;
},
getTabContentHolder: function(tab_holder) {
return tab_holder.children[1];
},
getTabContent: function() {
var el = document.createElement('div');
el.className = 'content active';
el.style.paddingLeft = '5px';
return el;
},
markTabActive: function(tab) {
tab.className += ' active';
},
markTabInactive: function(tab) {
tab.className = tab.className.replace(/\s*active/g,'');
},
addTab: function(holder, tab) {
holder.children[0].appendChild(tab);
}
});
// Foundation 4 Specific Theme
JSONEditor.defaults.themes.foundation4 = JSONEditor.defaults.themes.foundation.extend({
getHeaderButtonHolder: function() {
var el = this._super();
el.style.fontSize = '.6em';
return el;
},
setGridColumnSize: function(el,size) {
el.className = 'columns large-'+size;
},
getFormInputDescription: function(text) {
var el = this._super(text);
el.style.fontSize = '.8rem';
return el;
},
getFormInputLabel: function(text) {
var el = this._super(text);
el.style.fontWeight = 'bold';
return el;
}
});
// Foundation 5 Specific Theme
JSONEditor.defaults.themes.foundation5 = JSONEditor.defaults.themes.foundation.extend({
getFormInputDescription: function(text) {
var el = this._super(text);
el.style.fontSize = '.8rem';
return el;
},
setGridColumnSize: function(el,size) {
el.className = 'columns medium-'+size;
},
getButton: function(text, icon, title) {
var el = this._super(text,icon,title);
el.className = el.className.replace(/\s*small/g,'') + ' tiny';
return el;
},
getTabHolder: function() {
var el = document.createElement('div');
el.innerHTML = "<dl class='tabs vertical'></dl><div class='tabs-content vertical'></div>";
return el;
},
getTab: function(text) {
var el = document.createElement('dd');
var a = document.createElement('a');
a.setAttribute('href','#');
a.appendChild(text);
el.appendChild(a);
return el;
},
getTabContentHolder: function(tab_holder) {
return tab_holder.children[1];
},
getTabContent: function() {
var el = document.createElement('div');
el.className = 'content active';
el.style.paddingLeft = '5px';
return el;
},
markTabActive: function(tab) {
tab.className += ' active';
},
markTabInactive: function(tab) {
tab.className = tab.className.replace(/\s*active/g,'');
},
addTab: function(holder, tab) {
holder.children[0].appendChild(tab);
}
});
JSONEditor.defaults.themes.foundation6 = JSONEditor.defaults.themes.foundation5.extend({
getIndentedPanel: function() {
var el = document.createElement('div');
el.className = 'callout secondary';
return el;
},
getButtonHolder: function() {
var el = document.createElement('div');
el.className = 'button-group tiny';
el.style.marginBottom = 0;
return el;
},
getFormInputLabel: function(text) {
var el = this._super(text);
el.style.display = 'block';
return el;
},
getFormControl: function(label, input, description, infoText) {
var el = document.createElement('div');
el.className = 'form-control';
if(label) el.appendChild(label);
if(input.type === 'checkbox') {
label.insertBefore(input,label.firstChild);
}
else if (label) {
if(infoText) label.appendChild(infoText);
label.appendChild(input);
} else {
if(infoText) el.appendChild(infoText);
el.appendChild(input);
}
if(description) label.appendChild(description);
return el;
},
addInputError: function(input,text) {
if(!input.group) return;
input.group.className += ' error';
if(!input.errmsg) {
var errorEl = document.createElement('span');
errorEl.className = 'form-error is-visible';
input.group.getElementsByTagName('label')[0].appendChild(errorEl);
input.className = input.className + ' is-invalid-input';
input.errmsg = errorEl;
}
else {
input.errmsg.style.display = '';
input.className = '';
}
input.errmsg.textContent = text;
},
removeInputError: function(input) {
if(!input.errmsg) return;
input.className = input.className.replace(/ is-invalid-input/g,'');
if(input.errmsg.parentNode) {
input.errmsg.parentNode.removeChild(input.errmsg);
}
},
});
JSONEditor.defaults.themes.html = JSONEditor.AbstractTheme.extend({
getFormInputLabel: function(text) {
var el = this._super(text);
el.style.display = 'block';
el.style.marginBottom = '3px';
el.style.fontWeight = 'bold';
return el;
},
getFormInputDescription: function(text) {
var el = this._super(text);
el.style.fontSize = '.8em';
el.style.margin = 0;
el.style.display = 'inline-block';
el.style.fontStyle = 'italic';
return el;
},
getIndentedPanel: function() {
var el = this._super();
el.style.border = '1px solid #ddd';
el.style.padding = '5px';
el.style.margin = '5px';
el.style.borderRadius = '3px';
return el;
},
getChildEditorHolder: function() {
var el = this._super();
el.style.marginBottom = '8px';
return el;
},
getHeaderButtonHolder: function() {
var el = this.getButtonHolder();
el.style.display = 'inline-block';
el.style.marginLeft = '10px';
el.style.fontSize = '.8em';
el.style.verticalAlign = 'middle';
return el;
},
getTable: function() {
var el = this._super();
el.style.borderBottom = '1px solid #ccc';
el.style.marginBottom = '5px';
return el;
},
addInputError: function(input, text) {
input.style.borderColor = 'red';
if(!input.errmsg) {
var group = this.closest(input,'.form-control');
input.errmsg = document.createElement('div');
input.errmsg.setAttribute('class','errmsg');
input.errmsg.style = input.errmsg.style || {};
input.errmsg.style.color = 'red';
group.appendChild(input.errmsg);
}
else {
input.errmsg.style.display = 'block';
}
input.errmsg.innerHTML = '';
input.errmsg.appendChild(document.createTextNode(text));
},
removeInputError: function(input) {
input.style.borderColor = '';
if(input.errmsg) input.errmsg.style.display = 'none';
},
getProgressBar: function() {
var max = 100, start = 0;
var progressBar = document.createElement('progress');
progressBar.setAttribute('max', max);
progressBar.setAttribute('value', start);
return progressBar;
},
updateProgressBar: function(progressBar, progress) {
if (!progressBar) return;
progressBar.setAttribute('value', progress);
},
updateProgressBarUnknown: function(progressBar) {
if (!progressBar) return;
progressBar.removeAttribute('value');
}
});
JSONEditor.defaults.themes.jqueryui = JSONEditor.AbstractTheme.extend({
getTable: function() {
var el = this._super();
el.setAttribute('cellpadding',5);
el.setAttribute('cellspacing',0);
return el;
},
getTableHeaderCell: function(text) {
var el = this._super(text);
el.className = 'ui-state-active';
el.style.fontWeight = 'bold';
return el;
},
getTableCell: function() {
var el = this._super();
el.className = 'ui-widget-content';
return el;
},
getHeaderButtonHolder: function() {
var el = this.getButtonHolder();
el.style.marginLeft = '10px';
el.style.fontSize = '.6em';
el.style.display = 'inline-block';
return el;
},
getFormInputDescription: function(text) {
var el = this.getDescription(text);
el.style.marginLeft = '10px';
el.style.display = 'inline-block';
return el;
},
getFormControl: function(label, input, description, infoText) {
var el = this._super(label,input,description, infoText);
if(input.type === 'checkbox') {
el.style.lineHeight = '25px';
el.style.padding = '3px 0';
}
else {
el.style.padding = '4px 0 8px 0';
}
return el;
},
getDescription: function(text) {
var el = document.createElement('span');
el.style.fontSize = '.8em';
el.style.fontStyle = 'italic';
el.textContent = text;
return el;
},
getButtonHolder: function() {
var el = document.createElement('div');
el.className = 'ui-buttonset';
el.style.fontSize = '.7em';
return el;
},
getFormInputLabel: function(text) {
var el = document.createElement('label');
el.style.fontWeight = 'bold';
el.style.display = 'block';
el.textContent = text;
return el;
},
getButton: function(text, icon, title) {
var button = document.createElement("button");
button.className = 'ui-button ui-widget ui-state-default ui-corner-all';
// Icon only
if(icon && !text) {
button.className += ' ui-button-icon-only';
icon.className += ' ui-button-icon-primary ui-icon-primary';
button.appendChild(icon);
}
// Icon and Text
else if(icon) {
button.className += ' ui-button-text-icon-primary';
icon.className += ' ui-button-icon-primary ui-icon-primary';
button.appendChild(icon);
}
// Text only
else {
button.className += ' ui-button-text-only';
}
var el = document.createElement('span');
el.className = 'ui-button-text';
el.textContent = text||title||".";
button.appendChild(el);
button.setAttribute('title',title);
return button;
},
setButtonText: function(button,text, icon, title) {
button.innerHTML = '';
button.className = 'ui-button ui-widget ui-state-default ui-corner-all';
// Icon only
if(icon && !text) {
button.className += ' ui-button-icon-only';
icon.className += ' ui-button-icon-primary ui-icon-primary';
button.appendChild(icon);
}
// Icon and Text
else if(icon) {
button.className += ' ui-button-text-icon-primary';
icon.className += ' ui-button-icon-primary ui-icon-primary';
button.appendChild(icon);
}
// Text only
else {
button.className += ' ui-button-text-only';
}
var el = document.createElement('span');
el.className = 'ui-button-text';
el.textContent = text||title||".";
button.appendChild(el);
button.setAttribute('title',title);
},
getIndentedPanel: function() {
var el = document.createElement('div');
el.className = 'ui-widget-content ui-corner-all';
el.style.padding = '1em 1.4em';
el.style.marginBottom = '20px';
return el;
},
afterInputReady: function(input) {
if(input.controls) return;
input.controls = this.closest(input,'.form-control');
if (this.queuedInputErrorText) {
var text = this.queuedInputErrorText;
delete this.queuedInputErrorText;
this.addInputError(input,text);
}
},
addInputError: function(input,text) {
if(!input.controls) {
this.queuedInputErrorText = text;
return;
}
if(!input.errmsg) {
input.errmsg = document.createElement('div');
input.errmsg.className = 'ui-state-error';
input.controls.appendChild(input.errmsg);
}
else {
input.errmsg.style.display = '';
}
input.errmsg.textContent = text;
},
removeInputError: function(input) {
if(!input.controls) {
delete this.queuedInputErrorText;
}
if(!input.errmsg) return;
input.errmsg.style.display = 'none';
},
markTabActive: function(tab) {
tab.className = tab.className.replace(/\s*ui-widget-header/g,'')+' ui-state-active';
},
markTabInactive: function(tab) {
tab.className = tab.className.replace(/\s*ui-state-active/g,'')+' ui-widget-header';
}
});
JSONEditor.defaults.themes.barebones = JSONEditor.AbstractTheme.extend({
getFormInputLabel: function (text) {
var el = this._super(text);
return el;
},
getFormInputDescription: function (text) {
var el = this._super(text);
return el;
},
getIndentedPanel: function () {
var el = this._super();
return el;
},
getChildEditorHolder: function () {
var el = this._super();
return el;
},
getHeaderButtonHolder: function () {
var el = this.getButtonHolder();
return el;
},
getTable: function () {
var el = this._super();
return el;
},
addInputError: function (input, text) {
if (!input.errmsg) {
var group = this.closest(input, '.form-control');
input.errmsg = document.createElement('div');
input.errmsg.setAttribute('class', 'errmsg');
group.appendChild(input.errmsg);
}
else {
input.errmsg.style.display = 'block';
}
input.errmsg.innerHTML = '';
input.errmsg.appendChild(document.createTextNode(text));
},
removeInputError: function (input) {
input.style.borderColor = '';
if (input.errmsg) input.errmsg.style.display = 'none';
},
getProgressBar: function () {
var max = 100, start = 0;
var progressBar = document.createElement('progress');
progressBar.setAttribute('max', max);
progressBar.setAttribute('value', start);
return progressBar;
},
updateProgressBar: function (progressBar, progress) {
if (!progressBar) return;
progressBar.setAttribute('value', progress);
},
updateProgressBarUnknown: function (progressBar) {
if (!progressBar) return;
progressBar.removeAttribute('value');
}
});
JSONEditor.defaults.themes.materialize = JSONEditor.AbstractTheme.extend({
/**
* Applies grid size to specified element.
*
* @param {HTMLElement} el The DOM element to have specified size applied.
* @param {int} size The grid column size.
* @see http://materializecss.com/grid.html
*/
setGridColumnSize: function(el, size) {
el.className = 'col s' + size;
},
/**
* Gets a wrapped button element for a header.
*
* @returns {HTMLElement} The wrapped button element.
*/
getHeaderButtonHolder: function() {
return this.getButtonHolder();
},
/**
* Gets a wrapped button element.
*
* @returns {HTMLElement} The wrapped button element.
*/
getButtonHolder: function() {
return document.createElement('span');
},
/**
* Gets a single button element.
*
* @param {string} text The button text.
* @param {HTMLElement} icon The icon object.
* @param {string} title The button title.
* @returns {HTMLElement} The button object.
* @see http://materializecss.com/buttons.html
*/
getButton: function(text, icon, title) {
// Prepare icon.
if (text) {
icon.className += ' left';
icon.style.marginRight = '5px';
}
// Create and return button.
var el = this._super(text, icon, title);
el.className = 'waves-effect waves-light btn';
el.style.fontSize = '0.75rem';
el.style.height = '24px';
el.style.lineHeight = '24px';
el.style.marginLeft = '5px';
el.style.padding = '0 0.5rem';
return el;
},
/**
* Gets a form control object consisiting of several sub objects.
*
* @param {HTMLElement} label The label element.
* @param {HTMLElement} input The input element.
* @param {string} description The element description.
* @param {string} infoText The element information text.
* @returns {HTMLElement} The assembled DOM element.
* @see http://materializecss.com/forms.html
*/
getFormControl: function(label, input, description, infoText) {
var ctrl,
type = input.type;
// Checkboxes get wrapped in p elements.
if (type && type === 'checkbox') {
ctrl = document.createElement('p');
ctrl.appendChild(input);
if (label) {
label.setAttribute('for', input.id);
ctrl.appendChild(label);
}
return ctrl;
}
// Anything else gets wrapped in divs.
ctrl = this._super(label, input, description, infoText);
// Not .input-field for select wrappers.
if (!type || !type.startsWith('select'))
ctrl.className = 'input-field';
// Color needs special attention.
if (type && type === 'color') {
input.style.height = '3rem';
input.style.width = '100%';
input.style.margin = '5px 0 20px 0';
input.style.padding = '3px';
if (label) {
label.style.transform = 'translateY(-14px) scale(0.8)';
label.style['-webkit-transform'] = 'translateY(-14px) scale(0.8)';
label.style['-webkit-transform-origin'] = '0 0';
label.style['transform-origin'] = '0 0';
}
}
return ctrl;
},
getDescription: function(text) {
var el = document.createElement('div');
el.className = 'grey-text';
el.style.marginTop = '-15px';
el.innerHTML = text;
return el;
},
/**
* Gets a header element.
*
* @param {string|HTMLElement} text The header text or element.
* @returns {HTMLElement} The header element.
*/
getHeader: function(text) {
var el = document.createElement('h5');
if (typeof text === 'string') {
el.textContent = text;
} else {
el.appendChild(text);
}
return el;
},
getChildEditorHolder: function() {
var el = document.createElement('div');
el.marginBottom = '10px';
return el;
},
getIndentedPanel: function() {
var el = document.createElement("div");
el.className = "card-panel";
return el;
},
getTable: function() {
var el = document.createElement('table');
el.className = 'striped bordered';
el.style.marginBottom = '10px';
return el;
},
getTableRow: function() {
return document.createElement('tr');
},
getTableHead: function() {
return document.createElement('thead');
},
getTableBody: function() {
return document.createElement('tbody');
},
getTableHeaderCell: function(text) {
var el = document.createElement('th');
el.textContent = text;
return el;
},
getTableCell: function() {
var el = document.createElement('td');
return el;
},
/**
* Gets the tab holder element.
*
* @returns {HTMLElement} The tab holder component.
* @see https://github.com/Dogfalo/materialize/issues/2542#issuecomment-233458602
*/
getTabHolder: function() {
var html = [
'<div class="col s2">',
' <ul class="tabs" style="height: auto; margin-top: 0.82rem; -ms-flex-direction: column; -webkit-flex-direction: column; flex-direction: column; display: -webkit-flex; display: flex;">',
' </ul>',
'</div>',
'<div class="col s10">',
'<div>'
].join("\n");
var el = document.createElement('div');
el.className = 'row card-panel';
el.innerHTML = html;
return el;
},
/**
* Add specified tab to specified holder element.
*
* @param {HTMLElement} holder The tab holder element.
* @param {HTMLElement} tab The tab to add.
*/
addTab: function(holder, tab) {
holder.children[0].children[0].appendChild(tab);
},
/**
* Gets a single tab element.
*
* @param {HTMLElement} span The tab's content.
* @returns {HTMLElement} The tab element.
* @see https://github.com/Dogfalo/materialize/issues/2542#issuecomment-233458602
*/
getTab: function(span) {
var el = document.createElement('li');
el.className = 'tab';
this.applyStyles(el, {
width: '100%',
textAlign: 'left',
lineHeight: '24px',
height: '24px',
fontSize: '14px',
cursor: 'pointer'
});
el.appendChild(span);
return el;
},
/**
* Marks specified tab as active.
*
* @returns {HTMLElement} The tab element.
* @see https://github.com/Dogfalo/materialize/issues/2542#issuecomment-233458602
*/
markTabActive: function(tab) {
this.applyStyles(tab, {
width: '100%',
textAlign: 'left',
lineHeight: '24px',
height: '24px',
fontSize: '14px',
cursor: 'pointer',
color: 'rgba(238,110,115,1)',
transition: 'border-color .5s ease',
borderRight: '3px solid #424242'
});
},
/**
* Marks specified tab as inactive.
*
* @returns {HTMLElement} The tab element.
* @see https://github.com/Dogfalo/materialize/issues/2542#issuecomment-233458602
*/
markTabInactive: function(tab) {
this.applyStyles(tab, {
width: '100%',
textAlign: 'left',
lineHeight: '24px',
height: '24px',
fontSize: '14px',
cursor: 'pointer',
color: 'rgba(238,110,115,0.7)'
});
},
/**
* Returns the element that holds the tab contents.
*
* @param {HTMLElement} tabHolder The full tab holder element.
* @returns {HTMLElement} The content element inside specified tab holder.
*/
getTabContentHolder: function(tabHolder) {
return tabHolder.children[1];
},
/**
* Creates and returns a tab content element.
*
* @returns {HTMLElement} The new tab content element.
*/
getTabContent: function() {
return document.createElement('div');
},
/**
* Adds an error message to the specified input element.
*
* @param {HTMLElement} input The input element that caused the error.
* @param {string} text The error message.
*/
addInputError: function(input, text) {
// Get the parent element. Should most likely be a <div class="input-field" ... />.
var parent = input.parentNode,
el;
if (!parent) return;
// Remove any previous error.
this.removeInputError(input);
// Append an error message div.
el = document.createElement('div');
el.className = 'error-text red-text';
el.textContent = text;
parent.appendChild(el);
},
/**
* Removes any error message from the specified input element.
*
* @param {HTMLElement} input The input element that previously caused the error.
*/
removeInputError: function(input) {
// Get the parent element. Should most likely be a <div class="input-field" ... />.
var parent = input.parentElement,
els;
if (!parent) return;
// Remove all elements having class .error-text.
els = parent.getElementsByClassName('error-text');
for (var i = 0; i < els.length; i++)
parent.removeChild(els[i]);
},
addTableRowError: function(row) {
},
removeTableRowError: function(row) {
},
/**
* Gets a select DOM element.
*
* @param {object} options The option values.
* @return {HTMLElement} The DOM element.
* @see http://materializecss.com/forms.html#select
*/
getSelectInput: function(options) {
var select = this._super(options);
select.className = 'browser-default';
return select;
},
/**
* Gets a textarea DOM element.
*
* @returns {HTMLElement} The DOM element.
* @see http://materializecss.com/forms.html#textarea
*/
getTextareaInput: function() {
var el = document.createElement('textarea');
el.style.marginBottom = '5px';
el.style.fontSize = '1rem';
el.style.fontFamily = 'monospace';
return el;
},
getCheckbox: function() {
var el = this.getFormInputField('checkbox');
el.id = this.createUuid();
return el;
},
/**
* Gets the modal element for displaying Edit JSON and Properties dialogs.
*
* @returns {HTMLElement} The modal DOM element.
* @see http://materializecss.com/cards.html
*/
getModal: function() {
var el = document.createElement('div');
el.className = 'card-panel z-depth-3';
el.style.padding = '5px';
el.style.position = 'absolute';
el.style.zIndex = '10';
el.style.display = 'none';
return el;
},
/**
* Creates and returns a RFC4122 version 4 compliant unique id.
*
* @returns {string} A GUID.
* @see https://stackoverflow.com/a/2117523
*/
createUuid: function() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
});
JSONEditor.AbstractIconLib = Class.extend({
mapping: {
collapse: '',
expand: '',
"delete": '',
edit: '',
add: '',
cancel: '',
save: '',
moveup: '',
movedown: ''
},
icon_prefix: '',
getIconClass: function(key) {
if(this.mapping[key]) return this.icon_prefix+this.mapping[key];
else return null;
},
getIcon: function(key) {
var iconclass = this.getIconClass(key);
if(!iconclass) return null;
var i = document.createElement('i');
i.className = iconclass;
return i;
}
});
JSONEditor.defaults.iconlibs.bootstrap2 = JSONEditor.AbstractIconLib.extend({
mapping: {
collapse: 'chevron-down',
expand: 'chevron-up',
"delete": 'trash',
edit: 'pencil',
add: 'plus',
cancel: 'ban-circle',
save: 'ok',
moveup: 'arrow-up',
movedown: 'arrow-down'
},
icon_prefix: 'icon-'
});
JSONEditor.defaults.iconlibs.bootstrap3 = JSONEditor.AbstractIconLib.extend({
mapping: {
collapse: 'chevron-down',
expand: 'chevron-right',
"delete": 'remove',
edit: 'pencil',
add: 'plus',
cancel: 'floppy-remove',
save: 'floppy-saved',
moveup: 'arrow-up',
movedown: 'arrow-down'
},
icon_prefix: 'glyphicon glyphicon-'
});
JSONEditor.defaults.iconlibs.fontawesome3 = JSONEditor.AbstractIconLib.extend({
mapping: {
collapse: 'chevron-down',
expand: 'chevron-right',
"delete": 'remove',
edit: 'pencil',
add: 'plus',
cancel: 'ban-circle',
save: 'save',
moveup: 'arrow-up',
movedown: 'arrow-down'
},
icon_prefix: 'icon-'
});
JSONEditor.defaults.iconlibs.fontawesome4 = JSONEditor.AbstractIconLib.extend({
mapping: {
collapse: 'caret-square-o-down',
expand: 'caret-square-o-right',
"delete": 'times',
edit: 'pencil',
add: 'plus',
cancel: 'ban',
save: 'save',
moveup: 'arrow-up',
movedown: 'arrow-down',
copy: 'files-o'
},
icon_prefix: 'fa fa-'
});
JSONEditor.defaults.iconlibs.foundation2 = JSONEditor.AbstractIconLib.extend({
mapping: {
collapse: 'minus',
expand: 'plus',
"delete": 'remove',
edit: 'edit',
add: 'add-doc',
cancel: 'error',
save: 'checkmark',
moveup: 'up-arrow',
movedown: 'down-arrow'
},
icon_prefix: 'foundicon-'
});
JSONEditor.defaults.iconlibs.foundation3 = JSONEditor.AbstractIconLib.extend({
mapping: {
collapse: 'minus',
expand: 'plus',
"delete": 'x',
edit: 'pencil',
add: 'page-add',
cancel: 'x-circle',
save: 'save',
moveup: 'arrow-up',
movedown: 'arrow-down'
},
icon_prefix: 'fi-'
});
JSONEditor.defaults.iconlibs.jqueryui = JSONEditor.AbstractIconLib.extend({
mapping: {
collapse: 'triangle-1-s',
expand: 'triangle-1-e',
"delete": 'trash',
edit: 'pencil',
add: 'plusthick',
cancel: 'closethick',
save: 'disk',
moveup: 'arrowthick-1-n',
movedown: 'arrowthick-1-s'
},
icon_prefix: 'ui-icon ui-icon-'
});
JSONEditor.defaults.iconlibs.materialicons = JSONEditor.AbstractIconLib.extend({
mapping: {
collapse: 'arrow_drop_up',
expand: 'arrow_drop_down',
"delete": 'delete',
edit: 'edit',
add: 'add',
cancel: 'cancel',
save: 'save',
moveup: 'arrow_upward',
movedown: 'arrow_downward',
copy: 'content_copy'
},
icon_class: 'material-icons',
icon_prefix: '',
getIconClass: function(key) {
// This method is unused.
return this.icon_class;
},
getIcon: function(key) {
// Get the mapping.
var mapping = this.mapping[key];
if (!mapping) return null;
// @see http://materializecss.com/icons.html
var i = document.createElement('i');
i.className = this.icon_class;
var t = document.createTextNode(mapping);
i.appendChild(t);
return i;
}
});
JSONEditor.defaults.templates["default"] = function() {
return {
compile: function(template) {
var matches = template.match(/{{\s*([a-zA-Z0-9\-_ \.]+)\s*}}/g);
var l = matches && matches.length;
// Shortcut if the template contains no variables
if(!l) return function() { return template; };
// Pre-compute the search/replace functions
// This drastically speeds up template execution
var replacements = [];
var get_replacement = function(i) {
var p = matches[i].replace(/[{}]+/g,'').trim().split('.');
var n = p.length;
var func;
if(n > 1) {
var cur;
func = function(vars) {
cur = vars;
for(i=0; i<n; i++) {
cur = cur[p[i]];
if(!cur) break;
}
return cur;
};
}
else {
p = p[0];
func = function(vars) {
return vars[p];
};
}
replacements.push({
s: matches[i],
r: func
});
};
for(var i=0; i<l; i++) {
get_replacement(i);
}
// The compiled function
return function(vars) {
var ret = template+"";
var r;
for(i=0; i<l; i++) {
r = replacements[i];
ret = ret.replace(r.s, r.r(vars));
}
return ret;
};
}
};
};
JSONEditor.defaults.templates.ejs = function() {
if(!window.EJS) return false;
return {
compile: function(template) {
var compiled = new window.EJS({
text: template
});
return function(context) {
return compiled.render(context);
};
}
};
};
JSONEditor.defaults.templates.handlebars = function() {
return window.Handlebars;
};
JSONEditor.defaults.templates.hogan = function() {
if(!window.Hogan) return false;
return {
compile: function(template) {
var compiled = window.Hogan.compile(template);
return function(context) {
return compiled.render(context);
};
}
};
};
JSONEditor.defaults.templates.lodash = function() {
if(!window._) return false;
return {
compile: function(template) {
return function(context) {
return window._.template(template)(context);
};
}
};
};
JSONEditor.defaults.templates.markup = function() {
if(!window.Mark || !window.Mark.up) return false;
return {
compile: function(template) {
return function(context) {
return window.Mark.up(template,context);
};
}
};
};
JSONEditor.defaults.templates.mustache = function() {
if(!window.Mustache) return false;
return {
compile: function(template) {
return function(view) {
return window.Mustache.render(template, view);
};
}
};
};
JSONEditor.defaults.templates.swig = function() {
return window.swig;
};
JSONEditor.defaults.templates.underscore = function() {
if(!window._) return false;
return {
compile: function(template) {
return function(context) {
return window._.template(template, context);
};
}
};
};
// Set the default theme
JSONEditor.defaults.theme = 'html';
// Set the default template engine
JSONEditor.defaults.template = 'default';
// Default options when initializing JSON Editor
JSONEditor.defaults.options = {};
// String translate function
JSONEditor.defaults.translate = function(key, variables) {
var lang = JSONEditor.defaults.languages[JSONEditor.defaults.language];
if(!lang) throw "Unknown language "+JSONEditor.defaults.language;
var string = lang[key] || JSONEditor.defaults.languages[JSONEditor.defaults.default_language][key];
if(typeof string === "undefined") throw "Unknown translate string "+key;
if(variables) {
for(var i=0; i<variables.length; i++) {
string = string.replace(new RegExp('\\{\\{'+i+'}}','g'),variables[i]);
}
}
return string;
};
// Translation strings and default languages
JSONEditor.defaults.default_language = 'en';
JSONEditor.defaults.language = JSONEditor.defaults.default_language;
JSONEditor.defaults.languages.en = {
/**
* When a property is not set
*/
error_notset: "Property must be set",
/**
* When a string must not be empty
*/
error_notempty: "Value required",
/**
* When a value is not one of the enumerated values
*/
error_enum: "Value must be one of the enumerated values",
/**
* When a value doesn't validate any schema of a 'anyOf' combination
*/
error_anyOf: "Value must validate against at least one of the provided schemas",
/**
* When a value doesn't validate
* @variables This key takes one variable: The number of schemas the value does not validate
*/
error_oneOf: 'Value must validate against exactly one of the provided schemas. It currently validates against {{0}} of the schemas.',
/**
* When a value does not validate a 'not' schema
*/
error_not: "Value must not validate against the provided schema",
/**
* When a value does not match any of the provided types
*/
error_type_union: "Value must be one of the provided types",
/**
* When a value does not match the given type
* @variables This key takes one variable: The type the value should be of
*/
error_type: "Value must be of type {{0}}",
/**
* When the value validates one of the disallowed types
*/
error_disallow_union: "Value must not be one of the provided disallowed types",
/**
* When the value validates a disallowed type
* @variables This key takes one variable: The type the value should not be of
*/
error_disallow: "Value must not be of type {{0}}",
/**
* When a value is not a multiple of or divisible by a given number
* @variables This key takes one variable: The number mentioned above
*/
error_multipleOf: "Value must be a multiple of {{0}}",
/**
* When a value is greater than it's supposed to be (exclusive)
* @variables This key takes one variable: The maximum
*/
error_maximum_excl: "Value must be less than {{0}}",
/**
* When a value is greater than it's supposed to be (inclusive
* @variables This key takes one variable: The maximum
*/
error_maximum_incl: "Value must be at most {{0}}",
/**
* When a value is lesser than it's supposed to be (exclusive)
* @variables This key takes one variable: The minimum
*/
error_minimum_excl: "Value must be greater than {{0}}",
/**
* When a value is lesser than it's supposed to be (inclusive)
* @variables This key takes one variable: The minimum
*/
error_minimum_incl: "Value must be at least {{0}}",
/**
* When a value have too many characters
* @variables This key takes one variable: The maximum character count
*/
error_maxLength: "Value must be at most {{0}} characters long",
/**
* When a value does not have enough characters
* @variables This key takes one variable: The minimum character count
*/
error_minLength: "Value must be at least {{0}} characters long",
/**
* When a value does not match a given pattern
*/
error_pattern: "Value must match the pattern {{0}}",
/**
* When an array has additional items whereas it is not supposed to
*/
error_additionalItems: "No additional items allowed in this array",
/**
* When there are to many items in an array
* @variables This key takes one variable: The maximum item count
*/
error_maxItems: "Value must have at most {{0}} items",
/**
* When there are not enough items in an array
* @variables This key takes one variable: The minimum item count
*/
error_minItems: "Value must have at least {{0}} items",
/**
* When an array is supposed to have unique items but has duplicates
*/
error_uniqueItems: "Array must have unique items",
/**
* When there are too many properties in an object
* @variables This key takes one variable: The maximum property count
*/
error_maxProperties: "Object must have at most {{0}} properties",
/**
* When there are not enough properties in an object
* @variables This key takes one variable: The minimum property count
*/
error_minProperties: "Object must have at least {{0}} properties",
/**
* When a required property is not defined
* @variables This key takes one variable: The name of the missing property
*/
error_required: "Object is missing the required property '{{0}}'",
/**
* When there is an additional property is set whereas there should be none
* @variables This key takes one variable: The name of the additional property
*/
error_additional_properties: "No additional properties allowed, but property {{0}} is set",
/**
* When a dependency is not resolved
* @variables This key takes one variable: The name of the missing property for the dependency
*/
error_dependency: "Must have property {{0}}",
/**
* Text on Delete All buttons
*/
button_delete_all: "All",
/**
* Title on Delete All buttons
*/
button_delete_all_title: "Delete All",
/**
* Text on Delete Last buttons
* @variable This key takes one variable: The title of object to delete
*/
button_delete_last: "Last {{0}}",
/**
* Title on Delete Last buttons
* @variable This key takes one variable: The title of object to delete
*/
button_delete_last_title: "Delete Last {{0}}",
/**
* Title on Add Row buttons
* @variable This key takes one variable: The title of object to add
*/
button_add_row_title: "Add {{0}}",
/**
* Title on Move Down buttons
*/
button_move_down_title: "Move down",
/**
* Title on Move Up buttons
*/
button_move_up_title: "Move up",
/**
* Title on Delete Row buttons
* @variable This key takes one variable: The title of object to delete
*/
button_delete_row_title: "Delete {{0}}",
/**
* Title on Delete Row buttons, short version (no parameter with the object title)
*/
button_delete_row_title_short: "Delete",
/**
* Title on Collapse buttons
*/
button_collapse: "Collapse",
/**
* Title on Expand buttons
*/
button_expand: "Expand"
};
// Miscellaneous Plugin Settings
JSONEditor.plugins = {
ace: {
theme: ''
},
SimpleMDE: {
},
sceditor: {
},
select2: {
},
selectize: {
}
};
// Default per-editor options
$each(JSONEditor.defaults.editors, function(i,editor) {
JSONEditor.defaults.editors[i].options = editor.options || {};
});
// Set the default resolvers
// Use "multiple" as a fall back for everything
JSONEditor.defaults.resolvers.unshift(function(schema) {
if(typeof schema.type !== "string") return "multiple";
});
// If the type is not set but properties are defined, we can infer the type is actually object
JSONEditor.defaults.resolvers.unshift(function(schema) {
// If the schema is a simple type
if(!schema.type && schema.properties ) return "object";
});
// If the type is set and it's a basic type, use the primitive editor
JSONEditor.defaults.resolvers.unshift(function(schema) {
// If the schema is a simple type
if(typeof schema.type === "string") return schema.type;
});
// Use a specialized editor for ratings
JSONEditor.defaults.resolvers.unshift(function(schema) {
if(schema.type === "integer" && schema.format === "rating") return "rating";
});
// Use the select editor for all boolean values
JSONEditor.defaults.resolvers.unshift(function(schema) {
if(schema.type === 'boolean') {
// If explicitly set to 'checkbox', use that
if(schema.format === "checkbox" || (schema.options && schema.options.checkbox)) {
return "checkbox";
}
// Otherwise, default to select menu
return (JSONEditor.plugins.selectize.enable) ? 'selectize' : 'select';
}
});
// Use the multiple editor for schemas where the `type` is set to "any"
JSONEditor.defaults.resolvers.unshift(function(schema) {
// If the schema can be of any type
if(schema.type === "any") return "multiple";
});
// Editor for base64 encoded files
JSONEditor.defaults.resolvers.unshift(function(schema) {
// If the schema can be of any type
if(schema.type === "string" && schema.media && schema.media.binaryEncoding==="base64") {
return "base64";
}
});
// Editor for uploading files
JSONEditor.defaults.resolvers.unshift(function(schema) {
if(schema.type === "string" && schema.format === "url" && schema.options && schema.options.upload === true) {
if(window.FileReader) return "upload";
}
});
// Use the table editor for arrays with the format set to `table`
JSONEditor.defaults.resolvers.unshift(function(schema) {
// Type `array` with format set to `table`
if(schema.type === "array" && schema.format === "table") {
return "table";
}
});
// Use the `select` editor for dynamic enumSource enums
JSONEditor.defaults.resolvers.unshift(function(schema) {
if(schema.enumSource) return (JSONEditor.plugins.selectize.enable) ? 'selectize' : 'select';
});
// Use the `enum` or `select` editors for schemas with enumerated properties
JSONEditor.defaults.resolvers.unshift(function(schema) {
if(schema["enum"]) {
if(schema.type === "array" || schema.type === "object") {
return "enum";
}
else if(schema.type === "number" || schema.type === "integer" || schema.type === "string") {
return (JSONEditor.plugins.selectize.enable) ? 'selectize' : 'select';
}
}
});
// Specialized editors for arrays of strings
JSONEditor.defaults.resolvers.unshift(function(schema) {
if(schema.type === "array" && schema.items && !(Array.isArray(schema.items)) && schema.uniqueItems && ['string','number','integer'].indexOf(schema.items.type) >= 0) {
// For enumerated strings, number, or integers
if(schema.items.enum) {
return 'multiselect';
}
// For non-enumerated strings (tag editor)
else if(JSONEditor.plugins.selectize.enable && schema.items.type === "string") {
return 'arraySelectize';
}
}
});
// Use the multiple editor for schemas with `oneOf` set
JSONEditor.defaults.resolvers.unshift(function(schema) {
// If this schema uses `oneOf` or `anyOf`
if(schema.oneOf || schema.anyOf) return "multiple";
});
/**
* This is a small wrapper for using JSON Editor like a typical jQuery plugin.
*/
(function() {
if(window.jQuery || window.Zepto) {
var $ = window.jQuery || window.Zepto;
$.jsoneditor = JSONEditor.defaults;
$.fn.jsoneditor = function(options) {
var self = this;
var editor = this.data('jsoneditor');
if(options === 'value') {
if(!editor) throw "Must initialize jsoneditor before getting/setting the value";
// Set value
if(arguments.length > 1) {
editor.setValue(arguments[1]);
}
// Get value
else {
return editor.getValue();
}
}
else if(options === 'validate') {
if(!editor) throw "Must initialize jsoneditor before validating";
// Validate a specific value
if(arguments.length > 1) {
return editor.validate(arguments[1]);
}
// Validate current value
else {
return editor.validate();
}
}
else if(options === 'destroy') {
if(editor) {
editor.destroy();
this.data('jsoneditor',null);
}
}
else {
// Destroy first
if(editor) {
editor.destroy();
}
// Create editor
editor = new JSONEditor(this.get(0),options);
this.data('jsoneditor',editor);
// Setup event listeners
editor.on('change',function() {
self.trigger('change');
});
editor.on('ready',function() {
self.trigger('ready');
});
}
return this;
};
}
})();
window.JSONEditor = JSONEditor;
})();
//# sourceMappingURL=jsoneditor.js.map | mit |
cdnjs/cdnjs | ajax/libs/boosted/4.1.1/js/boosted.js | 163484 | /*!
* Boosted v4.1.1 (http://boosted.orange.com)
* Copyright 2014-2018 The Boosted Authors
* Copyright 2014-2018 Orange
* Licensed under MIT (https://github.com/orange-opensource/orange-boosted-bootstrap/blob/master/LICENSE)
* This a fork of Bootstrap : Initial license below
* Bootstrap v4.1.0 (https://getbootstrap.com)
* Copyright 2011-2018 The Bootstrap Authors
* Copyright 2011-2018 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('jquery'), require('popper.js')) :
typeof define === 'function' && define.amd ? define(['exports', 'jquery', 'popper.js'], factory) :
(factory((global.boosted = {}),global.jQuery,global.Popper));
}(this, (function (exports,$,Popper) { 'use strict';
$ = $ && $.hasOwnProperty('default') ? $['default'] : $;
Popper = Popper && Popper.hasOwnProperty('default') ? Popper['default'] : Popper;
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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === 'function') {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function (key) {
_defineProperty(target, key, source[key]);
});
}
return target;
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype.__proto__ = superClass && superClass.prototype;
subClass.__proto__ = superClass;
}
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.1.1): util.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Util = function ($$$1) {
/**
* ------------------------------------------------------------------------
* Private TransitionEnd Helpers
* ------------------------------------------------------------------------
*/
var TRANSITION_END = 'transitionend';
var MAX_UID = 1000000;
var MILLISECONDS_MULTIPLIER = 1000; // Shoutout AngusCroll (https://goo.gl/pxwQGp)
function toType(obj) {
return {}.toString.call(obj).match(/\s([a-z]+)/i)[1].toLowerCase();
}
function getSpecialTransitionEndEvent() {
return {
bindType: TRANSITION_END,
delegateType: TRANSITION_END,
handle: function handle(event) {
if ($$$1(event.target).is(this)) {
return event.handleObj.handler.apply(this, arguments); // eslint-disable-line prefer-rest-params
}
return undefined; // eslint-disable-line no-undefined
}
};
}
function transitionEndEmulator(duration) {
var _this = this;
var called = false;
$$$1(this).one(Util.TRANSITION_END, function () {
called = true;
});
setTimeout(function () {
if (!called) {
Util.triggerTransitionEnd(_this);
}
}, duration);
return this;
}
function setTransitionEndSupport() {
$$$1.fn.emulateTransitionEnd = transitionEndEmulator;
$$$1.event.special[Util.TRANSITION_END] = getSpecialTransitionEndEvent();
}
/**
* --------------------------------------------------------------------------
* Public Util Api
* --------------------------------------------------------------------------
*/
var Util = {
TRANSITION_END: 'bsTransitionEnd',
getUID: function getUID(prefix) {
do {
// eslint-disable-next-line no-bitwise
prefix += ~~(Math.random() * MAX_UID); // "~~" acts like a faster Math.floor() here
} while (document.getElementById(prefix));
return prefix;
},
getSelectorFromElement: function getSelectorFromElement(element) {
var selector = element.getAttribute('data-target');
if (!selector || selector === '#') {
selector = element.getAttribute('href') || '';
}
try {
var $selector = $$$1(document).find(selector);
return $selector.length > 0 ? selector : null;
} catch (err) {
return null;
}
},
getTransitionDurationFromElement: function getTransitionDurationFromElement(element) {
if (!element) {
return 0;
} // Get transition-duration of the element
var transitionDuration = $$$1(element).css('transition-duration');
var floatTransitionDuration = parseFloat(transitionDuration); // Return 0 if element or transition duration is not found
if (!floatTransitionDuration) {
return 0;
} // If multiple durations are defined, take the first
transitionDuration = transitionDuration.split(',')[0];
return parseFloat(transitionDuration) * MILLISECONDS_MULTIPLIER;
},
reflow: function reflow(element) {
return element.offsetHeight;
},
triggerTransitionEnd: function triggerTransitionEnd(element) {
$$$1(element).trigger(TRANSITION_END);
},
// TODO: Remove in v5
supportsTransitionEnd: function supportsTransitionEnd() {
return Boolean(TRANSITION_END);
},
isElement: function isElement(obj) {
return (obj[0] || obj).nodeType;
},
typeCheckConfig: function typeCheckConfig(componentName, config, configTypes) {
for (var property in configTypes) {
if (Object.prototype.hasOwnProperty.call(configTypes, property)) {
var expectedTypes = configTypes[property];
var value = config[property];
var valueType = value && Util.isElement(value) ? 'element' : toType(value);
if (!new RegExp(expectedTypes).test(valueType)) {
throw new Error(componentName.toUpperCase() + ": " + ("Option \"" + property + "\" provided type \"" + valueType + "\" ") + ("but expected type \"" + expectedTypes + "\"."));
}
}
}
}
};
setTransitionEndSupport();
return Util;
}($);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.1.1): alert.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Alert = function ($$$1) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'alert';
var VERSION = '4.1.1';
var DATA_KEY = 'bs.alert';
var EVENT_KEY = "." + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $$$1.fn[NAME];
var Selector = {
DISMISS: '[data-dismiss="alert"]'
};
var Event = {
CLOSE: "close" + EVENT_KEY,
CLOSED: "closed" + EVENT_KEY,
CLICK_DATA_API: "click" + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
ALERT: 'alert',
FADE: 'fade',
SHOW: 'show'
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var Alert =
/*#__PURE__*/
function () {
function Alert(element) {
this._element = element;
} // Getters
var _proto = Alert.prototype;
// Public
_proto.close = function close(element) {
var rootElement = this._element;
if (element) {
rootElement = this._getRootElement(element);
}
var customEvent = this._triggerCloseEvent(rootElement);
if (customEvent.isDefaultPrevented()) {
return;
}
this._removeElement(rootElement);
};
_proto.dispose = function dispose() {
$$$1.removeData(this._element, DATA_KEY);
this._element = null;
}; // Private
_proto._getRootElement = function _getRootElement(element) {
var selector = Util.getSelectorFromElement(element);
var parent = false;
if (selector) {
parent = $$$1(selector)[0];
}
if (!parent) {
parent = $$$1(element).closest("." + ClassName.ALERT)[0];
}
return parent;
};
_proto._triggerCloseEvent = function _triggerCloseEvent(element) {
var closeEvent = $$$1.Event(Event.CLOSE);
$$$1(element).trigger(closeEvent);
return closeEvent;
};
_proto._removeElement = function _removeElement(element) {
var _this = this;
$$$1(element).removeClass(ClassName.SHOW);
if (!$$$1(element).hasClass(ClassName.FADE)) {
this._destroyElement(element);
return;
}
var transitionDuration = Util.getTransitionDurationFromElement(element);
$$$1(element).one(Util.TRANSITION_END, function (event) {
return _this._destroyElement(element, event);
}).emulateTransitionEnd(transitionDuration);
};
_proto._destroyElement = function _destroyElement(element) {
$$$1(element).detach().trigger(Event.CLOSED).remove();
}; // Static
Alert._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var $element = $$$1(this);
var data = $element.data(DATA_KEY);
if (!data) {
data = new Alert(this);
$element.data(DATA_KEY, data);
}
if (config === 'close') {
data[config](this);
}
});
};
Alert._handleDismiss = function _handleDismiss(alertInstance) {
return function (event) {
if (event) {
event.preventDefault();
}
alertInstance.close(this);
};
};
_createClass(Alert, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}]);
return Alert;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$$$1(document).on(Event.CLICK_DATA_API, Selector.DISMISS, Alert._handleDismiss(new Alert()));
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$$$1.fn[NAME] = Alert._jQueryInterface;
$$$1.fn[NAME].Constructor = Alert;
$$$1.fn[NAME].noConflict = function () {
$$$1.fn[NAME] = JQUERY_NO_CONFLICT;
return Alert._jQueryInterface;
};
return Alert;
}($);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.1.1): button.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Button = function ($$$1) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'button';
var VERSION = '4.1.1';
var DATA_KEY = 'bs.button';
var EVENT_KEY = "." + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $$$1.fn[NAME];
var ClassName = {
ACTIVE: 'active',
BUTTON: 'btn',
FOCUS: 'focus'
};
var Selector = {
DATA_TOGGLE_CARROT: '[data-toggle^="button"]',
DATA_TOGGLE: '[data-toggle="buttons"]',
INPUT: 'input',
ACTIVE: '.active',
BUTTON: '.btn'
};
var Event = {
CLICK_DATA_API: "click" + EVENT_KEY + DATA_API_KEY,
FOCUS_BLUR_DATA_API: "focus" + EVENT_KEY + DATA_API_KEY + " " + ("blur" + EVENT_KEY + DATA_API_KEY)
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var Button =
/*#__PURE__*/
function () {
function Button(element) {
this._element = element;
} // Getters
var _proto = Button.prototype;
// Public
_proto.toggle = function toggle() {
var triggerChangeEvent = true;
var addAriaPressed = true;
var rootElement = $$$1(this._element).closest(Selector.DATA_TOGGLE)[0];
if (rootElement) {
var input = $$$1(this._element).find(Selector.INPUT)[0];
if (input) {
if (input.type === 'radio') {
if (input.checked && $$$1(this._element).hasClass(ClassName.ACTIVE)) {
triggerChangeEvent = false;
} else {
var activeElement = $$$1(rootElement).find(Selector.ACTIVE)[0];
if (activeElement) {
$$$1(activeElement).removeClass(ClassName.ACTIVE);
}
}
}
if (triggerChangeEvent) {
if (input.hasAttribute('disabled') || rootElement.hasAttribute('disabled') || input.classList.contains('disabled') || rootElement.classList.contains('disabled')) {
return;
}
input.checked = !$$$1(this._element).hasClass(ClassName.ACTIVE);
$$$1(input).trigger('change');
}
input.focus();
addAriaPressed = false;
}
}
if (addAriaPressed) {
this._element.setAttribute('aria-pressed', !$$$1(this._element).hasClass(ClassName.ACTIVE));
}
if (triggerChangeEvent) {
$$$1(this._element).toggleClass(ClassName.ACTIVE);
}
};
_proto.dispose = function dispose() {
$$$1.removeData(this._element, DATA_KEY);
this._element = null;
}; // Static
Button._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $$$1(this).data(DATA_KEY);
if (!data) {
data = new Button(this);
$$$1(this).data(DATA_KEY, data);
}
if (config === 'toggle') {
data[config]();
}
});
};
_createClass(Button, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}]);
return Button;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$$$1(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE_CARROT, function (event) {
event.preventDefault();
var button = event.target;
if (!$$$1(button).hasClass(ClassName.BUTTON)) {
button = $$$1(button).closest(Selector.BUTTON);
}
Button._jQueryInterface.call($$$1(button), 'toggle');
}).on(Event.FOCUS_BLUR_DATA_API, Selector.DATA_TOGGLE_CARROT, function (event) {
var button = $$$1(event.target).closest(Selector.BUTTON)[0];
$$$1(button).toggleClass(ClassName.FOCUS, /^focus(in)?$/.test(event.type));
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$$$1.fn[NAME] = Button._jQueryInterface;
$$$1.fn[NAME].Constructor = Button;
$$$1.fn[NAME].noConflict = function () {
$$$1.fn[NAME] = JQUERY_NO_CONFLICT;
return Button._jQueryInterface;
};
return Button;
}($);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.1.1): carousel.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Carousel = function ($$$1) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'carousel';
var VERSION = '4.1.1';
var DATA_KEY = 'bs.carousel';
var EVENT_KEY = "." + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $$$1.fn[NAME];
var ARROW_LEFT_KEYCODE = 37; // KeyboardEvent.which value for left arrow key
var ARROW_RIGHT_KEYCODE = 39; // KeyboardEvent.which value for right arrow key
var TOUCHEVENT_COMPAT_WAIT = 500; // Time for mouse compat events to fire after touch
var Default = {
interval: 5000,
keyboard: true,
slide: false,
pause: 'hover',
wrap: true
};
var DefaultType = {
interval: '(number|boolean)',
keyboard: 'boolean',
slide: '(boolean|string)',
pause: '(string|boolean)',
wrap: 'boolean'
};
var Direction = {
NEXT: 'next',
PREV: 'prev',
LEFT: 'left',
RIGHT: 'right'
};
var Event = {
SLIDE: "slide" + EVENT_KEY,
SLID: "slid" + EVENT_KEY,
KEYDOWN: "keydown" + EVENT_KEY,
MOUSEENTER: "mouseenter" + EVENT_KEY,
MOUSELEAVE: "mouseleave" + EVENT_KEY,
TOUCHEND: "touchend" + EVENT_KEY,
LOAD_DATA_API: "load" + EVENT_KEY + DATA_API_KEY,
CLICK_DATA_API: "click" + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
CAROUSEL: 'carousel',
ACTIVE: 'active',
SLIDE: 'slide',
RIGHT: 'carousel-item-right',
LEFT: 'carousel-item-left',
NEXT: 'carousel-item-next',
PREV: 'carousel-item-prev',
ITEM: 'carousel-item'
};
var Selector = {
ACTIVE: '.active',
ACTIVE_ITEM: '.active.carousel-item',
ITEM: '.carousel-item',
NEXT_PREV: '.carousel-item-next, .carousel-item-prev',
INDICATORS: '.carousel-indicators',
DATA_SLIDE: '[data-slide], [data-slide-to]',
DATA_RIDE: '[data-ride="carousel"]'
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var Carousel =
/*#__PURE__*/
function () {
function Carousel(element, config) {
this._items = null;
this._interval = null;
this._activeElement = null;
this._isPaused = false;
this._isSliding = false;
this.touchTimeout = null;
this._config = this._getConfig(config);
this._element = $$$1(element)[0];
this._indicatorsElement = $$$1(this._element).find(Selector.INDICATORS)[0];
this._addEventListeners();
} // Getters
var _proto = Carousel.prototype;
// Public
_proto.next = function next() {
if (!this._isSliding) {
this._slide(Direction.NEXT);
}
};
_proto.nextWhenVisible = function nextWhenVisible() {
// Don't call next when the page isn't visible
// or the carousel or its parent isn't visible
if (!document.hidden && $$$1(this._element).is(':visible') && $$$1(this._element).css('visibility') !== 'hidden') {
this.next();
}
};
_proto.prev = function prev() {
if (!this._isSliding) {
this._slide(Direction.PREV);
}
};
_proto.pause = function pause(event) {
if (!event) {
this._isPaused = true;
}
if ($$$1(this._element).find(Selector.NEXT_PREV)[0]) {
Util.triggerTransitionEnd(this._element);
this.cycle(true);
}
clearInterval(this._interval);
this._interval = null;
};
_proto.cycle = function cycle(event) {
if (!event) {
this._isPaused = false;
}
if (this._interval) {
clearInterval(this._interval);
this._interval = null;
}
if (this._config.interval && !this._isPaused) {
this._interval = setInterval((document.visibilityState ? this.nextWhenVisible : this.next).bind(this), this._config.interval);
}
};
_proto.to = function to(index) {
var _this = this;
this._activeElement = $$$1(this._element).find(Selector.ACTIVE_ITEM)[0];
var activeIndex = this._getItemIndex(this._activeElement);
if (index > this._items.length - 1 || index < 0) {
return;
}
if (this._isSliding) {
$$$1(this._element).one(Event.SLID, function () {
return _this.to(index);
});
return;
}
if (activeIndex === index) {
this.pause();
this.cycle();
return;
}
var direction = index > activeIndex ? Direction.NEXT : Direction.PREV;
this._slide(direction, this._items[index]);
};
_proto.dispose = function dispose() {
$$$1(this._element).off(EVENT_KEY);
$$$1.removeData(this._element, DATA_KEY);
this._items = null;
this._config = null;
this._element = null;
this._interval = null;
this._isPaused = null;
this._isSliding = null;
this._activeElement = null;
this._indicatorsElement = null;
}; // Private
_proto._getConfig = function _getConfig(config) {
config = _objectSpread({}, Default, config);
Util.typeCheckConfig(NAME, config, DefaultType);
return config;
};
_proto._addEventListeners = function _addEventListeners() {
var _this2 = this;
if (this._config.keyboard) {
$$$1(this._element).on(Event.KEYDOWN, function (event) {
return _this2._keydown(event);
});
}
if (this._config.pause === 'hover') {
$$$1(this._element).on(Event.MOUSEENTER, function (event) {
return _this2.pause(event);
}).on(Event.MOUSELEAVE, function (event) {
return _this2.cycle(event);
});
if ('ontouchstart' in document.documentElement) {
// If it's a touch-enabled device, mouseenter/leave are fired as
// part of the mouse compatibility events on first tap - the carousel
// would stop cycling until user tapped out of it;
// here, we listen for touchend, explicitly pause the carousel
// (as if it's the second time we tap on it, mouseenter compat event
// is NOT fired) and after a timeout (to allow for mouse compatibility
// events to fire) we explicitly restart cycling
$$$1(this._element).on(Event.TOUCHEND, function () {
_this2.pause();
if (_this2.touchTimeout) {
clearTimeout(_this2.touchTimeout);
}
_this2.touchTimeout = setTimeout(function (event) {
return _this2.cycle(event);
}, TOUCHEVENT_COMPAT_WAIT + _this2._config.interval);
});
}
}
};
_proto._keydown = function _keydown(event) {
if (/input|textarea/i.test(event.target.tagName)) {
return;
}
switch (event.which) {
case ARROW_LEFT_KEYCODE:
event.preventDefault();
this.prev();
break;
case ARROW_RIGHT_KEYCODE:
event.preventDefault();
this.next();
break;
default:
}
};
_proto._getItemIndex = function _getItemIndex(element) {
this._items = $$$1.makeArray($$$1(element).parent().find(Selector.ITEM));
return this._items.indexOf(element);
};
_proto._getItemByDirection = function _getItemByDirection(direction, activeElement) {
var isNextDirection = direction === Direction.NEXT;
var isPrevDirection = direction === Direction.PREV;
var activeIndex = this._getItemIndex(activeElement);
var lastItemIndex = this._items.length - 1;
var isGoingToWrap = isPrevDirection && activeIndex === 0 || isNextDirection && activeIndex === lastItemIndex;
if (isGoingToWrap && !this._config.wrap) {
return activeElement;
}
var delta = direction === Direction.PREV ? -1 : 1;
var itemIndex = (activeIndex + delta) % this._items.length;
return itemIndex === -1 ? this._items[this._items.length - 1] : this._items[itemIndex];
};
_proto._triggerSlideEvent = function _triggerSlideEvent(relatedTarget, eventDirectionName) {
var targetIndex = this._getItemIndex(relatedTarget);
var fromIndex = this._getItemIndex($$$1(this._element).find(Selector.ACTIVE_ITEM)[0]);
var slideEvent = $$$1.Event(Event.SLIDE, {
relatedTarget: relatedTarget,
direction: eventDirectionName,
from: fromIndex,
to: targetIndex
});
$$$1(this._element).trigger(slideEvent);
return slideEvent;
};
_proto._setActiveIndicatorElement = function _setActiveIndicatorElement(element) {
if (this._indicatorsElement) {
$$$1(this._indicatorsElement).find(Selector.ACTIVE).removeClass(ClassName.ACTIVE);
var nextIndicator = this._indicatorsElement.children[this._getItemIndex(element)];
if (nextIndicator) {
$$$1(nextIndicator).addClass(ClassName.ACTIVE);
}
}
};
_proto._slide = function _slide(direction, element) {
var _this3 = this;
var activeElement = $$$1(this._element).find(Selector.ACTIVE_ITEM)[0];
var activeElementIndex = this._getItemIndex(activeElement);
var nextElement = element || activeElement && this._getItemByDirection(direction, activeElement);
var nextElementIndex = this._getItemIndex(nextElement);
var isCycling = Boolean(this._interval);
var directionalClassName;
var orderClassName;
var eventDirectionName;
if (direction === Direction.NEXT) {
directionalClassName = ClassName.LEFT;
orderClassName = ClassName.NEXT;
eventDirectionName = Direction.LEFT;
} else {
directionalClassName = ClassName.RIGHT;
orderClassName = ClassName.PREV;
eventDirectionName = Direction.RIGHT;
}
if (nextElement && $$$1(nextElement).hasClass(ClassName.ACTIVE)) {
this._isSliding = false;
return;
}
var slideEvent = this._triggerSlideEvent(nextElement, eventDirectionName);
if (slideEvent.isDefaultPrevented()) {
return;
}
if (!activeElement || !nextElement) {
// Some weirdness is happening, so we bail
return;
}
this._isSliding = true;
if (isCycling) {
this.pause();
}
this._setActiveIndicatorElement(nextElement);
var slidEvent = $$$1.Event(Event.SLID, {
relatedTarget: nextElement,
direction: eventDirectionName,
from: activeElementIndex,
to: nextElementIndex
});
if ($$$1(this._element).hasClass(ClassName.SLIDE)) {
$$$1(nextElement).addClass(orderClassName);
Util.reflow(nextElement);
$$$1(activeElement).addClass(directionalClassName);
$$$1(nextElement).addClass(directionalClassName);
var transitionDuration = Util.getTransitionDurationFromElement(activeElement);
$$$1(activeElement).one(Util.TRANSITION_END, function () {
$$$1(nextElement).removeClass(directionalClassName + " " + orderClassName).addClass(ClassName.ACTIVE);
$$$1(activeElement).removeClass(ClassName.ACTIVE + " " + orderClassName + " " + directionalClassName);
_this3._isSliding = false;
setTimeout(function () {
return $$$1(_this3._element).trigger(slidEvent);
}, 0);
}).emulateTransitionEnd(transitionDuration);
} else {
$$$1(activeElement).removeClass(ClassName.ACTIVE);
$$$1(nextElement).addClass(ClassName.ACTIVE);
this._isSliding = false;
$$$1(this._element).trigger(slidEvent);
}
if (isCycling) {
this.cycle();
}
}; // Static
Carousel._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $$$1(this).data(DATA_KEY);
var _config = _objectSpread({}, Default, $$$1(this).data());
if (typeof config === 'object') {
_config = _objectSpread({}, _config, config);
}
var action = typeof config === 'string' ? config : _config.slide;
if (!data) {
data = new Carousel(this, _config);
$$$1(this).data(DATA_KEY, data);
}
if (typeof config === 'number') {
data.to(config);
} else if (typeof action === 'string') {
if (typeof data[action] === 'undefined') {
throw new TypeError("No method named \"" + action + "\"");
}
data[action]();
} else if (_config.interval) {
data.pause();
data.cycle();
}
});
};
Carousel._dataApiClickHandler = function _dataApiClickHandler(event) {
var selector = Util.getSelectorFromElement(this);
if (!selector) {
return;
}
var target = $$$1(selector)[0];
if (!target || !$$$1(target).hasClass(ClassName.CAROUSEL)) {
return;
}
var config = _objectSpread({}, $$$1(target).data(), $$$1(this).data());
var slideIndex = this.getAttribute('data-slide-to');
if (slideIndex) {
config.interval = false;
}
Carousel._jQueryInterface.call($$$1(target), config);
if (slideIndex) {
$$$1(target).data(DATA_KEY).to(slideIndex);
}
event.preventDefault();
};
_createClass(Carousel, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}, {
key: "Default",
get: function get() {
return Default;
}
}]);
return Carousel;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$$$1(document).on(Event.CLICK_DATA_API, Selector.DATA_SLIDE, Carousel._dataApiClickHandler);
$$$1(window).on(Event.LOAD_DATA_API, function () {
$$$1(Selector.DATA_RIDE).each(function () {
var $carousel = $$$1(this);
Carousel._jQueryInterface.call($carousel, $carousel.data());
});
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$$$1.fn[NAME] = Carousel._jQueryInterface;
$$$1.fn[NAME].Constructor = Carousel;
$$$1.fn[NAME].noConflict = function () {
$$$1.fn[NAME] = JQUERY_NO_CONFLICT;
return Carousel._jQueryInterface;
};
return Carousel;
}($);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.1.1): collapse.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Collapse = function ($$$1) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'collapse';
var VERSION = '4.1.1';
var DATA_KEY = 'bs.collapse';
var EVENT_KEY = "." + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $$$1.fn[NAME];
var Default = {
toggle: true,
parent: ''
};
var DefaultType = {
toggle: 'boolean',
parent: '(string|element)'
};
var Event = {
SHOW: "show" + EVENT_KEY,
SHOWN: "shown" + EVENT_KEY,
HIDE: "hide" + EVENT_KEY,
HIDDEN: "hidden" + EVENT_KEY,
CLICK_DATA_API: "click" + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
SHOW: 'show',
COLLAPSE: 'collapse',
COLLAPSING: 'collapsing',
COLLAPSED: 'collapsed'
};
var Dimension = {
WIDTH: 'width',
HEIGHT: 'height'
};
var Selector = {
ACTIVES: '*:not(.multi) > .show, *:not(.multi) > .collapsing, > .show, > .collapsing',
// boosted mod
DATA_TOGGLE: '[data-toggle="collapse"]'
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var Collapse =
/*#__PURE__*/
function () {
function Collapse(element, config) {
this._isTransitioning = false;
this._element = element;
this._config = this._getConfig(config);
this._triggerArray = $$$1.makeArray($$$1("[data-toggle=\"collapse\"][href=\"#" + element.id + "\"]," + ("[data-toggle=\"collapse\"][data-target=\"#" + element.id + "\"]")));
var tabToggles = $$$1(Selector.DATA_TOGGLE);
for (var i = 0; i < tabToggles.length; i++) {
var elem = tabToggles[i];
var selector = Util.getSelectorFromElement(elem);
if (selector !== null && $$$1(selector).filter(element).length > 0) {
this._selector = selector;
this._triggerArray.push(elem);
}
}
this._parent = this._config.parent ? this._getParent() : null;
if (!this._config.parent) {
this._addAriaAndCollapsedClass(this._element, this._triggerArray);
}
if (this._config.toggle) {
this.toggle();
}
} // Getters
var _proto = Collapse.prototype;
// Public
_proto.toggle = function toggle() {
if ($$$1(this._element).hasClass(ClassName.SHOW)) {
this.hide();
} else {
this.show();
}
};
_proto.show = function show() {
var _this = this;
if (this._isTransitioning || $$$1(this._element).hasClass(ClassName.SHOW)) {
return;
}
var actives;
var activesData;
if (this._parent) {
actives = $$$1.makeArray($$$1(this._parent).find(Selector.ACTIVES).filter("[data-parent=\"" + this._config.parent + "\"]"));
if (actives.length === 0) {
actives = null;
}
}
if (actives) {
activesData = $$$1(actives).not(this._selector).data(DATA_KEY);
if (activesData && activesData._isTransitioning) {
return;
}
}
var startEvent = $$$1.Event(Event.SHOW);
$$$1(this._element).trigger(startEvent);
if (startEvent.isDefaultPrevented()) {
return;
}
if (actives) {
Collapse._jQueryInterface.call($$$1(actives).not(this._selector), 'hide');
if (!activesData) {
$$$1(actives).data(DATA_KEY, null);
}
}
var dimension = this._getDimension();
$$$1(this._element).removeClass(ClassName.COLLAPSE).addClass(ClassName.COLLAPSING);
this._element.style[dimension] = 0;
this._element.setAttribute('aria-expanded', true); // boosted mod
if (this._triggerArray.length > 0) {
$$$1(this._triggerArray).removeClass(ClassName.COLLAPSED).attr('aria-expanded', true);
}
this.setTransitioning(true);
var complete = function complete() {
$$$1(_this._element).removeClass(ClassName.COLLAPSING).addClass(ClassName.COLLAPSE).addClass(ClassName.SHOW);
_this._element.style[dimension] = '';
_this.setTransitioning(false);
$$$1(_this._element).trigger(Event.SHOWN);
};
var capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1);
var scrollSize = "scroll" + capitalizedDimension;
var transitionDuration = Util.getTransitionDurationFromElement(this._element);
$$$1(this._element).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration);
this._element.style[dimension] = this._element[scrollSize] + "px";
};
_proto.hide = function hide() {
var _this2 = this;
if (this._isTransitioning || !$$$1(this._element).hasClass(ClassName.SHOW)) {
return;
}
var startEvent = $$$1.Event(Event.HIDE);
$$$1(this._element).trigger(startEvent);
if (startEvent.isDefaultPrevented()) {
return;
}
var dimension = this._getDimension();
this._element.style[dimension] = this._element.getBoundingClientRect()[dimension] + "px";
Util.reflow(this._element);
$$$1(this._element).addClass(ClassName.COLLAPSING).removeClass(ClassName.COLLAPSE).removeClass(ClassName.SHOW);
this._element.setAttribute('aria-expanded', false); // boosted mod
if (this._triggerArray.length > 0) {
for (var i = 0; i < this._triggerArray.length; i++) {
var trigger = this._triggerArray[i];
var selector = Util.getSelectorFromElement(trigger);
if (selector !== null) {
var $elem = $$$1(selector);
if (!$elem.hasClass(ClassName.SHOW)) {
$$$1(trigger).addClass(ClassName.COLLAPSED).attr('aria-expanded', false);
}
}
}
}
this.setTransitioning(true);
var complete = function complete() {
_this2.setTransitioning(false);
$$$1(_this2._element).removeClass(ClassName.COLLAPSING).addClass(ClassName.COLLAPSE).trigger(Event.HIDDEN);
};
this._element.style[dimension] = '';
var transitionDuration = Util.getTransitionDurationFromElement(this._element);
$$$1(this._element).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration);
};
_proto.setTransitioning = function setTransitioning(isTransitioning) {
this._isTransitioning = isTransitioning;
};
_proto.dispose = function dispose() {
$$$1.removeData(this._element, DATA_KEY);
this._config = null;
this._parent = null;
this._element = null;
this._triggerArray = null;
this._isTransitioning = null;
}; // Private
_proto._getConfig = function _getConfig(config) {
config = _objectSpread({}, Default, config);
config.toggle = Boolean(config.toggle); // Coerce string values
Util.typeCheckConfig(NAME, config, DefaultType);
return config;
};
_proto._getDimension = function _getDimension() {
var hasWidth = $$$1(this._element).hasClass(Dimension.WIDTH);
return hasWidth ? Dimension.WIDTH : Dimension.HEIGHT;
};
_proto._getParent = function _getParent() {
var _this3 = this;
var parent = null;
if (Util.isElement(this._config.parent)) {
parent = this._config.parent; // It's a jQuery object
if (typeof this._config.parent.jquery !== 'undefined') {
parent = this._config.parent[0];
}
} else {
parent = $$$1(this._config.parent)[0];
}
var selector = "[data-toggle=\"collapse\"][data-parent=\"" + this._config.parent + "\"]";
$$$1(parent).find(selector).each(function (i, element) {
_this3._addAriaAndCollapsedClass(Collapse._getTargetFromElement(element), [element]);
});
return parent;
};
_proto._addAriaAndCollapsedClass = function _addAriaAndCollapsedClass(element, triggerArray) {
if (element) {
var isOpen = $$$1(element).hasClass(ClassName.SHOW);
element.setAttribute('aria-expanded', isOpen); // boosted mod
if (triggerArray.length > 0) {
$$$1(triggerArray).toggleClass(ClassName.COLLAPSED, !isOpen).attr('aria-expanded', isOpen);
}
}
}; // Static
Collapse._getTargetFromElement = function _getTargetFromElement(element) {
var selector = Util.getSelectorFromElement(element);
return selector ? $$$1(selector)[0] : null;
};
Collapse._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var $this = $$$1(this);
var data = $this.data(DATA_KEY);
var _config = _objectSpread({}, Default, $this.data(), typeof config === 'object' && config ? config : {});
if (!data && _config.toggle && /show|hide|init/.test(config)) {
// Boosted mod
_config.toggle = false;
}
if (!data) {
data = new Collapse(this, _config);
$this.data(DATA_KEY, data);
} // Boosted mod
if (/init/.test(config)) {
return;
} // end mod
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new TypeError("No method named \"" + config + "\"");
}
data[config]();
}
});
};
_createClass(Collapse, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}, {
key: "Default",
get: function get() {
return Default;
}
}]);
return Collapse;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$$$1(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) {
// preventDefault only for <a> elements (which change the URL) not inside the collapsible element
if (event.currentTarget.tagName === 'A') {
event.preventDefault();
}
var $trigger = $$$1(this);
var selector = Util.getSelectorFromElement(this);
$$$1(selector).each(function () {
var $target = $$$1(this);
var data = $target.data(DATA_KEY);
var config = data ? 'toggle' : $trigger.data();
Collapse._jQueryInterface.call($target, config);
});
}) // Boosted mod
.on('DOMContentLoaded', function () {
$$$1(Selector.DATA_TOGGLE).each(function () {
var target = Collapse._getTargetFromElement(this);
Collapse._jQueryInterface.call($$$1(target), 'init');
});
}); // end mod
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$$$1.fn[NAME] = Collapse._jQueryInterface;
$$$1.fn[NAME].Constructor = Collapse;
$$$1.fn[NAME].noConflict = function () {
$$$1.fn[NAME] = JQUERY_NO_CONFLICT;
return Collapse._jQueryInterface;
};
return Collapse;
}($);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.1.1): dropdown.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Dropdown = function ($$$1) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'dropdown';
var VERSION = '4.1.1';
var DATA_KEY = 'bs.dropdown';
var EVENT_KEY = "." + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $$$1.fn[NAME];
var ESCAPE_KEYCODE = 27; // KeyboardEvent.which value for Escape (Esc) key
var SPACE_KEYCODE = 32; // KeyboardEvent.which value for space key
var TAB_KEYCODE = 9; // KeyboardEvent.which value for tab key
var ARROW_UP_KEYCODE = 38; // KeyboardEvent.which value for up arrow key
var ARROW_DOWN_KEYCODE = 40; // KeyboardEvent.which value for down arrow key
var RIGHT_MOUSE_BUTTON_WHICH = 3; // MouseEvent.which value for the right button (assuming a right-handed mouse)
var REGEXP_KEYDOWN = new RegExp(ARROW_UP_KEYCODE + "|" + ARROW_DOWN_KEYCODE + "|" + ESCAPE_KEYCODE);
var Event = {
HIDE: "hide" + EVENT_KEY,
HIDDEN: "hidden" + EVENT_KEY,
SHOW: "show" + EVENT_KEY,
SHOWN: "shown" + EVENT_KEY,
CLICK: "click" + EVENT_KEY,
CLICK_DATA_API: "click" + EVENT_KEY + DATA_API_KEY,
KEYDOWN_DATA_API: "keydown" + EVENT_KEY + DATA_API_KEY,
KEYUP_DATA_API: "keyup" + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
DISABLED: 'disabled',
SHOW: 'show',
DROPUP: 'dropup',
DROPRIGHT: 'dropright',
DROPLEFT: 'dropleft',
MENURIGHT: 'dropdown-menu-right',
MENULEFT: 'dropdown-menu-left',
POSITION_STATIC: 'position-static'
};
var Selector = {
DATA_TOGGLE: '[data-toggle="dropdown"]',
FORM_CHILD: '.dropdown form',
MENU: '.dropdown-menu',
NAVBAR_NAV: '.navbar-nav',
// Boosted mod
MENU_ITEMS: '.dropdown-menu .dropdown-item',
FIRST_ITEM_IN_MENU: '.dropdown-menu .dropdown-item:not(.disabled), .dropdown-menu .nav-link:not(.disabled)',
// end mod
VISIBLE_ITEMS: '.dropdown-menu .dropdown-item:not(.disabled):not(:disabled)'
};
var AttachmentMap = {
TOP: 'top-start',
TOPEND: 'top-end',
BOTTOM: 'bottom-start',
BOTTOMEND: 'bottom-end',
RIGHT: 'right-start',
RIGHTEND: 'right-end',
LEFT: 'left-start',
LEFTEND: 'left-end'
};
var Default = {
offset: 0,
flip: true,
boundary: 'scrollParent',
reference: 'toggle',
display: 'dynamic'
};
var DefaultType = {
offset: '(number|string|function)',
flip: 'boolean',
boundary: '(string|element)',
reference: '(string|element)',
display: 'string'
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var Dropdown =
/*#__PURE__*/
function () {
function Dropdown(element, config) {
this._element = element;
this._popper = null;
this._config = this._getConfig(config);
this._menu = this._getMenuElement();
this._inNavbar = this._detectNavbar();
this._addEventListeners();
this._addAccessibility(); // Boosted mod
} // Getters
var _proto = Dropdown.prototype;
// Public
_proto.toggle = function toggle() {
if (this._element.disabled || $$$1(this._element).hasClass(ClassName.DISABLED)) {
return;
}
var parent = Dropdown._getParentFromElement(this._element);
var isActive = $$$1(this._menu).hasClass(ClassName.SHOW);
Dropdown._clearMenus();
if (isActive) {
return;
}
var relatedTarget = {
relatedTarget: this._element
};
var showEvent = $$$1.Event(Event.SHOW, relatedTarget);
$$$1(parent).trigger(showEvent);
if (showEvent.isDefaultPrevented()) {
return;
} // Disable totally Popper.js for Dropdown in Navbar
if (!this._inNavbar) {
/**
* Check for Popper dependency
* Popper - https://popper.js.org
*/
if (typeof Popper === 'undefined') {
throw new TypeError('Bootstrap dropdown require Popper.js (https://popper.js.org)');
}
var referenceElement = this._element;
if (this._config.reference === 'parent') {
referenceElement = parent;
} else if (Util.isElement(this._config.reference)) {
referenceElement = this._config.reference; // Check if it's jQuery element
if (typeof this._config.reference.jquery !== 'undefined') {
referenceElement = this._config.reference[0];
}
} // If boundary is not `scrollParent`, then set position to `static`
// to allow the menu to "escape" the scroll parent's boundaries
// https://github.com/twbs/bootstrap/issues/24251
if (this._config.boundary !== 'scrollParent') {
$$$1(parent).addClass(ClassName.POSITION_STATIC);
}
this._popper = new Popper(referenceElement, this._menu, this._getPopperConfig());
} // If this is a touch-enabled device we add extra
// empty mouseover listeners to the body's immediate children;
// only needed because of broken event delegation on iOS
// https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html
if ('ontouchstart' in document.documentElement && $$$1(parent).closest(Selector.NAVBAR_NAV).length === 0) {
$$$1(document.body).children().on('mouseover', null, $$$1.noop);
}
this._element.focus();
this._element.setAttribute('aria-expanded', true);
$$$1(this._menu).toggleClass(ClassName.SHOW);
$$$1(parent).toggleClass(ClassName.SHOW).trigger($$$1.Event(Event.SHOWN, relatedTarget)); // Boosted mod
$$$1(parent).find(Selector.FIRST_ITEM_IN_MENU).first().trigger('focus'); // end mod
};
_proto.dispose = function dispose() {
$$$1.removeData(this._element, DATA_KEY);
$$$1(this._element).off(EVENT_KEY);
this._element = null;
this._menu = null;
if (this._popper !== null) {
this._popper.destroy();
this._popper = null;
}
};
_proto.update = function update() {
this._inNavbar = this._detectNavbar();
if (this._popper !== null) {
this._popper.scheduleUpdate();
}
}; // Private
_proto._addEventListeners = function _addEventListeners() {
var _this = this;
$$$1(this._element).on(Event.CLICK, function (event) {
event.preventDefault();
event.stopPropagation();
_this.toggle();
});
};
_proto._getConfig = function _getConfig(config) {
config = _objectSpread({}, this.constructor.Default, $$$1(this._element).data(), config);
Util.typeCheckConfig(NAME, config, this.constructor.DefaultType);
return config;
};
_proto._getMenuElement = function _getMenuElement() {
if (!this._menu) {
var parent = Dropdown._getParentFromElement(this._element);
this._menu = $$$1(parent).find(Selector.MENU)[0];
}
return this._menu;
};
_proto._getPlacement = function _getPlacement() {
var $parentDropdown = $$$1(this._element).parent();
var placement = AttachmentMap.BOTTOM; // Handle dropup
if ($parentDropdown.hasClass(ClassName.DROPUP)) {
placement = AttachmentMap.TOP;
if ($$$1(this._menu).hasClass(ClassName.MENURIGHT)) {
placement = AttachmentMap.TOPEND;
}
} else if ($parentDropdown.hasClass(ClassName.DROPRIGHT)) {
placement = AttachmentMap.RIGHT;
} else if ($parentDropdown.hasClass(ClassName.DROPLEFT)) {
placement = AttachmentMap.LEFT;
} else if ($$$1(this._menu).hasClass(ClassName.MENURIGHT)) {
placement = AttachmentMap.BOTTOMEND;
}
return placement;
};
_proto._detectNavbar = function _detectNavbar() {
return $$$1(this._element).closest('.navbar').length > 0;
};
_proto._getPopperConfig = function _getPopperConfig() {
var _this2 = this;
var offsetConf = {};
if (typeof this._config.offset === 'function') {
offsetConf.fn = function (data) {
data.offsets = _objectSpread({}, data.offsets, _this2._config.offset(data.offsets) || {});
return data;
};
} else {
offsetConf.offset = this._config.offset;
}
var popperConfig = {
placement: this._getPlacement(),
modifiers: {
offset: offsetConf,
flip: {
enabled: this._config.flip
},
preventOverflow: {
boundariesElement: this._config.boundary
}
} // Disable Popper.js if we have a static display
};
if (this._config.display === 'static') {
popperConfig.modifiers.applyStyle = {
enabled: false
};
}
return popperConfig;
}; // Boosted mod
_proto._addAccessibility = function _addAccessibility() {
$$$1(this._element).attr('aria-haspopup', true); // ensure that dropdown-menu have the role menu
$$$1(this._element).parent().children(Selector.MENU).attr('role', 'menu'); // ensure that dropdown-itm's have the role menuitem
$$$1(this._element).parent().children(Selector.MENU).children('.dropdown-item').attr('role', 'menuitem');
}; // end mod
// Static
Dropdown._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $$$1(this).data(DATA_KEY);
var _config = typeof config === 'object' ? config : null;
if (!data) {
data = new Dropdown(this, _config);
$$$1(this).data(DATA_KEY, data);
} // Boosted mod
if (/init/.test(config)) {
return;
} // end mod
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new TypeError("No method named \"" + config + "\"");
}
data[config]();
}
});
};
Dropdown._clearMenus = function _clearMenus(event) {
if (event && (event.which === RIGHT_MOUSE_BUTTON_WHICH || event.type === 'keyup' && event.which !== TAB_KEYCODE)) {
return;
}
var toggles = $$$1.makeArray($$$1(Selector.DATA_TOGGLE));
for (var i = 0; i < toggles.length; i++) {
var parent = Dropdown._getParentFromElement(toggles[i]);
var context = $$$1(toggles[i]).data(DATA_KEY);
var relatedTarget = {
relatedTarget: toggles[i]
};
if (!context) {
continue;
}
var dropdownMenu = context._menu;
if (!$$$1(parent).hasClass(ClassName.SHOW)) {
continue;
}
if (event && (event.type === 'click' && /input|textarea/i.test(event.target.tagName) || event.type === 'keyup' && event.which === TAB_KEYCODE) && $$$1.contains(parent, event.target)) {
continue;
}
var hideEvent = $$$1.Event(Event.HIDE, relatedTarget);
$$$1(parent).trigger(hideEvent);
if (hideEvent.isDefaultPrevented()) {
continue;
} // If this is a touch-enabled device we remove the extra
// empty mouseover listeners we added for iOS support
if ('ontouchstart' in document.documentElement) {
$$$1(document.body).children().off('mouseover', null, $$$1.noop);
}
toggles[i].setAttribute('aria-expanded', 'false');
$$$1(dropdownMenu).removeClass(ClassName.SHOW);
$$$1(parent).removeClass(ClassName.SHOW).trigger($$$1.Event(Event.HIDDEN, relatedTarget));
}
};
Dropdown._getParentFromElement = function _getParentFromElement(element) {
var parent;
var selector = Util.getSelectorFromElement(element);
if (selector) {
parent = $$$1(selector)[0];
}
return parent || element.parentNode;
}; // eslint-disable-next-line complexity
Dropdown._dataApiKeydownHandler = function _dataApiKeydownHandler(event) {
// If not input/textarea:
// - And not a key in REGEXP_KEYDOWN => not a dropdown command
// If input/textarea:
// - If space key => not a dropdown command
// - If key is other than escape
// - If key is not up or down => not a dropdown command
// - If trigger inside the menu => not a dropdown command
if (/input|textarea/i.test(event.target.tagName) ? event.which === SPACE_KEYCODE || event.which !== ESCAPE_KEYCODE && (event.which !== ARROW_DOWN_KEYCODE && event.which !== ARROW_UP_KEYCODE || $$$1(event.target).closest(Selector.MENU).length) : !REGEXP_KEYDOWN.test(event.which)) {
return;
}
event.preventDefault();
event.stopPropagation();
if (this.disabled || $$$1(this).hasClass(ClassName.DISABLED)) {
return;
}
var parent = Dropdown._getParentFromElement(this);
var isActive = $$$1(parent).hasClass(ClassName.SHOW);
if (!isActive && (event.which !== ESCAPE_KEYCODE || event.which !== SPACE_KEYCODE) || isActive && (event.which === ESCAPE_KEYCODE || event.which === SPACE_KEYCODE)) {
if (event.which === ESCAPE_KEYCODE) {
var toggle = $$$1(parent).find(Selector.DATA_TOGGLE)[0];
$$$1(toggle).trigger('focus');
}
$$$1(this).trigger('click');
return;
}
var items = $$$1(parent).find(Selector.VISIBLE_ITEMS).get();
if (items.length === 0) {
return;
}
var index = items.indexOf(event.target);
if (event.which === ARROW_UP_KEYCODE && index > 0) {
// Up
index--;
}
if (event.which === ARROW_DOWN_KEYCODE && index < items.length - 1) {
// Down
index++;
}
if (index < 0) {
index = 0;
}
items[index].focus();
};
_createClass(Dropdown, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}, {
key: "Default",
get: function get() {
return Default;
}
}, {
key: "DefaultType",
get: function get() {
return DefaultType;
}
}]);
return Dropdown;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$$$1(document).on(Event.KEYDOWN_DATA_API, Selector.DATA_TOGGLE, Dropdown._dataApiKeydownHandler).on(Event.KEYDOWN_DATA_API, Selector.MENU, Dropdown._dataApiKeydownHandler).on(Event.CLICK_DATA_API + " " + Event.KEYUP_DATA_API, Dropdown._clearMenus).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) {
event.preventDefault();
event.stopPropagation();
Dropdown._jQueryInterface.call($$$1(this), 'toggle');
}).on(Event.CLICK_DATA_API, Selector.FORM_CHILD, function (e) {
e.stopPropagation();
}) // Boosted mod
.on('DOMContentLoaded', function () {
// Instanciate every dropdown in the DOM
Dropdown._jQueryInterface.call($$$1(Selector.DATA_TOGGLE), 'init');
}); // end mod
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$$$1.fn[NAME] = Dropdown._jQueryInterface;
$$$1.fn[NAME].Constructor = Dropdown;
$$$1.fn[NAME].noConflict = function () {
$$$1.fn[NAME] = JQUERY_NO_CONFLICT;
return Dropdown._jQueryInterface;
};
return Dropdown;
}($, Popper);
/* eslint no-magic-numbers: ["error", { "ignore": [1,2] }] */
/**
* --------------------------------------------------------------------------
* Boosted (v4.1.0): o-megamenu.js
* Licensed under MIT (https://github.com/Orange-OpenSource/Orange-Boosted-Bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var MegaMenu = function ($$$1) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'megamenu';
var VERSION = '4.1.0';
var DATA_KEY = 'bs.megamenu';
var JQUERY_NO_CONFLICT = $$$1.fn[NAME];
var ARROW_LEFT_KEYCODE = 37; // KeyboardEvent.which value for left arrow key
var ARROW_RIGHT_KEYCODE = 39; // KeyboardEvent.which value for right arrow key
var ARROW_UP_KEYCODE = 38; // KeyboardEvent.which value for up arrow key
var ARROW_DOWN_KEYCODE = 40; // KeyboardEvent.which value for down arrow key
var TIMEOUT = 1000; // Timeout befor focusing first element
var PERCENTAGE = 100; // Width slide proportion
var SPLITLENGHT = 4;
var ClassName = {
TRANSITIONING: 'transitioning'
};
var Selector = {
MEGAMENU: '.mega-menu',
ROOT_NAV: '.mega-menu > .navbar-nav',
MEGAMENU_PANEL: '.mega-menu-panel',
MEGAMENU_NAV: '.nav-link + .navbar-nav',
NAV_MENU: '.navbar-nav',
NAV_ITEM: '.nav-item',
NAV_LINK: '.nav-link',
NAV_LINK_COLLAPSE: '.nav-link[data-toggle=collapse]',
NAV_LINK_BACK: '.nav-link.back',
NAV_LINK_EXPANDED: '.nav-link[aria-expanded=true]'
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var MegaMenu =
/*#__PURE__*/
function () {
function MegaMenu(element, config) {
this._element = element;
this._$navLinks = $$$1(this._element).find(Selector.NAV_LINK);
this._$goForwardLinks = $$$1(this._element).find(Selector.MEGAMENU_NAV).prev(Selector.NAV_LINK);
this._$goBackLinks = $$$1(this._element).find(Selector.NAV_LINK_BACK);
this._$topCollapseMenus = $$$1(this._element).find(Selector.MEGAMENU_PANEL);
this._$navLinkCollapses = $$$1(this._element).find(Selector.NAV_LINK_COLLAPSE);
this._config = config;
if (typeof this._config.noFocus === 'undefined') {
this._config.noFocus = false;
}
this._addEventListeners();
this._addAriaAttributes(this._element);
this.goTo = this._initPosition;
} // getters
var _proto = MegaMenu.prototype;
// public
// private
_proto._addEventListeners = function _addEventListeners() {
var _this = this;
this._$goForwardLinks.on('click', function (event) {
return _this._goForward(event);
});
this._$goBackLinks.on('click', function (event) {
return _this._goBackward(event);
});
this._$navLinks.on('keydown', function (event) {
return _this._manageKeyDown(event);
});
if (!this._config.noFocus) {
this._$topCollapseMenus.on('shown.bs.collapse', this._collapseFocus);
}
this._$navLinkCollapses.on('click', function (event) {
return _this._handleCollapseToggle(event);
});
};
_proto._addAriaAttributes = function _addAriaAttributes(element) {
var $subNavs = $$$1(element).find('.nav-link + .navbar-nav');
$$$1(element).attr('role', 'application');
$$$1(element).find('> .navbar-nav').attr('role', 'menu');
$$$1(element).find(Selector.MEGAMENU_PANEL).attr('role', 'menu');
$$$1(element).find('.nav-link[data-toggle=collapse]').attr('role', 'menuitem');
$$$1(element).find(Selector.NAV_LINK_BACK).attr({
'aria-hidden': true
});
$$$1(element).find(Selector.NAV_ITEM).attr('role', 'presentation');
$subNavs.each(function () {
var navId = Util.getUID(NAME);
var $thisNavToggler = $$$1(this).prev(Selector.NAV_LINK);
var $thisNav = $$$1(this);
var $thisNavBackLink = $thisNav.find(Selector.NAV_LINK_BACK);
var $topMenu = $$$1(this).closest(Selector.NAV_MENU).parent().closest(Selector.NAV_MENU).prev(Selector.NAV_LINK);
var goBackLabel = "go back to " + $topMenu.text() + " menu";
if (!$topMenu.length) {
goBackLabel = "go back to " + $$$1(this).closest(Selector.MEGAMENU_PANEL).prev(Selector.NAV_LINK).text() + " menu";
}
$thisNav.attr({
id: navId,
role: 'menu'
});
$thisNavToggler.attr({
role: 'menuitem',
'aria-controls': navId,
'aria-expanded': false,
'aria-haspopup': true
});
$thisNavBackLink.attr({
role: 'menuitem',
'aria-controls': navId,
'aria-label': goBackLabel
});
});
};
_proto._initPosition = function _initPosition(target) {
var _this2 = this;
if (!$$$1(target).length) {
return;
}
var $target = $$$1(target).first();
var position = $target.parents().index(this._element);
var rootPosition = $$$1('.mega-menu-panel .nav-link').first().parents().index($$$1('.mega-menu'));
var translatePercentage = -(position - rootPosition) * PERCENTAGE / 2;
var $thisNav = $target.closest(Selector.NAV_MENU);
var $rootNav = $$$1(Selector.ROOT_NAV);
$rootNav.addClass(ClassName.TRANSITIONING); // open collapse
if ($target.attr('data-toggle') === 'collapse') {
$target.siblings(Selector.MEGAMENU_PANEL).collapse('show');
this._$topCollapseMenus.not($target.siblings(Selector.MEGAMENU_PANEL)).collapse('hide');
$$$1(this._element).height('auto');
$rootNav.css('transform', 'translateX(0%)');
} else {
$target.closest(Selector.MEGAMENU_PANEL).collapse('show');
this._$topCollapseMenus.not($target.closest(Selector.MEGAMENU_PANEL)).collapse('hide'); // show menu and hide other
$target.parents(Selector.NAV_MENU).show(); // set aria on parent links
$target.parents(Selector.NAV_ITEM).find('> .nav-link').not($target).attr({
tabindex: -1,
'aria-hidden': true,
'aria-expanded': true
}); // translate to pos
$rootNav.css('transform', "translateX(" + translatePercentage + "%)");
if (translatePercentage) {
// adapt main collapse height to target height
$$$1(this._element).height($thisNav.height());
} else {
$$$1(this._element).height('auto');
}
} // set focus on target link
setTimeout(function () {
if (!_this2._config.noFocus) {
// set focus on target link
$target.trigger('focus');
}
$rootNav.removeClass(ClassName.TRANSITIONING);
}, TIMEOUT);
};
_proto._manageKeyDown = function _manageKeyDown(event) {
var $thisTarget = $$$1(event.target); // test key code
if (/input|textarea/i.test(event.target.tagName)) {
return;
} // proceed according to key code
switch (event.which) {
case ARROW_LEFT_KEYCODE:
this._goBackward(event);
break;
case ARROW_RIGHT_KEYCODE:
this._goForward(event);
break;
case ARROW_UP_KEYCODE:
// focus prev nav link
$thisTarget.parent().prev().find('>.nav-link').not(Selector.NAV_LINK_BACK).trigger('focus');
break;
case ARROW_DOWN_KEYCODE:
// focus next nav link
$thisTarget.parent().next().find('>.nav-link').trigger('focus');
break;
default:
}
};
_proto._collapseFocus = function _collapseFocus() {
$$$1(this).find(Selector.NAV_LINK).not(Selector.NAV_LINK_BACK).first().trigger('focus');
};
_proto._handleCollapseToggle = function _handleCollapseToggle(e) {
var $this = $$$1(e.target);
var $thisCollapse = $$$1($this.attr('href'));
this._$topCollapseMenus.not($thisCollapse).collapse('hide');
};
_proto._goForward = function _goForward(e) {
e.preventDefault();
var $this = $$$1(e.target);
var $thisNav = $this.closest(Selector.NAV_MENU);
var $targetNav = $this.next(Selector.NAV_MENU);
var $rootNav = $$$1(Selector.ROOT_NAV);
var $thisNavToggler = $this;
var currentTranslatePos = parseInt($rootNav.css('transform').split(',')[SPLITLENGHT], 10);
var navWidth = $rootNav.width();
var currentTranslatePercentage = PERCENTAGE * currentTranslatePos / navWidth;
if (!$this.next(Selector.NAV_MENU).length || $rootNav.hasClass(ClassName.TRANSITIONING)) {
return false;
}
$rootNav.addClass(ClassName.TRANSITIONING); // hide all nav on same level
$thisNav.find(Selector.NAV_MENU).hide(); // show target navbar-nav
$targetNav.show(); // adapt main collapse height to target height
$$$1(Selector.MEGAMENU).height($targetNav.height()); // make only visible elements focusable
if (!currentTranslatePercentage) {
$rootNav.find('>.nav-item .nav-link').attr({
tabindex: -1,
'aria-hidden': true
});
}
$thisNav.find(Selector.NAV_LINK).attr({
tabindex: -1,
'aria-hidden': true
});
$targetNav.find(Selector.NAV_LINK).attr({
tabindex: 0,
'aria-hidden': false
}); // translate menu
$rootNav.css('transform', "translateX(" + (currentTranslatePercentage - PERCENTAGE) + "%)"); // focus on target nav first item
$rootNav.one('transitionend', function () {
$thisNavToggler.attr('aria-expanded', true);
$targetNav.find(Selector.NAV_LINK).not(Selector.NAV_LINK_BACK).first().trigger('focus');
$rootNav.removeClass(ClassName.TRANSITIONING);
});
return true;
};
_proto._goBackward = function _goBackward(e) {
e.preventDefault();
var $this = $$$1(e.target);
var $thisNav = $this.closest(Selector.NAV_MENU);
var $targetNav = $thisNav.parent().closest(Selector.NAV_MENU);
var $rootNav = $$$1(Selector.ROOT_NAV);
var $targetNavToggler = $targetNav.find(Selector.NAV_LINK_EXPANDED);
var currentTranslatePos = parseInt($rootNav.css('transform').split(',')[SPLITLENGHT], 10);
var navWidth = $rootNav.width();
var currentTranslatePercentage = PERCENTAGE * currentTranslatePos / navWidth;
if (!currentTranslatePercentage || $rootNav.hasClass(ClassName.TRANSITIONING)) {
return false;
}
$rootNav.addClass(ClassName.TRANSITIONING); // make only visible elements focusable
$targetNav.find(Selector.NAV_LINK).attr({
tabindex: 0,
'aria-hidden': false
});
if (currentTranslatePercentage === -PERCENTAGE) {
// reset main collapse height
$$$1(Selector.MEGAMENU).css('height', 'auto');
$rootNav.find('>.nav-item .nav-link').attr({
tabindex: 0,
'aria-hidden': false
});
} // translate menu
$rootNav.css('transform', "translateX(" + (currentTranslatePercentage + PERCENTAGE) + "%)"); // focus on target nav first item
$rootNav.one('transitionend', function () {
$targetNavToggler.attr('aria-expanded', false);
$targetNavToggler.trigger('focus');
$thisNav.hide();
$rootNav.removeClass(ClassName.TRANSITIONING);
});
return true;
}; // static
MegaMenu._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var $element = $$$1(this);
if (!$element.is(Selector.MEGAMENU)) {
throw new Error('Element is not a mega menu');
}
if (!config) {
config = {};
} else if (config.noFocus && typeof config.noFocus !== 'boolean') {
// param = true
throw new Error('no-focus parameter must be boolean');
}
var data = $element.data(DATA_KEY);
if (!data) {
data = new MegaMenu(this, config);
$element.data(DATA_KEY, data);
}
if (config.target) {
if (typeof config.target !== 'string' || !/^[.#].*/.test(config.target)) {
throw new TypeError("Selector \"" + config.target + "\" is not supported");
}
data.goTo(config.target);
}
});
};
_createClass(MegaMenu, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}]);
return MegaMenu;
}();
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$$$1.fn[NAME] = MegaMenu._jQueryInterface;
$$$1.fn[NAME].Constructor = MegaMenu;
$$$1.fn[NAME].noConflict = function () {
$$$1.fn[NAME] = JQUERY_NO_CONFLICT;
return MegaMenu._jQueryInterface;
};
return MegaMenu;
}($);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.1.1): modal.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Modal = function ($$$1) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'modal';
var VERSION = '4.1.1';
var DATA_KEY = 'bs.modal';
var EVENT_KEY = "." + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $$$1.fn[NAME];
var ESCAPE_KEYCODE = 27; // KeyboardEvent.which value for Escape (Esc) key
var Default = {
backdrop: true,
keyboard: true,
focus: true,
show: true
};
var DefaultType = {
backdrop: '(boolean|string)',
keyboard: 'boolean',
focus: 'boolean',
show: 'boolean'
};
var Event = {
HIDE: "hide" + EVENT_KEY,
HIDDEN: "hidden" + EVENT_KEY,
SHOW: "show" + EVENT_KEY,
SHOWN: "shown" + EVENT_KEY,
FOCUSIN: "focusin" + EVENT_KEY,
RESIZE: "resize" + EVENT_KEY,
CLICK_DISMISS: "click.dismiss" + EVENT_KEY,
KEYDOWN_DISMISS: "keydown.dismiss" + EVENT_KEY,
MOUSEUP_DISMISS: "mouseup.dismiss" + EVENT_KEY,
MOUSEDOWN_DISMISS: "mousedown.dismiss" + EVENT_KEY,
CLICK_DATA_API: "click" + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
SCROLLBAR_MEASURER: 'modal-scrollbar-measure',
BACKDROP: 'modal-backdrop',
OPEN: 'modal-open',
FADE: 'fade',
SHOW: 'show'
};
var Selector = {
DIALOG: '.modal-dialog',
DATA_TOGGLE: '[data-toggle="modal"]',
DATA_DISMISS: '[data-dismiss="modal"]',
FIXED_CONTENT: '.fixed-top, .fixed-bottom, .is-fixed, .sticky-top',
STICKY_CONTENT: '.sticky-top',
NAVBAR_TOGGLER: '.navbar-toggler'
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var Modal =
/*#__PURE__*/
function () {
function Modal(element, config) {
this._config = this._getConfig(config);
this._element = element;
this._dialog = $$$1(element).find(Selector.DIALOG)[0];
this._backdrop = null;
this._isShown = false;
this._isBodyOverflowing = false;
this._ignoreBackdropClick = false;
this._scrollbarWidth = 0; // Boosted mod
this._addAria(); // end mod
} // Getters
var _proto = Modal.prototype;
// Public
_proto.toggle = function toggle(relatedTarget) {
return this._isShown ? this.hide() : this.show(relatedTarget);
};
_proto.show = function show(relatedTarget) {
var _this = this;
if (this._isTransitioning || this._isShown) {
return;
}
if ($$$1(this._element).hasClass(ClassName.FADE)) {
this._isTransitioning = true;
}
var showEvent = $$$1.Event(Event.SHOW, {
relatedTarget: relatedTarget
});
$$$1(this._element).trigger(showEvent);
if (this._isShown || showEvent.isDefaultPrevented()) {
return;
}
this._isShown = true;
this._checkScrollbar();
this._setScrollbar();
this._adjustDialog();
$$$1(document.body).addClass(ClassName.OPEN);
this._setEscapeEvent();
this._setResizeEvent();
$$$1(this._element).on(Event.CLICK_DISMISS, Selector.DATA_DISMISS, function (event) {
return _this.hide(event);
});
$$$1(this._dialog).on(Event.MOUSEDOWN_DISMISS, function () {
$$$1(_this._element).one(Event.MOUSEUP_DISMISS, function (event) {
if ($$$1(event.target).is(_this._element)) {
_this._ignoreBackdropClick = true;
}
});
});
this._showBackdrop(function () {
return _this._showElement(relatedTarget);
});
};
_proto.hide = function hide(event) {
var _this2 = this;
if (event) {
event.preventDefault();
}
if (this._isTransitioning || !this._isShown) {
return;
}
var hideEvent = $$$1.Event(Event.HIDE);
$$$1(this._element).trigger(hideEvent);
if (!this._isShown || hideEvent.isDefaultPrevented()) {
return;
}
this._isShown = false;
var transition = $$$1(this._element).hasClass(ClassName.FADE);
if (transition) {
this._isTransitioning = true;
}
this._setEscapeEvent();
this._setResizeEvent();
$$$1(document).off(Event.FOCUSIN);
$$$1(this._element).removeClass(ClassName.SHOW);
$$$1(this._element).off(Event.CLICK_DISMISS);
$$$1(this._dialog).off(Event.MOUSEDOWN_DISMISS);
if (transition) {
var transitionDuration = Util.getTransitionDurationFromElement(this._element);
$$$1(this._element).one(Util.TRANSITION_END, function (event) {
return _this2._hideModal(event);
}).emulateTransitionEnd(transitionDuration);
} else {
this._hideModal();
}
};
_proto.dispose = function dispose() {
$$$1.removeData(this._element, DATA_KEY);
$$$1(window, document, this._element, this._backdrop).off(EVENT_KEY);
this._config = null;
this._element = null;
this._dialog = null;
this._backdrop = null;
this._isShown = null;
this._isBodyOverflowing = null;
this._ignoreBackdropClick = null;
this._scrollbarWidth = null;
};
_proto.handleUpdate = function handleUpdate() {
this._adjustDialog();
}; // Private
_proto._getConfig = function _getConfig(config) {
config = _objectSpread({}, Default, config);
Util.typeCheckConfig(NAME, config, DefaultType);
return config;
};
_proto._showElement = function _showElement(relatedTarget) {
var _this3 = this;
var transition = $$$1(this._element).hasClass(ClassName.FADE);
if (!this._element.parentNode || this._element.parentNode.nodeType !== Node.ELEMENT_NODE) {
// Don't move modal's DOM position
document.body.appendChild(this._element);
}
this._element.style.display = 'block';
this._element.removeAttribute('aria-hidden');
this._element.scrollTop = 0;
if (transition) {
Util.reflow(this._element);
}
$$$1(this._element).addClass(ClassName.SHOW);
if (this._config.focus) {
this._enforceFocus();
}
var shownEvent = $$$1.Event(Event.SHOWN, {
relatedTarget: relatedTarget
});
var transitionComplete = function transitionComplete() {
if (_this3._config.focus) {
_this3._element.focus();
}
_this3._isTransitioning = false;
$$$1(_this3._element).trigger(shownEvent);
};
if (transition) {
var transitionDuration = Util.getTransitionDurationFromElement(this._element);
$$$1(this._dialog).one(Util.TRANSITION_END, transitionComplete).emulateTransitionEnd(transitionDuration);
} else {
transitionComplete();
}
};
_proto._enforceFocus = function _enforceFocus() {
var _this4 = this;
$$$1(document).off(Event.FOCUSIN) // Guard against infinite focus loop
.on(Event.FOCUSIN, function (event) {
if (document !== event.target && _this4._element !== event.target && $$$1(_this4._element).has(event.target).length === 0) {
_this4._element.focus();
}
});
};
_proto._setEscapeEvent = function _setEscapeEvent() {
var _this5 = this;
if (this._isShown && this._config.keyboard) {
$$$1(this._element).on(Event.KEYDOWN_DISMISS, function (event) {
if (event.which === ESCAPE_KEYCODE) {
event.preventDefault();
_this5.hide();
}
});
} else if (!this._isShown) {
$$$1(this._element).off(Event.KEYDOWN_DISMISS);
}
};
_proto._setResizeEvent = function _setResizeEvent() {
var _this6 = this;
if (this._isShown) {
$$$1(window).on(Event.RESIZE, function (event) {
return _this6.handleUpdate(event);
});
} else {
$$$1(window).off(Event.RESIZE);
}
};
_proto._hideModal = function _hideModal() {
var _this7 = this;
this._element.style.display = 'none';
this._element.setAttribute('aria-hidden', true);
this._isTransitioning = false;
this._showBackdrop(function () {
$$$1(document.body).removeClass(ClassName.OPEN);
_this7._resetAdjustments();
_this7._resetScrollbar();
$$$1(_this7._element).trigger(Event.HIDDEN);
});
};
_proto._removeBackdrop = function _removeBackdrop() {
if (this._backdrop) {
$$$1(this._backdrop).remove();
this._backdrop = null;
}
};
_proto._showBackdrop = function _showBackdrop(callback) {
var _this8 = this;
var animate = $$$1(this._element).hasClass(ClassName.FADE) ? ClassName.FADE : '';
if (this._isShown && this._config.backdrop) {
this._backdrop = document.createElement('div');
this._backdrop.className = ClassName.BACKDROP;
if (animate) {
$$$1(this._backdrop).addClass(animate);
}
$$$1(this._backdrop).appendTo(document.body);
$$$1(this._element).on(Event.CLICK_DISMISS, function (event) {
if (_this8._ignoreBackdropClick) {
_this8._ignoreBackdropClick = false;
return;
}
if (event.target !== event.currentTarget) {
return;
}
if (_this8._config.backdrop === 'static') {
_this8._element.focus();
} else {
_this8.hide();
}
});
if (animate) {
Util.reflow(this._backdrop);
}
$$$1(this._backdrop).addClass(ClassName.SHOW);
if (!callback) {
return;
}
if (!animate) {
callback();
return;
}
var backdropTransitionDuration = Util.getTransitionDurationFromElement(this._backdrop);
$$$1(this._backdrop).one(Util.TRANSITION_END, callback).emulateTransitionEnd(backdropTransitionDuration);
} else if (!this._isShown && this._backdrop) {
$$$1(this._backdrop).removeClass(ClassName.SHOW);
var callbackRemove = function callbackRemove() {
_this8._removeBackdrop();
if (callback) {
callback();
}
};
if ($$$1(this._element).hasClass(ClassName.FADE)) {
var _backdropTransitionDuration = Util.getTransitionDurationFromElement(this._backdrop);
$$$1(this._backdrop).one(Util.TRANSITION_END, callbackRemove).emulateTransitionEnd(_backdropTransitionDuration);
} else {
callbackRemove();
}
} else if (callback) {
callback();
}
}; // ----------------------------------------------------------------------
// the following methods are used to handle overflowing modals
// todo (fat): these should probably be refactored out of modal.js
// ----------------------------------------------------------------------
_proto._adjustDialog = function _adjustDialog() {
var isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight;
if (!this._isBodyOverflowing && isModalOverflowing) {
this._element.style.paddingLeft = this._scrollbarWidth + "px";
}
if (this._isBodyOverflowing && !isModalOverflowing) {
this._element.style.paddingRight = this._scrollbarWidth + "px";
}
};
_proto._resetAdjustments = function _resetAdjustments() {
this._element.style.paddingLeft = '';
this._element.style.paddingRight = '';
};
_proto._checkScrollbar = function _checkScrollbar() {
var rect = document.body.getBoundingClientRect();
this._isBodyOverflowing = rect.left + rect.right < window.innerWidth;
this._scrollbarWidth = this._getScrollbarWidth();
};
_proto._setScrollbar = function _setScrollbar() {
var _this9 = this;
if (this._isBodyOverflowing) {
// Note: DOMNode.style.paddingRight returns the actual value or '' if not set
// while $(DOMNode).css('padding-right') returns the calculated value or 0 if not set
// Adjust fixed content padding
$$$1(Selector.FIXED_CONTENT).each(function (index, element) {
var actualPadding = $$$1(element)[0].style.paddingRight;
var calculatedPadding = $$$1(element).css('padding-right');
$$$1(element).data('padding-right', actualPadding).css('padding-right', parseFloat(calculatedPadding) + _this9._scrollbarWidth + "px");
}); // Adjust sticky content margin
$$$1(Selector.STICKY_CONTENT).each(function (index, element) {
var actualMargin = $$$1(element)[0].style.marginRight;
var calculatedMargin = $$$1(element).css('margin-right');
$$$1(element).data('margin-right', actualMargin).css('margin-right', parseFloat(calculatedMargin) - _this9._scrollbarWidth + "px");
}); // Adjust navbar-toggler margin
$$$1(Selector.NAVBAR_TOGGLER).each(function (index, element) {
var actualMargin = $$$1(element)[0].style.marginRight;
var calculatedMargin = $$$1(element).css('margin-right');
$$$1(element).data('margin-right', actualMargin).css('margin-right', parseFloat(calculatedMargin) + _this9._scrollbarWidth + "px");
}); // Adjust body padding
var actualPadding = document.body.style.paddingRight;
var calculatedPadding = $$$1(document.body).css('padding-right');
$$$1(document.body).data('padding-right', actualPadding).css('padding-right', parseFloat(calculatedPadding) + this._scrollbarWidth + "px");
}
};
_proto._resetScrollbar = function _resetScrollbar() {
// Restore fixed content padding
$$$1(Selector.FIXED_CONTENT).each(function (index, element) {
var padding = $$$1(element).data('padding-right');
if (typeof padding !== 'undefined') {
$$$1(element).css('padding-right', padding).removeData('padding-right');
}
}); // Restore sticky content and navbar-toggler margin
$$$1(Selector.STICKY_CONTENT + ", " + Selector.NAVBAR_TOGGLER).each(function (index, element) {
var margin = $$$1(element).data('margin-right');
if (typeof margin !== 'undefined') {
$$$1(element).css('margin-right', margin).removeData('margin-right');
}
}); // Restore body padding
var padding = $$$1(document.body).data('padding-right');
if (typeof padding !== 'undefined') {
$$$1(document.body).css('padding-right', padding).removeData('padding-right');
}
};
_proto._getScrollbarWidth = function _getScrollbarWidth() {
// thx d.walsh
var scrollDiv = document.createElement('div');
scrollDiv.className = ClassName.SCROLLBAR_MEASURER;
document.body.appendChild(scrollDiv);
var scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
return scrollbarWidth;
}; // Boosted mod
_proto._addAria = function _addAria() {
var $ModalPanel = $$$1(this._element);
var $ModalTitle = $ModalPanel.find('.modal-title');
var $ModalDialog = $ModalPanel.find('.modal-dialog');
$ModalPanel.attr({
role: 'dialog',
'aria-modal': true
});
if ($ModalTitle) {
var ModalTitleId = $ModalTitle.attr('id');
if (ModalTitleId) {
$ModalPanel.attr({
'aria-labelledby': ModalTitleId
});
}
}
if ($ModalDialog) {
$ModalDialog.attr('role', 'document');
}
}; // end mod
// Static
Modal._jQueryInterface = function _jQueryInterface(config, relatedTarget) {
return this.each(function () {
var data = $$$1(this).data(DATA_KEY);
var _config = _objectSpread({}, Default, $$$1(this).data(), typeof config === 'object' && config ? config : {});
if (!data) {
data = new Modal(this, _config);
$$$1(this).data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new TypeError("No method named \"" + config + "\"");
}
data[config](relatedTarget);
} else if (_config.show) {
data.show(relatedTarget);
}
});
};
_createClass(Modal, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}, {
key: "Default",
get: function get() {
return Default;
}
}]);
return Modal;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$$$1(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) {
var _this10 = this;
var target;
var selector = Util.getSelectorFromElement(this);
if (selector) {
target = $$$1(selector)[0];
}
var config = $$$1(target).data(DATA_KEY) ? 'toggle' : _objectSpread({}, $$$1(target).data(), $$$1(this).data());
if (this.tagName === 'A' || this.tagName === 'AREA') {
event.preventDefault();
}
var $target = $$$1(target).one(Event.SHOW, function (showEvent) {
if (showEvent.isDefaultPrevented()) {
// Only register focus restorer if modal will actually get shown
return;
}
$target.one(Event.HIDDEN, function () {
if ($$$1(_this10).is(':visible')) {
_this10.focus();
}
});
});
Modal._jQueryInterface.call($$$1(target), config, this);
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$$$1.fn[NAME] = Modal._jQueryInterface;
$$$1.fn[NAME].Constructor = Modal;
$$$1.fn[NAME].noConflict = function () {
$$$1.fn[NAME] = JQUERY_NO_CONFLICT;
return Modal._jQueryInterface;
};
return Modal;
}($);
/**
* --------------------------------------------------------------------------
* Boosted (v4.1.0): o-navbar.js
* Licensed under MIT (https://github.com/Orange-OpenSource/Orange-Boosted-Bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Navbar = function ($$$1) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'navbar';
var VERSION = '4.1.0';
var DATA_KEY = 'bs.navbar';
var JQUERY_NO_CONFLICT = $$$1.fn[NAME];
var BREAKPOINT = 768;
var Default = {
sticky: false,
trigger: ''
};
var DefaultType = {
sticky: 'boolean',
trigger: 'string'
};
var Selector = {
SUPRA_BAR: '.navbar.supra',
MEGAMENU_PANEL: '.mega-menu.panel'
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var Navbar =
/*#__PURE__*/
function () {
function Navbar(element, config) {
var _this = this;
this._element = element;
this._supraBar = $$$1(element).find(Selector.SUPRA_BAR);
this._config = this._getConfig(config);
this._initialHeight = $$$1(this._element).outerHeight();
this._initialSupraHeight = $$$1(this._supraBar).outerHeight();
this._addAria();
if (this._config.sticky) {
$$$1(this._element).addClass('fixed-header');
$$$1(Selector.MEGAMENU_PANEL).addClass('sticky');
$$$1(document.body).css('padding-top', this._initialHeight);
$$$1(window).on('scroll', function () {
var Scroll = $$$1(window).scrollTop();
if (Scroll > 0) {
$$$1(_this._element).addClass('minimized');
} else {
$$$1(_this._element).removeClass('minimized');
}
});
}
if (this._config.hideSupra) {
$$$1(window).on('scroll', function () {
if ($$$1(window).innerWidth() < BREAKPOINT) {
return;
}
var Scroll = $$$1(window).scrollTop();
if (Scroll > 0) {
$$$1(Selector.SUPRA_BAR).hide();
} else {
$$$1(Selector.SUPRA_BAR).show();
}
});
}
} // getters
var _proto = Navbar.prototype;
// private
_proto._getConfig = function _getConfig(config) {
config = $$$1.extend({}, Default, config);
Util.typeCheckConfig(NAME, config, DefaultType);
return config;
};
_proto._addAria = function _addAria() {
$$$1(this._element).find('.navbar .nav-link[data-toggle]').attr('aria-haspopup', true);
}; // static
Navbar._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var $this = $$$1(this);
var data = $this.data(DATA_KEY);
var _config = $$$1.extend({}, Default, $this.data(), typeof config === 'object' && config);
if (!data) {
data = new Navbar(this, _config);
$this.data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new TypeError("No method named \"" + config + "\"");
}
data[config]();
}
});
};
_createClass(Navbar, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}, {
key: "Default",
get: function get() {
return Default;
}
}]);
return Navbar;
}();
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$$$1.fn[NAME] = Navbar._jQueryInterface;
$$$1.fn[NAME].Constructor = Navbar;
$$$1.fn[NAME].noConflict = function () {
$$$1.fn[NAME] = JQUERY_NO_CONFLICT;
return Navbar._jQueryInterface;
};
return Navbar;
}($);
/**
* ------------------------------------------------------------------------------------------------------
* Boosted (v4.1.0): otab.js
* Licensed under MIT (https://github.com/Orange-OpenSource/Orange-Boosted-Bootstrap/blob/master/LICENSE)
* ------------------------------------------------------------------------------------------------------
*/
var Otab = function ($$$1) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'otab';
var VERSION = '4.1.0';
var DATA_KEY = 'bs.otab';
var EVENT_KEY = "." + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $$$1.fn[NAME];
var DEFAULT_THRESHOLD = 2;
var Event = {
CLICK_DATA_API: "click" + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
ACTIVE: 'active',
SHOW: 'show',
ACCORDION_LAYOUT: 'accordion-layout'
};
var Selector = {
OTAB_HEADING: '.o-tab-heading',
OTAB_CONTENT: '.o-tab-content'
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var Otab =
/*#__PURE__*/
function () {
function Otab(element) {
this._element = element;
this._addAccessibility();
if ($$$1(this._element).parent().find(Selector.OTAB_HEADING).length > DEFAULT_THRESHOLD) {
$$$1(this._element).parent().addClass(ClassName.ACCORDION_LAYOUT);
}
} // getters
var _proto = Otab.prototype;
// public
_proto.show = function show() {
var $element = $$$1(this._element);
if ($element.next().hasClass(ClassName.SHOW)) {
return;
} // from parent remove all tab-content show classes
$element.parent().find(Selector.OTAB_CONTENT).removeClass(ClassName.SHOW); // remove all aria-expanded=true
$element.parent().find('[aria-expanded="true"]').attr('aria-expanded', false); // add show class to next tab-content
$element.next().addClass(ClassName.SHOW); // add aria-expanded=true to element
$element.attr('aria-expanded', true);
}; // private
_proto._addAccessibility = function _addAccessibility() {
var $tab = $$$1(this._element);
var $tabpanel = $tab.next();
$tab.attr('id', Util.getUID(NAME));
$tabpanel.attr('id', Util.getUID(NAME));
$tab.attr({
'aria-controls': $tabpanel.attr('id'),
role: 'tab'
});
$tabpanel.attr({
'aria-labelledby': $tab.attr('id'),
role: 'tabpanel',
tabindex: 0
});
if ($tabpanel.hasClass(ClassName.SHOW)) {
$tab.attr('aria-expanded', true);
} else {
$tab.attr('aria-expanded', false);
}
}; // static
Otab._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var $this = $$$1(this);
var data = $this.data(DATA_KEY);
if (!data) {
data = new Otab(this);
$this.data(DATA_KEY, data);
} // Boosted mod
if (/init/.test(config)) {
return;
} // end mod
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new TypeError("No method named \"" + config + "\"");
}
data[config]();
}
});
};
_createClass(Otab, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}]);
return Otab;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$$$1(document).on('DOMContentLoaded', function () {
Otab._jQueryInterface.call($$$1(Selector.OTAB_HEADING), 'init');
}).on(Event.CLICK_DATA_API, Selector.OTAB_HEADING, function (event) {
event.preventDefault();
Otab._jQueryInterface.call($$$1(this), ClassName.SHOW);
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$$$1.fn[NAME] = Otab._jQueryInterface;
$$$1.fn[NAME].Constructor = Otab;
$$$1.fn[NAME].noConflict = function () {
$$$1.fn[NAME] = JQUERY_NO_CONFLICT;
return Otab._jQueryInterface;
};
return Otab;
}($);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.1.1): tooltip.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Tooltip = function ($$$1) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'tooltip';
var VERSION = '4.1.1';
var DATA_KEY = 'bs.tooltip';
var EVENT_KEY = "." + DATA_KEY;
var JQUERY_NO_CONFLICT = $$$1.fn[NAME];
var CLASS_PREFIX = 'bs-tooltip';
var BSCLS_PREFIX_REGEX = new RegExp("(^|\\s)" + CLASS_PREFIX + "\\S+", 'g');
var DefaultType = {
animation: 'boolean',
template: 'string',
title: '(string|element|function)',
trigger: 'string',
delay: '(number|object)',
html: 'boolean',
selector: '(string|boolean)',
placement: '(string|function)',
offset: '(number|string)',
container: '(string|element|boolean)',
fallbackPlacement: '(string|array)',
boundary: '(string|element)'
};
var AttachmentMap = {
AUTO: 'auto',
TOP: 'top',
RIGHT: 'right',
BOTTOM: 'bottom',
LEFT: 'left'
};
var Default = {
animation: true,
template: '<div class="tooltip" role="tooltip">' + '<div class="arrow"></div>' + '<div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
selector: false,
placement: 'top',
offset: 0,
container: false,
fallbackPlacement: 'flip',
boundary: 'scrollParent'
};
var HoverState = {
SHOW: 'show',
OUT: 'out'
};
var Event = {
HIDE: "hide" + EVENT_KEY,
HIDDEN: "hidden" + EVENT_KEY,
SHOW: "show" + EVENT_KEY,
SHOWN: "shown" + EVENT_KEY,
INSERTED: "inserted" + EVENT_KEY,
CLICK: "click" + EVENT_KEY,
FOCUSIN: "focusin" + EVENT_KEY,
FOCUSOUT: "focusout" + EVENT_KEY,
MOUSEENTER: "mouseenter" + EVENT_KEY,
MOUSELEAVE: "mouseleave" + EVENT_KEY
};
var ClassName = {
FADE: 'fade',
SHOW: 'show'
};
var Selector = {
TOOLTIP: '.tooltip',
TOOLTIP_INNER: '.tooltip-inner',
ARROW: '.arrow'
};
var Trigger = {
HOVER: 'hover',
FOCUS: 'focus',
CLICK: 'click',
MANUAL: 'manual'
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var Tooltip =
/*#__PURE__*/
function () {
function Tooltip(element, config) {
/**
* Check for Popper dependency
* Popper - https://popper.js.org
*/
if (typeof Popper === 'undefined') {
throw new TypeError('Bootstrap tooltips require Popper.js (https://popper.js.org)');
} // private
this._isEnabled = true;
this._timeout = 0;
this._hoverState = '';
this._activeTrigger = {};
this._popper = null; // Protected
this.element = element;
this.config = this._getConfig(config);
this.tip = null;
this._setListeners();
} // Getters
var _proto = Tooltip.prototype;
// Public
_proto.enable = function enable() {
this._isEnabled = true;
};
_proto.disable = function disable() {
this._isEnabled = false;
};
_proto.toggleEnabled = function toggleEnabled() {
this._isEnabled = !this._isEnabled;
};
_proto.toggle = function toggle(event) {
if (!this._isEnabled) {
return;
}
if (event) {
var dataKey = this.constructor.DATA_KEY;
var context = $$$1(event.currentTarget).data(dataKey);
if (!context) {
context = new this.constructor(event.currentTarget, this._getDelegateConfig());
$$$1(event.currentTarget).data(dataKey, context);
}
context._activeTrigger.click = !context._activeTrigger.click;
if (context._isWithActiveTrigger()) {
context._enter(null, context);
} else {
context._leave(null, context);
}
} else {
if ($$$1(this.getTipElement()).hasClass(ClassName.SHOW)) {
this._leave(null, this);
return;
}
this._enter(null, this);
}
};
_proto.dispose = function dispose() {
clearTimeout(this._timeout);
$$$1.removeData(this.element, this.constructor.DATA_KEY);
$$$1(this.element).off(this.constructor.EVENT_KEY);
$$$1(this.element).closest('.modal').off('hide.bs.modal');
if (this.tip) {
$$$1(this.tip).remove();
}
this._isEnabled = null;
this._timeout = null;
this._hoverState = null;
this._activeTrigger = null;
if (this._popper !== null) {
this._popper.destroy();
}
this._popper = null;
this.element = null;
this.config = null;
this.tip = null;
};
_proto.show = function show() {
var _this = this;
if ($$$1(this.element).css('display') === 'none') {
throw new Error('Please use show on visible elements');
}
var showEvent = $$$1.Event(this.constructor.Event.SHOW);
if (this.isWithContent() && this._isEnabled) {
$$$1(this.element).trigger(showEvent);
var isInTheDom = $$$1.contains(this.element.ownerDocument.documentElement, this.element);
if (showEvent.isDefaultPrevented() || !isInTheDom) {
return;
}
var tip = this.getTipElement();
var tipId = Util.getUID(this.constructor.NAME);
tip.setAttribute('id', tipId);
this.element.setAttribute('aria-describedby', tipId);
this.setContent();
if (this.config.animation) {
$$$1(tip).addClass(ClassName.FADE);
}
var placement = typeof this.config.placement === 'function' ? this.config.placement.call(this, tip, this.element) : this.config.placement;
var attachment = this._getAttachment(placement);
this.addAttachmentClass(attachment);
var container = this.config.container === false ? document.body : $$$1(this.config.container);
$$$1(tip).data(this.constructor.DATA_KEY, this);
if (!$$$1.contains(this.element.ownerDocument.documentElement, this.tip)) {
$$$1(tip).appendTo(container);
}
$$$1(this.element).trigger(this.constructor.Event.INSERTED);
this._popper = new Popper(this.element, tip, {
placement: attachment,
modifiers: {
offset: {
offset: this.config.offset
},
flip: {
behavior: this.config.fallbackPlacement
},
arrow: {
element: Selector.ARROW
},
preventOverflow: {
boundariesElement: this.config.boundary
}
},
onCreate: function onCreate(data) {
if (data.originalPlacement !== data.placement) {
_this._handlePopperPlacementChange(data);
}
},
onUpdate: function onUpdate(data) {
_this._handlePopperPlacementChange(data);
}
});
$$$1(tip).addClass(ClassName.SHOW); // If this is a touch-enabled device we add extra
// empty mouseover listeners to the body's immediate children;
// only needed because of broken event delegation on iOS
// https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html
if ('ontouchstart' in document.documentElement) {
$$$1(document.body).children().on('mouseover', null, $$$1.noop);
}
var complete = function complete() {
if (_this.config.animation) {
_this._fixTransition();
}
var prevHoverState = _this._hoverState;
_this._hoverState = null;
$$$1(_this.element).trigger(_this.constructor.Event.SHOWN);
if (prevHoverState === HoverState.OUT) {
_this._leave(null, _this);
}
};
if ($$$1(this.tip).hasClass(ClassName.FADE)) {
var transitionDuration = Util.getTransitionDurationFromElement(this.tip);
$$$1(this.tip).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration);
} else {
complete();
}
}
};
_proto.hide = function hide(callback) {
var _this2 = this;
var tip = this.getTipElement();
var hideEvent = $$$1.Event(this.constructor.Event.HIDE);
var complete = function complete() {
if (_this2._hoverState !== HoverState.SHOW && tip.parentNode) {
tip.parentNode.removeChild(tip);
}
_this2._cleanTipClass();
_this2.element.removeAttribute('aria-describedby');
$$$1(_this2.element).trigger(_this2.constructor.Event.HIDDEN);
if (_this2._popper !== null) {
_this2._popper.destroy();
}
if (callback) {
callback();
}
};
$$$1(this.element).trigger(hideEvent);
if (hideEvent.isDefaultPrevented()) {
return;
}
$$$1(tip).removeClass(ClassName.SHOW); // If this is a touch-enabled device we remove the extra
// empty mouseover listeners we added for iOS support
if ('ontouchstart' in document.documentElement) {
$$$1(document.body).children().off('mouseover', null, $$$1.noop);
}
this._activeTrigger[Trigger.CLICK] = false;
this._activeTrigger[Trigger.FOCUS] = false;
this._activeTrigger[Trigger.HOVER] = false;
if ($$$1(this.tip).hasClass(ClassName.FADE)) {
var transitionDuration = Util.getTransitionDurationFromElement(tip);
$$$1(tip).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration);
} else {
complete();
}
this._hoverState = '';
};
_proto.update = function update() {
if (this._popper !== null) {
this._popper.scheduleUpdate();
}
}; // Protected
_proto.isWithContent = function isWithContent() {
return Boolean(this.getTitle());
};
_proto.addAttachmentClass = function addAttachmentClass(attachment) {
$$$1(this.getTipElement()).addClass(CLASS_PREFIX + "-" + attachment);
};
_proto.getTipElement = function getTipElement() {
this.tip = this.tip || $$$1(this.config.template)[0];
return this.tip;
};
_proto.setContent = function setContent() {
var $tip = $$$1(this.getTipElement());
this.setElementContent($tip.find(Selector.TOOLTIP_INNER), this.getTitle());
$tip.removeClass(ClassName.FADE + " " + ClassName.SHOW);
};
_proto.setElementContent = function setElementContent($element, content) {
var html = this.config.html;
if (typeof content === 'object' && (content.nodeType || content.jquery)) {
// Content is a DOM node or a jQuery
if (html) {
if (!$$$1(content).parent().is($element)) {
$element.empty().append(content);
}
} else {
$element.text($$$1(content).text());
}
} else {
$element[html ? 'html' : 'text'](content);
}
};
_proto.getTitle = function getTitle() {
var title = this.element.getAttribute('data-original-title');
if (!title) {
title = typeof this.config.title === 'function' ? this.config.title.call(this.element) : this.config.title;
}
return title;
}; // Private
_proto._getAttachment = function _getAttachment(placement) {
return AttachmentMap[placement.toUpperCase()];
};
_proto._setListeners = function _setListeners() {
var _this3 = this;
var triggers = this.config.trigger.split(' ');
triggers.forEach(function (trigger) {
if (trigger === 'click') {
$$$1(_this3.element).on(_this3.constructor.Event.CLICK, _this3.config.selector, function (event) {
return _this3.toggle(event);
});
} else if (trigger !== Trigger.MANUAL) {
var eventIn = trigger === Trigger.HOVER ? _this3.constructor.Event.MOUSEENTER : _this3.constructor.Event.FOCUSIN;
var eventOut = trigger === Trigger.HOVER ? _this3.constructor.Event.MOUSELEAVE : _this3.constructor.Event.FOCUSOUT;
$$$1(_this3.element).on(eventIn, _this3.config.selector, function (event) {
return _this3._enter(event);
}).on(eventOut, _this3.config.selector, function (event) {
return _this3._leave(event);
});
}
$$$1(_this3.element).closest('.modal').on('hide.bs.modal', function () {
return _this3.hide();
});
});
if (this.config.selector) {
this.config = _objectSpread({}, this.config, {
trigger: 'manual',
selector: ''
});
} else {
this._fixTitle();
}
};
_proto._fixTitle = function _fixTitle() {
var titleType = typeof this.element.getAttribute('data-original-title');
if (this.element.getAttribute('title') || titleType !== 'string') {
this.element.setAttribute('data-original-title', this.element.getAttribute('title') || '');
this.element.setAttribute('title', '');
}
};
_proto._enter = function _enter(event, context) {
var dataKey = this.constructor.DATA_KEY;
context = context || $$$1(event.currentTarget).data(dataKey);
if (!context) {
context = new this.constructor(event.currentTarget, this._getDelegateConfig());
$$$1(event.currentTarget).data(dataKey, context);
}
if (event) {
context._activeTrigger[event.type === 'focusin' ? Trigger.FOCUS : Trigger.HOVER] = true;
}
if ($$$1(context.getTipElement()).hasClass(ClassName.SHOW) || context._hoverState === HoverState.SHOW) {
context._hoverState = HoverState.SHOW;
return;
}
clearTimeout(context._timeout);
context._hoverState = HoverState.SHOW;
if (!context.config.delay || !context.config.delay.show) {
context.show();
return;
}
context._timeout = setTimeout(function () {
if (context._hoverState === HoverState.SHOW) {
context.show();
}
}, context.config.delay.show);
};
_proto._leave = function _leave(event, context) {
var dataKey = this.constructor.DATA_KEY;
context = context || $$$1(event.currentTarget).data(dataKey);
if (!context) {
context = new this.constructor(event.currentTarget, this._getDelegateConfig());
$$$1(event.currentTarget).data(dataKey, context);
}
if (event) {
context._activeTrigger[event.type === 'focusout' ? Trigger.FOCUS : Trigger.HOVER] = false;
}
if (context._isWithActiveTrigger()) {
return;
}
clearTimeout(context._timeout);
context._hoverState = HoverState.OUT;
if (!context.config.delay || !context.config.delay.hide) {
context.hide();
return;
}
context._timeout = setTimeout(function () {
if (context._hoverState === HoverState.OUT) {
context.hide();
}
}, context.config.delay.hide);
};
_proto._isWithActiveTrigger = function _isWithActiveTrigger() {
for (var trigger in this._activeTrigger) {
if (this._activeTrigger[trigger]) {
return true;
}
}
return false;
};
_proto._getConfig = function _getConfig(config) {
config = _objectSpread({}, this.constructor.Default, $$$1(this.element).data(), typeof config === 'object' && config ? config : {});
if (typeof config.delay === 'number') {
config.delay = {
show: config.delay,
hide: config.delay
};
}
if (typeof config.title === 'number') {
config.title = config.title.toString();
}
if (typeof config.content === 'number') {
config.content = config.content.toString();
}
Util.typeCheckConfig(NAME, config, this.constructor.DefaultType);
return config;
};
_proto._getDelegateConfig = function _getDelegateConfig() {
var config = {};
if (this.config) {
for (var key in this.config) {
if (this.constructor.Default[key] !== this.config[key]) {
config[key] = this.config[key];
}
}
}
return config;
};
_proto._cleanTipClass = function _cleanTipClass() {
var $tip = $$$1(this.getTipElement());
var tabClass = $tip.attr('class').match(BSCLS_PREFIX_REGEX);
if (tabClass !== null && tabClass.length > 0) {
$tip.removeClass(tabClass.join(''));
}
};
_proto._handlePopperPlacementChange = function _handlePopperPlacementChange(data) {
this._cleanTipClass();
this.addAttachmentClass(this._getAttachment(data.placement));
};
_proto._fixTransition = function _fixTransition() {
var tip = this.getTipElement();
var initConfigAnimation = this.config.animation;
if (tip.getAttribute('x-placement') !== null) {
return;
}
$$$1(tip).removeClass(ClassName.FADE);
this.config.animation = false;
this.hide();
this.show();
this.config.animation = initConfigAnimation;
}; // Static
Tooltip._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $$$1(this).data(DATA_KEY);
var _config = typeof config === 'object' && config;
if (!data && /dispose|hide/.test(config)) {
return;
}
if (!data) {
data = new Tooltip(this, _config);
$$$1(this).data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new TypeError("No method named \"" + config + "\"");
}
data[config]();
}
});
};
_createClass(Tooltip, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}, {
key: "Default",
get: function get() {
return Default;
}
}, {
key: "NAME",
get: function get() {
return NAME;
}
}, {
key: "DATA_KEY",
get: function get() {
return DATA_KEY;
}
}, {
key: "Event",
get: function get() {
return Event;
}
}, {
key: "EVENT_KEY",
get: function get() {
return EVENT_KEY;
}
}, {
key: "DefaultType",
get: function get() {
return DefaultType;
}
}]);
return Tooltip;
}();
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$$$1.fn[NAME] = Tooltip._jQueryInterface;
$$$1.fn[NAME].Constructor = Tooltip;
$$$1.fn[NAME].noConflict = function () {
$$$1.fn[NAME] = JQUERY_NO_CONFLICT;
return Tooltip._jQueryInterface;
};
return Tooltip;
}($, Popper);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.1.1): popover.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Popover = function ($$$1) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'popover';
var VERSION = '4.1.1';
var DATA_KEY = 'bs.popover';
var EVENT_KEY = "." + DATA_KEY;
var JQUERY_NO_CONFLICT = $$$1.fn[NAME];
var CLASS_PREFIX = 'bs-popover';
var BSCLS_PREFIX_REGEX = new RegExp("(^|\\s)" + CLASS_PREFIX + "\\S+", 'g');
var Default = _objectSpread({}, Tooltip.Default, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover" role="tooltip">' + '<div class="arrow"></div>' + '<h3 class="popover-header"></h3>' + '<div class="popover-body"></div></div>'
});
var DefaultType = _objectSpread({}, Tooltip.DefaultType, {
content: '(string|element|function)'
});
var ClassName = {
FADE: 'fade',
SHOW: 'show'
};
var Selector = {
TITLE: '.popover-header',
CONTENT: '.popover-body'
};
var Event = {
HIDE: "hide" + EVENT_KEY,
HIDDEN: "hidden" + EVENT_KEY,
SHOW: "show" + EVENT_KEY,
SHOWN: "shown" + EVENT_KEY,
INSERTED: "inserted" + EVENT_KEY,
CLICK: "click" + EVENT_KEY,
FOCUSIN: "focusin" + EVENT_KEY,
FOCUSOUT: "focusout" + EVENT_KEY,
MOUSEENTER: "mouseenter" + EVENT_KEY,
MOUSELEAVE: "mouseleave" + EVENT_KEY
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var Popover =
/*#__PURE__*/
function (_Tooltip) {
function Popover() {
return _Tooltip.apply(this, arguments) || this;
}
var _proto = Popover.prototype;
// Overrides
_proto.isWithContent = function isWithContent() {
return this.getTitle() || this._getContent();
};
_proto.addAttachmentClass = function addAttachmentClass(attachment) {
$$$1(this.getTipElement()).addClass(CLASS_PREFIX + "-" + attachment);
};
_proto.getTipElement = function getTipElement() {
this.tip = this.tip || $$$1(this.config.template)[0];
return this.tip;
};
_proto.setContent = function setContent() {
var $tip = $$$1(this.getTipElement()); // We use append for html objects to maintain js events
this.setElementContent($tip.find(Selector.TITLE), this.getTitle());
var content = this._getContent();
if (typeof content === 'function') {
content = content.call(this.element);
}
this.setElementContent($tip.find(Selector.CONTENT), content);
$tip.removeClass(ClassName.FADE + " " + ClassName.SHOW);
}; // Private
_proto._getContent = function _getContent() {
return this.element.getAttribute('data-content') || this.config.content;
};
_proto._cleanTipClass = function _cleanTipClass() {
var $tip = $$$1(this.getTipElement());
var tabClass = $tip.attr('class').match(BSCLS_PREFIX_REGEX);
if (tabClass !== null && tabClass.length > 0) {
$tip.removeClass(tabClass.join(''));
}
}; // Static
Popover._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $$$1(this).data(DATA_KEY);
var _config = typeof config === 'object' ? config : null;
if (!data && /destroy|hide/.test(config)) {
return;
}
if (!data) {
data = new Popover(this, _config);
$$$1(this).data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new TypeError("No method named \"" + config + "\"");
}
data[config]();
}
});
};
_createClass(Popover, null, [{
key: "VERSION",
// Getters
get: function get() {
return VERSION;
}
}, {
key: "Default",
get: function get() {
return Default;
}
}, {
key: "NAME",
get: function get() {
return NAME;
}
}, {
key: "DATA_KEY",
get: function get() {
return DATA_KEY;
}
}, {
key: "Event",
get: function get() {
return Event;
}
}, {
key: "EVENT_KEY",
get: function get() {
return EVENT_KEY;
}
}, {
key: "DefaultType",
get: function get() {
return DefaultType;
}
}]);
_inheritsLoose(Popover, _Tooltip);
return Popover;
}(Tooltip);
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$$$1.fn[NAME] = Popover._jQueryInterface;
$$$1.fn[NAME].Constructor = Popover;
$$$1.fn[NAME].noConflict = function () {
$$$1.fn[NAME] = JQUERY_NO_CONFLICT;
return Popover._jQueryInterface;
};
return Popover;
}($);
/**
* --------------------------------------------------------------------------
* Boosted (v4.1.0): o-priority-nav.js
* Licensed under MIT (https://github.com/Orange-OpenSource/Orange-Boosted-Bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var PriorityNav = function ($$$1) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'prioritynav';
var VERSION = '4.1.0';
var DATA_KEY = 'bs.prioritynav';
var JQUERY_NO_CONFLICT = $$$1.fn[NAME];
var RESIZE_DURATION = 500;
var TAB_KEYCODE = 9;
var Event = {
RESIZE: 'resize',
FOCUS: 'focus'
};
var ClassName = {
PRIORITY: 'priority',
HIDE: 'sr-only',
RESIZING: 'resizing'
};
var Selector = {
NAV_ELEMENTS: 'li:not(\'.overflow-nav\')',
FIRST_ELEMENT: 'li:first',
PRIORITY_ELEMENT: '.priority'
};
var MenuLabelDefault = 'More';
function MenuTemplate(MenuLabel) {
return "\n <li class=\"overflow-nav nav-item dropdown\">\n <a href=\"#\" class=\"dropdown-toggle nav-link\" data-toggle=\"dropdown\" role=\"button\" aria-haspopup=\"true\">" + MenuLabel + "</a>\n <ul class=\"overflow-nav-list dropdown-menu dropdown-menu-right\"></ul>\n </li>\n ";
}
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var PriorityNav =
/*#__PURE__*/
function () {
function PriorityNav(element, config) {
this._element = element;
this._config = config;
if ($$$1(element).is('ul')) {
this._$menu = $$$1(element);
} else {
this._$menu = $$$1(element).find('ul').first();
}
this._initMenu();
this._$allNavElements = this._$menu.find(Selector.NAV_ELEMENTS);
this._bindUIActions();
this._setupMenu();
} // getters
var _proto = PriorityNav.prototype;
// public
// private
_proto._initMenu = function _initMenu() {
var MenuLabel = this._config;
if (typeof MenuLabel === 'undefined') {
MenuLabel = MenuLabelDefault;
} // add menu template
this._$menu.append(MenuTemplate(MenuLabel));
};
_proto._setupMenu = function _setupMenu() {
var $allNavElements = this._$allNavElements; // Checking top position of first item (sometimes changes)
var firstPos = this._$menu.find(Selector.FIRST_ELEMENT).position(); // Empty collection in which to put menu items to move
var $wrappedElements = $$$1(); // Used to snag the previous menu item in addition to ones that have wrapped
var first = true; // Loop through all the nav items...
this._$allNavElements.each(function (i) {
var $elm = $$$1(this); // ...in which to find wrapped elements
var pos = $elm.position();
if (pos.top !== firstPos.top) {
// If element is wrapped, add it to set
$wrappedElements = $wrappedElements.add($elm); // Add the previous one too, if first
if (first) {
$wrappedElements = $wrappedElements.add($allNavElements.eq(i - 1));
first = false;
}
}
});
if ($wrappedElements.length) {
// Clone set before altering
var newSet = $wrappedElements.clone(); // Hide ones that we're moving
$wrappedElements.addClass(ClassName.HIDE);
$wrappedElements.find('.nav-link').attr('tabindex', -1); // Add wrapped elements to dropdown
this._$menu.find('.overflow-nav-list').append(newSet); // Show new menu
this._$menu.find('.overflow-nav').addClass('show-inline-block'); // Make overflow visible again so dropdown can be seen.
this._$menu.find('.o-nav-local').css('overflow', 'visible'); // Check if menu doesn't overflow after process
if (this._$menu.find('.overflow-nav').position().top !== firstPos.top) {
var $item = $$$1(this._element).find("." + ClassName.HIDE).first().prev();
var $itemDuplicate = $item.clone();
$item.addClass(ClassName.HIDE);
$item.find('.nav-link').attr('tabindex', -1);
this._$menu.find('.overflow-nav-list').prepend($itemDuplicate);
}
} // hide menu from AT
this._$menu.find('.overflow-nav').attr('aria-hidden', true);
};
_proto._tearDown = function _tearDown() {
this._$menu.find('.overflow-nav-list').empty();
this._$menu.find('.overflow-nav').removeClass('show-inline-block');
this._$allNavElements.removeClass(ClassName.HIDE);
this._$allNavElements.find('.nav-link').attr('tabindex', 0);
};
_proto._bindUIActions = function _bindUIActions() {
var _this = this;
$$$1(window).on(Event.RESIZE, function () {
_this._$menu.addClass(ClassName.RESIZING);
setTimeout(function () {
_this._tearDown();
_this._setupMenu();
_this._$menu.removeClass(ClassName.RESIZING);
}, RESIZE_DURATION);
});
this._$menu.find('.overflow-nav .dropdown-toggle').on('keyup', function (e) {
if (e.which === TAB_KEYCODE) {
$$$1(e.target).dropdown('toggle');
}
});
}; // static
PriorityNav._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var $element = $$$1(this);
var data = $element.data(DATA_KEY);
if (!data) {
data = new PriorityNav(this, config);
$element.data(DATA_KEY, data);
}
if (typeof config !== 'undefined' && config) {
if (typeof config !== 'string') {
throw new TypeError('Priority nav label type must be string');
}
}
});
};
_createClass(PriorityNav, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}]);
return PriorityNav;
}();
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$$$1.fn[NAME] = PriorityNav._jQueryInterface;
$$$1.fn[NAME].Constructor = PriorityNav;
$$$1.fn[NAME].noConflict = function () {
$$$1.fn[NAME] = JQUERY_NO_CONFLICT;
return PriorityNav._jQueryInterface;
};
return PriorityNav;
}($);
/**
* --------------------------------------------------------------------------
* Boosted (v4.1.0): o-scroll-up.js
* Licensed under MIT (https://github.com/Orange-OpenSource/Orange-Boosted-Bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var ScrollUp = function ($$$1) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'scrollup';
var VERSION = '4.1.0';
var DATA_KEY = 'bs.scrollup';
var EVENT_KEY = "." + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $$$1.fn[NAME];
var SCROLLANIMATE = 500;
var Default = {
offset: 10,
method: 'auto',
target: ''
};
var Event = {
SCROLL: "scroll" + EVENT_KEY,
CLICK_SCROLL: "click" + EVENT_KEY,
LOAD_DATA_API: "load" + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
SCROLL_TOP: 'o-scroll-up'
};
var Selector = {
SCROLL_TOP: '.o-scroll-up:not(.static)'
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var ScrollUp =
/*#__PURE__*/
function () {
function ScrollUp(element) {
this._element = element;
this._scrollElement = window;
$$$1(window).on(Event.SCROLL, $$$1.proxy(this._process, this));
$$$1(Selector.SCROLL_TOP).on(Event.CLICK_SCROLL, $$$1.proxy(this._backToTop, this));
this._process();
} // getters
var _proto = ScrollUp.prototype;
// public
_proto.dispose = function dispose() {
$$$1.removeData(this._element, DATA_KEY);
$$$1(this._scrollElement).off(EVENT_KEY);
this._element = null;
this._scrollElement = null;
}; // private
_proto._process = function _process() {
if ($$$1(this._scrollElement).scrollTop() > Number($$$1(this._scrollElement).height())) {
$$$1(Selector.SCROLL_TOP).show();
} else {
$$$1(Selector.SCROLL_TOP).hide();
}
};
_proto._clear = function _clear() {
$$$1(this._selector).filter(Selector.ACTIVE).removeClass(ClassName.ACTIVE);
};
_proto._backToTop = function _backToTop() {
if (typeof $$$1.animate === 'function') {
$$$1('html, body').animate({
scrollTop: 0
}, SCROLLANIMATE);
} else {
$$$1('html, body').scrollTop(0);
}
}; // static
ScrollUp._jQueryInterface = function _jQueryInterface() {
return this.each(function () {
var data = $$$1(this).data(DATA_KEY);
if (!data) {
data = new ScrollUp(this);
$$$1(this).data(DATA_KEY, data);
}
});
};
_createClass(ScrollUp, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}, {
key: "Default",
get: function get() {
return Default;
}
}]);
return ScrollUp;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$$$1(window).on(Event.LOAD_DATA_API, function () {
var scrollUps = $$$1.makeArray($$$1(Selector.SCROLL_TOP));
for (var i = scrollUps.length; i--;) {
var $scrollup = $$$1(scrollUps[i]);
ScrollUp._jQueryInterface.call($scrollup, $scrollup.data());
}
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$$$1.fn[NAME] = ScrollUp._jQueryInterface;
$$$1.fn[NAME].Constructor = ScrollUp;
$$$1.fn[NAME].noConflict = function () {
$$$1.fn[NAME] = JQUERY_NO_CONFLICT;
return ScrollUp._jQueryInterface;
};
return ScrollUp;
}($);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.1.1): scrollspy.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var ScrollSpy = function ($$$1) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'scrollspy';
var VERSION = '4.1.1';
var DATA_KEY = 'bs.scrollspy';
var EVENT_KEY = "." + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $$$1.fn[NAME];
var Default = {
offset: 10,
method: 'auto',
target: ''
};
var DefaultType = {
offset: 'number',
method: 'string',
target: '(string|element)'
};
var Event = {
ACTIVATE: "activate" + EVENT_KEY,
SCROLL: "scroll" + EVENT_KEY,
LOAD_DATA_API: "load" + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
DROPDOWN_ITEM: 'dropdown-item',
DROPDOWN_MENU: 'dropdown-menu',
ACTIVE: 'active'
};
var Selector = {
DATA_SPY: '[data-spy="scroll"]',
ACTIVE: '.active',
NAV_LIST_GROUP: '.nav, .list-group',
NAV_LINKS: '.nav-link',
NAV_ITEMS: '.nav-item',
LIST_ITEMS: '.list-group-item',
DROPDOWN: '.dropdown',
DROPDOWN_ITEMS: '.dropdown-item',
DROPDOWN_TOGGLE: '.dropdown-toggle'
};
var OffsetMethod = {
OFFSET: 'offset',
POSITION: 'position'
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var ScrollSpy =
/*#__PURE__*/
function () {
function ScrollSpy(element, config) {
var _this = this;
this._element = element;
this._scrollElement = element.tagName === 'BODY' ? window : element;
this._config = this._getConfig(config);
this._selector = this._config.target + " " + Selector.NAV_LINKS + "," + (this._config.target + " " + Selector.LIST_ITEMS + ",") + (this._config.target + " " + Selector.DROPDOWN_ITEMS);
this._offsets = [];
this._targets = [];
this._activeTarget = null;
this._scrollHeight = 0;
$$$1(this._scrollElement).on(Event.SCROLL, function (event) {
return _this._process(event);
});
this.refresh();
this._process();
} // Getters
var _proto = ScrollSpy.prototype;
// Public
_proto.refresh = function refresh() {
var _this2 = this;
var autoMethod = this._scrollElement === this._scrollElement.window ? OffsetMethod.OFFSET : OffsetMethod.POSITION;
var offsetMethod = this._config.method === 'auto' ? autoMethod : this._config.method;
var offsetBase = offsetMethod === OffsetMethod.POSITION ? this._getScrollTop() : 0;
this._offsets = [];
this._targets = [];
this._scrollHeight = this._getScrollHeight();
var targets = $$$1.makeArray($$$1(this._selector));
targets.map(function (element) {
var target;
var targetSelector = Util.getSelectorFromElement(element);
if (targetSelector) {
target = $$$1(targetSelector)[0];
}
if (target) {
var targetBCR = target.getBoundingClientRect();
if (targetBCR.width || targetBCR.height) {
// TODO (fat): remove sketch reliance on jQuery position/offset
return [$$$1(target)[offsetMethod]().top + offsetBase, targetSelector];
}
}
return null;
}).filter(function (item) {
return item;
}).sort(function (a, b) {
return a[0] - b[0];
}).forEach(function (item) {
_this2._offsets.push(item[0]);
_this2._targets.push(item[1]);
});
};
_proto.dispose = function dispose() {
$$$1.removeData(this._element, DATA_KEY);
$$$1(this._scrollElement).off(EVENT_KEY);
this._element = null;
this._scrollElement = null;
this._config = null;
this._selector = null;
this._offsets = null;
this._targets = null;
this._activeTarget = null;
this._scrollHeight = null;
}; // Private
_proto._getConfig = function _getConfig(config) {
config = _objectSpread({}, Default, typeof config === 'object' && config ? config : {});
if (typeof config.target !== 'string') {
var id = $$$1(config.target).attr('id');
if (!id) {
id = Util.getUID(NAME);
$$$1(config.target).attr('id', id);
}
config.target = "#" + id;
}
Util.typeCheckConfig(NAME, config, DefaultType);
return config;
};
_proto._getScrollTop = function _getScrollTop() {
return this._scrollElement === window ? this._scrollElement.pageYOffset : this._scrollElement.scrollTop;
};
_proto._getScrollHeight = function _getScrollHeight() {
return this._scrollElement.scrollHeight || Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
};
_proto._getOffsetHeight = function _getOffsetHeight() {
return this._scrollElement === window ? window.innerHeight : this._scrollElement.getBoundingClientRect().height;
};
_proto._process = function _process() {
var scrollTop = this._getScrollTop() + this._config.offset;
var scrollHeight = this._getScrollHeight();
var maxScroll = this._config.offset + scrollHeight - this._getOffsetHeight();
if (this._scrollHeight !== scrollHeight) {
this.refresh();
}
if (scrollTop >= maxScroll) {
var target = this._targets[this._targets.length - 1];
if (this._activeTarget !== target) {
this._activate(target);
}
return;
}
if (this._activeTarget && scrollTop < this._offsets[0] && this._offsets[0] > 0) {
this._activeTarget = null;
this._clear();
return;
}
for (var i = this._offsets.length; i--;) {
var isActiveTarget = this._activeTarget !== this._targets[i] && scrollTop >= this._offsets[i] && (typeof this._offsets[i + 1] === 'undefined' || scrollTop < this._offsets[i + 1]);
if (isActiveTarget) {
this._activate(this._targets[i]);
}
}
};
_proto._activate = function _activate(target) {
this._activeTarget = target;
this._clear();
var queries = this._selector.split(','); // eslint-disable-next-line arrow-body-style
queries = queries.map(function (selector) {
return selector + "[data-target=\"" + target + "\"]," + (selector + "[href=\"" + target + "\"]");
});
var $link = $$$1(queries.join(','));
if ($link.hasClass(ClassName.DROPDOWN_ITEM)) {
$link.closest(Selector.DROPDOWN).find(Selector.DROPDOWN_TOGGLE).addClass(ClassName.ACTIVE);
$link.addClass(ClassName.ACTIVE);
} else {
// Set triggered link as active
$link.addClass(ClassName.ACTIVE); // Set triggered links parents as active
// With both <ul> and <nav> markup a parent is the previous sibling of any nav ancestor
$link.parents(Selector.NAV_LIST_GROUP).prev(Selector.NAV_LINKS + ", " + Selector.LIST_ITEMS).addClass(ClassName.ACTIVE); // Handle special case when .nav-link is inside .nav-item
$link.parents(Selector.NAV_LIST_GROUP).prev(Selector.NAV_ITEMS).children(Selector.NAV_LINKS).addClass(ClassName.ACTIVE);
}
$$$1(this._scrollElement).trigger(Event.ACTIVATE, {
relatedTarget: target
});
};
_proto._clear = function _clear() {
$$$1(this._selector).filter(Selector.ACTIVE).removeClass(ClassName.ACTIVE);
}; // Static
ScrollSpy._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $$$1(this).data(DATA_KEY);
var _config = typeof config === 'object' && config;
if (!data) {
data = new ScrollSpy(this, _config);
$$$1(this).data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new TypeError("No method named \"" + config + "\"");
}
data[config]();
}
});
};
_createClass(ScrollSpy, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}, {
key: "Default",
get: function get() {
return Default;
}
}]);
return ScrollSpy;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$$$1(window).on(Event.LOAD_DATA_API, function () {
var scrollSpys = $$$1.makeArray($$$1(Selector.DATA_SPY));
for (var i = scrollSpys.length; i--;) {
var $spy = $$$1(scrollSpys[i]);
ScrollSpy._jQueryInterface.call($spy, $spy.data());
}
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$$$1.fn[NAME] = ScrollSpy._jQueryInterface;
$$$1.fn[NAME].Constructor = ScrollSpy;
$$$1.fn[NAME].noConflict = function () {
$$$1.fn[NAME] = JQUERY_NO_CONFLICT;
return ScrollSpy._jQueryInterface;
};
return ScrollSpy;
}($);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.1.1): tab.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Tab = function ($$$1) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'tab';
var VERSION = '4.1.1';
var DATA_KEY = 'bs.tab';
var EVENT_KEY = "." + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $$$1.fn[NAME]; // boosted mod
var ARROW_LEFT_KEYCODE = 37; // KeyboardEvent.which value for left arrow key
var ARROW_UP_KEYCODE = 38; // KeyboardEvent.which value for up arrow key
var ARROW_RIGHT_KEYCODE = 39; // KeyboardEvent.which value for right arrow key
var ARROW_DOWN_KEYCODE = 40; // KeyboardEvent.which value for down arrow key
var REGEXP_KEYDOWN = new RegExp(ARROW_LEFT_KEYCODE + "|" + ARROW_UP_KEYCODE + "|" + ARROW_RIGHT_KEYCODE + "|" + ARROW_DOWN_KEYCODE); // end mod
var Event = {
HIDE: "hide" + EVENT_KEY,
HIDDEN: "hidden" + EVENT_KEY,
SHOW: "show" + EVENT_KEY,
SHOWN: "shown" + EVENT_KEY,
CLICK_DATA_API: "click" + EVENT_KEY + DATA_API_KEY,
KEYDOWN_DATA_API: "keydown" + EVENT_KEY + DATA_API_KEY // boosted mod
};
var ClassName = {
DROPDOWN_MENU: 'dropdown-menu',
ACTIVE: 'active',
DISABLED: 'disabled',
FADE: 'fade',
SHOW: 'show'
};
var Selector = {
DROPDOWN: '.dropdown',
NAV_LIST_GROUP: '.nav, .list-group',
ACTIVE: '.active',
ACTIVE_UL: '> li > .active',
DATA_TOGGLE: '[data-toggle="tab"], [data-toggle="pill"], [data-toggle="list"]',
ACTIVE_CHILD: '> .nav-item > .active, > .active, > .dropdown > .dropdown-menu > .nav-item > .active, > .dropdown > .dropdown-menu > .active',
// boosted mod
DROPDOWN_TOGGLE: '.dropdown-toggle',
DROPDOWN_ACTIVE_CHILD: '> .dropdown-menu .active'
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
};
var Tab =
/*#__PURE__*/
function () {
function Tab(element) {
this._element = element;
this._addAccessibility(); // Boosted mod
} // Getters
var _proto = Tab.prototype;
// Public
_proto.show = function show() {
var _this = this;
if (this._element.parentNode && this._element.parentNode.nodeType === Node.ELEMENT_NODE && $$$1(this._element).hasClass(ClassName.ACTIVE) || $$$1(this._element).hasClass(ClassName.DISABLED)) {
return;
}
var target;
var previous;
var listElement = $$$1(this._element).closest(Selector.NAV_LIST_GROUP)[0];
var selector = Util.getSelectorFromElement(this._element);
if (listElement) {
var itemSelector = listElement.nodeName === 'UL' ? Selector.ACTIVE_UL : Selector.ACTIVE;
previous = $$$1.makeArray($$$1(listElement).find(itemSelector));
previous = previous[previous.length - 1];
}
var hideEvent = $$$1.Event(Event.HIDE, {
relatedTarget: this._element
});
var showEvent = $$$1.Event(Event.SHOW, {
relatedTarget: previous
});
if (previous) {
$$$1(previous).trigger(hideEvent);
}
$$$1(this._element).trigger(showEvent);
if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) {
return;
}
if (selector) {
target = $$$1(selector)[0];
}
this._activate(this._element, listElement);
var complete = function complete() {
var hiddenEvent = $$$1.Event(Event.HIDDEN, {
relatedTarget: _this._element
});
var shownEvent = $$$1.Event(Event.SHOWN, {
relatedTarget: previous
});
$$$1(previous).trigger(hiddenEvent);
$$$1(_this._element).trigger(shownEvent);
};
if (target) {
this._activate(target, target.parentNode, complete);
} else {
complete();
}
};
_proto.dispose = function dispose() {
$$$1.removeData(this._element, DATA_KEY);
this._element = null;
}; // Private
_proto._activate = function _activate(element, container, callback) {
var _this2 = this;
var activeElements;
if (container.nodeName === 'UL') {
activeElements = $$$1(container).find(Selector.ACTIVE_UL);
} else {
activeElements = $$$1(container).children(Selector.ACTIVE);
}
var active = activeElements[0];
var isTransitioning = callback && active && $$$1(active).hasClass(ClassName.FADE);
var complete = function complete() {
return _this2._transitionComplete(element, active, callback);
}; // Boosted mod
$$$1(container).find('.nav-link:not(.dropdown-toggle)').attr({
tabIndex: '-1',
'aria-selected': false
});
$$$1(container).find('.tab-pane').attr({
'aria-hidden': true,
tabIndex: '-1'
}); // end mod
if (active && isTransitioning) {
var transitionDuration = Util.getTransitionDurationFromElement(active);
$$$1(active).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration);
} else {
complete();
}
};
_proto._transitionComplete = function _transitionComplete(element, active, callback) {
if (active) {
$$$1(active).removeClass(ClassName.SHOW + " " + ClassName.ACTIVE);
var dropdownChild = $$$1(active.parentNode).find(Selector.DROPDOWN_ACTIVE_CHILD)[0];
if (dropdownChild) {
$$$1(dropdownChild).removeClass(ClassName.ACTIVE);
}
if (active.getAttribute('role') === 'tab') {
active.setAttribute('aria-selected', false);
}
}
$$$1(element).addClass(ClassName.ACTIVE);
if (element.getAttribute('role') === 'tab') {
element.setAttribute('aria-selected', true);
} // Boosted mod
$$$1(element).filter('.nav-link:not(.dropdown-toggle).active').attr({
tabIndex: '0',
'aria-selected': true
});
$$$1(element).filter('.tab-pane.active').attr({
'aria-hidden': false,
tabIndex: '0'
}); // end mod
Util.reflow(element);
$$$1(element).addClass(ClassName.SHOW);
if (element.parentNode && $$$1(element.parentNode).hasClass(ClassName.DROPDOWN_MENU)) {
var dropdownElement = $$$1(element).closest(Selector.DROPDOWN)[0];
if (dropdownElement) {
$$$1(dropdownElement).find(Selector.DROPDOWN_TOGGLE).addClass(ClassName.ACTIVE);
}
element.setAttribute('aria-expanded', true);
}
if (callback) {
callback();
}
}; // Boosted mod
_proto._addAccessibility = function _addAccessibility() {
var $tab = $$$1(this._element);
var $tabpanel = $$$1($tab.attr('href'));
var $tablist = $tab.closest(Selector.NAV_LIST_GROUP);
var tabId = $tab.attr('id') || Util.getUID(NAME);
$tab.attr('id', tabId);
if ($tabpanel) {
$tab.attr('role', 'tab');
$tablist.attr('role', 'tablist'); // $li.attr('role', 'presentation')
}
if ($tab.hasClass(ClassName.ACTIVE)) {
$tab.attr({
tabIndex: '0',
'aria-selected': 'true'
});
if ($tab.attr('href')) {
$tab.attr('aria-controls', $tab.attr('href').substr(1));
}
$tabpanel.attr({
role: 'tabpanel',
tabIndex: '0',
'aria-hidden': 'false',
'aria-labelledby': tabId
});
} else {
$tab.attr({
tabIndex: '-1',
'aria-selected': 'false'
});
if ($tab.attr('href')) {
$tab.attr('aria-controls', $tab.attr('href').substr(1));
}
$tabpanel.attr({
role: 'tabpanel',
tabIndex: '-1',
'aria-hidden': 'true',
'aria-labelledby': tabId
});
}
}; // end mod
// Static
// Boosted mod
Tab._dataApiKeydownHandler = function _dataApiKeydownHandler(e) {
var $this = $$$1(this);
var Items = $this.closest('ul[role=tablist] ').find('[role=tab]:visible');
var k = e.which || e.keyCode;
var index = 0;
index = Items.index(Items.filter(':focus'));
if (k === ARROW_UP_KEYCODE || k === ARROW_LEFT_KEYCODE) {
index--;
} // up & left
if (k === ARROW_RIGHT_KEYCODE || k === ARROW_DOWN_KEYCODE) {
index++;
} // down & right
if (index < 0) {
index = Items.length - 1;
}
if (index === Items.length) {
index = 0;
}
var nextTab = Items.eq(index);
if (nextTab.attr('role') === 'tab') {
nextTab.tab('show').trigger('focus');
}
e.preventDefault();
e.stopPropagation();
}; // end mod
Tab._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var $this = $$$1(this);
var data = $this.data(DATA_KEY);
if (!data) {
data = new Tab(this);
$this.data(DATA_KEY, data);
} // Boosted mod
if (/init/.test(config)) {
return;
} // end mod
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new TypeError("No method named \"" + config + "\"");
}
data[config]();
}
});
};
_createClass(Tab, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}]);
return Tab;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$$$1(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) {
event.preventDefault();
Tab._jQueryInterface.call($$$1(this), 'show');
}) // Boosted mod
.on(Event.KEYDOWN_DATA_API, Selector.DATA_TOGGLE, function (event) {
if (!REGEXP_KEYDOWN.test(event.which)) {
return;
}
event.preventDefault();
Tab._dataApiKeydownHandler.call($$$1(this), event);
}).on('DOMContentLoaded', function () {
Tab._jQueryInterface.call($$$1(Selector.DATA_TOGGLE), 'init');
}); // end mod
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$$$1.fn[NAME] = Tab._jQueryInterface;
$$$1.fn[NAME].Constructor = Tab;
$$$1.fn[NAME].noConflict = function () {
$$$1.fn[NAME] = JQUERY_NO_CONFLICT;
return Tab._jQueryInterface;
};
return Tab;
}($);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.1.1): index.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
(function ($$$1) {
if (typeof $$$1 === 'undefined') {
throw new TypeError('Bootstrap\'s JavaScript requires jQuery. jQuery must be included before Bootstrap\'s JavaScript.');
}
var version = $$$1.fn.jquery.split(' ')[0].split('.');
var minMajor = 1;
var ltMajor = 2;
var minMinor = 9;
var minPatch = 1;
var maxMajor = 4;
if (version[0] < ltMajor && version[1] < minMinor || version[0] === minMajor && version[1] === minMinor && version[2] < minPatch || version[0] >= maxMajor) {
throw new Error('Bootstrap\'s JavaScript requires at least jQuery v1.9.1 but less than v4.0.0');
}
})($);
exports.Util = Util;
exports.Alert = Alert;
exports.Button = Button;
exports.Carousel = Carousel;
exports.Collapse = Collapse;
exports.Dropdown = Dropdown;
exports.MegaMenu = MegaMenu;
exports.Modal = Modal;
exports.Navbar = Navbar;
exports.Otab = Otab;
exports.Popover = Popover;
exports.PriorityNav = PriorityNav;
exports.ScrollUp = ScrollUp;
exports.Scrollspy = ScrollSpy;
exports.Tab = Tab;
exports.Tooltip = Tooltip;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=boosted.js.map
| mit |
cdnjs/cdnjs | ajax/libs/san/3.8.3/san.modern.js | 268004 | /**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file San 主文件
*/
(function (root) {
// 人工调整打包代码顺序,通过注释手工写一些依赖
// // require('./util/guid');
// // require('./util/empty');
// // require('./util/extend');
// // require('./util/inherits');
// // require('./util/each');
// // require('./util/contains');
// // require('./util/bind');
// // require('./browser/on');
// // require('./browser/un');
// // require('./browser/svg-tags');
// // require('./browser/create-el');
// // require('./browser/remove-el');
// // require('./util/next-tick');
// // require('./browser/ie');
// // require('./browser/ie-old-than-9');
// // require('./browser/input-event-compatible');
// // require('./browser/auto-close-tags');
// // require('./util/data-types.js');
// // require('./util/create-data-types-checker.js');
// // require('./parser/walker');
// // require('./parser/parse-template');
// // require('./runtime/change-expr-compare');
// // require('./runtime/data-change-type');
// // require('./runtime/default-filters');
// // require('./view/life-cycle');
// // require('./view/node-type');
// // require('./view/get-prop-handler');
// // require('./view/is-data-change-by-element');
// // require('./view/get-event-listener');
// // require('./view/create-node');
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 唯一id
*/
/**
* 获取唯一id
*
* @type {number} 唯一id
*/
var guid = 1;
// exports = module.exports = guid;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 空函数
*/
/**
* 啥都不干
*/
function empty() {}
// exports = module.exports = empty;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 属性拷贝
*/
/**
* 对象属性拷贝
*
* @param {Object} target 目标对象
* @param {Object} source 源对象
* @return {Object} 返回目标对象
*/
function extend(target, source) {
for (var key in source) {
/* istanbul ignore else */
if (source.hasOwnProperty(key)) {
var value = source[key];
if (typeof value !== 'undefined') {
target[key] = value;
}
}
}
return target;
}
// exports = module.exports = extend;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 构建类之间的继承关系
*/
// var extend = require('./extend');
/**
* 构建类之间的继承关系
*
* @param {Function} subClass 子类函数
* @param {Function} superClass 父类函数
*/
function inherits(subClass, superClass) {
/* jshint -W054 */
var subClassProto = subClass.prototype;
var F = new Function();
F.prototype = superClass.prototype;
subClass.prototype = new F();
subClass.prototype.constructor = subClass;
extend(subClass.prototype, subClassProto);
/* jshint +W054 */
}
// exports = module.exports = inherits;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 遍历数组
*/
/**
* 遍历数组集合
*
* @param {Array} array 数组源
* @param {function(Any,number):boolean} iterator 遍历函数
*/
function each(array, iterator) {
if (array && array.length > 0) {
for (var i = 0, l = array.length; i < l; i++) {
if (iterator(array[i], i) === false) {
break;
}
}
}
}
// exports = module.exports = each;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 判断数组中是否包含某项
*/
// var each = require('./each');
/**
* 判断数组中是否包含某项
*
* @param {Array} array 数组
* @param {*} value 包含的项
* @return {boolean}
*/
function contains(array, value) {
var result = false;
each(array, function (item) {
result = item === value;
return !result;
});
return result;
}
// exports = module.exports = contains;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file bind函数
*/
/**
* Function.prototype.bind 方法的兼容性封装
*
* @param {Function} func 要bind的函数
* @param {Object} thisArg this指向对象
* @param {...*} args 预设的初始参数
* @return {Function}
*/
function bind(func, thisArg) {
var nativeBind = Function.prototype.bind;
var slice = Array.prototype.slice;
// #[begin] allua
// if (nativeBind && func.bind === nativeBind) {
// #[end]
return nativeBind.apply(func, slice.call(arguments, 1));
// #[begin] allua
// }
//
// /* istanbul ignore next */
// var args = slice.call(arguments, 2);
// /* istanbul ignore next */
// return function () {
// return func.apply(thisArg, args.concat(slice.call(arguments)));
// };
// #[end]
}
// exports = module.exports = bind;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file DOM 事件挂载
*/
/**
* DOM 事件挂载
*
* @inner
* @param {HTMLElement} el DOM元素
* @param {string} eventName 事件名
* @param {Function} listener 监听函数
* @param {boolean} capture 是否是捕获阶段
*/
function on(el, eventName, listener, capture) {
// #[begin] allua
// /* istanbul ignore else */
// if (el.addEventListener) {
// #[end]
el.addEventListener(eventName, listener, capture);
// #[begin] allua
// }
// else {
// el.attachEvent('on' + eventName, listener);
// }
// #[end]
}
// exports = module.exports = on;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file DOM 事件卸载
*/
/**
* DOM 事件卸载
*
* @inner
* @param {HTMLElement} el DOM元素
* @param {string} eventName 事件名
* @param {Function} listener 监听函数
* @param {boolean} capture 是否是捕获阶段
*/
function un(el, eventName, listener, capture) {
// #[begin] allua
// /* istanbul ignore else */
// if (el.addEventListener) {
// #[end]
el.removeEventListener(eventName, listener, capture);
// #[begin] allua
// }
// else {
// el.detachEvent('on' + eventName, listener);
// }
// #[end]
}
// exports = module.exports = un;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 将字符串逗号切分返回对象
*/
// var each = require('../util/each');
/**
* 将字符串逗号切分返回对象
*
* @param {string} source 源字符串
* @return {Object}
*/
function splitStr2Obj(source) {
var result = {};
each(
source.split(','),
function (key) {
result[key] = key;
}
);
return result;
}
// exports = module.exports = splitStr2Obj;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file SVG标签表
*/
// var splitStr2Obj = require('../util/split-str-2-obj');
/**
* svgTags
*
* @see https://www.w3.org/TR/SVG/svgdtd.html 只取常用
* @type {Object}
*/
var svgTags = splitStr2Obj(''
// structure
+ 'svg,g,defs,desc,metadata,symbol,use,'
// image & shape
+ 'image,path,rect,circle,line,ellipse,polyline,polygon,'
// text
+ 'text,tspan,tref,textpath,'
// other
+ 'marker,pattern,clippath,mask,filter,cursor,view,animate,'
// font
+ 'font,font-face,glyph,missing-glyph,'
// camel
+ 'animateColor,animateMotion,animateTransform,textPath,foreignObject'
);
// exports = module.exports = svgTags;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file DOM创建
*/
// var svgTags = require('./svg-tags');
/**
* 创建 DOM 元素
*
* @param {string} tagName tagName
* @return {HTMLElement}
*/
function createEl(tagName) {
if (svgTags[tagName] && document.createElementNS) {
return document.createElementNS('http://www.w3.org/2000/svg', tagName);
}
return document.createElement(tagName);
}
// exports = module.exports = createEl;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 移除DOM
*/
/**
* 将 DOM 从页面中移除
*
* @param {HTMLElement} el DOM元素
*/
function removeEl(el) {
if (el && el.parentNode) {
el.parentNode.removeChild(el);
}
}
// exports = module.exports = removeEl;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 在下一个时间周期运行任务
*/
// 该方法参照了vue2.5.0的实现,感谢vue团队
// SEE: https://github.com/vuejs/vue/blob/0948d999f2fddf9f90991956493f976273c5da1f/src/core/util/env.js#L68
// var bind = require('./bind');
/**
* 下一个周期要执行的任务列表
*
* @inner
* @type {Array}
*/
var nextTasks = [];
/**
* 执行下一个周期任务的函数
*
* @inner
* @type {Function}
*/
var nextHandler;
/**
* 浏览器是否支持原生Promise
* 对Promise做判断,是为了禁用一些不严谨的Promise的polyfill
*
* @inner
* @type {boolean}
*/
var isNativePromise = typeof Promise === 'function' && /native code/.test(Promise);
/**
* 在下一个时间周期运行任务
*
* @inner
* @param {Function} fn 要运行的任务函数
* @param {Object=} thisArg this指向对象
*/
function nextTick(fn, thisArg) {
if (thisArg) {
fn = bind(fn, thisArg);
}
nextTasks.push(fn);
if (nextHandler) {
return;
}
nextHandler = function () {
var tasks = nextTasks.slice(0);
nextTasks = [];
nextHandler = null;
for (var i = 0, l = tasks.length; i < l; i++) {
tasks[i]();
}
};
// 非标准方法,但是此方法非常吻合要求。
/* istanbul ignore next */
if (typeof setImmediate === 'function') {
setImmediate(nextHandler);
}
// 用MessageChannel去做setImmediate的polyfill
// 原理是将新的message事件加入到原有的dom events之后
else if (typeof MessageChannel === 'function') {
var channel = new MessageChannel();
var port = channel.port2;
channel.port1.onmessage = nextHandler;
port.postMessage(1);
}
// for native app
else if (isNativePromise) {
Promise.resolve().then(nextHandler);
}
else {
setTimeout(nextHandler, 0);
}
}
// exports = module.exports = nextTick;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file ie版本号
*/
// #[begin] allua
// /**
// * 从userAgent中ie版本号的匹配信息
// *
// * @type {Array}
// */
// var ieVersionMatch = typeof navigator !== 'undefined'
// && navigator.userAgent.match(/msie\s*([0-9]+)/i);
//
// /**
// * ie版本号,非ie时为0
// *
// * @type {number}
// */
// var ie = ieVersionMatch ? /* istanbul ignore next */ ieVersionMatch[1] - 0 : 0;
// #[end]
// exports = module.exports = ie;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 是否 IE 并且小于 9
*/
// var ie = require('./ie');
// HACK:
// 1. IE8下,设置innerHTML时如果以html comment开头,comment会被自动滤掉
// 为了保证stump存在,需要设置完html后,createComment并appendChild/insertBefore
// 2. IE8下,innerHTML还不支持custom element,所以需要用div替代,不用createElement
// 3. 虽然IE8已经优化了字符串+连接,碎片化连接性能不再退化
// 但是由于上面多个兼容场景都用 < 9 判断,所以字符串连接也沿用
// 所以结果是IE8下字符串连接用的是数组join的方式
// #[begin] allua
// /**
// * 是否 IE 并且小于 9
// */
// var ieOldThan9 = ie && /* istanbul ignore next */ ie < 9;
// #[end]
// exports = module.exports = ieOldThan9;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 触发元素事件
*/
/**
* 触发元素事件
*
* @inner
* @param {HTMLElement} el DOM元素
* @param {string} eventName 事件名
*/
function trigger(el, eventName) {
var event = document.createEvent('HTMLEvents');
event.initEvent(eventName, true, true);
el.dispatchEvent(event);
}
// exports = module.exports = trigger;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 解决 IE9 在表单元素中删除字符时不触发事件的问题
*/
// var ie = require('./ie');
// var on = require('./on');
// var trigger = require('./trigger');
// #[begin] allua
// /* istanbul ignore if */
// if (ie === 9) {
// on(document, 'selectionchange', function () {
// var el = document.activeElement;
// if (el.tagName === 'TEXTAREA' || el.tagName === 'INPUT') {
// trigger(el, 'input');
// }
// });
// }
// #[end]
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 自闭合标签表
*/
// var splitStr2Obj = require('../util/split-str-2-obj');
/**
* 自闭合标签列表
*
* @type {Object}
*/
var autoCloseTags = splitStr2Obj('area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr');
// exports = module.exports = autoCloseTags;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file data types
*/
// var bind = require('./bind');
// var empty = require('./empty');
// var extend = require('./extend');
// #[begin] error
// var ANONYMOUS_CLASS_NAME = '<<anonymous>>';
//
// /**
// * 获取精确的类型
// *
// * @NOTE 如果 obj 是一个 DOMElement,我们会返回 `element`;
// *
// * @param {*} obj 目标
// * @return {string}
// */
// function getDataType(obj) {
// // 不支持element了。data应该是纯数据
// // if (obj && obj.nodeType === 1) {
// // return 'element';
// // }
//
// return Object.prototype.toString
// .call(obj)
// .slice(8, -1)
// .toLowerCase();
// }
// #[end]
/**
* 创建链式的数据类型校验器
*
* @param {Function} validate 真正的校验器
* @return {Function}
*/
function createChainableChecker(validate) {
/* istanbul ignore next */
var chainedChecker = function () {};
chainedChecker.isRequired = empty;
// 只在 error 功能启用时才有实际上的 dataTypes 检测
// #[begin] error
// validate = validate || empty;
// var checkType = function (isRequired, data, dataName, componentName, fullDataName) {
//
// var dataValue = data[dataName];
// var dataType = getDataType(dataValue);
//
// /* istanbul ignore next */
// componentName = componentName || ANONYMOUS_CLASS_NAME;
//
// // 如果是 null 或 undefined,那么要提前返回啦
// if (dataValue == null) {
// // 是 required 就报错
// if (isRequired) {
// throw new Error('[SAN ERROR] '
// + 'The `' + dataName + '` '
// + 'is marked as required in `' + componentName + '`, '
// + 'but its value is ' + dataType
// );
// }
// // 不是 required,那就是 ok 的
// return;
// }
//
// validate(data, dataName, componentName, fullDataName);
//
// };
//
// chainedChecker = bind(checkType, null, false);
// chainedChecker.isRequired = bind(checkType, null, true);
// #[end]
return chainedChecker;
}
// #[begin] error
// /**
// * 生成主要类型数据校验器
// *
// * @param {string} type 主类型
// * @return {Function}
// */
// function createPrimaryTypeChecker(type) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName) {
//
// var dataValue = data[dataName];
// var dataType = getDataType(dataValue);
//
// if (dataType !== type) {
// throw new Error('[SAN ERROR] '
// + 'Invalid ' + componentName + ' data `' + fullDataName + '` of type'
// + '(' + dataType + ' supplied to ' + componentName + ', '
// + 'expected ' + type + ')'
// );
// }
//
// });
//
// }
//
//
//
// /**
// * 生成 arrayOf 校验器
// *
// * @param {Function} arrayItemChecker 数组中每项数据的校验器
// * @return {Function}
// */
// function createArrayOfChecker(arrayItemChecker) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName) {
//
// if (typeof arrayItemChecker !== 'function') {
// throw new Error('[SAN ERROR] '
// + 'Data `' + dataName + '` of `' + componentName + '` has invalid '
// + 'DataType notation inside `arrayOf`, expected `function`'
// );
// }
//
// var dataValue = data[dataName];
// var dataType = getDataType(dataValue);
//
// if (dataType !== 'array') {
// throw new Error('[SAN ERROR] '
// + 'Invalid ' + componentName + ' data `' + fullDataName + '` of type'
// + '(' + dataType + ' supplied to ' + componentName + ', '
// + 'expected array)'
// );
// }
//
// for (var i = 0, len = dataValue.length; i < len; i++) {
// arrayItemChecker(dataValue, i, componentName, fullDataName + '[' + i + ']');
// }
//
// });
//
// }
//
// /**
// * 生成 instanceOf 检测器
// *
// * @param {Function|Class} expectedClass 期待的类
// * @return {Function}
// */
// function createInstanceOfChecker(expectedClass) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName) {
//
// var dataValue = data[dataName];
//
// if (dataValue instanceof expectedClass) {
// return;
// }
//
// var dataValueClassName = dataValue.constructor && dataValue.constructor.name
// ? dataValue.constructor.name
// : /* istanbul ignore next */ ANONYMOUS_CLASS_NAME;
//
// /* istanbul ignore next */
// var expectedClassName = expectedClass.name || ANONYMOUS_CLASS_NAME;
//
// throw new Error('[SAN ERROR] '
// + 'Invalid ' + componentName + ' data `' + fullDataName + '` of type'
// + '(' + dataValueClassName + ' supplied to ' + componentName + ', '
// + 'expected instance of ' + expectedClassName + ')'
// );
//
//
// });
//
// }
//
// /**
// * 生成 shape 校验器
// *
// * @param {Object} shapeTypes shape 校验规则
// * @return {Function}
// */
// function createShapeChecker(shapeTypes) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName) {
//
// if (getDataType(shapeTypes) !== 'object') {
// throw new Error('[SAN ERROR] '
// + 'Data `' + fullDataName + '` of `' + componentName + '` has invalid '
// + 'DataType notation inside `shape`, expected `object`'
// );
// }
//
// var dataValue = data[dataName];
// var dataType = getDataType(dataValue);
//
// if (dataType !== 'object') {
// throw new Error('[SAN ERROR] '
// + 'Invalid ' + componentName + ' data `' + fullDataName + '` of type'
// + '(' + dataType + ' supplied to ' + componentName + ', '
// + 'expected object)'
// );
// }
//
// for (var shapeKeyName in shapeTypes) {
// /* istanbul ignore else */
// if (shapeTypes.hasOwnProperty(shapeKeyName)) {
// var checker = shapeTypes[shapeKeyName];
// if (typeof checker === 'function') {
// checker(dataValue, shapeKeyName, componentName, fullDataName + '.' + shapeKeyName);
// }
// }
// }
//
// });
//
// }
//
// /**
// * 生成 oneOf 校验器
// *
// * @param {Array} expectedEnumValues 期待的枚举值
// * @return {Function}
// */
// function createOneOfChecker(expectedEnumValues) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName) {
//
// if (getDataType(expectedEnumValues) !== 'array') {
// throw new Error('[SAN ERROR] '
// + 'Data `' + fullDataName + '` of `' + componentName + '` has invalid '
// + 'DataType notation inside `oneOf`, array is expected.'
// );
// }
//
// var dataValue = data[dataName];
//
// for (var i = 0, len = expectedEnumValues.length; i < len; i++) {
// if (dataValue === expectedEnumValues[i]) {
// return;
// }
// }
//
// throw new Error('[SAN ERROR] '
// + 'Invalid ' + componentName + ' data `' + fullDataName + '` of value'
// + '(`' + dataValue + '` supplied to ' + componentName + ', '
// + 'expected one of ' + expectedEnumValues.join(',') + ')'
// );
//
// });
//
// }
//
// /**
// * 生成 oneOfType 校验器
// *
// * @param {Array<Function>} expectedEnumOfTypeValues 期待的枚举类型
// * @return {Function}
// */
// function createOneOfTypeChecker(expectedEnumOfTypeValues) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName) {
//
// if (getDataType(expectedEnumOfTypeValues) !== 'array') {
// throw new Error('[SAN ERROR] '
// + 'Data `' + dataName + '` of `' + componentName + '` has invalid '
// + 'DataType notation inside `oneOf`, array is expected.'
// );
// }
//
// var dataValue = data[dataName];
//
// for (var i = 0, len = expectedEnumOfTypeValues.length; i < len; i++) {
//
// var checker = expectedEnumOfTypeValues[i];
//
// if (typeof checker !== 'function') {
// continue;
// }
//
// try {
// checker(data, dataName, componentName, fullDataName);
// // 如果 checker 完成校验没报错,那就返回了
// return;
// }
// catch (e) {
// // 如果有错误,那么应该把错误吞掉
// }
//
// }
//
// // 所有的可接受 type 都失败了,才丢一个异常
// throw new Error('[SAN ERROR] '
// + 'Invalid ' + componentName + ' data `' + dataName + '` of value'
// + '(`' + dataValue + '` supplied to ' + componentName + ')'
// );
//
// });
//
// }
//
// /**
// * 生成 objectOf 校验器
// *
// * @param {Function} typeChecker 对象属性值校验器
// * @return {Function}
// */
// function createObjectOfChecker(typeChecker) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName) {
//
// if (typeof typeChecker !== 'function') {
// throw new Error('[SAN ERROR] '
// + 'Data `' + dataName + '` of `' + componentName + '` has invalid '
// + 'DataType notation inside `objectOf`, expected function'
// );
// }
//
// var dataValue = data[dataName];
// var dataType = getDataType(dataValue);
//
// if (dataType !== 'object') {
// throw new Error('[SAN ERROR] '
// + 'Invalid ' + componentName + ' data `' + dataName + '` of type'
// + '(' + dataType + ' supplied to ' + componentName + ', '
// + 'expected object)'
// );
// }
//
// for (var dataKeyName in dataValue) {
// /* istanbul ignore else */
// if (dataValue.hasOwnProperty(dataKeyName)) {
// typeChecker(
// dataValue,
// dataKeyName,
// componentName,
// fullDataName + '.' + dataKeyName
// );
// }
// }
//
//
// });
//
// }
//
// /**
// * 生成 exact 校验器
// *
// * @param {Object} shapeTypes object 形态定义
// * @return {Function}
// */
// function createExactChecker(shapeTypes) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName, secret) {
//
// if (getDataType(shapeTypes) !== 'object') {
// throw new Error('[SAN ERROR] '
// + 'Data `' + dataName + '` of `' + componentName + '` has invalid '
// + 'DataType notation inside `exact`'
// );
// }
//
// var dataValue = data[dataName];
// var dataValueType = getDataType(dataValue);
//
// if (dataValueType !== 'object') {
// throw new Error('[SAN ERROR] '
// + 'Invalid data `' + fullDataName + '` of type `' + dataValueType + '`'
// + '(supplied to ' + componentName + ', expected `object`)'
// );
// }
//
// var allKeys = {};
//
// // 先合入 shapeTypes
// extend(allKeys, shapeTypes);
// // 再合入 dataValue
// extend(allKeys, dataValue);
// // 保证 allKeys 的类型正确
//
// for (var key in allKeys) {
// /* istanbul ignore else */
// if (allKeys.hasOwnProperty(key)) {
// var checker = shapeTypes[key];
//
// // dataValue 中有一个多余的数据项
// if (!checker) {
// throw new Error('[SAN ERROR] '
// + 'Invalid data `' + fullDataName + '` key `' + key + '` '
// + 'supplied to `' + componentName + '`. '
// + '(`' + key + '` is not defined in `DataTypes.exact`)'
// );
// }
//
// if (!(key in dataValue)) {
// throw new Error('[SAN ERROR] '
// + 'Invalid data `' + fullDataName + '` key `' + key + '` '
// + 'supplied to `' + componentName + '`. '
// + '(`' + key + '` is marked `required` in `DataTypes.exact`)'
// );
// }
//
// checker(
// dataValue,
// key,
// componentName,
// fullDataName + '.' + key,
// secret
// );
//
// }
// }
//
// });
//
// }
// #[end]
/* eslint-disable fecs-valid-var-jsdoc */
var DataTypes = {
array: createChainableChecker(),
object: createChainableChecker(),
func: createChainableChecker(),
string: createChainableChecker(),
number: createChainableChecker(),
bool: createChainableChecker(),
symbol: createChainableChecker(),
any: createChainableChecker,
arrayOf: createChainableChecker,
instanceOf: createChainableChecker,
shape: createChainableChecker,
oneOf: createChainableChecker,
oneOfType: createChainableChecker,
objectOf: createChainableChecker,
exact: createChainableChecker
};
// #[begin] error
// DataTypes = {
//
// any: createChainableChecker(),
//
// // 类型检测
// array: createPrimaryTypeChecker('array'),
// object: createPrimaryTypeChecker('object'),
// func: createPrimaryTypeChecker('function'),
// string: createPrimaryTypeChecker('string'),
// number: createPrimaryTypeChecker('number'),
// bool: createPrimaryTypeChecker('boolean'),
// symbol: createPrimaryTypeChecker('symbol'),
//
// // 复合类型检测
// arrayOf: createArrayOfChecker,
// instanceOf: createInstanceOfChecker,
// shape: createShapeChecker,
// oneOf: createOneOfChecker,
// oneOfType: createOneOfTypeChecker,
// objectOf: createObjectOfChecker,
// exact: createExactChecker
//
// };
// /* eslint-enable fecs-valid-var-jsdoc */
// #[end]
// module.exports = DataTypes;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 创建数据检测函数
*/
// #[begin] error
//
// /**
// * 创建数据检测函数
// *
// * @param {Object} dataTypes 数据格式
// * @param {string} componentName 组件名
// * @return {Function}
// */
// function createDataTypesChecker(dataTypes, componentName) {
//
// /**
// * 校验 data 是否满足 data types 的格式
// *
// * @param {*} data 数据
// */
// return function (data) {
//
// for (var dataTypeName in dataTypes) {
// /* istanbul ignore else */
// if (dataTypes.hasOwnProperty(dataTypeName)) {
//
// var dataTypeChecker = dataTypes[dataTypeName];
//
// if (typeof dataTypeChecker !== 'function') {
// throw new Error('[SAN ERROR] '
// + componentName + ':' + dataTypeName + ' is invalid; '
// + 'it must be a function, usually from san.DataTypes'
// );
// }
//
// dataTypeChecker(
// data,
// dataTypeName,
// componentName,
// dataTypeName
// );
//
//
// }
// }
//
// };
//
// }
//
// #[end]
// module.exports = createDataTypesChecker;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 字符串源码读取类
*/
/**
* 字符串源码读取类,用于模板字符串解析过程
*
* @class
* @param {string} source 要读取的字符串
*/
function Walker(source) {
this.source = source;
this.len = this.source.length;
this.index = 0;
}
/**
* 获取当前字符码
*
* @return {number}
*/
Walker.prototype.currentCode = function () {
return this.source.charCodeAt(this.index);
};
/**
* 截取字符串片段
*
* @param {number} start 起始位置
* @param {number} end 结束位置
* @return {string}
*/
Walker.prototype.cut = function (start, end) {
return this.source.slice(start, end);
};
/**
* 向前读取字符
*
* @param {number} distance 读取字符数
*/
Walker.prototype.go = function (distance) {
this.index += distance;
};
/**
* 读取下一个字符,返回下一个字符的 code
*
* @return {number}
*/
Walker.prototype.nextCode = function () {
this.go(1);
return this.currentCode();
};
/**
* 获取相应位置字符的 code
*
* @param {number} index 字符位置
* @return {number}
*/
Walker.prototype.charCode = function (index) {
return this.source.charCodeAt(index);
};
/**
* 向前读取字符,直到遇到指定字符再停止
* 未指定字符时,当遇到第一个非空格、制表符的字符停止
*
* @param {number=} charCode 指定字符的code
* @return {boolean} 当指定字符时,返回是否碰到指定的字符
*/
Walker.prototype.goUntil = function (charCode) {
var code;
while (this.index < this.len && (code = this.currentCode())) {
switch (code) {
case 32: // 空格 space
case 9: // 制表符 tab
case 13: // \r
case 10: // \n
this.index++;
break;
default:
if (code === charCode) {
this.index++;
return 1;
}
return;
}
}
};
/**
* 向前读取符合规则的字符片段,并返回规则匹配结果
*
* @param {RegExp} reg 字符片段的正则表达式
* @param {boolean} isMatchStart 是否必须匹配当前位置
* @return {Array?}
*/
Walker.prototype.match = function (reg, isMatchStart) {
reg.lastIndex = this.index;
var match = reg.exec(this.source);
if (match && (!isMatchStart || this.index === match.index)) {
this.index = reg.lastIndex;
return match;
}
};
// exports = module.exports = Walker;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 把 kebab case 字符串转换成 camel case
*/
/**
* 把 kebab case 字符串转换成 camel case
*
* @param {string} source 源字符串
* @return {string}
*/
function kebab2camel(source) {
return source.replace(/-+(.)/ig, function (match, alpha) {
return alpha.toUpperCase();
});
}
// exports = module.exports = kebab2camel;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file bool属性表
*/
// var splitStr2Obj = require('../util/split-str-2-obj');
/**
* bool属性表
*
* @type {Object}
*/
var boolAttrs = splitStr2Obj(
'allowpaymentrequest,async,autofocus,autoplay,'
+ 'checked,controls,default,defer,disabled,formnovalidate,'
+ 'hidden,ismap,itemscope,loop,multiple,muted,nomodule,novalidate,'
+ 'open,readonly,required,reversed,selected,typemustmatch'
);
// exports = module.exports = boolAttrs;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 表达式类型
*/
/**
* 表达式类型
*
* @const
* @type {Object}
*/
var ExprType = {
STRING: 1,
NUMBER: 2,
BOOL: 3,
ACCESSOR: 4,
INTERP: 5,
CALL: 6,
TEXT: 7,
BINARY: 8,
UNARY: 9,
TERTIARY: 10,
OBJECT: 11,
ARRAY: 12,
NULL: 13
};
// exports = module.exports = ExprType;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 创建访问表达式对象
*/
// var ExprType = require('./expr-type');
/**
* 创建访问表达式对象
*
* @param {Array} paths 访问路径
* @return {Object}
*/
function createAccessor(paths) {
return {
type: 4,
paths: paths
};
}
// exports = module.exports = createAccessor;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 读取字符串
*/
// var ExprType = require('./expr-type');
/**
* 读取字符串
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readString(walker) {
var startCode = walker.currentCode();
var startIndex = walker.index;
var charCode;
walkLoop: while ((charCode = walker.nextCode())) {
switch (charCode) {
case 92: // \
walker.go(1);
break;
case startCode:
walker.go(1);
break walkLoop;
}
}
var literal = walker.cut(startIndex, walker.index);
return {
type: 1,
// 处理字符转义
value: (new Function('return ' + literal))()
};
}
// exports = module.exports = readString;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 读取一元表达式
*/
// var ExprType = require('./expr-type');
// var readString = require('./read-string');
// var readNumber = require('./read-number');
// var readCall = require('./read-call');
// var readParenthesizedExpr = require('./read-parenthesized-expr');
// var readTertiaryExpr = require('./read-tertiary-expr');
function postUnaryExpr(expr, operator) {
switch (operator) {
case 33:
var value;
switch (expr.type) {
case 2:
case 1:
case 3:
value = !expr.value;
break;
case 12:
case 11:
value = false;
break;
case 13:
value = true;
break;
}
if (value != null) {
return {
type: 3,
value: value
};
}
break;
case 43:
switch (expr.type) {
case 2:
case 1:
case 3:
return {
type: 2,
value: +expr.value
};
}
break;
case 45:
switch (expr.type) {
case 2:
case 1:
case 3:
return {
type: 2,
value: -expr.value
};
}
break;
}
return {
type: 9,
expr: expr,
operator: operator
};
}
/**
* 读取一元表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readUnaryExpr(walker) {
walker.goUntil();
var currentCode = walker.currentCode();
switch (currentCode) {
case 33: // !
case 43: // +
case 45: // -
walker.go(1);
return postUnaryExpr(readUnaryExpr(walker), currentCode);
case 34: // "
case 39: // '
return readString(walker);
case 48: // number
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
return readNumber(walker);
case 40: // (
return readParenthesizedExpr(walker);
// array literal
case 91: // [
walker.go(1);
var arrItems = [];
while (!walker.goUntil(93)) { // ]
var item = {};
arrItems.push(item);
if (walker.currentCode() === 46 && walker.match(/\.\.\.\s*/g)) {
item.spread = true;
}
item.expr = readTertiaryExpr(walker);
walker.goUntil(44); // ,
}
return {
type: 12,
items: arrItems
};
// object literal
case 123: // {
walker.go(1);
var objItems = [];
while (!walker.goUntil(125)) { // }
var item = {};
objItems.push(item);
if (walker.currentCode() === 46 && walker.match(/\.\.\.\s*/g)) {
item.spread = true;
item.expr = readTertiaryExpr(walker);
}
else {
// #[begin] error
// var walkerIndexBeforeName = walker.index;
// #[end]
item.name = readUnaryExpr(walker);
// #[begin] error
// if (item.name.type > 4) {
// throw new Error(
// '[SAN FATAL] unexpect object name: '
// + walker.cut(walkerIndexBeforeName, walker.index)
// );
// }
// #[end]
if (walker.goUntil(58)) { // :
item.expr = readTertiaryExpr(walker);
}
else {
item.expr = item.name;
}
if (item.name.type === 4) {
item.name = item.name.paths[0];
}
}
walker.goUntil(44); // ,
}
return {
type: 11,
items: objItems
};
}
return readCall(walker);
}
// exports = module.exports = readUnaryExpr;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 读取数字
*/
// var ExprType = require('./expr-type');
// var readUnaryExpr = require('./read-unary-expr');
/**
* 读取数字
*
* @inner
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readNumber(walker) {
var match = walker.match(/\s*([0-9]+(\.[0-9]+)?)/g, 1);
if (match) {
return {
type: 2,
value: +match[1]
};
}
}
// exports = module.exports = readNumber;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 读取ident
*/
/**
* 读取ident
* 这里的 ident 指标识符(identifier),也就是通常意义上的变量名
* 这里默认的变量名规则为:由美元符号($)、数字、字母或者下划线(_)构成的字符串
*
* @inner
* @param {Walker} walker 源码读取对象
* @return {string}
*/
function readIdent(walker) {
var match = walker.match(/\s*([\$0-9a-z_]+)/ig, 1);
// #[begin] error
// if (!match) {
// throw new Error('[SAN FATAL] expect an ident: ' + walker.cut(walker.index));
// }
// #[end]
return match[1];
}
// exports = module.exports = readIdent;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 读取三元表达式
*/
// var ExprType = require('./expr-type');
// var readLogicalORExpr = require('./read-logical-or-expr');
/**
* 读取三元表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readTertiaryExpr(walker) {
var conditional = readLogicalORExpr(walker);
walker.goUntil();
if (walker.currentCode() === 63) { // ?
walker.go(1);
var yesExpr = readTertiaryExpr(walker);
walker.goUntil();
if (walker.currentCode() === 58) { // :
walker.go(1);
return {
type: 10,
segs: [
conditional,
yesExpr,
readTertiaryExpr(walker)
]
};
}
}
return conditional;
}
// exports = module.exports = readTertiaryExpr;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 读取访问表达式
*/
// var ExprType = require('./expr-type');
// var createAccessor = require('./create-accessor');
// var readIdent = require('./read-ident');
// var readTertiaryExpr = require('./read-tertiary-expr');
/**
* 读取访问表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readAccessor(walker) {
var firstSeg = readIdent(walker);
switch (firstSeg) {
case 'true':
case 'false':
return {
type: 3,
value: firstSeg === 'true'
};
case 'null':
return {
type: 13
};
}
var result = createAccessor([
{
type: 1,
value: firstSeg
}
]);
/* eslint-disable no-constant-condition */
accessorLoop: while (1) {
/* eslint-enable no-constant-condition */
switch (walker.currentCode()) {
case 46: // .
walker.go(1);
// ident as string
result.paths.push({
type: 1,
value: readIdent(walker)
});
break;
case 91: // [
walker.go(1);
result.paths.push(readTertiaryExpr(walker));
walker.goUntil(93); // ]
break;
default:
break accessorLoop;
}
}
return result;
}
// exports = module.exports = readAccessor;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 读取调用
*/
// var ExprType = require('./expr-type');
// var readAccessor = require('./read-accessor');
// var readTertiaryExpr = require('./read-tertiary-expr');
/**
* 读取调用
*
* @param {Walker} walker 源码读取对象
* @param {Array=} defaultArgs 默认参数
* @return {Object}
*/
function readCall(walker, defaultArgs) {
walker.goUntil();
var result = readAccessor(walker);
var args;
if (walker.goUntil(40)) { // (
args = [];
while (!walker.goUntil(41)) { // )
args.push(readTertiaryExpr(walker));
walker.goUntil(44); // ,
}
}
else if (defaultArgs) {
args = defaultArgs;
}
if (args) {
result = {
type: 6,
name: result,
args: args
};
}
return result;
}
// exports = module.exports = readCall;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 读取括号表达式
*/
// var readTertiaryExpr = require('./read-tertiary-expr');
/**
* 读取括号表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readParenthesizedExpr(walker) {
walker.go(1);
var expr = readTertiaryExpr(walker);
walker.goUntil(41); // )
expr.parenthesized = true;
return expr;
}
// exports = module.exports = readParenthesizedExpr;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 读取乘法表达式
*/
// var ExprType = require('./expr-type');
// var readUnaryExpr = require('./read-unary-expr');
/**
* 读取乘法表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readMultiplicativeExpr(walker) {
var expr = readUnaryExpr(walker);
while (1) {
walker.goUntil();
var code = walker.currentCode();
switch (code) {
case 37: // %
case 42: // *
case 47: // /
walker.go(1);
expr = {
type: 8,
operator: code,
segs: [expr, readUnaryExpr(walker)]
};
continue;
}
break;
}
return expr;
}
// exports = module.exports = readMultiplicativeExpr;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 读取加法表达式
*/
// var ExprType = require('./expr-type');
// var readMultiplicativeExpr = require('./read-multiplicative-expr');
/**
* 读取加法表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readAdditiveExpr(walker) {
var expr = readMultiplicativeExpr(walker);
while (1) {
walker.goUntil();
var code = walker.currentCode();
switch (code) {
case 43: // +
case 45: // -
walker.go(1);
expr = {
type: 8,
operator: code,
segs: [expr, readMultiplicativeExpr(walker)]
};
continue;
}
break;
}
return expr;
}
// exports = module.exports = readAdditiveExpr;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 读取关系判断表达式
*/
// var ExprType = require('./expr-type');
// var readAdditiveExpr = require('./read-additive-expr');
/**
* 读取关系判断表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readRelationalExpr(walker) {
var expr = readAdditiveExpr(walker);
walker.goUntil();
var code = walker.currentCode();
switch (code) {
case 60: // <
case 62: // >
if (walker.nextCode() === 61) {
code += 61;
walker.go(1);
}
return {
type: 8,
operator: code,
segs: [expr, readAdditiveExpr(walker)]
};
}
return expr;
}
// exports = module.exports = readRelationalExpr;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 读取相等比对表达式
*/
// var ExprType = require('./expr-type');
// var readRelationalExpr = require('./read-relational-expr');
/**
* 读取相等比对表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readEqualityExpr(walker) {
var expr = readRelationalExpr(walker);
walker.goUntil();
var code = walker.currentCode();
switch (code) {
case 61: // =
case 33: // !
if (walker.nextCode() === 61) {
code += 61;
if (walker.nextCode() === 61) {
code += 61;
walker.go(1);
}
return {
type: 8,
operator: code,
segs: [expr, readRelationalExpr(walker)]
};
}
walker.go(-1);
}
return expr;
}
// exports = module.exports = readEqualityExpr;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 读取逻辑与表达式
*/
// var ExprType = require('./expr-type');
// var readEqualityExpr = require('./read-equality-expr');
/**
* 读取逻辑与表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readLogicalANDExpr(walker) {
var expr = readEqualityExpr(walker);
walker.goUntil();
if (walker.currentCode() === 38) { // &
if (walker.nextCode() === 38) {
walker.go(1);
return {
type: 8,
operator: 76,
segs: [expr, readLogicalANDExpr(walker)]
};
}
walker.go(-1);
}
return expr;
}
// exports = module.exports = readLogicalANDExpr;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 读取逻辑或表达式
*/
// var ExprType = require('./expr-type');
// var readLogicalANDExpr = require('./read-logical-and-expr');
/**
* 读取逻辑或表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readLogicalORExpr(walker) {
var expr = readLogicalANDExpr(walker);
walker.goUntil();
if (walker.currentCode() === 124) { // |
if (walker.nextCode() === 124) {
walker.go(1);
return {
type: 8,
operator: 248,
segs: [expr, readLogicalORExpr(walker)]
};
}
walker.go(-1);
}
return expr;
}
// exports = module.exports = readLogicalORExpr;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 解析表达式
*/
// var Walker = require('./walker');
// var readTertiaryExpr = require('./read-tertiary-expr');
/**
* 解析表达式
*
* @param {string} source 源码
* @return {Object}
*/
function parseExpr(source) {
if (!source) {
return;
}
if (typeof source === 'object' && source.type) {
return source;
}
var expr = readTertiaryExpr(new Walker(source));
expr.raw = source;
return expr;
}
// exports = module.exports = parseExpr;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 解析调用
*/
// var Walker = require('./walker');
// var ExprType = require('./expr-type');
// var readCall = require('./read-call');
/**
* 解析调用
*
* @param {string} source 源码
* @param {Array=} defaultArgs 默认参数
* @return {Object}
*/
function parseCall(source, defaultArgs) {
var expr = readCall(new Walker(source), defaultArgs);
if (expr.type !== 6) {
expr = {
type: 6,
name: expr,
args: defaultArgs || []
};
}
expr.raw = source;
return expr;
}
// exports = module.exports = parseCall;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 解析插值替换
*/
// var Walker = require('./walker');
// var readTertiaryExpr = require('./read-tertiary-expr');
// var ExprType = require('./expr-type');
// var readCall = require('./read-call');
/**
* 解析插值替换
*
* @param {string} source 源码
* @return {Object}
*/
function parseInterp(source) {
var walker = new Walker(source);
var interp = {
type: 5,
expr: readTertiaryExpr(walker),
filters: [],
raw: source
};
while (walker.goUntil(124)) { // |
var callExpr = readCall(walker, []);
switch (callExpr.name.paths[0].value) {
case 'html':
break;
case 'raw':
interp.original = 1;
break;
default:
interp.filters.push(callExpr);
}
}
return interp;
}
// exports = module.exports = parseInterp;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 解码 HTML 字符实体
*/
var ENTITY_DECODE_MAP = {
lt: '<',
gt: '>',
nbsp: ' ',
quot: '\"',
emsp: '\u2003',
ensp: '\u2002',
thinsp: '\u2009',
copy: '\xa9',
reg: '\xae',
zwnj: '\u200c',
zwj: '\u200d',
amp: '&'
};
/**
* 解码 HTML 字符实体
*
* @param {string} source 要解码的字符串
* @return {string}
*/
function decodeHTMLEntity(source) {
return source
.replace(/&#([0-9]+);/g, function (match, code) {
return String.fromCharCode(+code);
})
.replace(/&#x([0-9a-f]+);/ig, function (match, code) {
return String.fromCharCode(parseInt(code, 16));
})
.replace(/&([a-z]+);/ig, function (match, code) {
return ENTITY_DECODE_MAP[code] || match;
});
}
// exports = module.exports = decodeHTMLEntity;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 解析文本
*/
// var Walker = require('./walker');
// var ExprType = require('./expr-type');
// var parseInterp = require('./parse-interp');
// var decodeHTMLEntity = require('../util/decode-html-entity');
/**
* 对字符串进行可用于new RegExp的字面化
*
* @inner
* @param {string} source 需要字面化的字符串
* @return {string} 字符串字面化结果
*/
function regexpLiteral(source) {
return source.replace(/[\^\[\]\$\(\)\{\}\?\*\.\+\\]/g, function (c) {
return '\\' + c;
});
}
var delimRegCache = {};
/**
* 解析文本
*
* @param {string} source 源码
* @param {Array?} delimiters 分隔符。默认为 ['{{', '}}']
* @return {Object}
*/
function parseText(source, delimiters) {
delimiters = delimiters || ['{{', '}}'];
var regCacheKey = delimiters[0] + '>..<' + delimiters[1];
var exprStartReg = delimRegCache[regCacheKey];
if (!exprStartReg) {
exprStartReg = new RegExp(
regexpLiteral(delimiters[0])
+ '\\s*([\\s\\S]+?)\\s*'
+ regexpLiteral(delimiters[1]),
'g'
);
delimRegCache[regCacheKey] = exprStartReg;
}
var exprMatch;
var walker = new Walker(source);
var beforeIndex = 0;
var expr = {
type: 7,
segs: []
};
function pushStringToSeg(text) {
text && expr.segs.push({
type: 1,
literal: text,
value: decodeHTMLEntity(text)
});
}
var delimEndLen = delimiters[1].length;
while ((exprMatch = walker.match(exprStartReg)) != null) {
var interpSource = exprMatch[1];
var interpLen = exprMatch[0].length;
if (walker.cut(walker.index + 1 - delimEndLen, walker.index + 1) === delimiters[1]) {
interpSource += walker.cut(walker.index, walker.index + 1);
walker.go(1);
interpLen++;
}
pushStringToSeg(walker.cut(
beforeIndex,
walker.index - interpLen
));
var interp = parseInterp(interpSource);
expr.original = expr.original || interp.original;
expr.segs.push(interp);
beforeIndex = walker.index;
}
pushStringToSeg(walker.cut(beforeIndex));
if (expr.segs.length === 1 && expr.segs[0].type === 1) {
expr.value = expr.segs[0].value;
}
return expr;
}
// exports = module.exports = parseText;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 解析指令
*/
// var Walker = require('./walker');
// var parseExpr = require('./parse-expr');
// var parseCall = require('./parse-call');
// var parseText = require('./parse-text');
// var readAccessor = require('./read-accessor');
// var readUnaryExpr = require('./read-unary-expr');
/**
* 指令解析器
*
* @inner
* @type {Object}
*/
var directiveParsers = {
'for': function (value) {
var walker = new Walker(value);
var match = walker.match(/^\s*([$0-9a-z_]+)(\s*,\s*([$0-9a-z_]+))?\s+in\s+/ig, 1);
if (match) {
var directive = {
item: match[1],
value: readUnaryExpr(walker)
};
if (match[3]) {
directive.index = match[3];
}
if (walker.match(/\s*trackby\s+/ig, 1)) {
var start = walker.index;
directive.trackBy = readAccessor(walker);
directive.trackBy.raw = walker.cut(start, walker.index);
}
return directive;
}
// #[begin] error
// throw new Error('[SAN FATAL] for syntax error: ' + value);
// #[end]
},
'ref': function (value, options) {
return {
value: parseText(value, options.delimiters)
};
},
'if': function (value) {
return {
value: parseExpr(value.replace(/(^\{\{|\}\}$)/g, ''))
};
},
'elif': function (value) {
return {
value: parseExpr(value.replace(/(^\{\{|\}\}$)/g, ''))
};
},
'else': function () {
return {
value: {}
};
},
'bind': function (value) {
return {
value: parseExpr(value.replace(/(^\{\{|\}\}$)/g, ''))
};
},
'html': function (value) {
return {
value: parseExpr(value.replace(/(^\{\{|\}\}$)/g, ''))
};
},
'transition': function (value) {
return {
value: parseCall(value)
};
}
};
/**
* 解析指令
*
* @param {ANode} aNode 抽象节点
* @param {string} name 指令名称
* @param {string} value 指令值
* @param {Object} options 解析参数
* @param {Array?} options.delimiters 插值分隔符列表
*/
function parseDirective(aNode, name, value, options) {
if (name === 'else-if') {
name = 'elif';
}
var parser = directiveParsers[name];
if (parser) {
(aNode.directives[name] = parser(value, options)).raw = value;
}
}
// exports = module.exports = parseDirective;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 解析抽象节点属性
*/
// var each = require('../util/each');
// var kebab2camel = require('../util/kebab2camel');
// var boolAttrs = require('../browser/bool-attrs');
// var ExprType = require('./expr-type');
// var createAccessor = require('./create-accessor');
// var parseExpr = require('./parse-expr');
// var parseCall = require('./parse-call');
// var parseText = require('./parse-text');
// var parseDirective = require('./parse-directive');
/**
* 解析抽象节点属性
*
* @param {ANode} aNode 抽象节点
* @param {string} name 属性名称
* @param {string} value 属性值
* @param {Object} options 解析参数
* @param {Array?} options.delimiters 插值分隔符列表
*/
function integrateAttr(aNode, name, value, options) {
var prefixIndex = name.indexOf('-');
var realName;
var prefix;
if (prefixIndex > 0) {
prefix = name.slice(0, prefixIndex);
realName = name.slice(prefixIndex + 1);
}
switch (prefix) {
case 'on':
var event = {
name: realName,
modifier: {}
};
aNode.events.push(event);
var colonIndex;
while ((colonIndex = value.indexOf(':')) > 0) {
var modifier = value.slice(0, colonIndex);
// eventHandler("dd:aa") 这种情况不能算modifier,需要辨识
if (!/^[a-z]+$/i.test(modifier)) {
break;
}
event.modifier[modifier] = true;
value = value.slice(colonIndex + 1);
}
event.expr = parseCall(value, [
createAccessor([
{type: 1, value: '$event'}
])
]);
break;
case 'san':
case 's':
parseDirective(aNode, realName, value, options);
break;
case 'prop':
integrateProp(aNode, realName, value, options);
break;
case 'var':
if (!aNode.vars) {
aNode.vars = [];
}
realName = kebab2camel(realName);
aNode.vars.push({
name: realName,
expr: parseExpr(value.replace(/(^\{\{|\}\}$)/g, ''))
});
break;
default:
integrateProp(aNode, name, value, options);
}
}
/**
* 解析抽象节点绑定属性
*
* @inner
* @param {ANode} aNode 抽象节点
* @param {string} name 属性名称
* @param {string} rawValue 属性值
* @param {Object} options 解析参数
* @param {Array?} options.delimiters 插值分隔符列表
*/
function integrateProp(aNode, name, rawValue, options) {
// parse two way binding, e.g. value="{=ident=}"
var value = rawValue || '';
var xMatch = value.match(/^\{=\s*(.*?)\s*=\}$/);
if (xMatch) {
aNode.props.push({
name: name,
expr: parseExpr(xMatch[1]),
x: 1,
raw: value
});
return;
}
var expr = parseText(value, options.delimiters);
// 这里不能把只有一个插值的属性抽取
// 因为插值里的值可能是html片段,容易被注入
// 组件的数据绑定在组件init时做抽取
switch (name) {
case 'class':
case 'style':
each(expr.segs, function (seg) {
if (seg.type === 5) {
seg.filters.push({
type: 6,
name: createAccessor([
{
type: 1,
value: '_' + name
}
]),
args: []
});
}
});
break;
}
if (expr.type === 7) {
switch (expr.segs.length) {
case 0:
if (boolAttrs[name]) {
expr = {
type: 3,
value: true
};
}
break;
case 1:
expr = expr.segs[0];
if (expr.type === 5 && expr.filters.length === 0) {
expr = expr.expr;
}
}
}
aNode.props.push({
name: name,
expr: expr,
raw: rawValue
});
}
// exports = module.exports = integrateAttr;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 解析模板
*/
// var Walker = require('./walker');
// var integrateAttr = require('./integrate-attr');
// var parseText = require('./parse-text');
// var svgTags = require('../browser/svg-tags');
// var autoCloseTags = require('../browser/auto-close-tags');
// #[begin] error
// function getXPath(stack, currentTagName) {
// var path = ['ROOT'];
// for (var i = 1, len = stack.length; i < len; i++) {
// path.push(stack[i].tagName);
// }
// if (currentTagName) {
// path.push(currentTagName);
// }
// return path.join('>');
// }
// #[end]
/* eslint-disable fecs-max-statements */
/**
* 解析 template
*
* @param {string} source template源码
* @param {Object?} options 解析参数
* @param {string?} options.trimWhitespace 空白文本的处理策略。none|blank|all
* @param {Array?} options.delimiters 插值分隔符列表
* @return {ANode}
*/
function parseTemplate(source, options) {
options = options || {};
options.trimWhitespace = options.trimWhitespace || 'none';
var rootNode = {
directives: {},
props: [],
events: [],
children: []
};
if (typeof source !== 'string') {
return rootNode;
}
source = source.replace(/<!--([\s\S]*?)-->/mg, '').replace(/(^\s+|\s+$)/g, '');
var walker = new Walker(source);
var tagReg = /<(\/)?([a-z][a-z0-9-]*)\s*/ig;
var attrReg = /([-:0-9a-z\[\]_]+)(\s*=\s*(['"])([^\3]*?)\3)?\s*/ig;
var tagMatch;
var currentNode = rootNode;
var stack = [rootNode];
var stackIndex = 0;
var beforeLastIndex = 0;
while ((tagMatch = walker.match(tagReg)) != null) {
var tagMatchStart = walker.index - tagMatch[0].length;
var tagEnd = tagMatch[1];
var tagName = tagMatch[2];
if (!svgTags[tagName]) {
tagName = tagName.toLowerCase();
}
// 62: >
// 47: /
// 处理 </xxxx >
if (tagEnd) {
if (walker.currentCode() === 62) {
// 满足关闭标签的条件时,关闭标签
// 向上查找到对应标签,找不到时忽略关闭
var closeIndex = stackIndex;
// #[begin] error
// // 如果正在闭合一个自闭合的标签,例如 </input>,报错
// if (autoCloseTags[tagName]) {
// throw new Error(''
// + '[SAN ERROR] ' + getXPath(stack, tagName) + ' is a `auto closed` tag, '
// + 'so it cannot be closed with </' + tagName + '>'
// );
// }
//
// // 如果关闭的 tag 和当前打开的不一致,报错
// if (
// stack[closeIndex].tagName !== tagName
// // 这里要把 table 自动添加 tbody 的情况给去掉
// && !(tagName === 'table' && stack[closeIndex].tagName === 'tbody')
// ) {
// throw new Error('[SAN ERROR] ' + getXPath(stack) + ' is closed with ' + tagName);
// }
// #[end]
pushTextNode(source.slice(beforeLastIndex, tagMatchStart));
while (closeIndex > 0 && stack[closeIndex].tagName !== tagName) {
closeIndex--;
}
if (closeIndex > 0) {
stackIndex = closeIndex - 1;
currentNode = stack[stackIndex];
}
walker.go(1);
}
// #[begin] error
// else {
// // 处理 </xxx 非正常闭合标签
//
// // 如果闭合标签时,匹配后的下一个字符是 <,即下一个标签的开始,那么当前闭合标签未闭合
// if (walker.currentCode() === 60) {
// throw new Error(''
// + '[SAN ERROR] ' + getXPath(stack)
// + '\'s close tag not closed'
// );
// }
//
// // 闭合标签有属性
// throw new Error(''
// + '[SAN ERROR] ' + getXPath(stack)
// + '\'s close tag has attributes'
// );
// }
// #[end]
}
else {
var aElement = {
directives: {},
props: [],
events: [],
children: [],
tagName: tagName
};
var tagClose = autoCloseTags[tagName];
// 解析 attributes
/* eslint-disable no-constant-condition */
while (1) {
/* eslint-enable no-constant-condition */
var nextCharCode = walker.currentCode();
// 标签结束时跳出 attributes 读取
// 标签可能直接结束或闭合结束
if (nextCharCode === 62) {
walker.go(1);
break;
}
// 遇到 /> 按闭合处理
if (nextCharCode === 47
&& walker.charCode(walker.index + 1) === 62
) {
walker.go(2);
tagClose = 1;
break;
}
// template 串结束了
// 这时候,说明这个读取周期的所有内容,都是text
if (!nextCharCode) {
pushTextNode(walker.cut(beforeLastIndex));
aElement = null;
break;
}
// #[begin] error
// // 在处理一个 open 标签时,如果遇到了 <, 即下一个标签的开始,则当前标签未能正常闭合,报错
// if (nextCharCode === 60) {
// throw new Error('[SAN ERROR] ' + getXPath(stack, tagName) + ' is not closed');
// }
// #[end]
// 读取 attribute
var attrMatch = walker.match(attrReg);
if (attrMatch) {
// #[begin] error
// // 如果属性有 =,但没取到 value,报错
// if (
// walker.charCode(attrMatch.index + attrMatch[1].length) === 61
// && !attrMatch[2]
// ) {
// throw new Error(''
// + '[SAN ERROR] ' + getXPath(stack, tagName) + ' attribute `'
// + attrMatch[1] + '` is not wrapped with ""'
// );
// }
// #[end]
integrateAttr(
aElement,
attrMatch[1],
attrMatch[3] ? attrMatch[4] : void(0),
options
);
}
}
if (aElement) {
pushTextNode(source.slice(beforeLastIndex, tagMatchStart));
// match if directive for else/elif directive
var elseDirective = aElement.directives['else'] // eslint-disable-line dot-notation
|| aElement.directives.elif;
if (elseDirective) {
var parentChildrenLen = currentNode.children.length;
var ifANode = null;
while (parentChildrenLen--) {
var parentChild = currentNode.children[parentChildrenLen];
if (parentChild.textExpr) {
currentNode.children.splice(parentChildrenLen, 1);
continue;
}
ifANode = parentChild;
break;
}
// #[begin] error
// if (!ifANode || !parentChild.directives['if']) { // eslint-disable-line dot-notation
// throw new Error('[SAN FATEL] else not match if.');
// }
// #[end]
if (ifANode) {
ifANode.elses = ifANode.elses || [];
ifANode.elses.push(aElement);
}
}
else {
if (aElement.tagName === 'tr' && currentNode.tagName === 'table') {
var tbodyNode = {
directives: {},
props: [],
events: [],
children: [],
tagName: 'tbody'
};
currentNode.children.push(tbodyNode);
currentNode = tbodyNode;
stack[++stackIndex] = tbodyNode;
}
currentNode.children.push(aElement);
}
if (!tagClose) {
currentNode = aElement;
stack[++stackIndex] = aElement;
}
}
}
beforeLastIndex = walker.index;
}
pushTextNode(walker.cut(beforeLastIndex));
return rootNode;
/**
* 在读取栈中添加文本节点
*
* @inner
* @param {string} text 文本内容
*/
function pushTextNode(text) {
switch (options.trimWhitespace) {
case 'blank':
if (/^\s+$/.test(text)) {
text = null;
}
break;
case 'all':
text = text.replace(/(^\s+|\s+$)/g, '');
break;
}
if (text) {
currentNode.children.push({
textExpr: parseText(text, options.delimiters)
});
}
}
}
/* eslint-enable fecs-max-statements */
// exports = module.exports = parseTemplate;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 默认filter
*/
/* eslint-disable fecs-camelcase */
function defaultStyleFilter(source) {
if (typeof source === 'object') {
var result = '';
for (var key in source) {
/* istanbul ignore else */
if (source.hasOwnProperty(key)) {
result += key + ':' + source[key] + ';';
}
}
return result;
}
return source;
}
/**
* 默认filter
*
* @const
* @type {Object}
*/
var DEFAULT_FILTERS = {
/**
* URL编码filter
*
* @param {string} source 源串
* @return {string} 替换结果串
*/
url: encodeURIComponent,
_class: function (source) {
if (source instanceof Array) {
return source.join(' ');
}
return source;
},
_style: defaultStyleFilter,
_xclass: function (outer, inner) {
if (outer instanceof Array) {
outer = outer.join(' ');
}
if (outer) {
if (inner) {
return inner + ' ' + outer;
}
return outer;
}
return inner;
},
_xstyle: function (outer, inner) {
outer = outer && defaultStyleFilter(outer);
if (outer) {
if (inner) {
return inner + ';' + outer;
}
return outer;
}
return inner;
}
};
/* eslint-enable fecs-camelcase */
// exports = module.exports = DEFAULT_FILTERS;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 表达式计算
*/
// var ExprType = require('../parser/expr-type');
// var extend = require('../util/extend');
// var DEFAULT_FILTERS = require('./default-filters');
// var evalArgs = require('./eval-args');
/**
* 计算表达式的值
*
* @param {Object} expr 表达式对象
* @param {Data} data 数据容器对象
* @param {Component=} owner 所属组件环境
* @return {*}
*/
function evalExpr(expr, data, owner) {
if (expr.value != null) {
return expr.value;
}
var value;
switch (expr.type) {
case 13:
return null;
case 9:
value = evalExpr(expr.expr, data, owner);
switch (expr.operator) {
case 33:
value = !value;
break;
case 43:
value = +value;
break;
case 45:
value = 0 - value;
break;
}
return value;
case 8:
value = evalExpr(expr.segs[0], data, owner);
var rightValue = evalExpr(expr.segs[1], data, owner);
/* eslint-disable eqeqeq */
switch (expr.operator) {
case 37:
value = value % rightValue;
break;
case 43:
value = value + rightValue;
break;
case 45:
value = value - rightValue;
break;
case 42:
value = value * rightValue;
break;
case 47:
value = value / rightValue;
break;
case 60:
value = value < rightValue;
break;
case 62:
value = value > rightValue;
break;
case 76:
value = value && rightValue;
break;
case 94:
value = value != rightValue;
break;
case 121:
value = value <= rightValue;
break;
case 122:
value = value == rightValue;
break;
case 123:
value = value >= rightValue;
break;
case 155:
value = value !== rightValue;
break;
case 183:
value = value === rightValue;
break;
case 248:
value = value || rightValue;
break;
}
/* eslint-enable eqeqeq */
return value;
case 10:
return evalExpr(
expr.segs[evalExpr(expr.segs[0], data, owner) ? 1 : 2],
data,
owner
);
case 12:
value = [];
for (var i = 0, l = expr.items.length; i < l; i++) {
var item = expr.items[i];
var itemValue = evalExpr(item.expr, data, owner);
if (item.spread) {
itemValue && (value = value.concat(itemValue));
}
else {
value.push(itemValue);
}
}
return value;
case 11:
value = {};
for (var i = 0, l = expr.items.length; i < l; i++) {
var item = expr.items[i];
var itemValue = evalExpr(item.expr, data, owner);
if (item.spread) {
itemValue && extend(value, itemValue);
}
else {
value[evalExpr(item.name, data, owner)] = itemValue;
}
}
return value;
case 4:
return data.get(expr);
case 5:
value = evalExpr(expr.expr, data, owner);
if (owner) {
for (var i = 0, l = expr.filters.length; i < l; i++) {
var filter = expr.filters[i];
var filterName = filter.name.paths[0].value;
switch (filterName) {
case 'url':
case '_class':
case '_style':
value = DEFAULT_FILTERS[filterName](value);
break;
case '_xclass':
case '_xstyle':
value = value = DEFAULT_FILTERS[filterName](value, evalExpr(filter.args[0], data, owner));
break;
default:
value = owner.filters[filterName] && owner.filters[filterName].apply(
owner,
[value].concat(evalArgs(filter.args, data, owner))
);
}
}
}
if (value == null) {
value = '';
}
return value;
case 6:
if (owner && expr.name.type === 4) {
var method = owner;
var pathsLen = expr.name.paths.length;
for (var i = 0; method && i < pathsLen; i++) {
method = method[evalExpr(expr.name.paths[i], data, owner)];
}
if (method) {
value = method.apply(owner, evalArgs(expr.args, data, owner));
}
}
break;
/* eslint-disable no-redeclare */
case 7:
var buf = '';
for (var i = 0, l = expr.segs.length; i < l; i++) {
var seg = expr.segs[i];
buf += seg.value || evalExpr(seg, data, owner);
}
return buf;
}
return value;
}
// exports = module.exports = evalExpr;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 为函数调用计算参数数组的值
*/
// var evalExpr = require('./eval-expr');
/**
* 为函数调用计算参数数组的值
*
* @param {Array} args 参数表达式列表
* @param {Data} data 数据环境
* @param {Component} owner 组件环境
* @return {Array}
*/
function evalArgs(args, data, owner) {
var result = [];
for (var i = 0; i < args.length; i++) {
result.push(evalExpr(args[i], data, owner));
}
return result;
}
// exports = module.exports = evalArgs;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 比较变更表达式与目标表达式之间的关系
*/
// var ExprType = require('../parser/expr-type');
// var evalExpr = require('./eval-expr');
/**
* 判断变更表达式与多个表达式之间的关系,0为完全没关系,1为有关系
*
* @inner
* @param {Object} changeExpr 目标表达式
* @param {Array} exprs 多个源表达式
* @param {Data} data 表达式所属数据环境
* @return {number}
*/
function changeExprCompareExprs(changeExpr, exprs, data) {
for (var i = 0, l = exprs.length; i < l; i++) {
if (changeExprCompare(changeExpr, exprs[i], data)) {
return 1;
}
}
return 0;
}
/**
* 比较变更表达式与目标表达式之间的关系,用于视图更新判断
* 视图更新需要根据其关系,做出相应的更新行为
*
* 0: 完全没关系
* 1: 变更表达式是目标表达式的母项(如a与a.b) 或 表示需要完全变化
* 2: 变更表达式是目标表达式相等
* >2: 变更表达式是目标表达式的子项,如a.b.c与a.b
*
* @param {Object} changeExpr 变更表达式
* @param {Object} expr 要比较的目标表达式
* @param {Data} data 表达式所属数据环境
* @return {number}
*/
function changeExprCompare(changeExpr, expr, data) {
var result = 0;
if (!expr.changeCache) {
expr.changeCache = {};
}
if (changeExpr.raw && !expr.dynamic) {
if (expr.changeCache[changeExpr.raw] != null) {
return expr.changeCache[changeExpr.raw];
}
}
switch (expr.type) {
case 4:
var paths = expr.paths;
var pathsLen = paths.length;
var changePaths = changeExpr.paths;
var changeLen = changePaths.length;
result = 1;
for (var i = 0; i < pathsLen; i++) {
var pathExpr = paths[i];
var pathExprValue = pathExpr.value;
if (pathExprValue == null && changeExprCompare(changeExpr, pathExpr, data)) {
result = 1;
break;
}
if (result && i < changeLen
/* eslint-disable eqeqeq */
&& (pathExprValue || evalExpr(pathExpr, data)) != changePaths[i].value
/* eslint-enable eqeqeq */
) {
result = 0;
}
}
if (result) {
result = Math.max(1, changeLen - pathsLen + 2);
}
break;
case 9:
result = changeExprCompare(changeExpr, expr.expr, data) ? 1 : 0;
break;
case 7:
case 8:
case 10:
result = changeExprCompareExprs(changeExpr, expr.segs, data);
break;
case 12:
case 11:
for (var i = 0; i < expr.items.length; i++) {
if (changeExprCompare(changeExpr, expr.items[i].expr, data)) {
result = 1;
break;
}
}
break;
case 5:
if (changeExprCompare(changeExpr, expr.expr, data)) {
result = 1;
}
else {
for (var i = 0; i < expr.filters.length; i++) {
if (changeExprCompareExprs(changeExpr, expr.filters[i].args, data)) {
result = 1;
break;
}
}
}
break;
case 6:
if (changeExprCompareExprs(changeExpr, expr.name.paths, data)
|| changeExprCompareExprs(changeExpr, expr.args, data)
) {
result = 1;
}
break;
}
if (changeExpr.raw && !expr.dynamic) {
expr.changeCache[changeExpr.raw] = result;
}
return result;
}
// exports = module.exports = changeExprCompare;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 数据变更类型枚举
*/
/**
* 数据变更类型枚举
*
* @const
* @type {Object}
*/
var DataChangeType = {
SET: 1,
SPLICE: 2
};
// exports = module.exports = DataChangeType;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 生命周期类
*/
function lifeCycleOwnIs(name) {
return this[name];
}
/* eslint-disable fecs-valid-var-jsdoc */
/**
* 节点生命周期信息
*
* @inner
* @type {Object}
*/
var LifeCycle = {
start: {},
compiled: {
is: lifeCycleOwnIs,
compiled: true
},
inited: {
is: lifeCycleOwnIs,
compiled: true,
inited: true
},
created: {
is: lifeCycleOwnIs,
compiled: true,
inited: true,
created: true
},
attached: {
is: lifeCycleOwnIs,
compiled: true,
inited: true,
created: true,
attached: true
},
leaving: {
is: lifeCycleOwnIs,
compiled: true,
inited: true,
created: true,
attached: true,
leaving: true
},
detached: {
is: lifeCycleOwnIs,
compiled: true,
inited: true,
created: true,
detached: true
},
disposed: {
is: lifeCycleOwnIs,
disposed: true
}
};
/* eslint-enable fecs-valid-var-jsdoc */
// exports = module.exports = LifeCycle;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 节点类型
*/
/**
* 节点类型
*
* @const
* @type {Object}
*/
var NodeType = {
TEXT: 1,
IF: 2,
FOR: 3,
ELEM: 4,
CMPT: 5,
SLOT: 6,
TPL: 7,
LOADER: 8
};
// exports = module.exports = NodeType;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 获取 ANode props 数组中相应 name 的项
*/
/**
* 获取 ANode props 数组中相应 name 的项
*
* @param {Object} aNode ANode对象
* @param {string} name name属性匹配串
* @return {Object}
*/
function getANodeProp(aNode, name) {
var index = aNode.hotspot.props[name];
if (index != null) {
return aNode.props[index];
}
}
// exports = module.exports = getANodeProp;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 获取属性处理对象
*/
// var contains = require('../util/contains');
// var empty = require('../util/empty');
// var svgTags = require('../browser/svg-tags');
// var ie = require('../browser/ie');
// var evalExpr = require('../runtime/eval-expr');
// var getANodeProp = require('./get-a-node-prop');
// var NodeType = require('./node-type');
/**
* HTML 属性和 DOM 操作属性的对照表
*
* @inner
* @const
* @type {Object}
*/
var HTML_ATTR_PROP_MAP = {
'readonly': 'readOnly',
'cellpadding': 'cellPadding',
'cellspacing': 'cellSpacing',
'colspan': 'colSpan',
'rowspan': 'rowSpan',
'valign': 'vAlign',
'usemap': 'useMap',
'frameborder': 'frameBorder',
'for': 'htmlFor'
};
/**
* 默认的元素的属性设置的变换方法
*
* @inner
* @type {Object}
*/
function defaultElementPropHandler(el, value, name) {
var propName = HTML_ATTR_PROP_MAP[name] || name;
var valueNotNull = value != null;
// input 的 type 是个特殊属性,其实也应该用 setAttribute
// 但是 type 不应该运行时动态改变,否则会有兼容性问题
// 所以这里直接就不管了
if (propName in el) {
el[propName] = valueNotNull ? value : '';
}
else if (valueNotNull) {
el.setAttribute(name, value);
}
if (!valueNotNull) {
el.removeAttribute(name);
}
}
function svgPropHandler(el, value, name) {
el.setAttribute(name, value);
}
function boolPropHandler(el, value, name) {
var propName = HTML_ATTR_PROP_MAP[name] || name;
el[propName] = !!value;
}
/* eslint-disable fecs-properties-quote */
/**
* 默认的属性设置变换方法
*
* @inner
* @type {Object}
*/
var defaultElementPropHandlers = {
style: function (el, value) {
el.style.cssText = value;
},
'class': function (el, value) { // eslint-disable-line
if (
// #[begin] allua
// ie
// ||
// #[end]
el.className !== value
) {
el.className = value;
}
},
slot: empty,
draggable: boolPropHandler
};
/* eslint-enable fecs-properties-quote */
var analInputChecker = {
checkbox: contains,
radio: function (a, b) {
return a === b;
}
};
function analInputCheckedState(element, value) {
var bindValue = getANodeProp(element.aNode, 'value');
var bindType = getANodeProp(element.aNode, 'type');
if (bindValue && bindType) {
var type = evalExpr(bindType.expr, element.scope, element.owner);
if (analInputChecker[type]) {
var bindChecked = getANodeProp(element.aNode, 'checked');
if (bindChecked != null && !bindChecked.hintExpr) {
bindChecked.hintExpr = bindValue.expr;
}
return !!analInputChecker[type](
value,
element.data
? evalExpr(bindValue.expr, element.data, element)
: evalExpr(bindValue.expr, element.scope, element.owner)
);
}
}
}
var elementPropHandlers = {
input: {
multiple: boolPropHandler,
checked: function (el, value, name, element) {
var state = analInputCheckedState(element, value);
boolPropHandler(
el,
state != null ? state : value,
'checked',
element
);
// #[begin] allua
// // 代码不用抽出来防重复,allua内的代码在现代浏览器版本会被编译时干掉,gzip也会处理重复问题
// // see: #378
// /* istanbul ignore if */
// if (ie && ie < 8 && !element.lifeCycle.attached) {
// boolPropHandler(
// el,
// state != null ? state : value,
// 'defaultChecked',
// element
// );
// }
// #[end]
},
readonly: boolPropHandler,
disabled: boolPropHandler,
autofocus: boolPropHandler,
required: boolPropHandler
},
option: {
value: function (el, value, name, element) {
defaultElementPropHandler(el, value, name, element);
if (isOptionSelected(element, value)) {
el.selected = true;
}
}
},
select: {
readonly: boolPropHandler,
disabled: boolPropHandler,
autofocus: boolPropHandler,
required: boolPropHandler
},
textarea: {
readonly: boolPropHandler,
disabled: boolPropHandler,
autofocus: boolPropHandler,
required: boolPropHandler
},
button: {
disabled: boolPropHandler,
autofocus: boolPropHandler,
type: function (el, value) {
el.setAttribute('type', value);
}
}
};
function isOptionSelected(element, value) {
var parentSelect = element.parent;
while (parentSelect) {
if (parentSelect.tagName === 'select') {
break;
}
parentSelect = parentSelect.parent;
}
if (parentSelect) {
var selectValue = null;
var prop;
var expr;
if ((prop = getANodeProp(parentSelect.aNode, 'value'))
&& (expr = prop.expr)
) {
selectValue = parentSelect.nodeType === 5
? evalExpr(expr, parentSelect.data, parentSelect)
: evalExpr(expr, parentSelect.scope, parentSelect.owner)
|| '';
}
if (selectValue === value) {
return 1;
}
}
}
/**
* 获取属性处理对象
*
* @param {string} tagName 元素tag
* @param {string} attrName 属性名
* @return {Object}
*/
function getPropHandler(tagName, attrName) {
if (svgTags[tagName]) {
return svgPropHandler;
}
var tagPropHandlers = elementPropHandlers[tagName];
if (!tagPropHandlers) {
tagPropHandlers = elementPropHandlers[tagName] = {};
}
var propHandler = tagPropHandlers[attrName];
if (!propHandler) {
propHandler = defaultElementPropHandlers[attrName] || defaultElementPropHandler;
tagPropHandlers[attrName] = propHandler;
}
return propHandler;
}
// exports = module.exports = getPropHandler;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 判断变更是否来源于元素
*/
/**
* 判断变更是否来源于元素,来源于元素时,视图更新需要阻断
*
* @param {Object} change 变更对象
* @param {Element} element 元素
* @param {string?} propName 属性名,可选。需要精确判断是否来源于此属性时传入
* @return {boolean}
*/
function isDataChangeByElement(change, element, propName) {
var changeTarget = change.option.target;
return changeTarget && changeTarget.node === element
&& (!propName || changeTarget.prop === propName);
}
// exports = module.exports = isDataChangeByElement;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 在对象上使用accessor表达式查找方法
*/
// var evalExpr = require('../runtime/eval-expr');
/**
* 在对象上使用accessor表达式查找方法
*
* @param {Object} source 源对象
* @param {Object} nameExpr 表达式
* @param {Data} data 所属数据环境
* @return {Function}
*/
function findMethod(source, nameExpr, data) {
var method = source;
for (var i = 0; method != null && i < nameExpr.paths.length; i++) {
method = method[evalExpr(nameExpr.paths[i], data)];
}
return method;
}
// exports = module.exports = findMethod;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 数据类
*/
// var ExprType = require('../parser/expr-type');
// var evalExpr = require('./eval-expr');
// var DataChangeType = require('./data-change-type');
// var createAccessor = require('../parser/create-accessor');
// var parseExpr = require('../parser/parse-expr');
/**
* 数据类
*
* @class
* @param {Object?} data 初始数据
* @param {Model?} parent 父级数据容器
*/
function Data(data, parent) {
this.parent = parent;
this.raw = data || {};
this.listeners = [];
}
// #[begin] error
// // 以下两个函数只在开发模式下可用,在生产模式下不存在
// /**
// * DataTypes 检测
// */
// Data.prototype.checkDataTypes = function () {
// if (this.typeChecker) {
// this.typeChecker(this.raw);
// }
// };
//
// /**
// * 设置 type checker
// *
// * @param {Function} typeChecker 类型校验器
// */
// Data.prototype.setTypeChecker = function (typeChecker) {
// this.typeChecker = typeChecker;
// };
//
// #[end]
/**
* 添加数据变更的事件监听器
*
* @param {Function} listener 监听函数
*/
Data.prototype.listen = function (listener) {
if (typeof listener === 'function') {
this.listeners.push(listener);
}
};
/**
* 移除数据变更的事件监听器
*
* @param {Function} listener 监听函数
*/
Data.prototype.unlisten = function (listener) {
var len = this.listeners.length;
while (len--) {
if (!listener || this.listeners[len] === listener) {
this.listeners.splice(len, 1);
}
}
};
/**
* 触发数据变更
*
* @param {Object} change 变更信息对象
*/
Data.prototype.fire = function (change) {
if (change.option.silent || change.option.silence || change.option.quiet) {
return;
}
for (var i = 0; i < this.listeners.length; i++) {
this.listeners[i].call(this, change);
}
};
/**
* 获取数据项
*
* @param {string|Object?} expr 数据项路径
* @param {Data?} callee 当前数据获取的调用环境
* @return {*}
*/
Data.prototype.get = function (expr, callee) {
var value = this.raw;
if (!expr) {
return value;
}
if (typeof expr !== 'object') {
expr = parseExpr(expr);
}
var paths = expr.paths;
callee = callee || this;
value = value[paths[0].value];
if (value == null && this.parent) {
value = this.parent.get(expr, callee);
}
else {
for (var i = 1, l = paths.length; value != null && i < l; i++) {
value = value[paths[i].value || evalExpr(paths[i], callee)];
}
}
return value;
};
/**
* 数据对象变更操作
*
* @inner
* @param {Object|Array} source 要变更的源数据
* @param {Array} exprPaths 属性路径
* @param {number} pathsStart 当前处理的属性路径指针位置
* @param {number} pathsLen 属性路径长度
* @param {*} value 变更属性值
* @param {Data} data 对应的Data对象
* @return {*} 变更后的新数据
*/
function immutableSet(source, exprPaths, pathsStart, pathsLen, value, data) {
if (pathsStart >= pathsLen) {
return value;
}
if (source == null) {
source = {};
}
var pathExpr = exprPaths[pathsStart];
var prop = evalExpr(pathExpr, data);
var result = source;
if (source instanceof Array) {
var index = +prop;
prop = isNaN(index) ? prop : index;
result = source.slice(0);
result[prop] = immutableSet(source[prop], exprPaths, pathsStart + 1, pathsLen, value, data);
}
else if (typeof source === 'object') {
result = {};
for (var key in source) {
/* istanbul ignore else */
if (key !== prop && source.hasOwnProperty(key)) {
result[key] = source[key];
}
}
result[prop] = immutableSet(source[prop], exprPaths, pathsStart + 1, pathsLen, value, data);
}
if (pathExpr.value == null) {
exprPaths[pathsStart] = {
type: typeof prop === 'string' ? 1 : 2,
value: prop
};
}
return result;
}
/**
* 设置数据项
*
* @param {string|Object} expr 数据项路径
* @param {*} value 数据值
* @param {Object=} option 设置参数
* @param {boolean} option.silent 静默设置,不触发变更事件
*/
Data.prototype.set = function (expr, value, option) {
option = option || {};
// #[begin] error
// var exprRaw = expr;
// #[end]
expr = parseExpr(expr);
// #[begin] error
// if (expr.type !== 4) {
// throw new Error('[SAN ERROR] Invalid Expression in Data set: ' + exprRaw);
// }
// #[end]
if (this.get(expr) === value && !option.force) {
return;
}
expr = {
type: 4,
paths: expr.paths.slice(0),
raw: expr.raw
};
var prop = expr.paths[0].value;
this.raw[prop] = immutableSet(this.raw[prop], expr.paths, 1, expr.paths.length, value, this);
this.fire({
type: 1,
expr: expr,
value: value,
option: option
});
// #[begin] error
// this.checkDataTypes();
// #[end]
};
/**
* 合并更新数据项
*
* @param {string|Object} expr 数据项路径
* @param {Object} source 待合并的数据值
* @param {Object=} option 设置参数
* @param {boolean} option.silent 静默设置,不触发变更事件
*/
Data.prototype.merge = function (expr, source, option) {
option = option || {};
// #[begin] error
// var exprRaw = expr;
// #[end]
expr = parseExpr(expr);
// #[begin] error
// if (expr.type !== 4) {
// throw new Error('[SAN ERROR] Invalid Expression in Data merge: ' + exprRaw);
// }
//
// if (typeof this.get(expr) !== 'object') {
// throw new Error('[SAN ERROR] Merge Expects a Target of Type \'object\'; got ' + typeof oldValue);
// }
//
// if (typeof source !== 'object') {
// throw new Error('[SAN ERROR] Merge Expects a Source of Type \'object\'; got ' + typeof source);
// }
// #[end]
for (var key in source) { // eslint-disable-line
this.set(
createAccessor(
expr.paths.concat(
[
{
type: 1,
value: key
}
]
)
),
source[key],
option
);
}
};
/**
* 基于更新函数更新数据项
*
* @param {string|Object} expr 数据项路径
* @param {Function} fn 数据处理函数
* @param {Object=} option 设置参数
* @param {boolean} option.silent 静默设置,不触发变更事件
*/
Data.prototype.apply = function (expr, fn, option) {
// #[begin] error
// var exprRaw = expr;
// #[end]
expr = parseExpr(expr);
// #[begin] error
// if (expr.type !== 4) {
// throw new Error('[SAN ERROR] Invalid Expression in Data apply: ' + exprRaw);
// }
// #[end]
var oldValue = this.get(expr);
// #[begin] error
// if (typeof fn !== 'function') {
// throw new Error(
// '[SAN ERROR] Invalid Argument\'s Type in Data apply: '
// + 'Expected Function but got ' + typeof fn
// );
// }
// #[end]
this.set(expr, fn(oldValue), option);
};
/**
* 数组数据项splice操作
*
* @param {string|Object} expr 数据项路径
* @param {Array} args splice 接受的参数列表,数组项与Array.prototype.splice的参数一致
* @param {Object=} option 设置参数
* @param {boolean} option.silent 静默设置,不触发变更事件
* @return {Array} 新数组
*/
Data.prototype.splice = function (expr, args, option) {
option = option || {};
// #[begin] error
// var exprRaw = expr;
// #[end]
expr = parseExpr(expr);
// #[begin] error
// if (expr.type !== 4) {
// throw new Error('[SAN ERROR] Invalid Expression in Data splice: ' + exprRaw);
// }
// #[end]
expr = {
type: 4,
paths: expr.paths.slice(0),
raw: expr.raw
};
var target = this.get(expr);
var returnValue = [];
if (target instanceof Array) {
var index = args[0];
var len = target.length;
if (index > len) {
index = len;
}
else if (index < 0) {
index = len + index;
if (index < 0) {
index = 0;
}
}
var newArray = target.slice(0);
returnValue = newArray.splice.apply(newArray, args);
this.raw = immutableSet(this.raw, expr.paths, 0, expr.paths.length, newArray, this);
this.fire({
expr: expr,
type: 2,
index: index,
deleteCount: returnValue.length,
value: returnValue,
insertions: args.slice(2),
option: option
});
}
// #[begin] error
// this.checkDataTypes();
// #[end]
return returnValue;
};
/**
* 数组数据项push操作
*
* @param {string|Object} expr 数据项路径
* @param {*} item 要push的值
* @param {Object=} option 设置参数
* @param {boolean} option.silent 静默设置,不触发变更事件
* @return {number} 新数组的length属性
*/
Data.prototype.push = function (expr, item, option) {
var target = this.get(expr);
if (target instanceof Array) {
this.splice(expr, [target.length, 0, item], option);
return target.length + 1;
}
};
/**
* 数组数据项pop操作
*
* @param {string|Object} expr 数据项路径
* @param {Object=} option 设置参数
* @param {boolean} option.silent 静默设置,不触发变更事件
* @return {*}
*/
Data.prototype.pop = function (expr, option) {
var target = this.get(expr);
if (target instanceof Array) {
var len = target.length;
if (len) {
return this.splice(expr, [len - 1, 1], option)[0];
}
}
};
/**
* 数组数据项shift操作
*
* @param {string|Object} expr 数据项路径
* @param {Object=} option 设置参数
* @param {boolean} option.silent 静默设置,不触发变更事件
* @return {*}
*/
Data.prototype.shift = function (expr, option) {
return this.splice(expr, [0, 1], option)[0];
};
/**
* 数组数据项unshift操作
*
* @param {string|Object} expr 数据项路径
* @param {*} item 要unshift的值
* @param {Object=} option 设置参数
* @param {boolean} option.silent 静默设置,不触发变更事件
* @return {number} 新数组的length属性
*/
Data.prototype.unshift = function (expr, item, option) {
var target = this.get(expr);
if (target instanceof Array) {
this.splice(expr, [0, 0, item], option);
return target.length + 1;
}
};
/**
* 数组数据项移除操作
*
* @param {string|Object} expr 数据项路径
* @param {number} index 要移除项的索引
* @param {Object=} option 设置参数
* @param {boolean} option.silent 静默设置,不触发变更事件
*/
Data.prototype.removeAt = function (expr, index, option) {
this.splice(expr, [index, 1], option);
};
/**
* 数组数据项移除操作
*
* @param {string|Object} expr 数据项路径
* @param {*} value 要移除的项
* @param {Object=} option 设置参数
* @param {boolean} option.silent 静默设置,不触发变更事件
*/
Data.prototype.remove = function (expr, value, option) {
var target = this.get(expr);
if (target instanceof Array) {
var len = target.length;
while (len--) {
if (target[len] === value) {
this.splice(expr, [len, 1], option);
break;
}
}
}
};
// exports = module.exports = Data;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 获取声明式事件的监听函数
*/
// var evalArgs = require('../runtime/eval-args');
// var findMethod = require('../runtime/find-method');
// var Data = require('../runtime/data');
/**
* 获取声明式事件的监听函数
*
* @param {Object} eventBind 绑定信息对象
* @param {Component} owner 所属组件环境
* @param {Data} data 数据环境
* @param {boolean} isComponentEvent 是否组件自定义事件
* @return {Function}
*/
function getEventListener(eventBind, owner, data, isComponentEvent) {
var args = eventBind.expr.args;
return function (e) {
e = isComponentEvent ? e : e || window.event;
var method = findMethod(owner, eventBind.expr.name, data);
if (typeof method === 'function') {
method.apply(
owner,
args.length ? evalArgs(args, new Data({ $event: e }, data), owner) : []
);
}
if (eventBind.modifier.prevent) {
e.preventDefault && e.preventDefault();
return false;
}
if (eventBind.modifier.stop) {
if (e.stopPropagation) {
e.stopPropagation();
}
else {
e.cancelBubble = true;
}
}
};
}
// exports = module.exports = getEventListener;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 判断变更数组是否影响到数据引用摘要
*/
/**
* 判断变更数组是否影响到数据引用摘要
*
* @param {Array} changes 变更数组
* @param {Object} dataRef 数据引用摘要
* @return {boolean}
*/
function changesIsInDataRef(changes, dataRef) {
if (dataRef) {
for (var i = 0; i < changes.length; i++) {
var change = changes[i];
if (!change.overview) {
var paths = change.expr.paths;
change.overview = paths[0].value;
if (paths.length > 1) {
change.extOverview = paths[0].value + '.' + paths[1].value;
change.wildOverview = paths[0].value + '.*';
}
}
if (dataRef[change.overview]
|| change.wildOverview && dataRef[change.wildOverview]
|| change.extOverview && dataRef[change.extOverview]
) {
return true;
}
}
}
}
// exports = module.exports = changesIsInDataRef;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file insertBefore 方法的兼容性封装
*/
/**
* insertBefore 方法的兼容性封装
*
* @param {HTMLNode} targetEl 要插入的节点
* @param {HTMLElement} parentEl 父元素
* @param {HTMLElement?} beforeEl 在此元素之前插入
*/
function insertBefore(targetEl, parentEl, beforeEl) {
if (parentEl) {
if (beforeEl) {
parentEl.insertBefore(targetEl, beforeEl);
}
else {
parentEl.appendChild(targetEl);
}
}
}
// exports = module.exports = insertBefore;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 元素的基本属性
*/
var baseProps = {
'class': 1,
'style': 1,
'id': 1
};
// exports = module.exports = baseProps;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 元素子节点遍历操作类
*/
// var removeEl = require('../browser/remove-el');
// #[begin] reverse
/**
* 元素子节点遍历操作类
*
* @inner
* @class
* @param {HTMLElement} el 要遍历的元素
*/
function DOMChildrenWalker(el) {
this.raw = [];
this.index = 0;
this.target = el;
var child = el.firstChild;
var next;
while (child) {
next = child.nextSibling;
switch (child.nodeType) {
case 3:
if (/^\s*$/.test(child.data || child.textContent)) {
removeEl(child);
}
else {
this.raw.push(child);
}
break;
case 1:
case 8:
this.raw.push(child);
}
child = next;
}
this.current = this.raw[this.index];
this.next = this.raw[this.index + 1];
}
/**
* 往下走一个元素
*/
DOMChildrenWalker.prototype.goNext = function () {
this.current = this.raw[++this.index];
this.next = this.raw[this.index + 1];
};
// #[end]
// exports = module.exports = DOMChildrenWalker;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 元素节点类
*/
// var changeExprCompare = require('../runtime/change-expr-compare');
// var changesIsInDataRef = require('../runtime/changes-is-in-data-ref');
// var evalExpr = require('../runtime/eval-expr');
// var insertBefore = require('../browser/insert-before');
// var LifeCycle = require('./life-cycle');
// var NodeType = require('./node-type');
// var baseProps = require('./base-props');
// var reverseElementChildren = require('./reverse-element-children');
// var isDataChangeByElement = require('./is-data-change-by-element');
// var getPropHandler = require('./get-prop-handler');
// var createNode = require('./create-node');
// var elementOwnDetach = require('./element-own-detach');
// var elementOwnDispose = require('./element-own-dispose');
// var elementOwnOnEl = require('./element-own-on-el');
// var elementOwnAttached = require('./element-own-attached');
// var nodeSBindInit = require('./node-s-bind-init');
// var nodeSBindUpdate = require('./node-s-bind-update');
// var warnSetHTML = require('./warn-set-html');
// var getNodePath = require('./get-node-path');
/**
* 元素节点类
*
* @class
* @param {Object} aNode 抽象节点
* @param {Node} parent 父亲节点
* @param {Model} scope 所属数据环境
* @param {Component} owner 所属组件环境
* @param {DOMChildrenWalker?} reverseWalker 子元素遍历对象
*/
function Element(aNode, parent, scope, owner, reverseWalker) {
this.aNode = aNode;
this.owner = owner;
this.scope = scope;
this.parent = parent;
this.lifeCycle = LifeCycle.start;
this.children = [];
this._elFns = [];
this.parentComponent = parent.nodeType === 5
? parent
: parent.parentComponent;
this.tagName = aNode.tagName;
// #[begin] allua
// // ie8- 不支持innerHTML输出自定义标签
// /* istanbul ignore if */
// if (ieOldThan9 && this.tagName.indexOf('-') > 0) {
// this.tagName = 'div';
// }
// #[end]
this._sbindData = nodeSBindInit(aNode.directives.bind, this.scope, this.owner);
this.lifeCycle = LifeCycle.inited;
// #[begin] reverse
if (reverseWalker) {
var currentNode = reverseWalker.current;
/* istanbul ignore if */
if (!currentNode) {
throw new Error('[SAN REVERSE ERROR] Element not found. \nPaths: '
+ getNodePath(this).join(' > '));
}
/* istanbul ignore if */
if (currentNode.nodeType !== 1) {
throw new Error('[SAN REVERSE ERROR] Element type not match, expect 1 but '
+ currentNode.nodeType + '.\nPaths: '
+ getNodePath(this).join(' > '));
}
/* istanbul ignore if */
if (currentNode.tagName.toLowerCase() !== this.tagName) {
throw new Error('[SAN REVERSE ERROR] Element tagName not match, expect '
+ this.tagName + ' but meat ' + currentNode.tagName.toLowerCase() + '.\nPaths: '
+ getNodePath(this).join(' > '));
}
this.el = currentNode;
reverseWalker.goNext();
reverseElementChildren(this, this.scope, this.owner);
this.lifeCycle = LifeCycle.created;
this._attached();
this.lifeCycle = LifeCycle.attached;
}
// #[end]
}
Element.prototype.nodeType = 4;
/**
* 将元素attach到页面
*
* @param {HTMLElement} parentEl 要添加到的父元素
* @param {HTMLElement=} beforeEl 要添加到哪个元素之前
*/
Element.prototype.attach = function (parentEl, beforeEl) {
if (!this.lifeCycle.attached) {
if (!this.el) {
var sourceNode = this.aNode.hotspot.sourceNode;
var props = this.aNode.props;
if (sourceNode) {
this.el = sourceNode.cloneNode(false);
props = this.aNode.hotspot.dynamicProps;
}
else {
this.el = createEl(this.tagName);
}
if (this._sbindData) {
for (var key in this._sbindData) {
if (this._sbindData.hasOwnProperty(key)) {
getPropHandler(this.tagName, key)(
this.el,
this._sbindData[key],
key,
this
);
}
}
}
for (var i = 0, l = props.length; i < l; i++) {
var prop = props[i];
var value = evalExpr(prop.expr, this.scope, this.owner);
if (value || !baseProps[prop.name]) {
prop.handler(this.el, value, prop.name, this);
}
}
this.lifeCycle = LifeCycle.created;
}
insertBefore(this.el, parentEl, beforeEl);
if (!this._contentReady) {
var htmlDirective = this.aNode.directives.html;
if (htmlDirective) {
// #[begin] error
// warnSetHTML(this.el);
// #[end]
this.el.innerHTML = evalExpr(htmlDirective.value, this.scope, this.owner);
}
else {
for (var i = 0, l = this.aNode.children.length; i < l; i++) {
var childANode = this.aNode.children[i];
var child = childANode.Clazz
? new childANode.Clazz(childANode, this, this.scope, this.owner)
: createNode(childANode, this, this.scope, this.owner);
this.children.push(child);
child.attach(this.el);
}
}
this._contentReady = 1;
}
this._attached();
this.lifeCycle = LifeCycle.attached;
}
};
Element.prototype.detach = elementOwnDetach;
Element.prototype.dispose = elementOwnDispose;
Element.prototype._onEl = elementOwnOnEl;
Element.prototype._leave = function () {
if (this.leaveDispose) {
if (!this.lifeCycle.disposed) {
var len = this.children.length;
while (len--) {
this.children[len].dispose(1, 1);
}
len = this._elFns.length;
while (len--) {
var fn = this._elFns[len];
un(this.el, fn[0], fn[1], fn[2]);
}
this._elFns = null;
// #[begin] allua
// /* istanbul ignore if */
// if (this._inputTimer) {
// clearInterval(this._inputTimer);
// this._inputTimer = null;
// }
// #[end]
// 如果没有parent,说明是一个root component,一定要从dom树中remove
if (!this.disposeNoDetach || !this.parent) {
removeEl(this.el);
}
this.lifeCycle = LifeCycle.detached;
this.el = null;
this.owner = null;
this.scope = null;
this.children = null;
this.lifeCycle = LifeCycle.disposed;
if (this._ondisposed) {
this._ondisposed();
}
}
}
};
/**
* 视图更新
*
* @param {Array} changes 数据变化信息
*/
Element.prototype._update = function (changes) {
var dataHotspot = this.aNode.hotspot.data;
if (dataHotspot && changesIsInDataRef(changes, dataHotspot)) {
// update s-bind
var me = this;
this._sbindData = nodeSBindUpdate(
this.aNode.directives.bind,
this._sbindData,
this.scope,
this.owner,
changes,
function (name, value) {
if (name in me.aNode.hotspot.props) {
return;
}
getPropHandler(me.tagName, name)(me.el, value, name, me);
}
);
// update prop
var dynamicProps = this.aNode.hotspot.dynamicProps;
for (var i = 0, l = dynamicProps.length; i < l; i++) {
var prop = dynamicProps[i];
var propName = prop.name;
for (var j = 0, changeLen = changes.length; j < changeLen; j++) {
var change = changes[j];
if (!isDataChangeByElement(change, this, propName)
&& (
changeExprCompare(change.expr, prop.expr, this.scope)
|| prop.hintExpr && changeExprCompare(change.expr, prop.hintExpr, this.scope)
)
) {
prop.handler(this.el, evalExpr(prop.expr, this.scope, this.owner), propName, this);
break;
}
}
}
// update content
var htmlDirective = this.aNode.directives.html;
if (htmlDirective) {
var len = changes.length;
while (len--) {
if (changeExprCompare(changes[len].expr, htmlDirective.value, this.scope)) {
// #[begin] error
// warnSetHTML(this.el);
// #[end]
this.el.innerHTML = evalExpr(htmlDirective.value, this.scope, this.owner);
break;
}
}
}
else {
for (var i = 0, l = this.children.length; i < l; i++) {
this.children[i]._update(changes);
}
}
}
};
/**
* 执行完成attached状态的行为
*/
Element.prototype._attached = elementOwnAttached;
// exports = module.exports = Element;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 创建节点对应的 stump comment 元素
*/
/**
* 创建节点对应的 stump comment 主元素
*/
function nodeOwnCreateStump() {
this.el = this.el || document.createComment(this.id);
}
// exports = module.exports = nodeOwnCreateStump;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 销毁释放元素的子元素
*/
/**
* 销毁释放元素的子元素
*
* @param {Array=} children 子元素数组
* @param {boolean=} noDetach 是否不要把节点从dom移除
* @param {boolean=} noTransition 是否不显示过渡动画效果
*/
function elementDisposeChildren(children, noDetach, noTransition) {
var len = children && children.length;
while (len--) {
children[len].dispose(noDetach, noTransition);
}
}
// exports = module.exports = elementDisposeChildren;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 简单执行销毁节点的行为
*/
// var removeEl = require('../browser/remove-el');
// var LifeCycle = require('./life-cycle');
// var elementDisposeChildren = require('./element-dispose-children');
/**
* 简单执行销毁节点的行为
*
* @param {boolean=} noDetach 是否不要把节点从dom移除
*/
function nodeOwnSimpleDispose(noDetach) {
elementDisposeChildren(this.children, noDetach, 1);
if (!noDetach) {
removeEl(this.el);
}
this.el = null;
this.owner = null;
this.scope = null;
this.children = null;
this.lifeCycle = LifeCycle.disposed;
if (this._ondisposed) {
this._ondisposed();
}
}
// exports = module.exports = nodeOwnSimpleDispose;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 异步组件类
*/
// var guid = require('../util/guid');
// var each = require('../util/each');
// var insertBefore = require('../browser/insert-before');
// var nodeOwnCreateStump = require('./node-own-create-stump');
// var nodeOwnSimpleDispose = require('./node-own-simple-dispose');
/**
* 异步组件类
*
* @class
* @param {Object} options 初始化参数
* @param {Object} loader 组件加载器
*/
function AsyncComponent(options, loader) {
this.options = options;
this.loader = loader;
this.id = guid++;
this.children = [];
// #[begin] reverse
var reverseWalker = options.reverseWalker;
if (reverseWalker) {
var PlaceholderComponent = this.loader.placeholder;
if (PlaceholderComponent) {
this.children[0] = new PlaceholderComponent(options);
}
this._create();
insertBefore(this.el, reverseWalker.target, reverseWalker.current);
var me = this;
this.loader.start(function (ComponentClass) {
me.onload(ComponentClass);
});
}
options.reverseWalker = null;
// #[end]
}
AsyncComponent.prototype._create = nodeOwnCreateStump;
AsyncComponent.prototype.dispose = nodeOwnSimpleDispose;
/**
* attach到页面
*
* @param {HTMLElement} parentEl 要添加到的父元素
* @param {HTMLElement=} beforeEl 要添加到哪个元素之前
*/
AsyncComponent.prototype.attach = function (parentEl, beforeEl) {
var PlaceholderComponent = this.loader.placeholder;
if (PlaceholderComponent) {
var component = new PlaceholderComponent(this.options);
this.children[0] = component;
component.attach(parentEl, beforeEl);
}
this._create();
insertBefore(this.el, parentEl, beforeEl);
var me = this;
this.loader.start(function (ComponentClass) {
me.onload(ComponentClass);
});
};
/**
* loader加载完成,渲染组件
*
* @param {Function=} ComponentClass 组件类
*/
AsyncComponent.prototype.onload = function (ComponentClass) {
if (this.el && ComponentClass) {
var component = new ComponentClass(this.options);
component.attach(this.el.parentNode, this.el);
var parentChildren = this.options.parent.children;
if (this.parentIndex == null || parentChildren[this.parentIndex] !== this) {
each(parentChildren, function (child, index) {
if (child instanceof AsyncComponent) {
child.parentIndex = index;
}
});
}
parentChildren[this.parentIndex] = component;
}
this.dispose();
};
/**
* 视图更新函数
*
* @param {Array} changes 数据变化信息
*/
AsyncComponent.prototype._update = function (changes) {
this.children[0] && this.children[0]._update(changes);
};
// exports = module.exports = AsyncComponent;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 通过组件反解创建节点的工厂方法
*/
// var Element = require('./element');
// var AsyncComponent = require('./async-component');
// #[begin] reverse
/**
* 通过组件反解创建节点
*
* @param {ANode} aNode 抽象节点
* @param {Node} parent 父亲节点
* @param {Model} scope 所属数据环境
* @param {Component} owner 所属组件环境
* @param {DOMChildrenWalker} reverseWalker 子元素遍历对象
* @return {Node}
*/
function createReverseNode(aNode, parent, scope, owner, reverseWalker) {
if (aNode.Clazz) {
return new aNode.Clazz(aNode, parent, scope, owner, reverseWalker);
}
var ComponentOrLoader = owner.getComponentType
? owner.getComponentType(aNode, scope)
: owner.components[aNode.tagName];
if (ComponentOrLoader) {
return typeof ComponentOrLoader === 'function'
? new ComponentOrLoader({
source: aNode,
owner: owner,
scope: scope,
parent: parent,
subTag: aNode.tagName,
reverseWalker: reverseWalker
})
: new AsyncComponent({
source: aNode,
owner: owner,
scope: scope,
parent: parent,
subTag: aNode.tagName,
reverseWalker: reverseWalker
}, ComponentOrLoader);
}
return new Element(aNode, parent, scope, owner, reverseWalker);
}
// #[end]
// exports = module.exports = createReverseNode;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 对元素的子节点进行反解
*/
// var each = require('../util/each');
// var DOMChildrenWalker = require('./dom-children-walker');
// var createReverseNode = require('./create-reverse-node');
// #[begin] reverse
/**
* 对元素的子节点进行反解
*
* @param {Object} element 元素
*/
function reverseElementChildren(element, scope, owner) {
var htmlDirective = element.aNode.directives.html;
if (!htmlDirective) {
var reverseWalker = new DOMChildrenWalker(element.el);
var aNodeChildren = element.aNode.children;
for (var i = 0, l = aNodeChildren.length; i < l; i++) {
element.children.push(
createReverseNode(aNodeChildren[i], element, scope, owner, reverseWalker)
);
}
}
}
// #[end]
// exports = module.exports = reverseElementChildren;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 创建节点的工厂方法
*/
// var Element = require('./element');
// var AsyncComponent = require('./async-component');
/**
* 创建节点
*
* @param {ANode} aNode 抽象节点
* @param {Node} parent 父亲节点
* @param {Model} scope 所属数据环境
* @param {Component} owner 所属组件环境
* @return {Node}
*/
function createNode(aNode, parent, scope, owner) {
if (aNode.Clazz) {
return new aNode.Clazz(aNode, parent, scope, owner);
}
var ComponentOrLoader = owner.getComponentType
? owner.getComponentType(aNode, scope)
: owner.components[aNode.tagName];
if (ComponentOrLoader) {
return typeof ComponentOrLoader === 'function'
? new ComponentOrLoader({
source: aNode,
owner: owner,
scope: scope,
parent: parent,
subTag: aNode.tagName
})
: new AsyncComponent({
source: aNode,
owner: owner,
scope: scope,
parent: parent,
subTag: aNode.tagName
}, ComponentOrLoader);
}
aNode.Clazz = Element;
return new Element(aNode, parent, scope, owner);
}
// exports = module.exports = createNode;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 获取 element 的 transition 控制对象
*/
// var evalArgs = require('../runtime/eval-args');
// var findMethod = require('../runtime/find-method');
// var NodeType = require('./node-type');
/**
* 获取 element 的 transition 控制对象
*
* @param {Object} element 元素
* @return {Object?}
*/
function elementGetTransition(element) {
var directive = element.aNode.directives.transition;
var owner = element.owner;
if (element.nodeType === 5) {
var cmptGivenTransition = element.source && element.source.directives.transition;
if (cmptGivenTransition) {
directive = cmptGivenTransition;
}
else {
owner = element;
}
}
var transition;
if (directive && owner) {
transition = findMethod(owner, directive.value.name);
if (typeof transition === 'function') {
transition = transition.apply(
owner,
evalArgs(directive.value.args, element.scope, owner)
);
}
}
return transition || element.transition;
}
// exports = module.exports = elementGetTransition;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 将元素从页面上移除
*/
// var elementGetTransition = require('./element-get-transition');
/**
* 将元素从页面上移除
*/
function elementOwnDetach() {
var lifeCycle = this.lifeCycle;
if (lifeCycle.leaving) {
return;
}
if (!this.disposeNoTransition) {
var transition = elementGetTransition(this);
if (transition && transition.leave) {
if (this._toPhase) {
this._toPhase('leaving');
}
else {
this.lifeCycle = LifeCycle.leaving;
}
var me = this;
transition.leave(this.el, function () {
me._leave();
});
return;
}
}
this._leave();
}
// exports = module.exports = elementOwnDetach;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 销毁释放元素
*/
/**
* 销毁释放元素
*
* @param {boolean=} noDetach 是否不要把节点从dom移除
* @param {boolean=} noTransition 是否不显示过渡动画效果
*/
function elementOwnDispose(noDetach, noTransition) {
this.leaveDispose = 1;
this.disposeNoDetach = noDetach;
this.disposeNoTransition = noTransition;
this.detach();
}
// exports = module.exports = elementOwnDispose;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 为元素的 el 绑定事件
*/
// var on = require('../browser/on');
/**
* 为元素的 el 绑定事件
*
* @param {string} name 事件名
* @param {Function} listener 监听器
* @param {boolean} capture 是否是捕获阶段触发
*/
function elementOwnOnEl(name, listener, capture) {
capture = !!capture;
this._elFns.push([name, listener, capture]);
on(this.el, name, listener, capture);
}
// exports = module.exports = elementOwnOnEl;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 是否浏览器环境
*/
var isBrowser = typeof window !== 'undefined';
// exports = module.exports = isBrowser;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 开发时的警告提示
*/
// #[begin] error
// /**
// * 开发时的警告提示
// *
// * @param {string} message 警告信息
// */
// function warn(message) {
// message = '[SAN WARNING] ' + message;
//
// /* eslint-disable no-console */
// /* istanbul ignore next */
// if (typeof console === 'object' && console.warn) {
// console.warn(message);
// }
// else {
// // 防止警告中断调用堆栈
// setTimeout(function () {
// throw new Error(message);
// }, 0);
// }
// /* eslint-enable no-console */
// }
// #[end]
// exports = module.exports = warn;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 事件绑定不存在的 warning
*/
// var each = require('../util/each');
// var warn = require('../util/warn');
// #[begin] error
// /**
// * 事件绑定不存在的 warning
// *
// * @param {Object} eventBind 事件绑定对象
// * @param {Component} owner 所属的组件对象
// */
// function warnEventListenMethod(eventBind, owner) {
// var valid = true;
// var method = owner;
// each(eventBind.expr.name.paths, function (path) {
// method = method[path.value];
// valid = !!method;
// return valid;
// });
//
// if (!valid) {
// var paths = [];
// each(eventBind.expr.name.paths, function (path) {
// paths.push(path.value);
// });
//
// warn(eventBind.name + ' listen fail,"' + paths.join('.') + '" not exist');
// }
// }
// #[end]
// exports = module.exports = warnEventListenMethod;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 完成元素 attached 后的行为
*/
// var empty = require('../util/empty');
// var isBrowser = require('../browser/is-browser');
// var trigger = require('../browser/trigger');
// var NodeType = require('./node-type');
// var elementGetTransition = require('./element-get-transition');
// var getEventListener = require('./get-event-listener');
// var warnEventListenMethod = require('./warn-event-listen-method');
/**
* 双绑输入框CompositionEnd事件监听函数
*
* @inner
*/
function inputOnCompositionEnd() {
if (!this.composing) {
return;
}
this.composing = 0;
trigger(this, 'input');
}
/**
* 双绑输入框CompositionStart事件监听函数
*
* @inner
*/
function inputOnCompositionStart() {
this.composing = 1;
}
function getXPropOutputer(element, xProp, data) {
return function () {
xPropOutput(element, xProp, data);
};
}
function getInputXPropOutputer(element, xProp, data) {
return function () {
if (!this.composing) {
xPropOutput(element, xProp, data);
}
};
}
// #[begin] allua
// /* istanbul ignore next */
// function getInputFocusXPropHandler(element, xProp, data) {
// return function () {
// element._inputTimer = setInterval(function () {
// xPropOutput(element, xProp, data);
// }, 16);
// };
// }
//
// /* istanbul ignore next */
// function getInputBlurXPropHandler(element) {
// return function () {
// clearInterval(element._inputTimer);
// element._inputTimer = null;
// };
// }
// #[end]
function xPropOutput(element, bindInfo, data) {
/* istanbul ignore if */
if (!element.lifeCycle.created) {
return;
}
var el = element.el;
if (element.tagName === 'input' && bindInfo.name === 'checked') {
var bindValue = getANodeProp(element.aNode, 'value');
var bindType = getANodeProp(element.aNode, 'type');
if (bindValue && bindType) {
switch (el.type.toLowerCase()) {
case 'checkbox':
data[el.checked ? 'push' : 'remove'](bindInfo.expr, el.value);
return;
case 'radio':
el.checked && data.set(bindInfo.expr, el.value, {
target: {
node: element,
prop: bindInfo.name
}
});
return;
}
}
}
data.set(bindInfo.expr, el[bindInfo.name], {
target: {
node: element,
prop: bindInfo.name
}
});
}
/**
* 完成元素 attached 后的行为
*
* @param {Object} element 元素节点
*/
function elementOwnAttached() {
if (this._rootNode) {
return;
}
var isComponent = this.nodeType === 5;
var data = isComponent ? this.data : this.scope;
/* eslint-disable no-redeclare */
// 处理自身变化时双向绑定的逻辑
var xProps = this.aNode.hotspot.xProps;
for (var i = 0, l = xProps.length; i < l; i++) {
var xProp = xProps[i];
switch (xProp.name) {
case 'value':
switch (this.tagName) {
case 'input':
case 'textarea':
if (isBrowser && window.CompositionEvent) {
this._onEl('change', inputOnCompositionEnd);
this._onEl('compositionstart', inputOnCompositionStart);
this._onEl('compositionend', inputOnCompositionEnd);
}
// #[begin] allua
// /* istanbul ignore else */
// if ('oninput' in this.el) {
// #[end]
this._onEl('input', getInputXPropOutputer(this, xProp, data));
// #[begin] allua
// }
// else {
// this._onEl('focusin', getInputFocusXPropHandler(this, xProp, data));
// this._onEl('focusout', getInputBlurXPropHandler(this));
// }
// #[end]
break;
case 'select':
this._onEl('change', getXPropOutputer(this, xProp, data));
break;
}
break;
case 'checked':
switch (this.tagName) {
case 'input':
switch (this.el.type) {
case 'checkbox':
case 'radio':
this._onEl('click', getXPropOutputer(this, xProp, data));
}
}
break;
}
}
var owner = isComponent ? this : this.owner;
for (var i = 0, l = this.aNode.events.length; i < l; i++) {
var eventBind = this.aNode.events[i];
// #[begin] error
// warnEventListenMethod(eventBind, owner);
// #[end]
this._onEl(
eventBind.name,
getEventListener(eventBind, owner, data, eventBind.modifier),
eventBind.modifier.capture
);
}
if (isComponent) {
for (var i = 0, l = this.nativeEvents.length; i < l; i++) {
var eventBind = this.nativeEvents[i];
// #[begin] error
// warnEventListenMethod(eventBind, this.owner);
// #[end]
this._onEl(
eventBind.name,
getEventListener(eventBind, this.owner, this.scope),
eventBind.modifier.capture
);
}
}
var transition = elementGetTransition(this);
if (transition && transition.enter) {
transition.enter(this.el, empty);
}
}
// exports = module.exports = elementOwnAttached;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 初始化节点的 s-bind 数据
*/
// var evalExpr = require('../runtime/eval-expr');
/**
* 初始化节点的 s-bind 数据
*
* @param {Object} sBind bind指令对象
* @param {Model} scope 所属数据环境
* @param {Component} owner 所属组件环境
* @return {boolean}
*/
function nodeSBindInit(sBind, scope, owner) {
if (sBind && scope) {
return evalExpr(sBind.value, scope, owner);
}
}
// exports = module.exports = nodeSBindInit;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 计算两个对象 key 的并集
*/
/**
* 计算两个对象 key 的并集
*
* @param {Object} obj1 目标对象
* @param {Object} obj2 源对象
* @return {Array}
*/
function unionKeys(obj1, obj2) {
var result = [];
var key;
for (key in obj1) {
/* istanbul ignore else */
if (obj1.hasOwnProperty(key)) {
result.push(key);
}
}
for (key in obj2) {
/* istanbul ignore else */
if (obj2.hasOwnProperty(key)) {
!obj1[key] && result.push(key);
}
}
return result;
}
// exports = module.exports = unionKeys;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 更新节点的 s-bind 数据
*/
// var unionKeys = require('../util/union-keys');
// var evalExpr = require('../runtime/eval-expr');
// var changeExprCompare = require('../runtime/change-expr-compare');
/**
* 更新节点的 s-bind 数据
*
* @param {Object} sBind bind指令对象
* @param {Object} oldBindData 当前s-bind数据
* @param {Model} scope 所属数据环境
* @param {Component} owner 所属组件环境
* @param {Array} changes 变更数组
* @param {Function} updater 绑定对象子项变更的更新函数
*/
function nodeSBindUpdate(sBind, oldBindData, scope, owner, changes, updater) {
if (sBind) {
var len = changes.length;
while (len--) {
if (changeExprCompare(changes[len].expr, sBind.value, scope)) {
var newBindData = evalExpr(sBind.value, scope, owner);
var keys = unionKeys(newBindData, oldBindData);
for (var i = 0, l = keys.length; i < l; i++) {
var key = keys[i];
var value = newBindData[key];
if (value !== oldBindData[key]) {
updater(key, value);
}
}
return newBindData;
}
}
}
}
// exports = module.exports = nodeSBindUpdate;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 判断元素是否不允许设置HTML
*/
// some html elements cannot set innerHTML in old ie
// see: https://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
/**
* 判断元素是否不允许设置HTML
*
* @param {HTMLElement} el 要判断的元素
* @return {boolean}
*/
function noSetHTML(el) {
return /^(col|colgroup|frameset|style|table|tbody|tfoot|thead|tr|select)$/i.test(el.tagName);
}
// exports = module.exports = noSetHTML;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 获取节点 stump 的 comment
*/
// var noSetHTML = require('../browser/no-set-html');
// var warn = require('../util/warn');
// #[begin] error
// /**
// * 获取节点 stump 的 comment
// *
// * @param {HTMLElement} el HTML元素
// */
// function warnSetHTML(el) {
// // dont warn if not in browser runtime
// /* istanbul ignore if */
// if (!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document)) {
// return;
// }
//
// // some html elements cannot set innerHTML in old ie
// // see: https://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
// if (noSetHTML(el)) {
// warn('set html for element "' + el.tagName + '" may cause an error in old IE');
// }
// }
// #[end]
// exports = module.exports = warnSetHTML;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 获取节点在组件树中的路径
*/
// var NodeType = require('./node-type');
// #[begin] reverse
/**
* 获取节点在组件树中的路径
*
* @param {Node} node 节点对象
* @return {Array}
*/
/* istanbul ignore next */
function getNodePath(node) {
var nodePaths = [];
var nodeParent = node;
while (nodeParent) {
switch (nodeParent.nodeType) {
case 4:
nodePaths.unshift(nodeParent.tagName);
break;
case 2:
nodePaths.unshift('if');
break;
case 3:
nodePaths.unshift('for[' + nodeParent.anode.directives['for'].raw + ']'); // eslint-disable-line dot-notation
break;
case 6:
nodePaths.unshift('slot[' + (nodeParent.name || 'default') + ']');
break;
case 7:
nodePaths.unshift('template');
break;
case 5:
nodePaths.unshift('component[' + (nodeParent.subTag || 'root') + ']');
break;
case 1:
nodePaths.unshift('text');
break;
}
nodeParent = nodeParent.parent;
}
return nodePaths;
}
// #[end]
// exports = module.exports = getNodePath;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 给 devtool 发通知消息
*/
// var isBrowser = require('../browser/is-browser');
// #[begin] devtool
// var san4devtool;
//
// /**
// * 给 devtool 发通知消息
// *
// * @param {string} name 消息名称
// * @param {*} arg 消息参数
// */
// function emitDevtool(name, arg) {
// /* istanbul ignore if */
// if (isBrowser && san4devtool && san4devtool.debug && window.__san_devtool__) {
// window.__san_devtool__.emit(name, arg);
// }
// }
//
// emitDevtool.start = function (main) {
// san4devtool = main;
// emitDevtool('san', main);
// };
// #[end]
// exports = module.exports = emitDevtool;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 组件类
*/
// var bind = require('../util/bind');
// var each = require('../util/each');
// var guid = require('../util/guid');
// var extend = require('../util/extend');
// var nextTick = require('../util/next-tick');
// var emitDevtool = require('../util/emit-devtool');
// var ExprType = require('../parser/expr-type');
// var parseExpr = require('../parser/parse-expr');
// var parseTemplate = require('../parser/parse-template');
// var createAccessor = require('../parser/create-accessor');
// var removeEl = require('../browser/remove-el');
// var Data = require('../runtime/data');
// var evalExpr = require('../runtime/eval-expr');
// var changeExprCompare = require('../runtime/change-expr-compare');
// var DataChangeType = require('../runtime/data-change-type');
// var insertBefore = require('../browser/insert-before');
// var un = require('../browser/un');
// var createNode = require('./create-node');
// var compileComponent = require('./compile-component');
// var preheatANode = require('./preheat-a-node');
// var LifeCycle = require('./life-cycle');
// var getANodeProp = require('./get-a-node-prop');
// var isDataChangeByElement = require('./is-data-change-by-element');
// var getEventListener = require('./get-event-listener');
// var reverseElementChildren = require('./reverse-element-children');
// var NodeType = require('./node-type');
// var nodeSBindInit = require('./node-s-bind-init');
// var nodeSBindUpdate = require('./node-s-bind-update');
// var elementOwnAttached = require('./element-own-attached');
// var elementOwnOnEl = require('./element-own-on-el');
// var elementOwnDetach = require('./element-own-detach');
// var elementOwnDispose = require('./element-own-dispose');
// var warnEventListenMethod = require('./warn-event-listen-method');
// var elementDisposeChildren = require('./element-dispose-children');
// var createDataTypesChecker = require('../util/create-data-types-checker');
// var warn = require('../util/warn');
/**
* 组件类
*
* @class
* @param {Object} options 初始化参数
*/
function Component(options) { // eslint-disable-line
// #[begin] error
// for (var key in Component.prototype) {
// if (this[key] !== Component.prototype[key]) {
// /* eslint-disable max-len */
// warn('\`' + key + '\` is a reserved key of san components. Overriding this property may cause unknown exceptions.');
// /* eslint-enable max-len */
// }
// }
// #[end]
options = options || {};
this.lifeCycle = LifeCycle.start;
this.children = [];
this._elFns = [];
this.listeners = {};
this.slotChildren = [];
this.implicitChildren = [];
var clazz = this.constructor;
this.filters = this.filters || clazz.filters || {};
this.computed = this.computed || clazz.computed || {};
this.messages = this.messages || clazz.messages || {};
if (options.transition) {
this.transition = options.transition;
}
this.subTag = options.subTag;
// compile
compileComponent(clazz);
var protoANode = clazz.prototype.aNode;
preheatANode(protoANode);
this.tagName = protoANode.tagName;
this.source = typeof options.source === 'string'
? parseTemplate(options.source).children[0]
: options.source;
preheatANode(this.source);
this.sourceSlotNameProps = [];
this.sourceSlots = {
named: {}
};
this.owner = options.owner;
this.scope = options.scope;
this.el = options.el;
var parent = options.parent;
if (parent) {
this.parent = parent;
this.parentComponent = parent.nodeType === 5
? parent
: parent && parent.parentComponent;
}
else if (this.owner) {
this.parentComponent = this.owner;
this.scope = this.owner.data;
}
this.id = guid++;
// #[begin] reverse
// 组件反解,读取注入的组件数据
if (this.el) {
var firstCommentNode = this.el.firstChild;
if (firstCommentNode && firstCommentNode.nodeType === 3) {
firstCommentNode = firstCommentNode.nextSibling;
}
if (firstCommentNode && firstCommentNode.nodeType === 8) {
var stumpMatch = firstCommentNode.data.match(/^\s*s-data:([\s\S]+)?$/);
if (stumpMatch) {
var stumpText = stumpMatch[1];
// fill component data
options.data = (new Function('return '
+ stumpText
.replace(/^[\s\n]*/, '')
.replace(
/"(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.\d+Z"/g,
function (match, y, mon, d, h, m, s) {
return 'new Date(' + (+y) + ',' + (+mon) + ',' + (+d)
+ ',' + (+h) + ',' + (+m) + ',' + (+s) + ')';
}
)
))();
if (firstCommentNode.previousSibling) {
removeEl(firstCommentNode.previousSibling);
}
removeEl(firstCommentNode);
}
}
}
// #[end]
// native事件数组
this.nativeEvents = [];
if (this.source) {
// 组件运行时传入的结构,做slot解析
this._initSourceSlots(1);
for (var i = 0, l = this.source.events.length; i < l; i++) {
var eventBind = this.source.events[i];
// 保存当前实例的native事件,下面创建aNode时候做合并
if (eventBind.modifier.native) {
this.nativeEvents.push(eventBind);
}
else {
// #[begin] error
// warnEventListenMethod(eventBind, options.owner);
// #[end]
this.on(
eventBind.name,
getEventListener(eventBind, options.owner, this.scope, 1),
eventBind
);
}
}
this.tagName = this.tagName || this.source.tagName;
this.binds = this.source.hotspot.binds;
// init s-bind data
this._srcSbindData = nodeSBindInit(this.source.directives.bind, this.scope, this.owner);
}
this._toPhase('compiled');
// init data
var initData = extend(
typeof this.initData === 'function' && this.initData() || {},
options.data || this._srcSbindData
);
if (this.binds && this.scope) {
for (var i = 0, l = this.binds.length; i < l; i++) {
var bindInfo = this.binds[i];
var value = evalExpr(bindInfo.expr, this.scope, this.owner);
if (typeof value !== 'undefined') {
// See: https://github.com/ecomfe/san/issues/191
initData[bindInfo.name] = value;
}
}
}
this.data = new Data(initData);
this.tagName = this.tagName || 'div';
// #[begin] allua
// // ie8- 不支持innerHTML输出自定义标签
// /* istanbul ignore if */
// if (ieOldThan9 && this.tagName.indexOf('-') > 0) {
// this.tagName = 'div';
// }
// #[end]
// #[begin] error
// // 在初始化 + 数据绑定后,开始数据校验
// // NOTE: 只在开发版本中进行属性校验
// var dataTypes = this.dataTypes || clazz.dataTypes;
// if (dataTypes) {
// var dataTypeChecker = createDataTypesChecker(
// dataTypes,
// this.subTag || this.name || clazz.name
// );
// this.data.setTypeChecker(dataTypeChecker);
// this.data.checkDataTypes();
// }
// #[end]
this.computedDeps = {};
for (var expr in this.computed) {
if (this.computed.hasOwnProperty(expr) && !this.computedDeps[expr]) {
this._calcComputed(expr);
}
}
this._initDataChanger();
this._sbindData = nodeSBindInit(this.aNode.directives.bind, this.data, this);
this._toPhase('inited');
// #[begin] reverse
var hasRootNode = this.aNode.hotspot.hasRootNode
|| (this.getComponentType
? this.getComponentType(this.aNode, this.data)
: this.components[this.aNode.tagName]
);
var reverseWalker = options.reverseWalker;
if (this.el || reverseWalker) {
if (hasRootNode) {
reverseWalker = reverseWalker || new DOMChildrenWalker(this.el);
this._rootNode = createReverseNode(this.aNode, this, this.data, this, reverseWalker);
this._rootNode._getElAsRootNode && (this.el = this._rootNode._getElAsRootNode());
}
else {
if (reverseWalker) {
var currentNode = reverseWalker.current;
if (currentNode && currentNode.nodeType === 1) {
this.el = currentNode;
reverseWalker.goNext();
}
}
reverseElementChildren(this, this.data, this);
}
this._toPhase('created');
this._attached();
this._toPhase('attached');
}
// #[end]
}
/**
* 初始化创建组件外部传入的插槽对象
*
* @protected
* @param {boolean} isFirstTime 是否初次对sourceSlots进行计算
*/
Component.prototype._initSourceSlots = function (isFirstTime) {
this.sourceSlots.named = {};
// 组件运行时传入的结构,做slot解析
if (this.source && this.scope) {
var sourceChildren = this.source.children;
for (var i = 0, l = sourceChildren.length; i < l; i++) {
var child = sourceChildren[i];
var target;
var slotBind = !child.textExpr && getANodeProp(child, 'slot');
if (slotBind) {
isFirstTime && this.sourceSlotNameProps.push(slotBind);
var slotName = evalExpr(slotBind.expr, this.scope, this.owner);
target = this.sourceSlots.named[slotName];
if (!target) {
target = this.sourceSlots.named[slotName] = [];
}
target.push(child);
}
else if (isFirstTime) {
target = this.sourceSlots.noname;
if (!target) {
target = this.sourceSlots.noname = [];
}
target.push(child);
}
}
}
};
/**
* 类型标识
*
* @type {string}
*/
Component.prototype.nodeType = 5;
/**
* 在下一个更新周期运行函数
*
* @param {Function} fn 要运行的函数
*/
Component.prototype.nextTick = nextTick;
Component.prototype._ctx = (new Date()).getTime().toString(16);
/* eslint-disable operator-linebreak */
/**
* 使节点到达相应的生命周期
*
* @protected
* @param {string} name 生命周期名称
*/
Component.prototype._callHook =
Component.prototype._toPhase = function (name) {
if (!this.lifeCycle[name]) {
this.lifeCycle = LifeCycle[name] || this.lifeCycle;
if (typeof this[name] === 'function') {
this[name]();
}
this._afterLife = this.lifeCycle;
// 通知devtool
// #[begin] devtool
// emitDevtool('comp-' + name, this);
// #[end]
}
};
/* eslint-enable operator-linebreak */
/**
* 添加事件监听器
*
* @param {string} name 事件名
* @param {Function} listener 监听器
* @param {string?} declaration 声明式
*/
Component.prototype.on = function (name, listener, declaration) {
if (typeof listener === 'function') {
if (!this.listeners[name]) {
this.listeners[name] = [];
}
this.listeners[name].push({fn: listener, declaration: declaration});
}
};
/**
* 移除事件监听器
*
* @param {string} name 事件名
* @param {Function=} listener 监听器
*/
Component.prototype.un = function (name, listener) {
var nameListeners = this.listeners[name];
var len = nameListeners && nameListeners.length;
while (len--) {
if (!listener || listener === nameListeners[len].fn) {
nameListeners.splice(len, 1);
}
}
};
/**
* 派发事件
*
* @param {string} name 事件名
* @param {Object} event 事件对象
*/
Component.prototype.fire = function (name, event) {
var me = this;
each(this.listeners[name], function (listener) {
listener.fn.call(me, event);
});
};
/**
* 计算 computed 属性的值
*
* @private
* @param {string} computedExpr computed表达式串
*/
Component.prototype._calcComputed = function (computedExpr) {
var computedDeps = this.computedDeps[computedExpr];
if (!computedDeps) {
computedDeps = this.computedDeps[computedExpr] = {};
}
var me = this;
this.data.set(computedExpr, this.computed[computedExpr].call({
data: {
get: function (expr) {
// #[begin] error
// if (!expr) {
// throw new Error('[SAN ERROR] call get method in computed need argument');
// }
// #[end]
if (!computedDeps[expr]) {
computedDeps[expr] = 1;
if (me.computed[expr] && !me.computedDeps[expr]) {
me._calcComputed(expr);
}
me.watch(expr, function () {
me._calcComputed(computedExpr);
});
}
return me.data.get(expr);
}
}
}));
};
/**
* 派发消息
* 组件可以派发消息,消息将沿着组件树向上传递,直到遇上第一个处理消息的组件
*
* @param {string} name 消息名称
* @param {*?} value 消息值
*/
Component.prototype.dispatch = function (name, value) {
var parentComponent = this.parentComponent;
while (parentComponent) {
var receiver = parentComponent.messages[name] || parentComponent.messages['*'];
if (typeof receiver === 'function') {
receiver.call(
parentComponent,
{target: this, value: value, name: name}
);
break;
}
parentComponent = parentComponent.parentComponent;
}
};
/**
* 获取组件内部的 slot
*
* @param {string=} name slot名称,空为default slot
* @return {Array}
*/
Component.prototype.slot = function (name) {
var result = [];
var me = this;
function childrenTraversal(children) {
each(children, function (child) {
if (child.nodeType === 6 && child.owner === me) {
if (child.isNamed && child.name === name
|| !child.isNamed && !name
) {
result.push(child);
}
}
else {
childrenTraversal(child.children);
}
});
}
childrenTraversal(this.children);
return result;
};
/**
* 获取带有 san-ref 指令的子组件引用
*
* @param {string} name 子组件的引用名
* @return {Component}
*/
Component.prototype.ref = function (name) {
var refTarget;
var owner = this;
function childrenTraversal(children) {
each(children, function (child) {
elementTraversal(child);
return !refTarget;
});
}
function elementTraversal(element) {
var nodeType = element.nodeType;
if (nodeType === 1) {
return;
}
if (element.owner === owner) {
var ref;
switch (element.nodeType) {
case 4:
ref = element.aNode.directives.ref;
if (ref && evalExpr(ref.value, element.scope, owner) === name) {
refTarget = element.el;
}
break;
case 5:
ref = element.source.directives.ref;
if (ref && evalExpr(ref.value, element.scope, owner) === name) {
refTarget = element;
}
}
!refTarget && childrenTraversal(element.slotChildren);
}
!refTarget && childrenTraversal(element.children);
}
childrenTraversal(this.children);
return refTarget;
};
/**
* 视图更新函数
*
* @param {Array?} changes 数据变化信息
*/
Component.prototype._update = function (changes) {
if (this.lifeCycle.disposed) {
return;
}
var me = this;
var needReloadForSlot = false;
this._notifyNeedReload = function () {
needReloadForSlot = true;
};
if (changes) {
if (this.source) {
this._srcSbindData = nodeSBindUpdate(
this.source.directives.bind,
this._srcSbindData,
this.scope,
this.owner,
changes,
function (name, value) {
if (name in me.source.hotspot.props) {
return;
}
me.data.set(name, value, {
target: {
node: me.owner
}
});
}
);
}
each(changes, function (change) {
var changeExpr = change.expr;
each(me.binds, function (bindItem) {
var relation;
var setExpr = bindItem.name;
var updateExpr = bindItem.expr;
if (!isDataChangeByElement(change, me, setExpr)
&& (relation = changeExprCompare(changeExpr, updateExpr, me.scope))
) {
if (relation > 2) {
setExpr = createAccessor(
[
{
type: 1,
value: setExpr
}
].concat(changeExpr.paths.slice(updateExpr.paths.length))
);
updateExpr = changeExpr;
}
if (relation >= 2 && change.type === 2) {
me.data.splice(setExpr, [change.index, change.deleteCount].concat(change.insertions), {
target: {
node: me.owner
}
});
}
else {
me.data.set(setExpr, evalExpr(updateExpr, me.scope, me.owner), {
target: {
node: me.owner
}
});
}
}
});
each(me.sourceSlotNameProps, function (bindItem) {
needReloadForSlot = needReloadForSlot || changeExprCompare(changeExpr, bindItem.expr, me.scope);
return !needReloadForSlot;
});
});
if (needReloadForSlot) {
this._initSourceSlots();
this._repaintChildren();
}
else {
var slotChildrenLen = this.slotChildren.length;
while (slotChildrenLen--) {
var slotChild = this.slotChildren[slotChildrenLen];
if (slotChild.lifeCycle.disposed) {
this.slotChildren.splice(slotChildrenLen, 1);
}
else if (slotChild.isInserted) {
slotChild._update(changes, 1);
}
}
}
}
var dataChanges = this._dataChanges;
if (dataChanges) {
this._dataChanges = null;
this._sbindData = nodeSBindUpdate(
this.aNode.directives.bind,
this._sbindData,
this.data,
this,
dataChanges,
function (name, value) {
if (me._rootNode || (name in me.aNode.hotspot.props)) {
return;
}
getPropHandler(me.tagName, name)(me.el, value, name, me);
}
);
if (this._rootNode) {
this._rootNode._update(dataChanges);
this._rootNode._getElAsRootNode && (this.el = this._rootNode._getElAsRootNode());
}
else {
var dynamicProps = this.aNode.hotspot.dynamicProps;
for (var i = 0; i < dynamicProps.length; i++) {
var prop = dynamicProps[i];
for (var j = 0; j < dataChanges.length; j++) {
var change = dataChanges[j];
if (changeExprCompare(change.expr, prop.expr, this.data)
|| prop.hintExpr && changeExprCompare(change.expr, prop.hintExpr, this.data)
) {
prop.handler(this.el, evalExpr(prop.expr, this.data, this), prop.name, this);
break;
}
}
}
for (var i = 0; i < this.children.length; i++) {
this.children[i]._update(dataChanges);
}
}
if (needReloadForSlot) {
this._initSourceSlots();
this._repaintChildren();
}
for (var i = 0; i < this.implicitChildren.length; i++) {
this.implicitChildren[i]._update(dataChanges);
}
this._toPhase('updated');
if (this.owner && this._updateBindxOwner(dataChanges)) {
this.owner._update();
}
}
this._notifyNeedReload = null;
};
Component.prototype._updateBindxOwner = function (dataChanges) {
var me = this;
var xbindUped;
each(dataChanges, function (change) {
each(me.binds, function (bindItem) {
var changeExpr = change.expr;
if (bindItem.x
&& !isDataChangeByElement(change, me.owner)
&& changeExprCompare(changeExpr, parseExpr(bindItem.name), me.data)
) {
var updateScopeExpr = bindItem.expr;
if (changeExpr.paths.length > 1) {
updateScopeExpr = createAccessor(
bindItem.expr.paths.concat(changeExpr.paths.slice(1))
);
}
xbindUped = 1;
me.scope.set(
updateScopeExpr,
evalExpr(changeExpr, me.data, me),
{
target: {
node: me,
prop: bindItem.name
}
}
);
}
});
});
return xbindUped;
};
/**
* 重新绘制组件的内容
* 当 dynamic slot name 发生变更或 slot 匹配发生变化时,重新绘制
* 在组件级别重绘有点粗暴,但是能保证视图结果正确性
*/
Component.prototype._repaintChildren = function () {
// TODO: repaint once?
if (this._rootNode) {
var parentEl = this._rootNode.el.parentNode;
var beforeEl = this._rootNode.el.nextSibling;
this._rootNode.dispose(0, 1);
this.slotChildren = [];
this._rootNode = createNode(this.aNode, this, this.data, this);
this._rootNode.attach(parentEl, beforeEl);
this._rootNode._getElAsRootNode && (this.el = this._rootNode._getElAsRootNode());
}
else {
elementDisposeChildren(this.children, 0, 1);
this.children = [];
this.slotChildren = [];
for (var i = 0, l = this.aNode.children.length; i < l; i++) {
var child = createNode(this.aNode.children[i], this, this.data, this);
this.children.push(child);
child.attach(this.el);
}
}
};
/**
* 初始化组件内部监听数据变化
*
* @private
* @param {Object} change 数据变化信息
*/
Component.prototype._initDataChanger = function (change) {
var me = this;
this._dataChanger = function (change) {
if (me._afterLife.created) {
if (!me._dataChanges) {
nextTick(me._update, me);
me._dataChanges = [];
}
me._dataChanges.push(change);
}
else if (me.lifeCycle.inited && me.owner) {
me._updateBindxOwner([change]);
}
};
this.data.listen(this._dataChanger);
};
/**
* 监听组件的数据变化
*
* @param {string} dataName 变化的数据项
* @param {Function} listener 监听函数
*/
Component.prototype.watch = function (dataName, listener) {
var dataExpr = parseExpr(dataName);
this.data.listen(bind(function (change) {
if (changeExprCompare(change.expr, dataExpr, this.data)) {
listener.call(this, evalExpr(dataExpr, this.data, this), change);
}
}, this));
};
Component.prototype._getElAsRootNode = function () {
return this.el;
};
/**
* 将组件attach到页面
*
* @param {HTMLElement} parentEl 要添加到的父元素
* @param {HTMLElement=} beforeEl 要添加到哪个元素之前
*/
Component.prototype.attach = function (parentEl, beforeEl) {
if (!this.lifeCycle.attached) {
this._attach(parentEl, beforeEl);
// element 都是内部创建的,只有动态创建的 component 才会进入这个分支
if (this.owner && !this.parent) {
this.owner.implicitChildren.push(this);
}
}
};
Component.prototype._attach = function (parentEl, beforeEl) {
var hasRootNode = this.aNode.hotspot.hasRootNode
|| (this.getComponentType
? this.getComponentType(this.aNode, this.data)
: this.components[this.aNode.tagName]
);
if (hasRootNode) {
this._rootNode = createNode(this.aNode, this, this.data, this);
this._rootNode.attach(parentEl, beforeEl);
this._rootNode._getElAsRootNode && (this.el = this._rootNode._getElAsRootNode());
}
else {
if (!this.el) {
var sourceNode = this.aNode.hotspot.sourceNode;
var props = this.aNode.props;
if (sourceNode) {
this.el = sourceNode.cloneNode(false);
props = this.aNode.hotspot.dynamicProps;
}
else {
this.el = createEl(this.tagName);
}
if (this._sbindData) {
for (var key in this._sbindData) {
if (this._sbindData.hasOwnProperty(key)) {
getPropHandler(this.tagName, key)(
this.el,
this._sbindData[key],
key,
this
);
}
}
}
for (var i = 0, l = props.length; i < l; i++) {
var prop = props[i];
var value = evalExpr(prop.expr, this.data, this);
if (value || !baseProps[prop.name]) {
prop.handler(this.el, value, prop.name, this);
}
}
this._toPhase('created');
}
insertBefore(this.el, parentEl, beforeEl);
if (!this._contentReady) {
for (var i = 0, l = this.aNode.children.length; i < l; i++) {
var childANode = this.aNode.children[i];
var child = childANode.Clazz
? new childANode.Clazz(childANode, this, this.data, this)
: createNode(childANode, this, this.data, this);
this.children.push(child);
child.attach(this.el);
}
this._contentReady = 1;
}
this._attached();
}
this._toPhase('attached');
};
Component.prototype.detach = elementOwnDetach;
Component.prototype.dispose = elementOwnDispose;
Component.prototype._onEl = elementOwnOnEl;
Component.prototype._attached = elementOwnAttached;
Component.prototype._leave = function () {
if (this.leaveDispose) {
if (!this.lifeCycle.disposed) {
this.data.unlisten();
this.dataChanger = null;
this._dataChanges = null;
var len = this.implicitChildren.length;
while (len--) {
this.implicitChildren[len].dispose(0, 1);
}
this.implicitChildren = null;
this.source = null;
this.sourceSlots = null;
this.sourceSlotNameProps = null;
// 这里不用挨个调用 dispose 了,因为 children 释放链会调用的
this.slotChildren = null;
if (this._rootNode) {
// 如果没有parent,说明是一个root component,一定要从dom树中remove
this._rootNode.dispose(this.disposeNoDetach && this.parent);
}
else {
var len = this.children.length;
while (len--) {
this.children[len].dispose(1, 1);
}
len = this._elFns.length;
while (len--) {
var fn = this._elFns[len];
un(this.el, fn[0], fn[1], fn[2]);
}
this._elFns = null;
// #[begin] allua
// /* istanbul ignore if */
// if (this._inputTimer) {
// clearInterval(this._inputTimer);
// this._inputTimer = null;
// }
// #[end]
// 如果没有parent,说明是一个root component,一定要从dom树中remove
if (!this.disposeNoDetach || !this.parent) {
removeEl(this.el);
}
}
this._toPhase('detached');
this._rootNode = null;
this.el = null;
this.owner = null;
this.scope = null;
this.children = null;
this._toPhase('disposed');
if (this._ondisposed) {
this._ondisposed();
}
}
}
else if (this.lifeCycle.attached) {
removeEl(this.el);
this._toPhase('detached');
}
};
// exports = module.exports = Component;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 创建组件类
*/
// var Component = require('./component');
// var inherits = require('../util/inherits');
/**
* 创建组件类
*
* @param {Object} proto 组件类的方法表
* @param {Function=} SuperComponent 父组件类
* @return {Function}
*/
function defineComponent(proto, SuperComponent) {
// 如果传入一个不是 san component 的 constructor,直接返回不是组件构造函数
// 这种场景导致的错误 san 不予考虑
if (typeof proto === 'function') {
return proto;
}
// #[begin] error
// if (typeof proto !== 'object') {
// throw new Error('[SAN FATAL] defineComponent need a plain object.');
// }
// #[end]
function ComponentClass(option) { // eslint-disable-line
Component.call(this, option);
}
ComponentClass.prototype = proto;
inherits(ComponentClass, SuperComponent || Component);
return ComponentClass;
}
// exports = module.exports = defineComponent;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 组件Loader类
*/
// var nextTick = require('../util/next-tick');
// var each = require('../util/each');
/**
* 组件Loader类
*
* @class
*
* @param {Function} load load方法
* @param {Function=} placeholder loading过程中渲染的组件
* @param {Function=} fallback load失败时渲染的组件
*/
function ComponentLoader(load, placeholder, fallback) {
this.load = load;
this.placeholder = placeholder;
this.fallback = fallback;
this.listeners = [];
}
/**
* 开始加载组件
*
* @param {Function} onload 组件加载完成监听函数
*/
ComponentLoader.prototype.start = function (onload) {
var me = this;
switch (this.state) {
case 2:
nextTick(function () {
onload(me.Component);
});
break;
case 1:
this.listeners.push(onload);
break;
default:
this.listeners.push(onload);
this.state = 1;
var startLoad = this.load();
var done = function (RealComponent) {
me.done(RealComponent);
};
if (startLoad && typeof startLoad.then === 'function') {
startLoad.then(done, done);
}
}
};
/**
* 完成组件加载
*
* @param {Function=} ComponentClass 组件类
*/
ComponentLoader.prototype.done = function (ComponentClass) {
this.state = 2;
ComponentClass = ComponentClass || this.fallback;
this.Component = ComponentClass;
each(this.listeners, function (listener) {
listener(ComponentClass);
});
};
// exports = module.exports = ComponentLoader;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 编译组件类
*/
// var warn = require('../util/warn');
// var parseTemplate = require('../parser/parse-template');
// var parseText = require('../parser/parse-text');
// var defineComponent = require('./define-component');
// var ComponentLoader = require('./component-loader');
/**
* 编译组件类。预解析template和components
*
* @param {Function} ComponentClass 组件类
*/
function compileComponent(ComponentClass) {
var proto = ComponentClass.prototype;
// pre define components class
/* istanbul ignore else */
if (!proto.hasOwnProperty('_cmptReady')) {
proto.components = ComponentClass.components || proto.components || {};
var components = proto.components;
for (var key in components) { // eslint-disable-line
var componentClass = components[key];
if (typeof componentClass === 'object' && !(componentClass instanceof ComponentLoader)) {
components[key] = defineComponent(componentClass);
}
else if (componentClass === 'self') {
components[key] = ComponentClass;
}
}
proto._cmptReady = 1;
}
// pre compile template
/* istanbul ignore else */
if (!proto.hasOwnProperty('aNode')) {
var aNode = parseTemplate(ComponentClass.template || proto.template, {
trimWhitespace: proto.trimWhitespace || ComponentClass.trimWhitespace,
delimiters: proto.delimiters || ComponentClass.delimiters
});
var firstChild = aNode.children[0];
if (firstChild && firstChild.textExpr) {
firstChild = null;
}
// #[begin] error
// if (aNode.children.length !== 1 || !firstChild) {
// warn('Component template must have a root element.');
// }
// #[end]
proto.aNode = firstChild = firstChild || {
directives: {},
props: [],
events: [],
children: []
};
if (firstChild.tagName === 'template') {
firstChild.tagName = null;
}
if (proto.autoFillStyleAndId !== false && ComponentClass.autoFillStyleAndId !== false) {
var toExtraProp = {
'class': 0, style: 0, id: 0
};
var len = firstChild.props.length;
while (len--) {
var prop = firstChild.props[len];
if (toExtraProp[prop.name] != null) {
toExtraProp[prop.name] = prop;
firstChild.props.splice(len, 1);
}
}
toExtraProp.id = toExtraProp.id || { name: 'id', expr: parseExpr('id') };
if (toExtraProp['class']) {
var classExpr = parseText('{{class | _xclass}}').segs[0];
classExpr.filters[0].args.push(toExtraProp['class'].expr);
toExtraProp['class'].expr = classExpr;
}
else {
toExtraProp['class'] = {
name: 'class',
expr: parseText('{{class | _class}}')
};
}
if (toExtraProp.style) {
var styleExpr = parseText('{{style | _xstyle}}').segs[0];
styleExpr.filters[0].args.push(toExtraProp.style.expr);
toExtraProp.style.expr = styleExpr;
}
else {
toExtraProp.style = {
name: 'style',
expr: parseText('{{style | _style}}')
};
}
firstChild.props.push(
toExtraProp['class'], // eslint-disable-line dot-notation
toExtraProp.style,
toExtraProp.id
);
}
}
}
// exports = module.exports = compileComponent;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 常用标签表,用于 element 创建优化
*/
// var splitStr2Obj = require('../util/split-str-2-obj');
/**
* 常用标签表
*
* @type {Object}
*/
var hotTags = splitStr2Obj(
'div,span,img,ul,ol,li,dl,dt,dd,a,b,u,hr,'
+ 'form,input,textarea,button,label,select,option,'
+ 'table,tbody,th,tr,td,thead,main,aside,header,footer,nav'
);
// exports = module.exports = hotTags;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 判断是否结束桩
*/
// #[begin] reverse
/**
* 判断是否结束桩
*
* @param {HTMLElement|HTMLComment} target 要判断的元素
* @param {string} type 桩类型
* @return {boolean}
*/
function isEndStump(target, type) {
return target.nodeType === 8 && target.data === '/s-' + type;
}
// #[end]
// exports = module.exports = isEndStump;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file text 节点类
*/
// var isBrowser = require('../browser/is-browser');
// var removeEl = require('../browser/remove-el');
// var insertBefore = require('../browser/insert-before');
// var changeExprCompare = require('../runtime/change-expr-compare');
// var evalExpr = require('../runtime/eval-expr');
// var NodeType = require('./node-type');
// var warnSetHTML = require('./warn-set-html');
// var isEndStump = require('./is-end-stump');
// var getNodePath = require('./get-node-path');
/**
* text 节点类
*
* @class
* @param {Object} aNode 抽象节点
* @param {Node} parent 父亲节点
* @param {Model} scope 所属数据环境
* @param {Component} owner 所属组件环境
* @param {DOMChildrenWalker?} reverseWalker 子元素遍历对象
*/
function TextNode(aNode, parent, scope, owner, reverseWalker) {
this.aNode = aNode;
this.owner = owner;
this.scope = scope;
this.parent = parent;
// #[begin] reverse
if (reverseWalker) {
var currentNode = reverseWalker.current;
if (currentNode) {
switch (currentNode.nodeType) {
case 8:
if (currentNode.data === 's-text') {
this.sel = currentNode;
currentNode.data = this.id;
reverseWalker.goNext();
while (1) { // eslint-disable-line
currentNode = reverseWalker.current;
/* istanbul ignore if */
if (!currentNode) {
throw new Error('[SAN REVERSE ERROR] Text end flag not found. \nPaths: '
+ getNodePath(this).join(' > '));
}
if (isEndStump(currentNode, 'text')) {
this.el = currentNode;
reverseWalker.goNext();
currentNode.data = this.id;
break;
}
reverseWalker.goNext();
}
}
break;
case 3:
reverseWalker.goNext();
if (!this.aNode.textExpr.original) {
this.el = currentNode;
}
break;
}
}
else {
this.el = document.createTextNode('');
insertBefore(this.el, reverseWalker.target, reverseWalker.current);
}
}
// #[end]
}
TextNode.prototype.nodeType = 1;
/**
* 将text attach到页面
*
* @param {HTMLElement} parentEl 要添加到的父元素
* @param {HTMLElement=} beforeEl 要添加到哪个元素之前
*/
TextNode.prototype.attach = function (parentEl, beforeEl) {
this.content = evalExpr(this.aNode.textExpr, this.scope, this.owner);
if (this.aNode.textExpr.original) {
this.sel = document.createComment(this.id);
insertBefore(this.sel, parentEl, beforeEl);
this.el = document.createComment(this.id);
insertBefore(this.el, parentEl, beforeEl);
var tempFlag = document.createElement('script');
parentEl.insertBefore(tempFlag, this.el);
tempFlag.insertAdjacentHTML('beforebegin', this.content);
parentEl.removeChild(tempFlag);
}
else {
this.el = document.createTextNode(this.content);
insertBefore(this.el, parentEl, beforeEl);
}
};
/**
* 销毁 text 节点
*
* @param {boolean=} noDetach 是否不要把节点从dom移除
*/
TextNode.prototype.dispose = function (noDetach) {
if (!noDetach) {
removeEl(this.el);
removeEl(this.sel);
}
this.el = null;
this.sel = null;
};
var textUpdateProp = isBrowser
&& (typeof document.createTextNode('').textContent === 'string'
? 'textContent'
: 'data');
/**
* 更新 text 节点的视图
*
* @param {Array} changes 数据变化信息
*/
TextNode.prototype._update = function (changes) {
if (this.aNode.textExpr.value) {
return;
}
var len = changes.length;
while (len--) {
if (changeExprCompare(changes[len].expr, this.aNode.textExpr, this.scope)) {
var text = evalExpr(this.aNode.textExpr, this.scope, this.owner);
if (text !== this.content) {
this.content = text;
if (this.aNode.textExpr.original) {
var startRemoveEl = this.sel.nextSibling;
var parentEl = this.el.parentNode;
while (startRemoveEl !== this.el) {
var removeTarget = startRemoveEl;
startRemoveEl = startRemoveEl.nextSibling;
removeEl(removeTarget);
}
// #[begin] error
// warnSetHTML(parentEl);
// #[end]
var tempFlag = document.createElement('script');
parentEl.insertBefore(tempFlag, this.el);
tempFlag.insertAdjacentHTML('beforebegin', text);
parentEl.removeChild(tempFlag);
}
else {
this.el[textUpdateProp] = text;
}
}
return;
}
}
};
// exports = module.exports = TextNode;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 将没有 root 只有 children 的元素 attach 到页面
*/
// var insertBefore = require('../browser/insert-before');
// var LifeCycle = require('./life-cycle');
// var createNode = require('./create-node');
/**
* 将没有 root 只有 children 的元素 attach 到页面
* 主要用于 slot 和 template
*
* @param {HTMLElement} parentEl 要添加到的父元素
* @param {HTMLElement=} beforeEl 要添加到哪个元素之前
*/
function nodeOwnOnlyChildrenAttach(parentEl, beforeEl) {
this.sel = document.createComment(this.id);
insertBefore(this.sel, parentEl, beforeEl);
for (var i = 0; i < this.aNode.children.length; i++) {
var child = createNode(
this.aNode.children[i],
this,
this.childScope || this.scope,
this.childOwner || this.owner
);
this.children.push(child);
child.attach(parentEl, beforeEl);
}
this.el = document.createComment(this.id);
insertBefore(this.el, parentEl, beforeEl);
this.lifeCycle = LifeCycle.attached;
}
// exports = module.exports = nodeOwnOnlyChildrenAttach;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file slot 节点类
*/
// var each = require('../util/each');
// var guid = require('../util/guid');
// var extend = require('../util/extend');
// var ExprType = require('../parser/expr-type');
// var createAccessor = require('../parser/create-accessor');
// var evalExpr = require('../runtime/eval-expr');
// var Data = require('../runtime/data');
// var DataChangeType = require('../runtime/data-change-type');
// var changeExprCompare = require('../runtime/change-expr-compare');
// var insertBefore = require('../browser/insert-before');
// var removeEl = require('../browser/remove-el');
// var NodeType = require('./node-type');
// var LifeCycle = require('./life-cycle');
// var getANodeProp = require('./get-a-node-prop');
// var nodeSBindInit = require('./node-s-bind-init');
// var nodeSBindUpdate = require('./node-s-bind-update');
// var createReverseNode = require('./create-reverse-node');
// var elementDisposeChildren = require('./element-dispose-children');
// var nodeOwnOnlyChildrenAttach = require('./node-own-only-children-attach');
/**
* slot 节点类
*
* @class
* @param {Object} aNode 抽象节点
* @param {Node} parent 父亲节点
* @param {Model} scope 所属数据环境
* @param {Component} owner 所属组件环境
* @param {DOMChildrenWalker?} reverseWalker 子元素遍历对象
*/
function SlotNode(aNode, parent, scope, owner, reverseWalker) {
this.owner = owner;
this.scope = scope;
this.parent = parent;
this.parentComponent = parent.nodeType === 5
? parent
: parent.parentComponent;
this.id = guid++;
this.lifeCycle = LifeCycle.start;
this.children = [];
// calc slot name
this.nameBind = getANodeProp(aNode, 'name');
if (this.nameBind) {
this.isNamed = true;
this.name = evalExpr(this.nameBind.expr, this.scope, this.owner);
}
// calc aNode children
var sourceSlots = owner.sourceSlots;
var matchedSlots;
if (sourceSlots) {
matchedSlots = this.isNamed ? sourceSlots.named[this.name] : sourceSlots.noname;
}
if (matchedSlots) {
this.isInserted = true;
}
this.aNode = {
directives: aNode.directives,
props: [],
events: [],
children: matchedSlots || aNode.children.slice(0),
vars: aNode.vars
};
this._sbindData = nodeSBindInit(aNode.directives.bind, this.scope, this.owner);
// calc scoped slot vars
var initData;
if (this._sbindData) {
initData = extend({}, this._sbindData);
}
if (aNode.vars) {
initData = initData || {};
each(aNode.vars, function (varItem) {
initData[varItem.name] = evalExpr(varItem.expr, scope, owner);
});
}
// child owner & child scope
if (this.isInserted) {
this.childOwner = owner.owner;
this.childScope = owner.scope;
}
if (initData) {
this.isScoped = true;
this.childScope = new Data(initData, this.childScope || this.scope);
}
owner.slotChildren.push(this);
// #[begin] reverse
if (reverseWalker) {
var hasFlagComment;
// start flag
if (reverseWalker.current && reverseWalker.current.nodeType === 8) {
this.sel = reverseWalker.current;
hasFlagComment = 1;
reverseWalker.goNext();
}
else {
this.sel = document.createComment(this.id);
reverseWalker.current
? reverseWalker.target.insertBefore(this.sel, reverseWalker.current)
: reverseWalker.target.appendChild(this.sel);
}
var aNodeChildren = this.aNode.children;
for (var i = 0, l = aNodeChildren.length; i < l; i++) {
this.children.push(createReverseNode(
aNodeChildren[i],
this,
this.childScope || this.scope,
this.childOwner || this.owner,
reverseWalker
));
}
// end flag
if (hasFlagComment) {
this.el = reverseWalker.current;
reverseWalker.goNext();
}
else {
this.el = document.createComment(this.id);
reverseWalker.current
? reverseWalker.target.insertBefore(this.el, reverseWalker.current)
: reverseWalker.target.appendChild(this.el);
}
this.lifeCycle = LifeCycle.attached;
}
// #[end]
}
SlotNode.prototype.nodeType = 6;
/**
* 销毁释放 slot
*
* @param {boolean=} noDetach 是否不要把节点从dom移除
* @param {boolean=} noTransition 是否不显示过渡动画效果
*/
SlotNode.prototype.dispose = function (noDetach, noTransition) {
this.childOwner = null;
this.childScope = null;
elementDisposeChildren(this.children, noDetach, noTransition);
if (!noDetach) {
removeEl(this.el);
removeEl(this.sel);
}
this.sel = null;
this.el = null;
this.owner = null;
this.scope = null;
this.children = null;
this.lifeCycle = LifeCycle.disposed;
if (this._ondisposed) {
this._ondisposed();
}
};
SlotNode.prototype.attach = nodeOwnOnlyChildrenAttach;
/**
* 视图更新函数
*
* @param {Array} changes 数据变化信息
* @param {boolean=} isFromOuter 变化信息是否来源于父组件之外的组件
* @return {boolean}
*/
SlotNode.prototype._update = function (changes, isFromOuter) {
var me = this;
if (this.nameBind && evalExpr(this.nameBind.expr, this.scope, this.owner) !== this.name) {
this.owner._notifyNeedReload();
return false;
}
if (isFromOuter) {
if (this.isInserted) {
for (var i = 0; i < this.children.length; i++) {
this.children[i]._update(changes);
}
}
}
else {
if (this.isScoped) {
var varKeys = {};
each(this.aNode.vars, function (varItem) {
varKeys[varItem.name] = 1;
me.childScope.set(varItem.name, evalExpr(varItem.expr, me.scope, me.owner));
});
var scopedChanges = [];
this._sbindData = nodeSBindUpdate(
this.aNode.directives.bind,
this._sbindData,
this.scope,
this.owner,
changes,
function (name, value) {
if (varKeys[name]) {
return;
}
me.childScope.set(name, value);
scopedChanges.push({
type: 1,
expr: createAccessor([
{type: 1, value: name}
]),
value: value,
option: {}
});
}
);
each(changes, function (change) {
if (!me.isInserted) {
scopedChanges.push(change);
}
each(me.aNode.vars, function (varItem) {
var name = varItem.name;
var relation = changeExprCompare(change.expr, varItem.expr, me.scope);
if (relation < 1) {
return;
}
if (change.type !== 2) {
scopedChanges.push({
type: 1,
expr: createAccessor([
{type: 1, value: name}
]),
value: me.childScope.get(name),
option: change.option
});
}
else if (relation === 2) {
scopedChanges.push({
expr: createAccessor([
{type: 1, value: name}
]),
type: 2,
index: change.index,
deleteCount: change.deleteCount,
value: change.value,
insertions: change.insertions,
option: change.option
});
}
});
});
for (var i = 0; i < this.children.length; i++) {
this.children[i]._update(scopedChanges);
}
}
else if (!this.isInserted) {
for (var i = 0; i < this.children.length; i++) {
this.children[i]._update(changes);
}
}
}
};
// exports = module.exports = SlotNode;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file for 指令节点类
*/
// var inherits = require('../util/inherits');
// var each = require('../util/each');
// var guid = require('../util/guid');
// var ExprType = require('../parser/expr-type');
// var parseExpr = require('../parser/parse-expr');
// var createAccessor = require('../parser/create-accessor');
// var Data = require('../runtime/data');
// var DataChangeType = require('../runtime/data-change-type');
// var changeExprCompare = require('../runtime/change-expr-compare');
// var evalExpr = require('../runtime/eval-expr');
// var changesIsInDataRef = require('../runtime/changes-is-in-data-ref');
// var insertBefore = require('../browser/insert-before');
// var NodeType = require('./node-type');
// var createNode = require('./create-node');
// var createReverseNode = require('./create-reverse-node');
// var nodeOwnSimpleDispose = require('./node-own-simple-dispose');
// var nodeOwnCreateStump = require('./node-own-create-stump');
/**
* 循环项的数据容器类
*
* @inner
* @class
* @param {Object} forElement for元素对象
* @param {*} item 当前项的数据
* @param {number} index 当前项的索引
*/
function ForItemData(forElement, item, index) {
this.parent = forElement.scope;
this.raw = {};
this.listeners = [];
this.directive = forElement.aNode.directives['for']; // eslint-disable-line dot-notation
this.indexName = this.directive.index || '$index';
this.raw[this.directive.item] = item;
this.raw[this.indexName] = index;
}
/**
* 将数据操作的表达式,转换成为对parent数据操作的表达式
* 主要是对item和index进行处理
*
* @param {Object} expr 表达式
* @return {Object}
*/
ForItemData.prototype.exprResolve = function (expr) {
var me = this;
var directive = this.directive;
function resolveItem(expr) {
if (expr.type === 4 && expr.paths[0].value === directive.item) {
return createAccessor(
directive.value.paths.concat(
{
type: 2,
value: me.raw[me.indexName]
},
expr.paths.slice(1)
)
);
}
return expr;
}
expr = resolveItem(expr);
var resolvedPaths = [];
each(expr.paths, function (item) {
resolvedPaths.push(
item.type === 4 && item.paths[0].value === me.indexName
? {
type: 2,
value: me.raw[me.indexName]
}
: resolveItem(item)
);
});
return createAccessor(resolvedPaths);
};
// 代理数据操作方法
inherits(ForItemData, Data);
each(
['set', 'remove', 'unshift', 'shift', 'push', 'pop', 'splice'],
function (method) {
ForItemData.prototype['_' + method] = Data.prototype[method];
ForItemData.prototype[method] = function (expr) {
expr = this.exprResolve(parseExpr(expr));
this.parent[method].apply(
this.parent,
[expr].concat(Array.prototype.slice.call(arguments, 1))
);
};
}
);
/**
* for 指令节点类
*
* @class
* @param {Object} aNode 抽象节点
* @param {Node} parent 父亲节点
* @param {Model} scope 所属数据环境
* @param {Component} owner 所属组件环境
* @param {DOMChildrenWalker?} reverseWalker 子元素遍历对象
*/
function ForNode(aNode, parent, scope, owner, reverseWalker) {
this.aNode = aNode;
this.owner = owner;
this.scope = scope;
this.parent = parent;
this.parentComponent = parent.nodeType === 5
? parent
: parent.parentComponent;
this.id = guid++;
this.children = [];
this.param = aNode.directives['for']; // eslint-disable-line dot-notation
this.itemPaths = [
{
type: 1,
value: this.param.item
}
];
this.itemExpr = {
type: 4,
paths: this.itemPaths,
raw: this.param.item
};
if (this.param.index) {
this.indexExpr = createAccessor([{
type: 1,
value: '' + this.param.index
}]);
}
// #[begin] reverse
if (reverseWalker) {
this.listData = evalExpr(this.param.value, this.scope, this.owner);
if (this.listData instanceof Array) {
for (var i = 0; i < this.listData.length; i++) {
this.children.push(createReverseNode(
this.aNode.forRinsed,
this,
new ForItemData(this, this.listData[i], i),
this.owner,
reverseWalker
));
}
}
else if (this.listData && typeof this.listData === 'object') {
for (var i in this.listData) {
if (this.listData.hasOwnProperty(i) && this.listData[i] != null) {
this.children.push(createReverseNode(
this.aNode.forRinsed,
this,
new ForItemData(this, this.listData[i], i),
this.owner,
reverseWalker
));
}
}
}
this._create();
insertBefore(this.el, reverseWalker.target, reverseWalker.current);
}
// #[end]
}
ForNode.prototype.nodeType = 3;
ForNode.prototype._create = nodeOwnCreateStump;
ForNode.prototype.dispose = nodeOwnSimpleDispose;
/**
* 将元素attach到页面的行为
*
* @param {HTMLElement} parentEl 要添加到的父元素
* @param {HTMLElement=} beforeEl 要添加到哪个元素之前
*/
ForNode.prototype.attach = function (parentEl, beforeEl) {
this._create();
insertBefore(this.el, parentEl, beforeEl);
this.listData = evalExpr(this.param.value, this.scope, this.owner);
this._createChildren();
};
/**
* 创建子元素
*/
ForNode.prototype._createChildren = function () {
var parentEl = this.el.parentNode;
var listData = this.listData;
if (listData instanceof Array) {
for (var i = 0; i < listData.length; i++) {
var childANode = this.aNode.forRinsed;
var child = childANode.Clazz
? new childANode.Clazz(childANode, this, new ForItemData(this, listData[i], i), this.owner)
: createNode(childANode, this, new ForItemData(this, listData[i], i), this.owner);
this.children.push(child);
child.attach(parentEl, this.el);
}
}
else if (listData && typeof listData === 'object') {
for (var i in listData) {
if (listData.hasOwnProperty(i) && listData[i] != null) {
var childANode = this.aNode.forRinsed;
var child = childANode.Clazz
? new childANode.Clazz(childANode, this, new ForItemData(this, listData[i], i), this.owner)
: createNode(childANode, this, new ForItemData(this, listData[i], i), this.owner);
this.children.push(child);
child.attach(parentEl, this.el);
}
}
}
};
/* eslint-disable fecs-max-statements */
/**
* 视图更新函数
*
* @param {Array} changes 数据变化信息
*/
ForNode.prototype._update = function (changes) {
var listData = evalExpr(this.param.value, this.scope, this.owner);
var oldIsArr = this.listData instanceof Array;
var newIsArr = listData instanceof Array;
if (this.children.length) {
if (!listData || newIsArr && listData.length === 0) {
this._disposeChildren();
this.listData = listData;
}
else if (oldIsArr !== newIsArr || !newIsArr) {
// 就是这么暴力
// 不推荐使用for遍历object,用的话自己负责
this.listData = listData;
var isListChanged;
for (var cIndex = 0; !isListChanged && cIndex < changes.length; cIndex++) {
isListChanged = changeExprCompare(changes[cIndex].expr, this.param.value, this.scope);
}
var dataHotspot = this.aNode.hotspot.data;
if (isListChanged || dataHotspot && changesIsInDataRef(changes, dataHotspot)) {
var me = this;
this._disposeChildren(null, function () {
me._createChildren();
});
}
}
else {
this._updateArray(changes, listData);
this.listData = listData;
}
}
else {
this.listData = listData;
this._createChildren();
}
};
/**
* 销毁释放子元素
*
* @param {Array?} children 要销毁的子元素,默认为自身的children
* @param {Function} callback 释放完成的回调函数
*/
ForNode.prototype._disposeChildren = function (children, callback) {
var parentEl = this.el.parentNode;
var parentFirstChild = parentEl.firstChild;
var parentLastChild = parentEl.lastChild;
var len = this.children.length;
var violentClear = !this.aNode.directives.transition
&& !children
// 是否 parent 的唯一 child
&& len && parentFirstChild === this.children[0].el && parentLastChild === this.el
;
if (!children) {
children = this.children;
this.children = [];
}
var disposedChildCount = 0;
len = children.length;
// 调用入口处已保证此处必有需要被删除的 child
for (var i = 0; i < len; i++) {
var disposeChild = children[i];
if (violentClear) {
disposeChild && disposeChild.dispose(violentClear, violentClear);
}
else if (disposeChild) {
disposeChild._ondisposed = childDisposed;
disposeChild.dispose();
}
else {
childDisposed();
}
}
if (violentClear) {
// #[begin] allua
// /* istanbul ignore next */
// if (ie) {
// parentEl.innerHTML = '';
// }
// else {
// #[end]
parentEl.textContent = '';
// #[begin] allua
// }
// #[end]
this.el = document.createComment(this.id);
parentEl.appendChild(this.el);
callback && callback();
}
function childDisposed() {
disposedChildCount++;
if (disposedChildCount >= len) {
callback && callback();
}
}
};
ForNode.prototype.opti = typeof navigator !== 'undefined'
&& /chrome\/[0-9]+/i.test(navigator.userAgent);
/**
* 数组类型的视图更新
*
* @param {Array} changes 数据变化信息
* @param {Array} newList 新数组数据
*/
ForNode.prototype._updateArray = function (changes, newList) {
var oldChildrenLen = this.children.length;
var childrenChanges = new Array(oldChildrenLen);
function pushToChildrenChanges(change) {
for (var i = 0, l = childrenChanges.length; i < l; i++) {
(childrenChanges[i] = childrenChanges[i] || []).push(change);
}
childrenNeedUpdate = null;
isOnlyDispose = false;
}
var disposeChildren = [];
// 控制列表是否整体更新的变量
var isChildrenRebuild;
//
var isOnlyDispose = true;
var childrenNeedUpdate = {};
var newLen = newList.length;
var getItemKey = this.aNode.hotspot.getForKey;
/* eslint-disable no-redeclare */
for (var cIndex = 0; cIndex < changes.length; cIndex++) {
var change = changes[cIndex];
var relation = changeExprCompare(change.expr, this.param.value, this.scope);
if (!relation) {
// 无关时,直接传递给子元素更新,列表本身不需要动
pushToChildrenChanges(change);
}
else {
if (relation > 2) {
// 变更表达式是list绑定表达式的子项
// 只需要对相应的子项进行更新
var changePaths = change.expr.paths;
var forLen = this.param.value.paths.length;
var changeIndex = +evalExpr(changePaths[forLen], this.scope, this.owner);
if (isNaN(changeIndex)) {
pushToChildrenChanges(change);
}
else if (!isChildrenRebuild) {
isOnlyDispose = false;
childrenNeedUpdate && (childrenNeedUpdate[changeIndex] = 1);
childrenChanges[changeIndex] = childrenChanges[changeIndex] || [];
if (this.param.index) {
childrenChanges[changeIndex].push(change);
}
change = change.type === 1
? {
type: change.type,
expr: createAccessor(
this.itemPaths.concat(changePaths.slice(forLen + 1))
),
value: change.value,
option: change.option
}
: {
index: change.index,
deleteCount: change.deleteCount,
insertions: change.insertions,
type: change.type,
expr: createAccessor(
this.itemPaths.concat(changePaths.slice(forLen + 1))
),
value: change.value,
option: change.option
};
childrenChanges[changeIndex].push(change);
if (change.type === 1) {
if (this.children[changeIndex]) {
this.children[changeIndex].scope._set(
change.expr,
change.value,
{
silent: 1
}
);
}
else {
// 设置数组项的索引可能超出数组长度,此时需要新增
// 比如当前数组只有2项,但是set list[4]
this.children[changeIndex] = 0;
}
}
else if (this.children[changeIndex]) {
this.children[changeIndex].scope._splice(
change.expr,
[].concat(change.index, change.deleteCount, change.insertions),
{
silent: 1
}
);
}
}
}
else if (isChildrenRebuild) {
continue;
}
else if (relation === 2 && change.type === 2
&& (this.owner.updateMode !== 'optimized' || !this.opti || this.aNode.directives.transition)
) {
childrenNeedUpdate = null;
// 变更表达式是list绑定表达式本身数组的splice操作
// 此时需要删除部分项,创建部分项
var changeStart = change.index;
var deleteCount = change.deleteCount;
var insertionsLen = change.insertions.length;
var newCount = insertionsLen - deleteCount;
if (newCount) {
var indexChange = this.param.index
? {
type: 1,
option: change.option,
expr: this.indexExpr
}
: null;
for (var i = changeStart + deleteCount; i < this.children.length; i++) {
if (indexChange) {
isOnlyDispose = false;
(childrenChanges[i] = childrenChanges[i] || []).push(indexChange);
}
var child = this.children[i];
if (child) {
child.scope.raw[child.scope.indexName] = i - deleteCount + insertionsLen;
}
}
}
var deleteLen = deleteCount;
while (deleteLen--) {
if (deleteLen < insertionsLen) {
isOnlyDispose = false;
var i = changeStart + deleteLen;
// update
(childrenChanges[i] = childrenChanges[i] || []).push({
type: 1,
option: change.option,
expr: this.itemExpr,
value: change.insertions[deleteLen]
});
if (this.children[i]) {
this.children[i].scope.raw[this.param.item] = change.insertions[deleteLen];
}
}
}
if (newCount < 0) {
disposeChildren = disposeChildren.concat(
this.children.splice(changeStart + insertionsLen, -newCount)
);
childrenChanges.splice(changeStart + insertionsLen, -newCount);
}
else if (newCount > 0) {
isOnlyDispose = false;
var spliceArgs = [changeStart + deleteCount, 0].concat(new Array(newCount));
this.children.splice.apply(this.children, spliceArgs);
childrenChanges.splice.apply(childrenChanges, spliceArgs);
}
}
else {
childrenNeedUpdate = null;
isOnlyDispose = false;
isChildrenRebuild = 1;
// 变更表达式是list绑定表达式本身或母项的重新设值
// 此时需要更新整个列表
if (getItemKey && newLen && oldChildrenLen) {
// 如果设置了trackBy,用lis更新。开始 ====
var newListKeys = [];
var oldListKeys = [];
var newListKeysMap = {};
var oldListInNew = [];
var oldListKeyIndex = {};
for (var i = 0; i < newList.length; i++) {
var itemKey = getItemKey(newList[i]);
newListKeys.push(itemKey);
newListKeysMap[itemKey] = i;
};
for (var i = 0; i < this.listData.length; i++) {
var itemKey = getItemKey(this.listData[i]);
oldListKeys.push(itemKey);
oldListKeyIndex[itemKey] = i;
if (newListKeysMap[itemKey] != null) {
oldListInNew[i] = newListKeysMap[itemKey];
}
else {
oldListInNew[i] = -1;
disposeChildren.push(this.children[i]);
}
};
var newIndexStart = 0;
var newIndexEnd = newLen;
var oldIndexStart = 0;
var oldIndexEnd = oldChildrenLen;
// 优化:从头开始比对新旧 list 项是否相同
while (newIndexStart < newLen
&& oldIndexStart < oldChildrenLen
&& newListKeys[newIndexStart] === oldListKeys[oldIndexStart]
) {
if (this.listData[oldIndexStart] !== newList[newIndexStart]) {
this.children[oldIndexStart].scope.raw[this.param.item] = newList[newIndexStart];
(childrenChanges[oldIndexStart] = childrenChanges[oldIndexStart] || []).push({
type: 1,
option: change.option,
expr: this.itemExpr,
value: newList[newIndexStart]
});
}
// 对list更上级数据的直接设置
if (relation < 2) {
(childrenChanges[oldIndexStart] = childrenChanges[oldIndexStart] || []).push(change);
}
newIndexStart++;
oldIndexStart++;
}
var indexChange = this.param.index
? {
type: 1,
option: change.option,
expr: this.indexExpr
}
: null;
// 优化:从尾开始比对新旧 list 项是否相同
while (newIndexEnd > newIndexStart && oldIndexEnd > oldIndexStart
&& newListKeys[newIndexEnd - 1] === oldListKeys[oldIndexEnd - 1]
) {
newIndexEnd--;
oldIndexEnd--;
if (this.listData[oldIndexEnd] !== newList[newIndexEnd]) {
// refresh item
this.children[oldIndexEnd].scope.raw[this.param.item] = newList[newIndexEnd];
(childrenChanges[oldIndexEnd] = childrenChanges[oldIndexEnd] || []).push({
type: 1,
option: change.option,
expr: this.itemExpr,
value: newList[newIndexEnd]
});
}
// refresh index
if (newIndexEnd !== oldIndexEnd) {
this.children[oldIndexEnd].scope.raw[this.children[oldIndexEnd].scope.indexName] = newIndexEnd;
if (indexChange) {
(childrenChanges[oldIndexEnd] = childrenChanges[oldIndexEnd] || []).push(indexChange);
}
}
// 对list更上级数据的直接设置
if (relation < 2) {
(childrenChanges[oldIndexEnd] = childrenChanges[oldIndexEnd] || []).push(change);
}
}
var oldListLIS = [];
var lisIdx = [];
var lisPos = -1;
var lisSource = oldListInNew.slice(oldIndexStart, oldIndexEnd);
var len = oldIndexEnd - oldIndexStart;
var preIdx = new Array(len);
for (var i = 0; i < len; i++) {
var oldItemInNew = lisSource[i];
if (oldItemInNew === -1) {
continue;
}
var rePos = -1;
var rePosEnd = oldListLIS.length;
if (rePosEnd > 0 && oldListLIS[rePosEnd - 1] <= oldItemInNew) {
rePos = rePosEnd - 1;
}
else {
while (rePosEnd - rePos > 1) {
var mid = Math.floor((rePos + rePosEnd) / 2);
if (oldListLIS[mid] > oldItemInNew) {
rePosEnd = mid;
} else {
rePos = mid;
}
}
}
if (rePos !== -1) {
preIdx[i] = lisIdx[rePos];
}
if (rePos === lisPos) {
lisPos++;
oldListLIS[lisPos] = oldItemInNew;
lisIdx[lisPos] = i;
} else if (oldItemInNew < oldListLIS[rePos + 1]) {
oldListLIS[rePos + 1] = oldItemInNew;
lisIdx[rePos + 1] = i;
}
}
for (var i = lisIdx[lisPos]; lisPos >= 0; i = preIdx[i], lisPos--) {
oldListLIS[lisPos] = i;
}
var oldListLISPos = oldListLIS.length;
var staticPos = oldListLISPos ? oldListInNew[oldListLIS[--oldListLISPos] + oldIndexStart] : -1;
var newChildren = [];
var newChildrenChanges = [];
for (var i = newLen - 1; i >= 0; i--) {
if (i >= newIndexEnd) {
newChildren[i] = this.children[oldChildrenLen - newLen + i];
newChildrenChanges[i] = childrenChanges[oldChildrenLen - newLen + i];
}
else if (i < newIndexStart) {
newChildren[i] = this.children[i];
newChildrenChanges[i] = childrenChanges[i];
}
else {
var oldListIndex = oldListKeyIndex[newListKeys[i]];
if (i === staticPos) {
var oldScope = this.children[oldListIndex].scope;
// 如果数据本身引用发生变化,设置变更
if (this.listData[oldListIndex] !== newList[i]) {
oldScope.raw[this.param.item] = newList[i];
(childrenChanges[oldListIndex] = childrenChanges[oldListIndex] || []).push({
type: 1,
option: change.option,
expr: this.itemExpr,
value: newList[i]
});
}
// refresh index
if (indexChange && i !== oldListIndex) {
oldScope.raw[oldScope.indexName] = i;
if (indexChange) {
(childrenChanges[oldListIndex] = childrenChanges[oldListIndex] || []).push(indexChange);
}
}
// 对list更上级数据的直接设置
if (relation < 2) {
(childrenChanges[oldListIndex] = childrenChanges[oldListIndex] || []).push(change);
}
newChildren[i] = this.children[oldListIndex];
newChildrenChanges[i] = childrenChanges[oldListIndex];
staticPos = oldListLISPos ? oldListInNew[oldListLIS[--oldListLISPos] + oldIndexStart] : -1;
}
else {
if (oldListIndex != null) {
disposeChildren.push(this.children[oldListIndex]);
}
newChildren[i] = 0;
newChildrenChanges[i] = 0;
}
}
}
this.children = newChildren;
childrenChanges = newChildrenChanges;
// 如果设置了trackBy,用lis更新。结束 ====
}
else {
// 老的比新的多的部分,标记需要dispose
if (oldChildrenLen > newLen) {
disposeChildren = disposeChildren.concat(this.children.slice(newLen));
childrenChanges = childrenChanges.slice(0, newLen);
this.children = this.children.slice(0, newLen);
}
// 剩下的部分整项变更
for (var i = 0; i < newLen; i++) {
// 对list更上级数据的直接设置
if (relation < 2) {
(childrenChanges[i] = childrenChanges[i] || []).push(change);
}
if (this.children[i]) {
if (this.children[i].scope.raw[this.param.item] !== newList[i]) {
this.children[i].scope.raw[this.param.item] = newList[i];
(childrenChanges[i] = childrenChanges[i] || []).push({
type: 1,
option: change.option,
expr: this.itemExpr,
value: newList[i]
});
}
}
else {
this.children[i] = 0;
}
}
}
}
}
}
// 标记 length 是否发生变化
if (newLen !== oldChildrenLen && this.param.value.paths) {
var lengthChange = {
type: 1,
option: {},
expr: createAccessor(
this.param.value.paths.concat({
type: 1,
value: 'length'
})
)
};
if (changesIsInDataRef([lengthChange], this.aNode.hotspot.data)) {
pushToChildrenChanges(lengthChange);
}
}
// 执行视图更新,先删再刷新
this._doCreateAndUpdate = doCreateAndUpdate;
var me = this;
if (disposeChildren.length === 0) {
doCreateAndUpdate();
}
else {
this._disposeChildren(disposeChildren, function () {
if (doCreateAndUpdate === me._doCreateAndUpdate) {
doCreateAndUpdate();
}
});
}
function doCreateAndUpdate() {
me._doCreateAndUpdate = null;
if (isOnlyDispose) {
return;
}
var beforeEl = me.el;
var parentEl = beforeEl.parentNode;
// 对相应的项进行更新
// 如果不attached则直接创建,如果存在则调用更新函数
var j = -1;
for (var i = 0; i < newLen; i++) {
var child = me.children[i];
if (child) {
if (childrenChanges[i] && (!childrenNeedUpdate || childrenNeedUpdate[i])) {
child._update(childrenChanges[i]);
}
}
else {
if (j < i) {
j = i + 1;
beforeEl = null;
while (j < newLen) {
var nextChild = me.children[j];
if (nextChild) {
beforeEl = nextChild.sel || nextChild.el;
break;
}
j++;
}
}
me.children[i] = createNode(me.aNode.forRinsed, me, new ForItemData(me, newList[i], i), me.owner);
me.children[i].attach(parentEl, beforeEl || me.el);
}
}
}
};
// exports = module.exports = ForNode;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file if 指令节点类
*/
// var each = require('../util/each');
// var guid = require('../util/guid');
// var insertBefore = require('../browser/insert-before');
// var evalExpr = require('../runtime/eval-expr');
// var NodeType = require('./node-type');
// var createNode = require('./create-node');
// var createReverseNode = require('./create-reverse-node');
// var nodeOwnCreateStump = require('./node-own-create-stump');
// var nodeOwnSimpleDispose = require('./node-own-simple-dispose');
/**
* if 指令节点类
*
* @class
* @param {Object} aNode 抽象节点
* @param {Node} parent 父亲节点
* @param {Model} scope 所属数据环境
* @param {Component} owner 所属组件环境
* @param {DOMChildrenWalker?} reverseWalker 子元素遍历对象
*/
function IfNode(aNode, parent, scope, owner, reverseWalker) {
this.aNode = aNode;
this.owner = owner;
this.scope = scope;
this.parent = parent;
this.parentComponent = parent.nodeType === 5
? parent
: parent.parentComponent;
this.id = guid++;
this.children = [];
// #[begin] reverse
if (reverseWalker) {
if (evalExpr(this.aNode.directives['if'].value, this.scope, this.owner)) { // eslint-disable-line dot-notation
this.elseIndex = -1;
this.children[0] = createReverseNode(
this.aNode.ifRinsed,
this,
this.scope,
this.owner,
reverseWalker
);
}
else {
var me = this;
each(aNode.elses, function (elseANode, index) {
var elif = elseANode.directives.elif;
if (!elif || elif && evalExpr(elif.value, me.scope, me.owner)) {
me.elseIndex = index;
me.children[0] = createReverseNode(
elseANode,
me,
me.scope,
me.owner,
reverseWalker
);
return false;
}
});
}
this._create();
insertBefore(this.el, reverseWalker.target, reverseWalker.current);
}
// #[end]
}
IfNode.prototype.nodeType = 2;
IfNode.prototype._create = nodeOwnCreateStump;
IfNode.prototype.dispose = nodeOwnSimpleDispose;
/**
* attach到页面
*
* @param {HTMLElement} parentEl 要添加到的父元素
* @param {HTMLElement=} beforeEl 要添加到哪个元素之前
*/
IfNode.prototype.attach = function (parentEl, beforeEl) {
var me = this;
var elseIndex;
var child;
if (evalExpr(this.aNode.directives['if'].value, this.scope, this.owner)) { // eslint-disable-line dot-notation
child = createNode(this.aNode.ifRinsed, this, this.scope, this.owner);
elseIndex = -1;
}
else {
each(this.aNode.elses, function (elseANode, index) {
var elif = elseANode.directives.elif;
if (!elif || elif && evalExpr(elif.value, me.scope, me.owner)) {
child = createNode(elseANode, me, me.scope, me.owner);
elseIndex = index;
return false;
}
});
}
if (child) {
this.children[0] = child;
child.attach(parentEl, beforeEl);
this.elseIndex = elseIndex;
}
this._create();
insertBefore(this.el, parentEl, beforeEl);
};
/**
* 视图更新函数
*
* @param {Array} changes 数据变化信息
*/
IfNode.prototype._update = function (changes) {
var me = this;
var childANode = this.aNode.ifRinsed;
var elseIndex;
if (evalExpr(this.aNode.directives['if'].value, this.scope, this.owner)) { // eslint-disable-line dot-notation
elseIndex = -1;
}
else {
each(this.aNode.elses, function (elseANode, index) {
var elif = elseANode.directives.elif;
if (elif && evalExpr(elif.value, me.scope, me.owner) || !elif) {
elseIndex = index;
childANode = elseANode;
return false;
}
});
}
var child = this.children[0];
if (elseIndex === this.elseIndex) {
child && child._update(changes);
}
else {
this.children = [];
if (child) {
child._ondisposed = newChild;
child.dispose();
}
else {
newChild();
}
this.elseIndex = elseIndex;
}
function newChild() {
if (typeof elseIndex !== 'undefined') {
(me.children[0] = createNode(childANode, me, me.scope, me.owner))
.attach(me.el.parentNode, me.el);
}
}
};
IfNode.prototype._getElAsRootNode = function () {
var child = this.children[0];
return child && child.el || this.el;
};
// exports = module.exports = IfNode;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file template 节点类
*/
// var each = require('../util/each');
// var guid = require('../util/guid');
// var insertBefore = require('../browser/insert-before');
// var removeEl = require('../browser/remove-el');
// var NodeType = require('./node-type');
// var LifeCycle = require('./life-cycle');
// var createReverseNode = require('./create-reverse-node');
// var elementDisposeChildren = require('./element-dispose-children');
// var nodeOwnOnlyChildrenAttach = require('./node-own-only-children-attach');
/**
* template 节点类
*
* @class
* @param {Object} aNode 抽象节点
* @param {Node} parent 父亲节点
* @param {Model} scope 所属数据环境
* @param {Component} owner 所属组件环境
* @param {DOMChildrenWalker?} reverseWalker 子元素遍历对象
*/
function TemplateNode(aNode, parent, scope, owner, reverseWalker) {
this.aNode = aNode;
this.owner = owner;
this.scope = scope;
this.parent = parent;
this.parentComponent = parent.nodeType === 5
? parent
: parent.parentComponent;
this.id = guid++;
this.lifeCycle = LifeCycle.start;
this.children = [];
// #[begin] reverse
if (reverseWalker) {
var hasFlagComment;
// start flag
if (reverseWalker.current && reverseWalker.current.nodeType === 8) {
this.sel = reverseWalker.current;
hasFlagComment = 1;
reverseWalker.goNext();
}
else {
this.sel = document.createComment(this.id);
insertBefore(this.sel, reverseWalker.target, reverseWalker.current);
}
// content
var aNodeChildren = this.aNode.children;
for (var i = 0, l = aNodeChildren.length; i < l; i++) {
this.children.push(
createReverseNode(aNodeChildren[i], this, this.scope, this.owner, reverseWalker)
);
}
// end flag
if (hasFlagComment) {
this.el = reverseWalker.current;
reverseWalker.goNext();
}
else {
this.el = document.createComment(this.id);
insertBefore(this.el, reverseWalker.target, reverseWalker.current);
}
this.lifeCycle = LifeCycle.attached;
}
// #[end]
}
TemplateNode.prototype.nodeType = 7;
TemplateNode.prototype.attach = nodeOwnOnlyChildrenAttach;
/**
* 销毁释放
*
* @param {boolean=} noDetach 是否不要把节点从dom移除
* @param {boolean=} noTransition 是否不显示过渡动画效果
*/
TemplateNode.prototype.dispose = function (noDetach, noTransition) {
elementDisposeChildren(this.children, noDetach, noTransition);
if (!noDetach) {
removeEl(this.el);
removeEl(this.sel);
}
this.sel = null;
this.el = null;
this.owner = null;
this.scope = null;
this.children = null;
this.lifeCycle = LifeCycle.disposed;
if (this._ondisposed) {
this._ondisposed();
}
};
/**
* 视图更新函数
*
* @param {Array} changes 数据变化信息
*/
TemplateNode.prototype._update = function (changes) {
for (var i = 0; i < this.children.length; i++) {
this.children[i]._update(changes);
}
};
// exports = module.exports = TemplateNode;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file ANode预热
*/
// var ExprType = require('../parser/expr-type');
// var each = require('../util/each');
// var extend = require('../util/extend');
// var kebab2camel = require('../util/kebab2camel');
// var hotTags = require('../browser/hot-tags');
// var createEl = require('../browser/create-el');
// var getPropHandler = require('./get-prop-handler');
// var getANodeProp = require('./get-a-node-prop');
// var isBrowser = require('../browser/is-browser');
// var TextNode = require('./text-node');
// var SlotNode = require('./slot-node');
// var ForNode = require('./for-node');
// var IfNode = require('./if-node');
// var TemplateNode = require('./template-node');
// var Element = require('./element');
/**
* ANode预热,分析的数据引用等信息
*
* @param {Object} aNode 要预热的ANode
*/
function preheatANode(aNode) {
var stack = [];
function recordHotspotData(expr, notContentData) {
var refs = analyseExprDataHotspot(expr);
if (refs.length) {
for (var i = 0, len = stack.length; i < len; i++) {
if (!notContentData || i !== len - 1) {
var data = stack[i].hotspot.data;
if (!data) {
data = stack[i].hotspot.data = {};
}
each(refs, function (ref) {
data[ref] = 1;
});
}
}
}
}
function analyseANodeHotspot(aNode) {
if (!aNode.hotspot) {
stack.push(aNode);
if (aNode.textExpr) {
aNode.hotspot = {};
aNode.Clazz = TextNode;
recordHotspotData(aNode.textExpr);
}
else {
var sourceNode;
if (isBrowser && aNode.tagName
&& aNode.tagName.indexOf('-') < 0
&& !/^(template|slot|select|input|option|button|video|audio|canvas|img|embed|object|iframe)$/i.test(aNode.tagName)
) {
sourceNode = createEl(aNode.tagName);
}
aNode.hotspot = {
dynamicProps: [],
xProps: [],
props: {},
binds: [],
sourceNode: sourceNode
};
// === analyse hotspot data: start
each(aNode.vars, function (varItem) {
recordHotspotData(varItem.expr);
});
each(aNode.props, function (prop) {
aNode.hotspot.binds.push({
name: kebab2camel(prop.name),
expr: prop.raw != null ? prop.expr : {
type: 3,
value: true
},
x: prop.x,
raw: prop.raw
});
recordHotspotData(prop.expr);
});
for (var key in aNode.directives) {
/* istanbul ignore else */
if (aNode.directives.hasOwnProperty(key)) {
var directive = aNode.directives[key];
recordHotspotData(
directive.value,
!/^(html|bind)$/.test(key)
);
// init trackBy getKey function
if (key === 'for') {
var trackBy = directive.trackBy;
if (trackBy
&& trackBy.type === 4
&& trackBy.paths[0].value === directive.item
) {
aNode.hotspot.getForKey = new Function(
directive.item,
'return ' + trackBy.raw
);
}
}
}
}
each(aNode.elses, function (child) {
analyseANodeHotspot(child);
});
each(aNode.children, function (child) {
analyseANodeHotspot(child);
});
// === analyse hotspot data: end
// === analyse hotspot props: start
each(aNode.props, function (prop, index) {
aNode.hotspot.props[prop.name] = index;
prop.handler = getPropHandler(aNode.tagName, prop.name);
if (prop.name === 'id') {
prop.id = true;
aNode.hotspot.idProp = prop;
aNode.hotspot.dynamicProps.push(prop);
}
else if (prop.expr.value != null) {
if (sourceNode) {
prop.handler(sourceNode, prop.expr.value, prop.name, aNode);
}
}
else {
if (prop.x) {
aNode.hotspot.xProps.push(prop);
}
aNode.hotspot.dynamicProps.push(prop);
}
});
// ie 下,如果 option 没有 value 属性,select.value = xx 操作不会选中 option
// 所以没有设置 value 时,默认把 option 的内容作为 value
if (aNode.tagName === 'option'
&& !getANodeProp(aNode, 'value')
&& aNode.children[0]
) {
var valueProp = {
name: 'value',
expr: aNode.children[0].textExpr,
handler: getPropHandler(aNode.tagName, 'value')
};
aNode.props.push(valueProp);
aNode.hotspot.dynamicProps.push(valueProp);
aNode.hotspot.props.value = aNode.props.length - 1;
}
if (aNode.directives['if']) { // eslint-disable-line dot-notation
aNode.ifRinsed = {
children: aNode.children,
props: aNode.props,
events: aNode.events,
tagName: aNode.tagName,
vars: aNode.vars,
hotspot: aNode.hotspot,
directives: extend({}, aNode.directives)
};
aNode.hotspot.hasRootNode = true;
aNode.Clazz = IfNode;
aNode = aNode.ifRinsed;
aNode.directives['if'] = null; // eslint-disable-line dot-notation
}
if (aNode.directives['for']) { // eslint-disable-line dot-notation
aNode.forRinsed = {
children: aNode.children,
props: aNode.props,
events: aNode.events,
tagName: aNode.tagName,
vars: aNode.vars,
hotspot: aNode.hotspot,
directives: extend({}, aNode.directives)
};
aNode.hotspot.hasRootNode = true;
aNode.Clazz = ForNode;
aNode.forRinsed.directives['for'] = null; // eslint-disable-line dot-notation
aNode = aNode.forRinsed;
}
if (hotTags[aNode.tagName]) {
aNode.Clazz = Element;
}
else {
switch (aNode.tagName) {
case 'slot':
aNode.Clazz = SlotNode;
break;
case 'template':
case 'fragment':
aNode.hotspot.hasRootNode = true;
aNode.Clazz = TemplateNode;
}
}
// === analyse hotspot props: end
}
stack.pop();
}
}
if (aNode) {
analyseANodeHotspot(aNode);
}
}
/**
* 分析表达式的数据引用
*
* @param {Object} expr 要分析的表达式
* @return {Array}
*/
function analyseExprDataHotspot(expr, accessorMeanDynamic) {
var refs = [];
var isDynamic;
function analyseExprs(exprs, accessorMeanDynamic) {
for (var i = 0, l = exprs.length; i < l; i++) {
refs = refs.concat(analyseExprDataHotspot(exprs[i], accessorMeanDynamic));
isDynamic = isDynamic || exprs[i].dynamic;
}
}
switch (expr.type) {
case 4:
isDynamic = accessorMeanDynamic;
var paths = expr.paths;
refs.push(paths[0].value);
if (paths.length > 1) {
refs.push(paths[0].value + '.' + (paths[1].value || '*'));
}
analyseExprs(paths.slice(1), 1);
break;
case 9:
refs = analyseExprDataHotspot(expr.expr, accessorMeanDynamic);
isDynamic = expr.expr.dynamic;
break;
case 7:
case 8:
case 10:
analyseExprs(expr.segs, accessorMeanDynamic);
break;
case 5:
refs = analyseExprDataHotspot(expr.expr);
isDynamic = expr.expr.dynamic;
each(expr.filters, function (filter) {
analyseExprs(filter.name.paths);
analyseExprs(filter.args);
});
break;
case 6:
analyseExprs(expr.name.paths);
analyseExprs(expr.args);
break;
case 12:
case 11:
for (var i = 0; i < expr.items.length; i++) {
refs = refs.concat(analyseExprDataHotspot(expr.items[i].expr));
isDynamic = isDynamic || expr.items[i].expr.dynamic;
}
break;
}
isDynamic && (expr.dynamic = true);
return refs;
}
// exports = module.exports = preheatANode;
/**
* Copyright (c) Baidu Inc. All rights reserved.
*
* This source code is licensed under the MIT license.
* See LICENSE file in the project root for license information.
*
* @file 创建组件Loader
*/
// var ComponentLoader = require('./component-loader');
/**
* 创建组件Loader
*
* @param {Object|Function} options 创建组件Loader的参数。为Object时参考下方描述,为Function时代表load方法。
* @param {Function} options.load load方法
* @param {Function=} options.placeholder loading过程中渲染的占位组件
* @param {Function=} options.fallback load失败时渲染的组件
* @return {ComponentLoader}
*/
function createComponentLoader(options) {
var placeholder = options.placeholder;
var fallback = options.fallback;
var load = typeof options === 'function' ? options : options.load;
return new ComponentLoader(load, placeholder, fallback);
}
// exports = module.exports = createComponentLoader;
/* eslint-disable no-unused-vars */
// var nextTick = require('./util/next-tick');
// var inherits = require('./util/inherits');
// var parseTemplate = require('./parser/parse-template');
// var parseExpr = require('./parser/parse-expr');
// var ExprType = require('./parser/expr-type');
// var LifeCycle = require('./view/life-cycle');
// var NodeType = require('./view/node-type');
// var Component = require('./view/component');
// var compileComponent = require('./view/compile-component');
// var defineComponent = require('./view/define-component');
// var createComponentLoader = require('./view/create-component-loader');
// var emitDevtool = require('./util/emit-devtool');
// var Data = require('./runtime/data');
// var evalExpr = require('./runtime/eval-expr');
// var DataTypes = require('./util/data-types');
var san = {
/**
* san版本号
*
* @type {string}
*/
version: '3.8.3',
// #[begin] devtool
// /**
// * 是否开启调试。开启调试时 devtool 会工作
// *
// * @type {boolean}
// */
// debug: true,
// #[end]
/**
* 组件基类
*
* @type {Function}
*/
Component: Component,
/**
* 创建组件类
*
* @param {Object} proto 组件类的方法表
* @return {Function}
*/
defineComponent: defineComponent,
/**
* 创建组件Loader
*
* @param {Object|Function} options 创建组件Loader的参数。为Object时参考下方描述,为Function时代表load方法。
* @param {Function} options.load load方法
* @param {Function=} options.placeholder loading过程中渲染的占位组件
* @param {Function=} options.fallback load失败时渲染的组件
* @return {ComponentLoader}
*/
createComponentLoader: createComponentLoader,
/**
* 编译组件类。预解析template和components
*
* @param {Function} ComponentClass 组件类
*/
compileComponent: compileComponent,
/**
* 解析 template
*
* @inner
* @param {string} source template 源码
* @return {ANode}
*/
parseTemplate: parseTemplate,
/**
* 解析表达式
*
* @param {string} source 源码
* @return {Object}
*/
parseExpr: parseExpr,
/**
* 表达式类型枚举
*
* @const
* @type {Object}
*/
ExprType: ExprType,
/**
* 生命周期
*/
LifeCycle: LifeCycle,
/**
* 节点类型
*
* @const
* @type {Object}
*/
NodeType: NodeType,
/**
* 在下一个更新周期运行函数
*
* @param {Function} fn 要运行的函数
*/
nextTick: nextTick,
/**
* 数据类
*
* @class
* @param {Object?} data 初始数据
* @param {Data?} parent 父级数据对象
*/
Data: Data,
/**
* 计算表达式的值
*
* @param {Object} expr 表达式对象
* @param {Data} data 数据对象
* @param {Component=} owner 组件对象,用于表达式中filter的执行
* @return {*}
*/
evalExpr: evalExpr,
/**
* 构建类之间的继承关系
*
* @param {Function} subClass 子类函数
* @param {Function} superClass 父类函数
*/
inherits: inherits,
/**
* DataTypes
*
* @type {Object}
*/
DataTypes: DataTypes
};
// export
if (typeof exports === 'object' && typeof module === 'object') {
// For CommonJS
exports = module.exports = san;
}
else if (typeof define === 'function' && define.amd) {
// For AMD
define('san', [], san);
}
else {
// For <script src="..."
root.san = san;
}
// #[begin] devtool
// emitDevtool.start(san);
// #[end]
})(this);
//@ sourceMappingURL=san.modern.js.map | mit |
fedspendingtransparency/data-act-broker-backend | tests/unit/dataactvalidator/test_fabs16_detached_award_financial_assistance.py | 3604 | from tests.unit.dataactcore.factories.staging import DetachedAwardFinancialAssistanceFactory
from tests.unit.dataactvalidator.utils import number_of_errors, query_columns
_FILE = 'fabs16_detached_award_financial_assistance'
def test_column_headers(database):
expected_subset = {'row_number', 'legal_entity_country_code', 'legal_entity_foreign_provi', 'record_type',
'uniqueid_AssistanceTransactionUniqueKey'}
actual = set(query_columns(_FILE, database))
assert expected_subset == actual
def test_success(database):
""" LegalEntityForeignProvinceName must be blank for domestic recipients (i.e., when LegalEntityCountryCode = USA)
or RecordType = 1. Foreign reign recipients don't affect success.
"""
det_award = DetachedAwardFinancialAssistanceFactory(legal_entity_country_code='Japan',
legal_entity_foreign_provi='Yamashiro',
record_type=2, correction_delete_indicatr='')
det_award_2 = DetachedAwardFinancialAssistanceFactory(legal_entity_country_code='UK',
legal_entity_foreign_provi='',
record_type=2, correction_delete_indicatr=None)
det_award_3 = DetachedAwardFinancialAssistanceFactory(legal_entity_country_code='UK',
legal_entity_foreign_provi=None,
record_type=1, correction_delete_indicatr='c')
det_award_4 = DetachedAwardFinancialAssistanceFactory(legal_entity_country_code='USA',
legal_entity_foreign_provi=None,
record_type=3, correction_delete_indicatr='C')
det_award_5 = DetachedAwardFinancialAssistanceFactory(legal_entity_country_code='USA',
legal_entity_foreign_provi='',
record_type=2, correction_delete_indicatr='')
# Ignore correction delete indicator of D
det_award_6 = DetachedAwardFinancialAssistanceFactory(legal_entity_country_code='UK',
legal_entity_foreign_provi='Test',
record_type=1, correction_delete_indicatr='d')
errors = number_of_errors(_FILE, database, models=[det_award, det_award_2, det_award_3, det_award_4, det_award_5,
det_award_6])
assert errors == 0
def test_failure(database):
""" Test failure LegalEntityForeignProvinceName must be blank for domestic recipients (i.e., when
LegalEntityCountryCode = USA) or RecordType = 1
"""
det_award = DetachedAwardFinancialAssistanceFactory(legal_entity_country_code='UsA',
legal_entity_foreign_provi='Test',
record_type=2, correction_delete_indicatr='')
det_award_2 = DetachedAwardFinancialAssistanceFactory(legal_entity_country_code='UK',
legal_entity_foreign_provi='Test',
record_type=1, correction_delete_indicatr='C')
errors = number_of_errors(_FILE, database, models=[det_award, det_award_2])
assert errors == 2
| cc0-1.0 |
lfreneda/cepdb | api/v1/69905166.jsonp.js | 138 | jsonp({"cep":"69905166","logradouro":"Rua Nilo Bezerra","bairro":"Baixada da Habitasa","cidade":"Rio Branco","uf":"AC","estado":"Acre"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/06145126.jsonp.js | 144 | jsonp({"cep":"06145126","logradouro":"Rua Celso Daniel","bairro":"Concei\u00e7\u00e3o","cidade":"Osasco","uf":"SP","estado":"S\u00e3o Paulo"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/13848767.jsonp.js | 162 | jsonp({"cep":"13848767","logradouro":"Rua Benedita Barbosa de Souza","bairro":"Jardim Eldorado","cidade":"Mogi Gua\u00e7u","uf":"SP","estado":"S\u00e3o Paulo"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/88807173.jsonp.js | 169 | jsonp({"cep":"88807173","logradouro":"Rua Maria Borges da Silva","bairro":"Vila S\u00e3o Sebasti\u00e3o","cidade":"Crici\u00fama","uf":"SC","estado":"Santa Catarina"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/25270510.jsonp.js | 150 | jsonp({"cep":"25270510","logradouro":"Avenida Tr\u00eas de Maio","bairro":"Taquara","cidade":"Duque de Caxias","uf":"RJ","estado":"Rio de Janeiro"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/07846080.jsonp.js | 138 | jsonp({"cep":"07846080","logradouro":"Rua Holanda","bairro":"Vila Bela","cidade":"Franco da Rocha","uf":"SP","estado":"S\u00e3o Paulo"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/19025520.jsonp.js | 177 | jsonp({"cep":"19025520","logradouro":"Rua Eduardo Rodrigues de Freitas","bairro":"Parque S\u00e3o Matheus","cidade":"Presidente Prudente","uf":"SP","estado":"S\u00e3o Paulo"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/36309372.jsonp.js | 153 | jsonp({"cep":"36309372","logradouro":"Rua A-1","bairro":"Vila S\u00e3o Bento","cidade":"S\u00e3o Jo\u00e3o Del Rei","uf":"MG","estado":"Minas Gerais"});
| cc0-1.0 |
educobuci/gamelauncher | javascript/main.js | 1961 | const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow
const path = require('path')
const url = require('url')
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600, experimentalFeatures: true})
// and load the index.html of the app.
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, '../html/index.html'),
protocol: 'file:',
slashes: true
}))
// Open the DevTools.
// mainWindow.webContents.openDevTools()
// Emitted when the window is closed.
mainWindow.on('closed', function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow()
}
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
| cc0-1.0 |
lfreneda/cepdb | api/v1/12244615.jsonp.js | 163 | jsonp({"cep":"12244615","logradouro":"Rua Serra das Vertentes","bairro":"Urbanova","cidade":"S\u00e3o Jos\u00e9 dos Campos","uf":"SP","estado":"S\u00e3o Paulo"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/78635000.jsonp.js | 85 | jsonp({"cep":"78635000","cidade":"\u00c1gua Boa","uf":"MT","estado":"Mato Grosso"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/07856040.jsonp.js | 155 | jsonp({"cep":"07856040","logradouro":"Viela Vinte e Sete","bairro":"Parque Vit\u00f3ria","cidade":"Franco da Rocha","uf":"SP","estado":"S\u00e3o Paulo"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/88122435.jsonp.js | 168 | jsonp({"cep":"88122435","logradouro":"Rua Jos\u00e9 Martins Neto","bairro":"Sert\u00e3o do Maruim","cidade":"S\u00e3o Jos\u00e9","uf":"SC","estado":"Santa Catarina"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/24942300.jsonp.js | 164 | jsonp({"cep":"24942300","logradouro":"Rua Francisco Thomas da Silva","bairro":"Ino\u00e3 (Ino\u00e3)","cidade":"Maric\u00e1","uf":"RJ","estado":"Rio de Janeiro"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/71010230.jsonp.js | 152 | jsonp({"cep":"71010230","logradouro":"Quadra QI 2 Conjunto X","bairro":"Guar\u00e1 I","cidade":"Bras\u00edlia","uf":"DF","estado":"Distrito Federal"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/01420903.jsonp.js | 148 | jsonp({"cep":"01420903","logradouro":"Alameda Ja\u00fa","bairro":"Jardim Paulista","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/05503070.jsonp.js | 144 | jsonp({"cep":"05503070","logradouro":"Rua C. Phisalix","bairro":"Butant\u00e3","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/12900410.jsonp.js | 156 | jsonp({"cep":"12900410","logradouro":"Rua Coronel Ladislau Leme","bairro":"Centro","cidade":"Bragan\u00e7a Paulista","uf":"SP","estado":"S\u00e3o Paulo"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/40230074.jsonp.js | 131 | jsonp({"cep":"40230074","logradouro":"Vila Verde","bairro":"Federa\u00e7\u00e3o","cidade":"Salvador","uf":"BA","estado":"Bahia"});
| cc0-1.0 |
lfreneda/cepdb | api/v1/66055171.jsonp.js | 135 | jsonp({"cep":"66055171","logradouro":"Rua Diogo M\u00f3ia","bairro":"Umarizal","cidade":"Bel\u00e9m","uf":"PA","estado":"Par\u00e1"});
| cc0-1.0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.