From 3f81c4a3b7715c42d6f78f3e2eae2eb192738497 Mon Sep 17 00:00:00 2001 From: Jonathan Creamer Date: Mon, 7 Aug 2017 11:46:58 -0500 Subject: [PATCH 01/29] Add HashedModuleIdsPlugin to webpack definitions --- types/webpack/index.d.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/types/webpack/index.d.ts b/types/webpack/index.d.ts index 14517ae3d6..07fa5644b1 100644 --- a/types/webpack/index.d.ts +++ b/types/webpack/index.d.ts @@ -832,6 +832,14 @@ declare namespace webpack { constructor(); } + class HashedModuleIdsPlugin extends Plugin { + constructor(options?: { + hashFunction: string, + hashDigest: string, + hashDigestLength: number + }); + } + class HotModuleReplacementPlugin extends Plugin { constructor(options?: any); } From 009b558381de953302aa347930ab162d9e72c6dc Mon Sep 17 00:00:00 2001 From: Michael Strobel Date: Tue, 8 Aug 2017 11:28:39 +0800 Subject: [PATCH 02/29] [bunyan] add levelFromName and nameFromLevel --- types/bunyan/bunyan-tests.ts | 3 +++ types/bunyan/index.d.ts | 3 +++ 2 files changed, 6 insertions(+) diff --git a/types/bunyan/bunyan-tests.ts b/types/bunyan/bunyan-tests.ts index 657a59c3a8..8b8f88a60c 100644 --- a/types/bunyan/bunyan-tests.ts +++ b/types/bunyan/bunyan-tests.ts @@ -129,3 +129,6 @@ class MyLogger extends Logger { super(options); } } + +const nameLevel: number = Logger.levelFromName['warn']; +const levelName: string = Logger.nameFromLevel[10]; diff --git a/types/bunyan/index.d.ts b/types/bunyan/index.d.ts index bc1dca298d..c622f7777d 100644 --- a/types/bunyan/index.d.ts +++ b/types/bunyan/index.d.ts @@ -210,6 +210,9 @@ declare namespace Logger { const ERROR: number; const FATAL: number; + const levelFromName: { [name: string]: number }; + const nameFromLevel: { [level: number]: string }; + type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal' | number; const stdSerializers: StdSerializers; From 07fef65e03a97bfb5eb096c08c6a85cd736c3aa5 Mon Sep 17 00:00:00 2001 From: Michael Strobel Date: Tue, 8 Aug 2017 13:06:12 +0800 Subject: [PATCH 03/29] [bunyan] Narrow types for levelFromName --- types/bunyan/bunyan-tests.ts | 4 +++- types/bunyan/index.d.ts | 8 +++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/types/bunyan/bunyan-tests.ts b/types/bunyan/bunyan-tests.ts index 8b8f88a60c..d4c4f61e1c 100644 --- a/types/bunyan/bunyan-tests.ts +++ b/types/bunyan/bunyan-tests.ts @@ -130,5 +130,7 @@ class MyLogger extends Logger { } } -const nameLevel: number = Logger.levelFromName['warn']; +const logLevelString: Logger.LogLevelString = 'warn'; +const nameLevel: number = Logger.levelFromName[logLevelString]; +const nameLevel2: number = Logger.levelFromName['warn']; const levelName: string = Logger.nameFromLevel[10]; diff --git a/types/bunyan/index.d.ts b/types/bunyan/index.d.ts index c622f7777d..a59790ebc9 100644 --- a/types/bunyan/index.d.ts +++ b/types/bunyan/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/trentm/node-bunyan // Definitions by: Alex Mikhalev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// @@ -210,10 +211,11 @@ declare namespace Logger { const ERROR: number; const FATAL: number; - const levelFromName: { [name: string]: number }; - const nameFromLevel: { [level: number]: string }; + type LogLevelString = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal'; + type LogLevel = LogLevelString | number; - type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal' | number; + const levelFromName: { [name in LogLevelString]: number }; + const nameFromLevel: { [level: number]: string }; const stdSerializers: StdSerializers; From 87e7467cb77031b676834cc45347a35a26690c0d Mon Sep 17 00:00:00 2001 From: John Gainfort Jr Date: Tue, 8 Aug 2017 10:29:58 -0600 Subject: [PATCH 04/29] fixes mentioned in https://github.com/DefinitelyTyped/DefinitelyTyped/pull/18552 and updated dispatched events and error types/details --- types/hls.js/hls.js-tests.ts | 80 +++++++++++++++++++++-------- types/hls.js/index.d.ts | 98 ++++++++++++++++++++++++++++++------ 2 files changed, 140 insertions(+), 38 deletions(-) diff --git a/types/hls.js/hls.js-tests.ts b/types/hls.js/hls.js-tests.ts index 9af972ebcc..daab1f23f2 100644 --- a/types/hls.js/hls.js-tests.ts +++ b/types/hls.js/hls.js-tests.ts @@ -1,33 +1,69 @@ import * as Hls from 'hls.js'; function process(playlist: string) { - return playlist; + return playlist; } class pLoader extends Hls.DefaultConfig.loader { - constructor(config: Hls.LoaderConfig) { - super(config); - const load = this.load.bind(this); - this.load = (context: Hls.LoaderContext, cfg: Hls.LoaderConfig, callbacks: Hls.LoaderCallbacks) => { - if (context.type === 'manifest') { - const onSuccess = callbacks.onSuccess; - callbacks.onSuccess = (response: Hls.LoaderResponse, stats: Hls.LoaderStats, context: Hls.LoaderContext) => { - response.data = process(response.data as string); - onSuccess(response, stats, context); + constructor(config: Hls.LoaderConfig) { + super(config); + const load = this.load.bind(this); + this.load = (context: Hls.LoaderContext, cfg: Hls.LoaderConfig, callbacks: Hls.LoaderCallbacks) => { + if (context.type === 'manifest') { + const onSuccess = callbacks.onSuccess; + callbacks.onSuccess = (response: Hls.LoaderResponse, stats: Hls.LoaderStats, context: Hls.LoaderContext) => { + response.data = process(response.data as string); + onSuccess(response, stats, context); + }; + } + load(context, config, callbacks); }; - } - load(context, config, callbacks); - }; - } + } } if (Hls.isSupported()) { - const video = document.getElementById('video'); - const hls = new Hls({ pLoader }); - const version: string = Hls.version; - hls.loadSource('http://www.streambox.fr/playlists/test_001/stream.m3u8'); - hls.attachMedia(video); - hls.on(Hls.Events.MANIFEST_PARSED, () => { - video.play(); - }); + const video = document.getElementById('video'); + const hls = new Hls({ pLoader }); + const version: string = Hls.version; + hls.loadSource('http://www.streambox.fr/playlists/test_001/stream.m3u8'); + hls.attachMedia(video); + + hls.on(Hls.Events.MANIFEST_PARSED, () => { + video.play(); + }); + + hls.on(Hls.Events.FRAG_LOAD_ERMERGENCY_ABORTED, (event: string, data: Hls.Data) => { + console.log('frag: ', data.frag); + }); + + hls.on(Hls.Events.ERROR, (event: string, data: Hls.Data) => { + const errorType = data.type; + const errorDetails = data.details; + const errorFatal = data.fatal; + + if (errorDetails) { + switch (errorDetails) { + case Hls.ErrorDetails.FRAG_LOAD_ERROR: + break; + default: + break; + } + } + + if (errorFatal) { + switch (data.type) { + case Hls.ErrorTypes.NETWORK_ERROR: + console.log('fatal network error encoutered, try to recover'); + hls.startLoad(); + break; + case Hls.ErrorTypes.MEDIA_ERROR: + console.log('fatal media error encourted, try to recover'); + hls.recoverMediaError(); + break; + default: + hls.destroy(); + break; + } + } + }); } diff --git a/types/hls.js/index.d.ts b/types/hls.js/index.d.ts index e80eecae3f..80f7bf471e 100644 --- a/types/hls.js/index.d.ts +++ b/types/hls.js/index.d.ts @@ -55,6 +55,11 @@ declare namespace Hls { * data: { tracks : { container, codec, levelCodec, initSegment, metadata } } */ const BUFFER_CODECS: string; + /** + * fired when sourcebuffers have been created + * data: { tracks: tracks } + */ + const BUFFER_CREATED: string; /** * fired when we append a segment to the buffer * data: { segment: segment object } @@ -205,6 +210,11 @@ declare namespace Hls { * data: { frag : fragment object with frag.loaded=stats.loaded, stats : { trequest, tfirst, loaded, total } } */ const FRAG_LOAD_PROGRESS: string; + /** + * identifier for fragment load aborting for emergency switch down + * data: { frag: fragment object } + */ + const FRAG_LOAD_ERMERGENCY_ABORTED: string; /** * fired when a fragment loading is completed * data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length}} @@ -275,12 +285,18 @@ declare namespace Hls { * data: { } */ const DESTROYING: string; + /** + * fired upon stream controller state transitions + * data: { previousState, nextState } + */ + const STREAM_STATE_TRANSITION: string; } /** * Hls error details */ namespace ErrorDetails { + // NETWORK_ERRORS // /** * raised when manifest loading fails because of a network error * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.MANIFEST_LOAD_ERROR, fatal : true, url : manifest URL, response : { code: error code, text: error text }, loader : URL loader } @@ -307,35 +323,57 @@ declare namespace Hls { */ const LEVEL_LOAD_TIMEOUT: string; /** - * raised when level switching fails - * data: { type : OTHER_ERROR, details : Hls.ErrorDetails.LEVEL_SWITCH_ERROR, fatal : false, level : failed level index, reason : failure reason } + * raised when audio track loading fails because of a network error + * data: { type: NETWORK_ERROR, details: Hls.ErrorDetails.AUDIO_TRACK_LOAD_ERROR, fatal: false, url: audio URL, loader: URL loader } */ - const LEVEL_SWITCH_ERROR: string; + const AUDIO_TRACK_LOAD_ERROR: string; + /** + * raised when audio track loading fails because of a timeout + * data: { type: NETWORK_ERROR, details: Hls.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT, fatal: false, url: audio URL, response: { code: error code, text: error text }, loader: URL loader } + */ + const AUDIO_TRACK_LOAD_TIMEOUT: string; /** * raised when fragment loading fails because of a network error * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.FRAG_LOAD_ERROR, fatal : true or false, frag : fragment object, response : { code: error code, text: error text } } */ const FRAG_LOAD_ERROR: string; - /** - * raised upon detection of same fragment being requested in loop - * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.FRAG_LOOP_LOADING_ERROR, fatal : true or false, frag : fragment object } - */ - const FRAG_LOOP_LOADING_ERROR: string; /** * raised when fragment loading fails because of a timeout * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.FRAG_LOAD_TIMEOUT, fatal : true or false, frag : fragment object } */ const FRAG_LOAD_TIMEOUT: string; /** - * raised when fragment parsing fails - * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.FRAG_PARSING_ERROR, fatal : true or false, reason : failure reason } + * raised when decrypt key loading fails because of a network error + * data: { type: NETWORK_ERROR, details: Hls.ErrorDetails.KEY_LOAD_ERROR, fatal: false, frag: fragment object } */ - const FRAG_PARSING_ERROR: string; + const KEY_LOAD_ERROR: string; + /** + * raised when decrypt key loading fails because of timeout + * data: { type: NETWORK_EROR, details: Hls.ErrorDetails.KEY_LOAD_TIMEOUT, fatal: true, frag: fragment object } + */ + const KEY_LOAD_TIMEOUT: string; + + // MEDIA_ERRORS // /** * raised when manifest only contains quality level with codecs incompatible with MediaSource Engine. * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR, fatal : true, url : manifest URL } */ const MANIFEST_INCOMPATIBLE_CODECS_ERROR: string; + /** + * raised upon detection of same fragment being requested in loop + * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.FRAG_LOOP_LOADING_ERROR, fatal : true or false, frag : fragment object } + */ + const FRAG_LOOP_LOADING_ERROR: string; + /** + * raised when fragment decryption fails + * data: { type: MEDIA_ERROR, details: Hls.ErrorDetails.FRAG_DECRYPT_ERROR, fatal: true, reason: failure reason } + */ + const FRAG_DECRYPT_ERROR: string; + /** + * raised when fragment parsing fails + * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.FRAG_PARSING_ERROR, fatal : true or false, reason : failure reason } + */ + const FRAG_PARSING_ERROR: string; /** * raised when MediaSource fails to add new sourceBuffer * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_ADD_CODEC_ERROR, fatal : false, err : error raised by MediaSource, mimeType: mimeType on which the failure happened } @@ -367,6 +405,30 @@ declare namespace Hls { * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_SEEK_OVER_HOLE, fatal : false, hole : hole duration } */ const BUFFER_SEEK_OVER_HOLE: string; + /** + * raised when playback is stuck although currentTime is in a buffered aread + * data: { type: MEDIA_ERROR, details: Hls.ErrorDetails.BUFFERED_STALLED_ERROR, fatal: true } + */ + const BUFFER_NUDGE_ON_STALL: string; + + // MUX_ERROR // + /** + * raised when memory allocation fails during remuxing + * data: { type: MUX_ERROR, details: Hls.ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes: mdat size, reason: failure reason } + */ + const REMUX_ALLOC_ERROR: string; + + // OTHER_ERROR // + /** + * raised when level switching fails + * data: { type : OTHER_ERROR, details : Hls.ErrorDetails.LEVEL_SWITCH_ERROR, fatal : false, level : failed level index, reason : failure reason } + */ + const LEVEL_SWITCH_ERROR: string; + /** + * raised when an exception occurs in an internal hls.js event handler + * data: { type: OTHER_ERROR, details: Hls.ErrorDetails.INTERNAL_EXCEPTION, fatal: true or false, event: event object or string, error: { message: error message } } + */ + const INTERNAL_EXCEPTION: string; } /** @@ -381,6 +443,10 @@ declare namespace Hls { * media/video related errors */ const MEDIA_ERROR: string; + /** + * muxing related errors + */ + const MUX_ERROR: string; /** * all other erros */ @@ -1366,7 +1432,7 @@ declare namespace Hls { /** * levelDetails object */ - details?: LevelDetails; + details?: string; /** * PTS drift observed when parsing last fragment */ @@ -1659,24 +1725,24 @@ declare class Hls { * * set to -1 for automatic level selection */ - nextLevel: Hls.Level; + nextLevel: number; /** * get: return last loaded fragment quality level * set: quality level for next loaded fragment * set to -1 for automatic level selection */ - loadLevel: Hls.Level; + loadLevel: number; /** * get: return quality level that will be used to load next fragment * set: force quality level for next loaded fragment * quality level will be forced only for that fragment * after a fragment at this quality level has been loaded, hls.loadLevel will prevail */ - nextLoadLevel: Hls.Level; + nextLoadLevel: number; /** * first level index (index of first level appearing in Manifest. it is usually defined as start level hint for player) */ - firstLevel: Hls.Level; + firstLevel: number; /** * array of audio tracks exposed in manifest */ From 751d76cfc574b195a760e59aae0f3f89e6c4b334 Mon Sep 17 00:00:00 2001 From: "Walton, Reese" Date: Tue, 8 Aug 2017 18:53:37 -0400 Subject: [PATCH 05/29] noResultsText can be React Component --- types/react-select/index.d.ts | 4 ++-- types/react-select/react-select-tests.tsx | 8 ++++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/types/react-select/index.d.ts b/types/react-select/index.d.ts index abfed81047..877b2557a0 100644 --- a/types/react-select/index.d.ts +++ b/types/react-select/index.d.ts @@ -284,7 +284,7 @@ declare namespace ReactSelectClass { * placeholder displayed when there are no matching search results or a falsy value to hide it * @default "No results found" */ - noResultsText?: string; + noResultsText?: string | JSX.Element; /** * onBlur handler: function (event) {} */ @@ -494,7 +494,7 @@ declare namespace ReactSelectClass { /** * placeholder displayed when there are no matching search results (shared with Select) */ - noResultsText?: string; + noResultsText?: string | JSX.Element; /** * field placeholder; displayed when there's no value (shared with Select) */ diff --git a/types/react-select/react-select-tests.tsx b/types/react-select/react-select-tests.tsx index 13d64d32ce..8b834d1bb6 100644 --- a/types/react-select/react-select-tests.tsx +++ b/types/react-select/react-select-tests.tsx @@ -171,4 +171,12 @@ describe("Examples", () => { valueRenderer={props => null} />; }); + + it("No Results renderer with string", () => { + ; + }); + + it("No Results renderer with element", () => { + no results} />; + }); }); From cda63c85ed5a8b84393914a4f68a4772c8528d42 Mon Sep 17 00:00:00 2001 From: Michael Strobel Date: Wed, 9 Aug 2017 08:20:19 +0800 Subject: [PATCH 06/29] Add minimum TypeScript version 2.1 to types depending on bunyan --- types/bunyan-config/index.d.ts | 1 + types/bunyan-logentries/index.d.ts | 1 + types/easy-api-request/index.d.ts | 1 + types/easy-xapi-utils/index.d.ts | 2 +- types/easy-xapi/index.d.ts | 2 +- 5 files changed, 5 insertions(+), 2 deletions(-) diff --git a/types/bunyan-config/index.d.ts b/types/bunyan-config/index.d.ts index 0ff84fd9d2..ebcddcd50d 100644 --- a/types/bunyan-config/index.d.ts +++ b/types/bunyan-config/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/LSEducation/bunyan-config // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/types/bunyan-logentries/index.d.ts b/types/bunyan-logentries/index.d.ts index 9a2a5c3fb9..33057d768b 100644 --- a/types/bunyan-logentries/index.d.ts +++ b/types/bunyan-logentries/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/nemtsov/node-bunyan-logentries // Definitions by: Aymeric Beaumet // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/types/easy-api-request/index.d.ts b/types/easy-api-request/index.d.ts index f04b68be3a..1b3606ccb1 100644 --- a/types/easy-api-request/index.d.ts +++ b/types/easy-api-request/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/DeadAlready/easy-api-request // Definitions by: Karl Düüna // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/types/easy-xapi-utils/index.d.ts b/types/easy-xapi-utils/index.d.ts index a4e5f568e6..a4b219bf43 100644 --- a/types/easy-xapi-utils/index.d.ts +++ b/types/easy-xapi-utils/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/DeadAlready/easy-xapi-utils // Definitions by: Karl Düüna // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.1 /// /// diff --git a/types/easy-xapi/index.d.ts b/types/easy-xapi/index.d.ts index f4a9e09391..aa4c0286cf 100644 --- a/types/easy-xapi/index.d.ts +++ b/types/easy-xapi/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/DeadAlready/easy-xapi // Definitions by: Karl Düüna // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.1 /// /// From f668da13f40cd2bc7ac2e21aea19fb11c8559432 Mon Sep 17 00:00:00 2001 From: Izik Lisbon Date: Wed, 9 Aug 2017 00:01:33 -0700 Subject: [PATCH 07/29] Sequelize is using Validator to validate that a string is a UUID. Validator supports 4 versions of UUID: https://github.com/chriso/validator.js/blob/b59133b1727b6af355b403a9a97a19226cceb34b/lib/isUUID.js#L14-L19 Update Sequelize's typescript to include `all` and change `number` type to a more specific type (3|4|5). Update Validator's typescript to be more specific. instead of `string | number` set the enum values (3|4|5|all) --- types/sequelize/index.d.ts | 2 +- types/sequelize/v3/index.d.ts | 2 +- types/validator/index.d.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/types/sequelize/index.d.ts b/types/sequelize/index.d.ts index e767118394..5bb602388a 100644 --- a/types/sequelize/index.d.ts +++ b/types/sequelize/index.d.ts @@ -4765,7 +4765,7 @@ declare namespace sequelize { /** * only allow uuids */ - isUUID?: number | { msg: string, args: number }; + isUUID?: 3|4|5|"3"|"4"|"5"|"all" | { msg: string, args: number }; /** * only allow date strings diff --git a/types/sequelize/v3/index.d.ts b/types/sequelize/v3/index.d.ts index 0e3a27a4e4..6d55a66b5a 100644 --- a/types/sequelize/v3/index.d.ts +++ b/types/sequelize/v3/index.d.ts @@ -4661,7 +4661,7 @@ declare namespace sequelize { /** * only allow uuids */ - isUUID?: number | { msg: string, args: number }; + isUUID?: 3|4|5|"3"|"4"|"5"|"all" | { msg: string, args: number }; /** * only allow date strings diff --git a/types/validator/index.d.ts b/types/validator/index.d.ts index 7c7283ebee..4dfa7dff1c 100644 --- a/types/validator/index.d.ts +++ b/types/validator/index.d.ts @@ -156,7 +156,7 @@ declare namespace ValidatorJS { isURL(str: string, options?: IsURLOptions): boolean; // check if the string is a UUID. Must be one of ['3', '4', '5', 'all'], default is all. - isUUID(str: string, version?: string | number): boolean; + isUUID(str: string, version?: 3|4|5|"3"|"4"|"5"|"all"): boolean; // check if the string is uppercase. isUppercase(str: string): boolean; From 97427521b22bd0e28bb059650e4bd9eb44079fd5 Mon Sep 17 00:00:00 2001 From: Joel Shepherd Date: Wed, 9 Aug 2017 23:50:28 +1000 Subject: [PATCH 08/29] Adding new screenfull methods --- types/screenfull/index.d.ts | 11 +++++++--- types/screenfull/screenfull-tests.ts | 31 ++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/types/screenfull/index.d.ts b/types/screenfull/index.d.ts index ad5c76037b..6d82971ea5 100644 --- a/types/screenfull/index.d.ts +++ b/types/screenfull/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for screenfull.js 3.2.0 +// Type definitions for screenfull.js 3.3.0 // Project: https://github.com/sindresorhus/screenfull.js -// Definitions by: Ilia Choly , lionelb +// Definitions by: Ilia Choly +// lionelb +// Joel Shepherd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - declare var screenfull: IScreenfull; interface IScreenfullRaw { @@ -25,6 +26,10 @@ interface IScreenfull { exit(): void; onchange(handler: () => void): void; onerror(handler: (event: Event) => void): void; + on(name: EventNameMap, handler: (event: Event) => void): void; + off(name: EventNameMap, handler: (event: Event) => void): void; } +type EventNameMap = 'change' | 'error'; + export = screenfull; diff --git a/types/screenfull/screenfull-tests.ts b/types/screenfull/screenfull-tests.ts index e5efa0bcc0..efb03da1ab 100644 --- a/types/screenfull/screenfull-tests.ts +++ b/types/screenfull/screenfull-tests.ts @@ -50,6 +50,7 @@ function test_raw_error() { }); } } + function test_detect_change() { if (screenfull.enabled) { screenfull.onchange(function () { @@ -70,6 +71,36 @@ function test_detect_error() { } } +function test_listener_on() { + if (screenfull.enabled) { + screenfull.on('change', function () { + if (screenfull.isFullscreen) { + console.log('fullscreen'); + } else { + console.log('not fullscreen'); + } + }); + screenfull.on('error', function (event) { + console.error('Failed to enable fullscreen', event); + }) + } +} + +function test_listener_off() { + if (screenfull.enabled) { + screenfull.off('change', function () { + if (screenfull.isFullscreen) { + console.log('fullscreen'); + } else { + console.log('not fullscreen'); + } + }); + screenfull.off('error', function (event) { + console.error('Failed to enable fullscreen', event); + }) + } +} + function test_access_element() { var elem = document.getElementById('target'); if (screenfull.enabled) { From 2eff7af8765e9e9333948a83067dee5b22d9d9c1 Mon Sep 17 00:00:00 2001 From: Mikko Vuorinen Date: Wed, 9 Aug 2017 14:58:24 +0100 Subject: [PATCH 09/29] [hellojs] Update definition for 1.15.1 (#18318) * [hellojs] Add/modify tests for latest version * [hellojs] Update definition to latest version Modify interfaces to reflect version 1.15.1 codebase. Add definition for hello.util. Simplify thenable definition. * [hellojs] Add missing method definition Include api() definition when calling with options object. * [hellojs] Add tslint.json and fix linting errors * [hellojs] Use TypeScript 2.3 Set TypeScript version to 2.3 to avoid errors with object-type. * [hellojs] Switch to PromiseLike https://github.com/DefinitelyTyped/DefinitelyTyped/issues/17251 * [hellojs] Remove unused interface * [hellojs] Rename namespace and add export Add default export for static hello-object. Rename namespace to hello so that the namespace as well as the hello-object will be exported. * [hellojs] Remove redundant 'export' keyword --- types/hellojs/hellojs-tests.ts | 135 +++++++++++++++-- types/hellojs/index.d.ts | 265 ++++++++++++++++++--------------- types/hellojs/tslint.json | 1 + 3 files changed, 269 insertions(+), 132 deletions(-) create mode 100644 types/hellojs/tslint.json diff --git a/types/hellojs/hellojs-tests.ts b/types/hellojs/hellojs-tests.ts index 9883c7a529..478e67fa94 100644 --- a/types/hellojs/hellojs-tests.ts +++ b/types/hellojs/hellojs-tests.ts @@ -1,7 +1,124 @@ +import * as hello from 'hellojs'; +// Test code copied from Azure AD B2C sample app at +// https://github.com/Azure-Samples/active-directory-b2c-javascript-hellojs-singlepageapp/tree/cd5982f09a7bff0a72b7b4e44c4b5190b09e20fa +hello.init({ + serviceName: { + name: 'Test', + oauth: { + version: 2, + auth: '', + grant: '' + }, + refresh: true, + scope_delim: ' ', + logout: () => { + let id_token = hello('networkName').getAuthResponse().id_token; + hello.utils.store('networkName', null); + }, + xhr: (p) => { + let token = p.query.access_token; + delete p.query.access_token; + if (token) { + p.headers = { + Authorization: 'Bearer ' + token, + }; + } + + if (p.method === 'post' || p.method === 'put') { + if (typeof (p.data) === 'object') { + try { + p.data = JSON.stringify(p.data); + p.headers['content-type'] = 'application/json'; + } catch (e) { } + } + } else if (p.method === 'patch') { + hello.utils.extend(p.query, p.data); + p.data = null; + } + return true; + }, + form: false + } +}); + +// Test code copied from hello.js built-in modules at +// https://github.com/MrSwitch/hello.js/blob/v1.15.1/src/modules/joinme.js +hello.init({ + joinme: { + name: 'join.me', + oauth: { + version: 2, + auth: '', + grant: '' + }, + refresh: false, + scope: { + basic: 'user_info', + user: 'user_info', + scheduler: 'scheduler', + start: 'start_meeting', + email: '', + friends: '', + share: '', + publish: '', + photos: '', + publish_files: '', + files: '', + videos: '', + offline_access: '' + }, + scope_delim: ' ', + login: (p) => { + p.options.popup.width = 400; + p.options.popup.height = 700; + }, + base: 'https://api.join.me/v1/', + get: { + me: 'user', + meetings: 'meetings', + 'meetings/info': 'meetings/@{id}' + }, + post: { + 'meetings/start/adhoc': (p, callback) => { + callback('meetings/start'); + }, + }, + patch: { + 'meetings/update': (p, callback) => { + callback('meetings/' + p.data.meetingId); + } + }, + del: { + 'meetings/delete': 'meetings/@{id}' + }, + wrap: { + me: (o, headers) => { + if (!o.email) { + return o; + } + + o.name = o.fullName; + o.first_name = o.name.split(' ')[0]; + o.last_name = o.name.split(' ')[1]; + o.id = o.email; + + return o; + }, + default: (o, headers) => { + return o; + } + }, + xhr: (p, qs) => { + let token = qs.access_token; + delete qs.access_token; + p.headers.Authorization = 'Bearer ' + token; + } + } +}); hello.init({ - 'facebook': '', + facebook: '', }, { redirect_uri: 'hello.html', display: 'page', @@ -19,30 +136,28 @@ hello('facebook').logout(); hello.on('auth.login', auth => { alert('log to ' + auth.network); }).on('auth.logout', auth => { - alert('unlog from ' + auth.network); - }); + alert('unlog from ' + auth.network); +}); hello.getAuthResponse('facebook'); hello.login('facebook', null, () => { - var req = hello.getAuthResponse('facebook'); + let req = hello.getAuthResponse('facebook'); }); hello.logout('facebook'); -var serviceInfo = hello.service('facebook'); - -hello("facebook").api("me").success(function(json) { +hello("facebook").api("me").then((json) => { alert("Your name is " + json.name); -}).error(function () { +}, () => { alert("Whoops!"); }); -var sessionstart = function () { +let sessionstart = () => { alert("Session has started"); }; hello.on("auth.login", sessionstart); hello.off("auth.login", sessionstart); -hello("facebook").login({ scope: "friends,photos,publish" }); \ No newline at end of file +hello("facebook").login({ scope: "friends,photos,publish" }); diff --git a/types/hellojs/index.d.ts b/types/hellojs/index.d.ts index ec07219cc3..16b19afb4a 100644 --- a/types/hellojs/index.d.ts +++ b/types/hellojs/index.d.ts @@ -1,127 +1,148 @@ -// Type definitions for hello.js 0.2 +// Type definitions for hello.js 1.15 // Project: http://adodson.com/hello.js/ // Definitions by: Pavel Zika +// Mikko Vuorinen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -interface HelloJSLoginOptions { - redirect_uri?: string; - display?: string; - scope?: string; - response_type?: string; - force?: boolean; - oauth_proxy?: string; - timeout?: number; - default_service?: string; -} - -interface HelloJSLogoutOptions { - force?: boolean; -} - -interface HelloJSImmediateSuccessCB { - (value: T): TP; -} - -interface HelloJSImmediateErrorCB { - (err: any): TP; -} - -interface HelloJSDeferredSuccessCB { - (value: T): HelloJSThenable; -} - -interface HelloJSDeferredErrorCB { - (error: any): HelloJSThenable; -} - -interface HelloJSThenable { - then( - successCB?: HelloJSDeferredSuccessCB, - errorCB?: HelloJSDeferredErrorCB - ): HelloJSThenable; - - then( - successCB?: HelloJSDeferredSuccessCB, - errorCB?: HelloJSImmediateErrorCB - ): HelloJSThenable; - - then( - successCB?: HelloJSImmediateSuccessCB, - errorCB?: HelloJSDeferredErrorCB - ): HelloJSThenable; - - then( - successCB?: HelloJSImmediateSuccessCB, - errorCB?: HelloJSImmediateErrorCB - ): HelloJSThenable; -} - -interface HelloJSEvent extends HelloJSThenable { - on(event: string, callback: (auth: HelloJSEventArgument) => void): HelloJSStatic; - off(event: string, callback: (auth: HelloJSEventArgument) => void): HelloJSStatic; - findEvents(event: string, callback: (name: string, index: number) => void): void; - emit(event: string, data: any): HelloJSStatic; - emitAfter(): HelloJSStatic; - success(callback: (json?: any) => void): HelloJSStatic; - error(callback: (json?: any) => void): HelloJSStatic; - complete(callback: (json?: any) => void): HelloJSStatic; -} - - - -interface HelloJSEventArgument { - network: string; - authResponse?: any; -} - - -interface HelloJSStatic extends HelloJSEvent { - init(serviceAppIds: { [id: string]: string; }, options?: HelloJSLoginOptions): void; - login(network: string, options?: HelloJSLoginOptions, callback?: () => void): HelloJSStatic; - logout(network: string, options?: HelloJSLogoutOptions, callback?: () => void): HelloJSStatic; - getAuthResponse(network: string): any; - service(network: string): HelloJSServiceDef; - settings: HelloJSLoginOptions; - (network: string): HelloJSStaticNamed; - init(servicesDef: { [id: string]: HelloJSServiceDef; }): void; -} - -interface HelloJSStaticNamed { - login(option?: HelloJSLoginOptions, callback?: () => void): void; - logout(callback?: () => void): void; - getAuthResponse(): any; - api(path?: string, method?: string, data?: any, callback?: (json?: any) => void): HelloJSStatic; -} - -interface HelloJSOAuthDef { - version: number; - auth: string; - request: string; - token: string; -} - -interface HelloJSServiceDef { - name: string; - oauth: HelloJSOAuthDef; - scope?: { [id: string]: string; }; - scope_delim?: string; - autorefresh?: boolean; - base?: string; - root?: string; - get?: { [id: string]: any; }; - post?: { [id: string]: any; }; - del?: { [id: string]: string; }; - put?: { [id: string]: any; }; - wrap?: { [id: string]: (par: any) => void; }; - xhr?: (par: any) => void; - jsonp?: (par: any) => void; - form?: (par: any) => void; - api?: (...par: any[]) => void; -} - -declare var hello: HelloJSStatic; - -// Support AMD require -declare module 'hellojs' { - export = hello; +export = hello; + +declare const hello: hello.HelloJSStatic; + +declare namespace hello { + interface HelloJSUtils { + extend(r: object, ...a: any[]): any; + error(code: number, message: string): { code: number, message: string }; + qs(url: string, params?: object, formatFunction?: (param: any) => string): string; + param(o: object, formatFunction?: (param: any) => string): string; + param(s: string, formatFunction?: (param: string) => any): any; + store(name?: string, value?: any): any; + append(node: string | HTMLElement, attr: object | undefined | null, target: string | HTMLElement): HTMLElement; + iframe(src: string, redirectUri?: string): void; + merge(...a: any[]): any; + args(o: object, args: object): any | false; + url(): Location; + url(path: string): URL | HTMLAnchorElement; + diff(a: any[], b: any[]): any[]; + diffKey(a: any[], b: any[]): any[]; + unique(a: any[]): any[]; + isEmpty(obj: any): boolean; + Event: HelloJSEvent; + globalEvent(callback: () => void, guid?: string): string; + popup(url: string, redirectUri?: string, options?: object): Window | any; + responseHandler(window: Window, parent?: any): void; + } + + // API utilities + interface HelloJSUtils { + request(p: object, callback: HelloJSResponseCallback): void; + request_cors(callback: HelloJSResponseCallback): boolean; + domInstance(type: string, data: any): boolean; + clone(obj: T): T; + xhr(method: string, url: string, headers: object, data: any, callback: HelloJSResponseCallback): XMLHttpRequest; + jsonp(url: string, callback: () => void, callbackID?: string, timeout?: number): void; + post(url: string, data: any, options: object, callback: HelloJSResponseCallback, callbackID?: string, timeout?: number): void; + hasBinary(data: any): boolean; + isBinary(data: any): boolean; + toBlob(dataURI: string): Blob | string; + dataToJSON(p: any): any; + nodeListToJSON(nodelist: NodeList): any; + } + + type HelloJSResponseCallback = (r: any, headers: any) => void; + + type HelloJSTokenResponseType = "token" | "code"; + + interface HelloJSLoginOptions { + redirect_uri?: string; + display?: string; + scope?: string; + response_type?: HelloJSTokenResponseType; + force?: boolean | null; + oauth_proxy?: string; + timeout?: number; + default_service?: string; + popup?: HelloJSPopupOptions; + state?: string; + } + + interface HelloJSLogoutOptions { + force?: boolean; + } + + interface HelloJSPopupOptions { + resizable: number; + scrollbars: number; + width: number; + height: number; + } + + interface HelloJSEvent { + on(event: string, callback: (auth: HelloJSEventArgument) => void): HelloJSStatic; + off(event: string, callback: (auth: HelloJSEventArgument) => void): HelloJSStatic; + findEvents(event: string, callback: (name: string, index: number) => void): void; + emit(event: string, data: any): HelloJSStatic; + emitAfter(): HelloJSStatic; + } + + interface HelloJSEventArgument { + network: string; + authResponse?: any; + } + + interface HelloJSStatic extends HelloJSEvent { + init(serviceAppIds: { [id: string]: string; }, options?: HelloJSLoginOptions): void; + init(servicesDef: { [id: string]: HelloJSServiceDef; }): void; + login(callback: () => void): PromiseLike; + login(options?: HelloJSLoginOptions, callback?: () => void): PromiseLike; + login(network?: string, options?: HelloJSLoginOptions, callback?: () => void): PromiseLike; + logout(callback?: () => void): PromiseLike; + logout(options?: HelloJSLogoutOptions, callback?: () => void): PromiseLike; + logout(network?: string, options?: HelloJSLogoutOptions, callback?: () => void): PromiseLike; + getAuthResponse(network?: string): any; + settings: HelloJSLoginOptions; + (network: string): HelloJSStatic; + utils: HelloJSUtils; + api(options: object): PromiseLike; + api(path?: string, method?: string, data?: object, callback?: (json: any) => void): PromiseLike; + api(path?: string, query?: object, method?: string, data?: object, timeout?: number, callback?: (json: any) => void): PromiseLike; + } + + interface HelloJSOAuthDef { + version: string | number; + auth?: string; + } + + interface HelloJSOAuth2Def extends HelloJSOAuthDef { + grant?: string; + response_type?: HelloJSTokenResponseType; + } + + interface HelloJSOAuth1Def extends HelloJSOAuthDef { + request?: string; + token?: string; + } + + type HelloJSUrlMappingFunction = (p: any, callback: (url: string) => void) => void; + + interface HelloJSServiceDef { + name?: string; + oauth: HelloJSOAuth2Def | HelloJSOAuth1Def; + scope?: { [id: string]: string; }; + scope_delim?: string; + refresh?: boolean; + base?: string; + root?: string; + get?: { [id: string]: string | HelloJSUrlMappingFunction }; + post?: { [id: string]: string | HelloJSUrlMappingFunction }; + del?: { [id: string]: string | HelloJSUrlMappingFunction }; + put?: { [id: string]: string | HelloJSUrlMappingFunction }; + patch?: { [id: string]: string | HelloJSUrlMappingFunction }; + wrap?: { [id: string]: (r: any, headers: any, p: any) => void; }; + xhr?(p: any, query: any): void; + jsonp?: ((p: any, query: any) => void) | boolean; + form?: ((p: any, query: any) => void) | boolean; + login?(p: any): void; + logout?: ((callback: () => void | string) => void) | string; + } } diff --git a/types/hellojs/tslint.json b/types/hellojs/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/hellojs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file From 245998780e61d37bbbc3e8358a114b0236c99cb6 Mon Sep 17 00:00:00 2001 From: Torgeir Hovden Date: Wed, 9 Aug 2017 16:02:00 +0200 Subject: [PATCH 10/29] Add missing option callback arg to setProps (#18215) * Add missing option callback arg to setProps * Allow callback only on ReactWrapper, ref. @MartynasZilinskas comment --- types/enzyme/enzyme-tests.tsx | 2 +- types/enzyme/index.d.ts | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/types/enzyme/enzyme-tests.tsx b/types/enzyme/enzyme-tests.tsx index 083cee54b2..cd3ffe9a68 100644 --- a/types/enzyme/enzyme-tests.tsx +++ b/types/enzyme/enzyme-tests.tsx @@ -599,7 +599,7 @@ function ReactWrapperTest() { } function test_setProps() { - reactWrapper = reactWrapper.setProps({ stringProp: 'foo' }); + reactWrapper = reactWrapper.setProps({ stringProp: 'foo' }, () => {}); } function test_setContext() { diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index e1fdba2027..3b0ae6ef13 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -6,6 +6,7 @@ // jwbay // huhuanming // MartynasZilinskas +// Torgeir Hovden // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -246,7 +247,6 @@ export interface CommonWrapper { * * NOTE: can only be called on a wrapper instance that is also the root instance. * @param props - * @param [callback] */ setProps(props: Pick): this; @@ -541,6 +541,20 @@ export interface ReactWrapper extends CommonWrapper { * Returns a wrapper with the direct parent of the node in the current wrapper. */ parent(): ReactWrapper; + + /** + * A method that sets the props of the root component, and re-renders. Useful for when you are wanting to test + * how the component behaves over time with changing props. Calling this, for instance, will call the + * componentWillReceiveProps lifecycle method. + * + * Similar to setState, this method accepts a props object and will merge it in with the already existing props. + * Returns itself. + * + * NOTE: can only be called on a wrapper instance that is also the root instance. + * @param props + * @param [callback] + */ + setProps(props: Pick, callback?: () => void): this; } export interface ShallowRendererProps { From ba5f95bae7ed89de3c930cc6bc2255e2df139a25 Mon Sep 17 00:00:00 2001 From: mad-mike Date: Wed, 9 Aug 2017 16:04:48 +0200 Subject: [PATCH 11/29] [@sap/xsenv] Add types for @sap/xsenv module (#18605) * Add types for @sap/xsenv module (available on SAP Service Marketplace or https://npm.sap.com) * Fix linter errors * Switch to path mapping instead of declare module * Rework links to documentation * Fix linter message --- types/sap__xsenv/index.d.ts | 54 ++++++++++++++++++++++++++++ types/sap__xsenv/sap__xsenv-tests.ts | 52 +++++++++++++++++++++++++++ types/sap__xsenv/tsconfig.json | 27 ++++++++++++++ types/sap__xsenv/tslint.json | 1 + 4 files changed, 134 insertions(+) create mode 100644 types/sap__xsenv/index.d.ts create mode 100644 types/sap__xsenv/sap__xsenv-tests.ts create mode 100644 types/sap__xsenv/tsconfig.json create mode 100644 types/sap__xsenv/tslint.json diff --git a/types/sap__xsenv/index.d.ts b/types/sap__xsenv/index.d.ts new file mode 100644 index 0000000000..3858f77feb --- /dev/null +++ b/types/sap__xsenv/index.d.ts @@ -0,0 +1,54 @@ +// Type definitions for @sap/xsenv 1.2 +// Project: https://help.sap.com/hana_platform +// Definitions by: [Michael Müller] +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// For more information see the Developer Guide for SAP HANA XS Advanced Model run time. +// The module is available on the https://npm.sap.com registry. + +export function loadEnv(jsonFile?: string): void; +export function readCFServices(): any; + +export type ServiceFilter = string | { name?: string; label?: string; tag?: string; plan?: string } | ((service: any) => boolean); + +/** + * Reads service configuration from CloudFoundry environment variable VCAP_SERVICES. + * + * @param filter Filter used to find a bound Cloud Foundry service, see filterCFServices + * @return credentials property of found service + * @throws Error in case no or multiple matching services are found + */ +export function cfServiceCredentials(filter: ServiceFilter): any; +/** + * Returns an array of Cloud Foundry services matching the given filter. + * + * @param filter {(string|Object|function)} + * - if string, returns the service with the same service instance name (name property) + * - if Object, should have some of these properties [name, label, tag, plan] and returns all services + * where all of the given properties match. Given tag matches if it is present in the tags array. + * - if function, should take a service object as argument and return true only if it matches the filter + * @returns Arrays of matching service objects, empty if no matches + */ +export function filterCFServices(filter: ServiceFilter): any; + +/** + * Looks up and returns bound Cloud Foundry services. + * + * If a service is not found in VCAP_SERVICES, returns default service configuration loaded from a JSON file. + * + * @param query {object} describes requested Cloud Foundry services, each property value is a filter + * as described in filterCFServices. + * @param servicesFile {string} path to JSON file to load default service configuration (default is default-services.json). + * If null, do not load default service configuration. + * + * @returns {object} with the same properties as in query argument where the value of each + * property is the respective service credentials object. + * @throws Error, if for some of the requested services no or multiple instances are found; Error, if query parameter is not provided + */ +export function getServices(query: any, servicesFile?: string): any; + +/** + * @deprecated use loadCertificates instead + */ +export function loadCaCert(): void; + +export function loadCertificates(certPath?: string): any; diff --git a/types/sap__xsenv/sap__xsenv-tests.ts b/types/sap__xsenv/sap__xsenv-tests.ts new file mode 100644 index 0000000000..4e7b6a5134 --- /dev/null +++ b/types/sap__xsenv/sap__xsenv-tests.ts @@ -0,0 +1,52 @@ +import xsenv = require('@sap/xsenv'); + +// code examples from the README.MD + +function test1() { + const services = xsenv.readCFServices(); + services.aservice.credentials; // prints { host: '...', port: '...', user: '...', passwrod: '...', ... } +} + +function test2() { + const services = xsenv.readCFServices(); + const svc = services['process.env.SERVICE_NAME']; +} + +function test3() { + const svc = xsenv.cfServiceCredentials({ tag: 'hdb' }); + // console.log(svc); // prints { host: '...', port: '...', user: '...', passwrod: '...', ... } +} + +function test4() { + const services = xsenv.getServices({ + hana: { tag: 'hdb' }, + scheduler: { label: 'jobs' } + }); + + const hanaCredentials = services.hana; + const schedulerCredentials = services.scheduler; +} + +function test5() { + xsenv.cfServiceCredentials('hana'); + xsenv.cfServiceCredentials({ tag: 'relational' }); + xsenv.cfServiceCredentials({ label: 'hana', plan: 'shared' }); + xsenv.cfServiceCredentials((service: any) => { + return /shared/.test(service.plan) && /hdi/.test(service.label); + }); +} + +function test6() { + xsenv.loadEnv(); + // console.log(process.env.PORT); // prints 3000 + xsenv.cfServiceCredentials('hana-R90'); // prints { host: 'myhana, port: '30015', user: 'SYSTEM', password: 'secret' } +} + +function test7() { + xsenv.loadEnv('myenv.json'); +} + +function test8() { + xsenv.loadCertificates(); + xsenv.loadCaCert(); +} diff --git a/types/sap__xsenv/tsconfig.json b/types/sap__xsenv/tsconfig.json new file mode 100644 index 0000000000..f338a2e5d8 --- /dev/null +++ b/types/sap__xsenv/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@sap/xsenv": [ + "sap__xsenv" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sap__xsenv-tests.ts" + ] +} \ No newline at end of file diff --git a/types/sap__xsenv/tslint.json b/types/sap__xsenv/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sap__xsenv/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 2ca09c9734e9738a8adefb40d2bbc3a342f8e80e Mon Sep 17 00:00:00 2001 From: Jonathan Creamer Date: Wed, 9 Aug 2017 09:50:18 -0500 Subject: [PATCH 12/29] Add tests, run lint --- types/webpack/index.d.ts | 7 ++++--- types/webpack/webpack-tests.ts | 6 ++++++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/types/webpack/index.d.ts b/types/webpack/index.d.ts index 07fa5644b1..afbbbf3928 100644 --- a/types/webpack/index.d.ts +++ b/types/webpack/index.d.ts @@ -5,6 +5,7 @@ // Boris Cherny // Tommy Troy Lin // Mohsen Azimi +// Jonathan Creamer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -834,9 +835,9 @@ declare namespace webpack { class HashedModuleIdsPlugin extends Plugin { constructor(options?: { - hashFunction: string, - hashDigest: string, - hashDigestLength: number + hashFunction?: string, + hashDigest?: string, + hashDigestLength?: number }); } diff --git a/types/webpack/webpack-tests.ts b/types/webpack/webpack-tests.ts index 6c7095483d..7db91f59d9 100644 --- a/types/webpack/webpack-tests.ts +++ b/types/webpack/webpack-tests.ts @@ -424,6 +424,12 @@ plugin = new webpack.LoaderOptionsPlugin({ plugin = new webpack.EnvironmentPlugin(['a', 'b']); plugin = new webpack.EnvironmentPlugin({a: true, b: 'c'}); plugin = new webpack.ProgressPlugin((percent: number, message: string) => {}); +plugin = new webpack.HashedModuleIdsPlugin(); +plugin = new webpack.HashedModuleIdsPlugin({ + hashFunction: 'sha256', + hashDigest: 'hex', + hashDigestLength: 20 +}); // // http://webpack.github.io/docs/node.js-api.html From a14233daa63fffb3b55bc73be9771805267a6c34 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Wed, 9 Aug 2017 19:29:07 +0200 Subject: [PATCH 13/29] [del] add typings for v3, enable strict null checks (#18785) --- types/del/del-tests.ts | 14 ++++++++------ types/del/index.d.ts | 7 +++++-- types/del/tsconfig.json | 4 ++-- types/del/v2/del-tests.ts | 37 +++++++++++++++++++++++++++++++++++++ types/del/v2/index.d.ts | 19 +++++++++++++++++++ types/del/v2/tsconfig.json | 25 +++++++++++++++++++++++++ types/del/v2/tslint.json | 1 + 7 files changed, 97 insertions(+), 10 deletions(-) create mode 100644 types/del/v2/del-tests.ts create mode 100644 types/del/v2/index.d.ts create mode 100644 types/del/v2/tsconfig.json create mode 100644 types/del/v2/tslint.json diff --git a/types/del/del-tests.ts b/types/del/del-tests.ts index 09702c4b39..fc6c63b6fa 100644 --- a/types/del/del-tests.ts +++ b/types/del/del-tests.ts @@ -3,8 +3,10 @@ import del = require("del"); let paths = ["build", "dist/**/*.js"]; del(["tmp/*.js", "!tmp/unicorn.js"]); - del(["tmp/*.js", "!tmp/unicorn.js"], {force: true}); +del(["tmp/*.js", "!tmp/unicorn.js"], {dryRun: true}); +del(["tmp/*.js", "!tmp/unicorn.js"], {concurrency: 20}); +del(["tmp/*.js", "!tmp/unicorn.js"], {cwd: ''}); del(["tmp/*.js", "!tmp/unicorn.js"]).then((paths: string[]) => { console.log('Deleted files/folders:\n', paths.join('\n')); @@ -15,9 +17,10 @@ del(["tmp/*.js", "!tmp/unicorn.js"], {force: true}).then((paths: string[]) => { }); del("tmp/*.js"); - del("tmp/*.js", {force: true}); - +del("tmp/*.js", {dryRun: true}); +del("tmp/*.js", {concurrency: 20}); +del("tmp/*.js", {cwd: ''}); del("tmp/*.js").then((paths: string[]) => { console.log('Deleted files/folders:\n', paths.join('\n')); }); @@ -27,11 +30,10 @@ del("tmp/*.js", {force: true}).then((paths: string[]) => { }); paths = del.sync(["tmp/*.js", "!tmp/unicorn.js"]); - paths = del.sync(["tmp/*.js", "!tmp/unicorn.js"], {force: true}); paths = del.sync("tmp/*.js"); - paths = del.sync("tmp/*.js", {force: true}); - paths = del.sync("tmp/*.js", {dryRun: true}); +paths = del.sync("tmp/*.js", {concurrency: 20}); +paths = del.sync("tmp/*.js", {cwd: ''}); diff --git a/types/del/index.d.ts b/types/del/index.d.ts index 50634e39eb..e3c250e69b 100644 --- a/types/del/index.d.ts +++ b/types/del/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for del 2.2 +// Type definitions for del 3.0 // Project: https://github.com/sindresorhus/del -// Definitions by: Asana , Aya Morisawa +// Definitions by: Asana +// Aya Morisawa +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import glob = require("glob"); @@ -13,6 +15,7 @@ declare namespace del { interface Options extends glob.IOptions { force?: boolean; dryRun?: boolean; + concurrency?: number; } } diff --git a/types/del/tsconfig.json b/types/del/tsconfig.json index dd4981bd08..ba10982e67 100644 --- a/types/del/tsconfig.json +++ b/types/del/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,4 +19,4 @@ "index.d.ts", "del-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/del/v2/del-tests.ts b/types/del/v2/del-tests.ts new file mode 100644 index 0000000000..09702c4b39 --- /dev/null +++ b/types/del/v2/del-tests.ts @@ -0,0 +1,37 @@ +import del = require("del"); + +let paths = ["build", "dist/**/*.js"]; + +del(["tmp/*.js", "!tmp/unicorn.js"]); + +del(["tmp/*.js", "!tmp/unicorn.js"], {force: true}); + +del(["tmp/*.js", "!tmp/unicorn.js"]).then((paths: string[]) => { + console.log('Deleted files/folders:\n', paths.join('\n')); +}); + +del(["tmp/*.js", "!tmp/unicorn.js"], {force: true}).then((paths: string[]) => { + console.log('Deleted files/folders:\n', paths.join('\n')); +}); + +del("tmp/*.js"); + +del("tmp/*.js", {force: true}); + +del("tmp/*.js").then((paths: string[]) => { + console.log('Deleted files/folders:\n', paths.join('\n')); +}); + +del("tmp/*.js", {force: true}).then((paths: string[]) => { + console.log('Deleted files/folders:\n', paths.join('\n')); +}); + +paths = del.sync(["tmp/*.js", "!tmp/unicorn.js"]); + +paths = del.sync(["tmp/*.js", "!tmp/unicorn.js"], {force: true}); + +paths = del.sync("tmp/*.js"); + +paths = del.sync("tmp/*.js", {force: true}); + +paths = del.sync("tmp/*.js", {dryRun: true}); diff --git a/types/del/v2/index.d.ts b/types/del/v2/index.d.ts new file mode 100644 index 0000000000..50634e39eb --- /dev/null +++ b/types/del/v2/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for del 2.2 +// Project: https://github.com/sindresorhus/del +// Definitions by: Asana , Aya Morisawa +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import glob = require("glob"); + +declare function del(patterns: string | string[], options?: del.Options): Promise; + +declare namespace del { + function sync(patterns: string | string[], options?: Options): string[]; + + interface Options extends glob.IOptions { + force?: boolean; + dryRun?: boolean; + } +} + +export = del; diff --git a/types/del/v2/tsconfig.json b/types/del/v2/tsconfig.json new file mode 100644 index 0000000000..4ec5576309 --- /dev/null +++ b/types/del/v2/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "del": ["del/v2"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "del-tests.ts" + ] +} diff --git a/types/del/v2/tslint.json b/types/del/v2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/del/v2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 1cffe215538b263452b4d6566b34888df0c66157 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Wed, 9 Aug 2017 19:30:16 +0200 Subject: [PATCH 14/29] [conf] add typings for v1, add strict null checks (#18783) --- types/conf/conf-tests.ts | 40 ++++++++++++++++++++++++++++--------- types/conf/index.d.ts | 25 ++++++++++++----------- types/conf/tsconfig.json | 7 +++---- types/conf/v0/conf-tests.ts | 20 +++++++++++++++++++ types/conf/v0/index.d.ts | 29 +++++++++++++++++++++++++++ types/conf/v0/tsconfig.json | 26 ++++++++++++++++++++++++ types/conf/v0/tslint.json | 1 + 7 files changed, 123 insertions(+), 25 deletions(-) create mode 100644 types/conf/v0/conf-tests.ts create mode 100644 types/conf/v0/index.d.ts create mode 100644 types/conf/v0/tsconfig.json create mode 100644 types/conf/v0/tslint.json diff --git a/types/conf/conf-tests.ts b/types/conf/conf-tests.ts index 0b9f49ff79..1da0e4de2d 100644 --- a/types/conf/conf-tests.ts +++ b/types/conf/conf-tests.ts @@ -1,19 +1,41 @@ import Conf = require('conf'); -const conf = new Conf(); +const conf = new Conf(); +new Conf({ + defaults: { + foo: 'bar', + unicorn: 'rainbow' + }, + configName: '', + projectName: 'foo', + cwd: '' +}); +// $ExpectError +new Conf({ + defaults: { + foo: 'bar', + unicorn: ['rainbow'] + } +}); conf.set('foo', 'bar'); conf.set('hello', 1); conf.set('unicorn', false); -conf.set('object', { - foo: 'bar', - unicorn: ['rainbow'] -}); +conf.set('null', null); // $ExpectError -conf.get('foo'); +conf.get('foo'); // $ExpectType string | number | boolean +conf.get('foo', 'bar'); // $ExpectType string | number | boolean +conf.get('foo', null); // $ExpectError conf.delete('foo'); -conf.has('foo'); +conf.has('foo'); // $ExpectType boolean conf.clear(); -for (const value of conf) { - console.log(value[0], value[1]); +conf.store = { + foo: 'bar', + unicorn: 'rainbow' +}; +conf.path; // $ExpectType string + +for (const [key, value] of conf) { + key; // $ExpectType string + value; // $ExpectType string | number | boolean } diff --git a/types/conf/index.d.ts b/types/conf/index.d.ts index 21c136e823..9f88a88355 100644 --- a/types/conf/index.d.ts +++ b/types/conf/index.d.ts @@ -1,29 +1,30 @@ -// Type definitions for conf 0.11 +// Type definitions for conf 1.1 // Project: https://github.com/sindresorhus/conf // Definitions by: Sam Verschueren +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -interface Options { - defaults?: any; +interface Options { + defaults?: {[key: string]: T}; configName?: string; projectName?: string; cwd?: string; } -declare class Conf implements Iterable<[string, string | number | boolean | symbol | {}]> { - path: string; - store: any; - +declare class Conf implements Iterable<[string, T]> { + store: {[key: string]: T}; + readonly path: string; readonly size: number; - constructor(options?: Options); - get(key: string): any; - set(key: string, val: string | number | boolean | symbol | {}): void; - set(object: {}): void; + constructor(options?: Options); + get(key: string, defaultValue?: T): T; + set(key: string, val: T): void; + set(object: {[key: string]: T}): void; has(key: string): boolean; delete(key: string): void; clear(): void; - [Symbol.iterator](): Iterator<[string, string | number | boolean | symbol | {}]>; + [Symbol.iterator](): Iterator<[string, T]>; } export = Conf; diff --git a/types/conf/tsconfig.json b/types/conf/tsconfig.json index 8ef2367ca4..d165e88ea2 100644 --- a/types/conf/tsconfig.json +++ b/types/conf/tsconfig.json @@ -2,13 +2,12 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "target": "es6", "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -21,4 +20,4 @@ "index.d.ts", "conf-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/conf/v0/conf-tests.ts b/types/conf/v0/conf-tests.ts new file mode 100644 index 0000000000..1368e45c29 --- /dev/null +++ b/types/conf/v0/conf-tests.ts @@ -0,0 +1,20 @@ +import Conf = require('conf'); + +const conf = new Conf(); +conf.set('foo', 'bar'); +conf.set('hello', 1); +conf.set('unicorn', false); +conf.set('object', { + foo: 'bar', + unicorn: ['rainbow'] +}); + +conf.get('foo'); +conf.delete('foo'); +conf.has('foo'); +conf.clear(); + +for (const [key, value] of conf) { + key; // $ExpectType string + value; // $ExpectType string | number | boolean | symbol | {} +} diff --git a/types/conf/v0/index.d.ts b/types/conf/v0/index.d.ts new file mode 100644 index 0000000000..21c136e823 --- /dev/null +++ b/types/conf/v0/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for conf 0.11 +// Project: https://github.com/sindresorhus/conf +// Definitions by: Sam Verschueren +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Options { + defaults?: any; + configName?: string; + projectName?: string; + cwd?: string; +} + +declare class Conf implements Iterable<[string, string | number | boolean | symbol | {}]> { + path: string; + store: any; + + readonly size: number; + + constructor(options?: Options); + get(key: string): any; + set(key: string, val: string | number | boolean | symbol | {}): void; + set(object: {}): void; + has(key: string): boolean; + delete(key: string): void; + clear(): void; + [Symbol.iterator](): Iterator<[string, string | number | boolean | symbol | {}]>; +} + +export = Conf; diff --git a/types/conf/v0/tsconfig.json b/types/conf/v0/tsconfig.json new file mode 100644 index 0000000000..6047f464f4 --- /dev/null +++ b/types/conf/v0/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "conf": ["conf/v0"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "conf-tests.ts" + ] +} diff --git a/types/conf/v0/tslint.json b/types/conf/v0/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/conf/v0/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 371bffbf56ea185a8699bc44b4e79dda22555f74 Mon Sep 17 00:00:00 2001 From: Roberts Slisans Date: Wed, 9 Aug 2017 20:31:00 +0300 Subject: [PATCH 15/29] Added uniqid definition (#18780) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Created definitions & tests for pick-weight 🎲 * Fix no-single-module * Added uniqid definition --- types/uniqid/index.d.ts | 13 +++++++++++++ types/uniqid/tsconfig.json | 22 ++++++++++++++++++++++ types/uniqid/tslint.json | 1 + types/uniqid/uniqid-tests.ts | 7 +++++++ 4 files changed, 43 insertions(+) create mode 100644 types/uniqid/index.d.ts create mode 100644 types/uniqid/tsconfig.json create mode 100644 types/uniqid/tslint.json create mode 100644 types/uniqid/uniqid-tests.ts diff --git a/types/uniqid/index.d.ts b/types/uniqid/index.d.ts new file mode 100644 index 0000000000..e3853a64a3 --- /dev/null +++ b/types/uniqid/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for uniqid 4.1 +// Project: http://github.com/adamhalasz/diet-uniqid/ +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// Commmon function signature +declare function f(prefix: string): string; + +// let x -> Workaround for ES6 imports +// Combined type because of assigning to function object in original module +declare let x: typeof f & { process: typeof f } & { time: typeof f }; + +export = x; diff --git a/types/uniqid/tsconfig.json b/types/uniqid/tsconfig.json new file mode 100644 index 0000000000..437a215958 --- /dev/null +++ b/types/uniqid/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "uniqid-tests.ts" + ] +} diff --git a/types/uniqid/tslint.json b/types/uniqid/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/uniqid/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/uniqid/uniqid-tests.ts b/types/uniqid/uniqid-tests.ts new file mode 100644 index 0000000000..f0f56aa2fd --- /dev/null +++ b/types/uniqid/uniqid-tests.ts @@ -0,0 +1,7 @@ +import * as uniqid from "uniqid"; + +const uniqueID = uniqid("123"); +const processString = uniqid.process("123"); +const timeString = uniqid.time("123"); + +if (uniqueID === "" && processString === "" && timeString === "") { /**/ } From 08863b85fc16d89b3827f5b247eb3dcce89b1ae0 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Wed, 9 Aug 2017 19:31:49 +0200 Subject: [PATCH 16/29] [element-ready] add typings (#18778) --- types/element-ready/element-ready-tests.ts | 9 +++++++++ types/element-ready/index.d.ts | 10 ++++++++++ types/element-ready/tsconfig.json | 23 ++++++++++++++++++++++ types/element-ready/tslint.json | 1 + 4 files changed, 43 insertions(+) create mode 100644 types/element-ready/element-ready-tests.ts create mode 100644 types/element-ready/index.d.ts create mode 100644 types/element-ready/tsconfig.json create mode 100644 types/element-ready/tslint.json diff --git a/types/element-ready/element-ready-tests.ts b/types/element-ready/element-ready-tests.ts new file mode 100644 index 0000000000..e003947bc1 --- /dev/null +++ b/types/element-ready/element-ready-tests.ts @@ -0,0 +1,9 @@ +import elementReady = require('element-ready'); + +const p = elementReady('#unicorn'); + +p.then(element => { + const el: HTMLElement = element; +}); + +p.cancel(); diff --git a/types/element-ready/index.d.ts b/types/element-ready/index.d.ts new file mode 100644 index 0000000000..03a750b59d --- /dev/null +++ b/types/element-ready/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for element-ready 2.1 +// Project: https://github.com/sindresorhus/element-ready#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import pCancelable = require('p-cancelable'); + +export = elementReady; + +declare function elementReady(selector: string): pCancelable.PCancelable; diff --git a/types/element-ready/tsconfig.json b/types/element-ready/tsconfig.json new file mode 100644 index 0000000000..42de8557bc --- /dev/null +++ b/types/element-ready/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "element-ready-tests.ts" + ] +} diff --git a/types/element-ready/tslint.json b/types/element-ready/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/element-ready/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 6c7066f9b153135c725e8714823db0cfe0b90836 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Wed, 9 Aug 2017 19:32:17 +0200 Subject: [PATCH 17/29] [clipboardy] add typings (#18771) --- types/clipboardy/clipboardy-tests.ts | 10 ++++++++++ types/clipboardy/index.d.ts | 9 +++++++++ types/clipboardy/tsconfig.json | 22 ++++++++++++++++++++++ types/clipboardy/tslint.json | 1 + 4 files changed, 42 insertions(+) create mode 100644 types/clipboardy/clipboardy-tests.ts create mode 100644 types/clipboardy/index.d.ts create mode 100644 types/clipboardy/tsconfig.json create mode 100644 types/clipboardy/tslint.json diff --git a/types/clipboardy/clipboardy-tests.ts b/types/clipboardy/clipboardy-tests.ts new file mode 100644 index 0000000000..33ae8ac9a8 --- /dev/null +++ b/types/clipboardy/clipboardy-tests.ts @@ -0,0 +1,10 @@ +import clipboardy = require('clipboardy'); + +clipboardy.writeSync('🦄'); +clipboardy.write('🦄').then(() => {}); + +let str: string; +str = clipboardy.readSync(); +clipboardy.read().then(toPaste => { + str = toPaste; +}); diff --git a/types/clipboardy/index.d.ts b/types/clipboardy/index.d.ts new file mode 100644 index 0000000000..12e2c3b85a --- /dev/null +++ b/types/clipboardy/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for clipboardy 1.1 +// Project: https://github.com/sindresorhus/clipboardy#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function write(input: string): Promise; +export function writeSync(input: string): void; +export function read(): Promise; +export function readSync(): string; diff --git a/types/clipboardy/tsconfig.json b/types/clipboardy/tsconfig.json new file mode 100644 index 0000000000..455154a1d2 --- /dev/null +++ b/types/clipboardy/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "clipboardy-tests.ts" + ] +} diff --git a/types/clipboardy/tslint.json b/types/clipboardy/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/clipboardy/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 48c8449d4b9aa5fa6d550b8f4ca798b950c2f164 Mon Sep 17 00:00:00 2001 From: am Date: Wed, 9 Aug 2017 19:37:17 +0200 Subject: [PATCH 18/29] [adone] introduce typings (#18709) * [adone] introduce typings * [adone] refactor to module style * [adone] set strictNullChecks = true, fix utils test * [adone] rename tests file, change compileOptions.target * [adone] add interface namespaces * [adone] add some util typings, fixes * util.toposort * util.GlobExp options * util.ltgt * util.fakeClock * fix loadAsset return type * [adone] create namespaces for tests * [adone] create interface for util.fakeClock --- types/adone/adone-tests.ts | 3 + types/adone/adone.d.ts | 77 +++ types/adone/glosses/common.d.ts | 462 +++++++++++++++++ types/adone/glosses/math.d.ts | 115 ++++ types/adone/glosses/std.d.ts | 65 +++ types/adone/glosses/utils.d.ts | 462 +++++++++++++++++ types/adone/index.d.ts | 9 + types/adone/test/glosses/common.ts | 808 +++++++++++++++++++++++++++++ types/adone/test/glosses/math.ts | 259 +++++++++ types/adone/test/glosses/std.ts | 161 ++++++ types/adone/test/glosses/utils.ts | 736 ++++++++++++++++++++++++++ types/adone/test/index-import.ts | 6 + types/adone/test/index.ts | 69 +++ types/adone/tsconfig.json | 34 ++ types/adone/tslint.json | 8 + 15 files changed, 3274 insertions(+) create mode 100644 types/adone/adone-tests.ts create mode 100644 types/adone/adone.d.ts create mode 100644 types/adone/glosses/common.d.ts create mode 100644 types/adone/glosses/math.d.ts create mode 100644 types/adone/glosses/std.d.ts create mode 100644 types/adone/glosses/utils.d.ts create mode 100644 types/adone/index.d.ts create mode 100644 types/adone/test/glosses/common.ts create mode 100644 types/adone/test/glosses/math.ts create mode 100644 types/adone/test/glosses/std.ts create mode 100644 types/adone/test/glosses/utils.ts create mode 100644 types/adone/test/index-import.ts create mode 100644 types/adone/test/index.ts create mode 100644 types/adone/tsconfig.json create mode 100644 types/adone/tslint.json diff --git a/types/adone/adone-tests.ts b/types/adone/adone-tests.ts new file mode 100644 index 0000000000..861660ee89 --- /dev/null +++ b/types/adone/adone-tests.ts @@ -0,0 +1,3 @@ +// Actual tests inside ./test/ + +const a: string = adone.ok; diff --git a/types/adone/adone.d.ts b/types/adone/adone.d.ts new file mode 100644 index 0000000000..f968bfa342 --- /dev/null +++ b/types/adone/adone.d.ts @@ -0,0 +1,77 @@ +/// + +declare const _null: symbol; +export { _null as null }; +export function noop(): void; +export function identity(x: T): T; +export function truly(): true; +export function falsely(): false; +export const ok: "OK"; +export const bad: "BAD"; +export const exts: [".js", ".tjs", ".ajs"]; +export function log(...args: any[]): void; +export function fatal(...args: any[]): void; +export function error(...args: any[]): void; +export function warn(...args: any[]): void; +export function info(...args: any[]): void; +export function debug(...args: any[]): void; +export function trace(...args: any[]): void; +export function o(...props: any[]): object; +export const Date: typeof global.Date; +export const hrtime: typeof global.process.hrtime; +export const setTimeout: typeof global.setTimeout; +export const setInterval: typeof global.setInterval; +export const setImmediate: typeof global.setImmediate; +export const clearTimeout: typeof global.clearTimeout; +export const clearInterval: typeof global.clearInterval; +export const clearImmediate: typeof global.clearImmediate; +interface LazifyOptions { + configurable: boolean; +} +export function lazify(modules: object, obj?: object, require?: (path: string) => any, options?: LazifyOptions): object; +interface Tag { + set(Class: object, tag: string): void; + has(obj: object, tag: string): boolean; + define(tag: string, predicate?: string): void; + SUBSYSTEM: symbol; + APPLICATION: symbol; + TRANSFORM: symbol; + CORE_STREAM: symbol; + LOGGER: symbol; + LONG: symbol; + BIGNUMBER: symbol; + EXBUFFER: symbol; + EXDATE: symbol; + CONFIGURATION: symbol; + GENESIS_NETRON: symbol; + GENESIS_PEER: symbol; + NETRON: symbol; + NETRON_PEER: symbol; + NETRON_ADAPTER: symbol; + NETRON_DEFINITION: symbol; + NETRON_DEFINITIONS: symbol; + NETRON_REFERENCE: symbol; + NETRON_INTERFACE: symbol; + NETRON_STUB: symbol; + NETRON_REMOTESTUB: symbol; + NETRON_STREAM: symbol; + FAST_STREAM: symbol; + FAST_FS_STREAM: symbol; + FAST_FS_MAP_STREAM: symbol; +} +export const tag: Tag; +export function run(App: object, ignoreArgs?: boolean): Promise; +export function bind(libName: string): object; +export function getAssetAbsolutePath(relPath: string): string; +export function loadAsset(relPath: string): string | Buffer; +export function require(path: string): object; +export const package: object; + +import * as std from "./glosses/std"; +export { std }; + +export * from "./glosses/common"; +export * from "./glosses/math"; +export * from "./glosses/utils"; + +export as namespace adone; diff --git a/types/adone/glosses/common.d.ts b/types/adone/glosses/common.d.ts new file mode 100644 index 0000000000..f424598c02 --- /dev/null +++ b/types/adone/glosses/common.d.ts @@ -0,0 +1,462 @@ +export namespace is { + function _null(obj: any): boolean; + export { _null as null }; + export function undefined(obj: any): boolean; + export function exist(obj: any): boolean; + export function nil(obj: any): boolean; + export function number(obj: any): boolean; + export function numeral(obj: any): boolean; + export function infinite(obj: any): boolean; + export function odd(obj: any): boolean; + export function even(obj: any): boolean; + export function float(obj: any): boolean; + export function negativeZero(obj: any): boolean; + export function string(obj: any): boolean; + export function emptyString(obj: any): boolean; + export function substring(substring: string, string: string, offset?: number): boolean; + export function prefix(prefix: string, string: string): boolean; + export function suffix(suffix: string, string: string): boolean; + export function boolean(obj: any): boolean; + export function json(obj: any): boolean; + export function object(obj: any): boolean; + export function plainObject(obj: any): boolean; + function _class(obj: any): boolean; + export { _class as class }; + export function emptyObject(obj: any): boolean; + export function propertyOwned(obj: any, field: string): boolean; + export function propertyDefined(obj: any, field: string): boolean; + export function conforms(obj: object, schema: object, strict?: boolean): boolean; + export function arrayLikeObject(obj: any): boolean; + export function inArray(value: T, array: any[], offset?: number, comparator?: (a: T, b: T) => boolean): boolean; + export function sameType(value: any, other: any): boolean; + export function primitive(obj: any): boolean; + export function equalArrays(left: any[], right: any[]): boolean; + export function deepEqual(left: any, right: any): boolean; + export function shallowEqual(left: any, right: any): boolean; + export function stream(obj: any): boolean; + export function writableStream(obj: any): boolean; + export function readableStream(obj: any): boolean; + export function duplexStream(obj: any): boolean; + export function transformStream(obj: any): boolean; + export function utf8(obj: Buffer): boolean; + export function win32PathAbsolute(path: string): boolean; + export function posixPathAbsolute(path: string): boolean; + export function pathAbsolute(path: string): boolean; + export function glob(str: string): boolean; + export function dotfile(str: string): boolean; + function _function(obj: any): boolean; + export { _function as function }; + export function asyncFunction(obj: any): boolean; + export function promise(obj: any): boolean; + export function validDate(str: string): boolean; + export function buffer(obj: any): boolean; + export function callback(obj: any): boolean; + export function generator(obj: any): boolean; + export function nan(obj: any): boolean; + export function finite(obj: any): boolean; + export function integer(obj: any): boolean; + export function safeInteger(obj: any): boolean; + export function array(obj: any): boolean; + export function uint8Array(obj: any): boolean; + export function configuration(obj: any): boolean; + export function long(obj: any): boolean; + export function bigNumber(obj: any): boolean; + export function exbuffer(obj: any): boolean; + export function exdate(obj: any): boolean; + export function transform(obj: any): boolean; + export function subsystem(obj: any): boolean; + export function application(obj: any): boolean; + export function logger(obj: any): boolean; + export function coreStream(obj: any): boolean; + export function fastStream(obj: any): boolean; + export function fastFSStream(obj: any): boolean; + export function fastFSMapStream(obj: any): boolean; + export function genesisNetron(obj: any): boolean; + export function genesisPeer(obj: any): boolean; + export function netronAdapter(obj: any): boolean; + export function netron(obj: any): boolean; + export function netronPeer(obj: any): boolean; + export function netronDefinition(obj: any): boolean; + export function netronDefinitions(obj: any): boolean; + export function netronReference(obj: any): boolean; + export function netronInterface(obj: any): boolean; + export function netronContext(obj: any): boolean; + export function netronIMethod(netronInterface: object, name: string): boolean; + export function netronIProperty(netronInterface: any, name: string): boolean; + export function netronStub(obj: any): boolean; + export function netronRemoteStub(obj: any): boolean; + export function netronStream(obj: any): boolean; + export function iterable(obj: any): boolean; + export const windows: boolean; + export const linux: boolean; + export const freebsd: boolean; + export const darwin: boolean; + export const sunos: boolean; + export function uppercase(str: string): boolean; + export function lowercase(str: string): boolean; + export function digits(str: string): boolean; + export function identifier(str: string): boolean; + export function binaryExtension(str: string): boolean; + export function binaryPath(str: string): boolean; + export function ip4(str: string): boolean; + export function ip6(str: string): boolean; + export function arrayBuffer(obj: any): boolean; + export function arrayBufferView(obj: any): boolean; + export function date(obj: any): boolean; + export function error(obj: any): boolean; + export function map(obj: any): boolean; + export function regexp(obj: any): boolean; + export function set(obj: any): boolean; + export function symbol(obj: any): boolean; + export function validUTF8(obj: any): boolean; +} + +export namespace x { + class Exception extends Error { + constructor(message?: string | Error, captureStackTrace?: boolean); + } + class Runtime extends Exception { } + class IncompleteBufferError extends Exception { } + class NotImplemented extends Exception { } + class IllegalState extends Exception { } + class NotValid extends Exception { } + class Unknown extends Exception { } + class NotExists extends Exception { } + class Exists extends Exception { } + class Empty extends Exception { } + class InvalidAccess extends Exception { } + class NotSupported extends Exception { } + class InvalidArgument extends Exception { } + class InvalidNumberOfArguments extends Exception { } + class NotFound extends Exception { } + class Timeout extends Exception { } + class Incorrect extends Exception { } + class NotAllowed extends Exception { } + class LimitExceeded extends Exception { } + class Encoding extends Exception { } + class Network extends Exception { } + class Bind extends Exception { } + class Connect extends Exception { } + class Database extends Exception { } + class DatabaseInitialization extends Exception { } + class DatabaseOpen extends Exception { } + class DatabaseRead extends Exception { } + class DatabaseWrite extends Exception { } + class NetronIllegalState extends Exception { } + class NetronPeerDisconnected extends Exception { } + class NetronTimeout extends Exception { } +} + +export class EventEmitter { + static listenerCount(emitter: EventEmitter, event: string | symbol): number; + static defaultMaxListeners: number; + + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Array<(...args: any[]) => any>; + emit(event: string | symbol, ...args: any[]): boolean; + eventNames(): Array; + listenerCount(type: string | symbol): number; +} + +export class AsyncEmitter extends EventEmitter { + constructor(concurrency?: number); + + setConcurrency(max?: number): this; + + emitParallel(event: string, ...args: any[]): Promise; + + emitSerial(event: string, ...args: any[]): Promise; + + emitReduce(event: string, ...args: any[]): Promise; + + emitReduceRight(event: string, ...args: any[]): Promise; + + subscribe(event: string, listener: (...args: any[]) => void, once?: boolean): () => void; +} + +declare namespace I { + type Long = adone.math.Long; + + type Longable = adone.math.I.Longable; + + namespace ExBuffer { + interface Varint32 { + value: number; + length: number; + } + + interface Varint64 { + value: Long; + length: number; + } + + interface String { + string: string; + length: number; + } + + type Wrappable = string | ExBuffer | Buffer | Uint8Array | ArrayBuffer; + + type METRICS = "b" | "c"; + } +} + +export class ExBuffer { + constructor(capacity?: number, noAssert?: boolean); + + readBitSet(offset?: number): number[]; + + read(length: number, offset?: number): ExBuffer; + + readInt8(offset?: number): number; + + readUInt8(offset?: number): number; + + readInt16LE(offset?: number): number; + + readUInt16LE(offset?: number): number; + + readInt16BE(offset?: number): number; + + readUInt16BE(offset?: number): number; + + readInt32LE(offset?: number): number; + + readUInt32LE(offset?: number): number; + + readInt32BE(offset?: number): number; + + readUInt32BE(offset?: number): number; + + readInt64LE(offset?: number): adone.math.Long; + + readUInt64LE(offset?: number): adone.math.Long; + + readInt64BE(offset?: number): adone.math.Long; + + readUInt64BE(offset?: number): adone.math.Long; + + readFloatLE(offset?: number): number; + + readFloatBE(offset?: number): number; + + readDoubleLE(offset?: number): number; + + readDoubleBE(offset?: number): number; + + write(source: I.ExBuffer.Wrappable, offset?: number, length?: number, encoding?: string): this; + + writeBitSet(value: number[]): this; + + writeBitSet(value: number[], offset: number): number; + + writeInt8(value: number, offset?: number): this; + + writeUInt8(value: number, offset?: number): this; + + writeInt16LE(value: number, offset?: number): this; + + writeInt16BE(value: number, offset?: number): this; + + writeUInt16LE(value: number, offset?: number): this; + + writeUInt16BE(value: number, offset?: number): this; + + writeInt32LE(value: number, offset?: number): this; + + writeInt32BE(value: number, offset?: number): this; + + writeUInt32LE(value: number, offset?: number): this; + + writeUInt32BE(value: number, offset?: number): this; + + writeInt64LE(value: I.Longable, offset?: number): this; + + writeInt64BE(value: I.Longable, offset?: number): this; + + writeUInt64LE(value: I.Longable, offset?: number): this; + + writeUInt64BE(value: I.Longable, offset?: number): this; + + writeFloatLE(value: number, offset?: number): this; + + writeFloatBE(value: number, offset?: number): this; + + writeDoubleLE(value: number, offset?: number): this; + + writeDoubleBE(value: number, offset?: number): this; + + writeVarint32(value: number): this; + + writeVarint32(value: number, offset: number): number; + + writeVarint32ZigZag(value: number): this; + + writeVarint32ZigZag(value: number, offset: number): number; + + readVarint32(): number; + + readVarint32(offset: number): I.ExBuffer.Varint32; + + readVarint32ZigZag(): number; + + readVarint32ZigZag(offset: number): I.ExBuffer.Varint32; + + writeVarint64(value: I.Longable): this; + + writeVarint64(value: I.Longable, offset: number): number; + + writeVarint64ZigZag(value: I.Longable): this; + + writeVarint64ZigZag(value: I.Longable, offset: number): number; + + readVarint64(): I.Long; + + readVarint64(offset: number): I.ExBuffer.Varint64; + + readVarint64ZigZag(): adone.math.Long; + + readVarint64ZigZag(offset: number): I.ExBuffer.Varint64; + + writeCString(str: string): this; + + writeCString(str: string, offset: number): number; + + readCString(): string; + + readCString(offset: number): I.ExBuffer.String; + + writeString(str: string): this; + + writeString(str: string, offset: number): number; + + readString(length: number, metrics?: I.ExBuffer.METRICS): string; + + readString(length: number, metrics: I.ExBuffer.METRICS, offset: number): I.ExBuffer.String; + + readString(length: number, offset: number): I.ExBuffer.String; + + writeVString(str: string): this; + + writeVString(str: string, offset: number): number; + + readVString(): string; + + readVString(offset: number): I.ExBuffer.String; + + appendTo(target: ExBuffer, offset?: number): this; + + assert(assert?: boolean): this; + + capacity(): number; + + clear(): this; + + compact(begin?: number, end?: number): this; + + copy(begin?: number, end?: number): ExBuffer; + + copyTo(target: ExBuffer, targetOffset?: number, souceOffset?: number, sourceLimit?: number): this | ExBuffer; + + ensureCapacity(capacity: number): this; + + fill(value: string | number, begin?: number, end?: number): this; + + flip(): this; + + mark(offset?: number): this; + + prepend(source: I.ExBuffer.Wrappable, encoding?: string, offset?: number): this; + + prepend(source: I.ExBuffer.Wrappable, offset: number): this; + + prependTo(target: ExBuffer, offset?: number): this; + + remaining(): number; + + reset(): this; + + resize(capacity: number): this; + + reverse(begin?: number, end?: number): this; + + skip(length: number): this; + + slice(begin?: number, end?: number): ExBuffer; + + toBuffer(forceCopy?: boolean, begin?: number, end?: number): Buffer; + + toArrayBuffer(): ArrayBuffer; + + toString(encoding?: string, begin?: number, end?: number): string; + + toBase64(begin?: number, end?: number): string; + + toBinary(begin?: number, end?: number): string; + + toDebug(columns?: boolean): string; + + toHex(begin?: number, end?: number): string; + + toUTF8(begin?: number, end?: number): string; + + static accessor(): typeof Buffer; + + static allocate(capacity?: number, noAssert?: boolean): ExBuffer; + + static concat(buffers: I.ExBuffer.Wrappable[], encoding?: string, noAssert?: boolean): ExBuffer; + + static type(): typeof Buffer; + + static wrap(buffer: I.ExBuffer.Wrappable, encoding?: string, noAssert?: boolean): ExBuffer; + + static calculateVarint32(value: number): number; + + static zigZagEncode32(n: number): number; + + static zigZagDecode32(n: number): number; + + static calculateVarint64(value: number | string): number; + + static zigZagEncode64(value: number | string | I.Long): I.Long; + + static zigZagDecode64(value: number | string | I.Long): I.Long; + + static calculateUTF8Chars(str: string): number; + + static calculateString(str: string): number; + + static fromBase64(str: string): ExBuffer; + + static btoa(str: string): string; + + static atob(b64: string): string; + + static fromBinary(str: string): ExBuffer; + + static fromDebug(str: string, noAssert?: boolean): ExBuffer; + + static fromHex(str: string, noAssert?: boolean): ExBuffer; + + static fromUTF8(str: string, noAssert?: boolean): ExBuffer; + + static DEFAULT_CAPACITY: number; + + static DEFAULT_NOASSERT: boolean; + + static MAX_VARINT32_BYTES: number; + + static MAX_VARINT64_BYTES: number; + + static METRICS_CHARS: string; + + static METRICS_BYTES: string; +} diff --git a/types/adone/glosses/math.d.ts b/types/adone/glosses/math.d.ts new file mode 100644 index 0000000000..d16b2a8c04 --- /dev/null +++ b/types/adone/glosses/math.d.ts @@ -0,0 +1,115 @@ +export namespace math { + namespace I { + interface LowHighBits { + low: number; + high: number; + } + type Longable = math.Long | number | string | LowHighBits; + } + + export class Long { + constructor(low?: number, high?: number, unsigned?: boolean); + + toInt(): number; + + toNumber(): number; + + toString(radix?: number): string; + + getHighBits(): number; + + getHighBitsUnsigned(): number; + + getLowBits(): number; + + getLowBitsUnsigned(): number; + + getNumBitsAbs(): number; + + isZero(): boolean; + + isNegative(): boolean; + + isPositive(): boolean; + + isOdd(): boolean; + + isEven(): boolean; + + equals(other: I.Longable): boolean; + + lessThan(other: I.Longable): boolean; + + lessThanOrEqual(other: I.Longable): boolean; + + greaterThan(other: I.Longable): boolean; + + greaterThanOrEqual(other: I.Longable): boolean; + + compare(other: I.Longable): number; + + negate(): Long; + + add(addend: I.Longable): Long; + + sub(subtrahend: I.Longable): Long; + + mul(multiplier: I.Longable): Long; + + div(divisor: I.Longable): Long; + + mod(divisor: I.Longable): Long; + + not(): Long; + + and(other: I.Longable): Long; + + or(other: I.Longable): Long; + + xor(other: I.Longable): Long; + + shl(numBits: number | Long): Long; + + shr(numBits: number | Long): Long; + + shru(numBits: number | Long): Long; + + toSigned(): Long; + + toUnsigned(): Long; + + toBytes(le?: boolean): number[]; + + toBytesLE(): number[]; + + toBytesBE(): number[]; + + static fromInt(value: number, unsigned?: boolean): Long; + + static fromNumber(value?: number, unsigned?: boolean): Long; + + static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long; + + static fromString(str: string, unsigned?: boolean, radix?: number): Long; + + static fromString(str: string, radix?: number): Long; + + static fromValue(val: I.Longable): Long; + + static MIN_VALUE: Long; + + static MAX_VALUE: Long; + + static MAX_UNSIGNED_VALUE: Long; + + static ZERO: Long; + + static UZERO: Long; + + static ONE: Long; + + static UONE: Long; + + static NEG_ONE: Long; + } +} diff --git a/types/adone/glosses/std.d.ts b/types/adone/glosses/std.d.ts new file mode 100644 index 0000000000..9c30b41f62 --- /dev/null +++ b/types/adone/glosses/std.d.ts @@ -0,0 +1,65 @@ +import * as assert from "assert"; +import * as fs from "fs"; +import * as path from "path"; +import * as util from "util"; +import * as events from "events"; +import * as stream from "stream"; +import * as url from "url"; +import * as net from "net"; +import * as http from "http"; +import * as https from "https"; +import * as child_process from "child_process"; +import * as os from "os"; +import * as cluster from "cluster"; +import * as repl from "repl"; +import * as punycode from "punycode"; +import * as readline from "readline"; +import * as string_decoder from "string_decoder"; +import * as querystring from "querystring"; +import * as crypto from "crypto"; +import * as vm from "vm"; +import * as v8 from "v8"; +import * as domain from "domain"; +import * as tty from "tty"; +import * as buffer from "buffer"; +import * as constants from "constants"; +import * as zlib from "zlib"; +import * as tls from "tls"; +import * as console from "console"; +import * as dns from "dns"; +import * as timers from "timers"; +import * as dgram from "dgram"; + +export { + assert, + fs, + path, + util, + events, + stream, + url, + net, + http, + https, + child_process, + os, + cluster, + repl, + punycode, + readline, + string_decoder, + querystring, + crypto, + vm, + v8, + domain, + tty, + buffer, + constants, + zlib, + tls, + console, + dns, + timers, + dgram, +}; diff --git a/types/adone/glosses/utils.d.ts b/types/adone/glosses/utils.d.ts new file mode 100644 index 0000000000..629b9a08bd --- /dev/null +++ b/types/adone/glosses/utils.d.ts @@ -0,0 +1,462 @@ +export namespace util { + function arrify(val: T[]): T[]; + function arrify(val: T): [T]; + + function slice(args: T[], sliceStart?: number, sliceEnd?: number): T[]; + + function spliceOne(list: any[], index: number): void; + + function normalizePath(str: string, stripTrailing?: boolean): string; + + function unixifyPath(filePath: string, unescape?: boolean): string; + + function functionName(fn: (...args: any[]) => any): string; + + function mapArguments(argmap: (...args: any[]) => any | any[]): (...args: any[]) => any; + function mapArguments(argmap: number): (...args: T[]) => T[]; + function mapArguments(...args: any[]): (x: T) => T; + + namespace I { + interface ParseMsResult { + days: number; + hours: number; + minutes: number; + seconds: number; + milliseconds: number; + } + } + function parseMs(ms: number): I.ParseMsResult; + + function pluralizeWord(str: string, plural?: string, count?: number): string; + + function functionParams(func: (...args: any[]) => any): string[]; + + function randomChoice(arrayLike: ArrayLike, from?: number, to?: number): T; + + function shuffleArray(array: T[]): T[]; + + function enumerate(iterable: Iterable, start?: number): IterableIterator<[number, T]>; + + function zip(a: Iterable, b: Iterable): IterableIterator<[T1, T2]>; + function zip(a: Iterable, b: Iterable, c: Iterable): IterableIterator<[T1, T2, T3]>; + function zip(a: Iterable, b: Iterable, c: Iterable, d: Iterable): IterableIterator<[T1, T2, T3, T4]>; + function zip(...iterables: Array>): IterableIterator; + + namespace I { + interface KeysOptions { + onlyEnumerable?: boolean; + followProto?: boolean; + all?: boolean; + } + } + function keys(object: object, options?: I.KeysOptions): string[]; + + function values(object: object, options?: I.KeysOptions): any[]; + + function entries(object: object, options?: I.KeysOptions): Array; + + function toDotNotation(object: object): object; + + namespace I { + interface FlattenOptions { + depth?: number; + } + } + function flatten(array: any[], options?: I.FlattenOptions): any[]; + + function globParent(str: string): string; + + namespace I { + interface ByResult { + (a: S, b: S): R; + compare(a: T, b: T): R; + by(a: S): T; + } + } + function by(by: (a: S) => T, compare?: (a: T, b: T) => R): I.ByResult; + + function toFastProperties(object: object): object; + + function stripBom(x: string): string; + + namespace I { + interface SortKeysOptions { + deep?: boolean; + compare?(a: any, b: any): number; + } + } + function sortKeys(object: object, options?: I.SortKeysOptions): object; + + namespace I { + interface GlobizeOptions { + exts?: string; + recursively?: boolean; + } + } + function globize(path: string, options?: I.GlobizeOptions): string; + + function unique(array: T[], projection?: (a: T) => any): T[]; + + function invertObject(source: object, options?: I.KeysOptions): object; + + namespace I { + interface HumanizeTimeOptions { + msDecimalDigits?: number; + secDecimalDigits?: number; + verbose?: boolean; + compact?: boolean; + } + } + function humanizeTime(ms: number, options?: I.HumanizeTimeOptions): string; + function humanizeSize(num: number, space?: string): string; + + function parseSize(str: string | number): number | null; + + namespace I { + interface CloneOptions { + deep?: boolean; + } + } + function clone(object: object, options?: I.CloneOptions): object; + + function toUTF8Array(str: string): number[]; + + function asyncIter(array: T[], iter: (elem: T, index: number, cb: () => void) => any, cb: () => void): void; + + function asyncFor(obj: { [key: string]: T }, iter: (key: string, value: T, index: number, length: number, next: () => void) => void, cb: () => void): void; + + namespace I { + interface OnceOptions { + silent: boolean; + } + } + function once(fn: (...args: any[]) => T, options?: I.OnceOptions): (...args: any[]) => T; + + namespace I { + type WaterFallTask = (...args: any[]) => void; + } + function asyncWaterfall(tasks: I.WaterFallTask[], callback?: (err?: Error | null, ...args: any[]) => void): void; + + function xrange(start?: number, stop?: number, step?: number): IterableIterator; + + function range(start?: number, stop?: number, step?: number): number[]; + + function reFindAll(regexp: RegExp, str: string): RegExpExecArray[]; + + function assignDeep(target: T, ...sources: object[]): T; + + namespace I { + interface MatchOptions { + index?: boolean; + start?: number; + end?: number; + dot?: boolean; + } + } + function match(criteria: any | any[], options?: I.MatchOptions): (value: any | any[], options?: I.MatchOptions) => number | boolean; + function match(criteria: any | any[], value: any | any[], options?: I.MatchOptions): number | boolean; + + namespace I { + interface ToposortFunction { + (edges: Array<[T, T]>): T[]; + array(nodes: T[], edges: Array<[T, T]>): T[]; + } + } + const toposort: I.ToposortFunction; + + namespace I { + interface JSEscOptions { + escapeEverything?: boolean; + minimal?: boolean; + isScriptContext?: boolean; + quotes?: string; + wrap?: boolean; + es6?: boolean; + json?: boolean; + compact?: boolean; + lowercaseHex?: boolean; + numbers?: string; + indent?: string; + indentLevel?: number; + __inline1__?: boolean; + __inline2__?: boolean; + } + } + function jsesc(argument: any, options?: I.JSEscOptions): string; + + function typeOf(obj: any): string; + + namespace memcpy { + function utou(target: Buffer, targetOffset: number, source: Buffer, sourceStart: number, sourceEnd: number): number; + function atoa(target: ArrayBuffer, targetOffset: number, source: ArrayBuffer, sourceStart: number, sourceEnd: number): number; + function atou(target: Buffer, targetOffset: number, source: ArrayBuffer, sourceStart: number, sourceEnd: number): number; + function utoa(target: ArrayBuffer, targetOffset: number, source: Buffer, sourceStart: number, sourceEnd: number): number; + function copy(target: Buffer | ArrayBuffer, targetOffset: number, source: Buffer | ArrayBuffer, sourceStart: number, sourceEnd: number): number; + } + + namespace uuid { + namespace I { + interface V1Options { + clockseq?: number; + msecs?: number; + nsecs?: number; + } + } + function v1(options?: I.V1Options): string; + function v1(options: I.V1Options, buf: any[], offset?: number): number[]; + + function v4(options?: any): string; + function v4(options: any, buf: any[], offset?: number): number[]; + + function v5(name: string | number[], namespace: string | number[]): string; + function v5(name: string | number[], namespace: string | number[], buf: any[], offset?: number): number[]; + } + + namespace I { + interface Delegator { + method(name: string): Delegator; + access(name: string): Delegator; + getter(name: string): Delegator; + setter(name: string): Delegator; + } + } + function delegate(object: object, property: string): I.Delegator; + + namespace I { + interface GlobExpOptions { + nocomment?: boolean; + nonegate?: boolean; + nobrace?: boolean; + noglobstar?: boolean; + nocase?: boolean; + dot?: boolean; + noext?: boolean; + matchBase?: boolean; + flipNegate?: boolean; + } + } + + class GlobExp { + constructor(pattern: string, options?: I.GlobExpOptions); + + hasMagic(): boolean; + + static hasMagic(pattern: string, options?: I.GlobExpOptions): boolean; + + expandBraces(): string[]; + + static expandBraces(pattern: string, options?: I.GlobExpOptions): string[]; + + makeRe(): RegExp; + + static makeRe(pattern: string, options?: I.GlobExpOptions): RegExp; + + static test(p: string, pattern: string, options?: I.GlobExpOptions): boolean; + + test(p: string): boolean; + } + + namespace iconv { + // TODO: need to normalize source code + } + + namespace sqlstring { + function escapeId(val: string | string[], forbidQualified?: boolean): string; + function dateToString(date: any, timeZone?: string): string; + function arrayToList(array: any[]): string; + function bufferToString(buffer: Buffer): string; + function objectToValues(object: object, timeZone?: string): string; + function escape(value: any, stringifyObjects?: boolean, timeZone?: string): string; + function format(sql: string, values?: any | any[], stringifyObjects?: boolean, timeZone?: string): string; + } + + namespace I { + interface EditorOptions { + text?: string; + editor?: string; + path?: string; + ext?: string; + } + } + class Editor { + static DEFAULT: string; + + constructor(options?: I.EditorOptions); + + spawn(): Promise; + + run(): Promise; + + cleanup(): Promise; + + static edit(options?: I.EditorOptions): Promise; + } + + namespace I { + interface BinarySearchFunction { + (aHaystack: T[], aNeedle: number, aLow?: number, aHigh?: number, aCompare?: (a: T, b: T) => number, aBias?: number): T; + GREATEST_LOWER_BOUND: number; + LEAST_UPPER_BOUND: number; + } + } + const binarySearch: I.BinarySearchFunction; + + namespace buffer { + function concat(list: Buffer[], totalLength: number): Buffer; + function mask(buffer: Buffer, mask: Buffer, output: Buffer, offset: number, length: number): void; + function unmask(buffer: Buffer, mask: Buffer): void; + } + + function shebang(str: string): string | null; + + class ReInterval { + constructor(callback: (...args: any[]) => void, interval: number, args?: any[]); + + reschedule(interval: number): void; + + clear(): void; + + destroy(): void; + } + + class RateLimiter { + constructor(tokensPerInterval?: number, interval?: number, fireImmediately?: boolean); + + removeTokens(count: number): Promise; + + tryRemoveTokens(count: number): boolean; + + getTokensRemaining(): number; + } + + namespace I { + interface ThrottleOptions { + max?: number; + interval?: number; + ordered?: boolean; + waitForReturn?: boolean; + } + } + function throttle(fn: () => R, options?: I.ThrottleOptions): () => Promise; + function throttle(fn: (a: T1) => R, options?: I.ThrottleOptions): (a: T1) => Promise; + function throttle(fn: (a: T1, b: T2) => R, options?: I.ThrottleOptions): (a: T1, b: T2) => Promise; + function throttle(fn: (a: T1, b: T2, c: T3) => R, options?: I.ThrottleOptions): (a: T1, b: T2, c: T3) => Promise; + function throttle(fn: (a: T1, b: T2, c: T3, d: T4) => R, options?: I.ThrottleOptions): (a: T1, b: T2, c: T3, d: T4) => Promise; + function throttle(fn: (a: T1, b: T2, c: T3, d: T4, e: T5) => R, options?: I.ThrottleOptions): (a: T1, b: T2, c: T3, d: T4, e: T5) => Promise; + function throttle(fn: (...args: any[]) => R, options?: I.ThrottleOptions): (...args: any[]) => Promise; + + namespace I.fakeClock { + interface Timer { + id: number; + ref(): void; + unref(): void; + } + interface Clock { + setTimeout(func: (...args: any[]) => void, timeout: number, ...args: any[]): Timer; + clearTimeout(timer: Timer): void; + nextTick(func: (...args: any[]) => void, ...args: any[]): void; + setInterval(func: (...args: any[]) => void, ...args: any[]): Timer; + clearInterval(timer: Timer): void; + setImmediate(func: (...args: any[]) => void, ...args: any[]): Timer; + clearImmediate(timer: Timer): void; + updateHrTime(newNow: number): void; + tick(ms: number): number; + next(): number; + runAll(): number; + runToLast(): number; + setSystemTime(systemTime: number): void; + hrtime(prev?: [number, number]): [number, number]; + } + interface InstalledClock extends Clock { + uninstall(): void; + } + interface InstallOptions { + target?: object; + now?: number; + toFake?: string[]; + loopLimit?: number; + shouldAdvanceTime?: boolean; + advanceTimeDelta?: number; + } + + interface Timers { + setTimeout: typeof global.setTimeout; + clearTimeout: typeof global.clearTimeout; + setInterval: typeof global.setInterval; + clearInterval: typeof global.clearInterval; + setImmediate: typeof global.setImmediate; + clearImmediate: typeof global.clearImmediate; + Date: typeof global.Date; + hrtime: typeof global.process.hrtime; + nextTick: typeof global.process.nextTick; + } + + interface FakeClock { + timers: Timers; + createClock(now?: number, loopLimit?: number): Clock; + install(now: number | Date | InstallOptions): InstalledClock; + } + } + + const fakeClock: I.fakeClock.FakeClock; + + namespace ltgt { + namespace I { + interface Range { + lt?: T; + lte?: T; + gt?: T; + gte?: T; + min?: T; + max?: T; + start?: T; + end?: T; + reverse?: boolean; + } + type Comparator = (a: T, b: T) => number; + } + function contains(range: I.Range, key: T, compare?: I.Comparator): boolean; + + function filter(range: I.Range, compare?: I.Comparator): (key: T) => boolean; + + function toLtgt( + range: I.Range, + _range: object, + map?: (value: T, isUpperBound: boolean) => R, + lowerBound?: T, + upperBound?: T + ): I.Range; + + function endInclusive(range: I.Range): boolean; + + function startInclusive(range: I.Range): boolean; + + function end(range: I.Range): T | undefined; + + function end(range: I.Range, defaultValue: R): T | R; + + function start(range: I.Range): T | undefined; + + function start(range: I.Range, defaultValue?: R): T | R; + + function upperBound(range: I.Range): T | undefined; + + function upperBound(range: I.Range, defaultValue: R): T | R; + + function upperBoundKey(range: I.Range): T | undefined; + + function upperBoundExclusive(range: I.Range): boolean; + + function lowerBoundExclusive(range: I.Range): boolean; + + function upperBoundInclusive(range: I.Range): boolean; + + function lowerBoundInclusive(range: I.Range): boolean; + + function lowerBound(range: I.Range): T | undefined; + + function lowerBound(range: I.Range, defaultValue: R): T | R; + + function lowerBoundKey(range: I.Range): T | undefined; + } +} diff --git a/types/adone/index.d.ts b/types/adone/index.d.ts new file mode 100644 index 0000000000..663e8c8407 --- /dev/null +++ b/types/adone/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for adone 0.6 +// Project: https://github.com/ciferox/adone +// Definitions by: am , Maximus +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import * as adone from "./adone"; + +export default adone; diff --git a/types/adone/test/glosses/common.ts b/types/adone/test/glosses/common.ts new file mode 100644 index 0000000000..c66f6a5410 --- /dev/null +++ b/types/adone/test/glosses/common.ts @@ -0,0 +1,808 @@ +namespace commonTests { + namespace is { + { const a: boolean = adone.is.null({}); } + { const a: boolean = adone.is.undefined({}); } + { const a: boolean = adone.is.exist({}); } + { const a: boolean = adone.is.nil({}); } + { const a: boolean = adone.is.number({}); } + { const a: boolean = adone.is.numeral({}); } + { const a: boolean = adone.is.infinite({}); } + { const a: boolean = adone.is.odd({}); } + { const a: boolean = adone.is.even({}); } + { const a: boolean = adone.is.float({}); } + { const a: boolean = adone.is.negativeZero({}); } + { const a: boolean = adone.is.string({}); } + { const a: boolean = adone.is.emptyString({}); } + { const a: boolean = adone.is.substring("abc", "abcdef"); } + { const a: boolean = adone.is.substring("abc", "abcdef", 0); } + { const a: boolean = adone.is.prefix("abc", "abcdef"); } + { const a: boolean = adone.is.suffix("def", "abbdef"); } + { const a: boolean = adone.is.boolean({}); } + { const a: boolean = adone.is.json({}); } + { const a: boolean = adone.is.object({}); } + { const a: boolean = adone.is.plainObject({}); } + { const a: boolean = adone.is.class({}); } + { const a: boolean = adone.is.emptyObject({}); } + { const a: boolean = adone.is.propertyOwned({}, "a"); } + { const a: boolean = adone.is.propertyDefined({}, "a"); } + { const a: boolean = adone.is.conforms({}, {}); } + { const a: boolean = adone.is.conforms({}, {}, true); } + { const a: boolean = adone.is.arrayLikeObject({}); } + { const a: boolean = adone.is.inArray(1, [1, 2, 3]); } + { const a: boolean = adone.is.inArray(1, [1, 2, 3], 0); } + { const a: boolean = adone.is.inArray(1, [1, 2, 3], 0, (a, b) => a === b); } + { const a: boolean = adone.is.sameType({}, {}); } + { const a: boolean = adone.is.primitive({}); } + { const a: boolean = adone.is.equalArrays([], []); } + { const a: boolean = adone.is.deepEqual({}, {}); } + { const a: boolean = adone.is.shallowEqual({}, {}); } + { const a: boolean = adone.is.stream({}); } + { const a: boolean = adone.is.writableStream({}); } + { const a: boolean = adone.is.readableStream({}); } + { const a: boolean = adone.is.duplexStream({}); } + { const a: boolean = adone.is.transformStream({}); } + { const a: boolean = adone.is.utf8(Buffer.alloc(10)); } + { const a: boolean = adone.is.win32PathAbsolute("abc"); } + { const a: boolean = adone.is.posixPathAbsolute("abc"); } + { const a: boolean = adone.is.pathAbsolute("abc"); } + { const a: boolean = adone.is.glob("abc"); } + { const a: boolean = adone.is.dotfile("abc"); } + { const a: boolean = adone.is.function(() => { }); } + { const a: boolean = adone.is.asyncFunction(async () => { }); } + { const a: boolean = adone.is.promise({}); } + { const a: boolean = adone.is.validDate("07.08.2017"); } + { const a: boolean = adone.is.buffer({}); } + { const a: boolean = adone.is.callback({}); } + { const a: boolean = adone.is.generator({}); } + { const a: boolean = adone.is.nan({}); } + { const a: boolean = adone.is.finite({}); } + { const a: boolean = adone.is.integer({}); } + { const a: boolean = adone.is.safeInteger({}); } + { const a: boolean = adone.is.array({}); } + { const a: boolean = adone.is.uint8Array({}); } + { const a: boolean = adone.is.configuration({}); } + { const a: boolean = adone.is.long({}); } + { const a: boolean = adone.is.bigNumber({}); } + { const a: boolean = adone.is.exbuffer({}); } + { const a: boolean = adone.is.exdate({}); } + { const a: boolean = adone.is.transform({}); } + { const a: boolean = adone.is.subsystem({}); } + { const a: boolean = adone.is.application({}); } + { const a: boolean = adone.is.logger({}); } + { const a: boolean = adone.is.coreStream({}); } + { const a: boolean = adone.is.fastStream({}); } + { const a: boolean = adone.is.fastFSStream({}); } + { const a: boolean = adone.is.fastFSMapStream({}); } + { const a: boolean = adone.is.genesisNetron({}); } + { const a: boolean = adone.is.genesisPeer({}); } + { const a: boolean = adone.is.netronAdapter({}); } + { const a: boolean = adone.is.netron({}); } + { const a: boolean = adone.is.netronPeer({}); } + { const a: boolean = adone.is.netronDefinition({}); } + { const a: boolean = adone.is.netronDefinitions({}); } + { const a: boolean = adone.is.netronReference({}); } + { const a: boolean = adone.is.netronInterface({}); } + { const a: boolean = adone.is.netronContext({}); } + { const a: boolean = adone.is.netronIMethod({}, "hello"); } + { const a: boolean = adone.is.netronIProperty({}, "hello"); } + { const a: boolean = adone.is.netronStub({}); } + { const a: boolean = adone.is.netronRemoteStub({}); } + { const a: boolean = adone.is.netronStream({}); } + { const a: boolean = adone.is.iterable({}); } + { const a: boolean = adone.is.windows; } + { const a: boolean = adone.is.linux; } + { const a: boolean = adone.is.freebsd; } + { const a: boolean = adone.is.darwin; } + { const a: boolean = adone.is.sunos; } + { const a: boolean = adone.is.uppercase("abc"); } + { const a: boolean = adone.is.lowercase("abc"); } + { const a: boolean = adone.is.digits("012"); } + { const a: boolean = adone.is.identifier("someMethod"); } + { const a: boolean = adone.is.binaryExtension("mp3"); } + { const a: boolean = adone.is.binaryPath("a.mp3"); } + { const a: boolean = adone.is.ip4("192.168.1.1"); } + { const a: boolean = adone.is.ip6("::192.168.1.1"); } + { const a: boolean = adone.is.arrayBuffer({}); } + { const a: boolean = adone.is.arrayBufferView({}); } + { const a: boolean = adone.is.date({}); } + { const a: boolean = adone.is.error({}); } + { const a: boolean = adone.is.map({}); } + { const a: boolean = adone.is.regexp({}); } + { const a: boolean = adone.is.set({}); } + { const a: boolean = adone.is.symbol({}); } + { const a: boolean = adone.is.validUTF8({}); } + } + + namespace x { + { const a: Error = new adone.x.Exception(); } + { const a: Error = new adone.x.Exception("message"); } + { const a: Error = new adone.x.Exception(new Error()); } + { const a: Error = new adone.x.Exception(new Error(), true); } + { const a: adone.x.Exception = new adone.x.Runtime(); } + { const a: adone.x.Exception = new adone.x.IncompleteBufferError(); } + { const a: adone.x.Exception = new adone.x.NotImplemented(); } + { const a: adone.x.Exception = new adone.x.IllegalState(); } + { const a: adone.x.Exception = new adone.x.NotValid(); } + { const a: adone.x.Exception = new adone.x.Unknown(); } + { const a: adone.x.Exception = new adone.x.NotExists(); } + { const a: adone.x.Exception = new adone.x.Exists(); } + { const a: adone.x.Exception = new adone.x.Empty(); } + { const a: adone.x.Exception = new adone.x.InvalidAccess(); } + { const a: adone.x.Exception = new adone.x.NotSupported(); } + { const a: adone.x.Exception = new adone.x.InvalidArgument(); } + { const a: adone.x.Exception = new adone.x.InvalidNumberOfArguments(); } + { const a: adone.x.Exception = new adone.x.NotFound(); } + { const a: adone.x.Exception = new adone.x.Timeout(); } + { const a: adone.x.Exception = new adone.x.Incorrect(); } + { const a: adone.x.Exception = new adone.x.NotAllowed(); } + { const a: adone.x.Exception = new adone.x.LimitExceeded(); } + { const a: adone.x.Exception = new adone.x.Encoding(); } + { const a: adone.x.Exception = new adone.x.Network(); } + { const a: adone.x.Exception = new adone.x.Bind(); } + { const a: adone.x.Exception = new adone.x.Connect(); } + { const a: adone.x.Exception = new adone.x.Database(); } + { const a: adone.x.Exception = new adone.x.DatabaseInitialization(); } + { const a: adone.x.Exception = new adone.x.DatabaseOpen(); } + { const a: adone.x.Exception = new adone.x.DatabaseRead(); } + { const a: adone.x.Exception = new adone.x.DatabaseWrite(); } + { const a: adone.x.Exception = new adone.x.NetronIllegalState(); } + { const a: adone.x.Exception = new adone.x.NetronPeerDisconnected(); } + { const a: adone.x.Exception = new adone.x.NetronTimeout(); } + } + + namespace EventEmitter { + namespace static { + const a: number = adone.EventEmitter.listenerCount(new adone.EventEmitter(), "event"); + const b: number = adone.EventEmitter.defaultMaxListeners; + } + + namespace addListener { + const a: adone.EventEmitter = new adone.EventEmitter().addListener("event", () => { }); + const b: adone.EventEmitter = new adone.EventEmitter().addListener(Symbol("event"), () => { }); + } + + namespace on { + const a: adone.EventEmitter = new adone.EventEmitter().on("event", () => { }); + const b: adone.EventEmitter = new adone.EventEmitter().on(Symbol("event"), () => { }); + } + + namespace once { + const a: adone.EventEmitter = new adone.EventEmitter().once("event", () => { }); + const b: adone.EventEmitter = new adone.EventEmitter().once(Symbol("event"), () => { }); + } + + namespace prependListener { + const a: adone.EventEmitter = new adone.EventEmitter().prependListener("event", () => { }); + const b: adone.EventEmitter = new adone.EventEmitter().prependListener(Symbol("event"), () => { }); + } + + namespace prependOnceListener { + const a: adone.EventEmitter = new adone.EventEmitter().prependOnceListener("event", () => { }); + const b: adone.EventEmitter = new adone.EventEmitter().prependOnceListener(Symbol("event"), () => { }); + } + + namespace prependOnceListener { + const a: adone.EventEmitter = new adone.EventEmitter().prependOnceListener("event", () => { }); + const b: adone.EventEmitter = new adone.EventEmitter().prependOnceListener(Symbol("event"), () => { }); + } + + namespace removeListener { + const a: adone.EventEmitter = new adone.EventEmitter().removeListener("event", () => { }); + const b: adone.EventEmitter = new adone.EventEmitter().removeListener(Symbol("event"), () => { }); + } + + namespace removeAllListeners { + const a: adone.EventEmitter = new adone.EventEmitter().removeAllListeners("event"); + const b: adone.EventEmitter = new adone.EventEmitter().removeAllListeners(Symbol("event")); + } + + namespace setMaxListeners { + const a: adone.EventEmitter = new adone.EventEmitter().setMaxListeners(10); + } + + namespace getMaxListeners { + const a: number = new adone.EventEmitter().getMaxListeners(); + } + + namespace listeners { + const a: Array<(...args: any[]) => any> = new adone.EventEmitter().listeners("event"); + const b: Array<(...args: any[]) => any> = new adone.EventEmitter().listeners(Symbol("event")); + } + + namespace emit { + const a: boolean = new adone.EventEmitter().emit("event", 1, 2, 3); + const b: boolean = new adone.EventEmitter().emit(Symbol("event"), 1, 2, 3); + } + + namespace eventNames { + const a: Array = new adone.EventEmitter().eventNames(); + const b: Array = new adone.EventEmitter().eventNames(); + } + + namespace listenerCount { + const a: number = new adone.EventEmitter().listenerCount("event"); + const b: number = new adone.EventEmitter().listenerCount(Symbol("event")); + } + } + + namespace AsyncEmitter { + const a: adone.EventEmitter = new adone.AsyncEmitter(); + new adone.AsyncEmitter(10); + + namespace setConcurrency { + const a: adone.AsyncEmitter = new adone.AsyncEmitter().setConcurrency(); + const b: adone.AsyncEmitter = new adone.AsyncEmitter().setConcurrency(10); + } + + namespace emitParallel { + const a: Promise = new adone.AsyncEmitter().emitParallel("even"); + const b: Promise = new adone.AsyncEmitter().emitParallel("even", 1, 2, 3); + } + + namespace emitSerial { + const a: Promise = new adone.AsyncEmitter().emitSerial("even"); + const b: Promise = new adone.AsyncEmitter().emitSerial("even", 1, 2, 3); + } + + namespace emitReduce { + const a: Promise = new adone.AsyncEmitter().emitReduce("even"); + const b: Promise = new adone.AsyncEmitter().emitReduce("even", 1, 2, 3); + } + + namespace emitReduceRight { + const a: Promise = new adone.AsyncEmitter().emitReduceRight("even"); + const b: Promise = new adone.AsyncEmitter().emitReduceRight("even", 1, 2, 3); + } + + namespace subscribe { + const a: () => void = new adone.AsyncEmitter().subscribe("event", () => { }); + const b: () => void = new adone.AsyncEmitter().subscribe("event", () => { }, true); + } + } + + namespace ExBuffer { + new adone.ExBuffer(); + new adone.ExBuffer(10); + new adone.ExBuffer(10, true); + + const buffer = new adone.ExBuffer(); + + namespace readBitSet { + const a: number[] = buffer.readBitSet(); + const b: number[] = buffer.readBitSet(10); + } + + namespace read { + const a: adone.ExBuffer = buffer.read(1); + const b: adone.ExBuffer = buffer.read(1, 10); + } + + namespace readInt8 { + const a: number = buffer.readInt8(); + const b: number = buffer.readInt8(10); + } + + namespace readUInt8 { + const a: number = buffer.readUInt8(); + const b: number = buffer.readUInt8(10); + } + + namespace readInt16LE { + const a: number = buffer.readInt16LE(); + const b: number = buffer.readInt16LE(10); + } + + namespace readUInt16LE { + const a: number = buffer.readUInt16LE(); + const b: number = buffer.readUInt16LE(10); + } + + namespace readInt16BE { + const a: number = buffer.readInt16BE(); + const b: number = buffer.readInt16BE(10); + } + + namespace readUInt16BE { + const a: number = buffer.readUInt16BE(); + const b: number = buffer.readUInt16BE(10); + } + + namespace readInt32LE { + const a: number = buffer.readInt32LE(); + const b: number = buffer.readInt32LE(10); + } + + namespace readUInt32LE { + const a: number = buffer.readUInt32LE(); + const b: number = buffer.readUInt32LE(10); + } + + namespace readInt32BE { + const a: number = buffer.readInt32BE(); + const b: number = buffer.readInt32BE(10); + } + + namespace readUInt32BE { + const a: number = buffer.readUInt32BE(); + const b: number = buffer.readUInt32BE(10); + } + + namespace readInt64LE { + const a: adone.math.Long = buffer.readInt64LE(); + const b: adone.math.Long = buffer.readInt64LE(10); + } + + namespace readUInt64LE { + const a: adone.math.Long = buffer.readUInt64LE(); + const b: adone.math.Long = buffer.readUInt64LE(10); + } + + namespace readInt64BE { + const a: adone.math.Long = buffer.readInt64BE(); + const b: adone.math.Long = buffer.readInt64BE(10); + } + + namespace readUInt64BE { + const a: adone.math.Long = buffer.readUInt64BE(); + const b: adone.math.Long = buffer.readUInt64BE(10); + } + + namespace readFloatLE { + const a: number = buffer.readFloatLE(); + const b: number = buffer.readFloatLE(10); + } + + namespace readFloatBE { + const a: number = buffer.readFloatBE(); + const b: number = buffer.readFloatBE(10); + } + + namespace readDoubleLE { + const a: number = buffer.readDoubleLE(); + const b: number = buffer.readDoubleLE(10); + } + + namespace readDoubleBE { + const a: number = buffer.readDoubleBE(); + const b: number = buffer.readDoubleBE(10); + } + + namespace write { + const a: adone.ExBuffer = buffer.write("1"); + const b: adone.ExBuffer = buffer.write(new adone.ExBuffer()); + const c: adone.ExBuffer = buffer.write(Buffer.alloc(10)); + const d: adone.ExBuffer = buffer.write(new Uint8Array([1, 2, 3])); + const e: adone.ExBuffer = buffer.write(new ArrayBuffer(10)); + const f: adone.ExBuffer = buffer.write("1", 10); + const g: adone.ExBuffer = buffer.write("1", 10, 10); + const h: adone.ExBuffer = buffer.write("1", 10, 10, "utf8"); + } + + namespace writeBitSet { + const a: adone.ExBuffer = buffer.writeBitSet([1, 2, 3]); + const b: number = buffer.writeBitSet([1, 2, 3], 10); + } + + namespace writeInt8 { + const a: adone.ExBuffer = buffer.writeInt8(10); + const b: adone.ExBuffer = buffer.writeInt8(10, 10); + } + + namespace writeUInt8 { + const a: adone.ExBuffer = buffer.writeUInt8(10); + const b: adone.ExBuffer = buffer.writeUInt8(10, 10); + } + + namespace writeInt16LE { + const a: adone.ExBuffer = buffer.writeInt16LE(10); + const b: adone.ExBuffer = buffer.writeInt16LE(10, 10); + } + + namespace writeInt16BE { + const a: adone.ExBuffer = buffer.writeInt16BE(10); + const b: adone.ExBuffer = buffer.writeInt16BE(10, 10); + } + + namespace writeUInt16LE { + const a: adone.ExBuffer = buffer.writeUInt16LE(10); + const b: adone.ExBuffer = buffer.writeUInt16LE(10, 10); + } + + namespace writeUInt16BE { + const a: adone.ExBuffer = buffer.writeUInt16BE(10); + const b: adone.ExBuffer = buffer.writeUInt16BE(10, 10); + } + + namespace writeInt32LE { + const a: adone.ExBuffer = buffer.writeInt32LE(10); + const b: adone.ExBuffer = buffer.writeInt32LE(10, 10); + } + + namespace writeInt32BE { + const a: adone.ExBuffer = buffer.writeInt32BE(10); + const b: adone.ExBuffer = buffer.writeInt32BE(10, 10); + } + + namespace writeUInt32LE { + const a: adone.ExBuffer = buffer.writeUInt32LE(10); + const b: adone.ExBuffer = buffer.writeUInt32LE(10, 10); + } + + namespace writeUInt32BE { + const a: adone.ExBuffer = buffer.writeUInt32BE(10); + const b: adone.ExBuffer = buffer.writeUInt32BE(10, 10); + } + + namespace writeInt64LE { + const a: adone.ExBuffer = buffer.writeInt64LE(10); + const b: adone.ExBuffer = buffer.writeInt64LE(10, 10); + } + + namespace writeInt64BE { + const a: adone.ExBuffer = buffer.writeInt64BE(10); + const b: adone.ExBuffer = buffer.writeInt64BE(10, 10); + } + + namespace writeUInt64LE { + const a: adone.ExBuffer = buffer.writeUInt64LE(10); + const b: adone.ExBuffer = buffer.writeUInt64LE(10, 10); + } + + namespace writeUInt64BE { + const a: adone.ExBuffer = buffer.writeUInt64BE(10); + const b: adone.ExBuffer = buffer.writeUInt64BE(10, 10); + } + + namespace writeFloatLE { + const a: adone.ExBuffer = buffer.writeFloatLE(10); + const b: adone.ExBuffer = buffer.writeFloatLE(10, 10); + } + + namespace writeFloatBE { + const a: adone.ExBuffer = buffer.writeFloatBE(10); + const b: adone.ExBuffer = buffer.writeFloatBE(10, 10); + } + + namespace writeDoubleLE { + const a: adone.ExBuffer = buffer.writeDoubleLE(10); + const b: adone.ExBuffer = buffer.writeDoubleLE(10, 10); + } + + namespace writeDoubleBE { + const a: adone.ExBuffer = buffer.writeDoubleBE(10); + const b: adone.ExBuffer = buffer.writeDoubleBE(10, 10); + } + + namespace writeVarInt32 { + const a: adone.ExBuffer = buffer.writeVarint32(10); + const b: number = buffer.writeVarint32(10, 10); + } + + namespace writeVarInt32ZigZag { + const a: adone.ExBuffer = buffer.writeVarint32ZigZag(10); + const b: number = buffer.writeVarint32ZigZag(10, 10); + } + + namespace readVarint32 { + const a: number = buffer.readVarint32(); + const b: { value: number, length: number } = buffer.readVarint32(10); + } + + namespace readVarint32ZigZag { + const a: number = buffer.readVarint32ZigZag(); + const b: { value: number, length: number } = buffer.readVarint32ZigZag(10); + } + + namespace writeVarint64 { + const a: adone.ExBuffer = buffer.writeVarint64(10); + const b: number = buffer.writeVarint64(10, 10); + } + + namespace writeVarint64ZigZag { + const a: adone.ExBuffer = buffer.writeVarint64ZigZag(10); + const b: number = buffer.writeVarint64ZigZag(10, 10); + } + + namespace readVarint64 { + const a: adone.math.Long = buffer.readVarint64(); + const b: { value: adone.math.Long, length: number } = buffer.readVarint64(10); + } + + namespace readVarint64ZigZag { + const a: adone.math.Long = buffer.readVarint64ZigZag(); + const b: { value: adone.math.Long, length: number } = buffer.readVarint64ZigZag(10); + } + + namespace writeCString { + const a: adone.ExBuffer = buffer.writeCString("asd"); + const b: number = buffer.writeCString("123", 10); + } + + namespace readCString { + const a: string = buffer.readCString(); + const b: { string: string, length: number } = buffer.readCString(10); + } + + namespace writeString { + const a: adone.ExBuffer = buffer.writeString("abc"); + const b: number = buffer.writeString("abc", 10); + } + + namespace readString { + const a: string = buffer.readString(10); + const b: string = buffer.readString(10, "b"); + const c: string = buffer.readString(10, "c"); + const d: { string: string, length: number } = buffer.readString(10, "c", 10); + } + + namespace writeVString { + const a: adone.ExBuffer = buffer.writeVString("abc"); + const b: number = buffer.writeVString("abc", 10); + } + + namespace readVString { + const a: string = buffer.readVString(); + const b: { string: string, length: number } = buffer.readVString(10); + } + + namespace appendTo { + const a: adone.ExBuffer = buffer.appendTo(new adone.ExBuffer()); + const b: adone.ExBuffer = buffer.appendTo(new adone.ExBuffer(), 10); + } + + namespace assert { + const a: adone.ExBuffer = buffer.assert(); + const b: adone.ExBuffer = buffer.assert(true); + } + + namespace capacity { + const a: number = buffer.capacity(); + } + + namespace clear { + const a: adone.ExBuffer = buffer.clear(); + } + + namespace compact { + const a: adone.ExBuffer = buffer.compact(); + const b: adone.ExBuffer = buffer.compact(1); + const c: adone.ExBuffer = buffer.compact(1, 10); + } + + namespace copyTo { + const a: adone.ExBuffer = buffer.copyTo(new adone.ExBuffer()); + const b: adone.ExBuffer = buffer.copyTo(new adone.ExBuffer(), 0); + const c: adone.ExBuffer = buffer.copyTo(new adone.ExBuffer(), 0, 0); + const d: adone.ExBuffer = buffer.copyTo(new adone.ExBuffer(), 0, 0, 10); + } + + namespace ensureCapacity { + const a: adone.ExBuffer = buffer.ensureCapacity(10); + } + + namespace fill { + const a: adone.ExBuffer = buffer.fill("0"); + const b: adone.ExBuffer = buffer.fill(0); + const c: adone.ExBuffer = buffer.fill(0, 0); + const d: adone.ExBuffer = buffer.fill(0, 0, 10); + } + + namespace flip { + const a: adone.ExBuffer = buffer.flip(); + } + + namespace mark { + const a: adone.ExBuffer = buffer.mark(); + const b: adone.ExBuffer = buffer.mark(10); + } + + namespace prepend { + const a: adone.ExBuffer = buffer.prepend(""); + const b: adone.ExBuffer = buffer.prepend(new adone.ExBuffer()); + const c: adone.ExBuffer = buffer.prepend(Buffer.alloc(10)); + const d: adone.ExBuffer = buffer.prepend(new Uint8Array([1, 2, 3])); + const e: adone.ExBuffer = buffer.prepend(new ArrayBuffer(10)); + const f: adone.ExBuffer = buffer.prepend("", "utf8"); + const g: adone.ExBuffer = buffer.prepend("", "utf8", 10); + const h: adone.ExBuffer = buffer.prepend("", 10); + } + + namespace prependTo { + const a: adone.ExBuffer = buffer.prependTo(new adone.ExBuffer()); + const b: adone.ExBuffer = buffer.prependTo(new adone.ExBuffer(), 10); + } + + namespace remaining { + const a: number = buffer.remaining(); + } + + namespace reset { + const a: adone.ExBuffer = buffer.reset(); + } + + namespace resize { + const a: adone.ExBuffer = buffer.resize(10); + } + + namespace reverse { + const a: adone.ExBuffer = buffer.reverse(); + const b: adone.ExBuffer = buffer.reverse(1); + const c: adone.ExBuffer = buffer.reverse(1, 10); + } + + namespace skip { + const a: adone.ExBuffer = buffer.skip(10); + } + + namespace slice { + const a: adone.ExBuffer = buffer.slice(); + const b: adone.ExBuffer = buffer.slice(1); + const c: adone.ExBuffer = buffer.slice(1, 10); + } + + namespace toBuffer { + const a: Buffer = buffer.toBuffer(); + const b: Buffer = buffer.toBuffer(true); + const c: Buffer = buffer.toBuffer(true, 0); + const d: Buffer = buffer.toBuffer(true, 0, 10); + } + + namespace toArrayBuffer { + const a: ArrayBuffer = buffer.toArrayBuffer(); + } + + namespace toString { + const a: string = buffer.toString(); + const b: string = buffer.toString("utf8"); + const c: string = buffer.toString("utf8", 0); + const d: string = buffer.toString("utf8", 0, 10); + } + + namespace toBase64 { + const a: string = buffer.toBase64(); + const b: string = buffer.toBase64(0); + const c: string = buffer.toBase64(0, 10); + } + + namespace toBinary { + const a: string = buffer.toBinary(); + const b: string = buffer.toBinary(0); + const c: string = buffer.toBinary(0, 10); + } + + namespace toDebug { + const a: string = buffer.toDebug(); + const b: string = buffer.toDebug(true); + } + + namespace toUTF8 { + const a: string = buffer.toUTF8(); + const b: string = buffer.toUTF8(0); + const c: string = buffer.toUTF8(0, 10); + } + + namespace static { + namespace accessor { + const a: typeof Buffer = adone.ExBuffer.accessor(); + } + + namespace allocate { + const a: adone.ExBuffer = adone.ExBuffer.allocate(); + const b: adone.ExBuffer = adone.ExBuffer.allocate(10); + const c: adone.ExBuffer = adone.ExBuffer.allocate(10, true); + } + + namespace concat { + const a: adone.ExBuffer = adone.ExBuffer.concat([ + new adone.ExBuffer(), + Buffer.alloc(10), + new Uint8Array([1, 2, 3]), + new ArrayBuffer(10) + ]); + const b: adone.ExBuffer = adone.ExBuffer.concat([ + new adone.ExBuffer(), + Buffer.alloc(10), + new Uint8Array([1, 2, 3]), + new ArrayBuffer(10) + ], "utf8"); + const c: adone.ExBuffer = adone.ExBuffer.concat([ + new adone.ExBuffer(), + Buffer.alloc(10), + new Uint8Array([1, 2, 3]), + new ArrayBuffer(10) + ], "utf8", true); + } + + namespace type { + const a: typeof Buffer = adone.ExBuffer.type(); + } + + namespace wrap { + const a: adone.ExBuffer = adone.ExBuffer.wrap(""); + const b: adone.ExBuffer = adone.ExBuffer.wrap(new adone.ExBuffer()); + const c: adone.ExBuffer = adone.ExBuffer.wrap(Buffer.alloc(10)); + const d: adone.ExBuffer = adone.ExBuffer.wrap(new Uint8Array([1, 2, 3])); + const e: adone.ExBuffer = adone.ExBuffer.wrap(new ArrayBuffer(10)); + const f: adone.ExBuffer = adone.ExBuffer.wrap("", "utf8"); + const g: adone.ExBuffer = adone.ExBuffer.wrap("", "utf8", true); + } + + namespace calculateVarint32 { + const a: number = adone.ExBuffer.calculateVarint32(10); + } + + namespace zigZagEncode32 { + const a: number = adone.ExBuffer.zigZagEncode32(10); + } + + namespace zigZagDecode32 { + const a: number = adone.ExBuffer.zigZagDecode32(10); + } + + namespace calculateVarint64 { + const a: number = adone.ExBuffer.calculateVarint64(10); + const b: number = adone.ExBuffer.calculateVarint64("10"); + } + + namespace zigZagEncode64 { + const a: adone.math.Long = adone.ExBuffer.zigZagEncode64(10); + const b: adone.math.Long = adone.ExBuffer.zigZagEncode64("10"); + const c: adone.math.Long = adone.ExBuffer.zigZagEncode64(adone.math.Long.fromValue(10)); + } + + namespace zigZagDecode64 { + const a: adone.math.Long = adone.ExBuffer.zigZagDecode64(10); + const b: adone.math.Long = adone.ExBuffer.zigZagDecode64("10"); + const c: adone.math.Long = adone.ExBuffer.zigZagDecode64(adone.math.Long.fromValue(10)); + } + + namespace calculateUTF8Chars { + const a: number = adone.ExBuffer.calculateUTF8Chars("123"); + } + + namespace calculateString { + const a: number = adone.ExBuffer.calculateString("123"); + } + + namespace fromBase64 { + const a: adone.ExBuffer = adone.ExBuffer.fromBase64("123"); + } + + namespace btoa { + const a: string = adone.ExBuffer.btoa("123"); + } + + namespace atob { + const a: string = adone.ExBuffer.atob("123"); + } + + namespace fromBinary { + const a: adone.ExBuffer = adone.ExBuffer.fromBinary("123"); + } + + namespace fromDebug { + const a: adone.ExBuffer = adone.ExBuffer.fromDebug("12"); + const b: adone.ExBuffer = adone.ExBuffer.fromDebug("12", true); + } + + namespace fromHex { + const a: adone.ExBuffer = adone.ExBuffer.fromHex("192"); + const b: adone.ExBuffer = adone.ExBuffer.fromHex("192", true); + } + + namespace fromUTF8 { + const a: adone.ExBuffer = adone.ExBuffer.fromUTF8("123"); + const b: adone.ExBuffer = adone.ExBuffer.fromUTF8("123", true); + } + + namespace constants { + const a: number = adone.ExBuffer.DEFAULT_CAPACITY; + const b: boolean = adone.ExBuffer.DEFAULT_NOASSERT; + const c: number = adone.ExBuffer.MAX_VARINT32_BYTES; + const d: number = adone.ExBuffer.MAX_VARINT64_BYTES; + const e: string = adone.ExBuffer.METRICS_CHARS; + const f: string = adone.ExBuffer.METRICS_BYTES; + } + } + } +} diff --git a/types/adone/test/glosses/math.ts b/types/adone/test/glosses/math.ts new file mode 100644 index 0000000000..8a9e9bc1cf --- /dev/null +++ b/types/adone/test/glosses/math.ts @@ -0,0 +1,259 @@ +const { math } = adone; + +namespace mathTests { + namespace Long { + new math.Long(); + new math.Long(0); + new math.Long(0, 0); + new math.Long(0, 0, true); + + namespace toInt { + const a: number = new math.Long().toInt(); + } + + namespace toNumber { + const a: number = new math.Long().toNumber(); + } + + namespace toString { + const a: string = new math.Long().toString(); + const b: string = new math.Long().toString(16); + } + + namespace getHighBits { + const a: number = new math.Long().getHighBits(); + } + + namespace getLowBits { + const a: number = new math.Long().getLowBits(); + } + + namespace getLowBitsUnsigned { + const a: number = new math.Long().getLowBitsUnsigned(); + } + + namespace getHighBitsUnsigned { + const a: number = new math.Long().getHighBitsUnsigned(); + } + + namespace getNumBitsAbs { + const a: number = new math.Long().getNumBitsAbs(); + } + + namespace isZero { + const a: boolean = new math.Long().isZero(); + } + + namespace isNegative { + const a: boolean = new math.Long().isNegative(); + } + + namespace isPositive { + const a: boolean = new math.Long().isPositive(); + } + + namespace isOdd { + const a: boolean = new math.Long().isOdd(); + } + + namespace isEven { + const a: boolean = new math.Long().isEven(); + } + + namespace equals { + const a = new math.Long(); + const b: boolean = a.equals(new math.Long()); + const c: boolean = a.equals(1); + const d: boolean = a.equals("1"); + const e: boolean = a.equals({ low: 0, high: 0 }); + } + + namespace lessThan { + const a = new math.Long(); + const b: boolean = a.lessThan(new math.Long()); + const c: boolean = a.lessThan(1); + const d: boolean = a.lessThan("1"); + const e: boolean = a.lessThan({ low: 0, high: 0 }); + } + + namespace lessThanOrEqual { + const a = new math.Long(); + const b: boolean = a.lessThanOrEqual(new math.Long()); + const c: boolean = a.lessThanOrEqual(1); + const d: boolean = a.lessThanOrEqual("1"); + const e: boolean = a.lessThanOrEqual({ low: 0, high: 0 }); + } + + namespace greaterThan { + const a = new math.Long(); + const b: boolean = a.greaterThan(new math.Long()); + const c: boolean = a.greaterThan(1); + const d: boolean = a.greaterThan("1"); + const e: boolean = a.greaterThan({ low: 0, high: 0 }); + } + + namespace greaterThanOrEqual { + const a = new math.Long(); + const b: boolean = a.greaterThanOrEqual(new math.Long()); + const c: boolean = a.greaterThanOrEqual(1); + const d: boolean = a.greaterThanOrEqual("1"); + const e: boolean = a.greaterThanOrEqual({ low: 0, high: 0 }); + } + + namespace greaterThanOrEqual { + const a = new math.Long(); + const b: number = a.compare(new math.Long()); + const c: number = a.compare(1); + const d: number = a.compare("1"); + const e: number = a.compare({ low: 0, high: 0 }); + } + + namespace negate { + const a: adone.math.Long = new math.Long().negate(); + } + + namespace add { + const a = new math.Long(); + const b: adone.math.Long = a.add(new math.Long()); + const c: adone.math.Long = a.add(1); + const d: adone.math.Long = a.add("1"); + const e: adone.math.Long = a.add({ low: 0, high: 0 }); + } + + namespace sub { + const a = new math.Long(); + const b: adone.math.Long = a.sub(new math.Long()); + const c: adone.math.Long = a.sub(1); + const d: adone.math.Long = a.sub("1"); + const e: adone.math.Long = a.sub({ low: 0, high: 0 }); + } + + namespace mul { + const a = new math.Long(); + const b: adone.math.Long = a.mul(new math.Long()); + const c: adone.math.Long = a.mul(1); + const d: adone.math.Long = a.mul("1"); + const e: adone.math.Long = a.mul({ low: 0, high: 0 }); + } + + namespace div { + const a = new math.Long(); + const b: adone.math.Long = a.div(new math.Long()); + const c: adone.math.Long = a.div(1); + const d: adone.math.Long = a.div("1"); + const e: adone.math.Long = a.div({ low: 0, high: 0 }); + } + + namespace mod { + const a = new math.Long(); + const b: adone.math.Long = a.mod(new math.Long()); + const c: adone.math.Long = a.mod(1); + const d: adone.math.Long = a.mod("1"); + const e: adone.math.Long = a.mod({ low: 0, high: 0 }); + } + + namespace not { + const a: adone.math.Long = new math.Long().not(); + } + + namespace and { + const a = new math.Long(); + const b: adone.math.Long = a.and(new math.Long()); + const c: adone.math.Long = a.and(1); + const d: adone.math.Long = a.and("1"); + const e: adone.math.Long = a.and({ low: 0, high: 0 }); + } + + namespace or { + const a = new math.Long(); + const b: adone.math.Long = a.or(new math.Long()); + const c: adone.math.Long = a.or(1); + const d: adone.math.Long = a.or("1"); + const e: adone.math.Long = a.or({ low: 0, high: 0 }); + } + + namespace xor { + const a = new math.Long(); + const b: adone.math.Long = a.xor(new math.Long()); + const c: adone.math.Long = a.xor(1); + const d: adone.math.Long = a.xor("1"); + const e: adone.math.Long = a.xor({ low: 0, high: 0 }); + } + + namespace shl { + const a = new math.Long(); + const b: adone.math.Long = a.shl(new math.Long()); + const c: adone.math.Long = a.shl(1); + } + + namespace shr { + const a = new math.Long(); + const b: adone.math.Long = a.shr(new math.Long()); + const c: adone.math.Long = a.shr(1); + } + + namespace shru { + const a = new math.Long(); + const b: adone.math.Long = a.shr(new math.Long()); + const c: adone.math.Long = a.shr(1); + } + + namespace toSigned { + const a: adone.math.Long = new math.Long().toSigned(); + } + + namespace toUnsigned { + const a: adone.math.Long = new math.Long().toUnsigned(); + } + + namespace toBytes { + const a: number[] = new math.Long().toBytes(); + } + + namespace toBytesLE { + const a: number[] = new math.Long().toBytesLE(); + } + + namespace static { + namespace fromInt { + const a: adone.math.Long = math.Long.fromInt(123); + const b: adone.math.Long = math.Long.fromInt(123, true); + } + + namespace fromNumber { + const a: adone.math.Long = math.Long.fromNumber(123); + const b: adone.math.Long = math.Long.fromNumber(123, true); + } + + namespace fromBits { + const a: adone.math.Long = math.Long.fromBits(0, 0); + const b: adone.math.Long = math.Long.fromBits(123, 0, true); + } + + namespace fromString { + const a: adone.math.Long = math.Long.fromString("123"); + const b: adone.math.Long = math.Long.fromString("123", true); + const c: adone.math.Long = math.Long.fromString("123", 16); + const d: adone.math.Long = math.Long.fromString("123", true, 16); + } + + namespace fromValue { + const a: adone.math.Long = math.Long.fromValue(new math.Long()); + const b: adone.math.Long = math.Long.fromValue(1); + const c: adone.math.Long = math.Long.fromValue("1"); + const e: adone.math.Long = math.Long.fromValue({ low: 0, high: 0 }); + } + + namespace constants { + const a: adone.math.Long = math.Long.MIN_VALUE; + const b: adone.math.Long = math.Long.MAX_VALUE; + const c: adone.math.Long = math.Long.MAX_UNSIGNED_VALUE; + const d: adone.math.Long = math.Long.ZERO; + const e: adone.math.Long = math.Long.UZERO; + const f: adone.math.Long = math.Long.ONE; + const g: adone.math.Long = math.Long.UONE; + const h: adone.math.Long = math.Long.NEG_ONE; + } + } + } +} diff --git a/types/adone/test/glosses/std.ts b/types/adone/test/glosses/std.ts new file mode 100644 index 0000000000..611f9401e9 --- /dev/null +++ b/types/adone/test/glosses/std.ts @@ -0,0 +1,161 @@ +import adone from "adone"; + +import * as assert from "assert"; +import * as fs from "fs"; +import * as path from "path"; +import * as util from "util"; +import * as events from "events"; +import * as stream from "stream"; +import * as url from "url"; +import * as net from "net"; +import * as http from "http"; +import * as https from "https"; +import * as child_process from "child_process"; +import * as os from "os"; +import * as cluster from "cluster"; +import * as repl from "repl"; +import * as punycode from "punycode"; +import * as readline from "readline"; +import * as string_decoder from "string_decoder"; +import * as querystring from "querystring"; +import * as crypto from "crypto"; +import * as vm from "vm"; +import * as v8 from "v8"; +import * as domain from "domain"; +import * as tty from "tty"; +import * as buffer from "buffer"; +import * as constants from "constants"; +import * as zlib from "zlib"; +import * as tls from "tls"; +import * as console from "console"; +import * as dns from "dns"; +import * as timers from "timers"; +import * as dgram from "dgram"; + +const { std } = adone; + +namespace stdTests { + namespace assert { + std.assert(true); + } + + namespace fs { + std.fs.readFileSync("test").length; + } + + namespace path { + std.path.join("a", "b").charAt(0); + } + + namespace util { + std.util.format("hello").charAt(0); + } + + namespace events { + new std.events.EventEmitter().on("event", () => {}); + } + + namespace steam { + new std.stream.PassThrough().resume(); + } + + namespace url { + std.url.parse("https://adone.io").hostname; + } + + namespace net { + std.net.connect(31337).write("hello"); + } + + namespace http { + std.http.get("http://localhost").end(); + } + + namespace https { + std.https.get("https://adone.io").end(); + } + + namespace child_process { + std.child_process.fork(__filename, [], { stdio: ["ipc"] }).send("hello"); + } + + namespace os { + std.os.tmpdir().charAt(0); + } + + namespace cluster { + std.cluster.fork().kill(); + } + + namespace repl { + std.repl.start().close(); + } + + namespace punycode { + std.punycode.decode("ads").charAt(0); + } + + namespace readline { + std.readline.clearLine(process.stdout, 1); + } + + namespace string_decoder { + new std.string_decoder.StringDecoder().end().charAt(0); + } + + namespace querystring { + std.querystring.escape("hello").charAt(0); + } + + namespace crypto { + std.crypto.createHash("sha1").update("hello").digest("hex"); + } + + namespace vm { + std.vm.runInContext("a + 2", std.vm.createContext({ a: 1 })); + } + + namespace v8 { + std.v8.getHeapStatistics().heap_size_limit + 2; + } + + namespace domain { + std.domain.create().members; + } + + namespace tty { + std.tty.isatty(1) === true; + } + + namespace buffer { + std.buffer.Buffer.alloc(10); + } + + namespace constants { + std.constants.EACCES + 2; + } + + namespace zlib { + std.zlib.createDeflate().write("ttt"); + } + + namespace tls { + std.tls.connect({}).end(); + } + + namespace console { + std.console.trace("message"); + } + + namespace dns { + std.dns.resolve4("adone.io", (err, data) => {}); + } + + namespace timers { + std.timers.setTimeout(() => {}, 2000).unref(); + } + + namespace dgram { + std.dgram.createSocket("udp4").bind(31337); + } +} diff --git a/types/adone/test/glosses/utils.ts b/types/adone/test/glosses/utils.ts new file mode 100644 index 0000000000..c0f119cb6e --- /dev/null +++ b/types/adone/test/glosses/utils.ts @@ -0,0 +1,736 @@ +const { util } = adone; + +namespace utilTests { + namespace arrify { + const a: number[] = util.arrify([1, 2, 3]); + const b: number[] = util.arrify(1); + const c: string[] = util.arrify("2"); + const d: string[] = util.arrify(["1"]); + } + + namespace slice { + const a: number[] = util.slice([1, 2, 3]); + const b: number[] = util.slice([1, 2, 3], 1); + const c: number[] = util.slice([1, 2, 3], 1, 4); + const d: string[] = util.slice(["1"]); + } + + namespace spliceOne { + util.spliceOne([1, 2, 3], 0); + } + + namespace normalizePath { + const a: string = util.normalizePath("path"); + const b: string = util.normalizePath("path", true); + } + + namespace unixifyPath { + const a: string = util.unixifyPath("path"); + const b: string = util.unixifyPath("path", true); + } + + namespace functionName { + const a: string = util.functionName(function f() { }); + const b: string = util.functionName((a, b, c) => { }); + } + + namespace mapArguments { + const a: (...args: any[]) => any = util.mapArguments(() => { }); + const b: (...args: T[]) => T[] = util.mapArguments(1); + const c: (...args: any[]) => any = util.mapArguments([1]); + const d: (x: T) => T = util.mapArguments(); + } + + namespace parseMs { + const result: { + days: number; + hours: number; + milliseconds: number; + minutes: number; + } = util.parseMs(123); + } + + namespace pluralizeWord { + const a: string = util.pluralizeWord("day"); + const b: string = util.pluralizeWord("day", "days"); + const c: string = util.pluralizeWord("day", "days", 1); + } + + namespace functionParams { + const a: string[] = util.functionParams((a: any, b: any, c: any) => { }); + } + + namespace randomChoice { + const a: number = util.randomChoice([1, 2, 3]); + const b: string = util.randomChoice(["1", "2", "3"]); + } + + namespace shuffleArray { + const a: number[] = util.shuffleArray([1, 2, 3]); + const b: string[] = util.shuffleArray(["1", "2", "3"]); + } + + namespace enumerate { + { + const a = util.enumerate([1, 2, 3]); + const it = a[Symbol.iterator](); + const value: [number, number] = it.next().value; + for (const i of a) { + const [idx, value]: [number, number] = i; + } + } + { + const a = util.enumerate(["1", "2"]); + const it = a[Symbol.iterator](); + const value: [number, string] = it.next().value; + for (const i of a) { + const [idx, value]: [number, string] = i; + } + } + } + + namespace zip { + { + const a = util.zip([1, 2, 3], ["4", "5", "6"]); + const it = a[Symbol.iterator](); + const value: [number, string] = it.next().value; + for (const i of a) { + const [i1, i2]: [number, string] = i; + } + } + { + const a = util.zip( + [1, 2, 3], + ["4", "5", "6"], + [7, 8, 9] + ); + const it = a[Symbol.iterator](); + const value: [number, string, number] = it.next().value; + for (const i of a) { + const [i1, i2, i3]: [number, string, number] = i; + } + } + { + const a = util.zip( + [1, 2, 3], + ["4", "5", "6"], + [7, 8, 9], + ["10", "11", "12"] + ); + const it = a[Symbol.iterator](); + const value: [number, string, number, string] = it.next().value; + for (const i of a) { + const [i1, i2, i3, i4]: [number, string, number, string] = i; + } + } + { + const a = util.zip( + [1, 2, 3], + ["4", "5", "6"], + [7, 8, 9], + ["10", "11", "12"], + [13, 14, 15, 16] + ); + const it = a[Symbol.iterator](); + const value: any[] = it.next().value; + for (const i of a) { + const [i1, i2, i3, i4]: any[] = i; + } + } + } + + namespace keys { + const a: string[] = util.keys({}); + const b: string[] = util.keys({}, { all: true }); + const c: string[] = util.keys({}, { followProto: true }); + const d: string[] = util.keys({}, { onlyEnumerable: true }); + } + + namespace values { + const a: any[] = util.values({}); + const b: any[] = util.values({}, { all: true }); + const c: any[] = util.values({}, { followProto: true }); + const d: any[] = util.values({}, { onlyEnumerable: true }); + } + + namespace entries { + const a: Array<[string, any]> = util.entries({}); + const b: Array<[string, any]> = util.entries({}, { all: true }); + const c: Array<[string, any]> = util.entries({}, { followProto: true }); + const d: Array<[string, any]> = util.entries({}, { onlyEnumerable: true }); + } + + namespace toDotNotation { + const a: object = util.toDotNotation({ a: 1 }); + } + + namespace flatten { + const a: number[] = util.flatten([1, [2, 3]]); + const b: number[] = util.flatten([1, [2, 3]], {}); + const c: number[] = util.flatten([1, [2, 3]], { depth: 1 }); + } + + namespace globParent { + const a: string = util.globParent("a/b/c/**"); + } + + namespace by { + const a: (a: number, b: number) => any = util.by((x: number): number => x); + const b: (a: number, b: number) => number = util.by((x: number): string => `${x}`, (a: string, b: string) => a.length - b.length); + } + + namespace toFastProperties { + const a: object = util.toFastProperties({}); + } + + namespace stripBom { + const a: string = util.stripBom("123"); + } + + namespace sortKeys { + const a: object = util.sortKeys({}); + const b: object = util.sortKeys({}, {}); + const c: object = util.sortKeys({}, { deep: true }); + const d: object = util.sortKeys({}, { compare: (a, b) => 2 }); + } + + namespace globize { + const a: string = util.globize("test"); + const b: string = util.globize("test", {}); + const c: string = util.globize("test", { exts: "" }); + const d: string = util.globize("test", { recursively: true }); + } + + namespace unique { + const a: number[] = util.unique([1, 2, 3]); + const b: string[] = util.unique(["1", "2", "3"]); + const c: object[] = util.unique([{ a: 1 }, { a: 2 }], (obj: any) => obj.a); + } + + namespace invertObject { + const a: object = util.invertObject({}); + const b: object = util.invertObject({}, {}); + const c: object = util.invertObject({}, { all: true }); + const d: object = util.invertObject({}, { followProto: true }); + const e: object = util.invertObject({}, { onlyEnumerable: true }); + } + + namespace humanizeTime { + const a: string = util.humanizeTime(12345); + const b: string = util.humanizeTime(12345, {}); + const c: string = util.humanizeTime(12345, { compact: true }); + const d: string = util.humanizeTime(12345, { msDecimalDigits: 2 }); + const e: string = util.humanizeTime(12345, { secDecimalDigits: 2 }); + const f: string = util.humanizeTime(12345, { verbose: true }); + } + + namespace humanizeSize { + const a: string = util.humanizeSize(12345); + const b: string = util.humanizeSize(12345, ""); + } + + namespace parseSize { + const a: number | null = util.parseSize(123); + const b: number | null = util.parseSize("123Kb"); + } + + namespace clone { + const a: object = util.clone({}); + const b: object = util.clone({}, {}); + const c: object = util.clone({}, { deep: true }); + } + + namespace toUTF8Array { + const a: number[] = util.toUTF8Array("hello"); + } + + namespace asyncIter { + util.asyncIter([1, 2, 3], () => { }, () => { }); + } + + namespace asyncFor { + util.asyncFor({}, () => { }, () => { }); + } + + namespace once { + { + const f = () => 2; + const a: () => number = util.once(f); + } + { + const f = (a: number) => `${a}`; + const a: (a: number) => string = util.once(f); + } + } + + namespace asyncWaterfall { + util.asyncWaterfall([ + (callback: (a: any, b: any, c: any) => void) => { + callback(null, 'one', 'two'); + } + ], (err: any, result: any) => { + // + }); + } + + namespace xrange { + for (const i of util.xrange(10)) { + const a: number = i; + } + for (const i of util.xrange(1, 10)) { + const a: number = i; + } + for (const i of util.xrange(1, 10, 2)) { + const a: number = i; + } + } + namespace range { + const a: number[] = util.range(10); + const b: number[] = util.range(1, 10); + const c: number[] = util.range(1, 10, 2); + } + + namespace reFindAll { + const a: RegExpExecArray[] = util.reFindAll(/\d+/, "1 2 3 4 5"); + } + + namespace assignDeep { + const a: object = util.assignDeep({ a: 1 }, { a: 2 }); + } + + namespace match { + const a: number | boolean = util.match(["a", "b", "c"], "a"); + const b: (a: any, b: any) => number | boolean = util.match("a", { index: true }); + const c: number | boolean = util.match(["a", "b", "c"], "a", { dot: true }); + const d: (a: any, b: any) => number | boolean = util.match("a", { end: 2 }); + const e: (a: any, b: any) => number | boolean = util.match("a", { start: 2 }); + const f: (a: any, b: any) => number | boolean = util.match("a"); + } + + namespace toposort { + const a: number[] = util.toposort([ + [0, 1], + [2, 3], + [4, 5], + [6, 7] + ]); + const b: number[] = util.toposort.array([0, 1, 2], [ + [0, 1], + [2, 3], + [4, 5], + [6, 7] + ]); + } + + namespace jsesc { + const a: string = util.jsesc({ a: 1 }); + const b: string = util.jsesc({ a: 1 }, { escapeEverything: true }); + const c: string = util.jsesc({ a: 1 }, { minimal: true }); + const d: string = util.jsesc({ a: 1 }, { isScriptContext: true }); + const e: string = util.jsesc({ a: 1 }, { quotes: "'" }); + const f: string = util.jsesc({ a: 1 }, { wrap: true }); + const g: string = util.jsesc({ a: 1 }, { es6: true }); + const h: string = util.jsesc({ a: 1 }, { json: true }); + const i: string = util.jsesc({ a: 1 }, { compact: true }); + const j: string = util.jsesc({ a: 1 }, { lowercaseHex: true }); + const k: string = util.jsesc({ a: 1 }, { numbers: "decimal" }); + const l: string = util.jsesc({ a: 1 }, { indent: " " }); + const m: string = util.jsesc({ a: 1 }, { indentLevel: 4 }); + const n: string = util.jsesc({ a: 1 }, { __inline1__: true }); + const o: string = util.jsesc({ a: 1 }, { __inline2__: true }); + } + + namespace typeOf { + const a: string = util.typeOf(1); + } + + namespace memcpy { + const a: number = util.memcpy.utou(Buffer.alloc(10), 0, Buffer.alloc(10), 0, 10); + const b: number = util.memcpy.atoa(new ArrayBuffer(10), 0, new ArrayBuffer(10), 0, 10); + const c: number = util.memcpy.atou(Buffer.alloc(10), 0, new ArrayBuffer(10), 0, 10); + const d: number = util.memcpy.utoa(new ArrayBuffer(10), 0, Buffer.alloc(10), 0, 10); + const e: number = util.memcpy.copy(Buffer.alloc(10), 0, Buffer.alloc(10), 0, 10); + const f: number = util.memcpy.copy(new ArrayBuffer(10), 0, new ArrayBuffer(10), 0, 10); + const g: number = util.memcpy.copy(Buffer.alloc(10), 0, new ArrayBuffer(10), 0, 10); + const h: number = util.memcpy.copy(new ArrayBuffer(10), 0, Buffer.alloc(10), 0, 10); + } + + namespace uuid { + namespace v1 { + const a: string = util.uuid.v1(); + const b: number[] = util.uuid.v1({}, []); + const c: number[] = util.uuid.v1({}, [], 1); + const d: string = util.uuid.v1({}); + const e: string = util.uuid.v1({ clockseq: 1 }); + const f: string = util.uuid.v1({ msecs: 1 }); + const g: string = util.uuid.v1({ nsecs: 1 }); + } + + namespace v4 { + const a: string = util.uuid.v4(); + const b: number[] = util.uuid.v4({}, []); + const c: number[] = util.uuid.v4({}, [], 1); + const d: string = util.uuid.v4({}); + const e: string = util.uuid.v4({ clockseq: 1 }); + const f: string = util.uuid.v4({ msecs: 1 }); + const g: string = util.uuid.v4({ nsecs: 1 }); + } + + namespace v5 { + const a: string = util.uuid.v5([], []); + const b: number[] = util.uuid.v5([], [], []); + const c: number[] = util.uuid.v5([], [], [], 1); + } + } + + namespace delegate { + const a = util.delegate({}, "a"); + a.getter("a").access("b").method("c").setter("d"); + } + + namespace GlobExp { + { + const glob = new util.GlobExp("*.js"); + const a: boolean = glob.hasMagic(); + const b: string[] = glob.expandBraces(); + const c: RegExp = glob.makeRe(); + const d: boolean = glob.test("a.js"); + } + { + const a: boolean = util.GlobExp.hasMagic("*.js"); + const b: string[] = util.GlobExp.expandBraces("*.js"); + const c: RegExp = util.GlobExp.makeRe("*.js"); + const d: boolean = util.GlobExp.test("*.js", "a.js"); + } + new util.GlobExp(""); + new util.GlobExp("", {}); + new util.GlobExp("", { dot: true }); + new util.GlobExp("", { flipNegate: true }); + new util.GlobExp("", { matchBase: true }); + new util.GlobExp("", { nobrace: true }); + new util.GlobExp("", { nocase: true }); + new util.GlobExp("", { nocomment: true }); + new util.GlobExp("", { noext: true }); + new util.GlobExp("", { noglobstar: true }); + new util.GlobExp("", { nonegate: true }); + util.GlobExp.hasMagic("", {}); + util.GlobExp.hasMagic("", { dot: true }); + util.GlobExp.hasMagic("", { flipNegate: true }); + util.GlobExp.hasMagic("", { matchBase: true }); + util.GlobExp.hasMagic("", { nobrace: true }); + util.GlobExp.hasMagic("", { nocase: true }); + util.GlobExp.hasMagic("", { nocomment: true }); + util.GlobExp.hasMagic("", { noext: true }); + util.GlobExp.hasMagic("", { noglobstar: true }); + util.GlobExp.hasMagic("", { nonegate: true }); + util.GlobExp.expandBraces("", {}); + util.GlobExp.expandBraces("", { dot: true }); + util.GlobExp.expandBraces("", { flipNegate: true }); + util.GlobExp.expandBraces("", { matchBase: true }); + util.GlobExp.expandBraces("", { nobrace: true }); + util.GlobExp.expandBraces("", { nocase: true }); + util.GlobExp.expandBraces("", { nocomment: true }); + util.GlobExp.expandBraces("", { noext: true }); + util.GlobExp.expandBraces("", { noglobstar: true }); + util.GlobExp.expandBraces("", { nonegate: true }); + util.GlobExp.makeRe("", {}); + util.GlobExp.makeRe("", { dot: true }); + util.GlobExp.makeRe("", { flipNegate: true }); + util.GlobExp.makeRe("", { matchBase: true }); + util.GlobExp.makeRe("", { nobrace: true }); + util.GlobExp.makeRe("", { nocase: true }); + util.GlobExp.makeRe("", { nocomment: true }); + util.GlobExp.makeRe("", { noext: true }); + util.GlobExp.makeRe("", { noglobstar: true }); + util.GlobExp.makeRe("", { nonegate: true }); + util.GlobExp.test("a", "b", {}); + util.GlobExp.test("a", "b", { dot: true }); + util.GlobExp.test("a", "b", { flipNegate: true }); + util.GlobExp.test("a", "b", { matchBase: true }); + util.GlobExp.test("a", "b", { nobrace: true }); + util.GlobExp.test("a", "b", { nocase: true }); + util.GlobExp.test("a", "b", { nocomment: true }); + util.GlobExp.test("a", "b", { noext: true }); + util.GlobExp.test("a", "b", { noglobstar: true }); + util.GlobExp.test("a", "b", { nonegate: true }); + } + + namespace iconv { + // TODO + } + + namespace sqlstring { + namespace escapeId { + const a: string = util.sqlstring.escapeId("asd"); + const b: string = util.sqlstring.escapeId(["asd"]); + const c: string = util.sqlstring.escapeId(["asd"], true); + } + + namespace dateToString { + const a: string = util.sqlstring.dateToString(Date.now()); + const b: string = util.sqlstring.dateToString(123, "local"); + } + + namespace arrayToList { + const a: string = util.sqlstring.arrayToList(["1", "a"]); + } + + namespace bufferToString { + const a: string = util.sqlstring.bufferToString(Buffer.alloc(10)); + } + + namespace objectToValues { + const a: string = util.sqlstring.objectToValues({ a: 1 }); + const b: string = util.sqlstring.objectToValues({ a: 1 }, "local"); + } + + namespace escape { + const a: string = util.sqlstring.escape(1); + const b: string = util.sqlstring.escape(1, true); + const c: string = util.sqlstring.escape(1, true, "local"); + } + + namespace format { + const a: string = util.sqlstring.format("??"); + const b: string = util.sqlstring.format("??", "a"); + const c: string = util.sqlstring.format("??", ["a"]); + const d: string = util.sqlstring.format("??", ["a"], true); + } + } + + namespace Editor { + namespace options { + new util.Editor(); + new util.Editor({}); + new util.Editor({ text: "" }); + new util.Editor({ editor: "" }); + new util.Editor({ path: "" }); + new util.Editor({ ext: "" }); + } + + const a: string = util.Editor.DEFAULT; + new util.Editor().spawn().then((x: adone.std.child_process.ChildProcess) => { }); + new util.Editor().run().then((x: string) => { }); + new util.Editor().cleanup().then((x: undefined) => { }); + util.Editor.edit().then((x: string) => { }); + } + + namespace binarySearch { + const a: number = util.binarySearch.GREATEST_LOWER_BOUND; + const b: number = util.binarySearch.GREATEST_LOWER_BOUND; + const c: number = util.binarySearch([1, 2, 3], 2); + const d: number = util.binarySearch([1, 2, 3], 2, 0); + const e: number = util.binarySearch([1, 2, 3], 2, 0, 10); + const f: number = util.binarySearch([1, 2, 3], 2, 0, 10, (a, b) => a - b); + const g: number = util.binarySearch([1, 2, 3], 2, 0, 10, (a, b) => a - b, util.binarySearch.GREATEST_LOWER_BOUND); + } + + namespace buffer { + const a: Buffer = util.buffer.concat([Buffer.alloc(10), Buffer.alloc(20)], 30); + util.buffer.mask(Buffer.alloc(10), Buffer.alloc(10), Buffer.alloc(10), 0, 10); + util.buffer.unmask(Buffer.alloc(10), Buffer.alloc(10)); + } + + namespace shebang { + const a: string | null = util.shebang("#!/bin/sh"); + } + + namespace ReInterval { + new util.ReInterval(() => { }, 1000); + new util.ReInterval(() => { }, 1000, [1]); + const a = new util.ReInterval(() => { }, 1000); + a.reschedule(400); + a.clear(); + a.destroy(); + } + + namespace RateLimiter { + new util.RateLimiter(); + new util.RateLimiter(1); + new util.RateLimiter(1, 1000); + new util.RateLimiter(1, 1000, true); + const a = new util.RateLimiter(); + a.removeTokens(1).then((x: number) => { }); + const b: boolean = a.tryRemoveTokens(10); + const c: number = a.getTokensRemaining(); + } + + namespace throttle { + const a: () => Promise = util.throttle(() => 42); + const b: (a: number) => Promise = util.throttle((a: number) => `${a}`); + const c: (a: number, b: string) => Promise = util.throttle((a: number, b: string) => String(a) + b); + const d = util.throttle(() => { }, {}); + const e = util.throttle(() => { }, { interval: 1000 }); + const f = util.throttle(() => { }, { max: 10 }); + const g = util.throttle(() => { }, { ordered: true }); + const h = util.throttle(() => { }, { waitForReturn: true }); + } + + namespace fakeClock { + namespace timers { + const a: typeof global.setTimeout = util.fakeClock.timers.setTimeout; + const b: typeof global.clearTimeout = util.fakeClock.timers.clearTimeout; + const c: typeof global.setInterval = util.fakeClock.timers.setInterval; + const d: typeof global.clearInterval = util.fakeClock.timers.clearInterval; + const e: typeof global.setImmediate = util.fakeClock.timers.setImmediate; + const f: typeof global.clearImmediate = util.fakeClock.timers.clearImmediate; + const g: typeof global.Date = util.fakeClock.timers.Date; + const h: typeof global.process.hrtime = util.fakeClock.timers.hrtime; + const i: typeof global.process.nextTick = util.fakeClock.timers.nextTick; + } + + namespace install { + util.fakeClock.install(100); + util.fakeClock.install(new Date()); + util.fakeClock.install({}); + util.fakeClock.install({ advanceTimeDelta: 20 }); + util.fakeClock.install({ loopLimit: 20 }); + util.fakeClock.install({ now: 20 }); + util.fakeClock.install({ shouldAdvanceTime: false }); + util.fakeClock.install({ target: {} }); + const clock = util.fakeClock.install({ toFake: ["setTimeout", "clearTimeout"] }); + { + const timer = clock.setTimeout(() => {}, 100, 1, 2, 3); + const id: number = timer.id; + timer.ref(); + timer.unref(); + clock.clearTimeout(timer); + } + { + const timer = clock.setInterval(() => {}, 1, 2, 3); + const id: number = timer.id; + timer.ref(); + timer.unref(); + clock.clearInterval(timer); + } + { + const timer = clock.setImmediate(() => {}, 1, 2, 3); + const id: number = timer.id; + timer.ref(); + timer.unref(); + clock.clearImmediate(timer); + } + clock.nextTick(() => {}, 1, 2, 3); + clock.updateHrTime(10); + const a: number = clock.tick(100); + const b: number = clock.next(); + const c: number = clock.runAll(); + const d: number = clock.runToLast(); + clock.setSystemTime(100); + const e: [number, number] = clock.hrtime(); + const f: [number, number] = clock.hrtime(e); + clock.uninstall(); + } + + namespace createClock { + util.fakeClock.createClock(); + util.fakeClock.createClock(0); + const clock = util.fakeClock.createClock(0, 100); + { + const timer = clock.setTimeout(() => {}, 100, 1, 2, 3); + const id: number = timer.id; + timer.ref(); + timer.unref(); + clock.clearTimeout(timer); + } + { + const timer = clock.setInterval(() => {}, 1, 2, 3); + const id: number = timer.id; + timer.ref(); + timer.unref(); + clock.clearInterval(timer); + } + { + const timer = clock.setImmediate(() => {}, 1, 2, 3); + const id: number = timer.id; + timer.ref(); + timer.unref(); + clock.clearImmediate(timer); + } + clock.nextTick(() => {}, 1, 2, 3); + clock.updateHrTime(10); + const a: number = clock.tick(100); + const b: number = clock.next(); + const c: number = clock.runAll(); + const d: number = clock.runToLast(); + clock.setSystemTime(100); + const e: [number, number] = clock.hrtime(); + const f: [number, number] = clock.hrtime(e); + } + + namespace ltgt { + namespace contains { + const a: boolean = util.ltgt.contains({ lt: 2 }, 2); + const b: boolean = util.ltgt.contains({ lt: 2 }, 2, (a, b) => b - a); + const c: boolean = util.ltgt.contains({ lt: "2" }, "2"); + const d: boolean = util.ltgt.contains({ lt: "2" }, "2", (a, b) => b.charCodeAt(0) - a.charCodeAt(0)); + } + + namespace filter { + const a: (a: number) => boolean = util.ltgt.filter({ lt: 2 }); + const b: (a: number) => boolean = util.ltgt.filter({ lt: 2 }, (a, b) => b - a); + const c: (a: string) => boolean = util.ltgt.filter({ lt: "2" }); + const d: (a: string) => boolean = util.ltgt.filter({ lt: "2" }, (a, b) => b.charCodeAt(0) - a.charCodeAt(0)); + } + + namespace toLtgt { + const a: adone.util.ltgt.I.Range = util.ltgt.toLtgt({ lt: 2 }, {}); + const b: adone.util.ltgt.I.Range = util.ltgt.toLtgt({ lt: 2 }, {}, (a) => `${a}`); + const c: adone.util.ltgt.I.Range = util.ltgt.toLtgt({ lt: 2 }, {}, (a) => a, 2); + const d: adone.util.ltgt.I.Range = util.ltgt.toLtgt({ lt: 2 }, {}, (a) => a, 2, 5); + } + + namespace endEnclusive { + const a: boolean = util.ltgt.endInclusive({ lt: 2 }); + } + + namespace startInclusive { + const a: boolean = util.ltgt.startInclusive({ lt: 2 }); + } + + namespace end { + const a: number | undefined = util.ltgt.end({ lt: 2 }); + const b: number | string = util.ltgt.end({ lt: 2 }, "2"); + const c: number = util.ltgt.end({ lt: 2 }, 2); + } + + namespace start { + const a: number | undefined = util.ltgt.start({ lt: 2 }); + const b: number | string = util.ltgt.start({ lt: 2 }, "2"); + const c: number = util.ltgt.start({ lt: 2 }, 2); + } + + namespace upperBound { + const a: number | undefined = util.ltgt.upperBound({ lt: 2 }); + const b: number | string = util.ltgt.upperBound({ lt: 2 }, "2"); + const c: number = util.ltgt.upperBound({ lt: 2 }, 2); + } + + namespace upperBoundKey { + const a: number | undefined = util.ltgt.upperBoundKey({ lt: 2 }); + } + + namespace upperBoundExclusive { + const a: boolean = util.ltgt.upperBoundInclusive({ lt: 2 }); + } + + namespace lowerBoundExclusive { + const a: boolean = util.ltgt.lowerBoundInclusive({ lt: 2 }); + } + + namespace upperBoundInclusive { + const a: boolean = util.ltgt.upperBoundInclusive({ lt: 2 }); + } + + namespace lowerBoundInclusive { + const a: boolean = util.ltgt.lowerBoundInclusive({ lt: 2 }); + } + + namespace lowerBound { + const a: number | undefined = util.ltgt.lowerBound({ lt: 2 }); + const b: number | string = util.ltgt.lowerBound({ lt: 2 }, "2"); + const c: number = util.ltgt.lowerBound({ lt: 2 }, 2); + } + } + } +} diff --git a/types/adone/test/index-import.ts b/types/adone/test/index-import.ts new file mode 100644 index 0000000000..906e57938c --- /dev/null +++ b/types/adone/test/index-import.ts @@ -0,0 +1,6 @@ +import adone from "adone"; + +namespace AdoneRootImportTests { + adone.falsely() === false; + adone.std.fs.createReadStream(__filename).close(); +} diff --git a/types/adone/test/index.ts b/types/adone/test/index.ts new file mode 100644 index 0000000000..7cc5034602 --- /dev/null +++ b/types/adone/test/index.ts @@ -0,0 +1,69 @@ +namespace AdoneRootTests { + { const a: symbol = adone.null; } + adone.noop(); + { const a: number = adone.identity(2); } + { const a: string = adone.identity("2"); } + { const a: number[] = adone.identity([1, 2]); } + { adone.truly() === true; } + { adone.falsely() === false; } + { const a: string = adone.ok; } + { const a: string = adone.bad; } + { const a: string[] = adone.exts; } + adone.log(); + adone.fatal(); + adone.error(); + adone.warn(); + adone.info(); + adone.debug(); + adone.trace(); + { const a: object = adone.o(); } + { const a: object = adone.o({}); } + { const a: typeof Date = adone.Date; } + { const a: typeof process.hrtime = adone.hrtime; } + { const a: typeof setTimeout = adone.setTimeout; } + { const a: typeof clearTimeout = adone.clearTimeout; } + { const a: typeof setInterval = adone.setInterval; } + { const a: typeof clearInterval = adone.clearInterval; } + { const a: typeof setImmediate = adone.setImmediate; } + { const a: typeof clearImmediate = adone.clearImmediate; } + adone.lazify({}); + adone.lazify({}, {}); + adone.lazify({}, {}, () => { }); + adone.lazify({}, {}, () => { }, { configurable: true }); + adone.tag.set({}, "123"); + adone.tag.has({}, "123") === true; + adone.tag.define("12"); + adone.tag.define("123", "456"); + { const a: symbol = adone.tag.SUBSYSTEM; } + { const a: symbol = adone.tag.APPLICATION; } + { const a: symbol = adone.tag.TRANSFORM; } + { const a: symbol = adone.tag.CORE_STREAM; } + { const a: symbol = adone.tag.LOGGER; } + { const a: symbol = adone.tag.LONG; } + { const a: symbol = adone.tag.BIGNUMBER; } + { const a: symbol = adone.tag.EXBUFFER; } + { const a: symbol = adone.tag.EXDATE; } + { const a: symbol = adone.tag.CONFIGURATION; } + { const a: symbol = adone.tag.GENESIS_NETRON; } + { const a: symbol = adone.tag.GENESIS_PEER; } + { const a: symbol = adone.tag.NETRON; } + { const a: symbol = adone.tag.NETRON_PEER; } + { const a: symbol = adone.tag.NETRON_ADAPTER; } + { const a: symbol = adone.tag.NETRON_DEFINITION; } + { const a: symbol = adone.tag.NETRON_DEFINITIONS; } + { const a: symbol = adone.tag.NETRON_REFERENCE; } + { const a: symbol = adone.tag.NETRON_INTERFACE; } + { const a: symbol = adone.tag.NETRON_STUB; } + { const a: symbol = adone.tag.NETRON_REMOTESTUB; } + { const a: symbol = adone.tag.NETRON_STREAM; } + { const a: symbol = adone.tag.FAST_STREAM; } + { const a: symbol = adone.tag.FAST_FS_STREAM; } + { const a: symbol = adone.tag.FAST_FS_MAP_STREAM; } + { const a: Promise = adone.run({}); } + { const a: Promise = adone.run({}, false); } + { const a: object = adone.bind("library"); } // hmm + { const a: string = adone.getAssetAbsolutePath("asset"); } + { const a: Buffer | string = adone.loadAsset("asset"); } + { const a: object = adone.require("path"); } + { const a: object = adone.package; } +} diff --git a/types/adone/tsconfig.json b/types/adone/tsconfig.json new file mode 100644 index 0000000000..6fe0c82586 --- /dev/null +++ b/types/adone/tsconfig.json @@ -0,0 +1,34 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es2017", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "adone.d.ts", + "glosses/common.d.ts", + "glosses/math.d.ts", + "glosses/std.d.ts", + "glosses/utils.d.ts", + "adone-tests.ts", + "test/index.ts", + "test/index-import.ts", + "test/glosses/common.ts", + "test/glosses/math.ts", + "test/glosses/std.ts", + "test/glosses/utils.ts" + ] +} diff --git a/types/adone/tslint.json b/types/adone/tslint.json new file mode 100644 index 0000000000..5f7dd6afd7 --- /dev/null +++ b/types/adone/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-namespace": false, + "strict-export-declare-modifiers": false, + "no-single-declare-module": false + } +} \ No newline at end of file From babd09c3ecd04aab81a06c5e9abdde0e230ab560 Mon Sep 17 00:00:00 2001 From: otociulis Date: Wed, 9 Aug 2017 10:40:51 -0700 Subject: [PATCH 19/29] Adding nodemailer-mailgun-transport definitions (#18584) * Adding diacritics package * Adding linter * Fixing linting errors * Fixing warnings and errors * Removing unnecessary namespace * Adding nodemailer-mailgun-transport definitions * Updating tsconfig.json * Updating tests --- types/nodemailer-mailgun-transport/index.d.ts | 17 +++++++++++++ .../nodemailer-mailgun-transport-tests.ts | 25 +++++++++++++++++++ .../tsconfig.json | 22 ++++++++++++++++ .../nodemailer-mailgun-transport/tslint.json | 1 + 4 files changed, 65 insertions(+) create mode 100644 types/nodemailer-mailgun-transport/index.d.ts create mode 100644 types/nodemailer-mailgun-transport/nodemailer-mailgun-transport-tests.ts create mode 100644 types/nodemailer-mailgun-transport/tsconfig.json create mode 100644 types/nodemailer-mailgun-transport/tslint.json diff --git a/types/nodemailer-mailgun-transport/index.d.ts b/types/nodemailer-mailgun-transport/index.d.ts new file mode 100644 index 0000000000..52ee795c12 --- /dev/null +++ b/types/nodemailer-mailgun-transport/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for nodemailer-mailgun-transport 1.3 +// Project: https://github.com/orliesaurus/nodemailer-mailgun-transport +// Definitions by: Oto Ciulis +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as nodemailer from 'nodemailer'; + +declare namespace mailgunTransport { + interface AuthOptions { + api_key: string; + domain?: string; + } +} + +declare function mailgunTransport(options: mailgunTransport.AuthOptions): nodemailer.Transport; + +export = mailgunTransport; diff --git a/types/nodemailer-mailgun-transport/nodemailer-mailgun-transport-tests.ts b/types/nodemailer-mailgun-transport/nodemailer-mailgun-transport-tests.ts new file mode 100644 index 0000000000..cdf2a9250c --- /dev/null +++ b/types/nodemailer-mailgun-transport/nodemailer-mailgun-transport-tests.ts @@ -0,0 +1,25 @@ +import mailgunTransport = require('nodemailer-mailgun-transport'); +import nodemailer = require('nodemailer'); + +const opts: mailgunTransport.AuthOptions = { + api_key: "harry" +}; + +const optsWithDomain: mailgunTransport.AuthOptions = { + api_key: "harry", + domain: "http://www.foo.com" +}; + +const transport: nodemailer.Transporter = nodemailer.createTransport(mailgunTransport(optsWithDomain)); + +// setup e-mail data with unicode symbols +const mailOptions: nodemailer.SendMailOptions = { + from: 'Fred Foo ✔ ', // sender address + to: 'bar@blurdybloop.com, baz@blurdybloop.com', // list of receivers + subject: 'Hello ✔', // Subject line + text: 'Hello world ✔', // plaintext body + html: 'Hello world ✔' // html body +}; +transport.sendMail(mailOptions, (error: Error, info: nodemailer.SentMessageInfo): void => { + // nothing +}); diff --git a/types/nodemailer-mailgun-transport/tsconfig.json b/types/nodemailer-mailgun-transport/tsconfig.json new file mode 100644 index 0000000000..0bccd31841 --- /dev/null +++ b/types/nodemailer-mailgun-transport/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "nodemailer-mailgun-transport-tests.ts" + ] +} \ No newline at end of file diff --git a/types/nodemailer-mailgun-transport/tslint.json b/types/nodemailer-mailgun-transport/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/nodemailer-mailgun-transport/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file From 03e66c690adf299b2ecee659be1400f8bd33eabb Mon Sep 17 00:00:00 2001 From: Gintautas Miselis Date: Wed, 9 Aug 2017 18:48:12 +0100 Subject: [PATCH 20/29] Add type definitions of express-fileupload (#18641) * Add type definitions of express-fileupload * Fixed all lint errors --- .../express-fileupload-tests.ts | 29 +++++++++++++++ types/express-fileupload/index.d.ts | 36 +++++++++++++++++++ types/express-fileupload/tsconfig.json | 22 ++++++++++++ types/express-fileupload/tslint.json | 1 + 4 files changed, 88 insertions(+) create mode 100644 types/express-fileupload/express-fileupload-tests.ts create mode 100644 types/express-fileupload/index.d.ts create mode 100644 types/express-fileupload/tsconfig.json create mode 100644 types/express-fileupload/tslint.json diff --git a/types/express-fileupload/express-fileupload-tests.ts b/types/express-fileupload/express-fileupload-tests.ts new file mode 100644 index 0000000000..61b8c2a9cc --- /dev/null +++ b/types/express-fileupload/express-fileupload-tests.ts @@ -0,0 +1,29 @@ +import * as express from 'express'; +import { RequestHandler, Request, Response, NextFunction } from 'express-serve-static-core'; +import { fileUpload, UploadedFile } from 'express-fileupload'; + +const app: express.Express = express(); + +app.use(fileUpload({debug: true})); + +function isUploadedFile(file: UploadedFile | UploadedFile[]): file is UploadedFile { + return typeof file === 'object' && ( file).name !== undefined; +} + +const uploadHandler: RequestHandler = (req: Request, res: Response, next: NextFunction) => { + if (typeof req.files === 'object') { + const fileField = req.files.field; + if (isUploadedFile(fileField)) { + console.log(fileField.name); + } + + const fileList = req.files.fileList; + if (Array.isArray(fileList)) { + for (const file of fileList) { + console.log(file.name); + } + } + } +}; + +app.post('/upload', uploadHandler); diff --git a/types/express-fileupload/index.d.ts b/types/express-fileupload/index.d.ts new file mode 100644 index 0000000000..33863758b4 --- /dev/null +++ b/types/express-fileupload/index.d.ts @@ -0,0 +1,36 @@ +// Type definitions for express-fileupload 0.1 +// Project: https://github.com/richardgirges/express-fileupload#readme +// Definitions by: Gintautas Miselis +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import express = require('express'); + +declare global { + namespace Express { + interface Request { + files?: FileArray; + } + } +} + +export class FileArray { + [index: string]: UploadedFile | UploadedFile[] +} + +export interface UploadedFile { + name: string; + encoding: string; + mimetype: string; + data: Buffer; + mv(path: string, callback: (err: any) => {}): void; +} + +export interface Options { + debug?: boolean; + safeFileNames?: boolean; + preserveExtension?: boolean | string | number; + [property: string]: any; +} + +export function fileUpload(options?: Options): express.RequestHandler; diff --git a/types/express-fileupload/tsconfig.json b/types/express-fileupload/tsconfig.json new file mode 100644 index 0000000000..53c878d430 --- /dev/null +++ b/types/express-fileupload/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "express-fileupload-tests.ts" + ] +} diff --git a/types/express-fileupload/tslint.json b/types/express-fileupload/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/express-fileupload/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 34aff41c755f74756819138f07b3598d67978714 Mon Sep 17 00:00:00 2001 From: stefanholzapfel Date: Wed, 9 Aug 2017 19:51:49 +0200 Subject: [PATCH 21/29] [meteor] Added optional parameters to Meteor's apply function (#18540) * Added optional parameters to Meteor's apply function * Add ramda.traverse (#18424) * Add ramda.traverse * Use correct indention * Added meteor/webapp definitions (#18471) * Added meteor/webapp definitions * Meteor modules now seperated * Fixes #18283 (#18404) * Explicitly specify possibly nullable types in CodeMirror (#18371) * Explicitly specify possibly nullable types in CodeMirror * scrollTo optional args * Improve Cursor.count (#18504) * add microrouter types (#18500) * add microrouter types * add params field to IncomingMessage * fix lint * use micro types for RequestHandler * Added optional parameters to Meteor's apply function --- types/meteor/index.d.ts | 2 +- types/meteor/meteor.d.ts | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/types/meteor/index.d.ts b/types/meteor/index.d.ts index 0ea69e0423..ec4454f81a 100644 --- a/types/meteor/index.d.ts +++ b/types/meteor/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Meteor 1.4 // Project: http://www.meteor.com/ -// Definitions by: Alex Borodach , Dave Allen , Olivier Refalo , Daniel Neveux , Birk Skyum , Arda TANRIKULU +// Definitions by: Alex Borodach , Dave Allen , Olivier Refalo , Daniel Neveux , Birk Skyum , Arda TANRIKULU , Stefan Holzapfel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/meteor/meteor.d.ts b/types/meteor/meteor.d.ts index 581ed11c55..07c1365459 100644 --- a/types/meteor/meteor.d.ts +++ b/types/meteor/meteor.d.ts @@ -56,6 +56,8 @@ declare module Meteor { function apply(name: string, args: EJSONable[], options?: { wait?: boolean; onResultReceived?: Function; + returnStubValue?: boolean; + throwStubExceptions?: boolean; }, asyncCallback?: Function): any; /** Method **/ @@ -157,6 +159,8 @@ declare module "meteor/meteor" { function apply(name: string, args: EJSONable[], options?: { wait?: boolean; onResultReceived?: Function; + returnStubValue?: boolean; + throwStubExceptions?: boolean; }, asyncCallback?: Function): any; /** Method **/ From 135ed17a234a1191444d2d8bfc89ca1c9ef108dc Mon Sep 17 00:00:00 2001 From: Simon Schick Date: Wed, 9 Aug 2017 19:56:27 +0200 Subject: [PATCH 22/29] joi: Improve `extend` typings (#18760) * joi: Improve `extend` typings * fixup! joi: Improve `extend` typings * fixup! joi: Improve `extend` typings * use TS 2.4 --- types/joi/index.d.ts | 37 +++++++++++++++++++++++++++++++------ types/joi/joi-tests.ts | 29 +++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 6 deletions(-) diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index fb3547b3e4..0772c82fbe 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -2,11 +2,11 @@ // Project: https://github.com/hapijs/joi // Definitions by: Bart van der Schoor , Laurence Dougal Myers , Christopher Glantschnig , David Broder-Rodgers , Gael Magnan de Bornier , Rytis Alekna , Pavel Ivanov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 // TODO express type of Schema in a type-parameter (.default, .valid, .example etc) - export interface ValidationOptions { /** * when true, stops validation on the first error, otherwise returns all the errors found. Defaults to true. @@ -337,6 +337,25 @@ export interface AnySchema> { * option has been set to `false`). */ error?(err: Error | ValidationErrorFunction): T; + + /** + * Creates a joi error object. + * Used in conjunction with custom rules. + * @param ruleName - the rule name to create the error for. + * @param context - must contain `v` eg. the value that was validated, all other properties + * are available in the `language` templates. + * @param state - should the context passed into the `validate` function in a + * custom rule + * @param options - should the context passed into the `validate` function in a + * custom rule + */ + createError(ruleName: string, context: { + v: any; + [key: string]: any; + }, state: State, options: ValidationOptions): Err; +} + +export interface State { } export interface BooleanSchema extends AnySchema { @@ -825,20 +844,26 @@ export interface Terms { export interface Rules { name: string; params?: ObjectSchema | { [key: string]: Schema }; - setup?: Function; - validate?: Function; + setup?: (this: AnySchema>, description: { [key: string]: any }) => AnySchema> | void; + validate?: (this: AnySchema>, params: { [key: string]: any }, value: any, state: State, options: ValidationOptions) => Err | undefined; description?: string | Function; } export interface Extension { name: string; base?: Schema; - pre?: Function; - language?: {}; - describe?: Function; + pre?: (this: AnySchema>, params: { [key: string]: any }, value: any, state: State, options: ValidationOptions) => Err | void; + language?: { + [key: string]: string; + }, + describe?: (this: AnySchema>, description: any) => any; rules?: Rules[]; } +export interface Err { + toString(): string; +} + // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- /** diff --git a/types/joi/joi-tests.ts b/types/joi/joi-tests.ts index a0684724b7..7bfb712247 100644 --- a/types/joi/joi-tests.ts +++ b/types/joi/joi-tests.ts @@ -886,6 +886,35 @@ schema = Joi.reach(schema, ''); const Joi2 = Joi.extend({ name: '', base: schema }); +const Joi3 = Joi.extend({ + base: Joi.string(), + name: 'string', + language: { + asd: 'must be exactly asd(f)', + }, + pre (value, state, options) { + }, + describe (description) { + }, + rules: [ + { + name: 'asd', + params: { + allowF: Joi.boolean().default(false), + }, + setup (params) { + const fIsAllowed = params.allowF; + }, + validate (params, value, state, options) { + if (value === 'asd' && (params.allowF && value === 'asdf')) { + return value; + } + return this.createError('asd', { v: value }, state, options); + }, + }, + ], +}); + // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- schema = Joi.allow(x, x); From afa59841f7afeb96e45f9fe48691cd27dbb6e6c1 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Wed, 9 Aug 2017 19:56:58 +0200 Subject: [PATCH 23/29] [redlock] change Lock to class declaration, simplify LockError definition (#18770) * add constructors and tests for classes exposed in redlock * [redlock] simplify Lock and LockError definitions --- types/redlock/index.d.ts | 17 ++++++----------- types/redlock/redlock-tests.ts | 2 ++ types/redlock/v2/index.d.ts | 19 +++++++------------ types/redlock/v2/redlock-tests.ts | 12 +++++++++--- 4 files changed, 24 insertions(+), 26 deletions(-) diff --git a/types/redlock/index.d.ts b/types/redlock/index.d.ts index 3cd1bf7d2e..27e6784886 100644 --- a/types/redlock/index.d.ts +++ b/types/redlock/index.d.ts @@ -13,14 +13,13 @@ export = Redlock; declare namespace Redlock { type Callback = (err: any, value?: T) => void; - interface Lock { + class Lock { redlock: Redlock; resource: string; value: string | null; expiration: number; - + constructor(redlock: Redlock, resource: string, value: string | null, expiration: number); unlock(callback?: Callback): Promise; - extend(ttl: number, callback?: Callback): Promise; } @@ -34,14 +33,9 @@ declare namespace Redlock { extendScript?(origExtendScript: string): string; } - interface LockErrorConstructor { - new(message?: string): LockError; - (message?: string): LockError; - readonly prototype: LockError; - } - - interface LockError extends Error { + class LockError extends Error { readonly name: 'LockError'; + constructor(message?: string); } interface CompatibleRedisClient { @@ -51,7 +45,8 @@ declare namespace Redlock { } declare class Redlock extends EventEmitter { - LockError: Redlock.LockErrorConstructor; + LockError: typeof Redlock.LockError; + Lock: typeof Redlock.Lock; driftFactor: number; retryCount: number; retryDelay: number; diff --git a/types/redlock/redlock-tests.ts b/types/redlock/redlock-tests.ts index 8a36679fe7..5a8ec00589 100644 --- a/types/redlock/redlock-tests.ts +++ b/types/redlock/redlock-tests.ts @@ -91,6 +91,8 @@ redlock.lock('locks:account:322456', 1000, (err, lock) => { } }); +new Object() instanceof redlock.Lock; + new Error() instanceof redlock.LockError; redlock.LockError.prototype; diff --git a/types/redlock/v2/index.d.ts b/types/redlock/v2/index.d.ts index 5ef9bb80c1..d683ec83a4 100644 --- a/types/redlock/v2/index.d.ts +++ b/types/redlock/v2/index.d.ts @@ -12,14 +12,13 @@ export = Redlock; declare namespace Redlock { type Callback = (err: any, value?: T) => void; - interface Lock { + class Lock { redlock: Redlock; resource: string; value: any; expiration: number; - + constructor(redlock: Redlock, resource: string, value: any, expiration: number); unlock(callback?: Callback): Promise; - extend(ttl: number, callback?: Callback): Promise; } @@ -29,19 +28,15 @@ declare namespace Redlock { retryDelay?: number; } - interface LockErrorConstructor { - new(message?: string): LockError; - (message?: string): LockError; - readonly prototype: LockError; - } - - interface LockError extends Error { + class LockError extends Error { readonly name: 'LockError'; + constructor(message?: string); } } declare class Redlock { - LockError: Redlock.LockErrorConstructor; + LockError: typeof Redlock.LockError; + Lock: typeof Redlock.Lock; driftFactor: number; retryCount: number; @@ -54,7 +49,7 @@ declare class Redlock { acquire(resource: string, ttl: number, callback?: Redlock.Callback): Promise; lock(resource: string, ttl: number, callback?: Redlock.Callback): Promise; - disposer(resource: string, ttl: number, errorHandler?: Redlock.Callback): any; // bluebird Disposer + disposer(resource: string, ttl: number, errorHandler?: Redlock.Callback): Promise.Disposer; // bluebird Disposer release(lock: Redlock.Lock, callback?: Redlock.Callback): Promise; unlock(lock: Redlock.Lock, callback?: Redlock.Callback): Promise; diff --git a/types/redlock/v2/redlock-tests.ts b/types/redlock/v2/redlock-tests.ts index 8b1c83c282..80c590e13c 100644 --- a/types/redlock/v2/redlock-tests.ts +++ b/types/redlock/v2/redlock-tests.ts @@ -1,6 +1,7 @@ import * as Redlock from 'redlock'; import { Lock } from 'redlock'; import { RedisClient } from 'redis'; +import { using } from 'bluebird'; let redlock: Redlock; let client: RedisClient = {}; @@ -18,9 +19,7 @@ redlock.acquire('resource', 30, (err: any, lock: Lock) => {}); redlock.lock('resource', 30).then((lock: Lock) => {}); redlock.lock('resource', 30, (err: any, lock: Lock) => {}); -// There is currently no way to test the disposer as the bluebird typings does not -// expose the .using method. -// promise.using(redlock.disposer('resource', 30), (lock: Lock) => {}); +using(redlock.disposer('resource', 30), (lock: Lock) => Promise.resolve()); redlock.release(lock); redlock.release(lock, (err: any) => {}); @@ -35,3 +34,10 @@ lock.unlock((err) => {}); lock.extend(30).then((lock: Lock) => {}); lock.extend(30, (err: any, lock: Lock) => {}); + +new Object() instanceof redlock.Lock; + +new Error() instanceof redlock.LockError; + +redlock.LockError.prototype; +const lockError: Redlock.LockError = new redlock.LockError(); From bf4b4034c200dcbd99491a985592c877a6bf9582 Mon Sep 17 00:00:00 2001 From: Marc Fallows Date: Thu, 10 Aug 2017 04:05:07 +1000 Subject: [PATCH 24/29] Types for react-measure 2.0 (#18273) --- types/react-measure/index.d.ts | 100 +++++++++++--------- types/react-measure/react-measure-tests.tsx | 93 ++++++++++++------ types/react-measure/tslint.json | 1 + 3 files changed, 116 insertions(+), 78 deletions(-) create mode 100644 types/react-measure/tslint.json diff --git a/types/react-measure/index.d.ts b/types/react-measure/index.d.ts index c487cd7264..6a06a04d37 100644 --- a/types/react-measure/index.d.ts +++ b/types/react-measure/index.d.ts @@ -1,54 +1,60 @@ -// Type definitions for react-measure 0.4 +// Type definitions for react-measure 2.0 // Project: https://github.com/souporserious/react-measure -// Definitions by: Alexey Svetliakov +// Definitions by: Alexey Svetliakov , Marc Fallows // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -declare module "react-measure" { - import * as React from "react"; +import * as React from "react"; - class Measure extends React.Component { } - namespace Measure { - type MeasurementType = "width" | "height" | "top" | "right" | "bottom" | "left"; - interface Dimensions { - width?: number; - height?: number; - top?: number; - right?: number; - bottom?: number; - left?: number; - } +type MeasurementType = "client" | "offset" | "scroll" | "bounds" | "margin"; - type MeasureChildren = React.ReactNode | React.ReactElement | ((dimension: Dimensions) => React.ReactElement); - - interface MeasureProps { - /** - * Tries to give the most accurate measure. Currently only works with height. - * Measures the content rather than the actual box of the element. - */ - accurate?: boolean; - /** - * Provide a list of properties to fire a callback for. - */ - whitelist?: MeasurementType[]; - /** - * Like whitelist, but will not fire a callback for the specified properties. - */ - blacklist?: MeasurementType[]; - /** - * Determines whether or not a measurement should occur. - * @default true - */ - shouldMeasure?: boolean; - /** - * Callback when the component has been mutated. Receives dimensions, mutations, and anything passed to shouldMeasure. - */ - onMeasure?(dimensions: Dimensions): void; - /** - * Children, ordinary JSX element or function. Leaving it for reference here - */ - children?: MeasureChildren; - } - } - export = Measure; +interface TopLeft { + readonly top: number; + readonly left: number; } + +interface BottomRight { + readonly bottom: number; + readonly right: number; +} + +interface Dimensions { + readonly width: number; + readonly height: number; +} + +export type Margin = TopLeft & BottomRight; + +export type Rect = TopLeft & Dimensions; + +export type BoundingRect = Dimensions & Margin; + +export interface ContentRect { + client?: Rect; + offset?: Rect; + scroll?: Rect; + bounds?: BoundingRect; + margin?: Margin; + entry?: any; +} + +export interface ChildrenOpts { + measureRef(ref: Element | null): void; + measure(): void; + contentRect: ContentRect; +} + +export interface MeasureProps { + client?: boolean; + offset?: boolean; + scroll?: boolean; + bounds?: boolean; + margin?: boolean; + innerRef?(ref: Element | null): void; + onResize?(contentRect: ContentRect): void; + children?(arg: ChildrenOpts): React.ReactElement; +} + +export declare function withContentRect(types: MeasurementType | MeasurementType[]): (fn: (arg: ChildrenOpts) => React.ReactElement) => React.ComponentClass; +declare class Measure extends React.Component> {} +export default Measure; diff --git a/types/react-measure/react-measure-tests.tsx b/types/react-measure/react-measure-tests.tsx index 4c02ba8f07..80637eb241 100644 --- a/types/react-measure/react-measure-tests.tsx +++ b/types/react-measure/react-measure-tests.tsx @@ -1,53 +1,84 @@ import * as React from "react"; -import * as Measure from "react-measure"; +import Measure, {ContentRect, withContentRect} from "react-measure"; class Test extends React.Component { render() { return ( - -
test
+ + {({measureRef}) => +
Measure me.
+ }
); } - onMeasure(dimensions: Measure.Dimensions): void { - dimensions.width; - dimensions.height; + innerRef(ref: Element): void { + console.log(`innerRef: ${ref}`); + } + + onResize(contentRect: ContentRect): void { + const {client, offset, scroll, bounds, margin} = contentRect; + if (client != null) { + console.log(`client - top: ${client.top}, left: ${client.left}, width: ${client.width}, height: ${client.height}`); + } + if (offset != null) { + console.log(`offset - top: ${offset.top}, left: ${offset.left}, width: ${offset.width}, height: ${offset.height}`); + } + if (scroll != null) { + console.log(`scroll - top: ${scroll.top}, left: ${scroll.left}, width: ${scroll.width}, height: ${scroll.height}`); + } + if (bounds != null) { + console.log(`bounds - top: ${bounds.top}, left: ${bounds.left}, bottom: ${bounds.bottom}, right: ${bounds.right}, width: ${bounds.width}, height: ${bounds.height}`); + } + if (margin != null) { + console.log(`bounds - top: ${margin.top}, left: ${margin.left}, bottom: ${margin.bottom}, right: ${margin.right}`); + } } } class Test2 extends React.Component { render() { return ( - - {(dimensions: Measure.Dimensions) => -
-
Height: {dimensions.height}
-
+ + {({measureRef}) => +
}
); } + + onResize(contentRect: ContentRect): void { + } } -function testHocComponent(Component: React.ComponentClass): React.ComponentClass { - return class extends React.Component { - render(): JSX.Element { - return ( - - ; - - ); - } - - private handleDimensionChange = (dimensions: Measure.Dimensions) => { - dimensions.width; - dimensions.height; - } - }; +function testHocComponent(): React.ComponentClass { + return withContentRect('bounds')(({measureRef, measure, contentRect}) => ( +
+ Some content here +
+              {JSON.stringify(contentRect, null, 2)}
+            
+
+ )); } + +function testHocComponent2(): React.ComponentClass { + return withContentRect(['scroll', 'margin'])(({measureRef}) => ( +
Some content here
+ )); +} + +const HocComponent = testHocComponent(); +const el = ; diff --git a/types/react-measure/tslint.json b/types/react-measure/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-measure/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From cad4b8a4fe5d4abf37c9c866b3d0897b9c31f3c1 Mon Sep 17 00:00:00 2001 From: John Gainfort Jr Date: Wed, 9 Aug 2017 12:28:40 -0600 Subject: [PATCH 25/29] updated docs to match property type --- types/hls.js/index.d.ts | 3498 +++++++++++++++++++-------------------- 1 file changed, 1749 insertions(+), 1749 deletions(-) diff --git a/types/hls.js/index.d.ts b/types/hls.js/index.d.ts index 80f7bf471e..5270bed7cf 100644 --- a/types/hls.js/index.d.ts +++ b/types/hls.js/index.d.ts @@ -5,468 +5,1704 @@ // TypeScript Version: 2.2 declare class Loader { - constructor(config: Hls.LoaderConfig) - /** - * Start retrieving content located at given URL (HTTP GET). - */ - load(context: Hls.LoaderContext, config: Hls.LoaderConfig, callbacks: Hls.LoaderCallbacks): void; - /** - * Abort any loading in progress. - */ - abort(): void; - /** - * Destroy loading context. - */ - destroy(): void; + constructor(config: Hls.LoaderConfig) + /** + * Start retrieving content located at given URL (HTTP GET). + */ + load(context: Hls.LoaderContext, config: Hls.LoaderConfig, callbacks: Hls.LoaderCallbacks): void; + /** + * Abort any loading in progress. + */ + abort(): void; + /** + * Destroy loading context. + */ + destroy(): void; } declare namespace Hls { - /** - * Hls events - */ - namespace Events { /** - * fired to attach Media to hls instance - * data: { video , mediaSource } + * Hls events */ - const MEDIA_ATTACHING: string; - /** - * fired when Media has been succesfully attached to hls instance - * data: { video , mediaSource } - */ - const MEDIA_ATTACHED: string; - /** - * fired before detaching Media from hls instance - * data: { } - */ - const MEDIA_DETACHING: string; - /** - * fired when Media has been detached from hls instance - * data: { } - */ - const MEDIA_DETACHED: string; - /** - * fired when the buffer is going to be reset - * data: { } - */ - const BUFFER_RESET: string; - /** - * fired when we know about the codecs that we need buffers for to push into - * data: { tracks : { container, codec, levelCodec, initSegment, metadata } } - */ - const BUFFER_CODECS: string; - /** - * fired when sourcebuffers have been created - * data: { tracks: tracks } - */ - const BUFFER_CREATED: string; - /** - * fired when we append a segment to the buffer - * data: { segment: segment object } - */ - const BUFFER_APPENDING: string; - /** - * fired when we are done with appending a media segment to the buffer - * data: { parent : segment parent that triggered BUFFER_APPENDING, pending : nb of segments waiting for appending for this segment parent } - */ - const BUFFER_APPENDED: string; - /** - * fired when the stream is finished and we want to notify the media buffer that there will be no more data - * data: { } - */ - const BUFFER_EOS: string; - /** - * fired when the media buffer should be flushed - * data: { } - */ - const BUFFER_FLUSHING: string; - /** - * fired when the media buffer has been flushed - * data: { } - */ - const BUFFER_FLUSHED: string; - /** - * fired to signal that a manifest loading starts - * data: { url : manifestURL } - */ - const MANIFEST_LOADING: string; - /** - * fired after manifest has been loaded - * data: { levels : [available quality levels] , audioTracks : [ available audio tracks], url : manifestURL, stats : { trequest, tfirst, tload, mtime}} - */ - const MANIFEST_LOADED: string; - /** - * fired after manifest has been parsed - * data: { levels : [ available quality levels ], firstLevel : index of first quality level appearing in Manifest } - */ - const MANIFEST_PARSED: string; - /** - * fired when a level playlist loading starts - * data: { url : level URL, level : id of level being loaded } - */ - const LEVEL_LOADING: string; - /** - * fired when a level playlist loading finishes - * data: { details : levelDetails object, levelId : id of loaded level, stats : { trequest, tfirst, tload, mtime } } - */ - const LEVEL_LOADED: string; - /** - * fired when a level's details have been updated based on previous details, after it has been loaded - * data: { details : levelDetails object, level : id of updated level } - */ - const LEVEL_UPDATED: string; - /** - * fired when a level's PTS information has been updated after parsing a fragment - * data: { details: levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment } - */ - const LEVEL_PTS_UPDATED: string; - /** - * fired when a level switch is requested - * data: { level: Level } - */ - const LEVEL_SWITCHING: string; - /** - * fired when a level switch is effective - * data: { level: level object } - */ - const LEVEL_SWITCHED: string; - /** - * fired to notify that audio track lists has been updated - * data: { audioTracks : audioTracks } - */ - const AUDIO_TRACKS_UPDATED: string; - /** - * fired when an audio track switch occurs. deprecated in favor AUDIO_TRACK_SWITCHING - * data: { id : audio track id } - */ - const AUDIO_TRACK_SWTICH: string; - /** - * fired when an audio track switching is requested - * data: { id : audio track id } - */ - const AUDIO_TRACK_SWITCHING: string; - /** - * fired when an audio track switch actually occurs - * data: { id : audio track id } - */ - const AUDIO_TRACK_SWITCHED: string; - /** - * fired when an audio track loading starts - * data: { url : audio track URL, id : audio track id } - */ - const AUDIO_TRACK_LOADING: string; - /** - * fired when an audio track loading finishes - * data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime } } - */ - const AUDIO_TRACK_LOADED: string; - /** - * fired to notify that subtitle track lists has been updated - * data: { subtitleTracks : subtitleTracks } - */ - const SUBTITLE_TRACKS_UPDATED: string; - /** - * fired when an subtitle track switch occurs - * data: { id : subtitle track id } - */ - const SUBTITLE_TRACK_SWITCH: string; - /** - * fired when a subtitle track loading starts - * data: { url : subtitle track URL, id : subtitle track id } - */ - const SUBTITLE_TRACK_LOADING: string; - /** - * fired when a subtitle track loading finishes - * data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime } } - */ - const SUBTITLE_TRACK_LOADED: string; - /** - * fired when a subtitle fragment has been processed - * data: { success : boolean, frag : the processed frag } - */ - const SUBTITLE_FRAG_PROCESSED: string; - /** - * fired when a decryption key loading starts - * data: { frag: fragment object } - */ - const KEY_LOADING: string; - /** - * fired when a decryption key loading is completed - * data: { frag: fragment object } - */ - const KEY_LOADED: string; - /** - * fired when first timestamp has been found - * data: { id: demuxer id, frag: fragment object, initPTS: initPTS } - */ - const INIT_PTS_FOUND: string; - /** - * fired when a fragment loading starts - * data: { frag : fragment object } - */ - const FRAG_LOADING: string; - /** - * fired when a fragment load is in progress - * data: { frag : fragment object with frag.loaded=stats.loaded, stats : { trequest, tfirst, loaded, total } } - */ - const FRAG_LOAD_PROGRESS: string; - /** - * identifier for fragment load aborting for emergency switch down - * data: { frag: fragment object } - */ - const FRAG_LOAD_ERMERGENCY_ABORTED: string; - /** - * fired when a fragment loading is completed - * data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length}} - */ - const FRAG_LOADED: string; - /** - * fired when a fragment decryption is completed - * data: { id: demuxer id, frag: fragment object, stats: { tstart, tdecrypt } } - */ - const FRAG_DECRYPTED: string; - /** - * fired when Init Segment has been extracted from fragment - * data: { id: demuxer id, moov : moov MP4 box, codecs : codecs found while parsing fragment} - */ - const FRAG_PARSING_INIT_SEGMENT: string; - /** - * fired when parsing id3 is completed - * data: { id: demuxer id, samples : [ id3 pes - pts and dts timestamp are relative, values are in seconds]} - */ - const FRAG_PARSING_METADATA: string; - /** - * fired when moof/mdat have been extracted from fragment - * data: { id: demuxer id, - * moof : moof MP4 box, - * mdat : mdat MP4 box, - * startPTS : PTS of first sample, - * endPTS : PTS of last sample, - * startDTS : DTS of first sample, - * endDTS : DTS of last sample, - * type : stream type (audio or video), - * nb : number of samples} - */ - const FRAG_PARSING_DATA: string; - /** - * fired when fragment parsing is completed - * data: { id: demuxer id} - */ - const FRAG_PARSED: string; - /** - * fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - * data: { id: demuxer id, frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tbuffered, length} } - */ - const FRAG_BUFFERED: string; - /** - * fired when fragment matching with current video position is changing - * data: { frag : fragment object } - */ - const FRAG_CHANGED: string; - /** - * triggered when FPS drop in last monitoring period is higher than given threshold - * data: { curentDropped : nb of dropped frames in last monitoring period, - * currentDecoded : nb of decoded frames in last monitoring period, - * totalDropped : total dropped frames on this video element } - */ - const FPS_DROP: string; - /** - * triggered when FPS drop triggers auto level capping - * data: { level: suggested new auto level capping by fps controller, droppedLevel : level has to much dropped frame will be restricted } - */ - const FPS_DROP_LEVEL_CAPPING: string; - /** - * Identifier for an error event - * data: { type : error type, details : error details, fatal : is error fatal or not, other error specific data } - */ - const ERROR: string; - /** - * fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a video to the instance of hls.js to handle mid-rolls for example. - * data: { } - */ - const DESTROYING: string; - /** - * fired upon stream controller state transitions - * data: { previousState, nextState } - */ - const STREAM_STATE_TRANSITION: string; - } + namespace Events { + /** + * fired to attach Media to hls instance + * data: { video , mediaSource } + */ + const MEDIA_ATTACHING: string; + /** + * fired when Media has been succesfully attached to hls instance + * data: { video , mediaSource } + */ + const MEDIA_ATTACHED: string; + /** + * fired before detaching Media from hls instance + * data: { } + */ + const MEDIA_DETACHING: string; + /** + * fired when Media has been detached from hls instance + * data: { } + */ + const MEDIA_DETACHED: string; + /** + * fired when the buffer is going to be reset + * data: { } + */ + const BUFFER_RESET: string; + /** + * fired when we know about the codecs that we need buffers for to push into + * data: { tracks : { container, codec, levelCodec, initSegment, metadata } } + */ + const BUFFER_CODECS: string; + /** + * fired when sourcebuffers have been created + * data: { tracks: tracks } + */ + const BUFFER_CREATED: string; + /** + * fired when we append a segment to the buffer + * data: { segment: segment object } + */ + const BUFFER_APPENDING: string; + /** + * fired when we are done with appending a media segment to the buffer + * data: { parent : segment parent that triggered BUFFER_APPENDING, pending : nb of segments waiting for appending for this segment parent } + */ + const BUFFER_APPENDED: string; + /** + * fired when the stream is finished and we want to notify the media buffer that there will be no more data + * data: { } + */ + const BUFFER_EOS: string; + /** + * fired when the media buffer should be flushed + * data: { } + */ + const BUFFER_FLUSHING: string; + /** + * fired when the media buffer has been flushed + * data: { } + */ + const BUFFER_FLUSHED: string; + /** + * fired to signal that a manifest loading starts + * data: { url : manifestURL } + */ + const MANIFEST_LOADING: string; + /** + * fired after manifest has been loaded + * data: { levels : [available quality levels] , audioTracks : [ available audio tracks], url : manifestURL, stats : { trequest, tfirst, tload, mtime}} + */ + const MANIFEST_LOADED: string; + /** + * fired after manifest has been parsed + * data: { levels : [ available quality levels ], firstLevel : index of first quality level appearing in Manifest } + */ + const MANIFEST_PARSED: string; + /** + * fired when a level playlist loading starts + * data: { url : level URL, level : id of level being loaded } + */ + const LEVEL_LOADING: string; + /** + * fired when a level playlist loading finishes + * data: { details : levelDetails object, levelId : id of loaded level, stats : { trequest, tfirst, tload, mtime } } + */ + const LEVEL_LOADED: string; + /** + * fired when a level's details have been updated based on previous details, after it has been loaded + * data: { details : levelDetails object, level : id of updated level } + */ + const LEVEL_UPDATED: string; + /** + * fired when a level's PTS information has been updated after parsing a fragment + * data: { details: levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment } + */ + const LEVEL_PTS_UPDATED: string; + /** + * fired when a level switch is requested + * data: { level: Level } + */ + const LEVEL_SWITCHING: string; + /** + * fired when a level switch is effective + * data: { level: level object } + */ + const LEVEL_SWITCHED: string; + /** + * fired to notify that audio track lists has been updated + * data: { audioTracks : audioTracks } + */ + const AUDIO_TRACKS_UPDATED: string; + /** + * fired when an audio track switch occurs. deprecated in favor AUDIO_TRACK_SWITCHING + * data: { id : audio track id } + */ + const AUDIO_TRACK_SWTICH: string; + /** + * fired when an audio track switching is requested + * data: { id : audio track id } + */ + const AUDIO_TRACK_SWITCHING: string; + /** + * fired when an audio track switch actually occurs + * data: { id : audio track id } + */ + const AUDIO_TRACK_SWITCHED: string; + /** + * fired when an audio track loading starts + * data: { url : audio track URL, id : audio track id } + */ + const AUDIO_TRACK_LOADING: string; + /** + * fired when an audio track loading finishes + * data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime } } + */ + const AUDIO_TRACK_LOADED: string; + /** + * fired to notify that subtitle track lists has been updated + * data: { subtitleTracks : subtitleTracks } + */ + const SUBTITLE_TRACKS_UPDATED: string; + /** + * fired when an subtitle track switch occurs + * data: { id : subtitle track id } + */ + const SUBTITLE_TRACK_SWITCH: string; + /** + * fired when a subtitle track loading starts + * data: { url : subtitle track URL, id : subtitle track id } + */ + const SUBTITLE_TRACK_LOADING: string; + /** + * fired when a subtitle track loading finishes + * data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime } } + */ + const SUBTITLE_TRACK_LOADED: string; + /** + * fired when a subtitle fragment has been processed + * data: { success : boolean, frag : the processed frag } + */ + const SUBTITLE_FRAG_PROCESSED: string; + /** + * fired when a decryption key loading starts + * data: { frag: fragment object } + */ + const KEY_LOADING: string; + /** + * fired when a decryption key loading is completed + * data: { frag: fragment object } + */ + const KEY_LOADED: string; + /** + * fired when first timestamp has been found + * data: { id: demuxer id, frag: fragment object, initPTS: initPTS } + */ + const INIT_PTS_FOUND: string; + /** + * fired when a fragment loading starts + * data: { frag : fragment object } + */ + const FRAG_LOADING: string; + /** + * fired when a fragment load is in progress + * data: { frag : fragment object with frag.loaded=stats.loaded, stats : { trequest, tfirst, loaded, total } } + */ + const FRAG_LOAD_PROGRESS: string; + /** + * identifier for fragment load aborting for emergency switch down + * data: { frag: fragment object } + */ + const FRAG_LOAD_ERMERGENCY_ABORTED: string; + /** + * fired when a fragment loading is completed + * data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length}} + */ + const FRAG_LOADED: string; + /** + * fired when a fragment decryption is completed + * data: { id: demuxer id, frag: fragment object, stats: { tstart, tdecrypt } } + */ + const FRAG_DECRYPTED: string; + /** + * fired when Init Segment has been extracted from fragment + * data: { id: demuxer id, moov : moov MP4 box, codecs : codecs found while parsing fragment} + */ + const FRAG_PARSING_INIT_SEGMENT: string; + /** + * fired when parsing id3 is completed + * data: { id: demuxer id, samples : [ id3 pes - pts and dts timestamp are relative, values are in seconds]} + */ + const FRAG_PARSING_METADATA: string; + /** + * fired when moof/mdat have been extracted from fragment + * data: { id: demuxer id, + * moof : moof MP4 box, + * mdat : mdat MP4 box, + * startPTS : PTS of first sample, + * endPTS : PTS of last sample, + * startDTS : DTS of first sample, + * endDTS : DTS of last sample, + * type : stream type (audio or video), + * nb : number of samples} + */ + const FRAG_PARSING_DATA: string; + /** + * fired when fragment parsing is completed + * data: { id: demuxer id} + */ + const FRAG_PARSED: string; + /** + * fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer + * data: { id: demuxer id, frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tbuffered, length} } + */ + const FRAG_BUFFERED: string; + /** + * fired when fragment matching with current video position is changing + * data: { frag : fragment object } + */ + const FRAG_CHANGED: string; + /** + * triggered when FPS drop in last monitoring period is higher than given threshold + * data: { curentDropped : nb of dropped frames in last monitoring period, + * currentDecoded : nb of decoded frames in last monitoring period, + * totalDropped : total dropped frames on this video element } + */ + const FPS_DROP: string; + /** + * triggered when FPS drop triggers auto level capping + * data: { level: suggested new auto level capping by fps controller, droppedLevel : level has to much dropped frame will be restricted } + */ + const FPS_DROP_LEVEL_CAPPING: string; + /** + * Identifier for an error event + * data: { type : error type, details : error details, fatal : is error fatal or not, other error specific data } + */ + const ERROR: string; + /** + * fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a video to the instance of hls.js to handle mid-rolls for example. + * data: { } + */ + const DESTROYING: string; + /** + * fired upon stream controller state transitions + * data: { previousState, nextState } + */ + const STREAM_STATE_TRANSITION: string; + } - /** - * Hls error details - */ - namespace ErrorDetails { - // NETWORK_ERRORS // /** - * raised when manifest loading fails because of a network error - * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.MANIFEST_LOAD_ERROR, fatal : true, url : manifest URL, response : { code: error code, text: error text }, loader : URL loader } + * Hls error details */ - const MANIFEST_LOAD_ERROR: string; - /** - * raised when manifest loading fails because of a timeout - * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.MANIFEST_LOAD_TIMEOUT, fatal : true, url : manifest URL, loader : URL loader } - */ - const MANIFEST_LOAD_TIMEOUT: string; - /** - * raised when manifest parsing failed to find proper content - * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.MANIFEST_PARSING_ERROR, fatal : true, url : manifest URL, reason : parsing error reason } - */ - const MANIFEST_PARSING_ERROR: string; - /** - * raised when level loading fails because of a network error - * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.LEVEL_LOAD_ERROR, fatal : true, url : level URL, response : { code: error code, text: error text }, loader : URL loader } - */ - const LEVEL_LOAD_ERROR: string; - /** - * raised when level loading fails because of a timeout - * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.LEVEL_LOAD_TIMEOUT, fatal : true, url : level URL, loader : URL loader } - */ - const LEVEL_LOAD_TIMEOUT: string; - /** - * raised when audio track loading fails because of a network error - * data: { type: NETWORK_ERROR, details: Hls.ErrorDetails.AUDIO_TRACK_LOAD_ERROR, fatal: false, url: audio URL, loader: URL loader } - */ - const AUDIO_TRACK_LOAD_ERROR: string; - /** - * raised when audio track loading fails because of a timeout - * data: { type: NETWORK_ERROR, details: Hls.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT, fatal: false, url: audio URL, response: { code: error code, text: error text }, loader: URL loader } - */ - const AUDIO_TRACK_LOAD_TIMEOUT: string; - /** - * raised when fragment loading fails because of a network error - * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.FRAG_LOAD_ERROR, fatal : true or false, frag : fragment object, response : { code: error code, text: error text } } - */ - const FRAG_LOAD_ERROR: string; - /** - * raised when fragment loading fails because of a timeout - * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.FRAG_LOAD_TIMEOUT, fatal : true or false, frag : fragment object } - */ - const FRAG_LOAD_TIMEOUT: string; - /** - * raised when decrypt key loading fails because of a network error - * data: { type: NETWORK_ERROR, details: Hls.ErrorDetails.KEY_LOAD_ERROR, fatal: false, frag: fragment object } - */ - const KEY_LOAD_ERROR: string; - /** - * raised when decrypt key loading fails because of timeout - * data: { type: NETWORK_EROR, details: Hls.ErrorDetails.KEY_LOAD_TIMEOUT, fatal: true, frag: fragment object } - */ - const KEY_LOAD_TIMEOUT: string; + namespace ErrorDetails { + // NETWORK_ERRORS // + /** + * raised when manifest loading fails because of a network error + * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.MANIFEST_LOAD_ERROR, fatal : true, url : manifest URL, response : { code: error code, text: error text }, loader : URL loader } + */ + const MANIFEST_LOAD_ERROR: string; + /** + * raised when manifest loading fails because of a timeout + * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.MANIFEST_LOAD_TIMEOUT, fatal : true, url : manifest URL, loader : URL loader } + */ + const MANIFEST_LOAD_TIMEOUT: string; + /** + * raised when manifest parsing failed to find proper content + * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.MANIFEST_PARSING_ERROR, fatal : true, url : manifest URL, reason : parsing error reason } + */ + const MANIFEST_PARSING_ERROR: string; + /** + * raised when level loading fails because of a network error + * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.LEVEL_LOAD_ERROR, fatal : true, url : level URL, response : { code: error code, text: error text }, loader : URL loader } + */ + const LEVEL_LOAD_ERROR: string; + /** + * raised when level loading fails because of a timeout + * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.LEVEL_LOAD_TIMEOUT, fatal : true, url : level URL, loader : URL loader } + */ + const LEVEL_LOAD_TIMEOUT: string; + /** + * raised when audio track loading fails because of a network error + * data: { type: NETWORK_ERROR, details: Hls.ErrorDetails.AUDIO_TRACK_LOAD_ERROR, fatal: false, url: audio URL, loader: URL loader } + */ + const AUDIO_TRACK_LOAD_ERROR: string; + /** + * raised when audio track loading fails because of a timeout + * data: { type: NETWORK_ERROR, details: Hls.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT, fatal: false, url: audio URL, response: { code: error code, text: error text }, loader: URL loader } + */ + const AUDIO_TRACK_LOAD_TIMEOUT: string; + /** + * raised when fragment loading fails because of a network error + * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.FRAG_LOAD_ERROR, fatal : true or false, frag : fragment object, response : { code: error code, text: error text } } + */ + const FRAG_LOAD_ERROR: string; + /** + * raised when fragment loading fails because of a timeout + * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.FRAG_LOAD_TIMEOUT, fatal : true or false, frag : fragment object } + */ + const FRAG_LOAD_TIMEOUT: string; + /** + * raised when decrypt key loading fails because of a network error + * data: { type: NETWORK_ERROR, details: Hls.ErrorDetails.KEY_LOAD_ERROR, fatal: false, frag: fragment object } + */ + const KEY_LOAD_ERROR: string; + /** + * raised when decrypt key loading fails because of timeout + * data: { type: NETWORK_EROR, details: Hls.ErrorDetails.KEY_LOAD_TIMEOUT, fatal: true, frag: fragment object } + */ + const KEY_LOAD_TIMEOUT: string; - // MEDIA_ERRORS // - /** - * raised when manifest only contains quality level with codecs incompatible with MediaSource Engine. - * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR, fatal : true, url : manifest URL } - */ - const MANIFEST_INCOMPATIBLE_CODECS_ERROR: string; - /** - * raised upon detection of same fragment being requested in loop - * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.FRAG_LOOP_LOADING_ERROR, fatal : true or false, frag : fragment object } - */ - const FRAG_LOOP_LOADING_ERROR: string; - /** - * raised when fragment decryption fails - * data: { type: MEDIA_ERROR, details: Hls.ErrorDetails.FRAG_DECRYPT_ERROR, fatal: true, reason: failure reason } - */ - const FRAG_DECRYPT_ERROR: string; - /** - * raised when fragment parsing fails - * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.FRAG_PARSING_ERROR, fatal : true or false, reason : failure reason } - */ - const FRAG_PARSING_ERROR: string; - /** - * raised when MediaSource fails to add new sourceBuffer - * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_ADD_CODEC_ERROR, fatal : false, err : error raised by MediaSource, mimeType: mimeType on which the failure happened } - */ - const BUFFER_ADD_CODEC_ERROR: string; - /** - * raised when exception is raised while calling buffer append - * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_APPEND_ERROR, fatal : true, frag : fragment object } - */ - const BUFFER_APPEND_ERROR: string; - /** - * raised when exception is raised during buffer appending - * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_APPENDING_ERROR, fatal : false } - */ - const BUFFER_APPENDING_ERROR: string; - /** - * raised when playback is stuck because buffer is running out of data - * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_STALLED_ERROR, fatal : false } - */ - const BUFFER_STALLED_ERROR: string; - /** - * raised when no data can be appended anymore in media buffer because it is full. - * This error is recovered automatically by performing a smooth level switching that empty buffers (without disrupting the playback) and reducing the max buffer length. - * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_FULL_ERROR, fatal : false } - */ - const BUFFER_FULL_ERROR: string; - /** - * raised after hls.js seeks over a buffer hole to unstuck the playback, - * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_SEEK_OVER_HOLE, fatal : false, hole : hole duration } - */ - const BUFFER_SEEK_OVER_HOLE: string; - /** - * raised when playback is stuck although currentTime is in a buffered aread - * data: { type: MEDIA_ERROR, details: Hls.ErrorDetails.BUFFERED_STALLED_ERROR, fatal: true } - */ - const BUFFER_NUDGE_ON_STALL: string; + // MEDIA_ERRORS // + /** + * raised when manifest only contains quality level with codecs incompatible with MediaSource Engine. + * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR, fatal : true, url : manifest URL } + */ + const MANIFEST_INCOMPATIBLE_CODECS_ERROR: string; + /** + * raised upon detection of same fragment being requested in loop + * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.FRAG_LOOP_LOADING_ERROR, fatal : true or false, frag : fragment object } + */ + const FRAG_LOOP_LOADING_ERROR: string; + /** + * raised when fragment decryption fails + * data: { type: MEDIA_ERROR, details: Hls.ErrorDetails.FRAG_DECRYPT_ERROR, fatal: true, reason: failure reason } + */ + const FRAG_DECRYPT_ERROR: string; + /** + * raised when fragment parsing fails + * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.FRAG_PARSING_ERROR, fatal : true or false, reason : failure reason } + */ + const FRAG_PARSING_ERROR: string; + /** + * raised when MediaSource fails to add new sourceBuffer + * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_ADD_CODEC_ERROR, fatal : false, err : error raised by MediaSource, mimeType: mimeType on which the failure happened } + */ + const BUFFER_ADD_CODEC_ERROR: string; + /** + * raised when exception is raised while calling buffer append + * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_APPEND_ERROR, fatal : true, frag : fragment object } + */ + const BUFFER_APPEND_ERROR: string; + /** + * raised when exception is raised during buffer appending + * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_APPENDING_ERROR, fatal : false } + */ + const BUFFER_APPENDING_ERROR: string; + /** + * raised when playback is stuck because buffer is running out of data + * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_STALLED_ERROR, fatal : false } + */ + const BUFFER_STALLED_ERROR: string; + /** + * raised when no data can be appended anymore in media buffer because it is full. + * This error is recovered automatically by performing a smooth level switching that empty buffers (without disrupting the playback) and reducing the max buffer length. + * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_FULL_ERROR, fatal : false } + */ + const BUFFER_FULL_ERROR: string; + /** + * raised after hls.js seeks over a buffer hole to unstuck the playback, + * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_SEEK_OVER_HOLE, fatal : false, hole : hole duration } + */ + const BUFFER_SEEK_OVER_HOLE: string; + /** + * raised when playback is stuck although currentTime is in a buffered aread + * data: { type: MEDIA_ERROR, details: Hls.ErrorDetails.BUFFERED_STALLED_ERROR, fatal: true } + */ + const BUFFER_NUDGE_ON_STALL: string; - // MUX_ERROR // - /** - * raised when memory allocation fails during remuxing - * data: { type: MUX_ERROR, details: Hls.ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes: mdat size, reason: failure reason } - */ - const REMUX_ALLOC_ERROR: string; + // MUX_ERROR // + /** + * raised when memory allocation fails during remuxing + * data: { type: MUX_ERROR, details: Hls.ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes: mdat size, reason: failure reason } + */ + const REMUX_ALLOC_ERROR: string; - // OTHER_ERROR // - /** - * raised when level switching fails - * data: { type : OTHER_ERROR, details : Hls.ErrorDetails.LEVEL_SWITCH_ERROR, fatal : false, level : failed level index, reason : failure reason } - */ - const LEVEL_SWITCH_ERROR: string; - /** - * raised when an exception occurs in an internal hls.js event handler - * data: { type: OTHER_ERROR, details: Hls.ErrorDetails.INTERNAL_EXCEPTION, fatal: true or false, event: event object or string, error: { message: error message } } - */ - const INTERNAL_EXCEPTION: string; - } + // OTHER_ERROR // + /** + * raised when level switching fails + * data: { type : OTHER_ERROR, details : Hls.ErrorDetails.LEVEL_SWITCH_ERROR, fatal : false, level : failed level index, reason : failure reason } + */ + const LEVEL_SWITCH_ERROR: string; + /** + * raised when an exception occurs in an internal hls.js event handler + * data: { type: OTHER_ERROR, details: Hls.ErrorDetails.INTERNAL_EXCEPTION, fatal: true or false, event: event object or string, error: { message: error message } } + */ + const INTERNAL_EXCEPTION: string; + } - /** - * Hls error types - */ - namespace ErrorTypes { /** - * network related errors + * Hls error types */ - const NETWORK_ERROR: string; + namespace ErrorTypes { + /** + * network related errors + */ + const NETWORK_ERROR: string; + /** + * media/video related errors + */ + const MEDIA_ERROR: string; + /** + * muxing related errors + */ + const MUX_ERROR: string; + /** + * all other erros + */ + const OTHER_ERROR: string; + } /** - * media/video related errors + * override Hls default configuration + * this configuration will be applied by default to all instances */ - const MEDIA_ERROR: string; + let DefaultConfig: Config; /** - * muxing related errors + * checks whether your browser is supporting MediaSource Extensions */ - const MUX_ERROR: string; + function isSupported(): boolean; /** - * all other erros + * returns hls.js dist version number */ - const OTHER_ERROR: string; - } - /** - * override Hls default configuration - * this configuration will be applied by default to all instances - */ - let DefaultConfig: Config; - /** - * checks whether your browser is supporting MediaSource Extensions - */ - function isSupported(): boolean; - /** - * returns hls.js dist version number - */ - const version: string; + const version: string; - interface Config { + interface Config { + /** + * (default: true) + * if set to true, start level playlist and first fragments will be loaded automatically, after triggering of Hls.Events.MANIFEST_PARSED event + * if set to false, an explicit API call (hls.startLoad(startPosition=-1)) will be needed to start quality level/fragment loading. + */ + autoStartLoad: boolean; + /** + * (default -1) + * if set to -1, playback will start from initialTime=0 for VoD and according to liveSyncDuration/liveSyncDurationCount config params for Live + * otherwise, playback will start from predefined value. (unless stated otherwise in autoStartLoad=false mode : in that case startPosition can be overrided using hls.startLoad(startPosition)). + */ + startPosition: number; + /** + * (default: false) + * if set to true, the adaptive algorithm with limit levels usable in auto-quality by the HTML video element dimensions (width and height) + * if set to false, levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration. + */ + capLevelToPlayerSize: boolean; + /** + * (default: false) + * setting config.debug = true; will turn on debug logs on JS console. + * a logger object could also be provided for custom logging: config.debug = customLogger; + */ + debug: boolean; + /** + * (default: undefined) + * if audio codec is not signaled in variant manifest, or if only a stream manifest is provided, hls.js tries to guess audio codec by parsing audio sampling rate in ADTS header. + * If sampling rate is less or equal than 22050 Hz, then hls.js assumes it is HE-AAC, otherwise it assumes it is AAC-LC. + * This could result in bad guess, leading to audio decode error, ending up in media error. + * It is possible to hint default audiocodec to hls.js by configuring this value as below: + * mp4a.40.2 (AAC-LC) or + * mp4a.40.5 (HE-AAC) or + * undefined (guess based on sampling rate) + */ + defaultAudioCodec: string; + /** + * (default: 1) + * number of segments needed to start a playback of Live stream. + */ + initialLiveManifestSize: number; + /** + * (default: 30 seconds) + * Maximum buffer length in seconds. If buffer length is/become less than this value, a new fragment will be loaded. + * This is the guaranteed buffer length hls.js will try to reach, regardless of maxBufferSize. + */ + maxBufferLength: number; + /** + * (default 600s) + * Maximum buffer length in seconds. Hls.js will never exceed this value, even if maxBufferSize is not reached yet. + * hls.js tries to buffer up to a maximum number of bytes (60 MB by default) rather than to buffer up to a maximum nb of seconds. + * This is to mimic the browser behaviour (the buffer eviction algorithm is starting after the browser detects that video buffer size reaches a limit in bytes) + * maxBufferLength is the minimum guaranteed buffer length that hls.js will try to achieve, even if that value exceeds the amount of bytes 60 MB of memory. + * maxMaxBufferLength acts as a capping value, as if bitrate is really low, you could need more than one hour of buffer to fill 60 MB. + */ + maxMaxBufferLength: number; + /** + * (default: 60 MB) + * 'Minimum' maximum buffer size in bytes. If buffer size upfront is bigger than this value, no fragment will be loaded + */ + maxBufferSize: number; + /** + * (default: 0.5 seconds) + * 'Maximum' inter-fragment buffer hole tolerance that hls.js can cope with when searching for the next fragment to load. When switching between quality level, + * fragments might not be perfectly aligned. + * This could result in small overlapping or hole in media buffer. This tolerance factor helps cope with this. + */ + maxBufferHole: number; + /** + * (default: 4s) + * + * ABR algorithm will always try to choose a quality level that should avoid rebuffering. In case no quality level with this criteria can + * be found (lets say for example that buffer length is 1s, but fetching a fragment at lowest quality is predicted to take around 2s ... + * ie we can forecast around 1s of rebuffering ...) then ABR algorithm will try to find a level that should guarantee less than + * maxStarvationDelay of buffering. + */ + maxStarvationDelay: number; + /** + * (default: 2s) + * In case playback is stalled, and a buffered range is available upfront, less than maxSeekHole seconds from current media position, + * hls.js will jump over this buffer hole to reach the beginning of this following buffered range. + * maxSeekHole allows to configure this jumpable threshold. + */ + maxSeekHole: number; + /** + * (default: 0.5s) + * media element is expected to play and if currentTime has not moved for more than lowBufferWatchdogPeriod and if there are less than maxBufferHole seconds buffered upfront, + * hls.js will try to nudge playhead to recover playback + */ + lowBufferWatchdogPeriod: number; + /** + * (default: 3s) + * if media element is expected to play and if currentTime has not moved for more than highBufferWatchdogPeriod and if there are more than maxBufferHole seconds buffered upfront, + * hls.js will try to nudge playhead to recover playback + */ + highBufferWatchdogPeriod: number; + /** + * (default: 0.1s) + * In case playback continues to stall after first playhead nudging, currentTime will be nudged evenmore following nudgeOffset to try to restore playback. + * media.currentTime += (nb nudge retry -1)*nudgeOffset + */ + nudgeOffset: number; + /** + * (default: 3s) + * In case playback continues to stall after first playhead nudging, currentTime will be nudged evenmore following nudgeOffset to try to restore playback. + * media.currentTime += (nb nudge retry -1)*nudgeOffset + */ + nudgeMaxRetry: number; + /** + * (default 0.2s) + * This tolerance factor is used during fragment lookup. + * Instead of checking whether buffered.end is located within [start, end] range, frag lookup will be done by checking within [start-maxFragLookUpTolerance, end-maxFragLookUpTolerance] range. + * This tolerance factor is used to cope with situations like: + * buffered.end = 9.991 + * frag[0] : [0,10] + * frag[1] : [10,20] + * buffered.end is within frag[0] range, but as we are close to frag[1], frag[1] should be choosen instead + * If maxFragLookUpTolerance = 0.2, this lookup will be adjusted to + * frag[0] : [-0.2,9.8] + * frag[1] : [9.8,19.8] + * This time, buffered.end is within frag[1] range, and frag[1] will be the next fragment to be loaded, as expected + */ + maxLoadingDelay: number; + /** + * (default 4s) + * + * 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 ) + */ + maxFragLookUpTolerance: number; + /** + * (default: 3) + * edge of live delay, expressed in multiple of EXT-X-TARGETDURATION. if set to 3, playback will start from fragment N-3, N being the last fragment of the live playlist. + * Decreasing this value is likely to cause playback stalls. + */ + liveSyncDurationCount: number; + /** + * (default: undefined) + * Alternative parameter to liveSyncDurationCount, expressed in seconds vs number of segments. + * If defined in the configuration object, liveSyncDuration will take precedence over the default liveSyncDurationCount. + * You can't define this parameter and either liveSyncDurationCount or liveMaxLatencyDurationCount in your configuration object at the same time. + * A value too low (inferior to ~3 segment durations) is likely to cause playback stalls. + */ + liveSyncDuration: number; + /** + * (default: Infinity) + * maximum delay allowed from edge of live, expressed in multiple of EXT-X-TARGETDURATION. + * If set to 10, the player will seek back to liveSyncDurationCount whenever the next fragment to be loaded is older than N-10, N being the last fragment of the live playlist. + * If set, this value must be stricly superior to liveSyncDurationCount a value too close from liveSyncDurationCount is likely to cause playback stalls. + */ + liveMaxLatencyDurationCount: number; + /** + * (default: undefined) + * Alternative parameter to liveMaxLatencyDurationCount, expressed in seconds vs number of segments. + * If defined in the configuration object, liveMaxLatencyDuration will take precedence over the default liveMaxLatencyDurationCount. + * If set, this value must be stricly superior to liveSyncDuration which must be defined as well. + * You can't define this parameter and either liveSyncDurationCount or liveMaxLatencyDurationCount in your configuration object at the same time. + * A value too close from liveSyncDuration is likely to cause playback stalls. + */ + liveMaxLatencyDuration: number; + /** + * (default: true) + * Enable WebWorker (if available on browser) for TS demuxing/MP4 remuxing, to improve performance and avoid lag/frame drops. + */ + enableWorker: boolean; + /** + * (default: true) + * Enable to use JavaScript version AES decryption for fallback of WebCrypto API. + */ + enableSoftwareAES: boolean; + /** + * (default: undefined) + * When set, use this level as the default hls.startLevel. Keep in mind that the startLevel set with the API takes precedence over + * config.startLevel configuration parameter. + */ + startLevel: number; + /** + * (default: 10000ms for level and manifest) + * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. + * It is up to the application to catch this event and treat it as needed. + */ + manifestLoadingTimeOut: number; + /** + * (default: 3) + * Max number of load retries. + */ + manifestLoadingMaxRetry: number; + /** + * (default: 1000 ms) + * Initial delay between XMLHttpRequest error and first load retry (in ms). + * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). + * Prefetch start fragment although media not attached. + */ + manifestLoadingRetryDelay: number; + /** + * (default: 64000 ms) + * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. + */ + manifestLoadingMaxRetryTimeout: number; + /** + * (default: 60000ms for fragment) + * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. + * It is up to the application to catch this event and treat it as needed. + */ + levelLoadingTimeOut: number; + /** + * (default: 3) + * Max number of load retries. + */ + levelLoadingMaxRetry: number; + /** + * (default: 1000 ms) + * Initial delay between XMLHttpRequest error and first load retry (in ms). + * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). + * Prefetch start fragment although media not attached. + */ + levelLoadingRetryDelay: number; + /** + * (default: 64000 ms) + * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. + */ + levelLoadingMaxRetryTimeout: number; + /** + * (default: 60000ms for fragment) + * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. + * It is up to the application to catch this event and treat it as needed. + */ + fragLoadingTimeOut: number; + /** + * (default: 3) + * Max number of load retries. + */ + fragLoadingMaxRetry: number; + /** + * (default: 1000 ms) + * Initial delay between XMLHttpRequest error and first load retry (in ms). + * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). + * Prefetch start fragment although media not attached. + */ + fragLoadingRetryDelay: number; + /** + * (default: 64000 ms) + * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. + */ + fragLoadingMaxRetryDelay: number; + /** + * (default: false) + * Start prefetching start fragment although media not attached yet. Max number of append retries. + */ + startFragPrefech: boolean; + /** + * (default: 3) + * Max number of sourceBuffer.appendBuffer() retry upon error. Such error could happen in loop with UHD streams, when internal buffer is full. (Quota Exceeding Error will be triggered). + * In that case we need to wait for the browser to evict some data before being able to append buffer correctly. + */ + appendErrorMaxRetry: number; + /** + * (default: standard XMLHttpRequest-based URL loader) + * Override standard URL loader by a custom one. Could be useful for P2P or stubbing (testing). + * Use this, if you want to overwrite both the fragment and the playlist loader. + * Note: If fLoader or pLoader are used, they overwrite loader! + */ + loader: typeof Loader; + /** + * (default: undefined) + * This enables the manipulation of the fragment loader. + * Note: This will overwrite the default loader, as well as your own loader function. + */ + fLoader?: typeof Loader; + /** + * (default: undefined) + * This enables the manipulation of the playlist loader. + * Note: This will overwrite the default loader, as well as your own loader function. + */ + pLoader?: typeof Loader; + /** + * (default: undefined) + * XMLHttpRequest customization callback for default XHR based loader. + * Parameter should be a function with two arguments (xhr: XMLHttpRequest, url: string). + * If xhrSetup is specified, default loader will invoke it before calling xhr.send(). This allows user to easily modify/setup XHR. + */ + xhrSetup?(xhr: XMLHttpRequest, url: string): void; + /** + * (default: undefined) + * Fetch customization callback for Fetch based loader. + * Parameter should be a function with two arguments (context and Request Init Params). + * If fetchSetup is specified and Fetch loader is used, fetchSetup will be triggered to instantiate Request Object. This allows user to easily tweak Fetch loader. + */ + fetchSetup?(context: any, initParams: any): Request; + /** + * (default: internal ABR controller) + * Customized Adaptive Bitrate Streaming Controller. + * Parameter should be a class providing 2 getters, 2 setters and a destroy() method: + * get/set nextAutoLevel: return next auto-quality level/force next auto-quality level that should be returned (currently used for emergency switch down) + * get/set autoLevelCapping: capping/max level value that could be used by ABR Controller + * destroy(): should clean-up all used resources + */ + abrController: AbrController; + /** + * (default: internal track timeline controller) + * Customized text track syncronization controller. + * Parameter should be a class with a destroy() method: + * destroy() : should clean-up all used resources + */ + timelineController: TimelineController; + /** + * (default: true) + * whether or not to enable CEA-708 captions + */ + enableCEA708Captions: boolean; + /** + * (default: English) + * Label for the text track generated for CEA-708 captions track 1. This is how it will appear in the browser's native menu for subtitles and captions. + */ + captionsTextTrack1Label: string; + /** + * (default: en) + * RFC 3066 language code for the text track generated for CEA-708 captions track 1. + */ + captionsTextTrack1LanguagedCode: string; + /** + * (default: Spanish) + * Label for the text track generated for CEA-708 captions track 2. This is how it will appear in the browser's native menu for subtitles and captions. + */ + captionsTextTrack2Label: string; + /** + * (default: es) + * RFC 3066 language code for the text track generated for CEA-708 captions track 2. + */ + captionsTextTrack2LanguageCode: string; + /** + * (default: false) + * If a segment's video track is shorter than its audio track by > min(maxSeekHole, maxBufferHole), extend the final video frame's duration to match the audio track's duration. + * This helps playback continue in certain cases that might otherwise get stuck. + */ + stretchShortVideoTrack: boolean; + /** + * (default: true) + * Whether or not to force having a key frame in the first AVC sample after a discontinuity. + * If set to true, after a discontinuity, the AVC samples without any key frame will be dropped until finding one that contains a key frame. + * If set to false, all AVC samples will be kept, which can help avoid holes in the stream. Setting this parameter to false can also generate decoding weirdness when switching level or seeking. + */ + forceKeyFrameOnDiscontinuity: boolean; + /** + * (default: 5.0) + * Fast bitrate Exponential moving average half-life, used to compute average bitrate for Live streams. + * Half of the estimate is based on the last abrEwmaFastLive seconds of sample history. Each of the sample is weighted by the fragment loading duration. + * parameter should be a float greater than 0 + */ + abrEwmaFastLive: number; + /** + * (default: 9.0) + * Slow bitrate Exponential moving average half-life, used to compute average bitrate for Live streams. + * Half of the estimate is based on the last abrEwmaSlowLive seconds of sample history. Each of the sample is weighted by the fragment loading duration. + * parameter should be a float greater than abrEwmaFastLive + */ + abrEwmaSlowLive: number; + /** + * (default: 4.0) + * Fast bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams. + * Half of the estimate is based on the last abrEwmaFastVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration. + * parameter should be a float greater than 0 + */ + abrEwmaFastVod: number; + /** + * (default: 15.0) + * Slow bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams. + * Half of the estimate is based on the last abrEwmaSlowVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration. + * parameter should be a float greater than abrEwmaFastVoD + */ + abrEwmaSlowVod: number; + /** + * (default: 500000) + * Default bandwidth estimate in bits/second prior to collecting fragment bandwidth samples. + * parameter should be a float + */ + abrEwmaDefaultEstimate: number; + /** + * (default: 0.8) + * Scale factor to be applied against measured bandwidth average, to determine whether we can stay on current or lower quality level. + * If abrBandWidthFactor * bandwidth average < level.bitrate then ABR can switch to that level providing that it is equal or less than current level. + */ + abrBandWidthFactor: number; + /** + * (default: 0.7) + * Scale factor to be applied against measured bandwidth average, to determine whether we can switch up to a higher quality level. + * If abrBandWidthUpFactor * bandwidth average < level.bitrate then ABR can switch up to that quality level. + */ + abrBandWidthUpFactor: number; + /** + * (default: false) + * max bitrate used in ABR by avg measured bitrate i.e. if bitrate signaled in variant manifest for a given level is 2Mb/s but average bitrate measured on this level is 2.5Mb/s, + * then if config value is set to true, ABR will use 2.5 Mb/s for this quality level. + */ + abrMaxWithRealBitrate: boolean; + /** + * (default: 0) + * Return the capping/min bandwidth value that could be used by automatic level selection algorithm. + * Useful when browser or tab of the browser is not in the focus and bandwidth drops + */ + minAutoBitrate: number; + } + + interface OptionalConfig { + /** + * (default: true) + * if set to true, start level playlist and first fragments will be loaded automatically, after triggering of Hls.Events.MANIFEST_PARSED event + * if set to false, an explicit API call (hls.startLoad(startPosition=-1)) will be needed to start quality level/fragment loading. + */ + autoStartLoad?: boolean; + /** + * (default -1) + * if set to -1, playback will start from initialTime=0 for VoD and according to liveSyncDuration/liveSyncDurationCount config params for Live + * otherwise, playback will start from predefined value. (unless stated otherwise in autoStartLoad=false mode : in that case startPosition can be overrided using hls.startLoad(startPosition)). + */ + startPosition?: number; + /** + * (default: false) + * if set to true, the adaptive algorithm with limit levels usable in auto-quality by the HTML video element dimensions (width and height) + * if set to false, levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration. + */ + capLevelToPlayerSize?: boolean; + /** + * (default: false) + * setting config.debug = true; will turn on debug logs on JS console. + * a logger object could also be provided for custom logging: config.debug = customLogger; + */ + debug?: boolean; + /** + * (default: undefined) + * if audio codec is not signaled in variant manifest, or if only a stream manifest is provided, hls.js tries to guess audio codec by parsing audio sampling rate in ADTS header. + * If sampling rate is less or equal than 22050 Hz, then hls.js assumes it is HE-AAC, otherwise it assumes it is AAC-LC. + * This could result in bad guess, leading to audio decode error, ending up in media error. + * It is possible to hint default audiocodec to hls.js by configuring this value as below: + * mp4a.40.2 (AAC-LC) or + * mp4a.40.5 (HE-AAC) or + * undefined (guess based on sampling rate) + */ + defaultAudioCodec?: string; + /** + * (default: 1) + * number of segments needed to start a playback of Live stream. + */ + initialLiveManifestSize?: number; + /** + * (default: 30 seconds) + * Maximum buffer length in seconds. If buffer length is/become less than this value, a new fragment will be loaded. + * This is the guaranteed buffer length hls.js will try to reach, regardless of maxBufferSize. + */ + maxBufferLength?: number; + /** + * (default 600s) + * Maximum buffer length in seconds. Hls.js will never exceed this value, even if maxBufferSize is not reached yet. + * hls.js tries to buffer up to a maximum number of bytes (60 MB by default) rather than to buffer up to a maximum nb of seconds. + * This is to mimic the browser behaviour (the buffer eviction algorithm is starting after the browser detects that video buffer size reaches a limit in bytes) + * maxBufferLength is the minimum guaranteed buffer length that hls.js will try to achieve, even if that value exceeds the amount of bytes 60 MB of memory. + * maxMaxBufferLength acts as a capping value, as if bitrate is really low, you could need more than one hour of buffer to fill 60 MB. + */ + maxMaxBufferLength?: number; + /** + * (default: 60 MB) + * 'Minimum' maximum buffer size in bytes. If buffer size upfront is bigger than this value, no fragment will be loaded + */ + maxBufferSize?: number; + /** + * (default: 0.5 seconds) + * 'Maximum' inter-fragment buffer hole tolerance that hls.js can cope with when searching for the next fragment to load. When switching between quality level, + * fragments might not be perfectly aligned. + * This could result in small overlapping or hole in media buffer. This tolerance factor helps cope with this. + */ + maxBufferHole?: number; + /** + * (default: 4s) + * + * ABR algorithm will always try to choose a quality level that should avoid rebuffering. In case no quality level with this criteria can + * be found (lets say for example that buffer length is 1s, but fetching a fragment at lowest quality is predicted to take around 2s ... + * ie we can forecast around 1s of rebuffering ...) then ABR algorithm will try to find a level that should guarantee less than + * maxStarvationDelay of buffering. + */ + maxStarvationDelay?: number; + /** + * (default: 2s) + * In case playback is stalled, and a buffered range is available upfront, less than maxSeekHole seconds from current media position, + * hls.js will jump over this buffer hole to reach the beginning of this following buffered range. + * maxSeekHole allows to configure this jumpable threshold. + */ + maxSeekHole?: number; + /** + * (default: 0.5s) + * media element is expected to play and if currentTime has not moved for more than lowBufferWatchdogPeriod and if there are less than maxBufferHole seconds buffered upfront, + * hls.js will try to nudge playhead to recover playback + */ + lowBufferWatchdogPeriod?: number; + /** + * (default: 3s) + * if media element is expected to play and if currentTime has not moved for more than highBufferWatchdogPeriod and if there are more than maxBufferHole seconds buffered upfront, + * hls.js will try to nudge playhead to recover playback + */ + highBufferWatchdogPeriod?: number; + /** + * (default: 0.1s) + * In case playback continues to stall after first playhead nudging, currentTime will be nudged evenmore following nudgeOffset to try to restore playback. + * media.currentTime += (nb nudge retry -1)*nudgeOffset + */ + nudgeOffset?: number; + /** + * (default: 3s) + * In case playback continues to stall after first playhead nudging, currentTime will be nudged evenmore following nudgeOffset to try to restore playback. + * media.currentTime += (nb nudge retry -1)*nudgeOffset + */ + nudgeMaxRetry?: number; + /** + * (default 0.2s) + * This tolerance factor is used during fragment lookup. + * Instead of checking whether buffered.end is located within [start, end] range, frag lookup will be done by checking within [start-maxFragLookUpTolerance, end-maxFragLookUpTolerance] range. + * This tolerance factor is used to cope with situations like: + * buffered.end = 9.991 + * frag[0] : [0,10] + * frag[1] : [10,20] + * buffered.end is within frag[0] range, but as we are close to frag[1], frag[1] should be choosen instead + * If maxFragLookUpTolerance = 0.2, this lookup will be adjusted to + * frag[0] : [-0.2,9.8] + * frag[1] : [9.8,19.8] + * This time, buffered.end is within frag[1] range, and frag[1] will be the next fragment to be loaded, as expected + */ + maxLoadingDelay?: number; + /** + * (default 4s) + * + * 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 ) + */ + maxFragLookUpTolerance?: number; + /** + * (default: 3) + * edge of live delay, expressed in multiple of EXT-X-TARGETDURATION. if set to 3, playback will start from fragment N-3, N being the last fragment of the live playlist. + * Decreasing this value is likely to cause playback stalls. + */ + liveSyncDurationCount?: number; + /** + * (default: undefined) + * Alternative parameter to liveSyncDurationCount, expressed in seconds vs number of segments. + * If defined in the configuration object, liveSyncDuration will take precedence over the default liveSyncDurationCount. + * You can't define this parameter and either liveSyncDurationCount or liveMaxLatencyDurationCount in your configuration object at the same time. + * A value too low (inferior to ~3 segment durations) is likely to cause playback stalls. + */ + liveSyncDuration?: number; + /** + * (default: Infinity) + * maximum delay allowed from edge of live, expressed in multiple of EXT-X-TARGETDURATION. + * If set to 10, the player will seek back to liveSyncDurationCount whenever the next fragment to be loaded is older than N-10, N being the last fragment of the live playlist. + * If set, this value must be stricly superior to liveSyncDurationCount a value too close from liveSyncDurationCount is likely to cause playback stalls. + */ + liveMaxLatencyDurationCount?: number; + /** + * (default: undefined) + * Alternative parameter to liveMaxLatencyDurationCount, expressed in seconds vs number of segments. + * If defined in the configuration object, liveMaxLatencyDuration will take precedence over the default liveMaxLatencyDurationCount. + * If set, this value must be stricly superior to liveSyncDuration which must be defined as well. + * You can't define this parameter and either liveSyncDurationCount or liveMaxLatencyDurationCount in your configuration object at the same time. + * A value too close from liveSyncDuration is likely to cause playback stalls. + */ + liveMaxLatencyDuration?: number; + /** + * (default: true) + * Enable WebWorker (if available on browser) for TS demuxing/MP4 remuxing, to improve performance and avoid lag/frame drops. + */ + enableWorker?: boolean; + /** + * (default: true) + * Enable to use JavaScript version AES decryption for fallback of WebCrypto API. + */ + enableSoftwareAES?: boolean; + /** + * (default: undefined) + * When set, use this level as the default hls.startLevel. Keep in mind that the startLevel set with the API takes precedence over + * config.startLevel configuration parameter. + */ + startLevel?: number; + /** + * (default: 10000ms for level and manifest) + * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. + * It is up to the application to catch this event and treat it as needed. + */ + manifestLoadingTimeOut?: number; + /** + * (default: 3) + * Max number of load retries. + */ + manifestLoadingMaxRetry?: number; + /** + * (default: 1000 ms) + * Initial delay between XMLHttpRequest error and first load retry (in ms). + * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). + * Prefetch start fragment although media not attached. + */ + manifestLoadingRetryDelay?: number; + /** + * (default: 64000 ms) + * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. + */ + manifestLoadingMaxRetryTimeout?: number; + /** + * (default: 60000ms for fragment) + * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. + * It is up to the application to catch this event and treat it as needed. + */ + levelLoadingTimeOut?: number; + /** + * (default: 3) + * Max number of load retries. + */ + levelLoadingMaxRetry?: number; + /** + * (default: 1000 ms) + * Initial delay between XMLHttpRequest error and first load retry (in ms). + * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). + * Prefetch start fragment although media not attached. + */ + levelLoadingRetryDelay?: number; + /** + * (default: 64000 ms) + * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. + */ + levelLoadingMaxRetryTimeout?: number; + /** + * (default: 60000ms for fragment) + * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. + * It is up to the application to catch this event and treat it as needed. + */ + fragLoadingTimeOut?: number; + /** + * (default: 3) + * Max number of load retries. + */ + fragLoadingMaxRetry?: number; + /** + * (default: 1000 ms) + * Initial delay between XMLHttpRequest error and first load retry (in ms). + * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). + * Prefetch start fragment although media not attached. + */ + fragLoadingRetryDelay?: number; + /** + * (default: 64000 ms) + * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. + */ + fragLoadingMaxRetryDelay?: number; + /** + * (default: false) + * Start prefetching start fragment although media not attached yet. Max number of append retries. + */ + startFragPrefech?: boolean; + /** + * (default: 3) + * Max number of sourceBuffer.appendBuffer() retry upon error. Such error could happen in loop with UHD streams, when internal buffer is full. (Quota Exceeding Error will be triggered). + * In that case we need to wait for the browser to evict some data before being able to append buffer correctly. + */ + appendErrorMaxRetry?: number; + /** + * (default: standard XMLHttpRequest-based URL loader) + * Override standard URL loader by a custom one. Could be useful for P2P or stubbing (testing). + * Use this, if you want to overwrite both the fragment and the playlist loader. + * Note: If fLoader or pLoader are used, they overwrite loader! + */ + loader?: typeof Loader; + /** + * (default: undefined) + * This enables the manipulation of the fragment loader. + * Note: This will overwrite the default loader, as well as your own loader function. + */ + fLoader?: typeof Loader; + /** + * (default: undefined) + * This enables the manipulation of the playlist loader. + * Note: This will overwrite the default loader, as well as your own loader function. + */ + pLoader?: typeof Loader; + /** + * (default: undefined) + * XMLHttpRequest customization callback for default XHR based loader. + * Parameter should be a function with two arguments (xhr: XMLHttpRequest, url: string). + * If xhrSetup is specified, default loader will invoke it before calling xhr.send(). This allows user to easily modify/setup XHR. + */ + xhrSetup?(xhr: XMLHttpRequest, url: string): void; + /** + * (default: undefined) + * Fetch customization callback for Fetch based loader. + * Parameter should be a function with two arguments (context and Request Init Params). + * If fetchSetup is specified and Fetch loader is used, fetchSetup will be triggered to instantiate Request Object. This allows user to easily tweak Fetch loader. + */ + fetchSetup?(context: any, initParams: any): Request; + /** + * (default: internal ABR controller) + * Customized Adaptive Bitrate Streaming Controller. + * Parameter should be a class providing 2 getters, 2 setters and a destroy() method: + * get/set nextAutoLevel: return next auto-quality level/force next auto-quality level that should be returned (currently used for emergency switch down) + * get/set autoLevelCapping: capping/max level value that could be used by ABR Controller + * destroy(): should clean-up all used resources + */ + abrController?: AbrController; + /** + * (default: internal track timeline controller) + * Customized text track syncronization controller. + * Parameter should be a class with a destroy() method: + * destroy() : should clean-up all used resources + */ + timelineController?: TimelineController; + /** + * (default: true) + * whether or not to enable CEA-708 captions + */ + enableCEA708Captions?: boolean; + /** + * (default: English) + * Label for the text track generated for CEA-708 captions track 1. This is how it will appear in the browser's native menu for subtitles and captions. + */ + captionsTextTrack1Label?: string; + /** + * (default: en) + * RFC 3066 language code for the text track generated for CEA-708 captions track 1. + */ + captionsTextTrack1LanguagedCode?: string; + /** + * (default: Spanish) + * Label for the text track generated for CEA-708 captions track 2. This is how it will appear in the browser's native menu for subtitles and captions. + */ + captionsTextTrack2Label?: string; + /** + * (default: es) + * RFC 3066 language code for the text track generated for CEA-708 captions track 2. + */ + captionsTextTrack2LanguageCode?: string; + /** + * (default: false) + * If a segment's video track is shorter than its audio track by > min(maxSeekHole, maxBufferHole), extend the final video frame's duration to match the audio track's duration. + * This helps playback continue in certain cases that might otherwise get stuck. + */ + stretchShortVideoTrack?: boolean; + /** + * (default: true) + * Whether or not to force having a key frame in the first AVC sample after a discontinuity. + * If set to true, after a discontinuity, the AVC samples without any key frame will be dropped until finding one that contains a key frame. + * If set to false, all AVC samples will be kept, which can help avoid holes in the stream. Setting this parameter to false can also generate decoding weirdness when switching level or seeking. + */ + forceKeyFrameOnDiscontinuity?: boolean; + /** + * (default: 5.0) + * Fast bitrate Exponential moving average half-life, used to compute average bitrate for Live streams. + * Half of the estimate is based on the last abrEwmaFastLive seconds of sample history. Each of the sample is weighted by the fragment loading duration. + * parameter should be a float greater than 0 + */ + abrEwmaFastLive?: number; + /** + * (default: 9.0) + * Slow bitrate Exponential moving average half-life, used to compute average bitrate for Live streams. + * Half of the estimate is based on the last abrEwmaSlowLive seconds of sample history. Each of the sample is weighted by the fragment loading duration. + * parameter should be a float greater than abrEwmaFastLive + */ + abrEwmaSlowLive?: number; + /** + * (default: 4.0) + * Fast bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams. + * Half of the estimate is based on the last abrEwmaFastVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration. + * parameter should be a float greater than 0 + */ + abrEwmaFastVod?: number; + /** + * (default: 15.0) + * Slow bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams. + * Half of the estimate is based on the last abrEwmaSlowVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration. + * parameter should be a float greater than abrEwmaFastVoD + */ + abrEwmaSlowVod?: number; + /** + * (default: 500000) + * Default bandwidth estimate in bits/second prior to collecting fragment bandwidth samples. + * parameter should be a float + */ + abrEwmaDefaultEstimate?: number; + /** + * (default: 0.8) + * Scale factor to be applied against measured bandwidth average, to determine whether we can stay on current or lower quality level. + * If abrBandWidthFactor * bandwidth average < level.bitrate then ABR can switch to that level providing that it is equal or less than current level. + */ + abrBandWidthFactor?: number; + /** + * (default: 0.7) + * Scale factor to be applied against measured bandwidth average, to determine whether we can switch up to a higher quality level. + * If abrBandWidthUpFactor * bandwidth average < level.bitrate then ABR can switch up to that quality level. + */ + abrBandWidthUpFactor?: number; + /** + * (default: false) + * max bitrate used in ABR by avg measured bitrate i.e. if bitrate signaled in variant manifest for a given level is 2Mb/s but average bitrate measured on this level is 2.5Mb/s, + * then if config value is set to true, ABR will use 2.5 Mb/s for this quality level. + */ + abrMaxWithRealBitrate?: boolean; + /** + * (default: 0) + * Return the capping/min bandwidth value that could be used by automatic level selection algorithm. + * Useful when browser or tab of the browser is not in the focus and bandwidth drops + */ + minAutoBitrate?: number; + } + + /** + * a Level object represents a given quality level and contains quality level related info + */ + interface Level { + /** + * level url. might contain sever items if failover/redundant streams are found in the manifest + */ + url: string[]; + /** + * level bitrate + */ + bitrate: number; + /** + * level name + */ + name: string; + /** + * used codecs + */ + codecs: string; + /** + * video width + */ + width: number; + /** + * video height + */ + height: number; + /** + * level details + */ + details: LevelDetails; + } + + /** + * a LevelDetails object contains level details retrieved after level playlist parsing + */ + interface LevelDetails { + /** + * protocol version + */ + version: number; + /** + * playlist type + */ + type: string; + /** + * start sequence number + */ + startSN: number; + /** + * end sequence number + */ + endSN: number; + /** + * level total duration + */ + totalduration: number; + /** + * level fragment target duration + */ + targetduration: number; + /** + * average fragment duration + */ + averagetargetduration: number; + /** + * array of fragments info + */ + fragments: Fragment[]; + /** + * is this level a live playlist or not? + */ + live: boolean; + } + + /** + * the Fragment object contains fragment related info + */ + interface Fragment { + /** + * fragment duration + */ + duration: number; + /** + * fragment level identifier + */ + level: number; + /** + * fragment sequence number + */ + sn: number; + /** + * fragment start offset + */ + start: number; + /** + * fragment url + */ + url: string; + /** + * stream start date and time + */ + programDateTime: Date; + /** + * continuity count + */ + cc: number; + /** + * list of tags associated with the fragment + */ + tagList: string[][]; + /** + * fragment title + */ + title: string; + } + + interface Data { + /** + * videoElement + */ + video?: HTMLVideoElement; + /** + * media source + */ + mediaSource?: string; + /** + * manifest url + */ + url?: string; + /** + * available quality levels + */ + levels?: number[]; + /** + * available audio tracks + */ + audioTracks?: AudioTrack[]; + /** + * XMLHttp request stats + */ + stats?: HlsStats; + /** + * index of first quality level appearing in Manifest + */ + firstLevel?: number; + /** + * id of updated level + */ + level?: number; + /** + * id of loaded level + */ + levelId?: number; + /** + * ErrorDetails type + */ + details?: string; + /** + * PTS drift observed when parsing last fragment + */ + drift?: number; + /** + * fragment object with frag.loaded=stats.loaded + */ + frag?: Fragment; + /** + * fragment payload + */ + payload?: any; // TODO: what is the payload? + /** + * id of level or demuxer + */ + id?: number; + /** + * moof MP4 box + */ + moof?: any; // TODO: whats is the moof? + /** + * mdat MP4 box + */ + mdat?: any; // TODO: what is mdat? + /** + * PTS of first sample + */ + startPTS?: number; + /** + * PTS of last sample + */ + endPTS?: number; + /** + * DTS of first sample + */ + startDTS?: number; + /** + * DTS of last sample + */ + endDTS?: number; + /** + * stream type (audio or video) + */ + type?: string; + /** + * number of samples + */ + nb?: number; + /** + * number of dropped frames in last monitoring period + */ + currentDropped?: number; + /** + * number of decoded frames in last monitoring period + */ + currentDecode?: number; + /** + * total dropped frames on this video element + */ + totalDropped?: number; + /** + * level has to much dropped frame will be restricted + */ + droppedLevel?: number; + /** + * is error fatal or not. + * if error is not fatal, hls.js will try to recover it + * if error is fatal, an action is required to (try to) recover it + */ + fatal?: boolean; + } + + /** + * (default: internal ABR controller) + * Customized Adaptive Bitrate Streaming Controller. + */ + interface AbrController { + /** + * get: capping/max level value that could be used by ABR Controller + * set: capping/max level value that could be used by ABR Controller + */ + autoLevelCapping: number; + /** + * accumulated handled events + */ + handledEvents: string[]; + /** + * current hls instance + */ + hls: Hls; + /** + * last fragments corresponding level + */ + lastLoadedFragLevel: number; + /** + * get: next auto-quality levele/force next auto-quality level that should be returned + * set: next auto-quality levele/force next auto-quality level that should be returned + * - currently used for emergency switch down + */ + nextAutoLevel: number; + useGenericHandler: boolean; + } + + /** + * Customized text track syncronization controller. + */ + interface TimelineController { + /**d + * clean-up all used resources + */ + destory(): void; + } + + interface LoaderResponse { + url: string; + data: string | ArrayBuffer; + } + + interface LoaderStats { + /** + * performance.now() just after load() has been called + */ + trequest: number; + /** + * performance.now() of first received byte + */ + tfirst: number; + /** + * performance.now() on load complete + */ + tload: number; + /** + * number of loaded bytes + */ + loaded: number; + /** + * download bandwitdh in bit/s + */ + bw: number; + /** + * total nb of bytes + */ + total: number; + } + + interface LoaderError { + /** + * error code + */ + code: number; + /** + * error description + */ + text: string; + } + + interface HlsStats { + /** + * performance.now() just after load() has been called + */ + trequest: number; + /** + * performance.now() of first received byte + */ + tfirst: number; + /** + * performance.now() on load complete + */ + tload: number; + mtime: number; + tbuffered?: number; + length?: number; + } + + interface LoaderContext { + /** + * target URL + */ + url: string; + /** + * loader response type (arraybuffer or default response type for playlist) + */ + responseType: string; + /** + * start byte range offset + */ + rangeStart?: number; + /** + * end byte range offset + */ + rangeEnd?: number; + /** + * true if onProgress should report partial chunk of loaded content + */ + progressData?: boolean; + /** + * fragment object + */ + frag: Fragment; + /** + * request type + * - level, manifest + */ + type: string; + /** + * level id + */ + level: number; + } + + interface LoaderConfig { + /** + * Max number of load retries + */ + maxRetry: number; + /** + * Timeout after which `onTimeOut` callback will be triggered (if loading is still not finished after that delay) + */ + timeout: number; + /** + * Delay between an I/O error and following connection retry (ms). This to avoid spamming the server + */ + retryDelay: number; + /** + * max connection retry delay (ms) + */ + maxRetryDelay: number; + } + + interface LoaderCallbacks { + onSuccess(response: LoaderResponse, stats: LoaderStats, context: LoaderContext): void; + onProgress(stats: LoaderStats, context: LoaderContext, data: string | ArrayBuffer): void; + onError(error: LoaderError, context: LoaderContext): void; + onTimeout(stats: LoaderStats, context: LoaderContext): void; + } +} + +declare class Hls { + /** + * Constructor. Can be provided an HlsConfig object as default properties and or overrides + */ + constructor(config?: Hls.OptionalConfig) + /** + * return array of available quality levels + */ + levels: Hls.Level[]; + /** + * get: return current playback quality level + * set: trigger an immediate quality level switch to new quality level + * this will pause the video if it was playing, flush the whole buffer, + * and fetch fragment matching with current position and requested quality level + * then resume the video if needed once fetched fragment will have been buffered + * + * set to -1 for automatic level selection + */ + currentLevel: number; + /** + * capping/max level (index of level) that could be used by ABR Controller. Defaults to -1 + * which means no limit + * set: max level value that could be used by the ABR Controller + */ + autoLevelCapping: number; + /** + * return start level index (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) + * + * default valus is hls.firstLevel + */ + startLevel: number; /** * (default: true) * if set to true, start level playlist and first fragments will be loaded automatically, after triggering of Hls.Events.MANIFEST_PARSED event @@ -474,1347 +1710,111 @@ declare namespace Hls { */ autoStartLoad: boolean; /** - * (default -1) - * if set to -1, playback will start from initialTime=0 for VoD and according to liveSyncDuration/liveSyncDurationCount config params for Live - * otherwise, playback will start from predefined value. (unless stated otherwise in autoStartLoad=false mode : in that case startPosition can be overrided using hls.startLoad(startPosition)). + * get: Return the bound videoElement from the hls instance */ - startPosition: number; + media: HTMLVideoElement; /** - * (default: false) - * if set to true, the adaptive algorithm with limit levels usable in auto-quality by the HTML video element dimensions (width and height) - * if set to false, levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration. + * hls.js config */ - capLevelToPlayerSize: boolean; + config: Hls.Config; /** - * (default: false) - * setting config.debug = true; will turn on debug logs on JS console. - * a logger object could also be provided for custom logging: config.debug = customLogger; - */ - debug: boolean; - /** - * (default: undefined) - * if audio codec is not signaled in variant manifest, or if only a stream manifest is provided, hls.js tries to guess audio codec by parsing audio sampling rate in ADTS header. - * If sampling rate is less or equal than 22050 Hz, then hls.js assumes it is HE-AAC, otherwise it assumes it is AAC-LC. - * This could result in bad guess, leading to audio decode error, ending up in media error. - * It is possible to hint default audiocodec to hls.js by configuring this value as below: - * mp4a.40.2 (AAC-LC) or - * mp4a.40.5 (HE-AAC) or - * undefined (guess based on sampling rate) - */ - defaultAudioCodec: string; - /** - * (default: 1) - * number of segments needed to start a playback of Live stream. - */ - initialLiveManifestSize: number; - /** - * (default: 30 seconds) - * Maximum buffer length in seconds. If buffer length is/become less than this value, a new fragment will be loaded. - * This is the guaranteed buffer length hls.js will try to reach, regardless of maxBufferSize. - */ - maxBufferLength: number; - /** - * (default 600s) - * Maximum buffer length in seconds. Hls.js will never exceed this value, even if maxBufferSize is not reached yet. - * hls.js tries to buffer up to a maximum number of bytes (60 MB by default) rather than to buffer up to a maximum nb of seconds. - * This is to mimic the browser behaviour (the buffer eviction algorithm is starting after the browser detects that video buffer size reaches a limit in bytes) - * maxBufferLength is the minimum guaranteed buffer length that hls.js will try to achieve, even if that value exceeds the amount of bytes 60 MB of memory. - * maxMaxBufferLength acts as a capping value, as if bitrate is really low, you could need more than one hour of buffer to fill 60 MB. - */ - maxMaxBufferLength: number; - /** - * (default: 60 MB) - * 'Minimum' maximum buffer size in bytes. If buffer size upfront is bigger than this value, no fragment will be loaded - */ - maxBufferSize: number; - /** - * (default: 0.5 seconds) - * 'Maximum' inter-fragment buffer hole tolerance that hls.js can cope with when searching for the next fragment to load. When switching between quality level, - * fragments might not be perfectly aligned. - * This could result in small overlapping or hole in media buffer. This tolerance factor helps cope with this. - */ - maxBufferHole: number; - /** - * (default: 4s) + * get: return next playback quality level (playback quality level for next buffered fragment) + * return -1 if next fragment not buffered yet + * set: trigger a quality level switch for next fragment + * this could eventually flush already buffered next fragment * - * ABR algorithm will always try to choose a quality level that should avoid rebuffering. In case no quality level with this criteria can - * be found (lets say for example that buffer length is 1s, but fetching a fragment at lowest quality is predicted to take around 2s ... - * ie we can forecast around 1s of rebuffering ...) then ABR algorithm will try to find a level that should guarantee less than - * maxStarvationDelay of buffering. + * set to -1 for automatic level selection */ - maxStarvationDelay: number; + nextLevel: number; /** - * (default: 2s) - * In case playback is stalled, and a buffered range is available upfront, less than maxSeekHole seconds from current media position, - * hls.js will jump over this buffer hole to reach the beginning of this following buffered range. - * maxSeekHole allows to configure this jumpable threshold. + * get: return last loaded fragment quality level + * set: quality level for next loaded fragment + * set to -1 for automatic level selection */ - maxSeekHole: number; + loadLevel: number; /** - * (default: 0.5s) - * media element is expected to play and if currentTime has not moved for more than lowBufferWatchdogPeriod and if there are less than maxBufferHole seconds buffered upfront, - * hls.js will try to nudge playhead to recover playback + * get: return quality level that will be used to load next fragment + * set: force quality level for next loaded fragment + * quality level will be forced only for that fragment + * after a fragment at this quality level has been loaded, hls.loadLevel will prevail */ - lowBufferWatchdogPeriod: number; + nextLoadLevel: number; /** - * (default: 3s) - * if media element is expected to play and if currentTime has not moved for more than highBufferWatchdogPeriod and if there are more than maxBufferHole seconds buffered upfront, - * hls.js will try to nudge playhead to recover playback + * first level index (index of first level appearing in Manifest. it is usually defined as start level hint for player) */ - highBufferWatchdogPeriod: number; + firstLevel: number; /** - * (default: 0.1s) - * In case playback continues to stall after first playhead nudging, currentTime will be nudged evenmore following nudgeOffset to try to restore playback. - * media.currentTime += (nb nudge retry -1)*nudgeOffset + * array of audio tracks exposed in manifest */ - nudgeOffset: number; + audioTracks: AudioTrack[]; /** - * (default: 3s) - * In case playback continues to stall after first playhead nudging, currentTime will be nudged evenmore following nudgeOffset to try to restore playback. - * media.currentTime += (nb nudge retry -1)*nudgeOffset + * get: returns audio track id + * set: sets audio track id (returned by) */ - nudgeMaxRetry: number; + audioTrack: number; /** - * (default 0.2s) - * This tolerance factor is used during fragment lookup. - * Instead of checking whether buffered.end is located within [start, end] range, frag lookup will be done by checking within [start-maxFragLookUpTolerance, end-maxFragLookUpTolerance] range. - * This tolerance factor is used to cope with situations like: - * buffered.end = 9.991 - * frag[0] : [0,10] - * frag[1] : [10,20] - * buffered.end is within frag[0] range, but as we are close to frag[1], frag[1] should be choosen instead - * If maxFragLookUpTolerance = 0.2, this lookup will be adjusted to - * frag[0] : [-0.2,9.8] - * frag[1] : [9.8,19.8] - * This time, buffered.end is within frag[1] range, and frag[1] will be the next fragment to be loaded, as expected + * position of live sync point (ie edge of live position minus safety delay defined by hls.config.liveSyncDuration) */ - maxLoadingDelay: number; + liveSyncPosition: number; /** - * (default 4s) + * calling this method will: + * bind videoElement and hls instances + * create MediaSource and set it as video source + * once MediaSource object is successfully created, MEDIA_ATTACHED event will be fired + */ + attachMedia(videoElement: HTMLVideoElement): void; + /** + * calling this method will: + * unbind VideoElement from hls instance + * signal the end of the stream on MediaSource + * reset video source ( video.src = '' ) + */ + detachMedia(): void; + /** + * tell whether auto level selection is enabled or not + */ + autoLevelEnabled(enabled: boolean): boolean; + /** + * loads provided url as media source + */ + loadSource(source: string): void; + /** + * by default, hls.js will automatically start loading quality level playlists, and fragments after Hls.Events.MANIFEST_PARSED event has been triggered (and video element has been attached) + * however if config.autoStartLoad is set to false, hls.startLoad() needs to be called to manually start playlist and fragments loading * - * 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 ) + * start/restart playlist/fragment loading. this is only effective if MANIFEST_PARSED event has been triggered and video element has been attached to hls object + * startPosition is the initial position in the playlist + * ff startPosition is not set to -1, it allows to override default startPosition to the one you want + * (it will bypass hls.config.liveSync* config params for Live for example, so that user can start playback from whatever position) */ - maxFragLookUpTolerance: number; + startLoad(startPosition?: number): void; /** - * (default: 3) - * edge of live delay, expressed in multiple of EXT-X-TARGETDURATION. if set to 3, playback will start from fragment N-3, N being the last fragment of the live playlist. - * Decreasing this value is likely to cause playback stalls. + * stop playlist/fragment loading. could be resumed later on by calling hls.startLoad() */ - liveSyncDurationCount: number; + stopLoad(): void; /** - * (default: undefined) - * Alternative parameter to liveSyncDurationCount, expressed in seconds vs number of segments. - * If defined in the configuration object, liveSyncDuration will take precedence over the default liveSyncDurationCount. - * You can't define this parameter and either liveSyncDurationCount or liveMaxLatencyDurationCount in your configuration object at the same time. - * A value too low (inferior to ~3 segment durations) is likely to cause playback stalls. + * should be invoked to recover media error. */ - liveSyncDuration: number; + recoverMediaError(): void; /** - * (default: Infinity) - * maximum delay allowed from edge of live, expressed in multiple of EXT-X-TARGETDURATION. - * If set to 10, the player will seek back to liveSyncDurationCount whenever the next fragment to be loaded is older than N-10, N being the last fragment of the live playlist. - * If set, this value must be stricly superior to liveSyncDurationCount a value too close from liveSyncDurationCount is likely to cause playback stalls. + * if media error are still raised after calling hls.recoverMediaError(), calling this method, could be useful to workaround audio codec mismatch. + * the workflow should be: + * on First Media Error : call hls.recoverMediaError() + * if another Media Error is raised 'quickly' after this first Media Error : first call hls.swapAudioCodec(), then call hls.recoverMediaError() */ - liveMaxLatencyDurationCount: number; + swapAudioCodec(): void; /** - * (default: undefined) - * Alternative parameter to liveMaxLatencyDurationCount, expressed in seconds vs number of segments. - * If defined in the configuration object, liveMaxLatencyDuration will take precedence over the default liveMaxLatencyDurationCount. - * If set, this value must be stricly superior to liveSyncDuration which must be defined as well. - * You can't define this parameter and either liveSyncDurationCount or liveMaxLatencyDurationCount in your configuration object at the same time. - * A value too close from liveSyncDuration is likely to cause playback stalls. + * should be called to free used resources and destroy hls context */ - liveMaxLatencyDuration: number; + destroy(): void; /** - * (default: true) - * Enable WebWorker (if available on browser) for TS demuxing/MP4 remuxing, to improve performance and avoid lag/frame drops. + * hls.js event listener */ - enableWorker: boolean; + on(event: string, callback: (event: string, data: Hls.Data) => void): void; /** - * (default: true) - * Enable to use JavaScript version AES decryption for fallback of WebCrypto API. + * remove hls.js event listener */ - enableSoftwareAES: boolean; - /** - * (default: undefined) - * When set, use this level as the default hls.startLevel. Keep in mind that the startLevel set with the API takes precedence over - * config.startLevel configuration parameter. - */ - startLevel: number; - /** - * (default: 10000ms for level and manifest) - * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. - * It is up to the application to catch this event and treat it as needed. - */ - manifestLoadingTimeOut: number; - /** - * (default: 3) - * Max number of load retries. - */ - manifestLoadingMaxRetry: number; - /** - * (default: 1000 ms) - * Initial delay between XMLHttpRequest error and first load retry (in ms). - * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). - * Prefetch start fragment although media not attached. - */ - manifestLoadingRetryDelay: number; - /** - * (default: 64000 ms) - * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. - */ - manifestLoadingMaxRetryTimeout: number; - /** - * (default: 60000ms for fragment) - * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. - * It is up to the application to catch this event and treat it as needed. - */ - levelLoadingTimeOut: number; - /** - * (default: 3) - * Max number of load retries. - */ - levelLoadingMaxRetry: number; - /** - * (default: 1000 ms) - * Initial delay between XMLHttpRequest error and first load retry (in ms). - * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). - * Prefetch start fragment although media not attached. - */ - levelLoadingRetryDelay: number; - /** - * (default: 64000 ms) - * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. - */ - levelLoadingMaxRetryTimeout: number; - /** - * (default: 60000ms for fragment) - * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. - * It is up to the application to catch this event and treat it as needed. - */ - fragLoadingTimeOut: number; - /** - * (default: 3) - * Max number of load retries. - */ - fragLoadingMaxRetry: number; - /** - * (default: 1000 ms) - * Initial delay between XMLHttpRequest error and first load retry (in ms). - * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). - * Prefetch start fragment although media not attached. - */ - fragLoadingRetryDelay: number; - /** - * (default: 64000 ms) - * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. - */ - fragLoadingMaxRetryDelay: number; - /** - * (default: false) - * Start prefetching start fragment although media not attached yet. Max number of append retries. - */ - startFragPrefech: boolean; - /** - * (default: 3) - * Max number of sourceBuffer.appendBuffer() retry upon error. Such error could happen in loop with UHD streams, when internal buffer is full. (Quota Exceeding Error will be triggered). - * In that case we need to wait for the browser to evict some data before being able to append buffer correctly. - */ - appendErrorMaxRetry: number; - /** - * (default: standard XMLHttpRequest-based URL loader) - * Override standard URL loader by a custom one. Could be useful for P2P or stubbing (testing). - * Use this, if you want to overwrite both the fragment and the playlist loader. - * Note: If fLoader or pLoader are used, they overwrite loader! - */ - loader: typeof Loader; - /** - * (default: undefined) - * This enables the manipulation of the fragment loader. - * Note: This will overwrite the default loader, as well as your own loader function. - */ - fLoader?: typeof Loader; - /** - * (default: undefined) - * This enables the manipulation of the playlist loader. - * Note: This will overwrite the default loader, as well as your own loader function. - */ - pLoader?: typeof Loader; - /** - * (default: undefined) - * XMLHttpRequest customization callback for default XHR based loader. - * Parameter should be a function with two arguments (xhr: XMLHttpRequest, url: string). - * If xhrSetup is specified, default loader will invoke it before calling xhr.send(). This allows user to easily modify/setup XHR. - */ - xhrSetup?(xhr: XMLHttpRequest, url: string): void; - /** - * (default: undefined) - * Fetch customization callback for Fetch based loader. - * Parameter should be a function with two arguments (context and Request Init Params). - * If fetchSetup is specified and Fetch loader is used, fetchSetup will be triggered to instantiate Request Object. This allows user to easily tweak Fetch loader. - */ - fetchSetup?(context: any, initParams: any): Request; - /** - * (default: internal ABR controller) - * Customized Adaptive Bitrate Streaming Controller. - * Parameter should be a class providing 2 getters, 2 setters and a destroy() method: - * get/set nextAutoLevel: return next auto-quality level/force next auto-quality level that should be returned (currently used for emergency switch down) - * get/set autoLevelCapping: capping/max level value that could be used by ABR Controller - * destroy(): should clean-up all used resources - */ - abrController: AbrController; - /** - * (default: internal track timeline controller) - * Customized text track syncronization controller. - * Parameter should be a class with a destroy() method: - * destroy() : should clean-up all used resources - */ - timelineController: TimelineController; - /** - * (default: true) - * whether or not to enable CEA-708 captions - */ - enableCEA708Captions: boolean; - /** - * (default: English) - * Label for the text track generated for CEA-708 captions track 1. This is how it will appear in the browser's native menu for subtitles and captions. - */ - captionsTextTrack1Label: string; - /** - * (default: en) - * RFC 3066 language code for the text track generated for CEA-708 captions track 1. - */ - captionsTextTrack1LanguagedCode: string; - /** - * (default: Spanish) - * Label for the text track generated for CEA-708 captions track 2. This is how it will appear in the browser's native menu for subtitles and captions. - */ - captionsTextTrack2Label: string; - /** - * (default: es) - * RFC 3066 language code for the text track generated for CEA-708 captions track 2. - */ - captionsTextTrack2LanguageCode: string; - /** - * (default: false) - * If a segment's video track is shorter than its audio track by > min(maxSeekHole, maxBufferHole), extend the final video frame's duration to match the audio track's duration. - * This helps playback continue in certain cases that might otherwise get stuck. - */ - stretchShortVideoTrack: boolean; - /** - * (default: true) - * Whether or not to force having a key frame in the first AVC sample after a discontinuity. - * If set to true, after a discontinuity, the AVC samples without any key frame will be dropped until finding one that contains a key frame. - * If set to false, all AVC samples will be kept, which can help avoid holes in the stream. Setting this parameter to false can also generate decoding weirdness when switching level or seeking. - */ - forceKeyFrameOnDiscontinuity: boolean; - /** - * (default: 5.0) - * Fast bitrate Exponential moving average half-life, used to compute average bitrate for Live streams. - * Half of the estimate is based on the last abrEwmaFastLive seconds of sample history. Each of the sample is weighted by the fragment loading duration. - * parameter should be a float greater than 0 - */ - abrEwmaFastLive: number; - /** - * (default: 9.0) - * Slow bitrate Exponential moving average half-life, used to compute average bitrate for Live streams. - * Half of the estimate is based on the last abrEwmaSlowLive seconds of sample history. Each of the sample is weighted by the fragment loading duration. - * parameter should be a float greater than abrEwmaFastLive - */ - abrEwmaSlowLive: number; - /** - * (default: 4.0) - * Fast bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams. - * Half of the estimate is based on the last abrEwmaFastVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration. - * parameter should be a float greater than 0 - */ - abrEwmaFastVod: number; - /** - * (default: 15.0) - * Slow bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams. - * Half of the estimate is based on the last abrEwmaSlowVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration. - * parameter should be a float greater than abrEwmaFastVoD - */ - abrEwmaSlowVod: number; - /** - * (default: 500000) - * Default bandwidth estimate in bits/second prior to collecting fragment bandwidth samples. - * parameter should be a float - */ - abrEwmaDefaultEstimate: number; - /** - * (default: 0.8) - * Scale factor to be applied against measured bandwidth average, to determine whether we can stay on current or lower quality level. - * If abrBandWidthFactor * bandwidth average < level.bitrate then ABR can switch to that level providing that it is equal or less than current level. - */ - abrBandWidthFactor: number; - /** - * (default: 0.7) - * Scale factor to be applied against measured bandwidth average, to determine whether we can switch up to a higher quality level. - * If abrBandWidthUpFactor * bandwidth average < level.bitrate then ABR can switch up to that quality level. - */ - abrBandWidthUpFactor: number; - /** - * (default: false) - * max bitrate used in ABR by avg measured bitrate i.e. if bitrate signaled in variant manifest for a given level is 2Mb/s but average bitrate measured on this level is 2.5Mb/s, - * then if config value is set to true, ABR will use 2.5 Mb/s for this quality level. - */ - abrMaxWithRealBitrate: boolean; - /** - * (default: 0) - * Return the capping/min bandwidth value that could be used by automatic level selection algorithm. - * Useful when browser or tab of the browser is not in the focus and bandwidth drops - */ - minAutoBitrate: number; - } - - interface OptionalConfig { - /** - * (default: true) - * if set to true, start level playlist and first fragments will be loaded automatically, after triggering of Hls.Events.MANIFEST_PARSED event - * if set to false, an explicit API call (hls.startLoad(startPosition=-1)) will be needed to start quality level/fragment loading. - */ - autoStartLoad?: boolean; - /** - * (default -1) - * if set to -1, playback will start from initialTime=0 for VoD and according to liveSyncDuration/liveSyncDurationCount config params for Live - * otherwise, playback will start from predefined value. (unless stated otherwise in autoStartLoad=false mode : in that case startPosition can be overrided using hls.startLoad(startPosition)). - */ - startPosition?: number; - /** - * (default: false) - * if set to true, the adaptive algorithm with limit levels usable in auto-quality by the HTML video element dimensions (width and height) - * if set to false, levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration. - */ - capLevelToPlayerSize?: boolean; - /** - * (default: false) - * setting config.debug = true; will turn on debug logs on JS console. - * a logger object could also be provided for custom logging: config.debug = customLogger; - */ - debug?: boolean; - /** - * (default: undefined) - * if audio codec is not signaled in variant manifest, or if only a stream manifest is provided, hls.js tries to guess audio codec by parsing audio sampling rate in ADTS header. - * If sampling rate is less or equal than 22050 Hz, then hls.js assumes it is HE-AAC, otherwise it assumes it is AAC-LC. - * This could result in bad guess, leading to audio decode error, ending up in media error. - * It is possible to hint default audiocodec to hls.js by configuring this value as below: - * mp4a.40.2 (AAC-LC) or - * mp4a.40.5 (HE-AAC) or - * undefined (guess based on sampling rate) - */ - defaultAudioCodec?: string; - /** - * (default: 1) - * number of segments needed to start a playback of Live stream. - */ - initialLiveManifestSize?: number; - /** - * (default: 30 seconds) - * Maximum buffer length in seconds. If buffer length is/become less than this value, a new fragment will be loaded. - * This is the guaranteed buffer length hls.js will try to reach, regardless of maxBufferSize. - */ - maxBufferLength?: number; - /** - * (default 600s) - * Maximum buffer length in seconds. Hls.js will never exceed this value, even if maxBufferSize is not reached yet. - * hls.js tries to buffer up to a maximum number of bytes (60 MB by default) rather than to buffer up to a maximum nb of seconds. - * This is to mimic the browser behaviour (the buffer eviction algorithm is starting after the browser detects that video buffer size reaches a limit in bytes) - * maxBufferLength is the minimum guaranteed buffer length that hls.js will try to achieve, even if that value exceeds the amount of bytes 60 MB of memory. - * maxMaxBufferLength acts as a capping value, as if bitrate is really low, you could need more than one hour of buffer to fill 60 MB. - */ - maxMaxBufferLength?: number; - /** - * (default: 60 MB) - * 'Minimum' maximum buffer size in bytes. If buffer size upfront is bigger than this value, no fragment will be loaded - */ - maxBufferSize?: number; - /** - * (default: 0.5 seconds) - * 'Maximum' inter-fragment buffer hole tolerance that hls.js can cope with when searching for the next fragment to load. When switching between quality level, - * fragments might not be perfectly aligned. - * This could result in small overlapping or hole in media buffer. This tolerance factor helps cope with this. - */ - maxBufferHole?: number; - /** - * (default: 4s) - * - * ABR algorithm will always try to choose a quality level that should avoid rebuffering. In case no quality level with this criteria can - * be found (lets say for example that buffer length is 1s, but fetching a fragment at lowest quality is predicted to take around 2s ... - * ie we can forecast around 1s of rebuffering ...) then ABR algorithm will try to find a level that should guarantee less than - * maxStarvationDelay of buffering. - */ - maxStarvationDelay?: number; - /** - * (default: 2s) - * In case playback is stalled, and a buffered range is available upfront, less than maxSeekHole seconds from current media position, - * hls.js will jump over this buffer hole to reach the beginning of this following buffered range. - * maxSeekHole allows to configure this jumpable threshold. - */ - maxSeekHole?: number; - /** - * (default: 0.5s) - * media element is expected to play and if currentTime has not moved for more than lowBufferWatchdogPeriod and if there are less than maxBufferHole seconds buffered upfront, - * hls.js will try to nudge playhead to recover playback - */ - lowBufferWatchdogPeriod?: number; - /** - * (default: 3s) - * if media element is expected to play and if currentTime has not moved for more than highBufferWatchdogPeriod and if there are more than maxBufferHole seconds buffered upfront, - * hls.js will try to nudge playhead to recover playback - */ - highBufferWatchdogPeriod?: number; - /** - * (default: 0.1s) - * In case playback continues to stall after first playhead nudging, currentTime will be nudged evenmore following nudgeOffset to try to restore playback. - * media.currentTime += (nb nudge retry -1)*nudgeOffset - */ - nudgeOffset?: number; - /** - * (default: 3s) - * In case playback continues to stall after first playhead nudging, currentTime will be nudged evenmore following nudgeOffset to try to restore playback. - * media.currentTime += (nb nudge retry -1)*nudgeOffset - */ - nudgeMaxRetry?: number; - /** - * (default 0.2s) - * This tolerance factor is used during fragment lookup. - * Instead of checking whether buffered.end is located within [start, end] range, frag lookup will be done by checking within [start-maxFragLookUpTolerance, end-maxFragLookUpTolerance] range. - * This tolerance factor is used to cope with situations like: - * buffered.end = 9.991 - * frag[0] : [0,10] - * frag[1] : [10,20] - * buffered.end is within frag[0] range, but as we are close to frag[1], frag[1] should be choosen instead - * If maxFragLookUpTolerance = 0.2, this lookup will be adjusted to - * frag[0] : [-0.2,9.8] - * frag[1] : [9.8,19.8] - * This time, buffered.end is within frag[1] range, and frag[1] will be the next fragment to be loaded, as expected - */ - maxLoadingDelay?: number; - /** - * (default 4s) - * - * 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 ) - */ - maxFragLookUpTolerance?: number; - /** - * (default: 3) - * edge of live delay, expressed in multiple of EXT-X-TARGETDURATION. if set to 3, playback will start from fragment N-3, N being the last fragment of the live playlist. - * Decreasing this value is likely to cause playback stalls. - */ - liveSyncDurationCount?: number; - /** - * (default: undefined) - * Alternative parameter to liveSyncDurationCount, expressed in seconds vs number of segments. - * If defined in the configuration object, liveSyncDuration will take precedence over the default liveSyncDurationCount. - * You can't define this parameter and either liveSyncDurationCount or liveMaxLatencyDurationCount in your configuration object at the same time. - * A value too low (inferior to ~3 segment durations) is likely to cause playback stalls. - */ - liveSyncDuration?: number; - /** - * (default: Infinity) - * maximum delay allowed from edge of live, expressed in multiple of EXT-X-TARGETDURATION. - * If set to 10, the player will seek back to liveSyncDurationCount whenever the next fragment to be loaded is older than N-10, N being the last fragment of the live playlist. - * If set, this value must be stricly superior to liveSyncDurationCount a value too close from liveSyncDurationCount is likely to cause playback stalls. - */ - liveMaxLatencyDurationCount?: number; - /** - * (default: undefined) - * Alternative parameter to liveMaxLatencyDurationCount, expressed in seconds vs number of segments. - * If defined in the configuration object, liveMaxLatencyDuration will take precedence over the default liveMaxLatencyDurationCount. - * If set, this value must be stricly superior to liveSyncDuration which must be defined as well. - * You can't define this parameter and either liveSyncDurationCount or liveMaxLatencyDurationCount in your configuration object at the same time. - * A value too close from liveSyncDuration is likely to cause playback stalls. - */ - liveMaxLatencyDuration?: number; - /** - * (default: true) - * Enable WebWorker (if available on browser) for TS demuxing/MP4 remuxing, to improve performance and avoid lag/frame drops. - */ - enableWorker?: boolean; - /** - * (default: true) - * Enable to use JavaScript version AES decryption for fallback of WebCrypto API. - */ - enableSoftwareAES?: boolean; - /** - * (default: undefined) - * When set, use this level as the default hls.startLevel. Keep in mind that the startLevel set with the API takes precedence over - * config.startLevel configuration parameter. - */ - startLevel?: number; - /** - * (default: 10000ms for level and manifest) - * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. - * It is up to the application to catch this event and treat it as needed. - */ - manifestLoadingTimeOut?: number; - /** - * (default: 3) - * Max number of load retries. - */ - manifestLoadingMaxRetry?: number; - /** - * (default: 1000 ms) - * Initial delay between XMLHttpRequest error and first load retry (in ms). - * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). - * Prefetch start fragment although media not attached. - */ - manifestLoadingRetryDelay?: number; - /** - * (default: 64000 ms) - * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. - */ - manifestLoadingMaxRetryTimeout?: number; - /** - * (default: 60000ms for fragment) - * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. - * It is up to the application to catch this event and treat it as needed. - */ - levelLoadingTimeOut?: number; - /** - * (default: 3) - * Max number of load retries. - */ - levelLoadingMaxRetry?: number; - /** - * (default: 1000 ms) - * Initial delay between XMLHttpRequest error and first load retry (in ms). - * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). - * Prefetch start fragment although media not attached. - */ - levelLoadingRetryDelay?: number; - /** - * (default: 64000 ms) - * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. - */ - levelLoadingMaxRetryTimeout?: number; - /** - * (default: 60000ms for fragment) - * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. - * It is up to the application to catch this event and treat it as needed. - */ - fragLoadingTimeOut?: number; - /** - * (default: 3) - * Max number of load retries. - */ - fragLoadingMaxRetry?: number; - /** - * (default: 1000 ms) - * Initial delay between XMLHttpRequest error and first load retry (in ms). - * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). - * Prefetch start fragment although media not attached. - */ - fragLoadingRetryDelay?: number; - /** - * (default: 64000 ms) - * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. - */ - fragLoadingMaxRetryDelay?: number; - /** - * (default: false) - * Start prefetching start fragment although media not attached yet. Max number of append retries. - */ - startFragPrefech?: boolean; - /** - * (default: 3) - * Max number of sourceBuffer.appendBuffer() retry upon error. Such error could happen in loop with UHD streams, when internal buffer is full. (Quota Exceeding Error will be triggered). - * In that case we need to wait for the browser to evict some data before being able to append buffer correctly. - */ - appendErrorMaxRetry?: number; - /** - * (default: standard XMLHttpRequest-based URL loader) - * Override standard URL loader by a custom one. Could be useful for P2P or stubbing (testing). - * Use this, if you want to overwrite both the fragment and the playlist loader. - * Note: If fLoader or pLoader are used, they overwrite loader! - */ - loader?: typeof Loader; - /** - * (default: undefined) - * This enables the manipulation of the fragment loader. - * Note: This will overwrite the default loader, as well as your own loader function. - */ - fLoader?: typeof Loader; - /** - * (default: undefined) - * This enables the manipulation of the playlist loader. - * Note: This will overwrite the default loader, as well as your own loader function. - */ - pLoader?: typeof Loader; - /** - * (default: undefined) - * XMLHttpRequest customization callback for default XHR based loader. - * Parameter should be a function with two arguments (xhr: XMLHttpRequest, url: string). - * If xhrSetup is specified, default loader will invoke it before calling xhr.send(). This allows user to easily modify/setup XHR. - */ - xhrSetup?(xhr: XMLHttpRequest, url: string): void; - /** - * (default: undefined) - * Fetch customization callback for Fetch based loader. - * Parameter should be a function with two arguments (context and Request Init Params). - * If fetchSetup is specified and Fetch loader is used, fetchSetup will be triggered to instantiate Request Object. This allows user to easily tweak Fetch loader. - */ - fetchSetup?(context: any, initParams: any): Request; - /** - * (default: internal ABR controller) - * Customized Adaptive Bitrate Streaming Controller. - * Parameter should be a class providing 2 getters, 2 setters and a destroy() method: - * get/set nextAutoLevel: return next auto-quality level/force next auto-quality level that should be returned (currently used for emergency switch down) - * get/set autoLevelCapping: capping/max level value that could be used by ABR Controller - * destroy(): should clean-up all used resources - */ - abrController?: AbrController; - /** - * (default: internal track timeline controller) - * Customized text track syncronization controller. - * Parameter should be a class with a destroy() method: - * destroy() : should clean-up all used resources - */ - timelineController?: TimelineController; - /** - * (default: true) - * whether or not to enable CEA-708 captions - */ - enableCEA708Captions?: boolean; - /** - * (default: English) - * Label for the text track generated for CEA-708 captions track 1. This is how it will appear in the browser's native menu for subtitles and captions. - */ - captionsTextTrack1Label?: string; - /** - * (default: en) - * RFC 3066 language code for the text track generated for CEA-708 captions track 1. - */ - captionsTextTrack1LanguagedCode?: string; - /** - * (default: Spanish) - * Label for the text track generated for CEA-708 captions track 2. This is how it will appear in the browser's native menu for subtitles and captions. - */ - captionsTextTrack2Label?: string; - /** - * (default: es) - * RFC 3066 language code for the text track generated for CEA-708 captions track 2. - */ - captionsTextTrack2LanguageCode?: string; - /** - * (default: false) - * If a segment's video track is shorter than its audio track by > min(maxSeekHole, maxBufferHole), extend the final video frame's duration to match the audio track's duration. - * This helps playback continue in certain cases that might otherwise get stuck. - */ - stretchShortVideoTrack?: boolean; - /** - * (default: true) - * Whether or not to force having a key frame in the first AVC sample after a discontinuity. - * If set to true, after a discontinuity, the AVC samples without any key frame will be dropped until finding one that contains a key frame. - * If set to false, all AVC samples will be kept, which can help avoid holes in the stream. Setting this parameter to false can also generate decoding weirdness when switching level or seeking. - */ - forceKeyFrameOnDiscontinuity?: boolean; - /** - * (default: 5.0) - * Fast bitrate Exponential moving average half-life, used to compute average bitrate for Live streams. - * Half of the estimate is based on the last abrEwmaFastLive seconds of sample history. Each of the sample is weighted by the fragment loading duration. - * parameter should be a float greater than 0 - */ - abrEwmaFastLive?: number; - /** - * (default: 9.0) - * Slow bitrate Exponential moving average half-life, used to compute average bitrate for Live streams. - * Half of the estimate is based on the last abrEwmaSlowLive seconds of sample history. Each of the sample is weighted by the fragment loading duration. - * parameter should be a float greater than abrEwmaFastLive - */ - abrEwmaSlowLive?: number; - /** - * (default: 4.0) - * Fast bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams. - * Half of the estimate is based on the last abrEwmaFastVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration. - * parameter should be a float greater than 0 - */ - abrEwmaFastVod?: number; - /** - * (default: 15.0) - * Slow bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams. - * Half of the estimate is based on the last abrEwmaSlowVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration. - * parameter should be a float greater than abrEwmaFastVoD - */ - abrEwmaSlowVod?: number; - /** - * (default: 500000) - * Default bandwidth estimate in bits/second prior to collecting fragment bandwidth samples. - * parameter should be a float - */ - abrEwmaDefaultEstimate?: number; - /** - * (default: 0.8) - * Scale factor to be applied against measured bandwidth average, to determine whether we can stay on current or lower quality level. - * If abrBandWidthFactor * bandwidth average < level.bitrate then ABR can switch to that level providing that it is equal or less than current level. - */ - abrBandWidthFactor?: number; - /** - * (default: 0.7) - * Scale factor to be applied against measured bandwidth average, to determine whether we can switch up to a higher quality level. - * If abrBandWidthUpFactor * bandwidth average < level.bitrate then ABR can switch up to that quality level. - */ - abrBandWidthUpFactor?: number; - /** - * (default: false) - * max bitrate used in ABR by avg measured bitrate i.e. if bitrate signaled in variant manifest for a given level is 2Mb/s but average bitrate measured on this level is 2.5Mb/s, - * then if config value is set to true, ABR will use 2.5 Mb/s for this quality level. - */ - abrMaxWithRealBitrate?: boolean; - /** - * (default: 0) - * Return the capping/min bandwidth value that could be used by automatic level selection algorithm. - * Useful when browser or tab of the browser is not in the focus and bandwidth drops - */ - minAutoBitrate?: number; - } - - /** - * a Level object represents a given quality level and contains quality level related info - */ - interface Level { - /** - * level url. might contain sever items if failover/redundant streams are found in the manifest - */ - url: string[]; - /** - * level bitrate - */ - bitrate: number; - /** - * level name - */ - name: string; - /** - * used codecs - */ - codecs: string; - /** - * video width - */ - width: number; - /** - * video height - */ - height: number; - /** - * level details - */ - details: LevelDetails; - } - - /** - * a LevelDetails object contains level details retrieved after level playlist parsing - */ - interface LevelDetails { - /** - * protocol version - */ - version: number; - /** - * playlist type - */ - type: string; - /** - * start sequence number - */ - startSN: number; - /** - * end sequence number - */ - endSN: number; - /** - * level total duration - */ - totalduration: number; - /** - * level fragment target duration - */ - targetduration: number; - /** - * average fragment duration - */ - averagetargetduration: number; - /** - * array of fragments info - */ - fragments: Fragment[]; - /** - * is this level a live playlist or not? - */ - live: boolean; - } - - /** - * the Fragment object contains fragment related info - */ - interface Fragment { - /** - * fragment duration - */ - duration: number; - /** - * fragment level identifier - */ - level: number; - /** - * fragment sequence number - */ - sn: number; - /** - * fragment start offset - */ - start: number; - /** - * fragment url - */ - url: string; - /** - * stream start date and time - */ - programDateTime: Date; - /** - * continuity count - */ - cc: number; - /** - * list of tags associated with the fragment - */ - tagList: string[][]; - /** - * fragment title - */ - title: string; - } - - interface Data { - /** - * videoElement - */ - video?: HTMLVideoElement; - /** - * media source - */ - mediaSource?: string; - /** - * manifest url - */ - url?: string; - /** - * available quality levels - */ - levels?: number[]; - /** - * available audio tracks - */ - audioTracks?: AudioTrack[]; - /** - * XMLHttp request stats - */ - stats?: HlsStats; - /** - * index of first quality level appearing in Manifest - */ - firstLevel?: number; - /** - * id of updated level - */ - level?: number; - /** - * id of loaded level - */ - levelId?: number; - /** - * levelDetails object - */ - details?: string; - /** - * PTS drift observed when parsing last fragment - */ - drift?: number; - /** - * fragment object with frag.loaded=stats.loaded - */ - frag?: Fragment; - /** - * fragment payload - */ - payload?: any; // TODO: what is the payload? - /** - * id of level or demuxer - */ - id?: number; - /** - * moof MP4 box - */ - moof?: any; // TODO: whats is the moof? - /** - * mdat MP4 box - */ - mdat?: any; // TODO: what is mdat? - /** - * PTS of first sample - */ - startPTS?: number; - /** - * PTS of last sample - */ - endPTS?: number; - /** - * DTS of first sample - */ - startDTS?: number; - /** - * DTS of last sample - */ - endDTS?: number; - /** - * stream type (audio or video) - */ - type?: string; - /** - * number of samples - */ - nb?: number; - /** - * number of dropped frames in last monitoring period - */ - currentDropped?: number; - /** - * number of decoded frames in last monitoring period - */ - currentDecode?: number; - /** - * total dropped frames on this video element - */ - totalDropped?: number; - /** - * level has to much dropped frame will be restricted - */ - droppedLevel?: number; - /** - * is error fatal or not. - * if error is not fatal, hls.js will try to recover it - * if error is fatal, an action is required to (try to) recover it - */ - fatal?: boolean; - } - - /** - * (default: internal ABR controller) - * Customized Adaptive Bitrate Streaming Controller. - */ - interface AbrController { - /** - * get: capping/max level value that could be used by ABR Controller - * set: capping/max level value that could be used by ABR Controller - */ - autoLevelCapping: number; - /** - * accumulated handled events - */ - handledEvents: string[]; - /** - * current hls instance - */ - hls: Hls; - /** - * last fragments corresponding level - */ - lastLoadedFragLevel: number; - /** - * get: next auto-quality levele/force next auto-quality level that should be returned - * set: next auto-quality levele/force next auto-quality level that should be returned - * - currently used for emergency switch down - */ - nextAutoLevel: number; - useGenericHandler: boolean; - } - - /** - * Customized text track syncronization controller. - */ - interface TimelineController { - /**d - * clean-up all used resources - */ - destory(): void; - } - - interface LoaderResponse { - url: string; - data: string | ArrayBuffer; - } - - interface LoaderStats { - /** - * performance.now() just after load() has been called - */ - trequest: number; - /** - * performance.now() of first received byte - */ - tfirst: number; - /** - * performance.now() on load complete - */ - tload: number; - /** - * number of loaded bytes - */ - loaded: number; - /** - * download bandwitdh in bit/s - */ - bw: number; - /** - * total nb of bytes - */ - total: number; - } - - interface LoaderError { - /** - * error code - */ - code: number; - /** - * error description - */ - text: string; - } - - interface HlsStats { - /** - * performance.now() just after load() has been called - */ - trequest: number; - /** - * performance.now() of first received byte - */ - tfirst: number; - /** - * performance.now() on load complete - */ - tload: number; - mtime: number; - tbuffered?: number; - length?: number; - } - - interface LoaderContext { - /** - * target URL - */ - url: string; - /** - * loader response type (arraybuffer or default response type for playlist) - */ - responseType: string; - /** - * start byte range offset - */ - rangeStart?: number; - /** - * end byte range offset - */ - rangeEnd?: number; - /** - * true if onProgress should report partial chunk of loaded content - */ - progressData?: boolean; - /** - * fragment object - */ - frag: Fragment; - /** - * request type - * - level, manifest - */ - type: string; - /** - * level id - */ - level: number; - } - - interface LoaderConfig { - /** - * Max number of load retries - */ - maxRetry: number; - /** - * Timeout after which `onTimeOut` callback will be triggered (if loading is still not finished after that delay) - */ - timeout: number; - /** - * Delay between an I/O error and following connection retry (ms). This to avoid spamming the server - */ - retryDelay: number; - /** - * max connection retry delay (ms) - */ - maxRetryDelay: number; - } - - interface LoaderCallbacks { - onSuccess(response: LoaderResponse, stats: LoaderStats, context: LoaderContext): void; - onProgress(stats: LoaderStats, context: LoaderContext, data: string | ArrayBuffer): void; - onError(error: LoaderError, context: LoaderContext): void; - onTimeout(stats: LoaderStats, context: LoaderContext): void; - } -} - -declare class Hls { - /** - * Constructor. Can be provided an HlsConfig object as default properties and or overrides - */ - constructor(config?: Hls.OptionalConfig) - /** - * return array of available quality levels - */ - levels: Hls.Level[]; - /** - * get: return current playback quality level - * set: trigger an immediate quality level switch to new quality level - * this will pause the video if it was playing, flush the whole buffer, - * and fetch fragment matching with current position and requested quality level - * then resume the video if needed once fetched fragment will have been buffered - * - * set to -1 for automatic level selection - */ - currentLevel: number; - /** - * capping/max level (index of level) that could be used by ABR Controller. Defaults to -1 - * which means no limit - * set: max level value that could be used by the ABR Controller - */ - autoLevelCapping: number; - /** - * return start level index (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) - * - * default valus is hls.firstLevel - */ - startLevel: number; - /** - * (default: true) - * if set to true, start level playlist and first fragments will be loaded automatically, after triggering of Hls.Events.MANIFEST_PARSED event - * if set to false, an explicit API call (hls.startLoad(startPosition=-1)) will be needed to start quality level/fragment loading. - */ - autoStartLoad: boolean; - /** - * get: Return the bound videoElement from the hls instance - */ - media: HTMLVideoElement; - /** - * hls.js config - */ - config: Hls.Config; - /** - * get: return next playback quality level (playback quality level for next buffered fragment) - * return -1 if next fragment not buffered yet - * set: trigger a quality level switch for next fragment - * this could eventually flush already buffered next fragment - * - * set to -1 for automatic level selection - */ - nextLevel: number; - /** - * get: return last loaded fragment quality level - * set: quality level for next loaded fragment - * set to -1 for automatic level selection - */ - loadLevel: number; - /** - * get: return quality level that will be used to load next fragment - * set: force quality level for next loaded fragment - * quality level will be forced only for that fragment - * after a fragment at this quality level has been loaded, hls.loadLevel will prevail - */ - nextLoadLevel: number; - /** - * first level index (index of first level appearing in Manifest. it is usually defined as start level hint for player) - */ - firstLevel: number; - /** - * array of audio tracks exposed in manifest - */ - audioTracks: AudioTrack[]; - /** - * get: returns audio track id - * set: sets audio track id (returned by) - */ - audioTrack: number; - /** - * position of live sync point (ie edge of live position minus safety delay defined by hls.config.liveSyncDuration) - */ - liveSyncPosition: number; - /** - * calling this method will: - * bind videoElement and hls instances - * create MediaSource and set it as video source - * once MediaSource object is successfully created, MEDIA_ATTACHED event will be fired - */ - attachMedia(videoElement: HTMLVideoElement): void; - /** - * calling this method will: - * unbind VideoElement from hls instance - * signal the end of the stream on MediaSource - * reset video source ( video.src = '' ) - */ - detachMedia(): void; - /** - * tell whether auto level selection is enabled or not - */ - autoLevelEnabled(enabled: boolean): boolean; - /** - * loads provided url as media source - */ - loadSource(source: string): void; - /** - * by default, hls.js will automatically start loading quality level playlists, and fragments after Hls.Events.MANIFEST_PARSED event has been triggered (and video element has been attached) - * however if config.autoStartLoad is set to false, hls.startLoad() needs to be called to manually start playlist and fragments loading - * - * start/restart playlist/fragment loading. this is only effective if MANIFEST_PARSED event has been triggered and video element has been attached to hls object - * startPosition is the initial position in the playlist - * ff startPosition is not set to -1, it allows to override default startPosition to the one you want - * (it will bypass hls.config.liveSync* config params for Live for example, so that user can start playback from whatever position) - */ - startLoad(startPosition?: number): void; - /** - * stop playlist/fragment loading. could be resumed later on by calling hls.startLoad() - */ - stopLoad(): void; - /** - * should be invoked to recover media error. - */ - recoverMediaError(): void; - /** - * if media error are still raised after calling hls.recoverMediaError(), calling this method, could be useful to workaround audio codec mismatch. - * the workflow should be: - * on First Media Error : call hls.recoverMediaError() - * if another Media Error is raised 'quickly' after this first Media Error : first call hls.swapAudioCodec(), then call hls.recoverMediaError() - */ - swapAudioCodec(): void; - /** - * should be called to free used resources and destroy hls context - */ - destroy(): void; - /** - * hls.js event listener - */ - on(event: string, callback: (event: string, data: Hls.Data) => void): void; - /** - * remove hls.js event listener - */ - off(event: string, callback: (event: string, data: Hls.Data) => void): void; + off(event: string, callback: (event: string, data: Hls.Data) => void): void; } export as namespace Hls; From c03cd18c58a8d0cc2ac3538c6b8d04776d474936 Mon Sep 17 00:00:00 2001 From: John Gainfort Jr Date: Wed, 9 Aug 2017 12:46:39 -0600 Subject: [PATCH 26/29] fixed spacing --- types/hls.js/index.d.ts | 3470 +++++++++++++++++++-------------------- 1 file changed, 1735 insertions(+), 1735 deletions(-) diff --git a/types/hls.js/index.d.ts b/types/hls.js/index.d.ts index 5270bed7cf..d8b34e5969 100644 --- a/types/hls.js/index.d.ts +++ b/types/hls.js/index.d.ts @@ -5,1704 +5,468 @@ // TypeScript Version: 2.2 declare class Loader { - constructor(config: Hls.LoaderConfig) - /** - * Start retrieving content located at given URL (HTTP GET). - */ - load(context: Hls.LoaderContext, config: Hls.LoaderConfig, callbacks: Hls.LoaderCallbacks): void; - /** - * Abort any loading in progress. - */ - abort(): void; - /** - * Destroy loading context. - */ - destroy(): void; + constructor(config: Hls.LoaderConfig) + /** + * Start retrieving content located at given URL (HTTP GET). + */ + load(context: Hls.LoaderContext, config: Hls.LoaderConfig, callbacks: Hls.LoaderCallbacks): void; + /** + * Abort any loading in progress. + */ + abort(): void; + /** + * Destroy loading context. + */ + destroy(): void; } declare namespace Hls { + /** + * Hls events + */ + namespace Events { /** - * Hls events + * fired to attach Media to hls instance + * data: { video , mediaSource } */ - namespace Events { - /** - * fired to attach Media to hls instance - * data: { video , mediaSource } - */ - const MEDIA_ATTACHING: string; - /** - * fired when Media has been succesfully attached to hls instance - * data: { video , mediaSource } - */ - const MEDIA_ATTACHED: string; - /** - * fired before detaching Media from hls instance - * data: { } - */ - const MEDIA_DETACHING: string; - /** - * fired when Media has been detached from hls instance - * data: { } - */ - const MEDIA_DETACHED: string; - /** - * fired when the buffer is going to be reset - * data: { } - */ - const BUFFER_RESET: string; - /** - * fired when we know about the codecs that we need buffers for to push into - * data: { tracks : { container, codec, levelCodec, initSegment, metadata } } - */ - const BUFFER_CODECS: string; - /** - * fired when sourcebuffers have been created - * data: { tracks: tracks } - */ - const BUFFER_CREATED: string; - /** - * fired when we append a segment to the buffer - * data: { segment: segment object } - */ - const BUFFER_APPENDING: string; - /** - * fired when we are done with appending a media segment to the buffer - * data: { parent : segment parent that triggered BUFFER_APPENDING, pending : nb of segments waiting for appending for this segment parent } - */ - const BUFFER_APPENDED: string; - /** - * fired when the stream is finished and we want to notify the media buffer that there will be no more data - * data: { } - */ - const BUFFER_EOS: string; - /** - * fired when the media buffer should be flushed - * data: { } - */ - const BUFFER_FLUSHING: string; - /** - * fired when the media buffer has been flushed - * data: { } - */ - const BUFFER_FLUSHED: string; - /** - * fired to signal that a manifest loading starts - * data: { url : manifestURL } - */ - const MANIFEST_LOADING: string; - /** - * fired after manifest has been loaded - * data: { levels : [available quality levels] , audioTracks : [ available audio tracks], url : manifestURL, stats : { trequest, tfirst, tload, mtime}} - */ - const MANIFEST_LOADED: string; - /** - * fired after manifest has been parsed - * data: { levels : [ available quality levels ], firstLevel : index of first quality level appearing in Manifest } - */ - const MANIFEST_PARSED: string; - /** - * fired when a level playlist loading starts - * data: { url : level URL, level : id of level being loaded } - */ - const LEVEL_LOADING: string; - /** - * fired when a level playlist loading finishes - * data: { details : levelDetails object, levelId : id of loaded level, stats : { trequest, tfirst, tload, mtime } } - */ - const LEVEL_LOADED: string; - /** - * fired when a level's details have been updated based on previous details, after it has been loaded - * data: { details : levelDetails object, level : id of updated level } - */ - const LEVEL_UPDATED: string; - /** - * fired when a level's PTS information has been updated after parsing a fragment - * data: { details: levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment } - */ - const LEVEL_PTS_UPDATED: string; - /** - * fired when a level switch is requested - * data: { level: Level } - */ - const LEVEL_SWITCHING: string; - /** - * fired when a level switch is effective - * data: { level: level object } - */ - const LEVEL_SWITCHED: string; - /** - * fired to notify that audio track lists has been updated - * data: { audioTracks : audioTracks } - */ - const AUDIO_TRACKS_UPDATED: string; - /** - * fired when an audio track switch occurs. deprecated in favor AUDIO_TRACK_SWITCHING - * data: { id : audio track id } - */ - const AUDIO_TRACK_SWTICH: string; - /** - * fired when an audio track switching is requested - * data: { id : audio track id } - */ - const AUDIO_TRACK_SWITCHING: string; - /** - * fired when an audio track switch actually occurs - * data: { id : audio track id } - */ - const AUDIO_TRACK_SWITCHED: string; - /** - * fired when an audio track loading starts - * data: { url : audio track URL, id : audio track id } - */ - const AUDIO_TRACK_LOADING: string; - /** - * fired when an audio track loading finishes - * data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime } } - */ - const AUDIO_TRACK_LOADED: string; - /** - * fired to notify that subtitle track lists has been updated - * data: { subtitleTracks : subtitleTracks } - */ - const SUBTITLE_TRACKS_UPDATED: string; - /** - * fired when an subtitle track switch occurs - * data: { id : subtitle track id } - */ - const SUBTITLE_TRACK_SWITCH: string; - /** - * fired when a subtitle track loading starts - * data: { url : subtitle track URL, id : subtitle track id } - */ - const SUBTITLE_TRACK_LOADING: string; - /** - * fired when a subtitle track loading finishes - * data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime } } - */ - const SUBTITLE_TRACK_LOADED: string; - /** - * fired when a subtitle fragment has been processed - * data: { success : boolean, frag : the processed frag } - */ - const SUBTITLE_FRAG_PROCESSED: string; - /** - * fired when a decryption key loading starts - * data: { frag: fragment object } - */ - const KEY_LOADING: string; - /** - * fired when a decryption key loading is completed - * data: { frag: fragment object } - */ - const KEY_LOADED: string; - /** - * fired when first timestamp has been found - * data: { id: demuxer id, frag: fragment object, initPTS: initPTS } - */ - const INIT_PTS_FOUND: string; - /** - * fired when a fragment loading starts - * data: { frag : fragment object } - */ - const FRAG_LOADING: string; - /** - * fired when a fragment load is in progress - * data: { frag : fragment object with frag.loaded=stats.loaded, stats : { trequest, tfirst, loaded, total } } - */ - const FRAG_LOAD_PROGRESS: string; - /** - * identifier for fragment load aborting for emergency switch down - * data: { frag: fragment object } - */ - const FRAG_LOAD_ERMERGENCY_ABORTED: string; - /** - * fired when a fragment loading is completed - * data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length}} - */ - const FRAG_LOADED: string; - /** - * fired when a fragment decryption is completed - * data: { id: demuxer id, frag: fragment object, stats: { tstart, tdecrypt } } - */ - const FRAG_DECRYPTED: string; - /** - * fired when Init Segment has been extracted from fragment - * data: { id: demuxer id, moov : moov MP4 box, codecs : codecs found while parsing fragment} - */ - const FRAG_PARSING_INIT_SEGMENT: string; - /** - * fired when parsing id3 is completed - * data: { id: demuxer id, samples : [ id3 pes - pts and dts timestamp are relative, values are in seconds]} - */ - const FRAG_PARSING_METADATA: string; - /** - * fired when moof/mdat have been extracted from fragment - * data: { id: demuxer id, - * moof : moof MP4 box, - * mdat : mdat MP4 box, - * startPTS : PTS of first sample, - * endPTS : PTS of last sample, - * startDTS : DTS of first sample, - * endDTS : DTS of last sample, - * type : stream type (audio or video), - * nb : number of samples} - */ - const FRAG_PARSING_DATA: string; - /** - * fired when fragment parsing is completed - * data: { id: demuxer id} - */ - const FRAG_PARSED: string; - /** - * fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - * data: { id: demuxer id, frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tbuffered, length} } - */ - const FRAG_BUFFERED: string; - /** - * fired when fragment matching with current video position is changing - * data: { frag : fragment object } - */ - const FRAG_CHANGED: string; - /** - * triggered when FPS drop in last monitoring period is higher than given threshold - * data: { curentDropped : nb of dropped frames in last monitoring period, - * currentDecoded : nb of decoded frames in last monitoring period, - * totalDropped : total dropped frames on this video element } - */ - const FPS_DROP: string; - /** - * triggered when FPS drop triggers auto level capping - * data: { level: suggested new auto level capping by fps controller, droppedLevel : level has to much dropped frame will be restricted } - */ - const FPS_DROP_LEVEL_CAPPING: string; - /** - * Identifier for an error event - * data: { type : error type, details : error details, fatal : is error fatal or not, other error specific data } - */ - const ERROR: string; - /** - * fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a video to the instance of hls.js to handle mid-rolls for example. - * data: { } - */ - const DESTROYING: string; - /** - * fired upon stream controller state transitions - * data: { previousState, nextState } - */ - const STREAM_STATE_TRANSITION: string; - } - + const MEDIA_ATTACHING: string; /** - * Hls error details + * fired when Media has been succesfully attached to hls instance + * data: { video , mediaSource } */ - namespace ErrorDetails { - // NETWORK_ERRORS // - /** - * raised when manifest loading fails because of a network error - * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.MANIFEST_LOAD_ERROR, fatal : true, url : manifest URL, response : { code: error code, text: error text }, loader : URL loader } - */ - const MANIFEST_LOAD_ERROR: string; - /** - * raised when manifest loading fails because of a timeout - * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.MANIFEST_LOAD_TIMEOUT, fatal : true, url : manifest URL, loader : URL loader } - */ - const MANIFEST_LOAD_TIMEOUT: string; - /** - * raised when manifest parsing failed to find proper content - * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.MANIFEST_PARSING_ERROR, fatal : true, url : manifest URL, reason : parsing error reason } - */ - const MANIFEST_PARSING_ERROR: string; - /** - * raised when level loading fails because of a network error - * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.LEVEL_LOAD_ERROR, fatal : true, url : level URL, response : { code: error code, text: error text }, loader : URL loader } - */ - const LEVEL_LOAD_ERROR: string; - /** - * raised when level loading fails because of a timeout - * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.LEVEL_LOAD_TIMEOUT, fatal : true, url : level URL, loader : URL loader } - */ - const LEVEL_LOAD_TIMEOUT: string; - /** - * raised when audio track loading fails because of a network error - * data: { type: NETWORK_ERROR, details: Hls.ErrorDetails.AUDIO_TRACK_LOAD_ERROR, fatal: false, url: audio URL, loader: URL loader } - */ - const AUDIO_TRACK_LOAD_ERROR: string; - /** - * raised when audio track loading fails because of a timeout - * data: { type: NETWORK_ERROR, details: Hls.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT, fatal: false, url: audio URL, response: { code: error code, text: error text }, loader: URL loader } - */ - const AUDIO_TRACK_LOAD_TIMEOUT: string; - /** - * raised when fragment loading fails because of a network error - * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.FRAG_LOAD_ERROR, fatal : true or false, frag : fragment object, response : { code: error code, text: error text } } - */ - const FRAG_LOAD_ERROR: string; - /** - * raised when fragment loading fails because of a timeout - * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.FRAG_LOAD_TIMEOUT, fatal : true or false, frag : fragment object } - */ - const FRAG_LOAD_TIMEOUT: string; - /** - * raised when decrypt key loading fails because of a network error - * data: { type: NETWORK_ERROR, details: Hls.ErrorDetails.KEY_LOAD_ERROR, fatal: false, frag: fragment object } - */ - const KEY_LOAD_ERROR: string; - /** - * raised when decrypt key loading fails because of timeout - * data: { type: NETWORK_EROR, details: Hls.ErrorDetails.KEY_LOAD_TIMEOUT, fatal: true, frag: fragment object } - */ - const KEY_LOAD_TIMEOUT: string; - - // MEDIA_ERRORS // - /** - * raised when manifest only contains quality level with codecs incompatible with MediaSource Engine. - * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR, fatal : true, url : manifest URL } - */ - const MANIFEST_INCOMPATIBLE_CODECS_ERROR: string; - /** - * raised upon detection of same fragment being requested in loop - * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.FRAG_LOOP_LOADING_ERROR, fatal : true or false, frag : fragment object } - */ - const FRAG_LOOP_LOADING_ERROR: string; - /** - * raised when fragment decryption fails - * data: { type: MEDIA_ERROR, details: Hls.ErrorDetails.FRAG_DECRYPT_ERROR, fatal: true, reason: failure reason } - */ - const FRAG_DECRYPT_ERROR: string; - /** - * raised when fragment parsing fails - * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.FRAG_PARSING_ERROR, fatal : true or false, reason : failure reason } - */ - const FRAG_PARSING_ERROR: string; - /** - * raised when MediaSource fails to add new sourceBuffer - * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_ADD_CODEC_ERROR, fatal : false, err : error raised by MediaSource, mimeType: mimeType on which the failure happened } - */ - const BUFFER_ADD_CODEC_ERROR: string; - /** - * raised when exception is raised while calling buffer append - * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_APPEND_ERROR, fatal : true, frag : fragment object } - */ - const BUFFER_APPEND_ERROR: string; - /** - * raised when exception is raised during buffer appending - * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_APPENDING_ERROR, fatal : false } - */ - const BUFFER_APPENDING_ERROR: string; - /** - * raised when playback is stuck because buffer is running out of data - * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_STALLED_ERROR, fatal : false } - */ - const BUFFER_STALLED_ERROR: string; - /** - * raised when no data can be appended anymore in media buffer because it is full. - * This error is recovered automatically by performing a smooth level switching that empty buffers (without disrupting the playback) and reducing the max buffer length. - * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_FULL_ERROR, fatal : false } - */ - const BUFFER_FULL_ERROR: string; - /** - * raised after hls.js seeks over a buffer hole to unstuck the playback, - * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_SEEK_OVER_HOLE, fatal : false, hole : hole duration } - */ - const BUFFER_SEEK_OVER_HOLE: string; - /** - * raised when playback is stuck although currentTime is in a buffered aread - * data: { type: MEDIA_ERROR, details: Hls.ErrorDetails.BUFFERED_STALLED_ERROR, fatal: true } - */ - const BUFFER_NUDGE_ON_STALL: string; - - // MUX_ERROR // - /** - * raised when memory allocation fails during remuxing - * data: { type: MUX_ERROR, details: Hls.ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes: mdat size, reason: failure reason } - */ - const REMUX_ALLOC_ERROR: string; - - // OTHER_ERROR // - /** - * raised when level switching fails - * data: { type : OTHER_ERROR, details : Hls.ErrorDetails.LEVEL_SWITCH_ERROR, fatal : false, level : failed level index, reason : failure reason } - */ - const LEVEL_SWITCH_ERROR: string; - /** - * raised when an exception occurs in an internal hls.js event handler - * data: { type: OTHER_ERROR, details: Hls.ErrorDetails.INTERNAL_EXCEPTION, fatal: true or false, event: event object or string, error: { message: error message } } - */ - const INTERNAL_EXCEPTION: string; - } - + const MEDIA_ATTACHED: string; /** - * Hls error types + * fired before detaching Media from hls instance + * data: { } */ - namespace ErrorTypes { - /** - * network related errors - */ - const NETWORK_ERROR: string; - /** - * media/video related errors - */ - const MEDIA_ERROR: string; - /** - * muxing related errors - */ - const MUX_ERROR: string; - /** - * all other erros - */ - const OTHER_ERROR: string; - } + const MEDIA_DETACHING: string; /** - * override Hls default configuration - * this configuration will be applied by default to all instances + * fired when Media has been detached from hls instance + * data: { } */ - let DefaultConfig: Config; + const MEDIA_DETACHED: string; /** - * checks whether your browser is supporting MediaSource Extensions + * fired when the buffer is going to be reset + * data: { } */ - function isSupported(): boolean; + const BUFFER_RESET: string; /** - * returns hls.js dist version number + * fired when we know about the codecs that we need buffers for to push into + * data: { tracks : { container, codec, levelCodec, initSegment, metadata } } */ - const version: string; - - interface Config { - /** - * (default: true) - * if set to true, start level playlist and first fragments will be loaded automatically, after triggering of Hls.Events.MANIFEST_PARSED event - * if set to false, an explicit API call (hls.startLoad(startPosition=-1)) will be needed to start quality level/fragment loading. - */ - autoStartLoad: boolean; - /** - * (default -1) - * if set to -1, playback will start from initialTime=0 for VoD and according to liveSyncDuration/liveSyncDurationCount config params for Live - * otherwise, playback will start from predefined value. (unless stated otherwise in autoStartLoad=false mode : in that case startPosition can be overrided using hls.startLoad(startPosition)). - */ - startPosition: number; - /** - * (default: false) - * if set to true, the adaptive algorithm with limit levels usable in auto-quality by the HTML video element dimensions (width and height) - * if set to false, levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration. - */ - capLevelToPlayerSize: boolean; - /** - * (default: false) - * setting config.debug = true; will turn on debug logs on JS console. - * a logger object could also be provided for custom logging: config.debug = customLogger; - */ - debug: boolean; - /** - * (default: undefined) - * if audio codec is not signaled in variant manifest, or if only a stream manifest is provided, hls.js tries to guess audio codec by parsing audio sampling rate in ADTS header. - * If sampling rate is less or equal than 22050 Hz, then hls.js assumes it is HE-AAC, otherwise it assumes it is AAC-LC. - * This could result in bad guess, leading to audio decode error, ending up in media error. - * It is possible to hint default audiocodec to hls.js by configuring this value as below: - * mp4a.40.2 (AAC-LC) or - * mp4a.40.5 (HE-AAC) or - * undefined (guess based on sampling rate) - */ - defaultAudioCodec: string; - /** - * (default: 1) - * number of segments needed to start a playback of Live stream. - */ - initialLiveManifestSize: number; - /** - * (default: 30 seconds) - * Maximum buffer length in seconds. If buffer length is/become less than this value, a new fragment will be loaded. - * This is the guaranteed buffer length hls.js will try to reach, regardless of maxBufferSize. - */ - maxBufferLength: number; - /** - * (default 600s) - * Maximum buffer length in seconds. Hls.js will never exceed this value, even if maxBufferSize is not reached yet. - * hls.js tries to buffer up to a maximum number of bytes (60 MB by default) rather than to buffer up to a maximum nb of seconds. - * This is to mimic the browser behaviour (the buffer eviction algorithm is starting after the browser detects that video buffer size reaches a limit in bytes) - * maxBufferLength is the minimum guaranteed buffer length that hls.js will try to achieve, even if that value exceeds the amount of bytes 60 MB of memory. - * maxMaxBufferLength acts as a capping value, as if bitrate is really low, you could need more than one hour of buffer to fill 60 MB. - */ - maxMaxBufferLength: number; - /** - * (default: 60 MB) - * 'Minimum' maximum buffer size in bytes. If buffer size upfront is bigger than this value, no fragment will be loaded - */ - maxBufferSize: number; - /** - * (default: 0.5 seconds) - * 'Maximum' inter-fragment buffer hole tolerance that hls.js can cope with when searching for the next fragment to load. When switching between quality level, - * fragments might not be perfectly aligned. - * This could result in small overlapping or hole in media buffer. This tolerance factor helps cope with this. - */ - maxBufferHole: number; - /** - * (default: 4s) - * - * ABR algorithm will always try to choose a quality level that should avoid rebuffering. In case no quality level with this criteria can - * be found (lets say for example that buffer length is 1s, but fetching a fragment at lowest quality is predicted to take around 2s ... - * ie we can forecast around 1s of rebuffering ...) then ABR algorithm will try to find a level that should guarantee less than - * maxStarvationDelay of buffering. - */ - maxStarvationDelay: number; - /** - * (default: 2s) - * In case playback is stalled, and a buffered range is available upfront, less than maxSeekHole seconds from current media position, - * hls.js will jump over this buffer hole to reach the beginning of this following buffered range. - * maxSeekHole allows to configure this jumpable threshold. - */ - maxSeekHole: number; - /** - * (default: 0.5s) - * media element is expected to play and if currentTime has not moved for more than lowBufferWatchdogPeriod and if there are less than maxBufferHole seconds buffered upfront, - * hls.js will try to nudge playhead to recover playback - */ - lowBufferWatchdogPeriod: number; - /** - * (default: 3s) - * if media element is expected to play and if currentTime has not moved for more than highBufferWatchdogPeriod and if there are more than maxBufferHole seconds buffered upfront, - * hls.js will try to nudge playhead to recover playback - */ - highBufferWatchdogPeriod: number; - /** - * (default: 0.1s) - * In case playback continues to stall after first playhead nudging, currentTime will be nudged evenmore following nudgeOffset to try to restore playback. - * media.currentTime += (nb nudge retry -1)*nudgeOffset - */ - nudgeOffset: number; - /** - * (default: 3s) - * In case playback continues to stall after first playhead nudging, currentTime will be nudged evenmore following nudgeOffset to try to restore playback. - * media.currentTime += (nb nudge retry -1)*nudgeOffset - */ - nudgeMaxRetry: number; - /** - * (default 0.2s) - * This tolerance factor is used during fragment lookup. - * Instead of checking whether buffered.end is located within [start, end] range, frag lookup will be done by checking within [start-maxFragLookUpTolerance, end-maxFragLookUpTolerance] range. - * This tolerance factor is used to cope with situations like: - * buffered.end = 9.991 - * frag[0] : [0,10] - * frag[1] : [10,20] - * buffered.end is within frag[0] range, but as we are close to frag[1], frag[1] should be choosen instead - * If maxFragLookUpTolerance = 0.2, this lookup will be adjusted to - * frag[0] : [-0.2,9.8] - * frag[1] : [9.8,19.8] - * This time, buffered.end is within frag[1] range, and frag[1] will be the next fragment to be loaded, as expected - */ - maxLoadingDelay: number; - /** - * (default 4s) - * - * 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 ) - */ - maxFragLookUpTolerance: number; - /** - * (default: 3) - * edge of live delay, expressed in multiple of EXT-X-TARGETDURATION. if set to 3, playback will start from fragment N-3, N being the last fragment of the live playlist. - * Decreasing this value is likely to cause playback stalls. - */ - liveSyncDurationCount: number; - /** - * (default: undefined) - * Alternative parameter to liveSyncDurationCount, expressed in seconds vs number of segments. - * If defined in the configuration object, liveSyncDuration will take precedence over the default liveSyncDurationCount. - * You can't define this parameter and either liveSyncDurationCount or liveMaxLatencyDurationCount in your configuration object at the same time. - * A value too low (inferior to ~3 segment durations) is likely to cause playback stalls. - */ - liveSyncDuration: number; - /** - * (default: Infinity) - * maximum delay allowed from edge of live, expressed in multiple of EXT-X-TARGETDURATION. - * If set to 10, the player will seek back to liveSyncDurationCount whenever the next fragment to be loaded is older than N-10, N being the last fragment of the live playlist. - * If set, this value must be stricly superior to liveSyncDurationCount a value too close from liveSyncDurationCount is likely to cause playback stalls. - */ - liveMaxLatencyDurationCount: number; - /** - * (default: undefined) - * Alternative parameter to liveMaxLatencyDurationCount, expressed in seconds vs number of segments. - * If defined in the configuration object, liveMaxLatencyDuration will take precedence over the default liveMaxLatencyDurationCount. - * If set, this value must be stricly superior to liveSyncDuration which must be defined as well. - * You can't define this parameter and either liveSyncDurationCount or liveMaxLatencyDurationCount in your configuration object at the same time. - * A value too close from liveSyncDuration is likely to cause playback stalls. - */ - liveMaxLatencyDuration: number; - /** - * (default: true) - * Enable WebWorker (if available on browser) for TS demuxing/MP4 remuxing, to improve performance and avoid lag/frame drops. - */ - enableWorker: boolean; - /** - * (default: true) - * Enable to use JavaScript version AES decryption for fallback of WebCrypto API. - */ - enableSoftwareAES: boolean; - /** - * (default: undefined) - * When set, use this level as the default hls.startLevel. Keep in mind that the startLevel set with the API takes precedence over - * config.startLevel configuration parameter. - */ - startLevel: number; - /** - * (default: 10000ms for level and manifest) - * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. - * It is up to the application to catch this event and treat it as needed. - */ - manifestLoadingTimeOut: number; - /** - * (default: 3) - * Max number of load retries. - */ - manifestLoadingMaxRetry: number; - /** - * (default: 1000 ms) - * Initial delay between XMLHttpRequest error and first load retry (in ms). - * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). - * Prefetch start fragment although media not attached. - */ - manifestLoadingRetryDelay: number; - /** - * (default: 64000 ms) - * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. - */ - manifestLoadingMaxRetryTimeout: number; - /** - * (default: 60000ms for fragment) - * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. - * It is up to the application to catch this event and treat it as needed. - */ - levelLoadingTimeOut: number; - /** - * (default: 3) - * Max number of load retries. - */ - levelLoadingMaxRetry: number; - /** - * (default: 1000 ms) - * Initial delay between XMLHttpRequest error and first load retry (in ms). - * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). - * Prefetch start fragment although media not attached. - */ - levelLoadingRetryDelay: number; - /** - * (default: 64000 ms) - * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. - */ - levelLoadingMaxRetryTimeout: number; - /** - * (default: 60000ms for fragment) - * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. - * It is up to the application to catch this event and treat it as needed. - */ - fragLoadingTimeOut: number; - /** - * (default: 3) - * Max number of load retries. - */ - fragLoadingMaxRetry: number; - /** - * (default: 1000 ms) - * Initial delay between XMLHttpRequest error and first load retry (in ms). - * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). - * Prefetch start fragment although media not attached. - */ - fragLoadingRetryDelay: number; - /** - * (default: 64000 ms) - * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. - */ - fragLoadingMaxRetryDelay: number; - /** - * (default: false) - * Start prefetching start fragment although media not attached yet. Max number of append retries. - */ - startFragPrefech: boolean; - /** - * (default: 3) - * Max number of sourceBuffer.appendBuffer() retry upon error. Such error could happen in loop with UHD streams, when internal buffer is full. (Quota Exceeding Error will be triggered). - * In that case we need to wait for the browser to evict some data before being able to append buffer correctly. - */ - appendErrorMaxRetry: number; - /** - * (default: standard XMLHttpRequest-based URL loader) - * Override standard URL loader by a custom one. Could be useful for P2P or stubbing (testing). - * Use this, if you want to overwrite both the fragment and the playlist loader. - * Note: If fLoader or pLoader are used, they overwrite loader! - */ - loader: typeof Loader; - /** - * (default: undefined) - * This enables the manipulation of the fragment loader. - * Note: This will overwrite the default loader, as well as your own loader function. - */ - fLoader?: typeof Loader; - /** - * (default: undefined) - * This enables the manipulation of the playlist loader. - * Note: This will overwrite the default loader, as well as your own loader function. - */ - pLoader?: typeof Loader; - /** - * (default: undefined) - * XMLHttpRequest customization callback for default XHR based loader. - * Parameter should be a function with two arguments (xhr: XMLHttpRequest, url: string). - * If xhrSetup is specified, default loader will invoke it before calling xhr.send(). This allows user to easily modify/setup XHR. - */ - xhrSetup?(xhr: XMLHttpRequest, url: string): void; - /** - * (default: undefined) - * Fetch customization callback for Fetch based loader. - * Parameter should be a function with two arguments (context and Request Init Params). - * If fetchSetup is specified and Fetch loader is used, fetchSetup will be triggered to instantiate Request Object. This allows user to easily tweak Fetch loader. - */ - fetchSetup?(context: any, initParams: any): Request; - /** - * (default: internal ABR controller) - * Customized Adaptive Bitrate Streaming Controller. - * Parameter should be a class providing 2 getters, 2 setters and a destroy() method: - * get/set nextAutoLevel: return next auto-quality level/force next auto-quality level that should be returned (currently used for emergency switch down) - * get/set autoLevelCapping: capping/max level value that could be used by ABR Controller - * destroy(): should clean-up all used resources - */ - abrController: AbrController; - /** - * (default: internal track timeline controller) - * Customized text track syncronization controller. - * Parameter should be a class with a destroy() method: - * destroy() : should clean-up all used resources - */ - timelineController: TimelineController; - /** - * (default: true) - * whether or not to enable CEA-708 captions - */ - enableCEA708Captions: boolean; - /** - * (default: English) - * Label for the text track generated for CEA-708 captions track 1. This is how it will appear in the browser's native menu for subtitles and captions. - */ - captionsTextTrack1Label: string; - /** - * (default: en) - * RFC 3066 language code for the text track generated for CEA-708 captions track 1. - */ - captionsTextTrack1LanguagedCode: string; - /** - * (default: Spanish) - * Label for the text track generated for CEA-708 captions track 2. This is how it will appear in the browser's native menu for subtitles and captions. - */ - captionsTextTrack2Label: string; - /** - * (default: es) - * RFC 3066 language code for the text track generated for CEA-708 captions track 2. - */ - captionsTextTrack2LanguageCode: string; - /** - * (default: false) - * If a segment's video track is shorter than its audio track by > min(maxSeekHole, maxBufferHole), extend the final video frame's duration to match the audio track's duration. - * This helps playback continue in certain cases that might otherwise get stuck. - */ - stretchShortVideoTrack: boolean; - /** - * (default: true) - * Whether or not to force having a key frame in the first AVC sample after a discontinuity. - * If set to true, after a discontinuity, the AVC samples without any key frame will be dropped until finding one that contains a key frame. - * If set to false, all AVC samples will be kept, which can help avoid holes in the stream. Setting this parameter to false can also generate decoding weirdness when switching level or seeking. - */ - forceKeyFrameOnDiscontinuity: boolean; - /** - * (default: 5.0) - * Fast bitrate Exponential moving average half-life, used to compute average bitrate for Live streams. - * Half of the estimate is based on the last abrEwmaFastLive seconds of sample history. Each of the sample is weighted by the fragment loading duration. - * parameter should be a float greater than 0 - */ - abrEwmaFastLive: number; - /** - * (default: 9.0) - * Slow bitrate Exponential moving average half-life, used to compute average bitrate for Live streams. - * Half of the estimate is based on the last abrEwmaSlowLive seconds of sample history. Each of the sample is weighted by the fragment loading duration. - * parameter should be a float greater than abrEwmaFastLive - */ - abrEwmaSlowLive: number; - /** - * (default: 4.0) - * Fast bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams. - * Half of the estimate is based on the last abrEwmaFastVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration. - * parameter should be a float greater than 0 - */ - abrEwmaFastVod: number; - /** - * (default: 15.0) - * Slow bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams. - * Half of the estimate is based on the last abrEwmaSlowVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration. - * parameter should be a float greater than abrEwmaFastVoD - */ - abrEwmaSlowVod: number; - /** - * (default: 500000) - * Default bandwidth estimate in bits/second prior to collecting fragment bandwidth samples. - * parameter should be a float - */ - abrEwmaDefaultEstimate: number; - /** - * (default: 0.8) - * Scale factor to be applied against measured bandwidth average, to determine whether we can stay on current or lower quality level. - * If abrBandWidthFactor * bandwidth average < level.bitrate then ABR can switch to that level providing that it is equal or less than current level. - */ - abrBandWidthFactor: number; - /** - * (default: 0.7) - * Scale factor to be applied against measured bandwidth average, to determine whether we can switch up to a higher quality level. - * If abrBandWidthUpFactor * bandwidth average < level.bitrate then ABR can switch up to that quality level. - */ - abrBandWidthUpFactor: number; - /** - * (default: false) - * max bitrate used in ABR by avg measured bitrate i.e. if bitrate signaled in variant manifest for a given level is 2Mb/s but average bitrate measured on this level is 2.5Mb/s, - * then if config value is set to true, ABR will use 2.5 Mb/s for this quality level. - */ - abrMaxWithRealBitrate: boolean; - /** - * (default: 0) - * Return the capping/min bandwidth value that could be used by automatic level selection algorithm. - * Useful when browser or tab of the browser is not in the focus and bandwidth drops - */ - minAutoBitrate: number; - } - - interface OptionalConfig { - /** - * (default: true) - * if set to true, start level playlist and first fragments will be loaded automatically, after triggering of Hls.Events.MANIFEST_PARSED event - * if set to false, an explicit API call (hls.startLoad(startPosition=-1)) will be needed to start quality level/fragment loading. - */ - autoStartLoad?: boolean; - /** - * (default -1) - * if set to -1, playback will start from initialTime=0 for VoD and according to liveSyncDuration/liveSyncDurationCount config params for Live - * otherwise, playback will start from predefined value. (unless stated otherwise in autoStartLoad=false mode : in that case startPosition can be overrided using hls.startLoad(startPosition)). - */ - startPosition?: number; - /** - * (default: false) - * if set to true, the adaptive algorithm with limit levels usable in auto-quality by the HTML video element dimensions (width and height) - * if set to false, levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration. - */ - capLevelToPlayerSize?: boolean; - /** - * (default: false) - * setting config.debug = true; will turn on debug logs on JS console. - * a logger object could also be provided for custom logging: config.debug = customLogger; - */ - debug?: boolean; - /** - * (default: undefined) - * if audio codec is not signaled in variant manifest, or if only a stream manifest is provided, hls.js tries to guess audio codec by parsing audio sampling rate in ADTS header. - * If sampling rate is less or equal than 22050 Hz, then hls.js assumes it is HE-AAC, otherwise it assumes it is AAC-LC. - * This could result in bad guess, leading to audio decode error, ending up in media error. - * It is possible to hint default audiocodec to hls.js by configuring this value as below: - * mp4a.40.2 (AAC-LC) or - * mp4a.40.5 (HE-AAC) or - * undefined (guess based on sampling rate) - */ - defaultAudioCodec?: string; - /** - * (default: 1) - * number of segments needed to start a playback of Live stream. - */ - initialLiveManifestSize?: number; - /** - * (default: 30 seconds) - * Maximum buffer length in seconds. If buffer length is/become less than this value, a new fragment will be loaded. - * This is the guaranteed buffer length hls.js will try to reach, regardless of maxBufferSize. - */ - maxBufferLength?: number; - /** - * (default 600s) - * Maximum buffer length in seconds. Hls.js will never exceed this value, even if maxBufferSize is not reached yet. - * hls.js tries to buffer up to a maximum number of bytes (60 MB by default) rather than to buffer up to a maximum nb of seconds. - * This is to mimic the browser behaviour (the buffer eviction algorithm is starting after the browser detects that video buffer size reaches a limit in bytes) - * maxBufferLength is the minimum guaranteed buffer length that hls.js will try to achieve, even if that value exceeds the amount of bytes 60 MB of memory. - * maxMaxBufferLength acts as a capping value, as if bitrate is really low, you could need more than one hour of buffer to fill 60 MB. - */ - maxMaxBufferLength?: number; - /** - * (default: 60 MB) - * 'Minimum' maximum buffer size in bytes. If buffer size upfront is bigger than this value, no fragment will be loaded - */ - maxBufferSize?: number; - /** - * (default: 0.5 seconds) - * 'Maximum' inter-fragment buffer hole tolerance that hls.js can cope with when searching for the next fragment to load. When switching between quality level, - * fragments might not be perfectly aligned. - * This could result in small overlapping or hole in media buffer. This tolerance factor helps cope with this. - */ - maxBufferHole?: number; - /** - * (default: 4s) - * - * ABR algorithm will always try to choose a quality level that should avoid rebuffering. In case no quality level with this criteria can - * be found (lets say for example that buffer length is 1s, but fetching a fragment at lowest quality is predicted to take around 2s ... - * ie we can forecast around 1s of rebuffering ...) then ABR algorithm will try to find a level that should guarantee less than - * maxStarvationDelay of buffering. - */ - maxStarvationDelay?: number; - /** - * (default: 2s) - * In case playback is stalled, and a buffered range is available upfront, less than maxSeekHole seconds from current media position, - * hls.js will jump over this buffer hole to reach the beginning of this following buffered range. - * maxSeekHole allows to configure this jumpable threshold. - */ - maxSeekHole?: number; - /** - * (default: 0.5s) - * media element is expected to play and if currentTime has not moved for more than lowBufferWatchdogPeriod and if there are less than maxBufferHole seconds buffered upfront, - * hls.js will try to nudge playhead to recover playback - */ - lowBufferWatchdogPeriod?: number; - /** - * (default: 3s) - * if media element is expected to play and if currentTime has not moved for more than highBufferWatchdogPeriod and if there are more than maxBufferHole seconds buffered upfront, - * hls.js will try to nudge playhead to recover playback - */ - highBufferWatchdogPeriod?: number; - /** - * (default: 0.1s) - * In case playback continues to stall after first playhead nudging, currentTime will be nudged evenmore following nudgeOffset to try to restore playback. - * media.currentTime += (nb nudge retry -1)*nudgeOffset - */ - nudgeOffset?: number; - /** - * (default: 3s) - * In case playback continues to stall after first playhead nudging, currentTime will be nudged evenmore following nudgeOffset to try to restore playback. - * media.currentTime += (nb nudge retry -1)*nudgeOffset - */ - nudgeMaxRetry?: number; - /** - * (default 0.2s) - * This tolerance factor is used during fragment lookup. - * Instead of checking whether buffered.end is located within [start, end] range, frag lookup will be done by checking within [start-maxFragLookUpTolerance, end-maxFragLookUpTolerance] range. - * This tolerance factor is used to cope with situations like: - * buffered.end = 9.991 - * frag[0] : [0,10] - * frag[1] : [10,20] - * buffered.end is within frag[0] range, but as we are close to frag[1], frag[1] should be choosen instead - * If maxFragLookUpTolerance = 0.2, this lookup will be adjusted to - * frag[0] : [-0.2,9.8] - * frag[1] : [9.8,19.8] - * This time, buffered.end is within frag[1] range, and frag[1] will be the next fragment to be loaded, as expected - */ - maxLoadingDelay?: number; - /** - * (default 4s) - * - * 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 ) - */ - maxFragLookUpTolerance?: number; - /** - * (default: 3) - * edge of live delay, expressed in multiple of EXT-X-TARGETDURATION. if set to 3, playback will start from fragment N-3, N being the last fragment of the live playlist. - * Decreasing this value is likely to cause playback stalls. - */ - liveSyncDurationCount?: number; - /** - * (default: undefined) - * Alternative parameter to liveSyncDurationCount, expressed in seconds vs number of segments. - * If defined in the configuration object, liveSyncDuration will take precedence over the default liveSyncDurationCount. - * You can't define this parameter and either liveSyncDurationCount or liveMaxLatencyDurationCount in your configuration object at the same time. - * A value too low (inferior to ~3 segment durations) is likely to cause playback stalls. - */ - liveSyncDuration?: number; - /** - * (default: Infinity) - * maximum delay allowed from edge of live, expressed in multiple of EXT-X-TARGETDURATION. - * If set to 10, the player will seek back to liveSyncDurationCount whenever the next fragment to be loaded is older than N-10, N being the last fragment of the live playlist. - * If set, this value must be stricly superior to liveSyncDurationCount a value too close from liveSyncDurationCount is likely to cause playback stalls. - */ - liveMaxLatencyDurationCount?: number; - /** - * (default: undefined) - * Alternative parameter to liveMaxLatencyDurationCount, expressed in seconds vs number of segments. - * If defined in the configuration object, liveMaxLatencyDuration will take precedence over the default liveMaxLatencyDurationCount. - * If set, this value must be stricly superior to liveSyncDuration which must be defined as well. - * You can't define this parameter and either liveSyncDurationCount or liveMaxLatencyDurationCount in your configuration object at the same time. - * A value too close from liveSyncDuration is likely to cause playback stalls. - */ - liveMaxLatencyDuration?: number; - /** - * (default: true) - * Enable WebWorker (if available on browser) for TS demuxing/MP4 remuxing, to improve performance and avoid lag/frame drops. - */ - enableWorker?: boolean; - /** - * (default: true) - * Enable to use JavaScript version AES decryption for fallback of WebCrypto API. - */ - enableSoftwareAES?: boolean; - /** - * (default: undefined) - * When set, use this level as the default hls.startLevel. Keep in mind that the startLevel set with the API takes precedence over - * config.startLevel configuration parameter. - */ - startLevel?: number; - /** - * (default: 10000ms for level and manifest) - * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. - * It is up to the application to catch this event and treat it as needed. - */ - manifestLoadingTimeOut?: number; - /** - * (default: 3) - * Max number of load retries. - */ - manifestLoadingMaxRetry?: number; - /** - * (default: 1000 ms) - * Initial delay between XMLHttpRequest error and first load retry (in ms). - * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). - * Prefetch start fragment although media not attached. - */ - manifestLoadingRetryDelay?: number; - /** - * (default: 64000 ms) - * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. - */ - manifestLoadingMaxRetryTimeout?: number; - /** - * (default: 60000ms for fragment) - * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. - * It is up to the application to catch this event and treat it as needed. - */ - levelLoadingTimeOut?: number; - /** - * (default: 3) - * Max number of load retries. - */ - levelLoadingMaxRetry?: number; - /** - * (default: 1000 ms) - * Initial delay between XMLHttpRequest error and first load retry (in ms). - * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). - * Prefetch start fragment although media not attached. - */ - levelLoadingRetryDelay?: number; - /** - * (default: 64000 ms) - * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. - */ - levelLoadingMaxRetryTimeout?: number; - /** - * (default: 60000ms for fragment) - * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. - * It is up to the application to catch this event and treat it as needed. - */ - fragLoadingTimeOut?: number; - /** - * (default: 3) - * Max number of load retries. - */ - fragLoadingMaxRetry?: number; - /** - * (default: 1000 ms) - * Initial delay between XMLHttpRequest error and first load retry (in ms). - * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). - * Prefetch start fragment although media not attached. - */ - fragLoadingRetryDelay?: number; - /** - * (default: 64000 ms) - * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. - */ - fragLoadingMaxRetryDelay?: number; - /** - * (default: false) - * Start prefetching start fragment although media not attached yet. Max number of append retries. - */ - startFragPrefech?: boolean; - /** - * (default: 3) - * Max number of sourceBuffer.appendBuffer() retry upon error. Such error could happen in loop with UHD streams, when internal buffer is full. (Quota Exceeding Error will be triggered). - * In that case we need to wait for the browser to evict some data before being able to append buffer correctly. - */ - appendErrorMaxRetry?: number; - /** - * (default: standard XMLHttpRequest-based URL loader) - * Override standard URL loader by a custom one. Could be useful for P2P or stubbing (testing). - * Use this, if you want to overwrite both the fragment and the playlist loader. - * Note: If fLoader or pLoader are used, they overwrite loader! - */ - loader?: typeof Loader; - /** - * (default: undefined) - * This enables the manipulation of the fragment loader. - * Note: This will overwrite the default loader, as well as your own loader function. - */ - fLoader?: typeof Loader; - /** - * (default: undefined) - * This enables the manipulation of the playlist loader. - * Note: This will overwrite the default loader, as well as your own loader function. - */ - pLoader?: typeof Loader; - /** - * (default: undefined) - * XMLHttpRequest customization callback for default XHR based loader. - * Parameter should be a function with two arguments (xhr: XMLHttpRequest, url: string). - * If xhrSetup is specified, default loader will invoke it before calling xhr.send(). This allows user to easily modify/setup XHR. - */ - xhrSetup?(xhr: XMLHttpRequest, url: string): void; - /** - * (default: undefined) - * Fetch customization callback for Fetch based loader. - * Parameter should be a function with two arguments (context and Request Init Params). - * If fetchSetup is specified and Fetch loader is used, fetchSetup will be triggered to instantiate Request Object. This allows user to easily tweak Fetch loader. - */ - fetchSetup?(context: any, initParams: any): Request; - /** - * (default: internal ABR controller) - * Customized Adaptive Bitrate Streaming Controller. - * Parameter should be a class providing 2 getters, 2 setters and a destroy() method: - * get/set nextAutoLevel: return next auto-quality level/force next auto-quality level that should be returned (currently used for emergency switch down) - * get/set autoLevelCapping: capping/max level value that could be used by ABR Controller - * destroy(): should clean-up all used resources - */ - abrController?: AbrController; - /** - * (default: internal track timeline controller) - * Customized text track syncronization controller. - * Parameter should be a class with a destroy() method: - * destroy() : should clean-up all used resources - */ - timelineController?: TimelineController; - /** - * (default: true) - * whether or not to enable CEA-708 captions - */ - enableCEA708Captions?: boolean; - /** - * (default: English) - * Label for the text track generated for CEA-708 captions track 1. This is how it will appear in the browser's native menu for subtitles and captions. - */ - captionsTextTrack1Label?: string; - /** - * (default: en) - * RFC 3066 language code for the text track generated for CEA-708 captions track 1. - */ - captionsTextTrack1LanguagedCode?: string; - /** - * (default: Spanish) - * Label for the text track generated for CEA-708 captions track 2. This is how it will appear in the browser's native menu for subtitles and captions. - */ - captionsTextTrack2Label?: string; - /** - * (default: es) - * RFC 3066 language code for the text track generated for CEA-708 captions track 2. - */ - captionsTextTrack2LanguageCode?: string; - /** - * (default: false) - * If a segment's video track is shorter than its audio track by > min(maxSeekHole, maxBufferHole), extend the final video frame's duration to match the audio track's duration. - * This helps playback continue in certain cases that might otherwise get stuck. - */ - stretchShortVideoTrack?: boolean; - /** - * (default: true) - * Whether or not to force having a key frame in the first AVC sample after a discontinuity. - * If set to true, after a discontinuity, the AVC samples without any key frame will be dropped until finding one that contains a key frame. - * If set to false, all AVC samples will be kept, which can help avoid holes in the stream. Setting this parameter to false can also generate decoding weirdness when switching level or seeking. - */ - forceKeyFrameOnDiscontinuity?: boolean; - /** - * (default: 5.0) - * Fast bitrate Exponential moving average half-life, used to compute average bitrate for Live streams. - * Half of the estimate is based on the last abrEwmaFastLive seconds of sample history. Each of the sample is weighted by the fragment loading duration. - * parameter should be a float greater than 0 - */ - abrEwmaFastLive?: number; - /** - * (default: 9.0) - * Slow bitrate Exponential moving average half-life, used to compute average bitrate for Live streams. - * Half of the estimate is based on the last abrEwmaSlowLive seconds of sample history. Each of the sample is weighted by the fragment loading duration. - * parameter should be a float greater than abrEwmaFastLive - */ - abrEwmaSlowLive?: number; - /** - * (default: 4.0) - * Fast bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams. - * Half of the estimate is based on the last abrEwmaFastVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration. - * parameter should be a float greater than 0 - */ - abrEwmaFastVod?: number; - /** - * (default: 15.0) - * Slow bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams. - * Half of the estimate is based on the last abrEwmaSlowVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration. - * parameter should be a float greater than abrEwmaFastVoD - */ - abrEwmaSlowVod?: number; - /** - * (default: 500000) - * Default bandwidth estimate in bits/second prior to collecting fragment bandwidth samples. - * parameter should be a float - */ - abrEwmaDefaultEstimate?: number; - /** - * (default: 0.8) - * Scale factor to be applied against measured bandwidth average, to determine whether we can stay on current or lower quality level. - * If abrBandWidthFactor * bandwidth average < level.bitrate then ABR can switch to that level providing that it is equal or less than current level. - */ - abrBandWidthFactor?: number; - /** - * (default: 0.7) - * Scale factor to be applied against measured bandwidth average, to determine whether we can switch up to a higher quality level. - * If abrBandWidthUpFactor * bandwidth average < level.bitrate then ABR can switch up to that quality level. - */ - abrBandWidthUpFactor?: number; - /** - * (default: false) - * max bitrate used in ABR by avg measured bitrate i.e. if bitrate signaled in variant manifest for a given level is 2Mb/s but average bitrate measured on this level is 2.5Mb/s, - * then if config value is set to true, ABR will use 2.5 Mb/s for this quality level. - */ - abrMaxWithRealBitrate?: boolean; - /** - * (default: 0) - * Return the capping/min bandwidth value that could be used by automatic level selection algorithm. - * Useful when browser or tab of the browser is not in the focus and bandwidth drops - */ - minAutoBitrate?: number; - } - + const BUFFER_CODECS: string; /** - * a Level object represents a given quality level and contains quality level related info + * fired when sourcebuffers have been created + * data: { tracks: tracks } */ - interface Level { - /** - * level url. might contain sever items if failover/redundant streams are found in the manifest - */ - url: string[]; - /** - * level bitrate - */ - bitrate: number; - /** - * level name - */ - name: string; - /** - * used codecs - */ - codecs: string; - /** - * video width - */ - width: number; - /** - * video height - */ - height: number; - /** - * level details - */ - details: LevelDetails; - } - + const BUFFER_CREATED: string; /** - * a LevelDetails object contains level details retrieved after level playlist parsing + * fired when we append a segment to the buffer + * data: { segment: segment object } */ - interface LevelDetails { - /** - * protocol version - */ - version: number; - /** - * playlist type - */ - type: string; - /** - * start sequence number - */ - startSN: number; - /** - * end sequence number - */ - endSN: number; - /** - * level total duration - */ - totalduration: number; - /** - * level fragment target duration - */ - targetduration: number; - /** - * average fragment duration - */ - averagetargetduration: number; - /** - * array of fragments info - */ - fragments: Fragment[]; - /** - * is this level a live playlist or not? - */ - live: boolean; - } - + const BUFFER_APPENDING: string; /** - * the Fragment object contains fragment related info + * fired when we are done with appending a media segment to the buffer + * data: { parent : segment parent that triggered BUFFER_APPENDING, pending : nb of segments waiting for appending for this segment parent } */ - interface Fragment { - /** - * fragment duration - */ - duration: number; - /** - * fragment level identifier - */ - level: number; - /** - * fragment sequence number - */ - sn: number; - /** - * fragment start offset - */ - start: number; - /** - * fragment url - */ - url: string; - /** - * stream start date and time - */ - programDateTime: Date; - /** - * continuity count - */ - cc: number; - /** - * list of tags associated with the fragment - */ - tagList: string[][]; - /** - * fragment title - */ - title: string; - } - - interface Data { - /** - * videoElement - */ - video?: HTMLVideoElement; - /** - * media source - */ - mediaSource?: string; - /** - * manifest url - */ - url?: string; - /** - * available quality levels - */ - levels?: number[]; - /** - * available audio tracks - */ - audioTracks?: AudioTrack[]; - /** - * XMLHttp request stats - */ - stats?: HlsStats; - /** - * index of first quality level appearing in Manifest - */ - firstLevel?: number; - /** - * id of updated level - */ - level?: number; - /** - * id of loaded level - */ - levelId?: number; - /** - * ErrorDetails type - */ - details?: string; - /** - * PTS drift observed when parsing last fragment - */ - drift?: number; - /** - * fragment object with frag.loaded=stats.loaded - */ - frag?: Fragment; - /** - * fragment payload - */ - payload?: any; // TODO: what is the payload? - /** - * id of level or demuxer - */ - id?: number; - /** - * moof MP4 box - */ - moof?: any; // TODO: whats is the moof? - /** - * mdat MP4 box - */ - mdat?: any; // TODO: what is mdat? - /** - * PTS of first sample - */ - startPTS?: number; - /** - * PTS of last sample - */ - endPTS?: number; - /** - * DTS of first sample - */ - startDTS?: number; - /** - * DTS of last sample - */ - endDTS?: number; - /** - * stream type (audio or video) - */ - type?: string; - /** - * number of samples - */ - nb?: number; - /** - * number of dropped frames in last monitoring period - */ - currentDropped?: number; - /** - * number of decoded frames in last monitoring period - */ - currentDecode?: number; - /** - * total dropped frames on this video element - */ - totalDropped?: number; - /** - * level has to much dropped frame will be restricted - */ - droppedLevel?: number; - /** - * is error fatal or not. - * if error is not fatal, hls.js will try to recover it - * if error is fatal, an action is required to (try to) recover it - */ - fatal?: boolean; - } - + const BUFFER_APPENDED: string; /** - * (default: internal ABR controller) - * Customized Adaptive Bitrate Streaming Controller. + * fired when the stream is finished and we want to notify the media buffer that there will be no more data + * data: { } */ - interface AbrController { - /** - * get: capping/max level value that could be used by ABR Controller - * set: capping/max level value that could be used by ABR Controller - */ - autoLevelCapping: number; - /** - * accumulated handled events - */ - handledEvents: string[]; - /** - * current hls instance - */ - hls: Hls; - /** - * last fragments corresponding level - */ - lastLoadedFragLevel: number; - /** - * get: next auto-quality levele/force next auto-quality level that should be returned - * set: next auto-quality levele/force next auto-quality level that should be returned - * - currently used for emergency switch down - */ - nextAutoLevel: number; - useGenericHandler: boolean; - } - + const BUFFER_EOS: string; /** - * Customized text track syncronization controller. + * fired when the media buffer should be flushed + * data: { } */ - interface TimelineController { - /**d - * clean-up all used resources - */ - destory(): void; - } - - interface LoaderResponse { - url: string; - data: string | ArrayBuffer; - } - - interface LoaderStats { - /** - * performance.now() just after load() has been called - */ - trequest: number; - /** - * performance.now() of first received byte - */ - tfirst: number; - /** - * performance.now() on load complete - */ - tload: number; - /** - * number of loaded bytes - */ - loaded: number; - /** - * download bandwitdh in bit/s - */ - bw: number; - /** - * total nb of bytes - */ - total: number; - } - - interface LoaderError { - /** - * error code - */ - code: number; - /** - * error description - */ - text: string; - } - - interface HlsStats { - /** - * performance.now() just after load() has been called - */ - trequest: number; - /** - * performance.now() of first received byte - */ - tfirst: number; - /** - * performance.now() on load complete - */ - tload: number; - mtime: number; - tbuffered?: number; - length?: number; - } - - interface LoaderContext { - /** - * target URL - */ - url: string; - /** - * loader response type (arraybuffer or default response type for playlist) - */ - responseType: string; - /** - * start byte range offset - */ - rangeStart?: number; - /** - * end byte range offset - */ - rangeEnd?: number; - /** - * true if onProgress should report partial chunk of loaded content - */ - progressData?: boolean; - /** - * fragment object - */ - frag: Fragment; - /** - * request type - * - level, manifest - */ - type: string; - /** - * level id - */ - level: number; - } - - interface LoaderConfig { - /** - * Max number of load retries - */ - maxRetry: number; - /** - * Timeout after which `onTimeOut` callback will be triggered (if loading is still not finished after that delay) - */ - timeout: number; - /** - * Delay between an I/O error and following connection retry (ms). This to avoid spamming the server - */ - retryDelay: number; - /** - * max connection retry delay (ms) - */ - maxRetryDelay: number; - } - - interface LoaderCallbacks { - onSuccess(response: LoaderResponse, stats: LoaderStats, context: LoaderContext): void; - onProgress(stats: LoaderStats, context: LoaderContext, data: string | ArrayBuffer): void; - onError(error: LoaderError, context: LoaderContext): void; - onTimeout(stats: LoaderStats, context: LoaderContext): void; - } -} - -declare class Hls { + const BUFFER_FLUSHING: string; /** - * Constructor. Can be provided an HlsConfig object as default properties and or overrides + * fired when the media buffer has been flushed + * data: { } */ - constructor(config?: Hls.OptionalConfig) + const BUFFER_FLUSHED: string; /** - * return array of available quality levels + * fired to signal that a manifest loading starts + * data: { url : manifestURL } */ - levels: Hls.Level[]; + const MANIFEST_LOADING: string; /** - * get: return current playback quality level - * set: trigger an immediate quality level switch to new quality level - * this will pause the video if it was playing, flush the whole buffer, - * and fetch fragment matching with current position and requested quality level - * then resume the video if needed once fetched fragment will have been buffered - * - * set to -1 for automatic level selection + * fired after manifest has been loaded + * data: { levels : [available quality levels] , audioTracks : [ available audio tracks], url : manifestURL, stats : { trequest, tfirst, tload, mtime}} */ - currentLevel: number; + const MANIFEST_LOADED: string; /** - * capping/max level (index of level) that could be used by ABR Controller. Defaults to -1 - * which means no limit - * set: max level value that could be used by the ABR Controller + * fired after manifest has been parsed + * data: { levels : [ available quality levels ], firstLevel : index of first quality level appearing in Manifest } */ - autoLevelCapping: number; + const MANIFEST_PARSED: string; /** - * return start level index (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) - * - * default valus is hls.firstLevel + * fired when a level playlist loading starts + * data: { url : level URL, level : id of level being loaded } */ - startLevel: number; + const LEVEL_LOADING: string; + /** + * fired when a level playlist loading finishes + * data: { details : levelDetails object, levelId : id of loaded level, stats : { trequest, tfirst, tload, mtime } } + */ + const LEVEL_LOADED: string; + /** + * fired when a level's details have been updated based on previous details, after it has been loaded + * data: { details : levelDetails object, level : id of updated level } + */ + const LEVEL_UPDATED: string; + /** + * fired when a level's PTS information has been updated after parsing a fragment + * data: { details: levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment } + */ + const LEVEL_PTS_UPDATED: string; + /** + * fired when a level switch is requested + * data: { level: Level } + */ + const LEVEL_SWITCHING: string; + /** + * fired when a level switch is effective + * data: { level: level object } + */ + const LEVEL_SWITCHED: string; + /** + * fired to notify that audio track lists has been updated + * data: { audioTracks : audioTracks } + */ + const AUDIO_TRACKS_UPDATED: string; + /** + * fired when an audio track switch occurs. deprecated in favor AUDIO_TRACK_SWITCHING + * data: { id : audio track id } + */ + const AUDIO_TRACK_SWTICH: string; + /** + * fired when an audio track switching is requested + * data: { id : audio track id } + */ + const AUDIO_TRACK_SWITCHING: string; + /** + * fired when an audio track switch actually occurs + * data: { id : audio track id } + */ + const AUDIO_TRACK_SWITCHED: string; + /** + * fired when an audio track loading starts + * data: { url : audio track URL, id : audio track id } + */ + const AUDIO_TRACK_LOADING: string; + /** + * fired when an audio track loading finishes + * data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime } } + */ + const AUDIO_TRACK_LOADED: string; + /** + * fired to notify that subtitle track lists has been updated + * data: { subtitleTracks : subtitleTracks } + */ + const SUBTITLE_TRACKS_UPDATED: string; + /** + * fired when an subtitle track switch occurs + * data: { id : subtitle track id } + */ + const SUBTITLE_TRACK_SWITCH: string; + /** + * fired when a subtitle track loading starts + * data: { url : subtitle track URL, id : subtitle track id } + */ + const SUBTITLE_TRACK_LOADING: string; + /** + * fired when a subtitle track loading finishes + * data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime } } + */ + const SUBTITLE_TRACK_LOADED: string; + /** + * fired when a subtitle fragment has been processed + * data: { success : boolean, frag : the processed frag } + */ + const SUBTITLE_FRAG_PROCESSED: string; + /** + * fired when a decryption key loading starts + * data: { frag: fragment object } + */ + const KEY_LOADING: string; + /** + * fired when a decryption key loading is completed + * data: { frag: fragment object } + */ + const KEY_LOADED: string; + /** + * fired when first timestamp has been found + * data: { id: demuxer id, frag: fragment object, initPTS: initPTS } + */ + const INIT_PTS_FOUND: string; + /** + * fired when a fragment loading starts + * data: { frag : fragment object } + */ + const FRAG_LOADING: string; + /** + * fired when a fragment load is in progress + * data: { frag : fragment object with frag.loaded=stats.loaded, stats : { trequest, tfirst, loaded, total } } + */ + const FRAG_LOAD_PROGRESS: string; + /** + * identifier for fragment load aborting for emergency switch down + * data: { frag: fragment object } + */ + const FRAG_LOAD_ERMERGENCY_ABORTED: string; + /** + * fired when a fragment loading is completed + * data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length}} + */ + const FRAG_LOADED: string; + /** + * fired when a fragment decryption is completed + * data: { id: demuxer id, frag: fragment object, stats: { tstart, tdecrypt } } + */ + const FRAG_DECRYPTED: string; + /** + * fired when Init Segment has been extracted from fragment + * data: { id: demuxer id, moov : moov MP4 box, codecs : codecs found while parsing fragment} + */ + const FRAG_PARSING_INIT_SEGMENT: string; + /** + * fired when parsing id3 is completed + * data: { id: demuxer id, samples : [ id3 pes - pts and dts timestamp are relative, values are in seconds]} + */ + const FRAG_PARSING_METADATA: string; + /** + * fired when moof/mdat have been extracted from fragment + * data: { id: demuxer id, + * moof : moof MP4 box, + * mdat : mdat MP4 box, + * startPTS : PTS of first sample, + * endPTS : PTS of last sample, + * startDTS : DTS of first sample, + * endDTS : DTS of last sample, + * type : stream type (audio or video), + * nb : number of samples} + */ + const FRAG_PARSING_DATA: string; + /** + * fired when fragment parsing is completed + * data: { id: demuxer id} + */ + const FRAG_PARSED: string; + /** + * fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer + * data: { id: demuxer id, frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tbuffered, length} } + */ + const FRAG_BUFFERED: string; + /** + * fired when fragment matching with current video position is changing + * data: { frag : fragment object } + */ + const FRAG_CHANGED: string; + /** + * triggered when FPS drop in last monitoring period is higher than given threshold + * data: { curentDropped : nb of dropped frames in last monitoring period, + * currentDecoded : nb of decoded frames in last monitoring period, + * totalDropped : total dropped frames on this video element } + */ + const FPS_DROP: string; + /** + * triggered when FPS drop triggers auto level capping + * data: { level: suggested new auto level capping by fps controller, droppedLevel : level has to much dropped frame will be restricted } + */ + const FPS_DROP_LEVEL_CAPPING: string; + /** + * Identifier for an error event + * data: { type : error type, details : error details, fatal : is error fatal or not, other error specific data } + */ + const ERROR: string; + /** + * fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a video to the instance of hls.js to handle mid-rolls for example. + * data: { } + */ + const DESTROYING: string; + /** + * fired upon stream controller state transitions + * data: { previousState, nextState } + */ + const STREAM_STATE_TRANSITION: string; + } + + /** + * Hls error details + */ + namespace ErrorDetails { + // NETWORK_ERRORS // + /** + * raised when manifest loading fails because of a network error + * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.MANIFEST_LOAD_ERROR, fatal : true, url : manifest URL, response : { code: error code, text: error text }, loader : URL loader } + */ + const MANIFEST_LOAD_ERROR: string; + /** + * raised when manifest loading fails because of a timeout + * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.MANIFEST_LOAD_TIMEOUT, fatal : true, url : manifest URL, loader : URL loader } + */ + const MANIFEST_LOAD_TIMEOUT: string; + /** + * raised when manifest parsing failed to find proper content + * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.MANIFEST_PARSING_ERROR, fatal : true, url : manifest URL, reason : parsing error reason } + */ + const MANIFEST_PARSING_ERROR: string; + /** + * raised when level loading fails because of a network error + * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.LEVEL_LOAD_ERROR, fatal : true, url : level URL, response : { code: error code, text: error text }, loader : URL loader } + */ + const LEVEL_LOAD_ERROR: string; + /** + * raised when level loading fails because of a timeout + * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.LEVEL_LOAD_TIMEOUT, fatal : true, url : level URL, loader : URL loader } + */ + const LEVEL_LOAD_TIMEOUT: string; + /** + * raised when audio track loading fails because of a network error + * data: { type: NETWORK_ERROR, details: Hls.ErrorDetails.AUDIO_TRACK_LOAD_ERROR, fatal: false, url: audio URL, loader: URL loader } + */ + const AUDIO_TRACK_LOAD_ERROR: string; + /** + * raised when audio track loading fails because of a timeout + * data: { type: NETWORK_ERROR, details: Hls.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT, fatal: false, url: audio URL, response: { code: error code, text: error text }, loader: URL loader } + */ + const AUDIO_TRACK_LOAD_TIMEOUT: string; + /** + * raised when fragment loading fails because of a network error + * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.FRAG_LOAD_ERROR, fatal : true or false, frag : fragment object, response : { code: error code, text: error text } } + */ + const FRAG_LOAD_ERROR: string; + /** + * raised when fragment loading fails because of a timeout + * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.FRAG_LOAD_TIMEOUT, fatal : true or false, frag : fragment object } + */ + const FRAG_LOAD_TIMEOUT: string; + /** + * raised when decrypt key loading fails because of a network error + * data: { type: NETWORK_ERROR, details: Hls.ErrorDetails.KEY_LOAD_ERROR, fatal: false, frag: fragment object } + */ + const KEY_LOAD_ERROR: string; + /** + * raised when decrypt key loading fails because of timeout + * data: { type: NETWORK_EROR, details: Hls.ErrorDetails.KEY_LOAD_TIMEOUT, fatal: true, frag: fragment object } + */ + const KEY_LOAD_TIMEOUT: string; + + // MEDIA_ERRORS // + /** + * raised when manifest only contains quality level with codecs incompatible with MediaSource Engine. + * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR, fatal : true, url : manifest URL } + */ + const MANIFEST_INCOMPATIBLE_CODECS_ERROR: string; + /** + * raised upon detection of same fragment being requested in loop + * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.FRAG_LOOP_LOADING_ERROR, fatal : true or false, frag : fragment object } + */ + const FRAG_LOOP_LOADING_ERROR: string; + /** + * raised when fragment decryption fails + * data: { type: MEDIA_ERROR, details: Hls.ErrorDetails.FRAG_DECRYPT_ERROR, fatal: true, reason: failure reason } + */ + const FRAG_DECRYPT_ERROR: string; + /** + * raised when fragment parsing fails + * data: { type : NETWORK_ERROR, details : Hls.ErrorDetails.FRAG_PARSING_ERROR, fatal : true or false, reason : failure reason } + */ + const FRAG_PARSING_ERROR: string; + /** + * raised when MediaSource fails to add new sourceBuffer + * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_ADD_CODEC_ERROR, fatal : false, err : error raised by MediaSource, mimeType: mimeType on which the failure happened } + */ + const BUFFER_ADD_CODEC_ERROR: string; + /** + * raised when exception is raised while calling buffer append + * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_APPEND_ERROR, fatal : true, frag : fragment object } + */ + const BUFFER_APPEND_ERROR: string; + /** + * raised when exception is raised during buffer appending + * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_APPENDING_ERROR, fatal : false } + */ + const BUFFER_APPENDING_ERROR: string; + /** + * raised when playback is stuck because buffer is running out of data + * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_STALLED_ERROR, fatal : false } + */ + const BUFFER_STALLED_ERROR: string; + /** + * raised when no data can be appended anymore in media buffer because it is full. + * This error is recovered automatically by performing a smooth level switching that empty buffers (without disrupting the playback) and reducing the max buffer length. + * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_FULL_ERROR, fatal : false } + */ + const BUFFER_FULL_ERROR: string; + /** + * raised after hls.js seeks over a buffer hole to unstuck the playback, + * data: { type : MEDIA_ERROR, details : Hls.ErrorDetails.BUFFER_SEEK_OVER_HOLE, fatal : false, hole : hole duration } + */ + const BUFFER_SEEK_OVER_HOLE: string; + /** + * raised when playback is stuck although currentTime is in a buffered aread + * data: { type: MEDIA_ERROR, details: Hls.ErrorDetails.BUFFERED_STALLED_ERROR, fatal: true } + */ + const BUFFER_NUDGE_ON_STALL: string; + + // MUX_ERROR // + /** + * raised when memory allocation fails during remuxing + * data: { type: MUX_ERROR, details: Hls.ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes: mdat size, reason: failure reason } + */ + const REMUX_ALLOC_ERROR: string; + + // OTHER_ERROR // + /** + * raised when level switching fails + * data: { type : OTHER_ERROR, details : Hls.ErrorDetails.LEVEL_SWITCH_ERROR, fatal : false, level : failed level index, reason : failure reason } + */ + const LEVEL_SWITCH_ERROR: string; + /** + * raised when an exception occurs in an internal hls.js event handler + * data: { type: OTHER_ERROR, details: Hls.ErrorDetails.INTERNAL_EXCEPTION, fatal: true or false, event: event object or string, error: { message: error message } } + */ + const INTERNAL_EXCEPTION: string; + } + + /** + * Hls error types + */ + namespace ErrorTypes { + /** + * network related errors + */ + const NETWORK_ERROR: string; + /** + * media/video related errors + */ + const MEDIA_ERROR: string; + /** + * muxing related errors + */ + const MUX_ERROR: string; + /** + * all other erros + */ + const OTHER_ERROR: string; + } + /** + * override Hls default configuration + * this configuration will be applied by default to all instances + */ + let DefaultConfig: Config; + /** + * checks whether your browser is supporting MediaSource Extensions + */ + function isSupported(): boolean; + /** + * returns hls.js dist version number + */ + const version: string; + + interface Config { /** * (default: true) * if set to true, start level playlist and first fragments will be loaded automatically, after triggering of Hls.Events.MANIFEST_PARSED event @@ -1710,111 +474,1347 @@ declare class Hls { */ autoStartLoad: boolean; /** - * get: Return the bound videoElement from the hls instance + * (default -1) + * if set to -1, playback will start from initialTime=0 for VoD and according to liveSyncDuration/liveSyncDurationCount config params for Live + * otherwise, playback will start from predefined value. (unless stated otherwise in autoStartLoad=false mode : in that case startPosition can be overrided using hls.startLoad(startPosition)). */ - media: HTMLVideoElement; + startPosition: number; /** - * hls.js config + * (default: false) + * if set to true, the adaptive algorithm with limit levels usable in auto-quality by the HTML video element dimensions (width and height) + * if set to false, levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration. */ - config: Hls.Config; + capLevelToPlayerSize: boolean; /** - * get: return next playback quality level (playback quality level for next buffered fragment) - * return -1 if next fragment not buffered yet - * set: trigger a quality level switch for next fragment - * this could eventually flush already buffered next fragment + * (default: false) + * setting config.debug = true; will turn on debug logs on JS console. + * a logger object could also be provided for custom logging: config.debug = customLogger; + */ + debug: boolean; + /** + * (default: undefined) + * if audio codec is not signaled in variant manifest, or if only a stream manifest is provided, hls.js tries to guess audio codec by parsing audio sampling rate in ADTS header. + * If sampling rate is less or equal than 22050 Hz, then hls.js assumes it is HE-AAC, otherwise it assumes it is AAC-LC. + * This could result in bad guess, leading to audio decode error, ending up in media error. + * It is possible to hint default audiocodec to hls.js by configuring this value as below: + * mp4a.40.2 (AAC-LC) or + * mp4a.40.5 (HE-AAC) or + * undefined (guess based on sampling rate) + */ + defaultAudioCodec: string; + /** + * (default: 1) + * number of segments needed to start a playback of Live stream. + */ + initialLiveManifestSize: number; + /** + * (default: 30 seconds) + * Maximum buffer length in seconds. If buffer length is/become less than this value, a new fragment will be loaded. + * This is the guaranteed buffer length hls.js will try to reach, regardless of maxBufferSize. + */ + maxBufferLength: number; + /** + * (default 600s) + * Maximum buffer length in seconds. Hls.js will never exceed this value, even if maxBufferSize is not reached yet. + * hls.js tries to buffer up to a maximum number of bytes (60 MB by default) rather than to buffer up to a maximum nb of seconds. + * This is to mimic the browser behaviour (the buffer eviction algorithm is starting after the browser detects that video buffer size reaches a limit in bytes) + * maxBufferLength is the minimum guaranteed buffer length that hls.js will try to achieve, even if that value exceeds the amount of bytes 60 MB of memory. + * maxMaxBufferLength acts as a capping value, as if bitrate is really low, you could need more than one hour of buffer to fill 60 MB. + */ + maxMaxBufferLength: number; + /** + * (default: 60 MB) + * 'Minimum' maximum buffer size in bytes. If buffer size upfront is bigger than this value, no fragment will be loaded + */ + maxBufferSize: number; + /** + * (default: 0.5 seconds) + * 'Maximum' inter-fragment buffer hole tolerance that hls.js can cope with when searching for the next fragment to load. When switching between quality level, + * fragments might not be perfectly aligned. + * This could result in small overlapping or hole in media buffer. This tolerance factor helps cope with this. + */ + maxBufferHole: number; + /** + * (default: 4s) * - * set to -1 for automatic level selection + * ABR algorithm will always try to choose a quality level that should avoid rebuffering. In case no quality level with this criteria can + * be found (lets say for example that buffer length is 1s, but fetching a fragment at lowest quality is predicted to take around 2s ... + * ie we can forecast around 1s of rebuffering ...) then ABR algorithm will try to find a level that should guarantee less than + * maxStarvationDelay of buffering. */ - nextLevel: number; + maxStarvationDelay: number; /** - * get: return last loaded fragment quality level - * set: quality level for next loaded fragment - * set to -1 for automatic level selection + * (default: 2s) + * In case playback is stalled, and a buffered range is available upfront, less than maxSeekHole seconds from current media position, + * hls.js will jump over this buffer hole to reach the beginning of this following buffered range. + * maxSeekHole allows to configure this jumpable threshold. */ - loadLevel: number; + maxSeekHole: number; /** - * get: return quality level that will be used to load next fragment - * set: force quality level for next loaded fragment - * quality level will be forced only for that fragment - * after a fragment at this quality level has been loaded, hls.loadLevel will prevail + * (default: 0.5s) + * media element is expected to play and if currentTime has not moved for more than lowBufferWatchdogPeriod and if there are less than maxBufferHole seconds buffered upfront, + * hls.js will try to nudge playhead to recover playback */ - nextLoadLevel: number; + lowBufferWatchdogPeriod: number; /** - * first level index (index of first level appearing in Manifest. it is usually defined as start level hint for player) + * (default: 3s) + * if media element is expected to play and if currentTime has not moved for more than highBufferWatchdogPeriod and if there are more than maxBufferHole seconds buffered upfront, + * hls.js will try to nudge playhead to recover playback */ - firstLevel: number; + highBufferWatchdogPeriod: number; /** - * array of audio tracks exposed in manifest + * (default: 0.1s) + * In case playback continues to stall after first playhead nudging, currentTime will be nudged evenmore following nudgeOffset to try to restore playback. + * media.currentTime += (nb nudge retry -1)*nudgeOffset */ - audioTracks: AudioTrack[]; + nudgeOffset: number; /** - * get: returns audio track id - * set: sets audio track id (returned by) + * (default: 3s) + * In case playback continues to stall after first playhead nudging, currentTime will be nudged evenmore following nudgeOffset to try to restore playback. + * media.currentTime += (nb nudge retry -1)*nudgeOffset */ - audioTrack: number; + nudgeMaxRetry: number; /** - * position of live sync point (ie edge of live position minus safety delay defined by hls.config.liveSyncDuration) + * (default 0.2s) + * This tolerance factor is used during fragment lookup. + * Instead of checking whether buffered.end is located within [start, end] range, frag lookup will be done by checking within [start-maxFragLookUpTolerance, end-maxFragLookUpTolerance] range. + * This tolerance factor is used to cope with situations like: + * buffered.end = 9.991 + * frag[0] : [0,10] + * frag[1] : [10,20] + * buffered.end is within frag[0] range, but as we are close to frag[1], frag[1] should be choosen instead + * If maxFragLookUpTolerance = 0.2, this lookup will be adjusted to + * frag[0] : [-0.2,9.8] + * frag[1] : [9.8,19.8] + * This time, buffered.end is within frag[1] range, and frag[1] will be the next fragment to be loaded, as expected */ - liveSyncPosition: number; + maxLoadingDelay: number; /** - * calling this method will: - * bind videoElement and hls instances - * create MediaSource and set it as video source - * once MediaSource object is successfully created, MEDIA_ATTACHED event will be fired - */ - attachMedia(videoElement: HTMLVideoElement): void; - /** - * calling this method will: - * unbind VideoElement from hls instance - * signal the end of the stream on MediaSource - * reset video source ( video.src = '' ) - */ - detachMedia(): void; - /** - * tell whether auto level selection is enabled or not - */ - autoLevelEnabled(enabled: boolean): boolean; - /** - * loads provided url as media source - */ - loadSource(source: string): void; - /** - * by default, hls.js will automatically start loading quality level playlists, and fragments after Hls.Events.MANIFEST_PARSED event has been triggered (and video element has been attached) - * however if config.autoStartLoad is set to false, hls.startLoad() needs to be called to manually start playlist and fragments loading + * (default 4s) * - * start/restart playlist/fragment loading. this is only effective if MANIFEST_PARSED event has been triggered and video element has been attached to hls object - * startPosition is the initial position in the playlist - * ff startPosition is not set to -1, it allows to override default startPosition to the one you want - * (it will bypass hls.config.liveSync* config params for Live for example, so that user can start playback from whatever position) + * 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 ) */ - startLoad(startPosition?: number): void; + maxFragLookUpTolerance: number; /** - * stop playlist/fragment loading. could be resumed later on by calling hls.startLoad() + * (default: 3) + * edge of live delay, expressed in multiple of EXT-X-TARGETDURATION. if set to 3, playback will start from fragment N-3, N being the last fragment of the live playlist. + * Decreasing this value is likely to cause playback stalls. */ - stopLoad(): void; + liveSyncDurationCount: number; /** - * should be invoked to recover media error. + * (default: undefined) + * Alternative parameter to liveSyncDurationCount, expressed in seconds vs number of segments. + * If defined in the configuration object, liveSyncDuration will take precedence over the default liveSyncDurationCount. + * You can't define this parameter and either liveSyncDurationCount or liveMaxLatencyDurationCount in your configuration object at the same time. + * A value too low (inferior to ~3 segment durations) is likely to cause playback stalls. */ - recoverMediaError(): void; + liveSyncDuration: number; /** - * if media error are still raised after calling hls.recoverMediaError(), calling this method, could be useful to workaround audio codec mismatch. - * the workflow should be: - * on First Media Error : call hls.recoverMediaError() - * if another Media Error is raised 'quickly' after this first Media Error : first call hls.swapAudioCodec(), then call hls.recoverMediaError() + * (default: Infinity) + * maximum delay allowed from edge of live, expressed in multiple of EXT-X-TARGETDURATION. + * If set to 10, the player will seek back to liveSyncDurationCount whenever the next fragment to be loaded is older than N-10, N being the last fragment of the live playlist. + * If set, this value must be stricly superior to liveSyncDurationCount a value too close from liveSyncDurationCount is likely to cause playback stalls. */ - swapAudioCodec(): void; + liveMaxLatencyDurationCount: number; /** - * should be called to free used resources and destroy hls context + * (default: undefined) + * Alternative parameter to liveMaxLatencyDurationCount, expressed in seconds vs number of segments. + * If defined in the configuration object, liveMaxLatencyDuration will take precedence over the default liveMaxLatencyDurationCount. + * If set, this value must be stricly superior to liveSyncDuration which must be defined as well. + * You can't define this parameter and either liveSyncDurationCount or liveMaxLatencyDurationCount in your configuration object at the same time. + * A value too close from liveSyncDuration is likely to cause playback stalls. */ - destroy(): void; + liveMaxLatencyDuration: number; /** - * hls.js event listener + * (default: true) + * Enable WebWorker (if available on browser) for TS demuxing/MP4 remuxing, to improve performance and avoid lag/frame drops. */ - on(event: string, callback: (event: string, data: Hls.Data) => void): void; + enableWorker: boolean; /** - * remove hls.js event listener + * (default: true) + * Enable to use JavaScript version AES decryption for fallback of WebCrypto API. */ - off(event: string, callback: (event: string, data: Hls.Data) => void): void; + enableSoftwareAES: boolean; + /** + * (default: undefined) + * When set, use this level as the default hls.startLevel. Keep in mind that the startLevel set with the API takes precedence over + * config.startLevel configuration parameter. + */ + startLevel: number; + /** + * (default: 10000ms for level and manifest) + * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. + * It is up to the application to catch this event and treat it as needed. + */ + manifestLoadingTimeOut: number; + /** + * (default: 3) + * Max number of load retries. + */ + manifestLoadingMaxRetry: number; + /** + * (default: 1000 ms) + * Initial delay between XMLHttpRequest error and first load retry (in ms). + * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). + * Prefetch start fragment although media not attached. + */ + manifestLoadingRetryDelay: number; + /** + * (default: 64000 ms) + * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. + */ + manifestLoadingMaxRetryTimeout: number; + /** + * (default: 60000ms for fragment) + * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. + * It is up to the application to catch this event and treat it as needed. + */ + levelLoadingTimeOut: number; + /** + * (default: 3) + * Max number of load retries. + */ + levelLoadingMaxRetry: number; + /** + * (default: 1000 ms) + * Initial delay between XMLHttpRequest error and first load retry (in ms). + * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). + * Prefetch start fragment although media not attached. + */ + levelLoadingRetryDelay: number; + /** + * (default: 64000 ms) + * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. + */ + levelLoadingMaxRetryTimeout: number; + /** + * (default: 60000ms for fragment) + * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. + * It is up to the application to catch this event and treat it as needed. + */ + fragLoadingTimeOut: number; + /** + * (default: 3) + * Max number of load retries. + */ + fragLoadingMaxRetry: number; + /** + * (default: 1000 ms) + * Initial delay between XMLHttpRequest error and first load retry (in ms). + * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). + * Prefetch start fragment although media not attached. + */ + fragLoadingRetryDelay: number; + /** + * (default: 64000 ms) + * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. + */ + fragLoadingMaxRetryDelay: number; + /** + * (default: false) + * Start prefetching start fragment although media not attached yet. Max number of append retries. + */ + startFragPrefech: boolean; + /** + * (default: 3) + * Max number of sourceBuffer.appendBuffer() retry upon error. Such error could happen in loop with UHD streams, when internal buffer is full. (Quota Exceeding Error will be triggered). + * In that case we need to wait for the browser to evict some data before being able to append buffer correctly. + */ + appendErrorMaxRetry: number; + /** + * (default: standard XMLHttpRequest-based URL loader) + * Override standard URL loader by a custom one. Could be useful for P2P or stubbing (testing). + * Use this, if you want to overwrite both the fragment and the playlist loader. + * Note: If fLoader or pLoader are used, they overwrite loader! + */ + loader: typeof Loader; + /** + * (default: undefined) + * This enables the manipulation of the fragment loader. + * Note: This will overwrite the default loader, as well as your own loader function. + */ + fLoader?: typeof Loader; + /** + * (default: undefined) + * This enables the manipulation of the playlist loader. + * Note: This will overwrite the default loader, as well as your own loader function. + */ + pLoader?: typeof Loader; + /** + * (default: undefined) + * XMLHttpRequest customization callback for default XHR based loader. + * Parameter should be a function with two arguments (xhr: XMLHttpRequest, url: string). + * If xhrSetup is specified, default loader will invoke it before calling xhr.send(). This allows user to easily modify/setup XHR. + */ + xhrSetup?(xhr: XMLHttpRequest, url: string): void; + /** + * (default: undefined) + * Fetch customization callback for Fetch based loader. + * Parameter should be a function with two arguments (context and Request Init Params). + * If fetchSetup is specified and Fetch loader is used, fetchSetup will be triggered to instantiate Request Object. This allows user to easily tweak Fetch loader. + */ + fetchSetup?(context: any, initParams: any): Request; + /** + * (default: internal ABR controller) + * Customized Adaptive Bitrate Streaming Controller. + * Parameter should be a class providing 2 getters, 2 setters and a destroy() method: + * get/set nextAutoLevel: return next auto-quality level/force next auto-quality level that should be returned (currently used for emergency switch down) + * get/set autoLevelCapping: capping/max level value that could be used by ABR Controller + * destroy(): should clean-up all used resources + */ + abrController: AbrController; + /** + * (default: internal track timeline controller) + * Customized text track syncronization controller. + * Parameter should be a class with a destroy() method: + * destroy() : should clean-up all used resources + */ + timelineController: TimelineController; + /** + * (default: true) + * whether or not to enable CEA-708 captions + */ + enableCEA708Captions: boolean; + /** + * (default: English) + * Label for the text track generated for CEA-708 captions track 1. This is how it will appear in the browser's native menu for subtitles and captions. + */ + captionsTextTrack1Label: string; + /** + * (default: en) + * RFC 3066 language code for the text track generated for CEA-708 captions track 1. + */ + captionsTextTrack1LanguagedCode: string; + /** + * (default: Spanish) + * Label for the text track generated for CEA-708 captions track 2. This is how it will appear in the browser's native menu for subtitles and captions. + */ + captionsTextTrack2Label: string; + /** + * (default: es) + * RFC 3066 language code for the text track generated for CEA-708 captions track 2. + */ + captionsTextTrack2LanguageCode: string; + /** + * (default: false) + * If a segment's video track is shorter than its audio track by > min(maxSeekHole, maxBufferHole), extend the final video frame's duration to match the audio track's duration. + * This helps playback continue in certain cases that might otherwise get stuck. + */ + stretchShortVideoTrack: boolean; + /** + * (default: true) + * Whether or not to force having a key frame in the first AVC sample after a discontinuity. + * If set to true, after a discontinuity, the AVC samples without any key frame will be dropped until finding one that contains a key frame. + * If set to false, all AVC samples will be kept, which can help avoid holes in the stream. Setting this parameter to false can also generate decoding weirdness when switching level or seeking. + */ + forceKeyFrameOnDiscontinuity: boolean; + /** + * (default: 5.0) + * Fast bitrate Exponential moving average half-life, used to compute average bitrate for Live streams. + * Half of the estimate is based on the last abrEwmaFastLive seconds of sample history. Each of the sample is weighted by the fragment loading duration. + * parameter should be a float greater than 0 + */ + abrEwmaFastLive: number; + /** + * (default: 9.0) + * Slow bitrate Exponential moving average half-life, used to compute average bitrate for Live streams. + * Half of the estimate is based on the last abrEwmaSlowLive seconds of sample history. Each of the sample is weighted by the fragment loading duration. + * parameter should be a float greater than abrEwmaFastLive + */ + abrEwmaSlowLive: number; + /** + * (default: 4.0) + * Fast bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams. + * Half of the estimate is based on the last abrEwmaFastVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration. + * parameter should be a float greater than 0 + */ + abrEwmaFastVod: number; + /** + * (default: 15.0) + * Slow bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams. + * Half of the estimate is based on the last abrEwmaSlowVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration. + * parameter should be a float greater than abrEwmaFastVoD + */ + abrEwmaSlowVod: number; + /** + * (default: 500000) + * Default bandwidth estimate in bits/second prior to collecting fragment bandwidth samples. + * parameter should be a float + */ + abrEwmaDefaultEstimate: number; + /** + * (default: 0.8) + * Scale factor to be applied against measured bandwidth average, to determine whether we can stay on current or lower quality level. + * If abrBandWidthFactor * bandwidth average < level.bitrate then ABR can switch to that level providing that it is equal or less than current level. + */ + abrBandWidthFactor: number; + /** + * (default: 0.7) + * Scale factor to be applied against measured bandwidth average, to determine whether we can switch up to a higher quality level. + * If abrBandWidthUpFactor * bandwidth average < level.bitrate then ABR can switch up to that quality level. + */ + abrBandWidthUpFactor: number; + /** + * (default: false) + * max bitrate used in ABR by avg measured bitrate i.e. if bitrate signaled in variant manifest for a given level is 2Mb/s but average bitrate measured on this level is 2.5Mb/s, + * then if config value is set to true, ABR will use 2.5 Mb/s for this quality level. + */ + abrMaxWithRealBitrate: boolean; + /** + * (default: 0) + * Return the capping/min bandwidth value that could be used by automatic level selection algorithm. + * Useful when browser or tab of the browser is not in the focus and bandwidth drops + */ + minAutoBitrate: number; + } + + interface OptionalConfig { + /** + * (default: true) + * if set to true, start level playlist and first fragments will be loaded automatically, after triggering of Hls.Events.MANIFEST_PARSED event + * if set to false, an explicit API call (hls.startLoad(startPosition=-1)) will be needed to start quality level/fragment loading. + */ + autoStartLoad?: boolean; + /** + * (default -1) + * if set to -1, playback will start from initialTime=0 for VoD and according to liveSyncDuration/liveSyncDurationCount config params for Live + * otherwise, playback will start from predefined value. (unless stated otherwise in autoStartLoad=false mode : in that case startPosition can be overrided using hls.startLoad(startPosition)). + */ + startPosition?: number; + /** + * (default: false) + * if set to true, the adaptive algorithm with limit levels usable in auto-quality by the HTML video element dimensions (width and height) + * if set to false, levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration. + */ + capLevelToPlayerSize?: boolean; + /** + * (default: false) + * setting config.debug = true; will turn on debug logs on JS console. + * a logger object could also be provided for custom logging: config.debug = customLogger; + */ + debug?: boolean; + /** + * (default: undefined) + * if audio codec is not signaled in variant manifest, or if only a stream manifest is provided, hls.js tries to guess audio codec by parsing audio sampling rate in ADTS header. + * If sampling rate is less or equal than 22050 Hz, then hls.js assumes it is HE-AAC, otherwise it assumes it is AAC-LC. + * This could result in bad guess, leading to audio decode error, ending up in media error. + * It is possible to hint default audiocodec to hls.js by configuring this value as below: + * mp4a.40.2 (AAC-LC) or + * mp4a.40.5 (HE-AAC) or + * undefined (guess based on sampling rate) + */ + defaultAudioCodec?: string; + /** + * (default: 1) + * number of segments needed to start a playback of Live stream. + */ + initialLiveManifestSize?: number; + /** + * (default: 30 seconds) + * Maximum buffer length in seconds. If buffer length is/become less than this value, a new fragment will be loaded. + * This is the guaranteed buffer length hls.js will try to reach, regardless of maxBufferSize. + */ + maxBufferLength?: number; + /** + * (default 600s) + * Maximum buffer length in seconds. Hls.js will never exceed this value, even if maxBufferSize is not reached yet. + * hls.js tries to buffer up to a maximum number of bytes (60 MB by default) rather than to buffer up to a maximum nb of seconds. + * This is to mimic the browser behaviour (the buffer eviction algorithm is starting after the browser detects that video buffer size reaches a limit in bytes) + * maxBufferLength is the minimum guaranteed buffer length that hls.js will try to achieve, even if that value exceeds the amount of bytes 60 MB of memory. + * maxMaxBufferLength acts as a capping value, as if bitrate is really low, you could need more than one hour of buffer to fill 60 MB. + */ + maxMaxBufferLength?: number; + /** + * (default: 60 MB) + * 'Minimum' maximum buffer size in bytes. If buffer size upfront is bigger than this value, no fragment will be loaded + */ + maxBufferSize?: number; + /** + * (default: 0.5 seconds) + * 'Maximum' inter-fragment buffer hole tolerance that hls.js can cope with when searching for the next fragment to load. When switching between quality level, + * fragments might not be perfectly aligned. + * This could result in small overlapping or hole in media buffer. This tolerance factor helps cope with this. + */ + maxBufferHole?: number; + /** + * (default: 4s) + * + * ABR algorithm will always try to choose a quality level that should avoid rebuffering. In case no quality level with this criteria can + * be found (lets say for example that buffer length is 1s, but fetching a fragment at lowest quality is predicted to take around 2s ... + * ie we can forecast around 1s of rebuffering ...) then ABR algorithm will try to find a level that should guarantee less than + * maxStarvationDelay of buffering. + */ + maxStarvationDelay?: number; + /** + * (default: 2s) + * In case playback is stalled, and a buffered range is available upfront, less than maxSeekHole seconds from current media position, + * hls.js will jump over this buffer hole to reach the beginning of this following buffered range. + * maxSeekHole allows to configure this jumpable threshold. + */ + maxSeekHole?: number; + /** + * (default: 0.5s) + * media element is expected to play and if currentTime has not moved for more than lowBufferWatchdogPeriod and if there are less than maxBufferHole seconds buffered upfront, + * hls.js will try to nudge playhead to recover playback + */ + lowBufferWatchdogPeriod?: number; + /** + * (default: 3s) + * if media element is expected to play and if currentTime has not moved for more than highBufferWatchdogPeriod and if there are more than maxBufferHole seconds buffered upfront, + * hls.js will try to nudge playhead to recover playback + */ + highBufferWatchdogPeriod?: number; + /** + * (default: 0.1s) + * In case playback continues to stall after first playhead nudging, currentTime will be nudged evenmore following nudgeOffset to try to restore playback. + * media.currentTime += (nb nudge retry -1)*nudgeOffset + */ + nudgeOffset?: number; + /** + * (default: 3s) + * In case playback continues to stall after first playhead nudging, currentTime will be nudged evenmore following nudgeOffset to try to restore playback. + * media.currentTime += (nb nudge retry -1)*nudgeOffset + */ + nudgeMaxRetry?: number; + /** + * (default 0.2s) + * This tolerance factor is used during fragment lookup. + * Instead of checking whether buffered.end is located within [start, end] range, frag lookup will be done by checking within [start-maxFragLookUpTolerance, end-maxFragLookUpTolerance] range. + * This tolerance factor is used to cope with situations like: + * buffered.end = 9.991 + * frag[0] : [0,10] + * frag[1] : [10,20] + * buffered.end is within frag[0] range, but as we are close to frag[1], frag[1] should be choosen instead + * If maxFragLookUpTolerance = 0.2, this lookup will be adjusted to + * frag[0] : [-0.2,9.8] + * frag[1] : [9.8,19.8] + * This time, buffered.end is within frag[1] range, and frag[1] will be the next fragment to be loaded, as expected + */ + maxLoadingDelay?: number; + /** + * (default 4s) + * + * 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 ) + */ + maxFragLookUpTolerance?: number; + /** + * (default: 3) + * edge of live delay, expressed in multiple of EXT-X-TARGETDURATION. if set to 3, playback will start from fragment N-3, N being the last fragment of the live playlist. + * Decreasing this value is likely to cause playback stalls. + */ + liveSyncDurationCount?: number; + /** + * (default: undefined) + * Alternative parameter to liveSyncDurationCount, expressed in seconds vs number of segments. + * If defined in the configuration object, liveSyncDuration will take precedence over the default liveSyncDurationCount. + * You can't define this parameter and either liveSyncDurationCount or liveMaxLatencyDurationCount in your configuration object at the same time. + * A value too low (inferior to ~3 segment durations) is likely to cause playback stalls. + */ + liveSyncDuration?: number; + /** + * (default: Infinity) + * maximum delay allowed from edge of live, expressed in multiple of EXT-X-TARGETDURATION. + * If set to 10, the player will seek back to liveSyncDurationCount whenever the next fragment to be loaded is older than N-10, N being the last fragment of the live playlist. + * If set, this value must be stricly superior to liveSyncDurationCount a value too close from liveSyncDurationCount is likely to cause playback stalls. + */ + liveMaxLatencyDurationCount?: number; + /** + * (default: undefined) + * Alternative parameter to liveMaxLatencyDurationCount, expressed in seconds vs number of segments. + * If defined in the configuration object, liveMaxLatencyDuration will take precedence over the default liveMaxLatencyDurationCount. + * If set, this value must be stricly superior to liveSyncDuration which must be defined as well. + * You can't define this parameter and either liveSyncDurationCount or liveMaxLatencyDurationCount in your configuration object at the same time. + * A value too close from liveSyncDuration is likely to cause playback stalls. + */ + liveMaxLatencyDuration?: number; + /** + * (default: true) + * Enable WebWorker (if available on browser) for TS demuxing/MP4 remuxing, to improve performance and avoid lag/frame drops. + */ + enableWorker?: boolean; + /** + * (default: true) + * Enable to use JavaScript version AES decryption for fallback of WebCrypto API. + */ + enableSoftwareAES?: boolean; + /** + * (default: undefined) + * When set, use this level as the default hls.startLevel. Keep in mind that the startLevel set with the API takes precedence over + * config.startLevel configuration parameter. + */ + startLevel?: number; + /** + * (default: 10000ms for level and manifest) + * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. + * It is up to the application to catch this event and treat it as needed. + */ + manifestLoadingTimeOut?: number; + /** + * (default: 3) + * Max number of load retries. + */ + manifestLoadingMaxRetry?: number; + /** + * (default: 1000 ms) + * Initial delay between XMLHttpRequest error and first load retry (in ms). + * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). + * Prefetch start fragment although media not attached. + */ + manifestLoadingRetryDelay?: number; + /** + * (default: 64000 ms) + * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. + */ + manifestLoadingMaxRetryTimeout?: number; + /** + * (default: 60000ms for fragment) + * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. + * It is up to the application to catch this event and treat it as needed. + */ + levelLoadingTimeOut?: number; + /** + * (default: 3) + * Max number of load retries. + */ + levelLoadingMaxRetry?: number; + /** + * (default: 1000 ms) + * Initial delay between XMLHttpRequest error and first load retry (in ms). + * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). + * Prefetch start fragment although media not attached. + */ + levelLoadingRetryDelay?: number; + /** + * (default: 64000 ms) + * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. + */ + levelLoadingMaxRetryTimeout?: number; + /** + * (default: 60000ms for fragment) + * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. + * It is up to the application to catch this event and treat it as needed. + */ + fragLoadingTimeOut?: number; + /** + * (default: 3) + * Max number of load retries. + */ + fragLoadingMaxRetry?: number; + /** + * (default: 1000 ms) + * Initial delay between XMLHttpRequest error and first load retry (in ms). + * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). + * Prefetch start fragment although media not attached. + */ + fragLoadingRetryDelay?: number; + /** + * (default: 64000 ms) + * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. + */ + fragLoadingMaxRetryDelay?: number; + /** + * (default: false) + * Start prefetching start fragment although media not attached yet. Max number of append retries. + */ + startFragPrefech?: boolean; + /** + * (default: 3) + * Max number of sourceBuffer.appendBuffer() retry upon error. Such error could happen in loop with UHD streams, when internal buffer is full. (Quota Exceeding Error will be triggered). + * In that case we need to wait for the browser to evict some data before being able to append buffer correctly. + */ + appendErrorMaxRetry?: number; + /** + * (default: standard XMLHttpRequest-based URL loader) + * Override standard URL loader by a custom one. Could be useful for P2P or stubbing (testing). + * Use this, if you want to overwrite both the fragment and the playlist loader. + * Note: If fLoader or pLoader are used, they overwrite loader! + */ + loader?: typeof Loader; + /** + * (default: undefined) + * This enables the manipulation of the fragment loader. + * Note: This will overwrite the default loader, as well as your own loader function. + */ + fLoader?: typeof Loader; + /** + * (default: undefined) + * This enables the manipulation of the playlist loader. + * Note: This will overwrite the default loader, as well as your own loader function. + */ + pLoader?: typeof Loader; + /** + * (default: undefined) + * XMLHttpRequest customization callback for default XHR based loader. + * Parameter should be a function with two arguments (xhr: XMLHttpRequest, url: string). + * If xhrSetup is specified, default loader will invoke it before calling xhr.send(). This allows user to easily modify/setup XHR. + */ + xhrSetup?(xhr: XMLHttpRequest, url: string): void; + /** + * (default: undefined) + * Fetch customization callback for Fetch based loader. + * Parameter should be a function with two arguments (context and Request Init Params). + * If fetchSetup is specified and Fetch loader is used, fetchSetup will be triggered to instantiate Request Object. This allows user to easily tweak Fetch loader. + */ + fetchSetup?(context: any, initParams: any): Request; + /** + * (default: internal ABR controller) + * Customized Adaptive Bitrate Streaming Controller. + * Parameter should be a class providing 2 getters, 2 setters and a destroy() method: + * get/set nextAutoLevel: return next auto-quality level/force next auto-quality level that should be returned (currently used for emergency switch down) + * get/set autoLevelCapping: capping/max level value that could be used by ABR Controller + * destroy(): should clean-up all used resources + */ + abrController?: AbrController; + /** + * (default: internal track timeline controller) + * Customized text track syncronization controller. + * Parameter should be a class with a destroy() method: + * destroy() : should clean-up all used resources + */ + timelineController?: TimelineController; + /** + * (default: true) + * whether or not to enable CEA-708 captions + */ + enableCEA708Captions?: boolean; + /** + * (default: English) + * Label for the text track generated for CEA-708 captions track 1. This is how it will appear in the browser's native menu for subtitles and captions. + */ + captionsTextTrack1Label?: string; + /** + * (default: en) + * RFC 3066 language code for the text track generated for CEA-708 captions track 1. + */ + captionsTextTrack1LanguagedCode?: string; + /** + * (default: Spanish) + * Label for the text track generated for CEA-708 captions track 2. This is how it will appear in the browser's native menu for subtitles and captions. + */ + captionsTextTrack2Label?: string; + /** + * (default: es) + * RFC 3066 language code for the text track generated for CEA-708 captions track 2. + */ + captionsTextTrack2LanguageCode?: string; + /** + * (default: false) + * If a segment's video track is shorter than its audio track by > min(maxSeekHole, maxBufferHole), extend the final video frame's duration to match the audio track's duration. + * This helps playback continue in certain cases that might otherwise get stuck. + */ + stretchShortVideoTrack?: boolean; + /** + * (default: true) + * Whether or not to force having a key frame in the first AVC sample after a discontinuity. + * If set to true, after a discontinuity, the AVC samples without any key frame will be dropped until finding one that contains a key frame. + * If set to false, all AVC samples will be kept, which can help avoid holes in the stream. Setting this parameter to false can also generate decoding weirdness when switching level or seeking. + */ + forceKeyFrameOnDiscontinuity?: boolean; + /** + * (default: 5.0) + * Fast bitrate Exponential moving average half-life, used to compute average bitrate for Live streams. + * Half of the estimate is based on the last abrEwmaFastLive seconds of sample history. Each of the sample is weighted by the fragment loading duration. + * parameter should be a float greater than 0 + */ + abrEwmaFastLive?: number; + /** + * (default: 9.0) + * Slow bitrate Exponential moving average half-life, used to compute average bitrate for Live streams. + * Half of the estimate is based on the last abrEwmaSlowLive seconds of sample history. Each of the sample is weighted by the fragment loading duration. + * parameter should be a float greater than abrEwmaFastLive + */ + abrEwmaSlowLive?: number; + /** + * (default: 4.0) + * Fast bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams. + * Half of the estimate is based on the last abrEwmaFastVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration. + * parameter should be a float greater than 0 + */ + abrEwmaFastVod?: number; + /** + * (default: 15.0) + * Slow bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams. + * Half of the estimate is based on the last abrEwmaSlowVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration. + * parameter should be a float greater than abrEwmaFastVoD + */ + abrEwmaSlowVod?: number; + /** + * (default: 500000) + * Default bandwidth estimate in bits/second prior to collecting fragment bandwidth samples. + * parameter should be a float + */ + abrEwmaDefaultEstimate?: number; + /** + * (default: 0.8) + * Scale factor to be applied against measured bandwidth average, to determine whether we can stay on current or lower quality level. + * If abrBandWidthFactor * bandwidth average < level.bitrate then ABR can switch to that level providing that it is equal or less than current level. + */ + abrBandWidthFactor?: number; + /** + * (default: 0.7) + * Scale factor to be applied against measured bandwidth average, to determine whether we can switch up to a higher quality level. + * If abrBandWidthUpFactor * bandwidth average < level.bitrate then ABR can switch up to that quality level. + */ + abrBandWidthUpFactor?: number; + /** + * (default: false) + * max bitrate used in ABR by avg measured bitrate i.e. if bitrate signaled in variant manifest for a given level is 2Mb/s but average bitrate measured on this level is 2.5Mb/s, + * then if config value is set to true, ABR will use 2.5 Mb/s for this quality level. + */ + abrMaxWithRealBitrate?: boolean; + /** + * (default: 0) + * Return the capping/min bandwidth value that could be used by automatic level selection algorithm. + * Useful when browser or tab of the browser is not in the focus and bandwidth drops + */ + minAutoBitrate?: number; + } + + /** + * a Level object represents a given quality level and contains quality level related info + */ + interface Level { + /** + * level url. might contain sever items if failover/redundant streams are found in the manifest + */ + url: string[]; + /** + * level bitrate + */ + bitrate: number; + /** + * level name + */ + name: string; + /** + * used codecs + */ + codecs: string; + /** + * video width + */ + width: number; + /** + * video height + */ + height: number; + /** + * level details + */ + details: LevelDetails; + } + + /** + * a LevelDetails object contains level details retrieved after level playlist parsing + */ + interface LevelDetails { + /** + * protocol version + */ + version: number; + /** + * playlist type + */ + type: string; + /** + * start sequence number + */ + startSN: number; + /** + * end sequence number + */ + endSN: number; + /** + * level total duration + */ + totalduration: number; + /** + * level fragment target duration + */ + targetduration: number; + /** + * average fragment duration + */ + averagetargetduration: number; + /** + * array of fragments info + */ + fragments: Fragment[]; + /** + * is this level a live playlist or not? + */ + live: boolean; + } + + /** + * the Fragment object contains fragment related info + */ + interface Fragment { + /** + * fragment duration + */ + duration: number; + /** + * fragment level identifier + */ + level: number; + /** + * fragment sequence number + */ + sn: number; + /** + * fragment start offset + */ + start: number; + /** + * fragment url + */ + url: string; + /** + * stream start date and time + */ + programDateTime: Date; + /** + * continuity count + */ + cc: number; + /** + * list of tags associated with the fragment + */ + tagList: string[][]; + /** + * fragment title + */ + title: string; + } + + interface Data { + /** + * videoElement + */ + video?: HTMLVideoElement; + /** + * media source + */ + mediaSource?: string; + /** + * manifest url + */ + url?: string; + /** + * available quality levels + */ + levels?: number[]; + /** + * available audio tracks + */ + audioTracks?: AudioTrack[]; + /** + * XMLHttp request stats + */ + stats?: HlsStats; + /** + * index of first quality level appearing in Manifest + */ + firstLevel?: number; + /** + * id of updated level + */ + level?: number; + /** + * id of loaded level + */ + levelId?: number; + /** + * ErrorDetails type + */ + details?: string; + /** + * PTS drift observed when parsing last fragment + */ + drift?: number; + /** + * fragment object with frag.loaded=stats.loaded + */ + frag?: Fragment; + /** + * fragment payload + */ + payload?: any; // TODO: what is the payload? + /** + * id of level or demuxer + */ + id?: number; + /** + * moof MP4 box + */ + moof?: any; // TODO: whats is the moof? + /** + * mdat MP4 box + */ + mdat?: any; // TODO: what is mdat? + /** + * PTS of first sample + */ + startPTS?: number; + /** + * PTS of last sample + */ + endPTS?: number; + /** + * DTS of first sample + */ + startDTS?: number; + /** + * DTS of last sample + */ + endDTS?: number; + /** + * stream type (audio or video) + */ + type?: string; + /** + * number of samples + */ + nb?: number; + /** + * number of dropped frames in last monitoring period + */ + currentDropped?: number; + /** + * number of decoded frames in last monitoring period + */ + currentDecode?: number; + /** + * total dropped frames on this video element + */ + totalDropped?: number; + /** + * level has to much dropped frame will be restricted + */ + droppedLevel?: number; + /** + * is error fatal or not. + * if error is not fatal, hls.js will try to recover it + * if error is fatal, an action is required to (try to) recover it + */ + fatal?: boolean; + } + + /** + * (default: internal ABR controller) + * Customized Adaptive Bitrate Streaming Controller. + */ + interface AbrController { + /** + * get: capping/max level value that could be used by ABR Controller + * set: capping/max level value that could be used by ABR Controller + */ + autoLevelCapping: number; + /** + * accumulated handled events + */ + handledEvents: string[]; + /** + * current hls instance + */ + hls: Hls; + /** + * last fragments corresponding level + */ + lastLoadedFragLevel: number; + /** + * get: next auto-quality levele/force next auto-quality level that should be returned + * set: next auto-quality levele/force next auto-quality level that should be returned + * - currently used for emergency switch down + */ + nextAutoLevel: number; + useGenericHandler: boolean; + } + + /** + * Customized text track syncronization controller. + */ + interface TimelineController { + /**d + * clean-up all used resources + */ + destory(): void; + } + + interface LoaderResponse { + url: string; + data: string | ArrayBuffer; + } + + interface LoaderStats { + /** + * performance.now() just after load() has been called + */ + trequest: number; + /** + * performance.now() of first received byte + */ + tfirst: number; + /** + * performance.now() on load complete + */ + tload: number; + /** + * number of loaded bytes + */ + loaded: number; + /** + * download bandwitdh in bit/s + */ + bw: number; + /** + * total nb of bytes + */ + total: number; + } + + interface LoaderError { + /** + * error code + */ + code: number; + /** + * error description + */ + text: string; + } + + interface HlsStats { + /** + * performance.now() just after load() has been called + */ + trequest: number; + /** + * performance.now() of first received byte + */ + tfirst: number; + /** + * performance.now() on load complete + */ + tload: number; + mtime: number; + tbuffered?: number; + length?: number; + } + + interface LoaderContext { + /** + * target URL + */ + url: string; + /** + * loader response type (arraybuffer or default response type for playlist) + */ + responseType: string; + /** + * start byte range offset + */ + rangeStart?: number; + /** + * end byte range offset + */ + rangeEnd?: number; + /** + * true if onProgress should report partial chunk of loaded content + */ + progressData?: boolean; + /** + * fragment object + */ + frag: Fragment; + /** + * request type + * - level, manifest + */ + type: string; + /** + * level id + */ + level: number; + } + + interface LoaderConfig { + /** + * Max number of load retries + */ + maxRetry: number; + /** + * Timeout after which `onTimeOut` callback will be triggered (if loading is still not finished after that delay) + */ + timeout: number; + /** + * Delay between an I/O error and following connection retry (ms). This to avoid spamming the server + */ + retryDelay: number; + /** + * max connection retry delay (ms) + */ + maxRetryDelay: number; + } + + interface LoaderCallbacks { + onSuccess(response: LoaderResponse, stats: LoaderStats, context: LoaderContext): void; + onProgress(stats: LoaderStats, context: LoaderContext, data: string | ArrayBuffer): void; + onError(error: LoaderError, context: LoaderContext): void; + onTimeout(stats: LoaderStats, context: LoaderContext): void; + } +} + +declare class Hls { + /** + * Constructor. Can be provided an HlsConfig object as default properties and or overrides + */ + constructor(config?: Hls.OptionalConfig) + /** + * return array of available quality levels + */ + levels: Hls.Level[]; + /** + * get: return current playback quality level + * set: trigger an immediate quality level switch to new quality level + * this will pause the video if it was playing, flush the whole buffer, + * and fetch fragment matching with current position and requested quality level + * then resume the video if needed once fetched fragment will have been buffered + * + * set to -1 for automatic level selection + */ + currentLevel: number; + /** + * capping/max level (index of level) that could be used by ABR Controller. Defaults to -1 + * which means no limit + * set: max level value that could be used by the ABR Controller + */ + autoLevelCapping: number; + /** + * return start level index (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) + * + * default valus is hls.firstLevel + */ + startLevel: number; + /** + * (default: true) + * if set to true, start level playlist and first fragments will be loaded automatically, after triggering of Hls.Events.MANIFEST_PARSED event + * if set to false, an explicit API call (hls.startLoad(startPosition=-1)) will be needed to start quality level/fragment loading. + */ + autoStartLoad: boolean; + /** + * get: Return the bound videoElement from the hls instance + */ + media: HTMLVideoElement; + /** + * hls.js config + */ + config: Hls.Config; + /** + * get: return next playback quality level (playback quality level for next buffered fragment) + * return -1 if next fragment not buffered yet + * set: trigger a quality level switch for next fragment + * this could eventually flush already buffered next fragment + * + * set to -1 for automatic level selection + */ + nextLevel: number; + /** + * get: return last loaded fragment quality level + * set: quality level for next loaded fragment + * set to -1 for automatic level selection + */ + loadLevel: number; + /** + * get: return quality level that will be used to load next fragment + * set: force quality level for next loaded fragment + * quality level will be forced only for that fragment + * after a fragment at this quality level has been loaded, hls.loadLevel will prevail + */ + nextLoadLevel: number; + /** + * first level index (index of first level appearing in Manifest. it is usually defined as start level hint for player) + */ + firstLevel: number; + /** + * array of audio tracks exposed in manifest + */ + audioTracks: AudioTrack[]; + /** + * get: returns audio track id + * set: sets audio track id (returned by) + */ + audioTrack: number; + /** + * position of live sync point (ie edge of live position minus safety delay defined by hls.config.liveSyncDuration) + */ + liveSyncPosition: number; + /** + * calling this method will: + * bind videoElement and hls instances + * create MediaSource and set it as video source + * once MediaSource object is successfully created, MEDIA_ATTACHED event will be fired + */ + attachMedia(videoElement: HTMLVideoElement): void; + /** + * calling this method will: + * unbind VideoElement from hls instance + * signal the end of the stream on MediaSource + * reset video source ( video.src = '' ) + */ + detachMedia(): void; + /** + * tell whether auto level selection is enabled or not + */ + autoLevelEnabled(enabled: boolean): boolean; + /** + * loads provided url as media source + */ + loadSource(source: string): void; + /** + * by default, hls.js will automatically start loading quality level playlists, and fragments after Hls.Events.MANIFEST_PARSED event has been triggered (and video element has been attached) + * however if config.autoStartLoad is set to false, hls.startLoad() needs to be called to manually start playlist and fragments loading + * + * start/restart playlist/fragment loading. this is only effective if MANIFEST_PARSED event has been triggered and video element has been attached to hls object + * startPosition is the initial position in the playlist + * ff startPosition is not set to -1, it allows to override default startPosition to the one you want + * (it will bypass hls.config.liveSync* config params for Live for example, so that user can start playback from whatever position) + */ + startLoad(startPosition?: number): void; + /** + * stop playlist/fragment loading. could be resumed later on by calling hls.startLoad() + */ + stopLoad(): void; + /** + * should be invoked to recover media error. + */ + recoverMediaError(): void; + /** + * if media error are still raised after calling hls.recoverMediaError(), calling this method, could be useful to workaround audio codec mismatch. + * the workflow should be: + * on First Media Error : call hls.recoverMediaError() + * if another Media Error is raised 'quickly' after this first Media Error : first call hls.swapAudioCodec(), then call hls.recoverMediaError() + */ + swapAudioCodec(): void; + /** + * should be called to free used resources and destroy hls context + */ + destroy(): void; + /** + * hls.js event listener + */ + on(event: string, callback: (event: string, data: Hls.Data) => void): void; + /** + * remove hls.js event listener + */ + off(event: string, callback: (event: string, data: Hls.Data) => void): void; } export as namespace Hls; From 93b267aec8952541c74e043b48b699302f3589a0 Mon Sep 17 00:00:00 2001 From: Charles Bunton Date: Wed, 9 Aug 2017 14:49:26 -0400 Subject: [PATCH 27/29] Undeclared `DrawItems` and Unacceptable Value for `contentComponents` Attribute (#18359) * The method isn't declared type and the contentComponent attribute in doesn't accept methods that return a react element * changed drawItems declaration --- types/react-navigation/index.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index 66dcde29a0..b0f426862e 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -7,6 +7,7 @@ // petejkim // Kyle Roach // phanalpha +// charlesfamu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -523,13 +524,17 @@ export function StackNavigator( stackConfig?: StackNavigatorConfig, ): NavigationContainer; +// DrawerItems +export const DrawerItems: React.ComponentClass; + + /** * Drawer Navigator */ export interface DrawerViewConfig { drawerWidth: number, drawerPosition: 'left' | 'right', - contentComponent: React.ComponentClass, + contentComponent: (props: any) => React.ReactElement | React.ComponentClass, contentOptions?: any, style?: ViewStyle, } From 5a4f1ea15fae5f8a05bac3d2c75cd9c5ac0acaa5 Mon Sep 17 00:00:00 2001 From: Sukhdeep Singh Date: Wed, 9 Aug 2017 14:59:50 -0400 Subject: [PATCH 28/29] Update Materialize-css definitions to version 0.100.1 (#18316) * Definitions updated to version 0.100.1 * Reverted TypeScript version to 2.3.0 to correct CI build * fix TypeScript version once more * Format using tabs --- types/materialize-css/index.d.ts | 1113 +++++++++-------- .../materialize-css/materialize-css-tests.ts | 280 +++-- 2 files changed, 759 insertions(+), 634 deletions(-) diff --git a/types/materialize-css/index.d.ts b/types/materialize-css/index.d.ts index 18a5ac1feb..1cb283e2d7 100644 --- a/types/materialize-css/index.d.ts +++ b/types/materialize-css/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for materialize-css v0.98.0 +// Type definitions for materialize-css v0.100.1 // Project: http://materializecss.com/ -// Definitions by: Erik Lieben , Leon Yu , Sukhdeep Singh +// Definitions by: Erik Lieben +// Leon Yu +// Sukhdeep Singh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -9,588 +11,687 @@ declare namespace Materialize { - /** - * The collapsible options - */ - interface CollapsibleOptions { - /** - * A setting that changes the collapsible behavior to expandable instead of the default accordion style - */ - accordion?: boolean; + /** + * The collapsible options + */ + interface CollapsibleOptions { + /** + * A setting that changes the collapsible behavior to expandable instead of the default accordion style + */ + accordion?: boolean; - /** - * Callback for Collapsible section close. - * Default: function() { alert('Closed'); } - */ - onClose?: Function; + /** + * Callback for Collapsible section close. + * @default `function() { alert('Closed'); }` + */ + onClose?: Function; - /** - * Callback for Collapsible section open. - * Default: function() { alert('Opened'); } - */ - onOpen?: Function; - } + /** + * Callback for Collapsible section open. + * @default `function() { alert('Opened'); }` + */ + onOpen?: Function; + } - interface TooltipOptions { - /** - * The delay before the tooltip shows (in milliseconds) - */ - delay: number; - /** - * Tooltip text. Can use custom HTML if you set the html option - */ - tooltip?: string; - /** - * Set the direction of the tooltip. 'top', 'right', 'bottom', 'left'. - * - * (Default: 'bottom') - */ - position?: string; - /** - * Allow custom html inside the tooltip. - * - * (Default: false) - */ - html?: boolean; - } + interface TooltipOptions { + /** + * The delay before the tooltip shows (in milliseconds) + */ + delay: number; + /** + * Tooltip text. Can use custom HTML if you set the html option + */ + tooltip?: string; + /** + * Set the direction of the tooltip. 'top', 'right', 'bottom', 'left'. + * + * @default `'bottom'` + */ + position?: string; + /** + * Allow custom html inside the tooltip. + * + * @default `false` + */ + html?: boolean; + } - /** - * The dropdown options - */ - interface DropDownOptions { + /** + * The dropdown options + */ + interface DropDownOptions { - /** - * The duration of the transition enter in milliseconds. - * Default: 300 - */ - inDuration?: number; + /** + * The duration of the transition enter in milliseconds. + * @default `300` + */ + inDuration?: number; - /** - * The duration of the transition out in milliseconds. - * Default: 225 - */ - outDuration?: number; + /** + * The duration of the transition out in milliseconds. + * @default `225` + */ + outDuration?: number; - /** - * If true, constrainWidth to the size of the dropdown activator. - * Default: true - */ - constrainWidth?: boolean; - /** - * If true, the dropdown will open on hover. - * Default: false - */ - hover?: boolean; + /** + * If true, constrainWidth to the size of the dropdown activator. + * @default `true` + */ + constrainWidth?: boolean; + /** + * If true, the dropdown will open on hover. + * @default `false` + */ + hover?: boolean; - /** - * This defines the spacing from the aligned edge. - * Default: 0 - */ - gutter?: number; + /** + * This defines the spacing from the aligned edge. + * @default `0` + */ + gutter?: number; - /** - * If true, the dropdown will show below the activator. - * Default: false - */ - belowOrigin?: boolean; + /** + * If true, the dropdown will show below the activator. + * @default `false` + */ + belowOrigin?: boolean; - /** - * Defines the edge the menu is aligned to. - * Default: 'left' - */ - alignment?: string; - /** - * If true, stops the event propagating from the dropdown origin click handler. - * - * Default: false - */ - stopPropagation?: boolean - } + /** + * Defines the edge the menu is aligned to. + * @default `'left'` + */ + alignment?: string; + /** + * If true, stops the event propagating from the dropdown origin click handler. + * + * @default `false` + */ + stopPropagation?: boolean + } - /** - * The slider options - */ - interface SliderOptions { + /** + * The slider options + */ + interface SliderOptions { - /** - * Set to false to hide slide indicators. - * Default: true - */ - indicators?: boolean; + /** + * Set to false to hide slide indicators. + * @default `true` + */ + indicators?: boolean; - /** - * Set height of slider. - * Default: 400 - */ - height?: number; + /** + * Set height of slider. + * @default `400` + */ + height?: number; - /** - * Set the duration of the transition animation in ms. - * Default: 500 - */ - transition?: number; + /** + * Set the duration of the transition animation in ms. + * @default `500` + */ + transition?: number; - /** - * Set the duration between transitions in ms. - * Default: 6000 - */ - interval?: number; - } + /** + * Set the duration between transitions in ms. + * @default `6000` + */ + interval?: number; + } - /** - * The carousel options - */ - interface CarouselOptions { - /** - * Transition duration in milliseconds - * Default: 200 - */ - duration?: number; + /** + * The carousel options + */ + interface CarouselOptions { + /** + * Transition duration in milliseconds + * @default `200` + */ + duration?: number; - /** - * Perspective zoom. If 0, all items are the same size. - * Default: -100 - */ - dist?: number; + /** + * Perspective zoom. If 0, all items are the same size. + * @default `-100` + */ + dist?: number; - /** - * Set the duration of the transition animation in ms. - * Default: 500 - */ - shift?: number; + /** + * Set the duration of the transition animation in ms. + * @default `500` + */ + shift?: number; - /** - * Set the duration between transitions in ms. - * Default: 6000 - */ - padding?: number; + /** + * Set the duration between transitions in ms. + * @default `6000` + */ + padding?: number; - /** - * Set the width of the carousel. - * Default: false - */ - fullWidth?: boolean; - /** - * Set to true to show indicators. - * - * Default: false - */ - indicators?: boolean; - /** - * Don't wrap around and cycle through items. - * - * Default: false - */ - noWrap?: boolean; - } + /** + * Set the width of the carousel. + * @default `false` + */ + fullWidth?: boolean; + /** + * Set to true to show indicators. + * + * @default `false` + */ + indicators?: boolean; + /** + * Don't wrap around and cycle through items. + * + * @default `false` + */ + noWrap?: boolean; + } - /** - * The modal options - */ - interface ModalOptions { + /** + * The modal options + */ + interface ModalOptions { - /** - * Modal can be dismissed by clicking outside of the modal. - * Default: true - */ - dismissible?: boolean; + /** + * Modal can be dismissed by clicking outside of the modal. + * @default `true` + */ + dismissible?: boolean; - /** - * Opacity of modal background. - * Default. .5 - */ - opacity?: number; + /** + * Opacity of modal background. + * @default `.5` + */ + opacity?: number; - /** - * Transition in duration. - * Default: 300 - */ - inDuration?: number; + /** + * Transition in duration. + * @default `300` + */ + inDuration?: number; - /** - * Transition out duration. - * Default: 200 - */ - outDuration?: number; - /** - * Starting top style attribute - * Default: `4%` - */ - startingTop?: string; - /** - * Ending top style attribute - * Default : `10%` - */ - endingTop?: string; + /** + * Transition out duration. + * @default `200` + */ + outDuration?: number; + /** + * Starting top style attribute + * @default `4%` + */ + startingTop?: string; + /** + * Ending top style attribute + * @default `10%` + */ + endingTop?: string; - /** - * Callback for Modal open. - * Default: function() { alert('Ready'); } - */ - ready?: Function; + /** + * Callback for Modal open. + * @default `function() { alert('Ready'); }` + */ + ready?: Function; - /** - * Callback for Modal close. - * Default: function() { alert('Closed'); } - */ - complete?: Function; - } + /** + * Callback for Modal close. + * @default `function() { alert('Closed'); }` + */ + complete?: Function; + } - /** - * The push pin options - */ - interface PushpinOptions { + /** + * The push pin options + */ + interface PushpinOptions { - /** - * The distance in pixels from the top of the page where the element becomes fixed. - * Default: 0 - */ - top?: number; + /** + * The distance in pixels from the top of the page where the element becomes fixed. + * @default `0` + */ + top?: number; - /** - * The distance in pixels from the top of the page where the elements stops being fixed. - * Default: Infinity - */ - bottom?: number; + /** + * The distance in pixels from the top of the page where the elements stops being fixed. + * @default `Infinity` + */ + bottom?: number; - /** - * The offset from the top the element will be fixed at. - * Default: 0 - */ - offset?: number; - } + /** + * The offset from the top the element will be fixed at. + * @default `0` + */ + offset?: number; + } - /** - * The scroll spy options - */ - interface ScrollSpyOptions { - /** - * Offset from top. - * Default: 200 - */ - scrollOffset?: number; - } + /** + * The scroll spy options + */ + interface ScrollSpyOptions { + /** + * Offset from top. + * @default `200` + */ + scrollOffset?: number; + /** + * Class name to be added to the active link. + * @default `active` + */ + activeClass?: string; + /** + * Function that returns a selector to add activeClass to. The parameter is the section id + */ + getActiveElement?: Function; + } - /** - * The slideNav options - */ - interface SideNavOptions { - /** - * Default: 240 - */ - menuWidth?: number; + /** + * The slideNav options + */ + interface SideNavOptions { + /** + * @default `240` + */ + menuWidth?: number; - /** - * The horizontal origin - * Default: ' left' - */ - edge?: string; + /** + * The horizontal origin + * @default `'left'` + */ + edge?: string; - /** - * Closes side-nav on clicks, useful for Angular/Meteor - * Default: false - */ - closeOnClick?: boolean; + /** + * Closes side-nav on clicks, useful for Angular/Meteor + * @default `false` + */ + closeOnClick?: boolean; - /** - * Choose whether you can drag to open on touch screens - * Default: true - */ - draggable?: boolean; - } + /** + * Choose whether you can drag to open on touch screens + * @default `true` + */ + draggable?: boolean; + } - interface ScrollFireOptions { + interface ScrollFireOptions { - /** - * The selector for the element that is being tracked. - */ - selector?: string; + /** + * The selector for the element that is being tracked. + */ + selector?: string; - /** - * Offset to use when activating the scroll fire event - * If this is 0, the callback will be fired when the selector element is at the very bottom of the user's window. - */ - offset?: number; + /** + * Offset to use when activating the scroll fire event + * If this is 0, the callback will be fired when the selector element is at the very bottom of the user's window. + */ + offset?: number; - /** - * The string function call that you want to make when the user scrolls to the threshold. - * It will only be called once. - * Example: 'console.log("hello, world!")'; - * or callback: () => { console.log('hello world'); } - */ - callback?: string | (() => void); - } + /** + * The string function call that you want to make when the user scrolls to the threshold. + * It will only be called once. + * Example: 'console.log("hello, world!")'; + * or callback: () => { console.log('hello world'); } + */ + callback?: string | (() => void); + } - interface TabOptions { - /** - * Execute a callback function when the tab is changed. - * - * The callback provides a parameter which refers to the current tab being shown. - */ - onShow?: Function; + interface TabOptions { + /** + * Execute a callback function when the tab is changed. + * + * The callback provides a parameter which refers to the current tab being shown. + */ + onShow?: Function; - /** - * Set to true to enable swipeable tabs. This also uses the responsiveThreshold option. - * - * Default: false - */ - swipeable?: boolean; + /** + * Set to true to enable swipeable tabs. This also uses the responsiveThreshold option. + * + * @default `false` + */ + swipeable?: boolean; - /** - * The maximum width of the screen, in pixels, where the swipeable functionality initializes. - * - * Default: Infinity - */ - responsiveThreshold?: number; - } + /** + * The maximum width of the screen, in pixels, where the swipeable functionality initializes. + * + * @default `Infinity` + */ + responsiveThreshold?: number; + } - interface ChipDataObject { - tag: string, - image?: string, - id?: number - } + interface ChipDataObject { + tag: string, + image?: string, + id?: number + } - interface ChipOptions { - /** - * Set the chip data - */ - data?: Materialize.ChipDataObject[]; - /** - * Set first placeholder when there are no tags - */ - placeholder?: string; - /** - * Set second placeholder when adding additional tags. - */ - secondaryPlaceholder?: string; - /** - * Set autocomplete data. - */ - autocompleteData?: any; - /** - * Set autocomplete limit. - */ - autocompleteLimit?: number; - } + interface ChipOptions { + /** + * Set the chip data + */ + data?: Materialize.ChipDataObject[]; + /** + * Set first placeholder when there are no tags + */ + placeholder?: string; + /** + * Set second placeholder when adding additional tags. + */ + secondaryPlaceholder?: string; + /** + * Set autocomplete data. + */ + autocompleteData?: any; + /** + * Set autocomplete limit. + */ + autocompleteLimit?: number; + /** + * Set autocompleteOptions + */ + autocompleteOptions?: Materialize.AutoCompleteOptions; + } + interface AutoCompleteOptions { + /** + * The JSON object data to be used for the autocomplete suggetions list + */ + data: object; + /** + * The max amount of results that can be shown at once. + * @default `Infinity` + */ + limit?: number; + /** + * Callback function when value is autcompleted. + */ + onAutocomplete?: (val: any) => void; + /** + * The minimum length of the input for the autocomplete to start. + * @default `1` + */ + minLength?: number; - /** - * The Materialize object - */ - interface Materialize { + } - /** - * Displays a toast message on screen - * - * @name message The message to display on screen - * @name displayLength The duration in milliseconds to display the message on screen - * @name className The className to use to format the message to display - * @name completeCallback Callback function to call when the messages completes/hides. - */ - toast(message: string | JQuery, displayLength: number, className?: string, completeCallback?: Function): void; + interface Toast { + /** + * Dismiss all toasts + */ + removeAll: Function; + } - /** - * Fires an event when the page is scrolled to a certain area - * - * @name options optional parameter with scroll fire options - */ - scrollFire(options?: ScrollFireOptions[]): void; + /** + * The Materialize object + */ + interface Materialize { - /** - * A staggered reveal effect for any UL Tag with list items - * - * @name selector the selector for the list to show in staggered fasion - */ - showStaggeredList(selector: string): void; + /** + * Displays a toast message on screen + * + * @param string | JQuery message The message to display on screen + * @param number displayLength The duration in milliseconds to display the message on screen + * @param string className The className to use to format the message to display + * @param Function completeCallback Callback function to call when the messages completes/hides. + */ + toast(message: string | JQuery, displayLength: number, className?: string, completeCallback?: Function): void; - /** - * Fade in images. It also animates grayscale and brightness to give it a unique effect. - * - * @name selector the selector for the image to fade in - */ - fadeInImage(selector: string): void; + /** + * Fires an event when the page is scrolled to a certain area + * + * @param ScrollFireOptions options optional parameter with scroll fire options + */ + scrollFire(options?: ScrollFireOptions[]): void; - /** - * Update all text field to reinitialize all the Materialize labels on the page if dynamically adding inputs - */ - updateTextFields(): void; - } + /** + * A staggered reveal effect for any UL Tag with list items + * + * @param string selector the selector for the list to show in staggered fasion + */ + showStaggeredList(selector: string): void; + + /** + * Fade in images. It also animates grayscale and brightness to give it a unique effect. + * + * @param string selector the selector for the image to fade in + */ + fadeInImage(selector: string): void; + + /** + * Update all text field to reinitialize all the Materialize labels on the page if dynamically adding inputs + */ + updateTextFields(): void; + + /** + * Toast functions + */ + Toast: Materialize.Toast; + } +} + +/** + * Declare Pickadate namespace again in order to add more Materialize specific properties to TimeOptions interface + * + * @see http://www.typescriptlang.org/docs/handbook/declaration-merging.html + */ +declare namespace Pickadate { + export interface TimeOptions { + /** + * Set default time such as : 'now', '1:30AM', '16:30'. + * @default `'now'` + */ + default?: string; + /** + * set default time to * milliseconds from now (using with default = 'now') + * @default `0` + */ + fromnow?: number; + /** + * Use AM/PM or 24-hour format + * @default `false` + */ + twelvehour?: boolean; + /** + * text for done-button + * @default `'OK'` + */ + donetext?: string; + /** + * text for clear-button + * @default `'Clear'` + */ + cleartext?: string; + /** + * Text for cancel-button + * @default `'Cancel'` + */ + canceltext?: string; + /** + * automatic close timepicker + * @default `false` + */ + autoclose?: boolean; + /** + * make AM PM clickable + * @default `true` + */ + ampmclickable?: boolean; + /** + * Function for after opening timepicker + */ + aftershow?: Function; + } } declare var Materialize: Materialize.Materialize; interface JQuery { - /** - * open Fixed Action Button - */ - openFAB(): void; - /** - * close Fixed Action Button - */ - closeFAB(): void; + /** + * open Fixed Action Button + */ + openFAB(): void; + /** + * close Fixed Action Button + */ + closeFAB(): void; - /** - * Select allows user input through specified options. - * Initialization - */ - material_select(): void; + /** + * Select allows user input through specified options. + * + * @param string method "destroy" destroy the material select + */ + material_select(method?: string): void; - /** - * Select allows user input through specified options. - * Updating/Destroying Select - * - * @name method "destroy" destroy the material select - */ - material_select(method: string): void; + /** + * Use a character counter in fields where a character restriction is in place. + */ + characterCounter(): JQuery; - /** - * Use a character counter in fields where a character restriction is in place. - */ - characterCounter(): JQuery; + /** + * Collapsibles are accordion elements that expand when clicked on. + * They allow you to hide content that is not immediately relevant to the user. + * + * @param CollapsibleOptions options the collapsible options + */ + collapsible(options?: Materialize.CollapsibleOptions): JQuery; - /** - * Collapsibles are accordion elements that expand when clicked on. - * They allow you to hide content that is not immediately relevant to the user. - * - * @name options the collapsible options - */ - collapsible(options?: Materialize.CollapsibleOptions): JQuery; + /** + * Tooltips are small, interactive, textual hints for mainly graphical elements. + * When using icons for actions you can use a tooltip to give people clarification on its function. + * + * @param TooltipOptions | string options the tooltip options or the string "remove" to remove the tooltip function + */ + tooltip(options?: Materialize.TooltipOptions | string): JQuery; - /** - * Tooltips are small, interactive, textual hints for mainly graphical elements. - * When using icons for actions you can use a tooltip to give people clarification on its function. - * - * @name options the tooltip options or the string "remove" to remove the tooltip function - */ - tooltip(options?: Materialize.TooltipOptions | string): JQuery; + /** + * Add a dropdown list to any button. + * Make sure that the data-activates attribute matches the id in the