From 53db0897816810df904fbbbbda46fef65a1c1e1a Mon Sep 17 00:00:00 2001 From: Yann Normand Date: Fri, 9 Nov 2018 15:14:19 +1000 Subject: [PATCH 01/66] add a new generic for resource type --- types/react-big-calendar/index.d.ts | 28 +++++++-------- .../react-big-calendar-tests.tsx | 35 ++++++++++++++++--- 2 files changed, 44 insertions(+), 19 deletions(-) diff --git a/types/react-big-calendar/index.d.ts b/types/react-big-calendar/index.d.ts index bbfd7047ec..eba901bfc9 100644 --- a/types/react-big-calendar/index.d.ts +++ b/types/react-big-calendar/index.d.ts @@ -171,19 +171,19 @@ export class DateLocalizer { format(value: FormatInput, format: string, culture: Culture): string; } -export interface BigCalendarProps extends React.Props> { +export interface BigCalendarProps extends React.Props> { localizer: DateLocalizer; date?: stringOrDate; now?: Date; view?: View; - events?: T[]; + events?: TEvent[]; onNavigate?: (newDate: Date, action: Navigate) => void; onView?: (view: View) => void; onDrillDown?: (date: Date, view: View) => void; onSelectSlot?: (slotInfo: { start: stringOrDate, end: stringOrDate, slots: Date[] | string[], action: 'select' | 'click' | 'doubleClick' }) => void; - onDoubleClickEvent?: (event: T, e: React.SyntheticEvent) => void; - onSelectEvent?: (event: T, e: React.SyntheticEvent) => void; + onDoubleClickEvent?: (event: TEvent, e: React.SyntheticEvent) => void; + onSelectEvent?: (event: TEvent, e: React.SyntheticEvent) => void; onSelecting?: (range: { start: stringOrDate, end: stringOrDate }) => boolean | undefined | null; selected?: any; views?: View[] | { @@ -202,7 +202,7 @@ export interface BigCalendarProps extends React.Props { className?: string, style?: React.CSSProperties }; + eventPropGetter?: (event: TEvent, start: stringOrDate, end: stringOrDate, isSelected: boolean) => { className?: string, style?: React.CSSProperties }; slotPropGetter?: (date: Date) => { className?: string, style?: object }; dayPropGetter?: (date: Date) => { className?: string, style?: object }; showMultiDayTimes?: boolean; @@ -213,14 +213,14 @@ export interface BigCalendarProps extends React.Props string); - allDayAccessor?: keyof T | ((event: T) => boolean); - startAccessor?: keyof T | ((event: T) => Date); - endAccessor?: keyof T | ((event: T) => Date); - resourceAccessor?: keyof T | ((event: T) => any); - resources?: any[]; - resourceIdAccessor?: keyof T | ((event: T) => any); - resourceTitleAccessor?: keyof T | ((event: T) => string); + titleAccessor?: keyof TEvent | ((event: TEvent) => string); + allDayAccessor?: keyof TEvent | ((event: TEvent) => boolean); + startAccessor?: keyof TEvent | ((event: TEvent) => Date); + endAccessor?: keyof TEvent | ((event: TEvent) => Date); + resourceAccessor?: keyof TEvent | ((event: TEvent) => any); + resources?: TResource[]; + resourceIdAccessor?: keyof TResource | ((resource: TResource) => any); + resourceTitleAccessor?: keyof TResource | ((resource: TResource) => string); defaultView?: View; defaultDate?: Date; className?: string; @@ -237,7 +237,7 @@ export interface MoveOptions { today: Date; } -export default class BigCalendar extends React.Component> { +export default class BigCalendar extends React.Component> { components: { dateCellWrapper: React.ComponentType, dayWrapper: React.ComponentType, diff --git a/types/react-big-calendar/react-big-calendar-tests.tsx b/types/react-big-calendar/react-big-calendar-tests.tsx index e1b561901e..e50858c546 100644 --- a/types/react-big-calendar/react-big-calendar-tests.tsx +++ b/types/react-big-calendar/react-big-calendar-tests.tsx @@ -17,13 +17,25 @@ class CalendarEvent { start: Date; end: Date; desc: string; + resourceId?: string; - constructor(_title: string, _start: Date, _end: Date, _allDay?: boolean, _desc?: string) { + constructor(_title: string, _start: Date, _end: Date, _allDay?: boolean, _desc?: string, _resourceId?: string) { this.title = _title; this.allDay = _allDay || false; this.start = _start; this.end = _end; this.desc = _desc || ''; + this.resourceId = _resourceId; + } +} + +class CalendarResource { + title: string; + id: string; + + constructor(id: string, title: string) { + this.id = id; + this.title = title; } } @@ -51,10 +63,10 @@ class CalendarEvent { { // Full API Example Test - based on API Documentation // http://intljusticemission.github.io/react-big-calendar/examples/index.html#api - class FullAPIExample extends React.Component> { + class FullAPIExample extends React.Component> { render() { return ( - {...this.props} date={new Date()} view={'day'} @@ -81,9 +93,9 @@ class CalendarEvent { rtl={true} eventPropGetter={(event, start, end, isSelected) => ({ className: 'some-class' })} titleAccessor={'title'} - allDayAccessor={(event: any) => !!event.allDay} + allDayAccessor={(event: CalendarEvent) => !!event.allDay} startAccessor={'start'} - endAccessor={(event: any) => event.end || event.start} + endAccessor={(event: CalendarEvent) => event.end || event.start} min={new Date()} max={new Date()} scrollToTime={new Date()} @@ -106,6 +118,10 @@ class CalendarEvent { dayPropGetter={customDayPropGetter} slotPropGetter={customSlotPropGetter} defaultDate={new Date()} + resources={getResources()} + resourceAccessor={event => event.resourceId} + resourceIdAccessor={resource => resource.id} + resourceTitleAccessor={resource => resource.title} /> ); } @@ -130,10 +146,19 @@ function getEvents(): CalendarEvent[] { new CalendarEvent('Happy Hour', new Date(2015, 3, 12, 17, 0, 0, 0), new Date(2015, 3, 12, 17, 30, 0, 0), undefined, 'Most important meal of the day'), new CalendarEvent('Dinner', new Date(2015, 3, 12, 20, 0, 0, 0), new Date(2015, 3, 12, 21, 0, 0, 0)), new CalendarEvent('Birthday Party', new Date(2015, 3, 13, 7, 0, 0), new Date(2015, 3, 13, 10, 30, 0)), + new CalendarEvent('Alice\'s break', new Date(2015, 3, 14, 20, 0, 0, 0), new Date(2015, 3, 14, 21, 0, 0, 0), undefined, undefined, "alice"), + new CalendarEvent('Bob\'s break', new Date(2015, 3, 15, 7, 0, 0), new Date(2015, 3, 15, 10, 30, 0), undefined, undefined, "bob"), ]; return events; } +function getResources(): CalendarResource[] { + return [ + new CalendarResource('alice', 'Alice'), + new CalendarResource('bob', 'Bob') + ]; +} + class EventAgenda extends React.Component { render() { // const { label } = this.props; From fe1169f35d5b0b9f577674f6c1ea0e34f58871af Mon Sep 17 00:00:00 2001 From: Yann Normand Date: Fri, 9 Nov 2018 16:30:58 +1000 Subject: [PATCH 02/66] upgrade to TypeScript Version 2.9 --- types/react-big-calendar/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-big-calendar/index.d.ts b/types/react-big-calendar/index.d.ts index eba901bfc9..e7faf76ff4 100644 --- a/types/react-big-calendar/index.d.ts +++ b/types/react-big-calendar/index.d.ts @@ -6,7 +6,7 @@ // Sebastian Silbermann // Paul Potsides // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 2.9 import { Validator } from 'prop-types'; import * as React from 'react'; From 6ffd9f2bc60165a597b34cc1ea55ee823fccc851 Mon Sep 17 00:00:00 2001 From: Yann Normand Date: Fri, 9 Nov 2018 16:33:24 +1000 Subject: [PATCH 03/66] fix onNavigate function --- types/react-big-calendar/index.d.ts | 2 +- types/react-big-calendar/react-big-calendar-tests.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/react-big-calendar/index.d.ts b/types/react-big-calendar/index.d.ts index e7faf76ff4..0e7da106c2 100644 --- a/types/react-big-calendar/index.d.ts +++ b/types/react-big-calendar/index.d.ts @@ -178,7 +178,7 @@ export interface BigCalendarProps void; + onNavigate?: (newDate: Date, view: View, action: Navigate) => void; onView?: (view: View) => void; onDrillDown?: (date: Date, view: View) => void; onSelectSlot?: (slotInfo: { start: stringOrDate, end: stringOrDate, slots: Date[] | string[], action: 'select' | 'click' | 'doubleClick' }) => void; diff --git a/types/react-big-calendar/react-big-calendar-tests.tsx b/types/react-big-calendar/react-big-calendar-tests.tsx index e50858c546..4b80e8a72c 100644 --- a/types/react-big-calendar/react-big-calendar-tests.tsx +++ b/types/react-big-calendar/react-big-calendar-tests.tsx @@ -71,7 +71,7 @@ class CalendarResource { date={new Date()} view={'day'} events={getEvents()} - onNavigate={(newDate: Date, action: Navigate) => { }} + onNavigate={(newDate: Date, view: View, action: Navigate) => { }} onView={(view: View) => { }} onSelectSlot={(slotInfo) => { const start = slotInfo.start; From 2437acbc1cad793b1596fc0e3e5ed5318b0a8da9 Mon Sep 17 00:00:00 2001 From: IanStorm Date: Mon, 19 Nov 2018 19:33:40 +0100 Subject: [PATCH 04/66] Generated required package structure by running `dts-gen --dt` --- types/list-stream/index.d.ts | 39 ++++++++++++++++++++++++++ types/list-stream/list-stream-tests.ts | 0 types/list-stream/tsconfig.json | 22 +++++++++++++++ types/list-stream/tslint.json | 1 + 4 files changed, 62 insertions(+) create mode 100644 types/list-stream/index.d.ts create mode 100644 types/list-stream/list-stream-tests.ts create mode 100644 types/list-stream/tsconfig.json create mode 100644 types/list-stream/tslint.json diff --git a/types/list-stream/index.d.ts b/types/list-stream/index.d.ts new file mode 100644 index 0000000000..f331fcf838 --- /dev/null +++ b/types/list-stream/index.d.ts @@ -0,0 +1,39 @@ +// Type definitions for list-stream 1.0 +// Project: https://github.com/rvagg/list-stream +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/*~ If this module is a UMD module that exposes a global variable 'myLib' when + *~ loaded outside a module loader environment, declare that global here. + *~ Otherwise, delete this declaration. + */ +export as namespace myLib; + +/*~ If this module has methods, declare them as functions like so. + */ +export function myMethod(a: string): string; +export function myOtherMethod(a: number): number; + +/*~ You can declare types that are available via importing the module */ +export interface someType { + name: string; + length: number; + extras?: string[]; +} + +/*~ You can declare properties of the module using const, let, or var */ +export const myField: number; + +/*~ If there are types, properties, or methods inside dotted names + *~ of the module, declare them inside a 'namespace'. + */ +export namespace subProp { + /*~ For example, given this definition, someone could write: + *~ import { subProp } from 'yourModule'; + *~ subProp.foo(); + *~ or + *~ import * as yourMod from 'yourModule'; + *~ yourMod.subProp.foo(); + */ + export function foo(): void; +} \ No newline at end of file diff --git a/types/list-stream/list-stream-tests.ts b/types/list-stream/list-stream-tests.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/types/list-stream/tsconfig.json b/types/list-stream/tsconfig.json new file mode 100644 index 0000000000..ce92e0529c --- /dev/null +++ b/types/list-stream/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", + "list-stream-tests.ts" + ] +} diff --git a/types/list-stream/tslint.json b/types/list-stream/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/list-stream/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 4b09a1e10024bbf4852f6b210066dae080fc39f8 Mon Sep 17 00:00:00 2001 From: IanStorm Date: Mon, 19 Nov 2018 19:35:07 +0100 Subject: [PATCH 05/66] Editing author information --- types/list-stream/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/list-stream/index.d.ts b/types/list-stream/index.d.ts index f331fcf838..4024bd51ee 100644 --- a/types/list-stream/index.d.ts +++ b/types/list-stream/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for list-stream 1.0 // Project: https://github.com/rvagg/list-stream -// Definitions by: My Self +// Definitions by: IanStorm // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /*~ If this module is a UMD module that exposes a global variable 'myLib' when From 1074143fd85b1e4e1cc17b8ace89cf2c9c8a5b07 Mon Sep 17 00:00:00 2001 From: IanStorm Date: Mon, 19 Nov 2018 20:34:19 +0100 Subject: [PATCH 06/66] Added actual type definition and tests --- types/list-stream/index.d.ts | 47 ++++++++++---------------- types/list-stream/list-stream-tests.ts | 37 ++++++++++++++++++++ 2 files changed, 55 insertions(+), 29 deletions(-) diff --git a/types/list-stream/index.d.ts b/types/list-stream/index.d.ts index 4024bd51ee..8b97483cdb 100644 --- a/types/list-stream/index.d.ts +++ b/types/list-stream/index.d.ts @@ -3,37 +3,26 @@ // Definitions by: IanStorm // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/*~ If this module is a UMD module that exposes a global variable 'myLib' when - *~ loaded outside a module loader environment, declare that global here. - *~ Otherwise, delete this declaration. - */ -export as namespace myLib; +/// -/*~ If this module has methods, declare them as functions like so. - */ -export function myMethod(a: string): string; -export function myOtherMethod(a: number): number; -/*~ You can declare types that are available via importing the module */ -export interface someType { - name: string; - length: number; - extras?: string[]; +import { Duplex, DuplexOptions } from "stream"; + +declare namespace ListStream { } -/*~ You can declare properties of the module using const, let, or var */ -export const myField: number; +declare class ListStream extends Duplex { + constructor(callback?: (err: Error, data: any[]) => void); + constructor(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void); -/*~ If there are types, properties, or methods inside dotted names - *~ of the module, declare them inside a 'namespace'. - */ -export namespace subProp { - /*~ For example, given this definition, someone could write: - *~ import { subProp } from 'yourModule'; - *~ subProp.foo(); - *~ or - *~ import * as yourMod from 'yourModule'; - *~ yourMod.subProp.foo(); - */ - export function foo(): void; -} \ No newline at end of file + static obj(callback?: (err: Error, data: any[]) => void): ListStream; + static obj(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream; + + append(chunk: any): void; + duplicate(): ListStream; + end(): void; + get(index: number): any; + length: number; +} + +export = ListStream; diff --git a/types/list-stream/list-stream-tests.ts b/types/list-stream/list-stream-tests.ts index e69de29bb2..aefb41bf0c 100644 --- a/types/list-stream/list-stream-tests.ts +++ b/types/list-stream/list-stream-tests.ts @@ -0,0 +1,37 @@ +import * as ListStream from "list-stream"; + +let chunk: any = "chunk"; +let listStream: ListStream; +let num: number = 1; + +listStream = new ListStream((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = new ListStream({ objectMode: true }, (err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = ListStream.obj((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); + +listStream.append(chunk); + +listStream = listStream.duplicate(); + +listStream.end(); + +chunk = listStream.get(num); + +num = listStream.length; From 8bd0adc2267e15543719193222ccf5d202234646 Mon Sep 17 00:00:00 2001 From: IanStorm Date: Mon, 19 Nov 2018 20:46:35 +0100 Subject: [PATCH 07/66] Added `strictFunctionTypes` inside `tsconfig.json` as required for Merge Request --- types/list-stream/tsconfig.json | 1 + 1 file changed, 1 insertion(+) diff --git a/types/list-stream/tsconfig.json b/types/list-stream/tsconfig.json index ce92e0529c..52ec1c73e1 100644 --- a/types/list-stream/tsconfig.json +++ b/types/list-stream/tsconfig.json @@ -7,6 +7,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" From 0ee6ec5d83ce1b1be83a95f67674afc39998d871 Mon Sep 17 00:00:00 2001 From: IanStorm Date: Mon, 19 Nov 2018 21:04:02 +0100 Subject: [PATCH 08/66] Fixed issues raised by `npm test`: * `no-consecutive-blank-lines` * `no-inferrable-types` --- types/list-stream/index.d.ts | 1 - types/list-stream/list-stream-tests.ts | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/types/list-stream/index.d.ts b/types/list-stream/index.d.ts index 8b97483cdb..226d4c09ab 100644 --- a/types/list-stream/index.d.ts +++ b/types/list-stream/index.d.ts @@ -5,7 +5,6 @@ /// - import { Duplex, DuplexOptions } from "stream"; declare namespace ListStream { diff --git a/types/list-stream/list-stream-tests.ts b/types/list-stream/list-stream-tests.ts index aefb41bf0c..4b7fc2a6ab 100644 --- a/types/list-stream/list-stream-tests.ts +++ b/types/list-stream/list-stream-tests.ts @@ -2,7 +2,7 @@ import * as ListStream from "list-stream"; let chunk: any = "chunk"; let listStream: ListStream; -let num: number = 1; +let num = 1; listStream = new ListStream((err: Error, data: any[]) => { if (err) { throw err; } From d2dd41340a12ebef17e104a61309611a51cf1183 Mon Sep 17 00:00:00 2001 From: Yann Normand Date: Wed, 21 Nov 2018 10:25:41 +1000 Subject: [PATCH 09/66] downgrade to Typescript 2.8 --- types/react-big-calendar/index.d.ts | 2 +- .../react-big-calendar-tests.tsx | 118 +++++++++--------- 2 files changed, 60 insertions(+), 60 deletions(-) diff --git a/types/react-big-calendar/index.d.ts b/types/react-big-calendar/index.d.ts index 0d4da60aa4..89e6f0eead 100644 --- a/types/react-big-calendar/index.d.ts +++ b/types/react-big-calendar/index.d.ts @@ -7,7 +7,7 @@ // Paul Potsides // janb87 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.9 +// TypeScript Version: 2.8 import { Validator } from 'prop-types'; import * as React from 'react'; diff --git a/types/react-big-calendar/react-big-calendar-tests.tsx b/types/react-big-calendar/react-big-calendar-tests.tsx index 918c352e0c..fd1e70f929 100644 --- a/types/react-big-calendar/react-big-calendar-tests.tsx +++ b/types/react-big-calendar/react-big-calendar-tests.tsx @@ -61,70 +61,70 @@ class CalendarResource { } { + class MyCalendar extends BigCalendar {} + // Full API Example Test - based on API Documentation // http://intljusticemission.github.io/react-big-calendar/examples/index.html#api class FullAPIExample extends React.Component> { render() { return ( - - {...this.props} - date={new Date()} - view={'day'} - events={getEvents()} - onNavigate={(newDate: Date, view: View, action: Navigate) => { }} - onView={(view: View) => { }} - onSelectSlot={(slotInfo) => { - const start = slotInfo.start; - const end = slotInfo.end; - const slots = slotInfo.slots; - }} - onSelectEvent={(event) => { }} - onSelecting={(slotInfo) => { - const start = slotInfo.start; - const end = slotInfo.end; - return true; - }} - views={['day']} - toolbar={true} - popup={true} - popupOffset={20} - selectable={true} - step={20} - rtl={true} - eventPropGetter={(event, start, end, isSelected) => ({ className: 'some-class' })} - titleAccessor={'title'} - allDayAccessor={(event: CalendarEvent) => !!event.allDay} - startAccessor={'start'} - endAccessor={(event: CalendarEvent) => event.end || event.start} - min={new Date()} - max={new Date()} - scrollToTime={new Date()} - formats={{ - dateFormat: "h a", - agendaDateFormat: (date: Date, culture?: string, localizer?: object) => "some-format", - dayRangeHeaderFormat: (range: DateRange, culture?: string, localizer?: object) => "some-format" - }} - messages={{}} - timeslots={24} - defaultView={'month'} - className={'my-calendar'} - elementProps={{ id: 'myCalendar' }} - components={{ - event: Event, - agenda: { - event: EventAgenda - }, - toolbar: Toolbar, - eventWrapper: EventWrapper, - }} - dayPropGetter={customDayPropGetter} - slotPropGetter={customSlotPropGetter} - defaultDate={new Date()} - resources={getResources()} - resourceAccessor={event => event.resourceId} - resourceIdAccessor={resource => resource.id} - resourceTitleAccessor={resource => resource.title} - /> + { }} + onView={(view: View) => { }} + onSelectSlot={(slotInfo) => { + const start = slotInfo.start; + const end = slotInfo.end; + const slots = slotInfo.slots; + }} + onSelectEvent={(event) => { }} + onSelecting={(slotInfo) => { + const start = slotInfo.start; + const end = slotInfo.end; + return true; + }} + views={['day']} + toolbar={true} + popup={true} + popupOffset={20} + selectable={true} + step={20} + rtl={true} + eventPropGetter={(event, start, end, isSelected) => ({ className: 'some-class' })} + titleAccessor={'title'} + allDayAccessor={(event: CalendarEvent) => !!event.allDay} + startAccessor={'start'} + endAccessor={(event: CalendarEvent) => event.end || event.start} + min={new Date()} + max={new Date()} + scrollToTime={new Date()} + formats={{ + dateFormat: "h a", + agendaDateFormat: (date: Date, culture?: string, localizer?: object) => "some-format", + dayRangeHeaderFormat: (range: DateRange, culture?: string, localizer?: object) => "some-format" + }} + messages={{}} + timeslots={24} + defaultView={'month'} + className={'my-calendar'} + elementProps={{ id: 'myCalendar' }} + components={{ + event: Event, + agenda: { + event: EventAgenda + }, + toolbar: Toolbar, + eventWrapper: EventWrapper, + }} + dayPropGetter={customDayPropGetter} + slotPropGetter={customSlotPropGetter} + defaultDate={new Date()} + resources={getResources()} + resourceAccessor={event => event.resourceId} + resourceIdAccessor={resource => resource.id} + resourceTitleAccessor={resource => resource.title} /> ); } } From f6a44f54c73a0b255e7b36a1953824e518165996 Mon Sep 17 00:00:00 2001 From: IanStorm Date: Wed, 21 Nov 2018 22:04:54 +0100 Subject: [PATCH 10/66] * Added "test" for instantiating `ListStream` without `new` * Added "test" for using `write` on a `ListStream` instance --- types/list-stream/index.d.ts | 17 +++++++++++------ types/list-stream/list-stream-tests.ts | 17 +++++++++++++++++ 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/types/list-stream/index.d.ts b/types/list-stream/index.d.ts index 226d4c09ab..b51c9bacb0 100644 --- a/types/list-stream/index.d.ts +++ b/types/list-stream/index.d.ts @@ -7,16 +7,21 @@ import { Duplex, DuplexOptions } from "stream"; -declare namespace ListStream { +interface ListStreamMethod { + (callback?: (err: Error, data: any[]) => void): ListStream; + (options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream; } -declare class ListStream extends Duplex { - constructor(callback?: (err: Error, data: any[]) => void); - constructor(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void); +interface ListStreamConstructor extends ListStreamMethod { + new(callback?: (err: Error, data: any[]) => void): ListStream; + new(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream; - static obj(callback?: (err: Error, data: any[]) => void): ListStream; - static obj(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream; + obj: ListStreamMethod; +} +declare let ListStream: ListStreamConstructor; + +interface ListStream extends Duplex { append(chunk: any): void; duplicate(): ListStream; end(): void; diff --git a/types/list-stream/list-stream-tests.ts b/types/list-stream/list-stream-tests.ts index 4b7fc2a6ab..5f04626b31 100644 --- a/types/list-stream/list-stream-tests.ts +++ b/types/list-stream/list-stream-tests.ts @@ -4,6 +4,20 @@ let chunk: any = "chunk"; let listStream: ListStream; let num = 1; +listStream = ListStream((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = ListStream({ objectMode: true }, (err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); listStream = new ListStream((err: Error, data: any[]) => { if (err) { throw err; } console.log(data.length); @@ -26,6 +40,9 @@ listStream = ListStream.obj((err: Error, data: any[]) => { } }); +listStream = ListStream.obj(); +listStream.write({ key: "value" }); + listStream.append(chunk); listStream = listStream.duplicate(); From c830fd6999d65e1c02f3be796233fb380f396826 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 26 Nov 2018 21:00:12 +0100 Subject: [PATCH 11/66] Add types for create-hash --- types/create-hash/create-hash-tests.ts | 9 +++++++++ types/create-hash/index.d.ts | 26 ++++++++++++++++++++++++++ types/create-hash/tsconfig.json | 23 +++++++++++++++++++++++ types/create-hash/tslint.json | 1 + 4 files changed, 59 insertions(+) create mode 100644 types/create-hash/create-hash-tests.ts create mode 100644 types/create-hash/index.d.ts create mode 100644 types/create-hash/tsconfig.json create mode 100644 types/create-hash/tslint.json diff --git a/types/create-hash/create-hash-tests.ts b/types/create-hash/create-hash-tests.ts new file mode 100644 index 0000000000..d039a5a704 --- /dev/null +++ b/types/create-hash/create-hash-tests.ts @@ -0,0 +1,9 @@ +import createHash = require('create-hash'); + +const hash = createHash('sha224'); + +hash.update('synchronous write'); +hash.digest(); +hash.write('write to it as a stream'); +hash.end(); +hash.read(); diff --git a/types/create-hash/index.d.ts b/types/create-hash/index.d.ts new file mode 100644 index 0000000000..712be2520f --- /dev/null +++ b/types/create-hash/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for create-hash 1.2 +// Project: https://github.com/crypto-browserify/createHash +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +import { Hash } from 'crypto'; + +export = createHash; + +declare function createHash(algo: createHash.Algorithm): Hash; + +declare namespace createHash { + type Algorithm = + | 'md5' + | 'rmd160' + | 'ripemd160' + | 'sha' + | 'sha1' + | 'sha224' + | 'sha256' + | 'sha384' + | 'sha512'; +} diff --git a/types/create-hash/tsconfig.json b/types/create-hash/tsconfig.json new file mode 100644 index 0000000000..83e50b425c --- /dev/null +++ b/types/create-hash/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "create-hash-tests.ts" + ] +} diff --git a/types/create-hash/tslint.json b/types/create-hash/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/create-hash/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From afe5664ded8cec5ccf443e2dd682298f5b53c5b7 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 26 Nov 2018 21:41:06 +0100 Subject: [PATCH 12/66] Add types for sha.js --- types/sha.js/index.d.ts | 26 ++++++++++++++++++++++++++ types/sha.js/sha.js-tests.ts | 15 +++++++++++++++ types/sha.js/tsconfig.json | 23 +++++++++++++++++++++++ types/sha.js/tslint.json | 1 + 4 files changed, 65 insertions(+) create mode 100644 types/sha.js/index.d.ts create mode 100644 types/sha.js/sha.js-tests.ts create mode 100644 types/sha.js/tsconfig.json create mode 100644 types/sha.js/tslint.json diff --git a/types/sha.js/index.d.ts b/types/sha.js/index.d.ts new file mode 100644 index 0000000000..d5dc4ba752 --- /dev/null +++ b/types/sha.js/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for sha.js 2.4 +// Project: https://github.com/crypto-browserify/sha.js +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Hash } from 'crypto'; + +export = SHA; + +declare function SHA(algorithm: string): Hash; + +declare namespace SHA { + type Algorithm = 'sha' | 'sha1' | 'sha224' | 'sha256' | 'sha384' | 'sha512'; + interface HashStatic { + new (): Hash; + } + + const sha: HashStatic; + const sha1: HashStatic; + const sha224: HashStatic; + const sha256: HashStatic; + const sha384: HashStatic; + const sha512: HashStatic; +} diff --git a/types/sha.js/sha.js-tests.ts b/types/sha.js/sha.js-tests.ts new file mode 100644 index 0000000000..fd3cde2e47 --- /dev/null +++ b/types/sha.js/sha.js-tests.ts @@ -0,0 +1,15 @@ +import shajs = require('sha.js'); + +shajs('sha256') + .update('42') + .digest('hex'); +new shajs.sha().update('42').digest('hex'); +new shajs.sha1().update('42').digest('hex'); +new shajs.sha224().update('42').digest('hex'); +new shajs.sha256().update('42').digest('hex'); +new shajs.sha384().update('42').digest('hex'); +new shajs.sha512().update('42').digest('hex'); + +const sha256stream = shajs('sha256'); +sha256stream.end('42'); +(sha256stream.read() as Buffer).toString('hex'); diff --git a/types/sha.js/tsconfig.json b/types/sha.js/tsconfig.json new file mode 100644 index 0000000000..9f10462f5a --- /dev/null +++ b/types/sha.js/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sha.js-tests.ts" + ] +} diff --git a/types/sha.js/tslint.json b/types/sha.js/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sha.js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 9ed2a742a2989285e8ca98bbc3b3c418df508c72 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 26 Nov 2018 22:03:57 +0100 Subject: [PATCH 13/66] Add types for ripemd160 --- types/ripemd160/index.d.ts | 16 ++++++++++++++++ types/ripemd160/ripemd160-tests.ts | 7 +++++++ types/ripemd160/tsconfig.json | 23 +++++++++++++++++++++++ types/ripemd160/tslint.json | 1 + 4 files changed, 47 insertions(+) create mode 100644 types/ripemd160/index.d.ts create mode 100644 types/ripemd160/ripemd160-tests.ts create mode 100644 types/ripemd160/tsconfig.json create mode 100644 types/ripemd160/tslint.json diff --git a/types/ripemd160/index.d.ts b/types/ripemd160/index.d.ts new file mode 100644 index 0000000000..27de423a18 --- /dev/null +++ b/types/ripemd160/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for ripemd160 2.0 +// Project: https://github.com/crypto-browserify/ripemd160#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Hash } from 'crypto'; + +export = RIPEMD160; + +declare const RIPEMD160: RIPEMD160Static; + +interface RIPEMD160Static { + new (): Hash; +} diff --git a/types/ripemd160/ripemd160-tests.ts b/types/ripemd160/ripemd160-tests.ts new file mode 100644 index 0000000000..3a78efbac3 --- /dev/null +++ b/types/ripemd160/ripemd160-tests.ts @@ -0,0 +1,7 @@ +import RIPEMD160 = require('ripemd160'); + +new RIPEMD160().update('42').digest('hex'); + +const ripemd160stream = new RIPEMD160(); +ripemd160stream.end('42'); +(ripemd160stream.read() as Buffer).toString('hex'); diff --git a/types/ripemd160/tsconfig.json b/types/ripemd160/tsconfig.json new file mode 100644 index 0000000000..07abc9bd05 --- /dev/null +++ b/types/ripemd160/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ripemd160-tests.ts" + ] +} diff --git a/types/ripemd160/tslint.json b/types/ripemd160/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ripemd160/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 009260118e5ebe5a5afe3ebf749998d69e0e5ea7 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sun, 25 Nov 2018 23:53:43 +0100 Subject: [PATCH 14/66] Add types for saslmechanisms --- types/saslmechanisms/index.d.ts | 31 ++++++++++++++++++++ types/saslmechanisms/saslmechanisms-tests.ts | 22 ++++++++++++++ types/saslmechanisms/tsconfig.json | 23 +++++++++++++++ types/saslmechanisms/tslint.json | 1 + 4 files changed, 77 insertions(+) create mode 100644 types/saslmechanisms/index.d.ts create mode 100644 types/saslmechanisms/saslmechanisms-tests.ts create mode 100644 types/saslmechanisms/tsconfig.json create mode 100644 types/saslmechanisms/tslint.json diff --git a/types/saslmechanisms/index.d.ts b/types/saslmechanisms/index.d.ts new file mode 100644 index 0000000000..62f71e8a25 --- /dev/null +++ b/types/saslmechanisms/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for saslmechanisms 0.1 +// Project: https://github.com/jaredhanson/js-sasl +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = Factory; + +declare class Factory { + static Factory: typeof Factory; + + use(name: string, mechanism: Factory.MechanismStatic): this; + use(mechanism: Factory.MechanismStatic): this; + create(mechanisms: string[]): Factory.Mechanism | null; +} + +declare namespace Factory { + interface MechanismStatic { + new (): Mechanism; + prototype: { + [key: string]: any; + name: string; + }; + } + interface Mechanism { + name: string; + + response(cred: { [key: string]: any }): string; + + challenge(chal: string): void; + } +} diff --git a/types/saslmechanisms/saslmechanisms-tests.ts b/types/saslmechanisms/saslmechanisms-tests.ts new file mode 100644 index 0000000000..d7e6fe7620 --- /dev/null +++ b/types/saslmechanisms/saslmechanisms-tests.ts @@ -0,0 +1,22 @@ +import Fct = require('saslmechanisms'); +import { Factory, MechanismStatic, Mechanism } from 'saslmechanisms'; + +const Mech: MechanismStatic = null as any; + +const factory = new Fct(); +new Factory(); +new Factory.Factory(); + +// $ExpectType Factory +factory.use(Mech); +factory.use('Mech', Mech); + +const mech: Mechanism | null = factory.create(['Mech']); +if (mech) { + // $ExpectType string + mech.name; + // $ExpectType string + mech.response({ foo: 'bar' }); + // $ExpectType void + mech.challenge('challenge'); +} diff --git a/types/saslmechanisms/tsconfig.json b/types/saslmechanisms/tsconfig.json new file mode 100644 index 0000000000..64beedfc0f --- /dev/null +++ b/types/saslmechanisms/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "saslmechanisms-tests.ts" + ] +} diff --git a/types/saslmechanisms/tslint.json b/types/saslmechanisms/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/saslmechanisms/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 84d0e5f3c6ed696e578b99865567b4ad93814368 Mon Sep 17 00:00:00 2001 From: Tyler Date: Thu, 29 Nov 2018 11:24:47 -0700 Subject: [PATCH 15/66] update react-flatpickr definitions --- types/react-flatpickr/index.d.ts | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/types/react-flatpickr/index.d.ts b/types/react-flatpickr/index.d.ts index a0a9725ccd..973f30efc9 100644 --- a/types/react-flatpickr/index.d.ts +++ b/types/react-flatpickr/index.d.ts @@ -1,18 +1,26 @@ -// Type definitions for react-flatpickr 3.2 +// Type definitions for react-flatpickr 3.6.4 // Project: https://github.com/coderhaoxin/react-flatpickr // Definitions by: begincalendar +// snaveevans // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import { Component } from 'react'; -import flatpickr from 'flatpickr'; +import { Component } from "react"; +import flatpickr from "flatpickr"; export interface DateTimePickerProps { - defaultValue?: string; - options?: flatpickr.Options.Options; - onChange?: flatpickr.Options.Hook; - value?: string; - className?: string; + defaultValue?: string; + options?: flatpickr.Options.Options; + onChange?: flatpickr.Options.Hook; + onOpen?: flatpickr.Options.Hook; + onClose?: flatpickr.Options.Hook; + onMonthChange?: flatpickr.Options.Hook; + onYearChange?: flatpickr.Options.Hook; + onReady?: flatpickr.Options.Hook; + onValueUpdate?: flatpickr.Options.Hook; + onDayCreate?: flatpickr.Options.Hook; + value?: string | Date | number | Array; + children?: JSX.Element; } export default class DatePicker extends Component {} From f8ad24974118da570659fcaf7a6f35271e828f15 Mon Sep 17 00:00:00 2001 From: Tyler Date: Thu, 29 Nov 2018 11:42:10 -0700 Subject: [PATCH 16/66] refactor react-flatpickr test --- .../react-flatpickr/react-flatpickr-tests.tsx | 50 ++++++++++++++----- 1 file changed, 38 insertions(+), 12 deletions(-) diff --git a/types/react-flatpickr/react-flatpickr-tests.tsx b/types/react-flatpickr/react-flatpickr-tests.tsx index 452d8529b4..ce7122a47f 100644 --- a/types/react-flatpickr/react-flatpickr-tests.tsx +++ b/types/react-flatpickr/react-flatpickr-tests.tsx @@ -1,22 +1,48 @@ -import flatpickr from 'flatpickr'; -import * as React from 'react'; -import DatePicker from 'react-flatpickr'; +import flatpickr from "flatpickr"; +import * as React from "react"; +import DatePicker from "react-flatpickr"; -const noParamsElement = ; +const noParamsElement = ; -const defaultValueElement = ; +const defaultValueElement = ; const options = { - dateFormat: 'YYYY-MM-DD' + dateFormat: "YYYY-MM-DD" }; -const optionsElement = ; +const optionsElement = ; -const onChange = ( - selectedDates: Date[], dateStr: string, instance: flatpickr.Instance, +const hook = ( + selectedDates: Date[], + dateStr: string, + instance: flatpickr.Instance, elem: HTMLElement ) => null; -const onChangeElement = ; +const onChangeElement = ; +const onOpenElement = ; +const onCloseElement = ; +const onMonthChangeElement = ; +const onYearChangeElement = ; +const onReadyElement = ; +const onValueUpdateElement = ; +const onDayCreateElement = ; -const valueElement = ; +const valueStringElement = ; +const valueDateElement = ; +const valueNumberElement = ; +const valueStringArrayElement = ( + +); +const valueDateArrayElement = ( + +); +const valueNumberArrayElement = ( + +); -const classNameElement = ; +const wrappedElement = ( + + + +); From 0085b9868c6252a56fed4690444231dbd8cb8099 Mon Sep 17 00:00:00 2001 From: Tyler Date: Thu, 29 Nov 2018 11:45:23 -0700 Subject: [PATCH 17/66] react-flatpickr remove minor version --- types/react-flatpickr/index.d.ts | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/types/react-flatpickr/index.d.ts b/types/react-flatpickr/index.d.ts index 973f30efc9..9f60b4d7be 100644 --- a/types/react-flatpickr/index.d.ts +++ b/types/react-flatpickr/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-flatpickr 3.6.4 +// Type definitions for react-flatpickr 3.6 // Project: https://github.com/coderhaoxin/react-flatpickr // Definitions by: begincalendar // snaveevans @@ -9,18 +9,18 @@ import { Component } from "react"; import flatpickr from "flatpickr"; export interface DateTimePickerProps { - defaultValue?: string; - options?: flatpickr.Options.Options; - onChange?: flatpickr.Options.Hook; - onOpen?: flatpickr.Options.Hook; - onClose?: flatpickr.Options.Hook; - onMonthChange?: flatpickr.Options.Hook; - onYearChange?: flatpickr.Options.Hook; - onReady?: flatpickr.Options.Hook; - onValueUpdate?: flatpickr.Options.Hook; - onDayCreate?: flatpickr.Options.Hook; - value?: string | Date | number | Array; - children?: JSX.Element; + defaultValue?: string; + options?: flatpickr.Options.Options; + onChange?: flatpickr.Options.Hook; + onOpen?: flatpickr.Options.Hook; + onClose?: flatpickr.Options.Hook; + onMonthChange?: flatpickr.Options.Hook; + onYearChange?: flatpickr.Options.Hook; + onReady?: flatpickr.Options.Hook; + onValueUpdate?: flatpickr.Options.Hook; + onDayCreate?: flatpickr.Options.Hook; + value?: string | Date | number | Array; + children?: JSX.Element; } export default class DatePicker extends Component {} From c652a0afb4330ca150f1755bba040cf72b4ec5f5 Mon Sep 17 00:00:00 2001 From: Tyler Date: Thu, 29 Nov 2018 11:47:37 -0700 Subject: [PATCH 18/66] Revert "react-flatpickr remove minor version" This reverts commit 0085b9868c6252a56fed4690444231dbd8cb8099. --- types/react-flatpickr/index.d.ts | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/types/react-flatpickr/index.d.ts b/types/react-flatpickr/index.d.ts index 9f60b4d7be..973f30efc9 100644 --- a/types/react-flatpickr/index.d.ts +++ b/types/react-flatpickr/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-flatpickr 3.6 +// Type definitions for react-flatpickr 3.6.4 // Project: https://github.com/coderhaoxin/react-flatpickr // Definitions by: begincalendar // snaveevans @@ -9,18 +9,18 @@ import { Component } from "react"; import flatpickr from "flatpickr"; export interface DateTimePickerProps { - defaultValue?: string; - options?: flatpickr.Options.Options; - onChange?: flatpickr.Options.Hook; - onOpen?: flatpickr.Options.Hook; - onClose?: flatpickr.Options.Hook; - onMonthChange?: flatpickr.Options.Hook; - onYearChange?: flatpickr.Options.Hook; - onReady?: flatpickr.Options.Hook; - onValueUpdate?: flatpickr.Options.Hook; - onDayCreate?: flatpickr.Options.Hook; - value?: string | Date | number | Array; - children?: JSX.Element; + defaultValue?: string; + options?: flatpickr.Options.Options; + onChange?: flatpickr.Options.Hook; + onOpen?: flatpickr.Options.Hook; + onClose?: flatpickr.Options.Hook; + onMonthChange?: flatpickr.Options.Hook; + onYearChange?: flatpickr.Options.Hook; + onReady?: flatpickr.Options.Hook; + onValueUpdate?: flatpickr.Options.Hook; + onDayCreate?: flatpickr.Options.Hook; + value?: string | Date | number | Array; + children?: JSX.Element; } export default class DatePicker extends Component {} From 5baad0aabf25ca9416d93f06c479d8c6e790a938 Mon Sep 17 00:00:00 2001 From: Tyler Date: Thu, 29 Nov 2018 11:48:28 -0700 Subject: [PATCH 19/66] react-flatpickr remove patch version --- types/react-flatpickr/index.d.ts | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/types/react-flatpickr/index.d.ts b/types/react-flatpickr/index.d.ts index 973f30efc9..9f60b4d7be 100644 --- a/types/react-flatpickr/index.d.ts +++ b/types/react-flatpickr/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-flatpickr 3.6.4 +// Type definitions for react-flatpickr 3.6 // Project: https://github.com/coderhaoxin/react-flatpickr // Definitions by: begincalendar // snaveevans @@ -9,18 +9,18 @@ import { Component } from "react"; import flatpickr from "flatpickr"; export interface DateTimePickerProps { - defaultValue?: string; - options?: flatpickr.Options.Options; - onChange?: flatpickr.Options.Hook; - onOpen?: flatpickr.Options.Hook; - onClose?: flatpickr.Options.Hook; - onMonthChange?: flatpickr.Options.Hook; - onYearChange?: flatpickr.Options.Hook; - onReady?: flatpickr.Options.Hook; - onValueUpdate?: flatpickr.Options.Hook; - onDayCreate?: flatpickr.Options.Hook; - value?: string | Date | number | Array; - children?: JSX.Element; + defaultValue?: string; + options?: flatpickr.Options.Options; + onChange?: flatpickr.Options.Hook; + onOpen?: flatpickr.Options.Hook; + onClose?: flatpickr.Options.Hook; + onMonthChange?: flatpickr.Options.Hook; + onYearChange?: flatpickr.Options.Hook; + onReady?: flatpickr.Options.Hook; + onValueUpdate?: flatpickr.Options.Hook; + onDayCreate?: flatpickr.Options.Hook; + value?: string | Date | number | Array; + children?: JSX.Element; } export default class DatePicker extends Component {} From 47b4772299affae7d56351a46668c9624d3b0aba Mon Sep 17 00:00:00 2001 From: Tyler Date: Thu, 29 Nov 2018 12:01:10 -0700 Subject: [PATCH 20/66] react-flatpickr use ReadonlyArray --- types/react-flatpickr/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-flatpickr/index.d.ts b/types/react-flatpickr/index.d.ts index 9f60b4d7be..f9b817bd00 100644 --- a/types/react-flatpickr/index.d.ts +++ b/types/react-flatpickr/index.d.ts @@ -19,7 +19,7 @@ export interface DateTimePickerProps { onReady?: flatpickr.Options.Hook; onValueUpdate?: flatpickr.Options.Hook; onDayCreate?: flatpickr.Options.Hook; - value?: string | Date | number | Array; + value?: string | Date | number | ReadonlyArray; children?: JSX.Element; } From 3bc0b5bec959415292efd71bf5c188eb170b550e Mon Sep 17 00:00:00 2001 From: Tyler Date: Thu, 29 Nov 2018 13:25:36 -0700 Subject: [PATCH 21/66] react-flatpickr allow Element array --- types/react-flatpickr/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-flatpickr/index.d.ts b/types/react-flatpickr/index.d.ts index f9b817bd00..5e3b12fdf8 100644 --- a/types/react-flatpickr/index.d.ts +++ b/types/react-flatpickr/index.d.ts @@ -20,7 +20,7 @@ export interface DateTimePickerProps { onValueUpdate?: flatpickr.Options.Hook; onDayCreate?: flatpickr.Options.Hook; value?: string | Date | number | ReadonlyArray; - children?: JSX.Element; + children?: JSX.Element | JSX.Element[]; } export default class DatePicker extends Component {} From 0ccda5781a317728dc62b4889daac7f8a1b396b0 Mon Sep 17 00:00:00 2001 From: Tyler Date: Thu, 29 Nov 2018 13:31:29 -0700 Subject: [PATCH 22/66] react-flatpickr test multiple elements --- types/react-flatpickr/react-flatpickr-tests.tsx | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/types/react-flatpickr/react-flatpickr-tests.tsx b/types/react-flatpickr/react-flatpickr-tests.tsx index ce7122a47f..c51f527707 100644 --- a/types/react-flatpickr/react-flatpickr-tests.tsx +++ b/types/react-flatpickr/react-flatpickr-tests.tsx @@ -46,3 +46,10 @@ const wrappedElement = ( ); + +const wrappedElements = ( + + + + +); From 42675056c5f5b3101a43b111931c825c65d7dcb3 Mon Sep 17 00:00:00 2001 From: Daniel Rose Date: Wed, 8 Aug 2018 09:00:40 +0200 Subject: [PATCH 23/66] Adds type definitions for packages: sc-auth, socketcluster, socketcluster-client, socketcluster-server, expirymanager, fleximap, sc-broker, sc-broker-cluster, sc-channel --- types/expirymanager/expirymanager-tests.ts | 19 ++ types/expirymanager/index.d.ts | 25 ++ types/expirymanager/tsconfig.json | 23 ++ types/expirymanager/tslint.json | 3 + types/fleximap/fleximap-tests.ts | 27 ++ types/fleximap/index.d.ts | 38 +++ types/fleximap/tsconfig.json | 23 ++ types/fleximap/tslint.json | 6 + types/sc-auth/index.d.ts | 19 ++ types/sc-auth/sc-auth-tests.ts | 102 ++++++ types/sc-auth/tsconfig.json | 23 ++ types/sc-auth/tslint.json | 1 + types/sc-broker-cluster/clientcluster.d.ts | 10 + types/sc-broker-cluster/index.d.ts | 160 +++++++++ .../sc-broker-cluster-tests.ts | 29 ++ types/sc-broker-cluster/scbroker.d.ts | 3 + types/sc-broker-cluster/tsconfig.json | 25 ++ types/sc-broker-cluster/tslint.json | 3 + types/sc-broker/index.d.ts | 165 +++++++++ types/sc-broker/sc-broker-tests.ts | 58 ++++ types/sc-broker/scbroker.d.ts | 32 ++ types/sc-broker/tsconfig.json | 24 ++ types/sc-broker/tslint.json | 3 + types/sc-channel/index.d.ts | 45 +++ types/sc-channel/sc-channel-tests.ts | 33 ++ types/sc-channel/tsconfig.json | 23 ++ types/sc-channel/tslint.json | 3 + types/socketcluster-client/index.d.ts | 23 ++ .../lib/scclientsocket.d.ts | 251 ++++++++++++++ .../socketcluster-client-tests.ts | 75 +++++ types/socketcluster-client/tsconfig.json | 24 ++ types/socketcluster-client/tslint.json | 3 + types/socketcluster-server/index.d.ts | 15 + types/socketcluster-server/scserver.d.ts | 315 ++++++++++++++++++ .../socketcluster-server/scserversocket.d.ts | 43 +++ .../socketcluster-server-tests.ts | 39 +++ types/socketcluster-server/tsconfig.json | 25 ++ types/socketcluster-server/tslint.json | 3 + types/socketcluster/fsutil.d.ts | 11 + types/socketcluster/index.d.ts | 84 +++++ types/socketcluster/scbroker.d.ts | 3 + types/socketcluster/scworker.d.ts | 63 ++++ types/socketcluster/socketcluster-tests.ts | 76 +++++ types/socketcluster/tsconfig.json | 26 ++ types/socketcluster/tslint.json | 3 + 45 files changed, 2007 insertions(+) create mode 100644 types/expirymanager/expirymanager-tests.ts create mode 100644 types/expirymanager/index.d.ts create mode 100644 types/expirymanager/tsconfig.json create mode 100644 types/expirymanager/tslint.json create mode 100644 types/fleximap/fleximap-tests.ts create mode 100644 types/fleximap/index.d.ts create mode 100644 types/fleximap/tsconfig.json create mode 100644 types/fleximap/tslint.json create mode 100644 types/sc-auth/index.d.ts create mode 100644 types/sc-auth/sc-auth-tests.ts create mode 100644 types/sc-auth/tsconfig.json create mode 100644 types/sc-auth/tslint.json create mode 100644 types/sc-broker-cluster/clientcluster.d.ts create mode 100644 types/sc-broker-cluster/index.d.ts create mode 100644 types/sc-broker-cluster/sc-broker-cluster-tests.ts create mode 100644 types/sc-broker-cluster/scbroker.d.ts create mode 100644 types/sc-broker-cluster/tsconfig.json create mode 100644 types/sc-broker-cluster/tslint.json create mode 100644 types/sc-broker/index.d.ts create mode 100644 types/sc-broker/sc-broker-tests.ts create mode 100644 types/sc-broker/scbroker.d.ts create mode 100644 types/sc-broker/tsconfig.json create mode 100644 types/sc-broker/tslint.json create mode 100644 types/sc-channel/index.d.ts create mode 100644 types/sc-channel/sc-channel-tests.ts create mode 100644 types/sc-channel/tsconfig.json create mode 100644 types/sc-channel/tslint.json create mode 100644 types/socketcluster-client/index.d.ts create mode 100644 types/socketcluster-client/lib/scclientsocket.d.ts create mode 100644 types/socketcluster-client/socketcluster-client-tests.ts create mode 100644 types/socketcluster-client/tsconfig.json create mode 100644 types/socketcluster-client/tslint.json create mode 100644 types/socketcluster-server/index.d.ts create mode 100644 types/socketcluster-server/scserver.d.ts create mode 100644 types/socketcluster-server/scserversocket.d.ts create mode 100644 types/socketcluster-server/socketcluster-server-tests.ts create mode 100644 types/socketcluster-server/tsconfig.json create mode 100644 types/socketcluster-server/tslint.json create mode 100644 types/socketcluster/fsutil.d.ts create mode 100644 types/socketcluster/index.d.ts create mode 100644 types/socketcluster/scbroker.d.ts create mode 100644 types/socketcluster/scworker.d.ts create mode 100644 types/socketcluster/socketcluster-tests.ts create mode 100644 types/socketcluster/tsconfig.json create mode 100644 types/socketcluster/tslint.json diff --git a/types/expirymanager/expirymanager-tests.ts b/types/expirymanager/expirymanager-tests.ts new file mode 100644 index 0000000000..2206b2673e --- /dev/null +++ b/types/expirymanager/expirymanager-tests.ts @@ -0,0 +1,19 @@ +import { ExpiryManager } from "expirymanager"; + +const expiryManager = new ExpiryManager(); + +const keys = ['1', '2']; + +expiryManager.expire(keys, 1); + +expiryManager.unexpire(keys); + +const expiry: number = expiryManager.getExpiry(keys[0]); + +let expiredKeys = expiryManager.getExpiredKeys(); +expiredKeys = expiryManager.getExpiredKeys(expiryManager.now()); + +expiredKeys = expiryManager.extractExpiredKeys(); +expiredKeys = expiryManager.extractExpiredKeys(expiryManager.now()); + +expiryManager.clear(); diff --git a/types/expirymanager/index.d.ts b/types/expirymanager/index.d.ts new file mode 100644 index 0000000000..c192da7af7 --- /dev/null +++ b/types/expirymanager/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for expirymanager 0.9 +// Project: https://github.com/SocketCluster/expirymanager +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type Key = any; +export type Keys = Key[]; + +export class ExpiryManager { + constructor(); + + now(): number; + + expire(keys: Keys, seconds: number): void; + unexpire(keys: Keys): void; + + getExpiry(key: Key): number; + + getKeysByExpiry(expiry: number): Keys; + + getExpiredKeys(time?: number): Keys; + extractExpiredKeys(time?: number): Keys; + + clear(): void; +} diff --git a/types/expirymanager/tsconfig.json b/types/expirymanager/tsconfig.json new file mode 100644 index 0000000000..094c4e8c8d --- /dev/null +++ b/types/expirymanager/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "expirymanager-tests.ts" + ] +} diff --git a/types/expirymanager/tslint.json b/types/expirymanager/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/expirymanager/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/fleximap/fleximap-tests.ts b/types/fleximap/fleximap-tests.ts new file mode 100644 index 0000000000..4ca0181662 --- /dev/null +++ b/types/fleximap/fleximap-tests.ts @@ -0,0 +1,27 @@ +import { FlexiMap } from "fleximap"; + +let flexiMap = new FlexiMap(); +flexiMap = new FlexiMap({ arr: [] }); +flexiMap = new FlexiMap([{ arr: [] }, { obj: {} }]); + +flexiMap.set('keyA', {arr: [], obj: {}}); +let result = flexiMap.get(['keyA', 'arr']); + +flexiMap.add(['keyB1', 'keyB2', 'keyB3'], 123); +result = flexiMap.get(['keyB1', 'keyB2']); + +const arr = []; +arr[5] = 'Hello world'; + +flexiMap.set(['keyC1', 'keyC2'], arr); +result = flexiMap.get(['keyC1', 'keyC2']); + +flexiMap.set(['itemsA', 0], 'hello'); +flexiMap.set(['itemsA', 2], 'world'); +flexiMap.remove(['itemsA', 0]); + +flexiMap.set(['itemsB', 0], 'a'); +flexiMap.set(['itemsB', 1], 'b'); +flexiMap.set(['itemsB', 2], 'c'); +let splicedItems = flexiMap.splice(['itemsB'], 1, 1); +splicedItems = flexiMap.splice(['itemsB'], 1, 0, 'b2'); diff --git a/types/fleximap/index.d.ts b/types/fleximap/index.d.ts new file mode 100644 index 0000000000..9bce180c66 --- /dev/null +++ b/types/fleximap/index.d.ts @@ -0,0 +1,38 @@ +// Type definitions for fleximap 0.9.10 +// Project: https://github.com/SocketCluster/fleximap +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +export type KeyChain = any; + +export class FlexiMap { + constructor(object?: any[] | object); + + get(keyChain: KeyChain): any; + getRange(keyChain: KeyChain, fromIndex: number, toIndex: number): any; + getRaw(keyChain: KeyChain): any; + getAll(): any[] | object; + + count(keyChain: KeyChain): number; + + hasImmediateKey(key: string): boolean; + hasKey(keyChain: KeyChain): boolean; + hasType(keyChain: KeyChain, type: any): boolean; + hasValue(keyChain: KeyChain, value: any): boolean; + hasObject(keyChain: KeyChain, object: object): boolean; + + set(keyChain: KeyChain, value: any): any; + + add(keyChain: KeyChain, value: any): number; + + concat(keyChain: KeyChain, value: any): any; + + remove(keyChain: KeyChain): any; + removeRange(keyChain: KeyChain, fromIndex: number, toIndex: number): any[]; + removeAll(): void; + + splice(keyChain: KeyChain, index: number, count: number, ...items: any[]): any[]; + + pop(keyChain: KeyChain): any[]; +} diff --git a/types/fleximap/tsconfig.json b/types/fleximap/tsconfig.json new file mode 100644 index 0000000000..710fa81c96 --- /dev/null +++ b/types/fleximap/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fleximap-tests.ts" + ] +} diff --git a/types/fleximap/tslint.json b/types/fleximap/tslint.json new file mode 100644 index 0000000000..65c83fb1e3 --- /dev/null +++ b/types/fleximap/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "dt-header": false + } +} diff --git a/types/sc-auth/index.d.ts b/types/sc-auth/index.d.ts new file mode 100644 index 0000000000..84f92bf674 --- /dev/null +++ b/types/sc-auth/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for sc-auth 5.0 +// Project: https://github.com/SocketCluster/sc-auth +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import { VerifyOptions, VerifyCallback, Secret, SignCallback, SignOptions } from "jsonwebtoken"; + +export interface SCAuthEngine { + verifyToken(signedToken: string, key: string | Buffer, options?: VerifyOptions, callback?: VerifyCallback): void; + signToken(token: string | object | Buffer, key: Secret, options?: SignOptions, callback?: SignCallback): void; +} + +export class AuthEngine implements SCAuthEngine { + constructor(); + + verifyToken(signedToken: string, key: string | Buffer, options?: VerifyOptions, callback?: VerifyCallback): void; + signToken(token: string | object | Buffer, key: Secret, options?: SignOptions, callback?: SignCallback): void; +} diff --git a/types/sc-auth/sc-auth-tests.ts b/types/sc-auth/sc-auth-tests.ts new file mode 100644 index 0000000000..4fa57d3391 --- /dev/null +++ b/types/sc-auth/sc-auth-tests.ts @@ -0,0 +1,102 @@ +/** + * This mostly delegates to jwt, so using its tests as base + */ + +import scAuth = require("sc-auth"); +import fs = require("fs"); + +let signedToken = ""; +let cert: Buffer; + +interface TestObject { + foo: string; +} + +const testObject = { foo: "bar" }; + +const authEngine = new scAuth.AuthEngine(); + +// sign with default (HMAC SHA256) +authEngine.signToken(testObject, "shhhhh"); + +// sign with default (HMAC SHA256) and single audience +authEngine.signToken(testObject, "shhhhh", { audience: "theAudience" }); + +// sign with default (HMAC SHA256) and multiple audiences +authEngine.signToken(testObject, "shhhhh", { + audience: ["audience1", "audience2"] +}); + +// sign with default (HMAC SHA256) and a keyid +authEngine.signToken(testObject, "shhhhh", { keyid: "theKeyId" }); + +// sign with RSA SHA256 +cert = fs.readFileSync("private.key"); // get private key +authEngine.signToken(testObject, cert, { algorithm: "RS256" }); + +// sign with encrypted RSA SHA256 private key (only PEM encoding is supported) +const privKey: Buffer = fs.readFileSync("encrypted_private.key"); // get private key +const secret = { key: privKey.toString(), passphrase: "keypwd" }; +authEngine.signToken(testObject, secret, { algorithm: "RS256" }); // the algorithm option is mandatory in this case + +// sign asynchronously +authEngine.signToken(testObject, cert, { algorithm: "RS256" }, (err, token) => { + signedToken = token; +}); + +// verify a token symmetric +authEngine.verifyToken(signedToken, "shhhhh", {}, (err, decoded) => { + const result = decoded as TestObject; + + console.log(result.foo); // bar +}); + +// use external time for verifying +authEngine.verifyToken(signedToken, "shhhhh", { clockTimestamp: 1 }, (err, decoded) => { + const result = decoded as TestObject; + + console.log(result.foo); // bar +}); + +// invalid token +authEngine.verifyToken(signedToken, "wrong-secret", {}, (err, decoded) => { + console.log(err); + + // decoded undefined +}); + +// verify a token asymmetric +cert = fs.readFileSync("public.pem"); // get public key +authEngine.verifyToken(signedToken, cert, {}, (err, decoded) => { + const result = decoded as TestObject; + + console.log(result.foo); // bar +}); + +// verify audience +cert = fs.readFileSync("public.pem"); // get public key +authEngine.verifyToken(signedToken, cert, { audience: "urn:foo" }, (err, decoded) => { + // if audience mismatch, err == invalid audience + console.log(err); +}); + +// verify issuer +cert = fs.readFileSync("public.pem"); // get public key +authEngine.verifyToken(signedToken, cert, { audience: "urn:foo", issuer: "urn:issuer" }, (err, decoded) => { + // if issuer mismatch, err == invalid issuer + console.log(err); +}); + +// verify algorithm +cert = fs.readFileSync("public.pem"); // get public key +authEngine.verifyToken(signedToken, cert, { algorithms: ["RS256"] }, (err, decoded) => { + // if algorithm mismatch, err == invalid algorithm + console.log(err); +}); + +// verify without expiration check +cert = fs.readFileSync("public.pem"); // get public key +authEngine.verifyToken(signedToken, cert, { ignoreExpiration: true }, (err, decoded) => { + // if ignoreExpration == false and token is expired, err == expired token + console.log(err); +}); diff --git a/types/sc-auth/tsconfig.json b/types/sc-auth/tsconfig.json new file mode 100644 index 0000000000..5c8e3a1e19 --- /dev/null +++ b/types/sc-auth/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sc-auth-tests.ts" + ] +} diff --git a/types/sc-auth/tslint.json b/types/sc-auth/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sc-auth/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sc-broker-cluster/clientcluster.d.ts b/types/sc-broker-cluster/clientcluster.d.ts new file mode 100644 index 0000000000..f2234df6ab --- /dev/null +++ b/types/sc-broker-cluster/clientcluster.d.ts @@ -0,0 +1,10 @@ +import { EventEmitter } from "events"; +import { SCBrokerClient } from "sc-broker"; +import { mapperFunction } from "."; + +export class ClientCluster extends EventEmitter { + constructor(clients: SCBrokerClient[]); + + setMapper(mapper: mapperFunction): void; + getMapper(): mapperFunction; +} diff --git a/types/sc-broker-cluster/index.d.ts b/types/sc-broker-cluster/index.d.ts new file mode 100644 index 0000000000..9314acda82 --- /dev/null +++ b/types/sc-broker-cluster/index.d.ts @@ -0,0 +1,160 @@ +// Type definitions for sc-broker-cluster 6.1 +// Project: https://github.com/SocketCluster/sc-broker-cluster +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { SCServerSocket, SCServer } from "socketcluster-server"; +import { BrokerStartInfo, BrokerExitInfo } from "socketcluster"; +import { SpliceOptions, QueryOptions } from "sc-broker"; +import { SCChannel } from "sc-channel"; +import { EventEmitter } from "events"; +import { AsyncResultArrayCallback } from "async"; +import { KeyChain, FlexiMap } from "fleximap"; +import { Keys } from "expirymanager"; +import { ClientCluster } from "./clientcluster"; + +export class AbstractDataClient extends EventEmitter { + constructor(dataClient: ClientCluster); + + set(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void; + set(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void; + + expire(keys: Keys, seconds: number, callback?: (err?: Error) => void): void; + unexpire(keys: Keys, callback?: (err?: Error) => void): void; + + add(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void; + add(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void; + + get(keyChain: KeyChain, callback: (err: Error | null, value: any) => void): void; + + getRange(keyChain: KeyChain, fromIndex: number, toIndex: number, callback: (err: Error | null, value: any) => void): void; + getRange(keyChain: KeyChain, fromIndex: number, callback: (err: Error | null, value: any) => void): void; + + getAll(callback: (err: Error | null, value: any[] | object) => void): void; + + count(keyChain: KeyChain, callback: (err: Error | null, value: number) => void): void; + + remove(keyChain: KeyChain, getValue?: boolean, callback?: (err?: Error) => void): void; + remove(keyChain: KeyChain, callback?: (err?: Error) => void): void; + + removeRange(keyChain: KeyChain, fromIndex: number, toIndex?: number, getValue?: boolean, callback?: (err?: Error) => void): void; + removeRange(keyChain: KeyChain, fromIndex: number, toIndex?: number, callback?: (err?: Error) => void): void; + removeRange(keyChain: KeyChain, fromIndex: number, callback?: (err?: Error) => void): void; + + removeAll(callback?: (err: Error) => void): void; + + splice(keyChain: KeyChain, options?: SpliceOptions, callback?: (err?: Error) => void): void; + splice(keyChain: KeyChain, callback?: (err?: Error) => void): void; + + pop(keyChain: KeyChain, callback: (err: Error | null, data: any) => void): void; + + hasKey(keyChain: KeyChain, callback: (err: Error | null, data: boolean) => void): void; + + extractKeys(keyChain: KeyChain): string[]; + + extractValues(keyChain: KeyChain): any[]; + + exec(query: (datamap: FlexiMap) => void, options?: QueryOptions, callback?: (err: Error | null, data: any) => void): void; + exec(query: (datamap: FlexiMap) => void, callback: (err: Error | null, data: any) => void): void; +} + +export type handlerFunction = (data: any) => void; + +export type mapperFunction = (keyChain: KeyChain, method: string, clientIds: number[]) => number | number[]; + +/** + * The exchange object is a top-level SCBrokerClient which lets you publish events and manipulate data within your brokers - It represents a cluster of 1 or more brokers. + */ +export class SCExchange extends AbstractDataClient { + constructor(privateClientCluster: ClientCluster, publicClientCluster: ClientCluster, ioClusterClient: Client); + + send(data: any, mapIndex: number | string | string[] | null, callback?: (err?: Error) => void): void; + + publish(channelName: string, data: any, callback: (err?: Error) => void): void; + + subscribe(channelName: string): SCChannel; + unsubscribe(channelName: string): void; + + channel(channelName: string): SCChannel; + destroyChannel(channelName: string): void; + + subscriptions(includePending?: boolean): string[]; + isSubscribed(channelName: string, includePending?: boolean): boolean; + + watch(channelName: string, handler: handlerFunction): void; + unwatch(channelName: string, handler?: handlerFunction): void; + watchers(channelName: string): handlerFunction[]; + + setMapper(mapper: mapperFunction): void; + getMapper(): mapperFunction; + + map(keyChain: KeyChain, method: string): { type: string; targets: Client[] }; + + destroy(): void; +} + +export interface SCBrokerClusterServerOptions { + brokers: string[]; + debug?: boolean; + inspect?: boolean; + instanceId?: string; + secretKey?: string; + expiryAccuracy?: number; + downgradeToUser: number | string; + appBrokerControllerPath?: string; + processTermTimeout?: number; + ipcAckTimeout?: number; + brokerOptions?: SCServer.SCServerOptions; +} + +export class Server extends EventEmitter { + constructor(options: SCBrokerClusterServerOptions); + + on(event: "brokerStart", listener: (brokerInfo: BrokerStartInfo) => void): this; + on(event: "brokerExit", listener: (brokerInfo: BrokerExitInfo) => void): this; + on(event: "brokerMessage", listener: (brokerId: string, data: any, callback: (err: Error | null, data: any) => void) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "error", listener: (err?: Error) => void): this; + + sendToBroker(brokerId: string, data: any, callback: (err: Error | null, data: any) => void): void; + killBrokers(): void; + destroy(): void; +} + +export interface SCBrokerClusterClientOptions { + brokers: string[]; + secretKey?: string; + pubSubBatchDuration?: number; + connectRetryErrorThreshold: number; +} + +export interface MessagePacket { + channel: string; + data: any; +} + +export class Client extends EventEmitter { + constructor(options: SCBrokerClusterClientOptions); + + exchange(): SCExchange; + + options: SCBrokerClusterClientOptions; + + on(event: "error", listener: (err?: Error) => void): this; + on(event: "warning", listener: (warning?: Error) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "message", listener: (packet: MessagePacket) => void): this; + + destroy(callback: AsyncResultArrayCallback): void; + + subscribe(channel: string, callback: (err?: Error) => void): void; + unsubscribe(channel: string, callback: () => void): void; + unsubscribeAll(callback: () => void): void; + isSubscribed(channel: string, includePending: boolean): boolean; + + subscribeSocket(socket: SCServerSocket, channel: string, callback?: (err?: Error) => void): void; + unsubscribeSocket(socket: SCServerSocket, channel: string, callback?: () => void): void; + + setSCServer(scServer: SCServer): void; +} diff --git a/types/sc-broker-cluster/sc-broker-cluster-tests.ts b/types/sc-broker-cluster/sc-broker-cluster-tests.ts new file mode 100644 index 0000000000..0f5c274248 --- /dev/null +++ b/types/sc-broker-cluster/sc-broker-cluster-tests.ts @@ -0,0 +1,29 @@ +import { Client } from "sc-broker-cluster"; +import { SCServer, SCServerSocket } from "socketcluster-server"; +import WebSocket = require("ws"); + +const client = new Client({ + brokers: [], + secretKey: "secretKey", + pubSubBatchDuration: 100, + connectRetryErrorThreshold: 5 +}); + +client.on("error", err => {}); +client.on("warning", err => {}); + +const exchange = client.exchange(); + +const scServer = new SCServer(); +client.setSCServer(scServer); + +client.once("ready", () => {}); + +const wsSocket = new WebSocket("address"); +const socket = new SCServerSocket("id", scServer, wsSocket); +client.subscribeSocket(socket, "channelName", err => {}); + +client.unsubscribeSocket(socket, "channelName"); + +const data: any = {}; +exchange.publish("channelName", data, err => {}); diff --git a/types/sc-broker-cluster/scbroker.d.ts b/types/sc-broker-cluster/scbroker.d.ts new file mode 100644 index 0000000000..a7ddb7db87 --- /dev/null +++ b/types/sc-broker-cluster/scbroker.d.ts @@ -0,0 +1,3 @@ +import SCBroker = require("sc-broker/scbroker"); + +export = SCBroker; diff --git a/types/sc-broker-cluster/tsconfig.json b/types/sc-broker-cluster/tsconfig.json new file mode 100644 index 0000000000..8ace8fc9dc --- /dev/null +++ b/types/sc-broker-cluster/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "clientcluster.d.ts", + "scbroker.d.ts", + "sc-broker-cluster-tests.ts" + ] +} diff --git a/types/sc-broker-cluster/tslint.json b/types/sc-broker-cluster/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/sc-broker-cluster/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/sc-broker/index.d.ts b/types/sc-broker/index.d.ts new file mode 100644 index 0000000000..ccb83e880e --- /dev/null +++ b/types/sc-broker/index.d.ts @@ -0,0 +1,165 @@ +// Type definitions for sc-broker 5.1 +// Project: https://github.com/SocketCluster/sc-broker +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { SCServer } from "socketcluster-server"; +import { WorkerExitInfo } from "socketcluster"; +import { EventEmitter } from "events"; +import { KeyChain, FlexiMap } from "fleximap"; +import { Keys, Key } from "expirymanager"; + +export interface SCBrokerServerOptions { + id?: string; + instanceId?: string; + debug?: boolean; + inspect?: boolean; + socketPath?: string; + port?: number; + expiryAccuracy?: number; + downgradeToUser: number | string; + brokerControllerPath?: string; + processTermTimeout?: number; + ipcAckTimeout?: number; + secretKey?: string; + brokerOptions?: SCServer.SCServerOptions; +} + +export interface SCBrokerServer extends EventEmitter { + options: SCBrokerServerOptions; + socketPath?: string; + port?: number; + ipcAckTimeout: number; + + on(event: "error", listener: (err?: Error) => void): this; + on(event: "brokerMessage", listener: (brokerId: string, data: any, callback: (err: Error | null, data: any) => void) => void): this; + on(event: "ready", listener: (data: any) => void): this; + on(event: "exit", listener: (data: WorkerExitInfo) => void): this; + + sendToBroker(data: any, callback?: (err: Error | null, data: any, brokerId: string) => void): void; +} + +export function createServer(options?: SCBrokerServerOptions): SCBrokerServer; + +export interface AutoReconnectOptions { + initialDelay?: number; + randomness?: number; + multiplier?: number; + maxDelay?: number; +} + +export interface SCBrokerClientOptions { + secretKey?: string; + timeout?: number; + socketPath?: string; + port?: number; + host?: string; + autoReconnect?: boolean; + autoReconnectOptions?: AutoReconnectOptions; + connectRetryErrorThreshold?: number; + pubSubBatchDuration?: number; +} + +export interface QueryOptions { + baseKey?: KeyChain; + noAck?: boolean; + data?: any; +} + +export interface SpliceOptions { + index?: number; + count?: number; + items?: any[]; + getValue?: boolean; + noAck?: boolean; +} + +export interface SCBrokerClient extends EventEmitter { + readonly CONNECTED: "connected"; + readonly CONNECTING: "connecting"; + readonly DISCONNECTED: "disconnected"; + + socketPath?: string; + port?: number; + host?: string; + autoReconnect: boolean; + autoReconnectOptions?: AutoReconnectOptions; + connectRetryErrorThreshold: number; + state: "connected" | "connecting" | "disconnected"; + connectAttempts: number; + pendingReconnect: boolean; + pendingReconnectTimeout: number | null; + + on(event: "error", listener: (err?: Error) => void): this; + on(event: "warning", listener: (warning?: Error) => void): this; + on(event: "ready", listener: (data: any) => void): this; + on(event: "message", listener: (channel: string, data: any) => void): this; + on(event: "subscribeFail", listener: (err: Error | null, channel: string) => void): this; + on(event: "subscribe", listener: (channel: string) => void): this; + on(event: "unsubscribe", listener: () => void): this; + + isConnected(): boolean; + + subscribe(channel: string, ackCallback: (err?: Error) => void, force?: boolean): void; + unsubscribe(channel: string, ackCallback: (err?: Error) => void): void; + + subscriptions(includePending?: boolean): string[]; + isSubscribed(channel: string, includePending?: boolean): boolean; + + publish(channel: string, data: any, callback: (err?: Error) => void): void; + + send(data: any, callback: (err?: Error) => void): void; + + set(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void; + set(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void; + + expire(keys: Keys, seconds: number, callback?: (err?: Error) => void): void; + unexpire(keys: Keys, callback?: (err?: Error) => void): void; + getExpiry(key: Key, callback?: (err?: Error) => void): number; + + add(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void; + add(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void; + + concat(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void; + concat(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void; + + get(keyChain: KeyChain, callback: (err: Error | null, value: any) => void): void; + + getRange(keyChain: KeyChain, fromIndex: number, toIndex: number, callback: (err: Error | null, value: any) => void): void; + getRange(keyChain: KeyChain, fromIndex: number, callback: (err: Error | null, value: any) => void): void; + + getAll(callback: (err: Error | null, value: any[] | object) => void): void; + + count(keyChain: KeyChain, callback: (err: Error | null, value: number) => void): void; + + exec(query: (datamap: FlexiMap) => void, options?: QueryOptions, callback?: (err: Error | null, data: any) => void): void; + exec(query: (datamap: FlexiMap) => void, callback: (err: Error | null, data: any) => void): void; + + query(query: (datamap: FlexiMap) => void, data?: any, callback?: (err: Error | null, data: any) => void): void; + query(query: (datamap: FlexiMap) => void, callback: (err: Error | null, data: any) => void): void; + + remove(keyChain: KeyChain, getValue?: boolean, callback?: (err?: Error) => void): void; + remove(keyChain: KeyChain, callback?: (err?: Error) => void): void; + + removeRange(keyChain: KeyChain, fromIndex: number, toIndex?: number, getValue?: boolean, callback?: (err?: Error) => void): void; + removeRange(keyChain: KeyChain, fromIndex: number, toIndex?: number, callback?: (err?: Error) => void): void; + removeRange(keyChain: KeyChain, fromIndex: number, callback?: (err?: Error) => void): void; + + removeAll(callback?: (err: Error) => void): void; + + splice(keyChain: KeyChain, options?: SpliceOptions, callback?: (err?: Error) => void): void; + splice(keyChain: KeyChain, callback?: (err?: Error) => void): void; + + pop(keyChain: KeyChain, callback: (err: Error | null, data: any) => void): void; + + hasKey(keyChain: KeyChain, callback: (err: Error | null, data: boolean) => void): void; + + extractKeys(keyChain: KeyChain): string[]; + + extractValues(keyChain: KeyChain): any[]; + + end(callback: (err?: Error) => void): void; +} + +export function createClient(options?: SCBrokerClientOptions): SCBrokerClient; diff --git a/types/sc-broker/sc-broker-tests.ts b/types/sc-broker/sc-broker-tests.ts new file mode 100644 index 0000000000..201ff10a27 --- /dev/null +++ b/types/sc-broker/sc-broker-tests.ts @@ -0,0 +1,58 @@ +import { SCServer, SCServerSocket } from "socketcluster-server"; +import SCBroker = require("sc-broker/scbroker"); +import { FlexiMap } from "fleximap"; +import { ExpiryManager } from "expirymanager"; + +//////////////////////////////////////////////////// +/// SCBroker tests +//////////////////////////////////////////////////// + +const options: SCServer.SCServerOptions = { port: 80 }; + +let scBroker = new SCBroker(); +scBroker = new SCBroker(options); +scBroker.options = { environment: "prod" }; + +const id: number = scBroker.id; +const instanceId: number = scBroker.instanceId; +const dataMap: FlexiMap = scBroker.dataMap; +const dataExpirer: ExpiryManager = scBroker.dataExpirer; +const subscriptions = scBroker.subscriptions; + +const socket: SCServerSocket = subscriptions[1]["test"]; + +scBroker.on("subscribe", channel => { + const subscribeChannel: string = channel; +}); +scBroker.on("unsubscribe", channel => { + const unsubscribeChannel: string = channel; +}); +scBroker.on("publish", (channel, data) => { + const publishChannel: string = channel; + const publishData: any = data; +}); +scBroker.on("masterMessage", (data, masterMessageResponse) => { + const masterMessageData: any = data; + masterMessageResponse(null, "test"); + masterMessageResponse(new Error(), null); +}); + +scBroker.publish("testChannel", 123); + +scBroker.exec(dataMap => { + dataMap.set(["main", "message"], "Message"); + return dataMap.get(["main"]); +}); + +scBroker.sendToMaster("data"); +scBroker.sendToMaster(123, (err, response) => { + if (!err) { + const answer = response; + } +}); + +class MyBroker extends SCBroker { + run() { + this.on("subscribe", channel => {}); + } +} diff --git a/types/sc-broker/scbroker.d.ts b/types/sc-broker/scbroker.d.ts new file mode 100644 index 0000000000..057b983adf --- /dev/null +++ b/types/sc-broker/scbroker.d.ts @@ -0,0 +1,32 @@ +import { EventEmitter } from "events"; +import { SCServer, SCServerSocket } from "socketcluster-server"; +import { FlexiMap, KeyChain } from "fleximap"; +import { ExpiryManager } from "expirymanager"; + +export = SCBroker; + +interface Subscriptions { + [socketId: number]: { + [channel: string]: SCServerSocket; + }; +} + +declare class SCBroker extends EventEmitter { + id: number; + options: SCServer.SCServerOptions; + instanceId: number; + dataMap: FlexiMap; + dataExpirer: ExpiryManager; + subscriptions: Subscriptions; + + constructor(options?: SCServer.SCServerOptions); + + on(event: "subscribe" | "unsubscribe", listener: (channel: string) => void): this; + on(event: "publish", listener: (channel: string, data: any) => void): this; + on(event: "masterMessage", listener: (data: any, respond: (err: Error | null, responseData: any) => void) => void): this; + + publish(channel: string, message: any): void; + run(): void; + exec(query: (dataMap: FlexiMap, dataExpirer: ExpiryManager, subscriptions: Subscriptions) => any, baseKey?: KeyChain): any; + sendToMaster(data: any, callback?: (err: Error | null, responseData: any) => void): void; +} diff --git a/types/sc-broker/tsconfig.json b/types/sc-broker/tsconfig.json new file mode 100644 index 0000000000..6adfe07a5b --- /dev/null +++ b/types/sc-broker/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "scbroker.d.ts", + "sc-broker-tests.ts" + ] +} diff --git a/types/sc-broker/tslint.json b/types/sc-broker/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/sc-broker/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/sc-channel/index.d.ts b/types/sc-channel/index.d.ts new file mode 100644 index 0000000000..034723c0ba --- /dev/null +++ b/types/sc-channel/index.d.ts @@ -0,0 +1,45 @@ +// Type definitions for sc-channel 1.2 +// Project: https://github.com/SocketCluster/sc-channel +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import Emitter = require("component-emitter"); +import { SCExchange, handlerFunction } from "sc-broker-cluster"; + +export interface SCChannelOptions { + waitForAuth?: boolean; + batch?: boolean; + data?: any; +} + +export class SCChannel extends Emitter { + readonly PENDING: "pending"; + readonly SUBSCRIBED: "subscribed"; + readonly UNSUBSCRIBED: "unsubscribed"; + + name: string; + state: ChannelState; + waitForAuth: boolean; + batch: boolean; + data: any; + + constructor(name: string, client: SCExchange, options?: SCChannelOptions); + + setOptions(options?: SCChannelOptions): void; + getState(): "pending" | "subscribed" | "unsubscribed"; + + subscribe(options?: any): void; + unsubscribe(): void; + isSubscribed(includePending?: boolean): boolean; + + publish(data: any, callback?: (err?: Error) => void): void; + + watch(handler: handlerFunction): void; + unwatch(handler?: handlerFunction): void; + watchers(): handlerFunction[]; + + destroy(): void; +} + +export type ChannelState = "pending" | "subscribed" | "unsubscribed"; diff --git a/types/sc-channel/sc-channel-tests.ts b/types/sc-channel/sc-channel-tests.ts new file mode 100644 index 0000000000..bfc90cee12 --- /dev/null +++ b/types/sc-channel/sc-channel-tests.ts @@ -0,0 +1,33 @@ +import { SCChannel, SCChannelOptions } from "sc-channel"; +import { handlerFunction, Client, SCBrokerClusterClientOptions } from "sc-broker-cluster"; + +const clientOptions: SCBrokerClusterClientOptions = { brokers: [], connectRetryErrorThreshold: 0 }; +const client = new Client(clientOptions); + +let channel = new SCChannel("channelName", client.exchange()); +const channelOptions: SCChannelOptions = {}; +channel = new SCChannel("channelName", client.exchange(), channelOptions); + +channel.state = channel.PENDING; +channel.state = channel.SUBSCRIBED; +channel.state = channel.UNSUBSCRIBED; + +const channelName: string = channel.name; + +const handler: handlerFunction = () => { }; + +channel.watch(handler); +channel.unwatch(); + +channel.subscribe(); +channel.subscribe(channelOptions); +channel.unsubscribe(); + +const data: any = channel.data; + +channel.emit("subscribe", channelName); +channel.emit("unsubscribe", channelName); + +channel.setOptions(channelOptions); + +channel.publish(data); diff --git a/types/sc-channel/tsconfig.json b/types/sc-channel/tsconfig.json new file mode 100644 index 0000000000..c5c5ce5f14 --- /dev/null +++ b/types/sc-channel/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sc-channel-tests.ts" + ] +} diff --git a/types/sc-channel/tslint.json b/types/sc-channel/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/sc-channel/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/socketcluster-client/index.d.ts b/types/socketcluster-client/index.d.ts new file mode 100644 index 0000000000..9c15a45465 --- /dev/null +++ b/types/socketcluster-client/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for socketcluster-client 13.0 +// Project: https://github.com/SocketCluster/socketcluster-client +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { SCAuthEngine } from "sc-auth"; +import { SCServer } from "socketcluster-server"; + +export import SCClientSocket = require("./lib/scclientsocket"); + +export function create(options?: SCClientSocket.ClientOptions): SCClientSocket; + +/** @deprecated */ +export function connect(options?: SCClientSocket.ClientOptions): SCClientSocket; + +export function destroy(socket: SCClientSocket): void; + +export const clients: { + [id: string]: SCClientSocket; +}; + +export const version: string; diff --git a/types/socketcluster-client/lib/scclientsocket.d.ts b/types/socketcluster-client/lib/scclientsocket.d.ts new file mode 100644 index 0000000000..19552bd102 --- /dev/null +++ b/types/socketcluster-client/lib/scclientsocket.d.ts @@ -0,0 +1,251 @@ +import Emitter = require("component-emitter"); +import { SCServer } from "socketcluster-server"; +import { SCAuthEngine } from "sc-auth"; +import { SCChannel, SCChannelOptions, ChannelState } from "sc-channel"; +import WebSocket = require("ws"); + +declare class SCClientSocket extends Emitter { + constructor(opts: SCClientSocket.ClientOptions); + + id: string; + + channels: { + [channelName: string]: SCChannel; + }; + + CONNECTING: "connecting"; + OPEN: "open"; + CLOSED: "closed"; + + state: SCClientSocket.States; + getState(): SCClientSocket.States; + + AUTHENTICATED: "authenticated"; + UNAUTHENTICATED: "unauthenticated"; + + authState: SCClientSocket.AuthStates; + + PENDING: "pending"; + + pendingReconnect: boolean; + pendingReconnectTimeout: number; + + getBytesReceived(): number; + + deauthenticate(callback?: (err: Error) => void): void; + + connect(): void; + open(): void; + disconnect(code?: number, data?: string | object): void; + reconnect(code?: number, data?: string | object): void; + destroy(code?: number, data?: string | object): void; + + decodeBase64(encodedString: string): string; + encodeBase64(decodedString: string): string; + + getAuthToken(): object | null; + authToken: object | null; + + getSignedAuthToken(): string | null; + signedAuthToken: string | null; + + // Perform client-initiated authentication by providing an encrypted token string. + authenticate(signedAuthToken: string, callback?: (err: Error, authStatus: SCClientSocket.AuthStatus) => void): void; + + decode(message: any): any; + encode(object: any): any; + + send(data: any): void; + + emit(event: string, data: any, callback?: (err: Error, responseData: any) => void): void; + + publish(channelName: string, data: any, callback?: (err: Error, ackData: any) => void): void; + + subscribe(channelName: string, options?: SCChannelOptions): SCChannel; + unsubscribe(channelName: string): void; + + channel(channelName: string, options?: SCChannelOptions): SCChannel; + + destroyChannel(channelName: string): void; + + subscriptions(includePending?: boolean): string[]; + isSubscribed(channelName: string, includePending?: boolean): boolean; + + processPendingSubscriptions(): void; + + watch(channelName: string, handler: SCClientSocket.WatcherFunction): void; + unwatch(channelName: string, handler?: SCClientSocket.WatcherFunction): void; + watchers(channelName: string): SCClientSocket.WatcherFunction[]; + + on(event: "connecting", listener: () => void): this; + on(event: "connect", listener: (status: SCClientSocket.ConnectStatus, processSubscriptions: () => void) => void): this; + on(event: "connectAbort" | "disconnect" | "close", listener: (code: number, data: string | object) => void): this; + + on(event: "kickOut", listener: (message: string, channelName: string) => void): this; + + on(event: "authenticate", listener: (signedAuthToken: string | null) => void): this; + on(event: "deauthenticate", listener: (oldSignedToken: string | null) => void): this; + on(event: "authStateChange", listener: (stateChangeData: SCClientSocket.AuthStateChangeData) => void): this; + on(event: "removeAuthToken", listener: (oldToken: object | null) => void): this; + + on(event: "subscribe" | "subscribeRequest", listener: (channelName: string, subscriptionOptions: SCChannelOptions) => void): this; + on(event: "subscribeStateChange", listener: (stateChangeData: SCClientSocket.SubscribeStateChangeData) => void): this; + on(event: "subscribeFail", listener: (err: Error, channelName: string, subscriptionOptions: SCChannelOptions) => void): this; + on(event: "unsubscribe", listener: (channelName: string) => void): this; + + on(event: "error", listener: (err: Error) => void): this; + + on(event: "raw", listener: (data: any) => void): this; + on(event: "message", listener: (message: WebSocket.Data) => void): this; + + // Implements Emitter interface + + // tslint:disable:ban-types + // tslint:disable:adjacent-overload-signatures + on(event: string, listener: Function): this; + once(event: string, listener: Function): this; + off(event?: string, listener?: Function): this; + emit(event: string, ...args: any[]): boolean; + listeners(event: string): Function[]; + hasListeners(event: string): boolean; + // tslint:enable:adjacent-overload-signatures + // tslint:enable:ban-types +} + +export = SCClientSocket; + +declare namespace SCClientSocket { + interface ClientOptions { + host?: string; + + // Defaults to the current host (read from the URL). + hostname?: string; + + // Defaults to false. + secure?: boolean; + + // Defaults to 80 if !secure otherwise defaults to 443. + port?: number; + + // The URL which SC uses to make the initial handshake for the WebSocket. Defaults to '/socketcluster/'. + path?: string; + + // A map of key-value pairs which will be used as query parameters for the initial HTTP handshake which will initiate the WebSocket connection. + query?: string | { [key: string]: string }; + + // (milliseconds) - This is the timeout for getting a response to a SCSocket emit event (when a callback is provided). + ackTimeout?: number; + + // (milliseconds) + connectTimeout?: number; + + // Whether or not to automatically connect the socket as soon as it is created. Default is true. + autoConnect?: boolean; + + // Whether or not to automatically reconnect the socket when it loses the connection. + autoReconnect?: boolean; + + // Valid properties are: initialDelay (milliseconds), randomness (milliseconds), multiplier (decimal; default is 1.5) and maxDelay (milliseconds). + autoReconnectOptions?: AutoReconnectOptions; + + // Whether or not a client automatically disconnects on page unload. If enabled, the client will disconnect when a user navigates away from the page. + // This can happen when a user closes the tab/window, clicks a link to leave the page, or types a new URL into the address bar. Defaults to true. + disconnectOnUnload?: boolean; + + // Turn on/off per-message deflate compression. If this is true, you need to make sure that this property is also set to true on the server-side. + // Note that this option is only relevant when running the client from Node.js. Most modern browsers will automatically use perMessageDeflate so + // you only need to turn it on from the server-side. + perMessageDeflate?: boolean; + + // Defaults to true; multiplexing allows you to reuse a socket instead of creating a second socket to the same address. + multiplex?: boolean; + + // Defaults to null (0 milliseconds); this property affects channel subscription batching; it determines the period in milliseconds for batching + // multiple subscription requests together. It only affects channels that have the batch option set to true. A value of null or 0 means that all + // subscribe or unsubscribe requests which were made within the same call stack will be batched together. This property was introduced on the + // client-side in SC version 8 (both the client and server versions need to be >= 8.0.0). Note that there is also a separate property with the + // same name which can be configured on the server. + pubSubBatchDuration?: number; + + // Whether or not to add a timestamp to the WebSocket handshake request. + timestampRequests?: boolean; + + // The query parameter name to use to hold the timestamp. + timestampParam?: string; + + // A custom engine to use for storing and loading JWT auth tokens on the client side. + authEngine?: SCAuthEngine | null; + + // The name of the JWT auth token (provided to the authEngine - By default this is the localStorage variable name); defaults to 'socketCluster.authToken'. + authTokenName?: string; + + // The type to use to represent binary on the client. Defaults to 'arraybuffer'. + binaryType?: string; + + // Set this to false during debugging - Otherwise client connection will fail when using self-signed certificates. + rejectUnauthorized?: boolean; + + // If you set this to true, any data/objects/arrays that you pass to the client socket will be cloned before being sent/queued up. If the socket + // is disconnected and you emit an event, it will be added to a queue which will be processed upon reconnection. The cloneData option is false + // by default; this means that if you emit/publish an object and that object changes somewhere else in your code before the queue is processed, + // then the changed version of that object will be sent out to the server. + cloneData?: boolean; + + // This is true by default. If you set this to false, then the socket will not automatically try to subscribe to pending subscriptions on + // connect - Instead, you will have to manually invoke the processSubscriptions callback from inside the 'connect' event handler on the client side. + // See SCSocket Client API. This gives you more fine-grained control with regards to when pending subscriptions are processed after the socket + // connection is established (or re-established). + autoSubscribeOnConnect?: boolean; + + // Lets you set a custom codec engine. This allows you to specify how data gets encoded before being sent over the wire and how it gets decoded + // once it reaches the other side. The codecEngine must be an object which exposes an encode(object) and a decode(encodedData) function. + // The encode function can return any data type - Commonly a string or a Buffer/ArrayBuffer. The decode function needs to return a JavaScript + // object which adheres to the SC protocol. The idea of using a custom codec is that it allows you to compress SC packets in any format you like + // (optimized for any use case) - By decoding these packets back into their original protocol form, SC will be able process them appropriately. + // Note that if you provide a codecEngine when creating a client socket see 'codecEngine', you will need to make sure that the server uses the + // same codec by passing the same engine to `worker.scServer.setCodecEngine(codecEngine)` when your SC worker initializes on the server side + // (see 'setCodecEngine' method here). The default codec engine used by SC is here. + codecEngine?: SCServer.SCCodecEngine | null; + + // A prefix to add to the channel names. + channelPrefix?: string | null; + + subscriptionRetryOptions?: object | null; + } + + interface AutoReconnectOptions { + initialDelay?: number; + randomness?: number; + multiplier?: number; + maxDelay?: number; + } + + interface AuthStatus { + isAuthenticated: AuthStates; + authError: Error; + } + + interface AuthStateChangeData { + oldState: AuthStates; + newState: AuthStates; + } + + interface ConnectStatus { + id: string; + pingTimeout: number; + isAuthenticated: boolean; + authToken?: object; + authError?: Error; + } + + interface SubscribeStateChangeData { + channel: string; + oldState: ChannelState; + newState: ChannelState; + subscriptionOptions: SCChannelOptions; + } + + type WatcherFunction = (data: any) => void; + type AuthStates = "authenticated" | "unauthenticated"; + type States = "connecting" | "open" | "closed"; +} diff --git a/types/socketcluster-client/socketcluster-client-tests.ts b/types/socketcluster-client/socketcluster-client-tests.ts new file mode 100644 index 0000000000..527385a5eb --- /dev/null +++ b/types/socketcluster-client/socketcluster-client-tests.ts @@ -0,0 +1,75 @@ +// Adapted from README + +import { create, destroy } from "socketcluster-client"; +import { ClientOptions } from "socketcluster-client/lib/scclientsocket"; + +const secureClientOptions: ClientOptions = { + hostname: "securedomain.com", + secure: true, + port: 443, + rejectUnauthorized: false +}; + +let socket = create(secureClientOptions); + +socket.on("connect", () => { + console.log("CONNECTED"); +}); + +// Listen to an event called 'rand' from the server +socket.on("rand", (num: any) => { + console.log("RANDOM: " + num); +}); + +const options: ClientOptions = { + path: "/socketcluster/", + port: 8000, + hostname: "127.0.0.1", + autoConnect: true, + secure: false, + rejectUnauthorized: false, + connectTimeout: 10000, // milliseconds + ackTimeout: 10000, // milliseconds + channelPrefix: null, + disconnectOnUnload: true, + multiplex: true, + autoReconnectOptions: { + initialDelay: 10000, // milliseconds + randomness: 10000, // milliseconds + multiplier: 1.5, // decimal + maxDelay: 60000 // milliseconds + }, + authEngine: null, + codecEngine: null, + subscriptionRetryOptions: {}, + query: { + yourparam: "hello" + } +}; +socket = create(options); + +socket.on("subscribe", channelname => { + console.log("subscribe:" + channelname); +}); + +socket.on("subscribeFail", channelname => { + console.log("subscribeFail:" + channelname); +}); + +socket.on("unsubscribe", channelname => { + console.log("unsubscribe:" + channelname); +}); + +socket.on("subscribeStateChange", data => { + console.log("subscribeStateChange:" + JSON.stringify(data)); +}); + +socket.on("message", data => { + console.log("message:" + data); +}); + +const channels = socket.channels; +const testChannel = channels["test"]; +const state = testChannel.getState(); + +destroy(socket); diff --git a/types/socketcluster-client/tsconfig.json b/types/socketcluster-client/tsconfig.json new file mode 100644 index 0000000000..54fc6ea8af --- /dev/null +++ b/types/socketcluster-client/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "lib/scclientsocket.d.ts", + "socketcluster-client-tests.ts" + ] +} diff --git a/types/socketcluster-client/tslint.json b/types/socketcluster-client/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/socketcluster-client/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/socketcluster-server/index.d.ts b/types/socketcluster-server/index.d.ts new file mode 100644 index 0000000000..7466d1daed --- /dev/null +++ b/types/socketcluster-server/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for socketcluster-server 13.1 +// Project: https://github.com/SocketCluster/socketcluster-server +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { Server } from "http"; + +export import SCServer = require("./scserver"); +export import SCServerSocket = require("./scserversocket"); + +export function listen(port?: number, options?: SCServer.SCServerOptions, listeningListener?: () => void): SCServer; +export function listen(port?: number, listeningListener?: () => void): SCServer; + +export function attach(server: Server, options?: SCServer.SCServerOptions): SCServer; diff --git a/types/socketcluster-server/scserver.d.ts b/types/socketcluster-server/scserver.d.ts new file mode 100644 index 0000000000..a7147aa2dd --- /dev/null +++ b/types/socketcluster-server/scserver.d.ts @@ -0,0 +1,315 @@ +import { EventEmitter } from "events"; +import { Secret } from "jsonwebtoken"; +import { ServerOptions } from "https"; +import { IncomingMessage, Server } from "http"; +import { SCAuthEngine } from "sc-auth"; +import { SCExchange } from "sc-broker-cluster"; +import WebSocket = require("ws"); + +import SCServerSocket = require("./scserversocket"); + +declare class SCServer extends EventEmitter { + readonly MIDDLEWARE_HANDSHAKE_WS: "handshakeWS"; + readonly MIDDLEWARE_HANDSHAKE_SC: "handshakeSC"; + readonly MIDDLEWARE_AUTHENTICATE: "authenticate"; + readonly MIDDLEWARE_SUBSCRIBE: "subscribe"; + readonly MIDDLEWARE_PUBLISH_IN: "publishIn"; + readonly MIDDLEWARE_PUBLISH_OUT: "publishOut"; + readonly MIDDLEWARE_EMIT: "emit"; + + options: SCServer.SCServerOptions; + exchange: SCExchange; + + clients: { + [id: string]: SCServerSocket; + }; + clientsCount: number; + + pendingClients: { + [id: string]: SCServerSocket; + }; + pendingClientsCount: number; + + constructor(options?: SCServer.SCServerOptions); + + on(event: "connection", listener: SCServer.connectionListenerFunction): this; + + addMiddleware(type: "handshakeWS", middlewareFn: (req: IncomingMessage, next: SCServer.nextMiddlewareFunction) => void): void; + addMiddleware(type: "handshakeSC", middlewareFn: (req: SCServer.HandshakeSCRequest, next: SCServer.nextHandshakeSCMiddlewareFunction) => void): void; + addMiddleware(type: "authenticate", middlewareFn: (req: SCServer.AuthenticateRequest, next: SCServer.nextAuthenticateMiddlewareFunction) => void): void; + addMiddleware(type: "subscribe", middlewareFn: (req: SCServer.SubscribeRequest, next: SCServer.nextMiddlewareFunction) => void): void; + addMiddleware(type: "publishIn", middlewareFn: (req: SCServer.PublishInRequest, next: SCServer.nextMiddlewareFunction) => void): void; + addMiddleware(type: "publishOut", middlewareFn: (req: SCServer.PublishOutRequest, next: SCServer.nextMiddlewareFunction) => void): void; + addMiddleware(type: "emit", middlewareFn: (req: SCServer.EmitRequest, next: SCServer.nextMiddlewareFunction) => void): void; + + setAuthEngine(authEngine: SCAuthEngine): void; + setCodecEngine(codecEngine: SCServer.SCCodecEngine): void; +} + +export = SCServer; + +declare namespace SCServer { + interface AuthToken { + [x: string]: any; + } + + interface SCServerOptions { + // The port on which to listen for outside connections/requests + port?: number; + + // Number of worker processes + workers?: number; + + // Number of broker processes + brokers?: number; + + // Should be either 'dev' or 'prod' - This affects the shutdown procedure + // when a 'SIGUSR2' signal is received by master. In 'dev', a SIGUSR2 will + // trigger an immediate shutdown of workers. In 'prod' workers will + // be terminated progressively in accordance with processTermTimeout. + environment?: string; + + // Setting this to true will cause the master process to shut down when + // it receives a SIGUSR2 signal (instead of just the workers). + // If you're using nodemon, set this to true. + killMasterOnSignal?: boolean; + + // A unique name for your app (this is used internally for + // various things such as the directory name in which to store socket + // file descriptors) - If you don't provide an appName, SC will + // generate a random one (UUID v4) + appName?: string; + + // This can be the name of an npm module or a path to a Node.js module + // to use as the WebSocket server engine. + // You can now set this to 'sc-uws' for a massive speedup of at least 2x! + wsEngine?: string; + + // An ID to associate with this specific instance of SC + // this may be useful if you are running an SC app on multiple + // hosts - You can access the instanceId from the Broker object + // (inside brokerController) - If you don't provide an instanceId, + // SC will generate a random one (UUID v4) + instanceId?: string; + + // A key which various SC processes will use to interact with + // scBroker broker processes securely, defaults to a 256 bits + // cryptographically random hex string + secretKey?: string; + + // The key which SC will use to encrypt/decrypt authTokens, defaults + // to a 256 bits cryptographically random hex string + // The default JWT algorithm used is 'HS256'. + // If you want to use RSA or ECDSA, you should provide a authPrivateKey + // and authPublicKey instead of authKey. + authKey?: Secret; + + // perMessageDeflate compression. Note that this option is passed directly to the wsEngine's + // Server object. So if you're using 'ws' as the engine, you can pass an object instead of + // a boolean. Search for perMessageDeflate here: + // https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback + // Note that by default, per-message deflate only kicks in for messages > 1024 bytes. + perMessageDeflate?: boolean; + + // If using an RSA or ECDSA algorithm to sign the authToken, you will need + // to provide an authPrivateKey and authPublicKey in PEM format (string or Buffer). + authPrivateKey?: Secret; + authPublicKey?: Secret; + + // The default expiry for auth tokens in seconds + authDefaultExpiry?: number; + + // The algorithm to use to sign and verify JWT tokens. + authAlgorithm?: string; + + // Crash workers when an error happens - This is the most sensible default + crashWorkerOnError?: boolean; + + // Reboot workers when they crash - This is a necessity + // in production but can be turned off for debugging + rebootWorkerOnCrash?: boolean; + + // Kill/respawn a worker process if its memory consumption exceeds this + // threshold (in bytes) - If this is null (default), this behavior + // will be switched off + killWorkerMemoryThreshold?: number; + + // Can be 'http' or 'https' + protocol?: "http" | "https"; + + // This is the same as the object provided to Node.js's https server + protocolOptions?: ServerOptions; + + // A log level of 3 will log everything, 2 will show notices and errors, + // 1 will only log errors, 0 will log nothing + logLevel?: 0 | 1 | 2 | 3; + + // In milliseconds, how long a client has to connect to SC before timing out + connectTimeout?: number; + + // In milliseconds - If the socket handshake hasn't been completed before + // this timeout is reached, the new connection attempt will be terminated. + handshakeTimeout?: number; + + // In milliseconds, the timeout for calling res(err, data) when + // your emit() call expects an ACK response from the other side + // (when callback is provided to emit) + ackTimeout?: number; + + // In milliseconds, the timeout for calling res(err, data) when + // your sendToWorker, sendToBroker or sendToMaster (IPC) call + // expects an ACK response from the other process + // (when callback is provided) + ipcAckTimeout?: number; + + // In milliseconds - If the socket cannot upgrade transport + // within this period, it will stop trying + socketUpgradeTimeout?: number; + + // Origins which are allowed to connect to the real-time scServer + origins?: string; + + // The maximum number of unique channels which a single + // socket can subscribe to + socketChannelLimit?: number; + + // The interval in milliseconds on which to + // send a ping to the client to check that + // it is still alive + pingInterval?: number; + + // How many milliseconds to wait without receiving a ping + // before closing the socket + pingTimeout?: number; + + // Maximum amount of milliseconds to wait before force-killing + // a process after it was passed a 'SIGTERM' or 'SIGUSR2' signal + processTermTimeout?: number; + + // Whether or not errors from child processes (workers and brokers) + // should be passed to the current master process + propagateErrors?: boolean; + + // Whether or not warnings from child processes (workers and brokers) + // should be passed to the current master process + propagateWarnings?: number; + + // Whether or not a 'warning' event should be emitted (and logged to console) + // whenever an action is blocked by a middleware function + middlewareEmitWarnings?: number; + + // Lets you specify a host name to bind to - Defaults to + // 127.0.0.1 (localhost) + host?: string; + + // The path to a file used to bootstrap worker processes + workerController?: string; + + // The path to a file used to bootstrap broker processes + brokerController?: string; + + // The path to a file used to bootstrap the workerCluster process + workerClusterController?: string; + + // By default, SC will reboot all workers when it receives a 'SIGUSR2' signal - + // This can be used for updating workers with fresh source code in production + rebootOnSignal?: boolean; + + // If you run your master process (server.js) as super user, this option + // lets you downgrade worker and broker processes to run under + // the specified user (with fewer permissions than master) - You can provide + // a Linux UID or username + downgradeToUser?: number | string; + + // The URL path reserved by SocketCluster clients to interact with the server + path?: string; + + // The root directory in which to store your socket files in Linux. + socketRoot?: string; + + // Defaults to "rr", but can be set to "none" + schedulingPolicy?: "rr" | "none"; + + // Whether or not clients are allowed to publish messages to channels + allowClientPublish?: boolean; + + // This option is passed to the Node.js HTTP server if provided + tcpSynBacklog?: number; + + // SC keeps track of request per minutes internally - This allows you to change + // how often this gets updated + workerStatusInterval?: number; + + // This allows you to batch multiple messages together when passing them across + // message brokers. This may improve the efficiency of your pub/sub operations. + // This value is in milliseconds. 5 is generally a safe value to set this to. + pubSubBatchDuration?: number; + + // The default clustering/brokering engine (Node.js module name) which provides the + // SCWorker.exchange object and manages brokers behind the scenes. + // You shouldn't need to change this unless you want to build your own + // process clustering engine (which is difficult to do). + brokerEngine?: string; + + wsEngineServerOptions?: WebSocket.ClientOptions; + maxPayload?: number; + pingTimeoutDisabled?: boolean; + authSignAsync?: boolean; + authVerifyAsync?: boolean; + httpServer?: Server; + } + + interface SCServerSocketStatus { + id: string; + pingTimeout: number; + } + + interface HandshakeSCRequest { + socket: SCServerSocket; + } + + interface AuthenticateRequest { + socket: SCServerSocket; + authToken: AuthToken; + } + + interface SubscribeRequest { + socket: SCServerSocket; + authTokenExpiredError?: Error; + channel?: string; + waitForAuth?: boolean; + data?: any; + } + + interface PublishInRequest { + socket: SCServerSocket; + authTokenExpiredError?: Error; + channel?: string; + data?: any; + ackData?: any; + } + + interface PublishOutRequest { + socket: SCServerSocket; + channel?: string; + data?: any; + useCache?: boolean; + } + + interface EmitRequest { + socket: SCServerSocket; + authTokenExpiredError?: Error; + event: string; + data?: any; + } + + type nextMiddlewareFunction = (error?: true | string | Error) => void; + type nextHandshakeSCMiddlewareFunction = (error?: true | string | Error | null, statusCode?: number) => void; + type nextAuthenticateMiddlewareFunction = (error?: true | string | Error | null, isBadToken?: boolean) => void; + type connectionListenerFunction = (scSocket: SCServerSocket, serverSocketStatus: SCServerSocketStatus) => void; + + interface SCCodecEngine { + decode: (input: any) => any; + ncode: (object: any) => any; + } +} diff --git a/types/socketcluster-server/scserversocket.d.ts b/types/socketcluster-server/scserversocket.d.ts new file mode 100644 index 0000000000..7b32cef72c --- /dev/null +++ b/types/socketcluster-server/scserversocket.d.ts @@ -0,0 +1,43 @@ +import Emitter = require("component-emitter"); +import { IncomingMessage } from "http"; +import { SCExchange } from "sc-broker-cluster"; +import { SignOptions } from "jsonwebtoken"; +import WebSocket = require("ws"); + +import SCServer = require("./scserver"); + +declare class SCServerSocket extends Emitter { + readonly CONNECTING: "connecting"; + readonly OPEN: "open"; + readonly CLOSED: "closed"; + + readonly AUTHENTICATED: "authenticated"; + readonly UNAUTHENTICATED: "unauthenticated"; + + id: string; + request: IncomingMessage; + + remoteAddress: string; + remoteFamily: string; + remotePort: number; + + exchange: SCExchange; + + state: "connecting" | "open" | "closed"; + authState: "authenticated" | "unauthenticated"; + authToken?: SCServer.AuthToken; + + constructor(id: string, server: SCServer, socket: WebSocket); + + getState(): "connecting" | "open" | "closed"; + disconnect(code?: number, data?: any): void; + send(data: any, options: { mask?: boolean; binary?: boolean; compress?: boolean; fin?: boolean }): void; + getAuthToken(): SCServer.AuthToken; + setAuthToken(data: SCServer.AuthToken, options?: SignOptions): void; + deauthenticate(): void; + kickOut(channel?: string, message?: string, callback?: () => void): void; + subscriptions(): string[]; + isSubscribed(channel?: string): boolean; +} + +export = SCServerSocket; diff --git a/types/socketcluster-server/socketcluster-server-tests.ts b/types/socketcluster-server/socketcluster-server-tests.ts new file mode 100644 index 0000000000..3d62fe9041 --- /dev/null +++ b/types/socketcluster-server/socketcluster-server-tests.ts @@ -0,0 +1,39 @@ +// Adapted from README + +// Using with basic http(s) module (example) + +import http = require("http"); +import * as socketClusterServer from "socketcluster-server"; + +let httpServer = http.createServer(); +let scServer = socketClusterServer.attach(httpServer); + +scServer.on("connection", socket => { + // ... Handle new socket connections here +}); + +httpServer.listen(8000); + +// Using with Express (example) + +import serveStatic = require("serve-static"); +import path = require("path"); +import express = require("express"); + +const app = express(); + +app.use(serveStatic(path.resolve(__dirname, "public"))); + +httpServer = http.createServer(); + +// Attach express to our httpServer +httpServer.on("request", app); + +// Attach socketcluster-server to our httpServer +scServer = socketClusterServer.attach(httpServer); + +scServer.on("connection", socket => { + // ... Handle new socket connections here +}); + +httpServer.listen(8000); diff --git a/types/socketcluster-server/tsconfig.json b/types/socketcluster-server/tsconfig.json new file mode 100644 index 0000000000..be1a6bdcb0 --- /dev/null +++ b/types/socketcluster-server/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "scserver.d.ts", + "scserversocket.d.ts", + "socketcluster-server-tests.ts" + ] +} diff --git a/types/socketcluster-server/tslint.json b/types/socketcluster-server/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/socketcluster-server/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/socketcluster/fsutil.d.ts b/types/socketcluster/fsutil.d.ts new file mode 100644 index 0000000000..bcfcbfc59f --- /dev/null +++ b/types/socketcluster/fsutil.d.ts @@ -0,0 +1,11 @@ +import { PathLike } from "fs"; + +export function fileExists(filePath: PathLike, callback: (exists: boolean) => void): void; + +export function waitForFile( + filePath: PathLike, + checkInterval: number, + startTime: number, + maxWaitDuration: number, + timeoutErrorMessage?: string +): Promise; diff --git a/types/socketcluster/index.d.ts b/types/socketcluster/index.d.ts new file mode 100644 index 0000000000..0ec8485cfa --- /dev/null +++ b/types/socketcluster/index.d.ts @@ -0,0 +1,84 @@ +// Type definitions for socketcluster 14.0 +// Project: https://github.com/SocketCluster/socketcluster +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { EventEmitter } from "events"; +import { SCServer } from "socketcluster-server"; +import { ChildProcess } from "child_process"; + +interface WorkerStartInfo { + id: number; + pid: number; + respawn: boolean; +} + +interface WorkerClusterStartInfo { + pid: number; + childProcess: ChildProcess; +} + +interface WorkerClusterReadyInfo { + pid: number; + childProcess: ChildProcess; +} + +interface WorkerClusterExitInfo { + pid: number; + code: number; + signal: string; + childProcess: ChildProcess; +} + +export = SocketCluster; + +declare class SocketCluster extends EventEmitter { + readonly EVENT_FAIL: "fail"; + readonly EVENT_WARNING: "warning"; + readonly EVENT_READY: "ready"; + readonly EVENT_WORKER_START: "workerStart"; + readonly EVENT_WORKER_EXIT: "workerExit"; + readonly EVENT_BROKER_START: "brokerStart"; + readonly EVENT_BROKER_EXIT: "brokerExit"; + readonly EVENT_WORKER_CLUSTER_START: "workerClusterStart"; + readonly EVENT_WORKER_CLUSTER_READY: "workerClusterReady"; + readonly EVENT_WORKER_CLUSTER_EXIT: "workerClusterExit"; + + options: SCServer.SCServerOptions; + + constructor(options?: SCServer.SCServerOptions); + + on(event: "fail", listener: (err: Error) => void): this; + on(event: "warning", listener: (warning: Error) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "workerStart", listener: (workerInfo: WorkerStartInfo) => void): this; + on(event: "workerExit", listener: (workerInfo: SocketCluster.WorkerExitInfo) => void): this; + on(event: "brokerStart", listener: (brokerInfo: SocketCluster.BrokerStartInfo) => void): this; + on(event: "brokerExit", listener: (brokerInfo: SocketCluster.BrokerExitInfo) => void): this; + on(event: "workerClusterStart", listener: (workerClusterInfo: WorkerClusterStartInfo) => void): this; + on(event: "workerClusterReady", listener: (workerClusterInfo: WorkerClusterReadyInfo) => void): this; + on(event: "workerClusterExit", listener: (workerClusterInfo: WorkerClusterExitInfo) => void): this; +} + +declare namespace SocketCluster { + interface WorkerExitInfo { + id: number; + pid: number; + code: number; + signal: string; + } + + interface BrokerStartInfo { + id: number; + pid: number; + respawn: boolean; + } + + interface BrokerExitInfo { + id: number; + pid: number; + code: number; + signal: string; + } +} diff --git a/types/socketcluster/scbroker.d.ts b/types/socketcluster/scbroker.d.ts new file mode 100644 index 0000000000..461801aa63 --- /dev/null +++ b/types/socketcluster/scbroker.d.ts @@ -0,0 +1,3 @@ +import SCBroker = require("sc-broker-cluster/scbroker"); + +export = SCBroker; diff --git a/types/socketcluster/scworker.d.ts b/types/socketcluster/scworker.d.ts new file mode 100644 index 0000000000..48502692be --- /dev/null +++ b/types/socketcluster/scworker.d.ts @@ -0,0 +1,63 @@ +import { EventEmitter } from "events"; +import { Server as httpServer } from "http"; +import { Server as httpsServer } from "https"; +import { SCServer, SCServerSocket } from "socketcluster-server"; +import { SCAuthEngine } from "sc-auth"; +import { SCExchange } from "sc-broker-cluster"; + +export = SCWorker; + +type middlewareFunction = (options: SCServer.SCServerOptions, next: (error?: string | Error) => void) => void; + +declare class SCWorker extends EventEmitter { + readonly EVENT_ERROR: "error"; + readonly EVENT_WARNING: "warning"; + readonly EVENT_EXIT: "exit"; + readonly EVENT_READY: "ready"; + readonly EVENT_CONNECTION: "connection"; + + readonly MIDDLEWARE_START: "start"; + + id: number; + isLeader: boolean; + options: SCServer.SCServerOptions; + httpServer: httpServer | httpsServer; + scServer: SCServer; + exchange: SCExchange; + auth: SCAuthEngine; + + constructor(options?: SCServer.SCServerOptions); + + run(): void; + + getSCServer(): SCServer; + getHTTPServer(): httpServer | httpsServer; + getSocketPath(): string; + + setAuthEngine(authEngine: SCAuthEngine): void; + setCodecEngine(codecEngine: SCServer.SCCodecEngine): void; + + open(): void; + close(callback?: () => void): void; + + addMiddleware(type: "start", middlewareFn: middlewareFunction): void; + removeMiddleware(type: "start", middlewareFn: middlewareFunction): void; + + startHTTPServer(): void; + start(): Promise; + + getStatus(): { + clientCount: any; + httpRPM: number; + wsRPM: number; + }; + + sendToMaster(data: any, callback: (err: Error | null, data: any) => void): void; + respondToMaster(err: Error | null, data: any, rid: number): void; + + on(event: "connection", listener: (scSocket: SCServerSocket) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "warning", listener: (warning: Error) => void): this; + on(event: "masterMessage", listener: (data: any, respond: (err: Error | null, responseData: any) => void) => void): this; +} diff --git a/types/socketcluster/socketcluster-tests.ts b/types/socketcluster/socketcluster-tests.ts new file mode 100644 index 0000000000..85ad9c3d05 --- /dev/null +++ b/types/socketcluster/socketcluster-tests.ts @@ -0,0 +1,76 @@ +import * as fsutil from "socketcluster/fsutil"; +import SocketCluster = require("socketcluster"); +import { SCServer } from "socketcluster-server"; +import { ChildProcess } from "child_process"; + +//////////////////////////////////////////////////// +/// SocketCluster tests +//////////////////////////////////////////////////// + +{ + const options: SCServer.SCServerOptions = { port: 80 }; + + let sc = new SocketCluster(); + sc = new SocketCluster(options); + sc.options = { environment: "prod" }; + + sc.on(sc.EVENT_FAIL, err => { + const error: Error = err; + }); + sc.on(sc.EVENT_WARNING, warning => { + const warn: Error = warning; + }); + + sc.on(sc.EVENT_READY, () => {}); + + sc.on(sc.EVENT_WORKER_START, workerInfo => { + const id: number = workerInfo.id; + const pid: number = workerInfo.pid; + const respawn: boolean = workerInfo.respawn; + }); + sc.on(sc.EVENT_WORKER_EXIT, workerInfo => { + const id: number = workerInfo.id; + const pid: number = workerInfo.pid; + const code: number = workerInfo.code; + const signal: string = workerInfo.signal; + }); + + sc.on(sc.EVENT_BROKER_START, brokerInfo => { + const id: number = brokerInfo.id; + const pid: number = brokerInfo.pid; + const respawn: boolean = brokerInfo.respawn; + }); + sc.on(sc.EVENT_BROKER_EXIT, brokerInfo => { + const id: number = brokerInfo.id; + const pid: number = brokerInfo.pid; + const code: number = brokerInfo.code; + const signal: string = brokerInfo.signal; + }); + + sc.on(sc.EVENT_WORKER_CLUSTER_START, workerClusterInfo => { + const pid: number = workerClusterInfo.pid; + const childProcess: ChildProcess = workerClusterInfo.childProcess; + }); + sc.on(sc.EVENT_WORKER_CLUSTER_READY, workerClusterInfo => { + const pid: number = workerClusterInfo.pid; + const childProcess: ChildProcess = workerClusterInfo.childProcess; + }); + sc.on(sc.EVENT_WORKER_CLUSTER_EXIT, workerClusterInfo => { + const pid: number = workerClusterInfo.pid; + const code: number = workerClusterInfo.code; + const signal: string = workerClusterInfo.signal; + const childProcess: ChildProcess = workerClusterInfo.childProcess; + }); +} + +//////////////////////////////////////////////////// +/// fsutil tests +//////////////////////////////////////////////////// + +{ + fsutil.fileExists("/path/to/folder", err => {}); + fsutil.fileExists(Buffer.from(""), err => {}); + + const pathPromise: Promise = fsutil.waitForFile("/path/to/folder", 100, 0, 100); + const bufferPromise: Promise = fsutil.waitForFile(Buffer.from(""), 0, 0, 0, "timeout"); +} diff --git a/types/socketcluster/tsconfig.json b/types/socketcluster/tsconfig.json new file mode 100644 index 0000000000..1a0267f5f0 --- /dev/null +++ b/types/socketcluster/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fsutil.d.ts", + "scbroker.d.ts", + "scworker.d.ts", + "socketcluster-tests.ts" + ] +} diff --git a/types/socketcluster/tslint.json b/types/socketcluster/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/socketcluster/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From 96d4557ecde6e7cedc60cf9fa6486aa19ffce841 Mon Sep 17 00:00:00 2001 From: Zak Angelle Date: Fri, 30 Nov 2018 12:53:15 -0600 Subject: [PATCH 24/66] yup: Add resolve type to TestContext --- types/yup/index.d.ts | 1 + types/yup/yup-tests.ts | 2 ++ 2 files changed, 3 insertions(+) diff --git a/types/yup/index.d.ts b/types/yup/index.d.ts index 821b0e3526..7d93dd3326 100644 --- a/types/yup/index.d.ts +++ b/types/yup/index.d.ts @@ -206,6 +206,7 @@ export interface TestContext { options: ValidateOptions; parent: any; schema: Schema; + resolve: (value: any) => any; createError: (params: { path: string; message: string }) => ValidationError; } diff --git a/types/yup/yup-tests.ts b/types/yup/yup-tests.ts index efef78d319..b4dedc6bcb 100644 --- a/types/yup/yup-tests.ts +++ b/types/yup/yup-tests.ts @@ -174,6 +174,8 @@ const testContext = function(this: TestContext) { this.parent; // $ExpectType Schema this.schema; + // $ExpectType (value: any) => any + this.resolve; // $ExpectType ValidationError this.createError({ path: "1", message: "1" }); return true; From 2e2869dcd8f5cbc8be06e600d789dd9c99d08c46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Den=C3=A8le?= Date: Fri, 30 Nov 2018 21:51:13 +0100 Subject: [PATCH 25/66] [puppeteer] 1.11.0 update type definitions --- types/puppeteer/index.d.ts | 214 ++++++++++++++++++------------------- 1 file changed, 102 insertions(+), 112 deletions(-) diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index cbb31f2fd0..202cc05181 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for puppeteer 1.10 +// Type definitions for puppeteer 1.11 // Project: https://github.com/GoogleChrome/puppeteer#readme // Definitions by: Marvin Hagemeister // Christopher Deutsch @@ -398,6 +398,8 @@ export interface Cookie { path: string; /** The cookie Unix expiration time in seconds. */ expires: number; + /** The cookie size */ + size: number; /** The cookie http only flag. */ httpOnly: boolean; /** The session cookie flag. */ @@ -414,7 +416,6 @@ export interface DeleteCookie { url?: string; domain?: string; path?: string; - secure?: boolean; } export interface SetCookie { @@ -579,20 +580,20 @@ export interface PDFOptions { * @default 'Letter' */ format?: PDFFormat; - /** Paper width, accepts values labeled with units. */ - width?: string; - /** Paper height, accepts values labeled with units. */ - height?: string; + /** Paper width, accepts values labeled with units. Treat numbers as pixel values */ + width?: string | number; + /** Paper height, accepts values labeled with units. Treat numbers as pixel values */ + height?: string | number; /** Paper margins, defaults to none. */ margin?: { - /** Top margin, accepts values labeled with units. */ - top?: string; - /** Right margin, accepts values labeled with units. */ - right?: string; - /** Bottom margin, accepts values labeled with units. */ - bottom?: string; - /** Left margin, accepts values labeled with units. */ - left?: string; + /** Top margin, accepts values labeled with units. Treat numbers as pixel values */ + top?: string | number; + /** Right margin, accepts values labeled with units. Treat numbers as pixel values */ + right?: string | number; + /** Bottom margin, accepts values labeled with units. Treat numbers as pixel values */ + bottom?: string | number; + /** Left margin, accepts values labeled with units. Treat numbers as pixel values */ + left?: string | number; }; /** @@ -1177,8 +1178,9 @@ export interface FrameBase extends Evalable { /** * Sets the page content. * @param html HTML markup to assign to the page. + * @param options The navigation parameters. */ - setContent(html: string): Promise; + setContent(html: string, options?: NavigationOptions): Promise; /** * This method fetches an element with `selector`, scrolls it into view if needed, @@ -1395,11 +1397,11 @@ export interface AXNode { /** * Whether the checkbox is checked, or "mixed". */ - checked: boolean | string; + checked: boolean | "mixed"; /** * Whether the toggle button is checked, or "mixed". */ - pressed: boolean | string; + pressed: boolean | "mixed"; /** * The level of a heading. */ @@ -1620,9 +1622,9 @@ export interface Page extends EventEmitter, FrameBase { /** * Determines whether cache is enabled on the page. - * @param enabled Whether or not to enable cache on the page. + * @param enabled Whether or not to enable cache on the page. Defaults to true. */ - setCacheEnabled(enabled: boolean): Promise; + setCacheEnabled(enabled?: boolean): Promise; /** * Sets the cookies on the page. @@ -1934,26 +1936,6 @@ export interface Target { } export interface LaunchOptions extends Timeoutable { - /** - * Whether to open chrome in appMode. - * @default false - */ - appMode?: boolean; - /** - * Whether to ignore HTTPS errors during navigation. - * @default false - */ - ignoreHTTPSErrors?: boolean; - /** - * Do not use `puppeteer.defaultArgs()` for launching Chromium. - * @default false - */ - ignoreDefaultArgs?: boolean | string[]; - /** - * Whether to run Chromium in headless mode. - * @default true - */ - headless?: boolean; /** * Path to a Chromium executable to run instead of bundled Chromium. If * executablePath is a relative path, then it is resolved relative to current @@ -1961,10 +1943,73 @@ export interface LaunchOptions extends Timeoutable { */ executablePath?: string; /** - * Slows down Puppeteer operations by the specified amount of milliseconds. - * Useful so that you can see what is going on. + * Do not use `puppeteer.defaultArgs()` for launching Chromium. + * @default false */ - slowMo?: number; + ignoreDefaultArgs?: boolean | string[]; + /** + * Close chrome process on Ctrl-C. + * @default true + */ + handleSIGINT?: boolean; + /** + * Close chrome process on SIGTERM. + * @default true + */ + handleSIGTERM?: boolean; + /** + * Close chrome process on SIGHUP. + * @default true + */ + handleSIGHUP?: boolean; + /** + * Whether to pipe browser process stdout and stderr into process.stdout and + * process.stderr. + * @default false + */ + dumpio?: boolean; + /** + * Specify environment variables that will be visible to Chromium. + * @default `process.env`. + */ + env?: { + [key: string]: string | boolean | number; + }; + /** + * Connects to the browser over a pipe instead of a WebSocket. + * @default false + */ + pipe?: boolean; +} + +export interface ChromeArgOptions { + /** + * Whether to run browser in headless mode. + * @default true unless the devtools option is true. + */ + headless?: boolean; + /** + * Additional arguments to pass to the browser instance. + * The list of Chromium flags can be found here. + */ + args?: string[]; + /** + * Path to a User Data Directory. + */ + userDataDir?: string; + /** + * Whether to auto-open a DevTools panel for each tab. + * If this option is true, the headless option will be set false. + */ + devtools?: boolean; +} + +export interface BrowserOptions { + /** + * Whether to ignore HTTPS errors during navigation. + * @default false + */ + ignoreHTTPSErrors?: boolean; /** * Sets a consistent viewport for each page. Defaults to an 800x600 viewport. null disables the default viewport. */ @@ -2000,81 +2045,26 @@ export interface LaunchOptions extends Timeoutable { isLandscape?: boolean; }; /** - * Additional arguments to pass to the Chromium instance. List of Chromium - * flags can be found here. + * Slows down Puppeteer operations by the specified amount of milliseconds. + * Useful so that you can see what is going on. */ - args?: string[]; - /** - * Close chrome process on Ctrl-C. - * @default true - */ - handleSIGINT?: boolean; - /** - * Close chrome process on SIGTERM. - * @default true - */ - handleSIGTERM?: boolean; - /** - * Close chrome process on SIGHUP. - * @default true - */ - handleSIGHUP?: boolean; - /** - * Whether to pipe browser process stdout and stderr into process.stdout and - * process.stderr. - * @default false - */ - dumpio?: boolean; - /** Path to a User Data Directory. */ - userDataDir?: string; - /** - * Specify environment variables that will be visible to Chromium. - * @default `process.env`. - */ - env?: { - [key: string]: string | boolean | number; - }; - /** - * Whether to auto-open DevTools panel for each tab. If this option is true, the headless option will be set false. - */ - devtools?: boolean; - /** - * Connects to the browser over a pipe instead of a WebSocket. - * @default false - */ - pipe?: boolean; -} - -export interface DefaultArgsOptions { - /** - * Whether to run browser in headless mode. - * @default true unless the devtools option is true. - */ - headless?: boolean; - /** - * Additional arguments to pass to the browser instance. - * The list of Chromium flags can be found here. - */ - args?: string[]; - /** - * Path to a User Data Directory. - */ - userDataDir?: string; - /** - * Whether to auto-open a DevTools panel for each tab. - * If this option is true, the headless option will be set false. - */ - devtools?: boolean; + slowMo?: number; } export interface ConnectOptions { /** A browser websocket endpoint to connect to. */ browserWSEndpoint?: string; /** - * Whether to ignore HTTPS errors during navigation. - * @default false + * **Experimental** Specify a custom transport object for Puppeteer to use. */ - ignoreHTTPSErrors?: boolean; + transport?: ConnectionTransport; +} + +export interface ConnectionTransport { + send: (message: string) => void; + close: () => void; + onmessage?: (message: string) => void; + onclose?: () => void; } export interface CDPSession extends EventEmitter { @@ -2117,10 +2107,10 @@ export interface CoverageEntry { } /** Attaches Puppeteer to an existing Chromium instance */ -export function connect(options?: ConnectOptions): Promise; +export function connect(options?: ConnectOptions & BrowserOptions): Promise; /** The default flags that Chromium will be launched with */ -export function defaultArgs(options?: DefaultArgsOptions): string[]; +export function defaultArgs(options?: ChromeArgOptions): string[]; /** Path where Puppeteer expects to find bundled Chromium */ export function executablePath(): string; /** The method launches a browser instance with given arguments. The browser will be closed when the parent node.js process is closed. */ -export function launch(options?: LaunchOptions): Promise; +export function launch(options?: LaunchOptions & ChromeArgOptions & BrowserOptions): Promise; From f86366a401ca98ebaa7aa3ec4a0ef5391970eee7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Den=C3=A8le?= Date: Sat, 1 Dec 2018 02:44:09 +0100 Subject: [PATCH 26/66] Prefer notation without arrow function --- types/puppeteer/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index 202cc05181..813f256835 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -2061,10 +2061,10 @@ export interface ConnectOptions { } export interface ConnectionTransport { - send: (message: string) => void; - close: () => void; - onmessage?: (message: string) => void; - onclose?: () => void; + send(message: string): void; + close(): void; + onmessage?(message: string): void; + onclose?(): void; } export interface CDPSession extends EventEmitter { From 0a82ed88126e5b99a876aa5514ce2beedb9f441a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Den=C3=A8le?= Date: Sat, 1 Dec 2018 02:45:40 +0100 Subject: [PATCH 27/66] Remove empty line --- types/puppeteer/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index 813f256835..fe4fb0d14a 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -2033,7 +2033,6 @@ export interface BrowserOptions { */ isMobile?: boolean; /** - * * Specifies if viewport supports touch events. * @default false */ From b506cfa9c04bbeff9866b50a0712808b45ea171b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Den=C3=A8le?= Date: Sat, 1 Dec 2018 03:01:35 +0100 Subject: [PATCH 28/66] Define type for layout dimension --- types/puppeteer/index.d.ts | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index fe4fb0d14a..1b675b20c5 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -513,6 +513,9 @@ export interface DirectNavigationOptions extends NavigationOptions { referer?: string; } +/** Accepts values labeled with units. If number, treat as pixels. */ +export type LayoutDimension = string | number; + export type PDFFormat = | "Letter" | "Legal" @@ -580,22 +583,21 @@ export interface PDFOptions { * @default 'Letter' */ format?: PDFFormat; - /** Paper width, accepts values labeled with units. Treat numbers as pixel values */ - width?: string | number; - /** Paper height, accepts values labeled with units. Treat numbers as pixel values */ - height?: string | number; - /** Paper margins, defaults to none. */ + /** Paper width. */ + width?: LayoutDimension; + /** Paper height. */ + height?: LayoutDimension; + /** Paper margins, defaults to none. */ margin?: { - /** Top margin, accepts values labeled with units. Treat numbers as pixel values */ - top?: string | number; - /** Right margin, accepts values labeled with units. Treat numbers as pixel values */ - right?: string | number; - /** Bottom margin, accepts values labeled with units. Treat numbers as pixel values */ - bottom?: string | number; - /** Left margin, accepts values labeled with units. Treat numbers as pixel values */ - left?: string | number; + /** Top margin. */ + top?: LayoutDimension; + /** Right margin. */ + right?: LayoutDimension; + /** Bottom margin. */ + bottom?: LayoutDimension; + /** Left margin. */ + left?: LayoutDimension; }; - /** * Give any CSS @page size declared in the page priority over what is declared in width and * height or format options. From 8775d384e1fccf160bc9727d076ffdc23ae53c05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Den=C3=A8le?= Date: Sat, 1 Dec 2018 03:17:17 +0100 Subject: [PATCH 29/66] Extends interfaces for ConnectOptions & LaunchOptions --- types/puppeteer/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index 1b675b20c5..e48e29b7ec 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -1937,7 +1937,7 @@ export interface Target { url(): string; } -export interface LaunchOptions extends Timeoutable { +export interface LaunchOptions extends ChromeArgOptions, BrowserOptions, Timeoutable { /** * Path to a Chromium executable to run instead of bundled Chromium. If * executablePath is a relative path, then it is resolved relative to current @@ -2052,7 +2052,7 @@ export interface BrowserOptions { slowMo?: number; } -export interface ConnectOptions { +export interface ConnectOptions extends BrowserOptions { /** A browser websocket endpoint to connect to. */ browserWSEndpoint?: string; /** @@ -2108,10 +2108,10 @@ export interface CoverageEntry { } /** Attaches Puppeteer to an existing Chromium instance */ -export function connect(options?: ConnectOptions & BrowserOptions): Promise; +export function connect(options?: ConnectOptions): Promise; /** The default flags that Chromium will be launched with */ export function defaultArgs(options?: ChromeArgOptions): string[]; /** Path where Puppeteer expects to find bundled Chromium */ export function executablePath(): string; /** The method launches a browser instance with given arguments. The browser will be closed when the parent node.js process is closed. */ -export function launch(options?: LaunchOptions & ChromeArgOptions & BrowserOptions): Promise; +export function launch(options?: LaunchOptions): Promise; From c45cef2c6ebdbb8764f2631154f61213109c5733 Mon Sep 17 00:00:00 2001 From: Kobi Cohen Date: Sun, 2 Dec 2018 12:58:30 +0200 Subject: [PATCH 30/66] updating isMatchWithCustomizer type to accept two more arguments: object and source per lodash docs https://lodash.com/docs/4.17.11#isMatchWith --- types/lodash/common/lang.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/lodash/common/lang.d.ts b/types/lodash/common/lang.d.ts index 9afe554b28..723388c9cc 100644 --- a/types/lodash/common/lang.d.ts +++ b/types/lodash/common/lang.d.ts @@ -1020,7 +1020,7 @@ declare module "../index" { // isMatchWith - type isMatchWithCustomizer = (value: any, other: any, indexOrKey: PropertyName) => boolean; + type isMatchWithCustomizer = (value: any, other: any, indexOrKey: PropertyName, object: object, source: object) => boolean; interface LoDashStatic { /** From f368a2dbfdd73511fbde3ab961ec111ce0486646 Mon Sep 17 00:00:00 2001 From: Christian Sporer Date: Sun, 2 Dec 2018 20:01:52 +0100 Subject: [PATCH 31/66] Adaptations according to the ES6 spec: * https://github.com/definitelyTyped/DefinitelyTyped/#should-i-add-an-empty-namespace-to-a-package-that-doesnt-export-a-module-to-use-es6-style-imports * https://stackoverflow.com/a/39415662 * https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#support-for-import-d-from-cjs-form-commonjs-modules-with---esmoduleinterop --- types/list-stream/list-stream-tests.ts | 2 +- types/list-stream/tsconfig.json | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/types/list-stream/list-stream-tests.ts b/types/list-stream/list-stream-tests.ts index 5f04626b31..3648097ad6 100644 --- a/types/list-stream/list-stream-tests.ts +++ b/types/list-stream/list-stream-tests.ts @@ -1,4 +1,4 @@ -import * as ListStream from "list-stream"; +import ListStream from "list-stream"; let chunk: any = "chunk"; let listStream: ListStream; diff --git a/types/list-stream/tsconfig.json b/types/list-stream/tsconfig.json index 52ec1c73e1..060c211379 100644 --- a/types/list-stream/tsconfig.json +++ b/types/list-stream/tsconfig.json @@ -14,7 +14,8 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true }, "files": [ "index.d.ts", From 3f185078d8bdf57c6669b08a5ea135de65555d9d Mon Sep 17 00:00:00 2001 From: Christian Sporer Date: Sun, 2 Dec 2018 20:04:46 +0100 Subject: [PATCH 32/66] Fix error while running `npm test` --- types/list-stream/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/list-stream/index.d.ts b/types/list-stream/index.d.ts index b51c9bacb0..f92eb5f917 100644 --- a/types/list-stream/index.d.ts +++ b/types/list-stream/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/rvagg/list-stream // Definitions by: IanStorm // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 /// From 5bc22c159118f003bd6898338945e4e7930345a6 Mon Sep 17 00:00:00 2001 From: Robert Stigsson Date: Mon, 3 Dec 2018 09:04:56 +0100 Subject: [PATCH 33/66] recharts: added ReferenceArea.ifOverflow, ReferenceDot.ifOverflow and ReferenceLine.ifOverflow --- types/recharts/index.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/types/recharts/index.d.ts b/types/recharts/index.d.ts index 34e3cbcb88..d2cd6458d0 100644 --- a/types/recharts/index.d.ts +++ b/types/recharts/index.d.ts @@ -11,6 +11,7 @@ // Paul Melnikow // Harry Cruse // Andrew Palugniok +// Robert Stigsson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -634,6 +635,7 @@ export interface ReferenceAreaProps extends Partial { yAxis?: object; isFront?: boolean; alwaysShow?: boolean; + ifOverflow?: 'hidden' | 'visible' | 'discard' | 'extendDomain' x1?: number | string; x2?: number | string; y1?: number | string; @@ -657,6 +659,7 @@ export interface ReferenceDotProps extends EventAttributes, Partial | React.ReactElement; From 4ea0c9f150ab7aec3c4ba6f2ea9e9568c7e0951f Mon Sep 17 00:00:00 2001 From: Robert Stigsson Date: Mon, 3 Dec 2018 09:44:41 +0100 Subject: [PATCH 34/66] recharts: fixed issue with missing semi-colon --- types/recharts/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/recharts/index.d.ts b/types/recharts/index.d.ts index d2cd6458d0..7054b18e08 100644 --- a/types/recharts/index.d.ts +++ b/types/recharts/index.d.ts @@ -635,7 +635,7 @@ export interface ReferenceAreaProps extends Partial { yAxis?: object; isFront?: boolean; alwaysShow?: boolean; - ifOverflow?: 'hidden' | 'visible' | 'discard' | 'extendDomain' + ifOverflow?: 'hidden' | 'visible' | 'discard' | 'extendDomain'; x1?: number | string; x2?: number | string; y1?: number | string; @@ -659,7 +659,7 @@ export interface ReferenceDotProps extends EventAttributes, Partial | React.ReactElement; From d654965211716edda15c5183fb58332760185896 Mon Sep 17 00:00:00 2001 From: craig bruce Date: Mon, 3 Dec 2018 21:03:30 +1100 Subject: [PATCH 35/66] Expose modules globally as nested modules --- .../cast.framework.breaks.d.ts | 169 +- .../cast.framework.d.ts | 1467 +++---- .../cast.framework.events.d.ts | 782 ++-- .../cast.framework.messages.d.ts | 3792 ++++++++--------- .../cast.framework.system.d.ts | 322 +- .../cast.framework.ui.d.ts | 362 +- .../chromecast-caf-receiver-tests.ts | 68 +- types/chromecast-caf-receiver/index.d.ts | 3 + 8 files changed, 3468 insertions(+), 3497 deletions(-) diff --git a/types/chromecast-caf-receiver/cast.framework.breaks.d.ts b/types/chromecast-caf-receiver/cast.framework.breaks.d.ts index 21adf13fb0..5ece1f15e9 100644 --- a/types/chromecast-caf-receiver/cast.framework.breaks.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.breaks.d.ts @@ -1,92 +1,91 @@ import { Break, BreakClip } from "./cast.framework.messages"; -export = cast.framework.breaks; -declare namespace cast.framework.breaks { - class BreakSeekData { - constructor(seekFrom: number, seekTo: number, breaks: Break[]); +export as namespace breaks +export class BreakSeekData { + constructor(seekFrom: number, seekTo: number, breaks: Break[]); - /** - * List of breaks - */ - breaks: Break[]; + /** + * List of breaks + */ + breaks: Break[]; - /** - * Current playback time - */ - seekFrom: number; + /** + * Current playback time + */ + seekFrom: number; - /** - * The time to seek to - */ - seekTo: number; - } - - /** Provide context information for break clip load interceptor. */ - class BreakClipLoadInterceptorContext { - constructor(brk: Break); - - /** - * The container break for the break clip - */ - break: Break; - } - - /** Interface to manage breaks */ - interface BreakManager { - /** - * Get current media break by id. - */ - getBreakById(id: string): Break; - - /** - * Get current media break clip by id - */ - getBreakClipById(id: string): BreakClip; - - /** Get current media break clips. */ - getBreakClips(): BreakClip[]; - - /** Get current media breaks. */ - getBreaks(): Break[]; - - /** Returns true if watched breaks should be played. */ - getPlayWatchedBreak(): boolean; - - /** - * Provide an interceptor to allow developer to insert more break clips or modify current break clip before a break is started. - * If interceptor is null it will reset the interceptor to default one. - * By default VAST fetching and parsing logic in default interceptor. - * So if customized interceptor is set by developer; - * the VAST logic will be overridden and developers should implement their own VAST fetching and parsing logic in the provided interceptor. - */ - setBreakClipLoadInterceptor( - interceptor: ( - breakClip: BreakClip, - breakClipLoaderContext?: BreakClipLoadInterceptorContext - ) => void - ): void; - - /** - * Provide an interceptor for developer to specify what breaks they want to play after seek. - */ - setBreakSeekInterceptor( - seekInterceptor: (breakSeekData: BreakSeekData) => void - ): void; - - /** - * Set a flag to control if the watched client stitching break should be played. - */ - setPlayWatchedBreak(playWatchedBreak: boolean): void; - - /** - * Provide an interceptor to modify VAST tracking URL before it is being sent to server. - * The input of the interceptor is a string of the tracking URL. - * The interceptor can either return a modified string of URL or a Promise of modified string of URL. - * The interceptor can also return null if you want to send the tracking URL by your own code instead of by CAF. - */ - setVastTrackingInterceptor( - interceptor?: (trackingUrl: string) => void - ): void; - } + /** + * The time to seek to + */ + seekTo: number; } + +/** Provide context information for break clip load interceptor. */ +export class BreakClipLoadInterceptorContext { + constructor(brk: Break); + + /** + * The container break for the break clip + */ + break: Break; +} + +/** Interface to manage breaks */ +export interface BreakManager { + /** + * Get current media break by id. + */ + getBreakById(id: string): Break; + + /** + * Get current media break clip by id + */ + getBreakClipById(id: string): BreakClip; + + /** Get current media break clips. */ + getBreakClips(): BreakClip[]; + + /** Get current media breaks. */ + getBreaks(): Break[]; + + /** Returns true if watched breaks should be played. */ + getPlayWatchedBreak(): boolean; + + /** + * Provide an interceptor to allow developer to insert more break clips or modify current break clip before a break is started. + * If interceptor is null it will reset the interceptor to default one. + * By default VAST fetching and parsing logic in default interceptor. + * So if customized interceptor is set by developer; + * the VAST logic will be overridden and developers should implement their own VAST fetching and parsing logic in the provided interceptor. + */ + setBreakClipLoadInterceptor( + interceptor: ( + breakClip: BreakClip, + breakClipLoaderContext?: BreakClipLoadInterceptorContext + ) => void + ): void; + + /** + * Provide an interceptor for developer to specify what breaks they want to play after seek. + */ + setBreakSeekInterceptor( + seekInterceptor: (breakSeekData: BreakSeekData) => void + ): void; + + /** + * Set a flag to control if the watched client stitching break should be played. + */ + setPlayWatchedBreak(playWatchedBreak: boolean): void; + + /** + * Provide an interceptor to modify VAST tracking URL before it is being sent to server. + * The input of the interceptor is a string of the tracking URL. + * The interceptor can either return a modified string of URL or a Promise of modified string of URL. + * The interceptor can also return null if you want to send the tracking URL by your own code instead of by CAF. + */ + setVastTrackingInterceptor( + interceptor?: (trackingUrl: string) => void + ): void; +} + diff --git a/types/chromecast-caf-receiver/cast.framework.d.ts b/types/chromecast-caf-receiver/cast.framework.d.ts index 28b0c69e2d..6e2be61eb0 100644 --- a/types/chromecast-caf-receiver/cast.framework.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.d.ts @@ -1,3 +1,8 @@ +import * as breaks from "./cast.framework.breaks"; +import * as events from "./cast.framework.events"; +import * as messages from "./cast.framework.messages"; +import * as system from "./cast.framework.system"; +import * as ui from "./cast.framework.ui"; import { EventType } from "./cast.framework.events"; import { PlayerState, @@ -27,757 +32,761 @@ import { SystemState } from "./cast.framework.system"; -export = cast.framework; -type HTMLMediaElement = any; -declare namespace cast.framework { - type LoggerLevel = - | "DEBUG" - | "VERBOSE" - | "INFO" - | "WARNING" - | "ERROR" - | "NONE"; +export import breaks = breaks; +export import events = events; +export import ui = ui; +export import system = system; +export import messages = messages; - type ContentProtection = "NONE" | "CLEARKEY" | "PLAYREADY" | "WIDEVINE"; +export type HTMLMediaElement = any; +export as namespace framework +export type LoggerLevel = + | "DEBUG" + | "VERBOSE" + | "INFO" + | "WARNING" + | "ERROR" + | "NONE"; + +export type ContentProtection = "NONE" | "CLEARKEY" | "PLAYREADY" | "WIDEVINE"; + +/** + * Manages text tracks. + */ +export class TextTracksManager { + constructor(params?: any); /** - * Manages text tracks. + * Adds text tracks to the list. */ - class TextTracksManager { - constructor(params?: any); - - /** - * Adds text tracks to the list. - */ - addTracks(tracks: Track[]): void; - - /** - * Creates a text track. - */ - createTrack(): Track; - - /** - * Gets all active text ids. - */ - getActiveIds(): number[]; - - /** - * Gets all active text tracks. - */ - getActiveTracks(): Track[]; - - /** - * Returns the current text track style. - */ - getTextTracksStyle(): TextTrackStyle; - - /** - * Gets text track by id. - */ - getTrackById(id: number): Track; - - /** - * Returns all text tracks. - */ - getTracks(): Track[]; - - /** - * Gets text tracks by language. - */ - getTracksByLanguage(language: string): Track[]; - - /** - * Sets text tracks to be active by id. - */ - setActiveByIds(newIds: number[]): void; - - /** - * Sets text tracks to be active by language. - */ - setActiveByLanguage(language: string): void; - - /** - * Sets text track style. - */ - setTextTrackStyle(style: TextTrackStyle): void; - } + addTracks(tracks: Track[]): void; /** - * QueueManager exposes several queue manipulation APIs to developers. + * Creates a text track. */ - class QueueManager { - constructor(params?: any); - - /** - * Returns the current queue item. - */ - getCurrentItem(): QueueItem; - - /** - * Returns the index of the current queue item. - */ - getCurrentItemIndex(): number; - - /** - * Returns the queue items. - */ - getItems(): QueueItem[]; - - /** - * Inserts items into the queue. - */ - insertItems(items: QueueItem[], insertBefore?: number): void; - - /** - * Removes items from the queue. - */ - removeItems(itemIds: number[]): void; - - /** - * Sets whether to limit the number of queue items to be reported in Media Status (default is true). - */ - setQueueStatusLimit(limitQueueItemsInStatus: boolean): void; - - /** - * Updates existing queue items by matching itemId. - */ - updateItems(items: QueueItem[]): void; - } + createTrack(): Track; /** - * Base implementation of a queue. + * Gets all active text ids. */ - class QueueBase { - /** - * Fetches a window of items using the specified item id as reference; called by the receiver MediaManager when it needs more queue items; - * often as a request from senders. If only one of nextCount and prevCount is non-zero; fetchItems should only return items after or before - * the reference item; if both nextCount and prevCount are non-zero; a window of items including the reference item should be returned. - */ - fetchItems( - itemId: number, - nextCount: number, - prevCount: number - ): QueueItem[] | Promise; - - /** - * Initializes the queue with the requestData. This is called when a new LOAD request comes in to the receiver. - * If this returns or resolves to null; our default queueing implementation will create a queue based on queueData.items or the single media - * in the load request data. - */ - initialize( - requestData: LoadRequestData - ): QueueData | Promise; - - /** - * Returns next items after the reference item; often the end of the current queue; called by the receiver MediaManager. - */ - nextItems(itemId?: number): QueueItem[] | Promise; - - /** - * Sets the current item with the itemId; called by the receiver MediaManager when it changes the current playing item. - */ - onCurrentItemIdChanged(itemId: number): void; - - /** - * A callback for informing the following items have been inserted into the receiver queue in this session. - * A cloud based implementation can optionally choose to update its queue based on the new information. - */ - onItemsInserted(items: QueueItem[], insertBefore?: number): void; - - /** - * A callback for informing the following items have been removed from the receiver queue in this session. - * A cloud based implementation can optionally choose to update its queue based on the new information. - */ - onItemsRemoved(itemIds: number[]): void; - - /** - * Returns previous items before the reference item; often at the beginning of the queue; called by the receiver MediaManager. - */ - prevItems(itemId?: number): QueueItem[] | Promise; - - /** - * Shuffles the queue and returns new queue items. Returns null if the operation is not supported. - */ - shuffle(): QueueItem[] | Promise; - } + getActiveIds(): number[]; /** - * Controls and monitors media playback. + * Gets all active text tracks. */ - class PlayerManager { - constructor(params?: any); - - /** - * Adds an event listener for player event. - */ - addEventListener: ( - eventType: EventType | EventType[], - eventListener: EventHandler - ) => void; - - /** - * Sends a media status message to all senders (broadcast). Applications use this to send a custom state change. - */ - broadcastStatus( - includeMedia?: boolean, - requestId?: number, - customData?: any, - includeQueueItems?: boolean - ): void; - - getAudioTracksManager(): AudioTracksManager; - - /** - * Returns current time in sec in currently-playing break clip. - */ - getBreakClipCurrentTimeSec(): number; - - /** - * Returns duration in sec of currently-playing break clip. - */ - getBreakClipDurationSec(): number; - - /** - * Obtain the breaks (Ads) manager. - */ - getBreakManager(): BreakManager; - - /** - * Returns list of breaks. - */ - getBreaks(): Break[]; - - /** - * Gets current time in sec of current media. - */ - getCurrentTimeSec(): number; - - /** - * Gets duration in sec of currently playing media. - */ - getDurationSec(): number; - - /** - * Returns live seekable range with start and end time in seconds. The values are media time based. - */ - getLiveSeekableRange(): LiveSeekableRange; - - /** - * Gets media information of current media. - */ - getMediaInformation(): MediaInformation; - - /** - * Returns playback configuration. - */ - getPlaybackConfig(): PlaybackConfig; - - /** - * Returns current playback rate. - */ - getPlaybackRate(): number; - - /** - * Gets player state. - */ - getPlayerState(): PlayerState; - - /** - * Get the preferred playback rate. (Can be used on shutdown event to save latest preferred playback rate to a persistent storage; - * so it can be used in next session in the cast options). - */ - getPreferredPlaybackRate(): number; - - /** - * Get the preferred text track language. - */ - getPreferredTextLanguage(): string; - - /** - * Obtain QueueManager API. - */ - getQueueManager(): QueueManager; - - getTextTracksManager(): TextTracksManager; - - /** - * Loads media. - */ - load(loadRequest: LoadRequestData): Promise; - - /** - * Pauses currently playing media. - */ - pause(): void; - - /** - * Plays currently paused media. - */ - play(): void; - - /** - * Requests a text string to be played back locally on the receiver device. - */ - playString(stringId: PlayStringId, args?: string[]): Promise; - - /** - * Request Google Assistant to refresh the credentials. Only works if the original credentials came from the assistant. - */ - refreshCredentials(): Promise; - - /** - * Removes the event listener added for given player event. If event listener is not added; it will be ignored. - */ - removeEventListener( - eventType: EventType | EventType[], - eventListener: EventHandler - ): void; - - /** - * Seeks in current media. - */ - seek(seekTime: number): void; - - /** - * Sends an error to a specific sender - */ - sendError( - senderId: string, - requestId: number, - type: ErrorType, - reason?: ErrorReason, - customData?: any - ): void; - - /** - * Send local media request. - */ - sendLocalMediaRequest(request: RequestData): void; - - /** - * Sends a media status message to a specific sender. - */ - sendStatus( - senderId: string, - requestId: number, - includeMedia?: boolean, - customData?: any, - includeQueueItems?: boolean - ): void; - - /** - * Sets the IDLE reason. This allows applications that want to force the IDLE state to indicate the reason that made the player going to IDLE state - * (a custom error; for example). The idle reason will be sent in the next status message. NOTE: Most applications do not need to set this value; - * it is only needed if they want to make the player go to IDLE in special circumstances and the default idleReason does not reflect their intended - * behavior. - */ - setIdleReason(idleReason: IdleReason): void; - - /** - * Sets MediaElement to use. If Promise of MediaElement is set; media begins playback after Promise is resolved. - */ - setMediaElement(mediaElement: HTMLMediaElement): void; - - /** - * Sets media information. - */ - setMediaInformation( - mediaInformation: MediaInformation, - opt_broadcast?: boolean - ): void; - - /** - * Sets a handler to return or modify PlaybackConfig; for a specific load request. The handler paramaters are the load request data - * and default playback config for the receiver (provided in the context options). The handler should returns a modified playback config; - * or null to prevent the media from playing. The return value can be a promise to allow waiting for data from the server. - */ - setMediaPlaybackInfoHandler( - handler: ( - loadRequestData: LoadRequestData, - playbackConfig: PlaybackConfig - ) => void - ): void; - - /** - * Sets a handler to return the media url for a load request. This handler can be used to avoid having the media content url published as part - * of the media status. By default the media contentId is used as the content url. - */ - setMediaUrlResolver( - resolver: (loadRequestData: LoadRequestData) => void - ): void; - - /** - * Provide an interceptor of incoming and outgoing messages. - * The interceptor can update the request data; and return updated data; a promise of - * updated data if need to get more data from the server; or null if the request should not be handled. - * Note that if load message interceptor is provided; and no interceptor is provided for preload - - * the load interceptor will be called for preload messages. - */ - setMessageInterceptor( - type: MessageType, - interceptor: (requestData: RequestData) => Promise - ): void; - - /** - * Sets playback configuration on the PlayerManager. - */ - setPlaybackConfig(playbackConfig: PlaybackConfig): void; - - /** - * Set the preferred playback rate for follow up load or media items. The preferred playback rate will be updated automatically to the latest - * playback rate that was provided by a load request or explicit set of playback rate. - */ - setPreferredPlaybackRate(preferredPlaybackRate: number): void; - - /** - * Set the preferred text track language. The preferred text track language will be updated automatically to the latest enabled language - * by a load request or explicit change to text tracks. (Should be called only in idle state; and Will only apply to next loaded media). - */ - setPreferredTextLanguage(preferredTextLanguage: string): void; - - /** - * Stops currently playing media. - */ - stop(): void; - } + getActiveTracks(): Track[]; /** - * Configuration to customize playback behavior. + * Returns the current text track style. */ - class PlaybackConfig { - /** - * Duration of buffered media in seconds to start buffering. - */ - autoPauseDuration?: number; + getTextTracksStyle(): TextTrackStyle; - /** - * Duration of buffered media in seconds to start/resume playback after auto-paused due to buffering. - */ - autoResumeDuration?: number; - - /** - * Minimum number of buffered segments to start/resume playback. - */ - autoResumeNumberOfSegments?: number; - - /** - * A function to customize request to get a caption segment. - */ - captionsRequestHandler?: RequestHandler; - - /** - * Initial bandwidth in bits in per second. - */ - initialBandwidth?: number; - - /** - * Custom license data. - */ - licenseCustomData?: string; - - /** - * Handler to process license data. The handler is passed the license data; and returns the modified license data. - */ - licenseHandler?: BinaryHandler; - - /** - * A function to customize request to get a license. - */ - licenseRequestHandler?: RequestHandler; - - /** - * Url for acquiring the license. - */ - licenseUrl?: string; - - /** - * Handler to process manifest data. The handler is passed the manifest; and returns the modified manifest. - */ - manifestHandler?: (manifest: string) => string; - - /** - * A function to customize request to get a manifest. - */ - manifestRequestHandler?: RequestHandler; - - /** - * Preferred protection system to use for decrypting content. - */ - protectionSystem: ContentProtection; - - /** - * Handler to process segment data. The handler is passed the segment data; and returns the modified segment data. - */ - segmentHandler?: BinaryHandler; - - /** - * A function to customize request information to get a media segment. - */ - segmentRequestHandler?: RequestHandler; - - /** - * Maximum number of times to retry a network request for a segment. - */ - segmentRequestRetryLimit?: number; - } /** - * HTTP(s) Request/Response information. + * Gets text track by id. */ - class NetworkRequestInfo { - /** - * The content of the request. Can be used to modify license request body. - */ - content: Uint8Array; + getTrackById(id: number): Track; - /** - * An object containing properties that you would like to send in the header. - */ - headers: any; + /** + * Returns all text tracks. + */ + getTracks(): Track[]; - /** - * The URL requested. - */ - url: string; + /** + * Gets text tracks by language. + */ + getTracksByLanguage(language: string): Track[]; - /** - * Indicates whether CORS Access-Control requests should be made using credentials such as cookies or authorization headers. - */ - withCredentials: boolean; - } - /** Cast receiver context options. All options are optionals. */ - class CastReceiverOptions { - /** - * Optional map of custom messages namespaces to initialize and their types. - * Custom messages namespaces need to be initiated before the application started; - * so it is best to provide the namespaces in the receiver options. - * (The default type of a message bus is JSON; if not provided here). - */ - customNamespaces?: any; + /** + * Sets text tracks to be active by id. + */ + setActiveByIds(newIds: number[]): void; - /** - * Sender id used for local requests. Default value is 'local'. - */ - localSenderId?: string; + /** + * Sets text tracks to be active by language. + */ + setActiveByLanguage(language: string): void; - /** - * Maximum time in seconds before closing an idle sender connection. - * Setting this value enables a heartbeat message to keep the connection alive. - * Used to detect unresponsive senders faster than typical TCP timeouts. - * The minimum value is 5 seconds; there is no upper bound enforced but practically it's minutes before platform TCP timeouts come into play. - * Default value is 10 seconds. - */ - maxInactivity?: number; - - /** - * Optional media element to play content with. Default behavior is to use the first found media element in the page. - */ - mediaElement?: HTMLMediaElement; - - /** - * Optional playback configuration. - */ - playbackConfig?: PlaybackConfig; - - /** - * If this is true; the watched client stitching break will also be played. - */ - playWatchedBreak?: boolean; - - /** - * Preferred value for player playback rate. It is used if playback rate value is not provided in the load request. - */ - preferredPlaybackRate?: number; - - /** - * Preferred text track language. It is used if no active track is provided in the load request. - */ - preferredTextLanguage?: string; - - /** - * Optional queue implementation. - */ - queue?: QueueBase; - - /** - * Text that represents the application status. - * It should meet internationalization rules as may be displayed by the sender application. - */ - statusText?: string; - - /** - * A bitmask of media commands supported by the application. - * LOAD; PLAY; STOP; GET_STATUS must always be supported. - * If this value is not provided; then PAUSE; SEEK; STREAM_VOLUME; STREAM_MUTE are assumed to be supported too. - */ - supportedCommands?: number; - - /** - * Indicate that MPL should be used for DASH content. - */ - useLegacyDashSupport?: boolean; - - /** - * An integer used as an internal version number. - * This number is used only to distinguish between receiver releases and higher numbers do not necessarily have to represent newer releases. - */ - versionCode?: number; - } - - /** Manages loading of underlying libraries and initializes underlying cast receiver SDK. */ - class CastReceiverContext { - /** Returns the CastReceiverContext singleton instance. */ - static getInstance(): CastReceiverContext; - - constructor(params: any); - - /** - * Sets message listener on custom message channel. - */ - addCustomMessageListener( - namespace: string, - listener: EventHandler - ): void; - - /** - * Add listener to cast system events. - */ - addEventListener( - type: SystemEventType | SystemEventType[], - handler: EventHandler - ): void; - - /** - * Checks if the given media params of video or audio streams are supported by the platform. - */ - canDisplayType( - mimeType: string, - codecs?: string, - width?: number, - height?: number, - framerate?: number - ): boolean; - - /** - * Provides application information once the system is ready; otherwise it will be null. - */ - getApplicationData(): ApplicationData; - - /** - * Provides device capabilities information once the system is ready; otherwise it will be null. - * If an empty object is returned; the device does not expose any capabilities information. - */ - getDeviceCapabilities(): any; - - /** - * Get Player instance that can control and monitor media playback. - */ - getPlayerManager(): PlayerManager; - - /** - * Get a sender by sender id - */ - getSender(senderId: string): Sender; - - /** - * Gets a list of currently-connected senders. - */ - getSenders(): Sender[]; - - /** - * Reports if the cast application's HDMI input is in standby. - */ - getStandbyState(): StandbyState; - - /** - * Provides application information about the system state. - */ - getSystemState(): SystemState; - - /** - * Reports if the cast application is the HDMI active input. - */ - getVisibilityState(): any; - - /** - * When the application calls start; the system will send the ready event to indicate - * that the application information is ready and the application can send messages as soon as there is one sender connected. - */ - isSystemReady(): boolean; - - /** - * Start loading player js. This can be used to start loading the players js code in early stage of starting the receiver before calling start. - * This function is a no-op if players were already loaded (start was called). - */ - loadPlayerLibraries(useLegacyDashSupport?: boolean): void; - - /** - * Remove a message listener on custom message channel. - */ - removeCustomMessageListener( - namespace: string, - listener: EventHandler - ): void; - - /** - * Remove listener to cast system events. - */ - removeEventListener(type: EventType, handler: EventHandler): void; - - /** - * Sends a message to a specific sender. - */ - sendCustomMessage( - namespace: string, - senderId: string, - message: any - ): void; - - /** - * This function should be called in response to the feedbackstarted event if the application - * add debug state information to log in the feedback report. - * It takes in a parameter ‘message’ that is a string that represents the debug information that the application wants to log. - */ - sendFeedbackMessage(feedbackMessage: string): void; - - /** - * Sets the application state. The application should call this when its state changes. - * If undefined or set to an empty string; the value of the Application Name established during application - * registration is used for the application state by default. - */ - setApplicationState(statusText: string): void; - - /** - * Sets the receiver inactivity timeout. - * It is recommended to set the maximum inactivity value when calling Start and not changing it. - * This API is just provided for development/debugging purposes. - */ - setInactivityTimeout(maxInactivity: number): void; - - /** - * Sets the log verbosity level. - */ - setLoggerLevel(level: LoggerLevel): void; - - /** - * Initializes system manager and media manager; so that receiver app can receive requests from senders. - */ - start(options?: CastReceiverOptions): CastReceiverContext; - - /** - * Shutdown receiver application. - */ - stop(): void; - } - - /** Manages audio tracks. */ - class AudioTracksManager { - constructor(params: any); - getActiveId(): number; - getActiveTrack(): Track; - getTrackById(id: number): Track; - getTracks(): Track[]; - getTracksByLanguage(language: string): Track[]; - setActiveById(id: number): void; - setActiveByLanguage(language: string): void; - } + /** + * Sets text track style. + */ + setTextTrackStyle(style: TextTrackStyle): void; +} + +/** + * QueueManager exposes several queue manipulation APIs to developers. + */ +export class QueueManager { + constructor(params?: any); + + /** + * Returns the current queue item. + */ + getCurrentItem(): QueueItem; + + /** + * Returns the index of the current queue item. + */ + getCurrentItemIndex(): number; + + /** + * Returns the queue items. + */ + getItems(): QueueItem[]; + + /** + * Inserts items into the queue. + */ + insertItems(items: QueueItem[], insertBefore?: number): void; + + /** + * Removes items from the queue. + */ + removeItems(itemIds: number[]): void; + + /** + * Sets whether to limit the number of queue items to be reported in Media Status (default is true). + */ + setQueueStatusLimit(limitQueueItemsInStatus: boolean): void; + + /** + * Updates existing queue items by matching itemId. + */ + updateItems(items: QueueItem[]): void; +} + +/** + * Base implementation of a queue. + */ +export class QueueBase { + /** + * Fetches a window of items using the specified item id as reference; called by the receiver MediaManager when it needs more queue items; + * often as a request from senders. If only one of nextCount and prevCount is non-zero; fetchItems should only return items after or before + * the reference item; if both nextCount and prevCount are non-zero; a window of items including the reference item should be returned. + */ + fetchItems( + itemId: number, + nextCount: number, + prevCount: number + ): QueueItem[] | Promise; + + /** + * Initializes the queue with the requestData. This is called when a new LOAD request comes in to the receiver. + * If this returns or resolves to null; our default queueing implementation will create a queue based on queueData.items or the single media + * in the load request data. + */ + initialize( + requestData: LoadRequestData + ): QueueData | Promise; + + /** + * Returns next items after the reference item; often the end of the current queue; called by the receiver MediaManager. + */ + nextItems(itemId?: number): QueueItem[] | Promise; + + /** + * Sets the current item with the itemId; called by the receiver MediaManager when it changes the current playing item. + */ + onCurrentItemIdChanged(itemId: number): void; + + /** + * A callback for informing the following items have been inserted into the receiver queue in this session. + * A cloud based implementation can optionally choose to update its queue based on the new information. + */ + onItemsInserted(items: QueueItem[], insertBefore?: number): void; + + /** + * A callback for informing the following items have been removed from the receiver queue in this session. + * A cloud based implementation can optionally choose to update its queue based on the new information. + */ + onItemsRemoved(itemIds: number[]): void; + + /** + * Returns previous items before the reference item; often at the beginning of the queue; called by the receiver MediaManager. + */ + prevItems(itemId?: number): QueueItem[] | Promise; + + /** + * Shuffles the queue and returns new queue items. Returns null if the operation is not supported. + */ + shuffle(): QueueItem[] | Promise; +} + +/** + * Controls and monitors media playback. + */ +export class PlayerManager { + constructor(params?: any); + + /** + * Adds an event listener for player event. + */ + addEventListener: ( + eventType: EventType | EventType[], + eventListener: EventHandler + ) => void; + + /** + * Sends a media status message to all senders (broadcast). Applications use this to send a custom state change. + */ + broadcastStatus( + includeMedia?: boolean, + requestId?: number, + customData?: any, + includeQueueItems?: boolean + ): void; + + getAudioTracksManager(): AudioTracksManager; + + /** + * Returns current time in sec in currently-playing break clip. + */ + getBreakClipCurrentTimeSec(): number; + + /** + * Returns duration in sec of currently-playing break clip. + */ + getBreakClipDurationSec(): number; + + /** + * Obtain the breaks (Ads) manager. + */ + getBreakManager(): BreakManager; + + /** + * Returns list of breaks. + */ + getBreaks(): Break[]; + + /** + * Gets current time in sec of current media. + */ + getCurrentTimeSec(): number; + + /** + * Gets duration in sec of currently playing media. + */ + getDurationSec(): number; + + /** + * Returns live seekable range with start and end time in seconds. The values are media time based. + */ + getLiveSeekableRange(): LiveSeekableRange; + + /** + * Gets media information of current media. + */ + getMediaInformation(): MediaInformation; + + /** + * Returns playback configuration. + */ + getPlaybackConfig(): PlaybackConfig; + + /** + * Returns current playback rate. + */ + getPlaybackRate(): number; + + /** + * Gets player state. + */ + getPlayerState(): PlayerState; + + /** + * Get the preferred playback rate. (Can be used on shutdown event to save latest preferred playback rate to a persistent storage; + * so it can be used in next session in the cast options). + */ + getPreferredPlaybackRate(): number; + + /** + * Get the preferred text track language. + */ + getPreferredTextLanguage(): string; + + /** + * Obtain QueueManager API. + */ + getQueueManager(): QueueManager; + + getTextTracksManager(): TextTracksManager; + + /** + * Loads media. + */ + load(loadRequest: LoadRequestData): Promise; + + /** + * Pauses currently playing media. + */ + pause(): void; + + /** + * Plays currently paused media. + */ + play(): void; + + /** + * Requests a text string to be played back locally on the receiver device. + */ + playString(stringId: PlayStringId, args?: string[]): Promise; + + /** + * Request Google Assistant to refresh the credentials. Only works if the original credentials came from the assistant. + */ + refreshCredentials(): Promise; + + /** + * Removes the event listener added for given player event. If event listener is not added; it will be ignored. + */ + removeEventListener( + eventType: EventType | EventType[], + eventListener: EventHandler + ): void; + + /** + * Seeks in current media. + */ + seek(seekTime: number): void; + + /** + * Sends an error to a specific sender + */ + sendError( + senderId: string, + requestId: number, + type: ErrorType, + reason?: ErrorReason, + customData?: any + ): void; + + /** + * Send local media request. + */ + sendLocalMediaRequest(request: RequestData): void; + + /** + * Sends a media status message to a specific sender. + */ + sendStatus( + senderId: string, + requestId: number, + includeMedia?: boolean, + customData?: any, + includeQueueItems?: boolean + ): void; + + /** + * Sets the IDLE reason. This allows applications that want to force the IDLE state to indicate the reason that made the player going to IDLE state + * (a custom error; for example). The idle reason will be sent in the next status message. NOTE: Most applications do not need to set this value; + * it is only needed if they want to make the player go to IDLE in special circumstances and the default idleReason does not reflect their intended + * behavior. + */ + setIdleReason(idleReason: IdleReason): void; + + /** + * Sets MediaElement to use. If Promise of MediaElement is set; media begins playback after Promise is resolved. + */ + setMediaElement(mediaElement: HTMLMediaElement): void; + + /** + * Sets media information. + */ + setMediaInformation( + mediaInformation: MediaInformation, + opt_broadcast?: boolean + ): void; + + /** + * Sets a handler to return or modify PlaybackConfig; for a specific load request. The handler paramaters are the load request data + * and default playback config for the receiver (provided in the context options). The handler should returns a modified playback config; + * or null to prevent the media from playing. The return value can be a promise to allow waiting for data from the server. + */ + setMediaPlaybackInfoHandler( + handler: ( + loadRequestData: LoadRequestData, + playbackConfig: PlaybackConfig + ) => void + ): void; + + /** + * Sets a handler to return the media url for a load request. This handler can be used to avoid having the media content url published as part + * of the media status. By default the media contentId is used as the content url. + */ + setMediaUrlResolver( + resolver: (loadRequestData: LoadRequestData) => void + ): void; + + /** + * Provide an interceptor of incoming and outgoing messages. + * The interceptor can update the request data; and return updated data; a promise of + * updated data if need to get more data from the server; or null if the request should not be handled. + * Note that if load message interceptor is provided; and no interceptor is provided for preload - + * the load interceptor will be called for preload messages. + */ + setMessageInterceptor( + type: MessageType, + interceptor: (requestData: RequestData) => Promise + ): void; + + /** + * Sets playback configuration on the PlayerManager. + */ + setPlaybackConfig(playbackConfig: PlaybackConfig): void; + + /** + * Set the preferred playback rate for follow up load or media items. The preferred playback rate will be updated automatically to the latest + * playback rate that was provided by a load request or explicit set of playback rate. + */ + setPreferredPlaybackRate(preferredPlaybackRate: number): void; + + /** + * Set the preferred text track language. The preferred text track language will be updated automatically to the latest enabled language + * by a load request or explicit change to text tracks. (Should be called only in idle state; and Will only apply to next loaded media). + */ + setPreferredTextLanguage(preferredTextLanguage: string): void; + + /** + * Stops currently playing media. + */ + stop(): void; +} + +/** + * Configuration to customize playback behavior. + */ +export class PlaybackConfig { + /** + * Duration of buffered media in seconds to start buffering. + */ + autoPauseDuration?: number; + + /** + * Duration of buffered media in seconds to start/resume playback after auto-paused due to buffering. + */ + autoResumeDuration?: number; + + /** + * Minimum number of buffered segments to start/resume playback. + */ + autoResumeNumberOfSegments?: number; + + /** + * A function to customize request to get a caption segment. + */ + captionsRequestHandler?: RequestHandler; + + /** + * Initial bandwidth in bits in per second. + */ + initialBandwidth?: number; + + /** + * Custom license data. + */ + licenseCustomData?: string; + + /** + * Handler to process license data. The handler is passed the license data; and returns the modified license data. + */ + licenseHandler?: BinaryHandler; + + /** + * A function to customize request to get a license. + */ + licenseRequestHandler?: RequestHandler; + + /** + * Url for acquiring the license. + */ + licenseUrl?: string; + + /** + * Handler to process manifest data. The handler is passed the manifest; and returns the modified manifest. + */ + manifestHandler?: (manifest: string) => string; + + /** + * A function to customize request to get a manifest. + */ + manifestRequestHandler?: RequestHandler; + + /** + * Preferred protection system to use for decrypting content. + */ + protectionSystem: ContentProtection; + + /** + * Handler to process segment data. The handler is passed the segment data; and returns the modified segment data. + */ + segmentHandler?: BinaryHandler; + + /** + * A function to customize request information to get a media segment. + */ + segmentRequestHandler?: RequestHandler; + + /** + * Maximum number of times to retry a network request for a segment. + */ + segmentRequestRetryLimit?: number; +} +/** + * HTTP(s) Request/Response information. + */ +export class NetworkRequestInfo { + /** + * The content of the request. Can be used to modify license request body. + */ + content: Uint8Array; + + /** + * An object containing properties that you would like to send in the header. + */ + headers: any; + + /** + * The URL requested. + */ + url: string; + + /** + * Indicates whether CORS Access-Control requests should be made using credentials such as cookies or authorization headers. + */ + withCredentials: boolean; +} +/** Cast receiver context options. All options are optionals. */ +export class CastReceiverOptions { + /** + * Optional map of custom messages namespaces to initialize and their types. + * Custom messages namespaces need to be initiated before the application started; + * so it is best to provide the namespaces in the receiver options. + * (The default type of a message bus is JSON; if not provided here). + */ + customNamespaces?: any; + + /** + * Sender id used for local requests. Default value is 'local'. + */ + localSenderId?: string; + + /** + * Maximum time in seconds before closing an idle sender connection. + * Setting this value enables a heartbeat message to keep the connection alive. + * Used to detect unresponsive senders faster than typical TCP timeouts. + * The minimum value is 5 seconds; there is no upper bound enforced but practically it's minutes before platform TCP timeouts come into play. + * Default value is 10 seconds. + */ + maxInactivity?: number; + + /** + * Optional media element to play content with. Default behavior is to use the first found media element in the page. + */ + mediaElement?: HTMLMediaElement; + + /** + * Optional playback configuration. + */ + playbackConfig?: PlaybackConfig; + + /** + * If this is true; the watched client stitching break will also be played. + */ + playWatchedBreak?: boolean; + + /** + * Preferred value for player playback rate. It is used if playback rate value is not provided in the load request. + */ + preferredPlaybackRate?: number; + + /** + * Preferred text track language. It is used if no active track is provided in the load request. + */ + preferredTextLanguage?: string; + + /** + * Optional queue implementation. + */ + queue?: QueueBase; + + /** + * Text that represents the application status. + * It should meet internationalization rules as may be displayed by the sender application. + */ + statusText?: string; + + /** + * A bitmask of media commands supported by the application. + * LOAD; PLAY; STOP; GET_STATUS must always be supported. + * If this value is not provided; then PAUSE; SEEK; STREAM_VOLUME; STREAM_MUTE are assumed to be supported too. + */ + supportedCommands?: number; + + /** + * Indicate that MPL should be used for DASH content. + */ + useLegacyDashSupport?: boolean; + + /** + * An integer used as an internal version number. + * This number is used only to distinguish between receiver releases and higher numbers do not necessarily have to represent newer releases. + */ + versionCode?: number; +} + +/** Manages loading of underlying libraries and initializes underlying cast receiver SDK. */ +export class CastReceiverContext { + /** Returns the CastReceiverContext singleton instance. */ + static getInstance(): CastReceiverContext; + + constructor(params: any); + + /** + * Sets message listener on custom message channel. + */ + addCustomMessageListener( + namespace: string, + listener: EventHandler + ): void; + + /** + * Add listener to cast system events. + */ + addEventListener( + type: SystemEventType | SystemEventType[], + handler: EventHandler + ): void; + + /** + * Checks if the given media params of video or audio streams are supported by the platform. + */ + canDisplayType( + mimeType: string, + codecs?: string, + width?: number, + height?: number, + framerate?: number + ): boolean; + + /** + * Provides application information once the system is ready; otherwise it will be null. + */ + getApplicationData(): ApplicationData; + + /** + * Provides device capabilities information once the system is ready; otherwise it will be null. + * If an empty object is returned; the device does not expose any capabilities information. + */ + getDeviceCapabilities(): any; + + /** + * Get Player instance that can control and monitor media playback. + */ + getPlayerManager(): PlayerManager; + + /** + * Get a sender by sender id + */ + getSender(senderId: string): Sender; + + /** + * Gets a list of currently-connected senders. + */ + getSenders(): Sender[]; + + /** + * Reports if the cast application's HDMI input is in standby. + */ + getStandbyState(): StandbyState; + + /** + * Provides application information about the system state. + */ + getSystemState(): SystemState; + + /** + * Reports if the cast application is the HDMI active input. + */ + getVisibilityState(): any; + + /** + * When the application calls start; the system will send the ready event to indicate + * that the application information is ready and the application can send messages as soon as there is one sender connected. + */ + isSystemReady(): boolean; + + /** + * Start loading player js. This can be used to start loading the players js code in early stage of starting the receiver before calling start. + * This function is a no-op if players were already loaded (start was called). + */ + loadPlayerLibraries(useLegacyDashSupport?: boolean): void; + + /** + * Remove a message listener on custom message channel. + */ + removeCustomMessageListener( + namespace: string, + listener: EventHandler + ): void; + + /** + * Remove listener to cast system events. + */ + removeEventListener(type: EventType, handler: EventHandler): void; + + /** + * Sends a message to a specific sender. + */ + sendCustomMessage( + namespace: string, + senderId: string, + message: any + ): void; + + /** + * This function should be called in response to the feedbackstarted event if the application + * add debug state information to log in the feedback report. + * It takes in a parameter ‘message’ that is a string that represents the debug information that the application wants to log. + */ + sendFeedbackMessage(feedbackMessage: string): void; + + /** + * Sets the application state. The application should call this when its state changes. + * If undefined or set to an empty string; the value of the Application Name established during application + * registration is used for the application state by default. + */ + setApplicationState(statusText: string): void; + + /** + * Sets the receiver inactivity timeout. + * It is recommended to set the maximum inactivity value when calling Start and not changing it. + * This API is just provided for development/debugging purposes. + */ + setInactivityTimeout(maxInactivity: number): void; + + /** + * Sets the log verbosity level. + */ + setLoggerLevel(level: LoggerLevel): void; + + /** + * Initializes system manager and media manager; so that receiver app can receive requests from senders. + */ + start(options?: CastReceiverOptions): CastReceiverContext; + + /** + * Shutdown receiver application. + */ + stop(): void; +} + +/** Manages audio tracks. */ +export class AudioTracksManager { + constructor(params: any); + getActiveId(): number; + getActiveTrack(): Track; + getTrackById(id: number): Track; + getTracks(): Track[]; + getTracksByLanguage(language: string): Track[]; + setActiveById(id: number): void; + setActiveByLanguage(language: string): void; } diff --git a/types/chromecast-caf-receiver/cast.framework.events.d.ts b/types/chromecast-caf-receiver/cast.framework.events.d.ts index 03b70ca459..468ed98158 100644 --- a/types/chromecast-caf-receiver/cast.framework.events.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.events.d.ts @@ -4,423 +4,421 @@ import { Track, MediaStatus } from "./cast.framework.messages"; -export = cast.framework.events; -declare namespace cast.framework.events { - type EventType = - | "ALL" - | "ABORT" - | "CAN_PLAY" - | "CAN_PLAY_THROUGH" - | "DURATION_CHANGE" - | "EMPTIED" - | "ENDED" - | "LOADED_DATA" - | "LOADED_METADATA" - | "LOAD_START" - | "PAUSE" - | "PLAY" - | "PLAYING" - | "PROGRESS" - | "RATE_CHANGE" - | "SEEKED" - | "SEEKING" - | "STALLED" - | "TIME_UPDATE" - | "SUSPEND" - | "WAITING" - | "BITRATE_CHANGED" - | "BREAK_STARTED" - | "BREAK_ENDED" - | "BREAK_CLIP_LOADING" - | "BREAK_CLIP_STARTED" - | "BREAK_CLIP_ENDED" - | "BUFFERING" - | "CACHE_LOADED" - | "CACHE_HIT" - | "CACHE_INSERTED" - | "CLIP_STARTED" - | "CLIP_ENDED" - | "EMSG" - | "ERROR" - | "ID3" - | "MEDIA_STATUS" - | "MEDIA_FINISHED" - | "PLAYER_PRELOADING" - | "PLAYER_PRELOADING_CANCELLED" - | "PLAYER_LOAD_COMPLETE" - | "PLAYER_LOADING" - | "SEGMENT_DOWNLOADED" - | "REQUEST_SEEK" - | "REQUEST_LOAD" - | "REQUEST_STOP" - | "REQUEST_PAUSE" - | "REQUEST_PLAY" - | "REQUEST_PLAY_AGAIN" - | "REQUEST_PLAYBACK_RATE_CHANGE" - | "REQUEST_SKIP_AD" - | "REQUEST_VOLUME_CHANGE" - | "REQUEST_EDIT_TRACKS_INFO" - | "REQUEST_EDIT_AUDIO_TRACKS" - | "REQUEST_SET_CREDENTIALS" - | "REQUEST_LOAD_BY_ENTITY" - | "REQUEST_USER_ACTION" - | "REQUEST_DISPLAY_STATUS" - | "REQUEST_CUSTOM_COMMAND" - | "REQUEST_FOCUS_STATE" - | "REQUEST_QUEUE_LOAD" - | "REQUEST_QUEUE_INSERT" - | "REQUEST_QUEUE_UPDATE" - | "REQUEST_QUEUE_REMOVE" - | "REQUEST_QUEUE_REORDER" - | "REQUEST_QUEUE_GET_ITEM_RANGE" - | "REQUEST_QUEUE_GET_ITEMS" - | "REQUEST_QUEUE_GET_ITEM_IDS" - | "REQUEST_PRECACHE"; +export as namespace events +export type EventType = + | "ALL" + | "ABORT" + | "CAN_PLAY" + | "CAN_PLAY_THROUGH" + | "DURATION_CHANGE" + | "EMPTIED" + | "ENDED" + | "LOADED_DATA" + | "LOADED_METADATA" + | "LOAD_START" + | "PAUSE" + | "PLAY" + | "PLAYING" + | "PROGRESS" + | "RATE_CHANGE" + | "SEEKED" + | "SEEKING" + | "STALLED" + | "TIME_UPDATE" + | "SUSPEND" + | "WAITING" + | "BITRATE_CHANGED" + | "BREAK_STARTED" + | "BREAK_ENDED" + | "BREAK_CLIP_LOADING" + | "BREAK_CLIP_STARTED" + | "BREAK_CLIP_ENDED" + | "BUFFERING" + | "CACHE_LOADED" + | "CACHE_HIT" + | "CACHE_INSERTED" + | "CLIP_STARTED" + | "CLIP_ENDED" + | "EMSG" + | "ERROR" + | "ID3" + | "MEDIA_STATUS" + | "MEDIA_FINISHED" + | "PLAYER_PRELOADING" + | "PLAYER_PRELOADING_CANCELLED" + | "PLAYER_LOAD_COMPLETE" + | "PLAYER_LOADING" + | "SEGMENT_DOWNLOADED" + | "REQUEST_SEEK" + | "REQUEST_LOAD" + | "REQUEST_STOP" + | "REQUEST_PAUSE" + | "REQUEST_PLAY" + | "REQUEST_PLAY_AGAIN" + | "REQUEST_PLAYBACK_RATE_CHANGE" + | "REQUEST_SKIP_AD" + | "REQUEST_VOLUME_CHANGE" + | "REQUEST_EDIT_TRACKS_INFO" + | "REQUEST_EDIT_AUDIO_TRACKS" + | "REQUEST_SET_CREDENTIALS" + | "REQUEST_LOAD_BY_ENTITY" + | "REQUEST_USER_ACTION" + | "REQUEST_DISPLAY_STATUS" + | "REQUEST_CUSTOM_COMMAND" + | "REQUEST_FOCUS_STATE" + | "REQUEST_QUEUE_LOAD" + | "REQUEST_QUEUE_INSERT" + | "REQUEST_QUEUE_UPDATE" + | "REQUEST_QUEUE_REMOVE" + | "REQUEST_QUEUE_REORDER" + | "REQUEST_QUEUE_GET_ITEM_RANGE" + | "REQUEST_QUEUE_GET_ITEMS" + | "REQUEST_QUEUE_GET_ITEM_IDS" + | "REQUEST_PRECACHE"; - type DetailedErrorCode = - | "MEDIA_UNKNOWN" - | "MEDIA_ABORTED" - | "MEDIA_DECODE" - | "MEDIA_NETWORK" - | "MEDIA_SRC_NOT_SUPPORTED" - | "SOURCE_BUFFER_FAILURE" - | "MEDIAKEYS_UNKNOWN" - | "MEDIAKEYS_NETWORK" - | "MEDIAKEYS_UNSUPPORTED" - | "MEDIAKEYS_WEBCRYPTO" - | "NETWORK_UNKNOWN" - | "SEGMENT_NETWORK" - | "HLS_NETWORK_MASTER_PLAYLIST" - | "HLS_NETWORK_PLAYLIST" - | "HLS_NETWORK_NO_KEY_RESPONSE" - | "HLS_NETWORK_KEY_LOAD" - | "HLS_NETWORK_INVALID_SEGMENT" - | "HLS_SEGMENT_PARSING" - | "DASH_NETWORK" - | "DASH_NO_INIT" - | "SMOOTH_NETWORK" - | "SMOOTH_NO_MEDIA_DATA" - | "MANIFEST_UNKNOWN" - | "HLS_MANIFEST_MASTER" - | "HLS_MANIFEST_PLAYLIST" - | "DASH_MANIFEST_UNKNOWN" - | "DASH_MANIFEST_NO_PERIODS" - | "DASH_MANIFEST_NO_MIMETYPE" - | "DASH_INVALID_SEGMENT_INFO" - | "SMOOTH_MANIFEST" - | "SEGMENT_UNKNOWN" - | "TEXT_UNKNOWN" - | "APP" - | "BREAK_CLIP_LOADING_ERROR" - | "BREAK_SEEK_INTERCEPTOR_ERROR" - | "IMAGE_ERROR" - | "LOAD_INTERRUPTED" - | "GENERIC"; +export type DetailedErrorCode = + | "MEDIA_UNKNOWN" + | "MEDIA_ABORTED" + | "MEDIA_DECODE" + | "MEDIA_NETWORK" + | "MEDIA_SRC_NOT_SUPPORTED" + | "SOURCE_BUFFER_FAILURE" + | "MEDIAKEYS_UNKNOWN" + | "MEDIAKEYS_NETWORK" + | "MEDIAKEYS_UNSUPPORTED" + | "MEDIAKEYS_WEBCRYPTO" + | "NETWORK_UNKNOWN" + | "SEGMENT_NETWORK" + | "HLS_NETWORK_MASTER_PLAYLIST" + | "HLS_NETWORK_PLAYLIST" + | "HLS_NETWORK_NO_KEY_RESPONSE" + | "HLS_NETWORK_KEY_LOAD" + | "HLS_NETWORK_INVALID_SEGMENT" + | "HLS_SEGMENT_PARSING" + | "DASH_NETWORK" + | "DASH_NO_INIT" + | "SMOOTH_NETWORK" + | "SMOOTH_NO_MEDIA_DATA" + | "MANIFEST_UNKNOWN" + | "HLS_MANIFEST_MASTER" + | "HLS_MANIFEST_PLAYLIST" + | "DASH_MANIFEST_UNKNOWN" + | "DASH_MANIFEST_NO_PERIODS" + | "DASH_MANIFEST_NO_MIMETYPE" + | "DASH_INVALID_SEGMENT_INFO" + | "SMOOTH_MANIFEST" + | "SEGMENT_UNKNOWN" + | "TEXT_UNKNOWN" + | "APP" + | "BREAK_CLIP_LOADING_ERROR" + | "BREAK_SEEK_INTERCEPTOR_ERROR" + | "IMAGE_ERROR" + | "LOAD_INTERRUPTED" + | "GENERIC"; - type EndedReason = - | "END_OF_STREAM" - | "ERROR" - | "STOPPED" - | "INTERRUPTED" - | "SKIPPED" - | "BREAK_SWITCH"; +export type EndedReason = + | "END_OF_STREAM" + | "ERROR" + | "STOPPED" + | "INTERRUPTED" + | "SKIPPED" + | "BREAK_SWITCH"; + +/** + * Event data for @see{@link EventType.SEGMENT_DOWNLOADED} event. + */ +export class SegmentDownloadedEvent extends Event { + constructor(downloadTime?: number, size?: number); /** - * Event data for @see{@link EventType.SEGMENT_DOWNLOADED} event. + * The time it took to download the segment; in milliseconds. */ - class SegmentDownloadedEvent extends Event { - constructor(downloadTime?: number, size?: number); - - /** - * The time it took to download the segment; in milliseconds. - */ - downloadTime?: number; - - /** - * The number of bytes in the segment. - */ - size?: number; - } + downloadTime?: number; /** - * Event data for all events that represent requests made to the receiver. + * The number of bytes in the segment. */ - class RequestEvent extends Event { - constructor( - type: EventType, - requestData?: RequestData, - senderId?: string - ); + size?: number; +} + +/** + * Event data for all events that represent requests made to the receiver. + */ +export class RequestEvent extends Event { + constructor( + type: EventType, + requestData?: RequestData, + senderId?: string + ); - /** - * The data that was sent with the request. - */ - requestData?: RequestData; + /** + * The data that was sent with the request. + */ + requestData?: RequestData; + + /** + * The sender id the request came from. + */ + senderId?: string; +} + +/** + * Event data superexport class for all events dispatched by @see{@link PlayerManager} + */ +export class Event { + constructor(type: EventType); + + /** + * Type of the event. + */ + type: EventType; +} +/** + * Event data for @see{@link EventType.MEDIA_STATUS} event. + */ +export class MediaStatusEvent extends Event { + constructor(type: EventType, mediaStatus?: MediaStatus); + + /** + * The media status that was sent. + */ + mediaStatus?: MediaStatus; +} +/** + * Event data for pause events forwarded from the MediaElement. + */ +export class MediaPauseEvent extends Event { + constructor(currentMediaTime?: number, ended?: boolean); + + /** + * Indicate if the media ended (indicates the pause was fired due to stream reached the end). + */ + ended?: boolean; +} +/** + * Event data for @see{@link EventType.MEDIA_FINISHED} event. + */ +export class MediaFinishedEvent extends Event { + constructor(currentMediaTime?: number, endedReason?: EndedReason); + + /** + * The time when the media finished (in seconds). For an item in a queue; this value represents the time in the currently playing queue item ( where 0 means the queue item has just started). + */ + currentTime?: number; + + /** + * The reason the media finished. + */ + endedReason?: EndedReason; +} +/** + * Event data for all events forwarded from the MediaElement. + */ +export class MediaElementEvent extends Event { + constructor(type: EventType, currentMediaTime?: number); + + /** + * The time in the currently playing clip when the event was fired (in seconds). Undefined if playback has not started yet. + */ + currentMediaTime?: number; +} +/** + * Event data for all events pertaining to processing a load / preload request. made to the player. + */ +export class LoadEvent extends Event { + constructor(type: EventType, media?: MediaInformation); + + /** + * Information about the media being loaded. + */ + media: MediaInformation; +} +/** + * Event data for @see{@link EventType.INBAND_TRACK_ADDED} event. + */ +export class InbandTrackAddedEvent { + constructor(track: Track); + + /** + * Added track. + */ + track: Track; +} + +/** Event data for @see{@link EventType.ID3} event. */ +export class Id3Event extends Event { + constructor(segmentData: Uint8Array); + + /** + * The segment data. + */ + segmentData: Uint8Array; +} +/** + * Event data for @see{@link EventType.EMSG} event. + */ +export class EmsgEvent extends Event { + constructor(emsgData: any); + + /** + * The time that the event ends (in presentation time). Undefined if using legacy Dash support. + */ + endTime: any; + + /** + * The duration of the event (in units of timescale). Undefined if using legacy Dash support. + */ + eventDuration: any; + + /** + * A field identifying this instance of the message. Undefined if using legacy Dash support. + */ + id: any; + + /** + * Body of the message. Undefined if using legacy Dash support. + */ + messageData: any; + + /** + * The offset that the event starts; relative to the start of the segment this is contained in (in units of timescale). Undefined if using legacy Dash support. + */ + presentationTimeDelta: any; - /** - * The sender id the request came from. - */ - senderId?: string; - } + /** + * Identifies the message scheme. Undefined if using legacy Dash support. + */ + schemeIdUri: any; /** - * Event data superclass for all events dispatched by @see{@link PlayerManager} + * The segment data. This is only defined if using legacy Dash support. */ - class Event { - constructor(type: EventType); + segmentData: any; - /** - * Type of the event. - */ - type: EventType; - } /** - * Event data for @see{@link EventType.MEDIA_STATUS} event. + * The time that the event starts (in presentation time). Undefined if using legacy Dash support. */ - class MediaStatusEvent extends Event { - constructor(type: EventType, mediaStatus?: MediaStatus); + startTime: any; - /** - * The media status that was sent. - */ - mediaStatus?: MediaStatus; - } /** - * Event data for pause events forwarded from the MediaElement. + * Provides the timescale; in ticks per second. Undefined if using legacy Dash support. */ - class MediaPauseEvent extends Event { - constructor(currentMediaTime?: number, ended?: boolean); + timescale: any; - /** - * Indicate if the media ended (indicates the pause was fired due to stream reached the end). - */ - ended?: boolean; - } - /** - * Event data for @see{@link EventType.MEDIA_FINISHED} event. - */ - class MediaFinishedEvent extends Event { - constructor(currentMediaTime?: number, endedReason?: EndedReason); - - /** - * The time when the media finished (in seconds). For an item in a queue; this value represents the time in the currently playing queue item ( where 0 means the queue item has just started). - */ - currentTime?: number; - - /** - * The reason the media finished. - */ - endedReason?: EndedReason; - } - /** - * Event data for all events forwarded from the MediaElement. - */ - class MediaElementEvent extends Event { - constructor(type: EventType, currentMediaTime?: number); - - /** - * The time in the currently playing clip when the event was fired (in seconds). Undefined if playback has not started yet. - */ - currentMediaTime?: number; - } - /** - * Event data for all events pertaining to processing a load / preload request. made to the player. - */ - class LoadEvent extends Event { - constructor(type: EventType, media?: MediaInformation); - - /** - * Information about the media being loaded. - */ - media: MediaInformation; - } /** - * Event data for @see{@link EventType.INBAND_TRACK_ADDED} event. - */ - class InbandTrackAddedEvent { - constructor(track: Track); + * Specifies the value for the event. Undefined if using legacy Dash support. + */ + value: any; +} +/** + * Event data for @see{@link EventType.CLIP_ENDED} event. + */ +export class ClipEndedEvent extends Event { + constructor(currentMediaTime: number, endedReason?: EndedReason); - /** - * Added track. - */ - track: Track; - } - - /** Event data for @see{@link EventType.ID3} event. */ - class Id3Event extends Event { - constructor(segmentData: Uint8Array); + /** + * The time in media (in seconds) when clip ended. + */ + currentMediaTime: number; - /** - * The segment data. - */ - segmentData: Uint8Array; - } /** - * Event data for @see{@link EventType.EMSG} event. + * The reason the clip ended. */ - class EmsgEvent extends Event { - constructor(emsgData: any); + endedReason?: EndedReason; +} + +/** + * Event data for @see{@link EventType.CACHE_LOADED} event. + */ +export class CacheLoadedEvent extends Event { + constructor(media?: MediaInformation); + + /** + * Information about the media being cached. + */ + media: MediaInformation; +} + +export class CacheItemEvent extends Event { + constructor(type: EventType, url: string); + + /** + * The URL of data fetched from cache + */ + url: string; +} + +export class BufferingEvent extends Event { + constructor(isBuffering: boolean); + + /** + * True if the player is entering a buffering state. + */ + isBuffering: boolean; +} + +export class BreaksEvent extends Event { + constructor( + type: EventType, + currentMediaTime?: number, + index?: number, + total?: number, + whenSkippable?: number, + endedReason?: EndedReason, + breakClipId?: string, + breakId?: string + ); + + /** + * The break's id. Refer to Break.id + */ + breakId?: string; + + /** + * The break clip's id. Refer to BreakClip.id + */ + breakClipId?: string; + + /** + * The time in the currently playing media when the break event occurred. + */ + currentMediaTime?: number; + + /** + * The reason the break clip ended. + */ + endedReason?: EndedReason; + + /** + * Index of break clip; which starts from 1. + */ + index: number; + + /** + * Total number of break clips. + */ + total: number; + + /** + * When to skip current break clip in sec; after break clip begins to play. + */ + whenSkippable?: number; +} + +/** + * Event data for @see {@link EventType.BITRATE_CHANGED} event. + */ +export class BitrateChangedEvent { + constructor(totalBitrate?: number); + + /** The bitrate of the media (audio and video) in bits per second. */ + totalBitrate: number; +} + +export class ErrorEvent extends Event { + constructor(detailedErrorCode: DetailedErrorCode, error?: any); - /** - * The time that the event ends (in presentation time). Undefined if using legacy Dash support. - */ - endTime: any; - - /** - * The duration of the event (in units of timescale). Undefined if using legacy Dash support. - */ - eventDuration: any; - - /** - * A field identifying this instance of the message. Undefined if using legacy Dash support. - */ - id: any; - - /** - * Body of the message. Undefined if using legacy Dash support. - */ - messageData: any; - - /** - * The offset that the event starts; relative to the start of the segment this is contained in (in units of timescale). Undefined if using legacy Dash support. - */ - presentationTimeDelta: any; - - /** - * Identifies the message scheme. Undefined if using legacy Dash support. - */ - schemeIdUri: any; - - /** - * The segment data. This is only defined if using legacy Dash support. - */ - segmentData: any; - - /** - * The time that the event starts (in presentation time). Undefined if using legacy Dash support. - */ - startTime: any; - - /** - * Provides the timescale; in ticks per second. Undefined if using legacy Dash support. - */ - timescale: any; - - /** - * Specifies the value for the event. Undefined if using legacy Dash support. - */ - value: any; - } - /** - * Event data for @see{@link EventType.CLIP_ENDED} event. - */ - class ClipEndedEvent extends Event { - constructor(currentMediaTime: number, endedReason?: EndedReason); - - /** - * The time in media (in seconds) when clip ended. - */ - currentMediaTime: number; - - /** - * The reason the clip ended. - */ - endedReason?: EndedReason; - } - - /** - * Event data for @see{@link EventType.CACHE_LOADED} event. - */ - class CacheLoadedEvent extends Event { - constructor(media?: MediaInformation); - - /** - * Information about the media being cached. - */ - media: MediaInformation; - } - - class CacheItemEvent extends Event { - constructor(type: EventType, url: string); - - /** - * The URL of data fetched from cache - */ - url: string; - } - - class BufferingEvent extends Event { - constructor(isBuffering: boolean); - - /** - * True if the player is entering a buffering state. - */ - isBuffering: boolean; - } - - class BreaksEvent extends Event { - constructor( - type: EventType, - currentMediaTime?: number, - index?: number, - total?: number, - whenSkippable?: number, - endedReason?: EndedReason, - breakClipId?: string, - breakId?: string - ); - - /** - * The break's id. Refer to Break.id - */ - breakId?: string; - - /** - * The break clip's id. Refer to BreakClip.id - */ - breakClipId?: string; - - /** - * The time in the currently playing media when the break event occurred. - */ - currentMediaTime?: number; - - /** - * The reason the break clip ended. - */ - endedReason?: EndedReason; - - /** - * Index of break clip; which starts from 1. - */ - index: number; - - /** - * Total number of break clips. - */ - total: number; - - /** - * When to skip current break clip in sec; after break clip begins to play. - */ - whenSkippable?: number; - } - - /** - * Event data for @see {@link EventType.BITRATE_CHANGED} event. - */ - class BitrateChangedEvent { - constructor(totalBitrate?: number); - - /** The bitrate of the media (audio and video) in bits per second. */ - totalBitrate: number; - } - - class ErrorEvent extends Event { - constructor(detailedErrorCode: DetailedErrorCode, error?: any); - - detailedErrorCode: DetailedErrorCode; - error?: any; - } + detailedErrorCode: DetailedErrorCode; + error?: any; } diff --git a/types/chromecast-caf-receiver/cast.framework.messages.d.ts b/types/chromecast-caf-receiver/cast.framework.messages.d.ts index d6dda6d145..c3dc4a405f 100644 --- a/types/chromecast-caf-receiver/cast.framework.messages.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.messages.d.ts @@ -1,1900 +1,1898 @@ import { Event, DetailedErrorCode } from "./cast.framework.events"; -export = cast.framework.messages; -declare namespace cast.framework.messages { - type UserAction = - | "LIKE" - | "DISLIKE" - | "FOLLOW" - | "UNFOLLOW" - | "FLAG" - | "SKIP_AD"; - - type UserActionContext = - | "UNKNOWN_CONTEXT" - | "ALBUM" - | "ARTIST" - | "PLAYLIST" - | "EPISODE" - | "SERIES" - | "MOVIE" - | "CHANNEL" - | "TEAM" - | "PLAYER" - | "COACH"; - - type TextTrackType = - | "SUBTITLES" - | "CAPTIONS" - | "DESCRIPTIONS" - | "CHAPTERS" - | "METADATA"; - - type TextTrackWindowType = "NONE" | "NORMAL" | "ROUNDED_CORNERS"; - - type TrackType = "TEXT" | "AUDIO" | "VIDEO"; - - type TextTrackFontGenericFamily = - | "SANS_SERIF" - | "MONOSPACED_SANS_SERIF" - | "SERIF" - | "MONOSPACED_SERIF" - | "CASUAL" - | "CURSIVE" - | "SMALL_CAPITALS"; - - type TextTrackFontStyle = "NORMAL" | "BOLD" | "BOLD_ITALIC" | "ITALIC"; - - type TextTrackEdgeType = - | "NONE" - | "OUTLINE" - | "DROP_SHADOW" - | "RAISED" - | "DEPRESSED"; - - type Command = - | "PAUSE" - | "SEEK" - | "STREAM_VOLUME" - | "STREAM_MUTE" - | "ALL_BASIC_MEDIA" - | "QUEUE_NEXT" - | "QUEUE_PREV" - | "QUEUE_SHUFFLE" - | "SKIP_AD"; - - type SeekResumeState = "PLAYBACK_START" | "PLAYBACK_PAUSE"; - - type StreamingProtocolType = - | "UNKNOWN" - | "MPEG_DASH" - | "HLS" - | "SMOOTH_STREAMING"; - - type StreamType = "BUFFERED" | "LIVE" | "NONE"; - - type FocusState = "IN_FOCUS" | "NOT_IN_FOCUS"; - - type ExtendedPlayerState = "LOADING"; - - type ErrorType = - | "INVALID_PLAYER_STATE" - | "LOAD_FAILED" - | "LOAD_CANCELLED" - | "INVALID_REQUEST" - | "ERROR"; - - type ErrorReason = - | "INVALID_COMMAND" - | "INVALID_PARAMS" - | "INVALID_MEDIA_SESSION_ID" - | "SKIP_LIMIT_REACHED" - | "NOT_SUPPORTED" - | "LANGUAGE_NOT_SUPPORTED" - | "END_OF_QUEUE" - | "APP_ERROR" - | "AUTHENTICATION_EXPIRED" - | "PREMIUM_ACCOUNT_REQUIRED" - | "CONCURRENT_STREAM_LIMIT" - | "PARENTAL_CONTROL_RESTRICTED" - | "NOT_AVAILABLE_IN_REGION" - | "CONTENT_ALREADY_PLAYING" - | "INVALID_REQUEST" - | "GENERIC_LOAD_ERROR"; - - type RepeatMode = - | "REPEAT_OFF" - | "REPEAT_ALL" - | "REPEAT_SINGLE" - | "REPEAT_ALL_AND_SHUFFLE"; - - type IdleReason = "CANCELLED" | "INTERRUPTED" | "FINISHED" | "ERROR"; - - type HlsSegmentFormat = "AAC" | "AC3" | "MP3" | "TS" | "TS_AAC"; - - type HdrType = "SDR" | "HDR" | "DV"; - - type PlayStringId = - | "FREE_TRIAL_ABOUT_TO_EXPIRE" - | "SUBSCRIPTION_ABOUT_TO_EXPIRE" - | "STREAM_HIJACKED"; - - type GetStatusOptions = "NO_METADATA" | "NO_QUEUE_ITEMS"; - - type MessageType = - | "MEDIA_STATUS" - | "CLOUD_STATUS" - | "QUEUE_CHANGE" - | "QUEUE_ITEMS" - | "QUEUE_ITEM_IDS" - | "GET_STATUS" - | "LOAD" - | "PAUSE" - | "STOP" - | "PLAY" - | "SKIP_AD" - | "PLAY_AGAIN" - | "SEEK" - | "SET_PLAYBACK_RATE" - | "SET_VOLUME" - | "EDIT_TRACKS_INFO" - | "EDIT_AUDIO_TRACKS" - | "PRECACHE" - | "PRELOAD" - | "QUEUE_LOAD" - | "QUEUE_INSERT" - | "QUEUE_UPDATE" - | "QUEUE_REMOVE" - | "QUEUE_REORDER" - | "QUEUE_NEXT" - | "QUEUE_PREV" - | "QUEUE_GET_ITEM_RANGE" - | "QUEUE_GET_ITEMS" - | "QUEUE_GET_ITEM_IDS" - | "QUEUE_SHUFFLE" - | "SET_CREDENTIALS" - | "LOAD_BY_ENTITY" - | "USER_ACTION" - | "DISPLAY_STATUS" - | "FOCUS_STATE" - | "CUSTOM_COMMAND"; - - type PlayerState = "IDLE" | "PLAYING" | "PAUSED" | "BUFFERING"; - - type QueueChangeType = - | "INSERT" - | "REMOVE" - | "ITEMS_CHANGE" - | "UPDATE" - | "NO_CHANGE"; - - type QueueType = - | "ALBUM" - | "PLAYLIST" - | "AUDIOBOOK" - | "RADIO_STATION" - | "PODCAST_SERIES" - | "TV_SERIES" - | "VIDEO_PLAYLIST" - | "LIVE_TV" - | "MOVIE"; - - type MetadataType = - | "GENERIC" - | "MOVIE" - | "TV_SHOW" - | "MUSIC_TRACK" - | "PHOTO"; - - /** - * RefreshCredentials request data. - */ - interface RefreshCredentialsRequestData { - [key: string]: any; - } - - /** - * Media event SET_VOLUME request data. - */ - interface VolumeRequestData extends RequestData { - /** - * The media stream volume - */ - volume?: Volume; - } - - /** - * Represents the volume of a media session stream. - */ - interface Volume { - /** - * Value from 0 to 1 that represents the current stream volume level. - */ - level?: number; - - /** - * Whether the stream is muted. - */ - muted?: boolean; - } - - /** - * Video information such as video resolution and High Dynamic Range (HDR). - */ - class VideoInformation { - constructor(width: number, height: number, hdrType: HdrType); - - width: number; - - height: number; - - hdrType: HdrType; - } - - /** - * VAST ad request configuration. - */ - interface VastAdsRequest { - /** - * Specifies a VAST document to be used as the ads response instead of making a - * request via an ad tag url. - * This can be useful for debugging and other situations where a VAST response is - * already available. - */ - adsResponse?: string; - - /** - * URL for VAST file. - */ - adTagUrl?: string; - } - - /** - * UserAction request data. - */ - interface UserActionRequestData { - /** - * Optional request source. - * It contain the assistent query that initiate the request. - */ - source?: string; - - /** - * User action to be handled by the application. - */ - userAction?: UserAction; - - /** - * Optional context information for the user action. - */ - userActionContext?: UserActionContext; - } - - /** - * A TV episode media description. - */ - interface TvShowMediaMetadata { - /** - * TV episode number. A positive integer. - */ - episode?: number; - - /** - * @deprecated use episode instead - */ - episodeNumber?: number; - - /** - * @deprecated use episode instead - */ - episodeTitle?: string; - - /** - * Content images. Examples would include cover art or a thumbnail of - * the currently playing media. - */ - images?: Image[]; - - /** - * ISO 8601 date when the episode originally aired; e.g. 2014-02-10. - */ - originalAirdate?: string; - - /** - * @deprecated use originalAirdate instead. - */ - releaseYear?: number; - - /** - * TV episode season. A positive integer. - */ - season?: number; - - /** - * @deprecated use season instead. - */ - seasonNumber?: number; - - /** - * TV series title. - */ - seriesTitle?: string; - - /** - * TV episode title. - */ - title?: string; - } - /** - * Describes track metadata information. - */ - class Track { - constructor(trackId: number, trackType: TrackType); - - /** - * Custom data set by the receiver application. - */ - customData?: string; - - /** - * Language tag as per RFC 5646 (If subtype is “SUBTITLES” it is mandatory). - */ - language?: string; - - /** - * A descriptive; human readable name for the track. For example "Spanish". - */ - name?: string; - - /** - * For text tracks; the type of text track. - */ - subtype?: string; - - /** - * It can be the url of the track or any other identifier that allows the receiver - * to find the content (when the track is not inband or included in the manifest). - * For example it can be the url of a vtt file. - */ - trackContentId?: string; - - /** - * It represents the MIME type of the track content. For example if the track - * is a vtt file it will be ‘text/vtt’. This field is needed for out of band tracks; - * so it is usually provided if a trackContentId has also been provided. - * It is not mandatory if the receiver has a way to identify the content from - * the trackContentId; but recommended. - * The track content type; if provided; must be consistent with the track type. - */ - trackContentType?: string; - - /** - * Unique identifier of the track within the context of a MediaInformation object. - */ - trackId?: number; - - /** - * The type of track. - */ - type: TrackType; - } - /** - * Describes style information for a text track. - */ - interface TextTrackStyle { - /** - * The background 32 bit RGBA color. The alpha channel should be used for transparent backgrounds. - */ - backgroundColor?: string; - - /** - * Custom data set by the receiver application. - */ - customData?: any; - - /** - * RGBA color for the edge; this value will be ignored if edgeType is NONE. - */ - edgeColor?: string; - - edgeType?: TextTrackEdgeType; - - /** - * If the font is not available in the receiver the fontGenericFamily will be used. - */ - fontFamily?: string; - - /** - * The text track generic family. - */ - fontGenericFamily?: TextTrackFontGenericFamily; - - /** - * The font scaling factor for the text track (the default is 1). - */ - fontScale?: number; - - /** - * The text track font style. - */ - fontStyle?: TextTrackFontStyle; - - /** - * The foreground 32 bit RGBA color. - */ - foregroundColor?: string; - - /** - * 32 bit RGBA color for the window. This value will be ignored if windowType is NONE. - */ - windowColor?: string; - - /** - * Rounded corner radius absolute value in pixels (px). This value will be ignored - * if windowType is not ROUNDED_CORNERS. - */ - windowRoundedCornerRadius?: number; - - /** - * The window concept is defined in CEA-608 and CEA-708. In WebVTT is called a region. - */ - windowType?: TextTrackWindowType; - } - - /** - * Media event playback rate request data. - */ - interface SetPlaybackRateRequestData extends RequestData { - /** - * New playback rate (>0). - */ - playbackRate?: number; - - /** - * New playback rate relative to current playback rate. - * New rate will be the result of multiplying the current rate with the value. - * For example a value of 1.1 will increase rate by 10%. - * (Only used if the playbackRate value is not provided). - */ - relativePlaybackRate?: number; - } - - /** - * SetCredentials request data. - */ - interface SetCredentialsRequestData { - /** - * Credentials to use by receiver. - */ - credentials?: string; - - /** - * If it is a response for refresh credentials; it will indicate the request id - * of the refresh credentials request. - */ - forRequestId?: number; - - /** - * Optional request source. It contain the assistent query that initiate the request. - */ - source?: string; - } - - /** - * Media event SEEK request data. - */ - interface SeekRequestData extends RequestData { - /** - * Seconds since beginning of content. - */ - currentTime?: number; - - /** - * Seconds relative to the current playback position. If this field is defined; - * the currentTime field will be ignored. - */ - relativeTime?: number; - - /** - * The playback state after a SEEK request. - */ - resumeState?: SeekResumeState; - } - - /** - * Provides seekable range in seconds. - */ - class SeekableRange { - constructor(start?: number, end?: number); - - /** - * End of the seekable range in seconds. - */ - end?: number; - - /** - * Start of the seekable range in seconds. - */ - start?: number; - } - - /** - * Media event request data. - */ - class RequestData { - constructor(type: MessageType); - - /** - * Application-specific data for this request. - * It enables the sender and receiver to easily extend the media protocol - * without having to use a new namespace with custom messages. - */ - customData?: any; - - /** - * Id of the media session that the request applies to. - */ - mediaSessionId?: number; - - /** - * Id of the request; used to correlate request/response. - */ - requestId: number; - } - - /** - * Media event UPDATE queue request data. - */ - interface QueueUpdateRequestData { - /** - * ID of the current media Item after the deletion - * (if not provided; the currentItem value will be the same as before the deletion; - * if it does not exist because it has been deleted; the currentItem will point to - * the next logical item in the list). - */ - currentItemId?: number; - - /** - * Seconds since the beginning of content to start playback of the current item. - * If provided; this value will take precedence over the startTime value provided - * at the QueueItem level but only the first time the item is played. - * This is to cover the common case where the user jumps to the middle of an - * item so the currentTime does not apply to the item permanently like the - * QueueItem startTime does. It avoids having to reset the startTime dynamically - * (that may not be possible if the phone has gone to sleep). - */ - currentTime?: number; - - /** - * List of queue items to be updated. No reordering will happen; the items will - * retain the existing order. - */ - items?: QueueItem[]; - - /** - * Skip/Go back number of items with respect to the position of currentItem - * (it can be negative). If it is out of boundaries; the currentItem will be the - * next logical item in the queue wrapping around the boundaries. - * The new currentItem position will follow the rules of the queue repeat behavior. - */ - jump?: number; - - /** - * Behavior of the queue when all items have been played. - */ - repeatMode?: RepeatMode; - - /** - * Shuffle the queue items when the update is processed. - * After the queue items are shuffled; the item at the currentItem position will - * be loaded. - */ - shuffle?: boolean; - } - - /** - * Media event queue REORDER request data. - */ - class QueueReorderRequestData extends RequestData { - constructor(itemIds: number[]); - - /** - * ID of the current media Item after the deletion (if not provided; - * the currentItem value will be the same as before the deletion; - * if it does not exist because it has been deleted; - * the currentItem will point to the next logical item in the list). - */ - currentItemId?: number; - - /** - * Seconds since the beginning of content to start playback of the current item. - * If provided; this value will take precedence over the startTime value provided - * at the QueueItem level but only the first time the item is played. - * This is to cover the common case where the user jumps to the middle of an - * item so the currentTime does not apply to the item permanently like - * the QueueItem startTime does. It avoids having to reset the startTime dynamically - * (that may not be possible if the phone has gone to sleep). - */ - currentTime?: number; - - /** - * ID of the item that will be located immediately after the reordered list. - * If the ID is not found or it is not provided; - * the reordered list will be appended at the end of the existing list. - */ - insertBefore?: number; - - /** - * IDs of the items to be reordered; in the new order. - * Items not provided will keep their existing order. - * The provided list will be inserted at the position determined by insertBefore. - * For example: - * If insertBefore is not specified Existing queue: “A”;”D”;”G”;”H”;”B”;”E” itemIds: - * “D”;”H”;”B” New Order: “A”;”G”;”E”;“D”;”H”;”B” - * If insertBefore is “A” Existing queue: “A”;”D”;”G”;”H”;”B” itemIds: - * “D”;”H”;”B” New Order: “D”;”H”;”B”;“A”;”G”;”E” - * If insertBefore is “G” Existing queue: “A”;”D”;”G”;”H”;”B” itemIds: - * “D”;”H”;”B” New Order: “A”;“D”;”H”;”B”;”G”;”E” - */ - itemIds: number[]; - } - - /** - * Media event queue REMOVE request data. - */ - class QueueRemoveRequestData extends RequestData { - constructor(itemIds: number[]); - - /** - * ID of the current media Item after the deletion - * (if not provided; the currentItem value will be the same as before the deletion; - * if it does not exist because it has been deleted; - * the currentItem will point to the next logical item in the list). - */ - currentItemId?: number; - - /** - * Seconds since the beginning of content to start playback of the current item. - * If provided; this value will take precedence over the startTime value provided - * at the QueueItem level but only the first time the item is played. - * This is to cover the common case where the user jumps to the middle of an - * item so the currentTime does not apply to the item permanently like the - * QueueItem startTime does. It avoids having to reset the startTime dynamically - * (that may not be possible if the phone has gone to sleep). - */ - currentTime?: number; - - /** - * IDs of queue items to be deleted. - */ - itemIds?: number[]; - } - /** - * Media event queue LOAD request data. - */ - class QueueLoadRequestData extends RequestData { - constructor(items: QueueItem[]); - - /** - * Seconds (since the beginning of content) to start playback of the first item to - * be played. If provided; this value will take precedence over the - * startTime value provided at the QueueItem level but only the first - * time the item is played. This is to cover the common case where the user - * casts the item that was playing locally so the currentTime does not apply - * to the item permanently like the QueueItem startTime does. - * It avoids having to reset the startTime dynamically - * (that may not be possible if the phone has gone to sleep). - */ - currentTime?: number; - - /** - * Behavior of the queue when all items have been played. - */ - items: QueueItem[]; - - /** - * Id of the request; used to correlate request/response. - */ - repeatMode?: RepeatMode; - - /** - * The index of the item in the items array that must be the first currentItem - * (the item that will be played first). Note this is the index of the array - * (starts at 0) and not the itemId (as it is not known until the queue is created). - * If repeatMode is REPEAT_OFF playback will end when the last item in the array is - * played (elements before the startIndex will not be played). - * This may be useful for continuation scenarios where the user was already - * using the sender app and in the middle decides to cast. - * In this way the sender app does not need to map between the local and remote queue - * positions or saves one extra QUEUE_UPDATE request. - */ - startIndex?: number; - } - - /** - * Queue item information. Application developers may need to create a QueueItem to - * insert a queue element using InsertQueueItems. In this case they should not - * provide an itemId (as the actual itemId will be assigned when the item is inserted - * in the queue). This prevents ID collisions with items added from a sender app. - */ - class QueueItem { - constructor(opt_itemId?: number); - - /** - * Array of Track trackIds that are active. If the array is not provided; - * the default tracks will be active. - */ - activeTrackIds?: number[]; - - /** - * If the autoplay parameter is not specified or is true; the media player - * will begin playing the element in the queue when the item becomes the currentItem. - */ - autoplay?: boolean; - - /** - * The application can define any extra queue item information needed. - */ - customData?: any; - - /** - * Unique identifier of the item in the queue. - * The attribute is optional because for LOAD or INSERT should not be provided - * (as it will be assigned by the receiver when an item is first created/inserted). - */ - itemId?: number; - - /** - * Metadata (including contentId) of the playlist element. - */ - media?: MediaInformation; - - /** - * Playback duration of the item; if it is larger than the actual duration - - * startTime it will be ignored (default behavior). - * It can be negative; in such case the duration will be the actual asset - * duration minus the duration provided. - * It can be used for photo slideshows to control the duration the item should - * be presented or for live events to control the duration that the program - * should be played. It may be useful for autoplay scenarios to avoid displaying all - * the credits after an episode has ended. - */ - playbackDuration?: number; - - /** - * This parameter is a hint for the receiver to preload this media - * item before it is played. It allows for a smooth transition between items - * played from the queue. The time is expressed in seconds; relative to - * the beginning of this item playback (usually the end of the previous item playback). - * Only positive values are valid. For example; if the value is 10 seconds; this item - * will be preloaded 10 seconds before the previous item has finished. - * The receiver will try to honor this value but will not guarantee it; - * for example if the value is larger than the previous item duration the - * receiver may just preload this item shortly after the previous item has started playing - * (there will never be two items being preloaded in parallel). - * Also; if an item is inserted in the queue just after the currentItem and the time to preload is higher than the - * time left on the currentItem; the preload will just happen as soon as possible. - */ - preloadTime?: number; - - /** - * Seconds since beginning of content. If the content is live content; - * and startTime is not specified; the stream will start at the live position. - */ - startTime?: number; - } - - /** - * Media event queue INSERT request data. - */ - class QueueInsertRequestData extends RequestData { - constructor(items: QueueItem[]); - - /** - * ID of the current media Item after the insertion (if not provided; - * the currentItem value will be the same as before the insertion). - */ - currentItemId?: number; - - /** - * Index (relative to the items array; starting with 0) of the new current media Item. - * For inserted items we use the index (similar to startIndex in QUEUE_LOAD) and not - * currentItemId; because the itemId is unknown until the items are inserted. - * If not provided; the currentItem value will be the same as before the insertion - * (unless currentItemId is provided). This param allows to make atomic the common use - * case of insert and play an item. - */ - currentItemIndex?: number; - - /** - * Seconds since the beginning of content to start playback of the current item. - * If provided; this value will take precedence over the startTime value provided - * at the QueueItem level but only the first time the item is played. - * This is to cover the common case where the user jumps to the middle of an - * item so the currentTime does not apply to the item permanently like the - * QueueItem startTime does. It avoids having to reset the startTime dynamically - * (that may not be possible if the phone has gone to sleep). - */ - currentTime?: number; - - /** - * ID of the item that will be located immediately after the inserted list. - * If the ID is not found or it is not provided; the list will be appended at - * the end of the existing list. - */ - insertBefore?: number; - - /** - * List of queue items. The itemId field of the items should be empty. - * It is sorted (first element will be played first). - */ - items: QueueItem[]; - } - - /** - * Represents a data message containing the full list of queue ids. - */ - interface QueueIds { - /** - * List of queue item ids. - */ - itemIds?: number[]; - - /** - * The corresponding request id. - */ - requestId?: number; - - type: MessageType; - } - - /** - * Queue data as part of the LOAD request. - */ - class QueueData { - constructor( - id?: string, - name?: string, - description?: string, - repeatMode?: RepeatMode, - items?: QueueItem[], - startIndex?: number, - startTime?: number - ); - - /** - * Description of the queue. - */ - description?: string; - - /** - * Optional Queue entity id; provide Google Assistant deep link. - */ - entity?: string; - - /** - * Id of the queue. - */ - id?: string; - - /** - * Array of queue items. It is sorted (first element will be played first). - */ - items?: QueueItem[]; - - /** - * Name of the queue. - */ - name?: string; - - /** - * Queue type; e.g. album; playlist; radio station; tv series; etc. - */ - queueType?: QueueType; - - /** - * Continuous playback behavior of the queue. - */ - repeatMode?: RepeatMode; - - /** - * The index of the item in the queue that should be used to start playback first. - */ - startIndex?: number; - - /** - * Seconds (since the beginning of content) to start playback of the first item. - */ - startTime?: number; - } - - /** - * Represents a queue change message; such as insert; remove; and update. - */ - interface QueueChange { - /** - * The actual queue change type. - */ - changeType?: QueueChangeType; - - /** - * The id to insert the list of itemIds before. - */ - insertBefore?: number; - - /** - * List of changed itemIds. - */ - itemIds?: number[]; - - /** - * The corresponding request id. - */ - requestId?: number; - - /** - * The queue change sequence ID. Used to coordinate state sync between various - * senders and the receiver. - */ - sequenceNumber?: number; - - type: MessageType; - } - - /** - * Media event PRELOAD request data. - */ - class PreloadRequestData implements LoadRequestData { - /** - * Array of trackIds that are active. If the array is not provided; - * the default tracks will be active. - */ - activeTrackIds: number[]; - /** - * If the autoplay parameter is specified; the media player will begin playing - * the content when it is loaded. Even if autoplay is not specified;the media player - * implementation may choose to begin playback immediately. - */ - autoplay?: boolean; - /** - * Optional user credentials. - */ - credentials?: string; - /** - * Optional credentials type. The type 'cloud' is a reserved type used by load - * requests that were originated by voice assistant commands. - */ - credentialsType?: string; - /** - * Seconds since beginning of content. If the content is live content; - * and currentTime is not specified; the stream will start at the live position. - */ - currentTime?: number; - /** - * If the autoplay parameter is specified; the media player will begin playing - * the content when it is loaded. Even if autoplay is not specified; the media - * player implementation may choose to begin playback immediately. - */ - media: MediaInformation; - /** - * The media playback rate. - */ - playbackRate?: number; - /** - * Queue data. - */ - queueData: QueueData; - /** - * Application-specific data for this request. - * It enables the sender and receiver to easily extend the media protocol - * without having to use a new namespace with custom messages. - */ - customData?: any; - /** - * Id of the media session that the request applies to. - */ - mediaSessionId?: number; - /** - * Id of the request; used to correlate request/response. - */ - requestId: number; - constructor(itemId: number); - - /** - * The ID of the queue item. - */ - itemId: number; - } - - /** - * Media event PRECACHE request data. (Some fields of the load request; - * like autoplay and queueData; are ignored). - */ - class PrecacheRequestData implements LoadRequestData { - /** - * Array of trackIds that are active. If the array is not provided; - * the default tracks will be active. - */ - activeTrackIds: number[]; - /** - * If the autoplay parameter is specified; the media player will begin playing - * the content when it is loaded. Even if autoplay is not specified;the media player - * implementation may choose to begin playback immediately. - */ - autoplay?: boolean; - /** - * Optional user credentials. - */ - credentials?: string; - /** - * Optional credentials type. The type 'cloud' is a reserved type used by load - * requests that were originated by voice assistant commands. - */ - credentialsType?: string; - /** - * Seconds since beginning of content. If the content is live content; and - * currentTime is not specified; the stream will start at the live position. - */ - currentTime?: number; - /** - * If the autoplay parameter is specified; the media player will begin playing - * the content when it is loaded. Even if autoplay is not specified; - * the media player implementation may choose to begin playback immediately. - */ - media: MediaInformation; - /** - * The media playback rate. - */ - playbackRate?: number; - /** - * Queue data. - */ - queueData: QueueData; - /** - * Application-specific data for this request. - * It enables the sender and receiver to easily extend the media protocol - * without having to use a new namespace with custom messages. - */ - customData?: any; - /** - * Id of the media session that the request applies to. - */ - mediaSessionId?: number; - /** - * Id of the request; used to correlate request/response. - */ - requestId: number; - constructor(data?: string); - - /** - * Application precache data. - */ - precacheData?: string; - } - - /** - * PlayString request data. - */ - class PlayStringRequestData { - constructor(stringId: PlayStringId, opt_arguments?: string[]); - - /** - * An optional array of string values to be filled into the text. - */ - arguments?: string[]; - - /** - * An identifier for the text to be played back. - */ - stringId: PlayStringId; - } - - /** - * A photo media description. - */ - interface PhotoMediaMetadata { - /** - * Name of the photographer. - */ - artist?: string; - - /** - * ISO 8601 date and time the photo was taken; e.g. 2014-02-10T15:47:00Z. - */ - creationDateTime?: string; - - /** - * Photo height; in pixels. - */ - height?: number; - - /** - * Images associated with the content. Examples would include a photo thumbnail. - */ - images: Image[]; - - /** - * Latitude. - */ - latitude?: number; - - /** - * Location where the photo was taken. For example; "Seattle; Washington; USA". - */ - location?: string; - - /** - * Longitude. - */ - longitude?: number; - - /** - * Photo title. - */ - title?: string; - - /** - * Photo width; in pixels. - */ - width?: number; - } - - /** - * A music track media description. - */ - interface MusicTrackMediaMetadata { - /** - * Album artist name. - */ - albumArtist?: string; - - /** - * Album name. - */ - albumName?: string; - - /** - * Track artist name. - */ - artist?: string; - - /** - * @deprecated: use @see{@link artist} instead - */ - artistName: string; - - /** - * Track composer name. - */ - composer?: string; - - /** - * Disc number. A positive integer. - */ - discNumber?: number; - - /** - * Content images. Examples would include cover art or a thumbnail of the - * currently playing media. - */ - images: Image[]; - - /** - * ISO 8601 date when the track was released; e.g. 2014-02-10. - */ - releaseDate?: string; - - /** - * @deprecated: Use @see{@link releaseDate} instead - */ - releaseYear?: string; - - /** - * Track name. - */ - songName?: string; - - /** - * Track title. - */ - title?: string; - - /** - * Track number in album. A positive integer. - */ - trackNumber?: number; - } - - /** - * A movie media description. - */ - interface MovieMediaMetadata { - /** - * Content images. Examples would include cover art or a thumbnail of the - * currently playing media. - */ - images: Image[]; - - /** - * ISO 8601 date when the movie was released; e.g. 2014-02-10. - */ - releaseDate?: string; - - /** - * @deprecated: use @see{@link releaseDate} instead - */ - releaseYear?: number; - - /** - * Movie studio. - */ - studio?: string; - - /** - * Movie subtitle. - */ - subtitle?: string; - - /** - * Movie title. - */ - title?: string; - } - /** - * Represents the status of a media session. - */ - interface MediaStatus { - /** - * List of IDs corresponding to the active tracks. - */ - activeTrackIds: number[]; - - /** - * Status of break; if receiver is playing break. - * This field will be defined only when receiver is playing break. - */ - breakStatus: BreakStatus; - - /** - * ID of this media item (the item that originated the status change). - */ - currentItemId?: number; - - /** - * The current playback position. - */ - currentTime: number; - - /** - * Application-specific media status. - */ - customData?: any; - - /** - * Extended media status information. - */ - extendedStatus: ExtendedMediaStatus; - - /** - * If the state is IDLE; the reason the player went to IDLE state. - */ - idleReason: IdleReason; - - /** - * List of media queue items. - */ - items: QueueItem[]; - - /** - * Seekable range of a live or event stream. It uses relative media time in seconds. - * It will be undefined for VOD streams. - */ - liveSeekableRange: LiveSeekableRange; - - /** - * ID of the media Item currently loading. If there is no item being loaded; - * it will be undefined. - */ - loadingItemId?: number; - - /** - * The media information. - */ - media: MediaInformation; - - /** - * Unique id for the session. - */ - mediaSessionId: number; - - /** - * The playback rate. - */ - playbackRate: number; - - /** - * The playback state. - */ - playerState: PlayerState; - - /** - * ID of the next Item; only available if it has been preloaded. - * Media items can be preloaded and cached temporarily in memory; - * so when they are loaded later on; the process is faster - * (as the media does not have to be fetched from the network). - */ - preloadedItemId?: number; - - /** - * Queue data. - */ - queueData: QueueData; - - /** - * The behavior of the queue when all items have been played. - */ - repeatMode: RepeatMode; - - /** - * The commands supported by this player. - */ - supportedMediaCommands: number; - - type: MessageType; - - /** - * The video information. - */ - videoInfo: VideoInformation; - - /** - * The current stream volume. - */ - volume: Volume; - } - /** - * Common media metadata used as part of MediaInformation - */ - class MediaMetadata { - constructor(type: MetadataType); - - /** - * The type of metadata - */ - metadataType: MetadataType; - } - - /** - * Represents the media information. - */ - interface MediaInformation { - /** - * Partial list of break clips that includes current break clip that receiver - * is playing or ones that receiver will play shortly after; instead of sending - * whole list of clips. This is to avoid overflow of MediaStatus message. - */ - breakClips: BreakClip[]; - - /** - * List of breaks. - */ - breaks: Break[]; - - /** - * Typically the url of the media. - */ - contentId: string; - - /** - * The content MIME type. - */ - contentType: string; - - /** - * Optional media url; to allow using contentId for real id. If contentUrl - * is provided; it will be used as media url; otherwise the contentId will - * be used as the media url. - */ - contentUrl?: string; - - /** - * Application-specific media information. - */ - customData?: any; - - /** - * The media duration. - */ - duration?: number; - - /** - * Optional Media entity; provide Google Assistant deep link. - */ - entity?: string; - - /** - * The format of the HLS media segment. - */ - hlsSegmentFormat: HlsSegmentFormat; - - /** - * The media metadata. - */ - metadata: MediaMetadata; - - /** - * The stream type. - */ - streamType: StreamType; - - /** - * The style of text track. - */ - textTrackStyle: TextTrackStyle; - - /** - * The media tracks. - */ - tracks: Track[]; - } - - /** - * Media event LOAD request data. - */ - interface LoadRequestData extends RequestData { - /** - * Array of trackIds that are active. If the array is not provided; the - * default tracks will be active. - */ - activeTrackIds: number[]; - - /** - * If the autoplay parameter is specified; the media player will begin - * playing the content when it is loaded. Even if autoplay is not - * specified;the media player implementation may choose to begin playback - * immediately. - */ - autoplay?: boolean; - - /** - * Optional user credentials. - */ - credentials?: string; - - /** - * Optional credentials type. The type 'cloud' is a reserved type used by - * load requests that were originated by voice assistant commands. - */ - credentialsType?: string; - - /** - * Seconds since beginning of content. If the content is live content; - * and currentTime is not specified; the stream will start at the live position. - */ - currentTime?: number; - - /** - * If the autoplay parameter is specified; the media player will begin playing - * the content when it is loaded. Even if autoplay is not specified; the media - * player implementation may choose to begin playback immediately. - */ - media: MediaInformation; - - /** - * The media playback rate. - */ - playbackRate?: number; - - /** - * Queue data. - */ - queueData: QueueData; - } - - /** - * LoadByEntity request data. - */ - interface LoadByEntityRequestData { - /** - * Content entity information; typically represented by a stringified JSON object - */ - entity: string; - - /** - * Shuffle the items to play. - */ - shuffle?: boolean; - - /** - * Optional request source. It contain the assistent query that initiate the request. - */ - source?: string; - } - - /** - * Provides live seekable range with start and end time in seconds and two more - * attributes. - */ - class LiveSeekableRange { - constructor( - start?: number, - end?: number, - isMovingWindow?: boolean, - isLiveDone?: boolean - ); - - /** - * A boolean value indicates whether a live stream is ended. If it is done; - * the end of live seekable range should stop updating. - */ - isLiveDone?: boolean; - - /** - * A boolean value indicates whether the live seekable range is a moving window. - * If false; it will be either a expanding range or a fixed range meaning live - * has ended. - */ - isMovingWindow?: boolean; - } - - /** - * Represents a data message containing item information for each requested ids. - */ - interface ItemsInfo { - /** - * List of changed itemIds. - */ - items: QueueItem[]; - - /** - * The corresponding request id. - */ - requestId?: number; - - type: MessageType; - } - - /** - * An image that describes a receiver application or media item. - * This could be an application icon; cover art; or a thumbnail. - */ - class Image { - constructor(url: string); - - /** - * The height of the image. - */ - height?: number; - - /** - * the URL to the image - */ - url: string; - - /** - * The width of the image - */ - width?: number; - } - /** Media event GET_STATUS request data. */ - interface GetStatusRequestData extends RequestData { - /** - * The options of a GET_STATUS request. - */ - options: GetStatusOptions; - } - - /** - * Get items info request data. - */ - class GetItemsInfoRequestData extends RequestData { - constructor(itemIds: number[]); - - /** - * List of item ids to be requested. - */ - itemIds: number[]; - } - /** - * A generic media description. - */ - interface GenericMediaMetadata extends MediaMetadata { - /** - * Content images. Examples would include cover art or a thumbnail of the - * currently playing media. - */ - images: Image[]; - - /** - * ISO 8601 date and/or time when the content was released; e.g. 2014-02-10. - */ - releaseDate?: string; - - /** - * @deprecated - use @see{@link releaseDate} instead - */ - releaseYear?: number; - - /** - * Content subtitle. - */ - subtitle?: string; - - /** - * Content title. - */ - title?: string; - } - - /** - * Focus state change message. - */ - interface FocusStateRequestData { - /** - * The focus state of the app. - */ - state: FocusState; - } - - /** Fetch items request data. */ - class FetchItemsRequestData extends RequestData { - constructor(itemId: number, nextCount: number, prevCount: number); - - /** - * ID of the reference media item for fetching more items. - */ - itemId: number; - - /** - * Number of items after the reference item to be fetched. - */ - nextCount: number; - - /** - * Number of items before the reference item to be fetched. - */ - prevCount: number; - } - - /** - * Extended media status information - */ - class ExtendedMediaStatus { - constructor( - playerState: MediaInformation, - opt_media?: MediaInformation - ); - - media: MediaInformation; - - playerState: ExtendedPlayerState; - } - - /** Event data for @see{@link EventType.ERROR} event. */ - class ErrorEvent extends Event { - constructor(detailedErrorCode?: DetailedErrorCode, error?: any); - - /** - * An error code representing the cause of the error. - */ - detailedErrorCode?: DetailedErrorCode; - - /** - * The error object. - * This could be an Error object (e.g.; if an Error was thrown in an event handler) - * or an object with error information (e.g.; if the receiver received an invalid - * command). - */ - error?: any; - } - - class ErrorData { - constructor(type: ErrorType); - - /** - * Application-specific data for this request. - * It enables the sender and receiver to easily extend the media protocol - * without having to use a new namespace with custom messages. - */ - customData?: any; - - /** - * Id of the request; used to correlate request/response. - */ - requestId?: number; - } - - /** Media event EDIT_TRACKS_INFO request data. */ - interface EditTracksInfoRequestData extends RequestData { - /** - * Array of the Track trackIds that should be active. - * If it is not provided; the active tracks will not change. - * If the array is empty; no track will be active. - */ - activeTrackIds?: number[]; - - /** - * Flag to enable or disable text tracks. - * If false it will disable all text tracks; - * if true it will enable the first text track; or the previous active text tracks. - * This flag is ignored if activeTrackIds or language is provided. - */ - enableTextTracks?: boolean; - - /** - * Indicates that the provided language was not explicit user request; but rather - * inferred from used language in voice query. - * It allows receiver apps to use user saved preference instead of spoken language. - */ - isSuggestedLanguage?: boolean; - - /** - * Language for the tracks that should be active. The language field will take - * precedence over activeTrackIds if both are specified. - */ - language?: string; - - textTrackStyle?: TextTrackStyle; - } - - /** - * Media event EDIT_AUDIO_TRACKS request data. If language is not provided; - * the default audio track for the media will be enabled. - */ - interface EditAudioTracksRequestData extends RequestData { - /** - * Indicates that the provided language was not explicit user request; - * but rather inferred from used language in voice query. - * It allows receiver apps to use user saved preference instead of spoken language. - */ - isSuggestedLanguage?: boolean; - - language?: string; - } - - /** DisplayStatus request data. */ - interface DisplayStatusRequestData { - /** - * Optional request source. It contain the assistent query that initiate the request. - */ - source: string; - } - - /** CustomCommand request data. */ - interface CustomCommandRequestData { - /** - * Custom Data; typically represented by a stringified JSON object. - */ - data: string; - - /** - * Optional request source. It contain the assistent query that initiate the request. - */ - source: string; - } - - class BreakStatus { - constructor(currentBreakTime: number, currentBreakClipTime: number); - - /** - * Id of current break clip. - */ - breakClipId: string; - - /** - * Id of current break. - */ - breakId: string; - - /** - * Time in sec elapsed after current break clip starts. - */ - currentBreakClipTime: number; - - /** - * Time in sec elapsed after current break starts. - */ - currentBreakTime: number; - - /** - * The time in sec when this break clip becomes skippable. - * 5 means that end user can skip this break clip after 5 seconds. - * If this field is not defined; it means that current break clip is not skippable. - */ - whenSkippable: number; - } - - /** - * Represents break clip (e.g. a clip of ad during ad break) - */ - class BreakClip { - constructor(id: string); - - /** - * Url of page that sender will display; when end user clicks link on sender UI; while receiver is playing this clip. - */ - clickThroughUrl?: string; - /** - * Typically the url of the break media (playing on the receiver). - */ - contentId?: string; - /** - * The content MIME type. - */ - contentType?: string; - /** - * Optional break media url; to allow using contentId for real id. - * If contentUrl is provided; it will be used as media url; - * otherwise the contentId will be used as the media url. - */ - contentUrl?: string; - /** - * Application-specific break clip data. - */ - customData?: any; - /** - * Duration of break clip in sec. - */ - duration?: number; - /** - * The format of the HLS media segment. - */ - hlsSegmentFormat?: HlsSegmentFormat; - /** - * Unique id of break clip. - */ - id: string; - /** - * Url of content that sender will display while receiver is playing this clip. - */ - posterUrl?: string; - /** - * Title of break clip. Sender might display this on its screen; if provided. - */ - title?: string; - /** - * VAST ad request configuration. Used if contentId or contentUrl is not provided. - */ - vastAdsRequest?: VastAdsRequest; - /** - * The time in sec when this break clip becomes skippable. - * 5 means that end user can skip this break clip after 5 seconds. - * If this field is not defined; it means that current break clip is not skippable. - */ - whenSkippable?: number; - } - - /** Represents break (e.g. ad break) included in main video. */ - class Break { - constructor(id: string, breakClipIds: string[], position: number); - /** - * List of ids of break clip that this break includes. - */ - breakClipIds: string[]; - /** - * Duration of break in sec. - */ - duration?: number; - /** - * Unique id of break. - */ - id: string; - /** - * If true; indicates this is embedded break in main stream. - */ - - isEmbedded?: boolean; - /** - * Whether break is watched. - * Sender can change color of progress bar marker corresponding to this break once - * this field changes from false to true; - * denoting that the end-user already watched this break. - */ - isWatched: boolean; - - /** - * Where the break is located inside main video. -1 represents the end of main video. - */ - position: number; - } +export as namespace messages +export type UserAction = + | "LIKE" + | "DISLIKE" + | "FOLLOW" + | "UNFOLLOW" + | "FLAG" + | "SKIP_AD"; + +export type UserActionContext = + | "UNKNOWN_CONTEXT" + | "ALBUM" + | "ARTIST" + | "PLAYLIST" + | "EPISODE" + | "SERIES" + | "MOVIE" + | "CHANNEL" + | "TEAM" + | "PLAYER" + | "COACH"; + +export type TextTrackType = + | "SUBTITLES" + | "CAPTIONS" + | "DESCRIPTIONS" + | "CHAPTERS" + | "METADATA"; + +export type TextTrackWindowType = "NONE" | "NORMAL" | "ROUNDED_CORNERS"; + +export type TrackType = "TEXT" | "AUDIO" | "VIDEO"; + +export type TextTrackFontGenericFamily = + | "SANS_SERIF" + | "MONOSPACED_SANS_SERIF" + | "SERIF" + | "MONOSPACED_SERIF" + | "CASUAL" + | "CURSIVE" + | "SMALL_CAPITALS"; + +export type TextTrackFontStyle = "NORMAL" | "BOLD" | "BOLD_ITALIC" | "ITALIC"; + +export type TextTrackEdgeType = + | "NONE" + | "OUTLINE" + | "DROP_SHADOW" + | "RAISED" + | "DEPRESSED"; + +export type Command = + | "PAUSE" + | "SEEK" + | "STREAM_VOLUME" + | "STREAM_MUTE" + | "ALL_BASIC_MEDIA" + | "QUEUE_NEXT" + | "QUEUE_PREV" + | "QUEUE_SHUFFLE" + | "SKIP_AD"; + +export type SeekResumeState = "PLAYBACK_START" | "PLAYBACK_PAUSE"; + +export type StreamingProtocolType = + | "UNKNOWN" + | "MPEG_DASH" + | "HLS" + | "SMOOTH_STREAMING"; + +export type StreamType = "BUFFERED" | "LIVE" | "NONE"; + +export type FocusState = "IN_FOCUS" | "NOT_IN_FOCUS"; + +export type ExtendedPlayerState = "LOADING"; + +export type ErrorType = + | "INVALID_PLAYER_STATE" + | "LOAD_FAILED" + | "LOAD_CANCELLED" + | "INVALID_REQUEST" + | "ERROR"; + +export type ErrorReason = + | "INVALID_COMMAND" + | "INVALID_PARAMS" + | "INVALID_MEDIA_SESSION_ID" + | "SKIP_LIMIT_REACHED" + | "NOT_SUPPORTED" + | "LANGUAGE_NOT_SUPPORTED" + | "END_OF_QUEUE" + | "APP_ERROR" + | "AUTHENTICATION_EXPIRED" + | "PREMIUM_ACCOUNT_REQUIRED" + | "CONCURRENT_STREAM_LIMIT" + | "PARENTAL_CONTROL_RESTRICTED" + | "NOT_AVAILABLE_IN_REGION" + | "CONTENT_ALREADY_PLAYING" + | "INVALID_REQUEST" + | "GENERIC_LOAD_ERROR"; + +export type RepeatMode = + | "REPEAT_OFF" + | "REPEAT_ALL" + | "REPEAT_SINGLE" + | "REPEAT_ALL_AND_SHUFFLE"; + +export type IdleReason = "CANCELLED" | "INTERRUPTED" | "FINISHED" | "ERROR"; + +export type HlsSegmentFormat = "AAC" | "AC3" | "MP3" | "TS" | "TS_AAC"; + +export type HdrType = "SDR" | "HDR" | "DV"; + +export type PlayStringId = + | "FREE_TRIAL_ABOUT_TO_EXPIRE" + | "SUBSCRIPTION_ABOUT_TO_EXPIRE" + | "STREAM_HIJACKED"; + +export type GetStatusOptions = "NO_METADATA" | "NO_QUEUE_ITEMS"; + +export type MessageType = + | "MEDIA_STATUS" + | "CLOUD_STATUS" + | "QUEUE_CHANGE" + | "QUEUE_ITEMS" + | "QUEUE_ITEM_IDS" + | "GET_STATUS" + | "LOAD" + | "PAUSE" + | "STOP" + | "PLAY" + | "SKIP_AD" + | "PLAY_AGAIN" + | "SEEK" + | "SET_PLAYBACK_RATE" + | "SET_VOLUME" + | "EDIT_TRACKS_INFO" + | "EDIT_AUDIO_TRACKS" + | "PRECACHE" + | "PRELOAD" + | "QUEUE_LOAD" + | "QUEUE_INSERT" + | "QUEUE_UPDATE" + | "QUEUE_REMOVE" + | "QUEUE_REORDER" + | "QUEUE_NEXT" + | "QUEUE_PREV" + | "QUEUE_GET_ITEM_RANGE" + | "QUEUE_GET_ITEMS" + | "QUEUE_GET_ITEM_IDS" + | "QUEUE_SHUFFLE" + | "SET_CREDENTIALS" + | "LOAD_BY_ENTITY" + | "USER_ACTION" + | "DISPLAY_STATUS" + | "FOCUS_STATE" + | "CUSTOM_COMMAND"; + +export type PlayerState = "IDLE" | "PLAYING" | "PAUSED" | "BUFFERING"; + +export type QueueChangeType = + | "INSERT" + | "REMOVE" + | "ITEMS_CHANGE" + | "UPDATE" + | "NO_CHANGE"; + +export type QueueType = + | "ALBUM" + | "PLAYLIST" + | "AUDIOBOOK" + | "RADIO_STATION" + | "PODCAST_SERIES" + | "TV_SERIES" + | "VIDEO_PLAYLIST" + | "LIVE_TV" + | "MOVIE"; + +export type MetadataType = + | "GENERIC" + | "MOVIE" + | "TV_SHOW" + | "MUSIC_TRACK" + | "PHOTO"; + +/** + * RefreshCredentials request data. + */ +export interface RefreshCredentialsRequestData { + [key: string]: any; +} + +/** + * Media event SET_VOLUME request data. + */ +export interface VolumeRequestData extends RequestData { + /** + * The media stream volume + */ + volume?: Volume; +} + +/** + * Represents the volume of a media session stream. + */ +export interface Volume { + /** + * Value from 0 to 1 that represents the current stream volume level. + */ + level?: number; + + /** + * Whether the stream is muted. + */ + muted?: boolean; +} + +/** + * Video information such as video resolution and High Dynamic Range (HDR). + */ +export class VideoInformation { + constructor(width: number, height: number, hdrType: HdrType); + + width: number; + + height: number; + + hdrType: HdrType; +} + +/** + * VAST ad request configuration. + */ +export interface VastAdsRequest { + /** + * Specifies a VAST document to be used as the ads response instead of making a + * request via an ad tag url. + * This can be useful for debugging and other situations where a VAST response is + * already available. + */ + adsResponse?: string; + + /** + * URL for VAST file. + */ + adTagUrl?: string; +} + +/** + * UserAction request data. + */ +export interface UserActionRequestData { + /** + * Optional request source. + * It contain the assistent query that initiate the request. + */ + source?: string; + + /** + * User action to be handled by the application. + */ + userAction?: UserAction; + + /** + * Optional context information for the user action. + */ + userActionContext?: UserActionContext; +} + +/** + * A TV episode media description. + */ +export interface TvShowMediaMetadata { + /** + * TV episode number. A positive integer. + */ + episode?: number; + + /** + * @deprecated use episode instead + */ + episodeNumber?: number; + + /** + * @deprecated use episode instead + */ + episodeTitle?: string; + + /** + * Content images. Examples would include cover art or a thumbnail of + * the currently playing media. + */ + images?: Image[]; + + /** + * ISO 8601 date when the episode originally aired; e.g. 2014-02-10. + */ + originalAirdate?: string; + + /** + * @deprecated use originalAirdate instead. + */ + releaseYear?: number; + + /** + * TV episode season. A positive integer. + */ + season?: number; + + /** + * @deprecated use season instead. + */ + seasonNumber?: number; + + /** + * TV series title. + */ + seriesTitle?: string; + + /** + * TV episode title. + */ + title?: string; +} +/** + * Describes track metadata information. + */ +export class Track { + constructor(trackId: number, trackType: TrackType); + + /** + * Custom data set by the receiver application. + */ + customData?: string; + + /** + * Language tag as per RFC 5646 (If subtype is “SUBTITLES” it is mandatory). + */ + language?: string; + + /** + * A descriptive; human readable name for the track. For example "Spanish". + */ + name?: string; + + /** + * For text tracks; the type of text track. + */ + subtype?: string; + + /** + * It can be the url of the track or any other identifier that allows the receiver + * to find the content (when the track is not inband or included in the manifest). + * For example it can be the url of a vtt file. + */ + trackContentId?: string; + + /** + * It represents the MIME type of the track content. For example if the track + * is a vtt file it will be ‘text/vtt’. This field is needed for out of band tracks; + * so it is usually provided if a trackContentId has also been provided. + * It is not mandatory if the receiver has a way to identify the content from + * the trackContentId; but recommended. + * The track content type; if provided; must be consistent with the track type. + */ + trackContentType?: string; + + /** + * Unique identifier of the track within the context of a MediaInformation object. + */ + trackId?: number; + + /** + * The type of track. + */ + type: TrackType; +} +/** + * Describes style information for a text track. + */ +export interface TextTrackStyle { + /** + * The background 32 bit RGBA color. The alpha channel should be used for transparent backgrounds. + */ + backgroundColor?: string; + + /** + * Custom data set by the receiver application. + */ + customData?: any; + + /** + * RGBA color for the edge; this value will be ignored if edgeType is NONE. + */ + edgeColor?: string; + + edgeType?: TextTrackEdgeType; + + /** + * If the font is not available in the receiver the fontGenericFamily will be used. + */ + fontFamily?: string; + + /** + * The text track generic family. + */ + fontGenericFamily?: TextTrackFontGenericFamily; + + /** + * The font scaling factor for the text track (the default is 1). + */ + fontScale?: number; + + /** + * The text track font style. + */ + fontStyle?: TextTrackFontStyle; + + /** + * The foreground 32 bit RGBA color. + */ + foregroundColor?: string; + + /** + * 32 bit RGBA color for the window. This value will be ignored if windowType is NONE. + */ + windowColor?: string; + + /** + * Rounded corner radius absolute value in pixels (px). This value will be ignored + * if windowType is not ROUNDED_CORNERS. + */ + windowRoundedCornerRadius?: number; + + /** + * The window concept is defined in CEA-608 and CEA-708. In WebVTT is called a region. + */ + windowType?: TextTrackWindowType; +} + +/** + * Media event playback rate request data. + */ +export interface SetPlaybackRateRequestData extends RequestData { + /** + * New playback rate (>0). + */ + playbackRate?: number; + + /** + * New playback rate relative to current playback rate. + * New rate will be the result of multiplying the current rate with the value. + * For example a value of 1.1 will increase rate by 10%. + * (Only used if the playbackRate value is not provided). + */ + relativePlaybackRate?: number; +} + +/** + * SetCredentials request data. + */ +export interface SetCredentialsRequestData { + /** + * Credentials to use by receiver. + */ + credentials?: string; + + /** + * If it is a response for refresh credentials; it will indicate the request id + * of the refresh credentials request. + */ + forRequestId?: number; + + /** + * Optional request source. It contain the assistent query that initiate the request. + */ + source?: string; +} + +/** + * Media event SEEK request data. + */ +export interface SeekRequestData extends RequestData { + /** + * Seconds since beginning of content. + */ + currentTime?: number; + + /** + * Seconds relative to the current playback position. If this field is defined; + * the currentTime field will be ignored. + */ + relativeTime?: number; + + /** + * The playback state after a SEEK request. + */ + resumeState?: SeekResumeState; +} + +/** + * Provides seekable range in seconds. + */ +export class SeekableRange { + constructor(start?: number, end?: number); + + /** + * End of the seekable range in seconds. + */ + end?: number; + + /** + * Start of the seekable range in seconds. + */ + start?: number; +} + +/** + * Media event request data. + */ +export class RequestData { + constructor(type: MessageType); + + /** + * Application-specific data for this request. + * It enables the sender and receiver to easily extend the media protocol + * without having to use a new namespace with custom messages. + */ + customData?: any; + + /** + * Id of the media session that the request applies to. + */ + mediaSessionId?: number; + + /** + * Id of the request; used to correlate request/response. + */ + requestId: number; +} + +/** + * Media event UPDATE queue request data. + */ +export interface QueueUpdateRequestData { + /** + * ID of the current media Item after the deletion + * (if not provided; the currentItem value will be the same as before the deletion; + * if it does not exist because it has been deleted; the currentItem will point to + * the next logical item in the list). + */ + currentItemId?: number; + + /** + * Seconds since the beginning of content to start playback of the current item. + * If provided; this value will take precedence over the startTime value provided + * at the QueueItem level but only the first time the item is played. + * This is to cover the common case where the user jumps to the middle of an + * item so the currentTime does not apply to the item permanently like the + * QueueItem startTime does. It avoids having to reset the startTime dynamically + * (that may not be possible if the phone has gone to sleep). + */ + currentTime?: number; + + /** + * List of queue items to be updated. No reordering will happen; the items will + * retain the existing order. + */ + items?: QueueItem[]; + + /** + * Skip/Go back number of items with respect to the position of currentItem + * (it can be negative). If it is out of boundaries; the currentItem will be the + * next logical item in the queue wrapping around the boundaries. + * The new currentItem position will follow the rules of the queue repeat behavior. + */ + jump?: number; + + /** + * Behavior of the queue when all items have been played. + */ + repeatMode?: RepeatMode; + + /** + * Shuffle the queue items when the update is processed. + * After the queue items are shuffled; the item at the currentItem position will + * be loaded. + */ + shuffle?: boolean; +} + +/** + * Media event queue REORDER request data. + */ +export class QueueReorderRequestData extends RequestData { + constructor(itemIds: number[]); + + /** + * ID of the current media Item after the deletion (if not provided; + * the currentItem value will be the same as before the deletion; + * if it does not exist because it has been deleted; + * the currentItem will point to the next logical item in the list). + */ + currentItemId?: number; + + /** + * Seconds since the beginning of content to start playback of the current item. + * If provided; this value will take precedence over the startTime value provided + * at the QueueItem level but only the first time the item is played. + * This is to cover the common case where the user jumps to the middle of an + * item so the currentTime does not apply to the item permanently like + * the QueueItem startTime does. It avoids having to reset the startTime dynamically + * (that may not be possible if the phone has gone to sleep). + */ + currentTime?: number; + + /** + * ID of the item that will be located immediately after the reordered list. + * If the ID is not found or it is not provided; + * the reordered list will be appended at the end of the existing list. + */ + insertBefore?: number; + + /** + * IDs of the items to be reordered; in the new order. + * Items not provided will keep their existing order. + * The provided list will be inserted at the position determined by insertBefore. + * For example: + * If insertBefore is not specified Existing queue: “A”;”D”;”G”;”H”;”B”;”E” itemIds: + * “D”;”H”;”B” New Order: “A”;”G”;”E”;“D”;”H”;”B” + * If insertBefore is “A” Existing queue: “A”;”D”;”G”;”H”;”B” itemIds: + * “D”;”H”;”B” New Order: “D”;”H”;”B”;“A”;”G”;”E” + * If insertBefore is “G” Existing queue: “A”;”D”;”G”;”H”;”B” itemIds: + * “D”;”H”;”B” New Order: “A”;“D”;”H”;”B”;”G”;”E” + */ + itemIds: number[]; +} + +/** + * Media event queue REMOVE request data. + */ +export class QueueRemoveRequestData extends RequestData { + constructor(itemIds: number[]); + + /** + * ID of the current media Item after the deletion + * (if not provided; the currentItem value will be the same as before the deletion; + * if it does not exist because it has been deleted; + * the currentItem will point to the next logical item in the list). + */ + currentItemId?: number; + + /** + * Seconds since the beginning of content to start playback of the current item. + * If provided; this value will take precedence over the startTime value provided + * at the QueueItem level but only the first time the item is played. + * This is to cover the common case where the user jumps to the middle of an + * item so the currentTime does not apply to the item permanently like the + * QueueItem startTime does. It avoids having to reset the startTime dynamically + * (that may not be possible if the phone has gone to sleep). + */ + currentTime?: number; + + /** + * IDs of queue items to be deleted. + */ + itemIds?: number[]; +} +/** + * Media event queue LOAD request data. + */ +export class QueueLoadRequestData extends RequestData { + constructor(items: QueueItem[]); + + /** + * Seconds (since the beginning of content) to start playback of the first item to + * be played. If provided; this value will take precedence over the + * startTime value provided at the QueueItem level but only the first + * time the item is played. This is to cover the common case where the user + * casts the item that was playing locally so the currentTime does not apply + * to the item permanently like the QueueItem startTime does. + * It avoids having to reset the startTime dynamically + * (that may not be possible if the phone has gone to sleep). + */ + currentTime?: number; + + /** + * Behavior of the queue when all items have been played. + */ + items: QueueItem[]; + + /** + * Id of the request; used to correlate request/response. + */ + repeatMode?: RepeatMode; + + /** + * The index of the item in the items array that must be the first currentItem + * (the item that will be played first). Note this is the index of the array + * (starts at 0) and not the itemId (as it is not known until the queue is created). + * If repeatMode is REPEAT_OFF playback will end when the last item in the array is + * played (elements before the startIndex will not be played). + * This may be useful for continuation scenarios where the user was already + * using the sender app and in the middle decides to cast. + * In this way the sender app does not need to map between the local and remote queue + * positions or saves one extra QUEUE_UPDATE request. + */ + startIndex?: number; +} + +/** + * Queue item information. Application developers may need to create a QueueItem to + * insert a queue element using InsertQueueItems. In this case they should not + * provide an itemId (as the actual itemId will be assigned when the item is inserted + * in the queue). This prevents ID collisions with items added from a sender app. + */ +export class QueueItem { + constructor(opt_itemId?: number); + + /** + * Array of Track trackIds that are active. If the array is not provided; + * the default tracks will be active. + */ + activeTrackIds?: number[]; + + /** + * If the autoplay parameter is not specified or is true; the media player + * will begin playing the element in the queue when the item becomes the currentItem. + */ + autoplay?: boolean; + + /** + * The application can define any extra queue item information needed. + */ + customData?: any; + + /** + * Unique identifier of the item in the queue. + * The attribute is optional because for LOAD or INSERT should not be provided + * (as it will be assigned by the receiver when an item is first created/inserted). + */ + itemId?: number; + + /** + * Metadata (including contentId) of the playlist element. + */ + media?: MediaInformation; + + /** + * Playback duration of the item; if it is larger than the actual duration - + * startTime it will be ignored (default behavior). + * It can be negative; in such case the duration will be the actual asset + * duration minus the duration provided. + * It can be used for photo slideshows to control the duration the item should + * be presented or for live events to control the duration that the program + * should be played. It may be useful for autoplay scenarios to avoid displaying all + * the credits after an episode has ended. + */ + playbackDuration?: number; + + /** + * This parameter is a hint for the receiver to preload this media + * item before it is played. It allows for a smooth transition between items + * played from the queue. The time is expressed in seconds; relative to + * the beginning of this item playback (usually the end of the previous item playback). + * Only positive values are valid. For example; if the value is 10 seconds; this item + * will be preloaded 10 seconds before the previous item has finished. + * The receiver will try to honor this value but will not guarantee it; + * for example if the value is larger than the previous item duration the + * receiver may just preload this item shortly after the previous item has started playing + * (there will never be two items being preloaded in parallel). + * Also; if an item is inserted in the queue just after the currentItem and the time to preload is higher than the + * time left on the currentItem; the preload will just happen as soon as possible. + */ + preloadTime?: number; + + /** + * Seconds since beginning of content. If the content is live content; + * and startTime is not specified; the stream will start at the live position. + */ + startTime?: number; +} + +/** + * Media event queue INSERT request data. + */ +export class QueueInsertRequestData extends RequestData { + constructor(items: QueueItem[]); + + /** + * ID of the current media Item after the insertion (if not provided; + * the currentItem value will be the same as before the insertion). + */ + currentItemId?: number; + + /** + * Index (relative to the items array; starting with 0) of the new current media Item. + * For inserted items we use the index (similar to startIndex in QUEUE_LOAD) and not + * currentItemId; because the itemId is unknown until the items are inserted. + * If not provided; the currentItem value will be the same as before the insertion + * (unless currentItemId is provided). This param allows to make atomic the common use + * case of insert and play an item. + */ + currentItemIndex?: number; + + /** + * Seconds since the beginning of content to start playback of the current item. + * If provided; this value will take precedence over the startTime value provided + * at the QueueItem level but only the first time the item is played. + * This is to cover the common case where the user jumps to the middle of an + * item so the currentTime does not apply to the item permanently like the + * QueueItem startTime does. It avoids having to reset the startTime dynamically + * (that may not be possible if the phone has gone to sleep). + */ + currentTime?: number; + + /** + * ID of the item that will be located immediately after the inserted list. + * If the ID is not found or it is not provided; the list will be appended at + * the end of the existing list. + */ + insertBefore?: number; + + /** + * List of queue items. The itemId field of the items should be empty. + * It is sorted (first element will be played first). + */ + items: QueueItem[]; +} + +/** + * Represents a data message containing the full list of queue ids. + */ +export interface QueueIds { + /** + * List of queue item ids. + */ + itemIds?: number[]; + + /** + * The corresponding request id. + */ + requestId?: number; + + type: MessageType; +} + +/** + * Queue data as part of the LOAD request. + */ +export class QueueData { + constructor( + id?: string, + name?: string, + description?: string, + repeatMode?: RepeatMode, + items?: QueueItem[], + startIndex?: number, + startTime?: number + ); + + /** + * Description of the queue. + */ + description?: string; + + /** + * Optional Queue entity id; provide Google Assistant deep link. + */ + entity?: string; + + /** + * Id of the queue. + */ + id?: string; + + /** + * Array of queue items. It is sorted (first element will be played first). + */ + items?: QueueItem[]; + + /** + * Name of the queue. + */ + name?: string; + + /** + * Queue type; e.g. album; playlist; radio station; tv series; etc. + */ + queueType?: QueueType; + + /** + * Continuous playback behavior of the queue. + */ + repeatMode?: RepeatMode; + + /** + * The index of the item in the queue that should be used to start playback first. + */ + startIndex?: number; + + /** + * Seconds (since the beginning of content) to start playback of the first item. + */ + startTime?: number; +} + +/** + * Represents a queue change message; such as insert; remove; and update. + */ +export interface QueueChange { + /** + * The actual queue change type. + */ + changeType?: QueueChangeType; + + /** + * The id to insert the list of itemIds before. + */ + insertBefore?: number; + + /** + * List of changed itemIds. + */ + itemIds?: number[]; + + /** + * The corresponding request id. + */ + requestId?: number; + + /** + * The queue change sequence ID. Used to coordinate state sync between various + * senders and the receiver. + */ + sequenceNumber?: number; + + type: MessageType; +} + +/** + * Media event PRELOAD request data. + */ +export class PreloadRequestData implements LoadRequestData { + /** + * Array of trackIds that are active. If the array is not provided; + * the default tracks will be active. + */ + activeTrackIds: number[]; + /** + * If the autoplay parameter is specified; the media player will begin playing + * the content when it is loaded. Even if autoplay is not specified;the media player + * implementation may choose to begin playback immediately. + */ + autoplay?: boolean; + /** + * Optional user credentials. + */ + credentials?: string; + /** + * Optional credentials type. The type 'cloud' is a reserved type used by load + * requests that were originated by voice assistant commands. + */ + credentialsType?: string; + /** + * Seconds since beginning of content. If the content is live content; + * and currentTime is not specified; the stream will start at the live position. + */ + currentTime?: number; + /** + * If the autoplay parameter is specified; the media player will begin playing + * the content when it is loaded. Even if autoplay is not specified; the media + * player implementation may choose to begin playback immediately. + */ + media: MediaInformation; + /** + * The media playback rate. + */ + playbackRate?: number; + /** + * Queue data. + */ + queueData: QueueData; + /** + * Application-specific data for this request. + * It enables the sender and receiver to easily extend the media protocol + * without having to use a new namespace with custom messages. + */ + customData?: any; + /** + * Id of the media session that the request applies to. + */ + mediaSessionId?: number; + /** + * Id of the request; used to correlate request/response. + */ + requestId: number; + constructor(itemId: number); + + /** + * The ID of the queue item. + */ + itemId: number; +} + +/** + * Media event PRECACHE request data. (Some fields of the load request; + * like autoplay and queueData; are ignored). + */ +export class PrecacheRequestData implements LoadRequestData { + /** + * Array of trackIds that are active. If the array is not provided; + * the default tracks will be active. + */ + activeTrackIds: number[]; + /** + * If the autoplay parameter is specified; the media player will begin playing + * the content when it is loaded. Even if autoplay is not specified;the media player + * implementation may choose to begin playback immediately. + */ + autoplay?: boolean; + /** + * Optional user credentials. + */ + credentials?: string; + /** + * Optional credentials type. The type 'cloud' is a reserved type used by load + * requests that were originated by voice assistant commands. + */ + credentialsType?: string; + /** + * Seconds since beginning of content. If the content is live content; and + * currentTime is not specified; the stream will start at the live position. + */ + currentTime?: number; + /** + * If the autoplay parameter is specified; the media player will begin playing + * the content when it is loaded. Even if autoplay is not specified; + * the media player implementation may choose to begin playback immediately. + */ + media: MediaInformation; + /** + * The media playback rate. + */ + playbackRate?: number; + /** + * Queue data. + */ + queueData: QueueData; + /** + * Application-specific data for this request. + * It enables the sender and receiver to easily extend the media protocol + * without having to use a new namespace with custom messages. + */ + customData?: any; + /** + * Id of the media session that the request applies to. + */ + mediaSessionId?: number; + /** + * Id of the request; used to correlate request/response. + */ + requestId: number; + constructor(data?: string); + + /** + * Application precache data. + */ + precacheData?: string; +} + +/** + * PlayString request data. + */ +export class PlayStringRequestData { + constructor(stringId: PlayStringId, opt_arguments?: string[]); + + /** + * An optional array of string values to be filled into the text. + */ + arguments?: string[]; + + /** + * An identifier for the text to be played back. + */ + stringId: PlayStringId; +} + +/** + * A photo media description. + */ +export interface PhotoMediaMetadata { + /** + * Name of the photographer. + */ + artist?: string; + + /** + * ISO 8601 date and time the photo was taken; e.g. 2014-02-10T15:47:00Z. + */ + creationDateTime?: string; + + /** + * Photo height; in pixels. + */ + height?: number; + + /** + * Images associated with the content. Examples would include a photo thumbnail. + */ + images: Image[]; + + /** + * Latitude. + */ + latitude?: number; + + /** + * Location where the photo was taken. For example; "Seattle; Washington; USA". + */ + location?: string; + + /** + * Longitude. + */ + longitude?: number; + + /** + * Photo title. + */ + title?: string; + + /** + * Photo width; in pixels. + */ + width?: number; +} + +/** + * A music track media description. + */ +export interface MusicTrackMediaMetadata { + /** + * Album artist name. + */ + albumArtist?: string; + + /** + * Album name. + */ + albumName?: string; + + /** + * Track artist name. + */ + artist?: string; + + /** + * @deprecated: use @see{@link artist} instead + */ + artistName: string; + + /** + * Track composer name. + */ + composer?: string; + + /** + * Disc number. A positive integer. + */ + discNumber?: number; + + /** + * Content images. Examples would include cover art or a thumbnail of the + * currently playing media. + */ + images: Image[]; + + /** + * ISO 8601 date when the track was released; e.g. 2014-02-10. + */ + releaseDate?: string; + + /** + * @deprecated: Use @see{@link releaseDate} instead + */ + releaseYear?: string; + + /** + * Track name. + */ + songName?: string; + + /** + * Track title. + */ + title?: string; + + /** + * Track number in album. A positive integer. + */ + trackNumber?: number; +} + +/** + * A movie media description. + */ +export interface MovieMediaMetadata { + /** + * Content images. Examples would include cover art or a thumbnail of the + * currently playing media. + */ + images: Image[]; + + /** + * ISO 8601 date when the movie was released; e.g. 2014-02-10. + */ + releaseDate?: string; + + /** + * @deprecated: use @see{@link releaseDate} instead + */ + releaseYear?: number; + + /** + * Movie studio. + */ + studio?: string; + + /** + * Movie subtitle. + */ + subtitle?: string; + + /** + * Movie title. + */ + title?: string; +} +/** + * Represents the status of a media session. + */ +export interface MediaStatus { + /** + * List of IDs corresponding to the active tracks. + */ + activeTrackIds: number[]; + + /** + * Status of break; if receiver is playing break. + * This field will be defined only when receiver is playing break. + */ + breakStatus: BreakStatus; + + /** + * ID of this media item (the item that originated the status change). + */ + currentItemId?: number; + + /** + * The current playback position. + */ + currentTime: number; + + /** + * Application-specific media status. + */ + customData?: any; + + /** + * Extended media status information. + */ + extendedStatus: ExtendedMediaStatus; + + /** + * If the state is IDLE; the reason the player went to IDLE state. + */ + idleReason: IdleReason; + + /** + * List of media queue items. + */ + items: QueueItem[]; + + /** + * Seekable range of a live or event stream. It uses relative media time in seconds. + * It will be undefined for VOD streams. + */ + liveSeekableRange: LiveSeekableRange; + + /** + * ID of the media Item currently loading. If there is no item being loaded; + * it will be undefined. + */ + loadingItemId?: number; + + /** + * The media information. + */ + media: MediaInformation; + + /** + * Unique id for the session. + */ + mediaSessionId: number; + + /** + * The playback rate. + */ + playbackRate: number; + + /** + * The playback state. + */ + playerState: PlayerState; + + /** + * ID of the next Item; only available if it has been preloaded. + * Media items can be preloaded and cached temporarily in memory; + * so when they are loaded later on; the process is faster + * (as the media does not have to be fetched from the network). + */ + preloadedItemId?: number; + + /** + * Queue data. + */ + queueData: QueueData; + + /** + * The behavior of the queue when all items have been played. + */ + repeatMode: RepeatMode; + + /** + * The commands supported by this player. + */ + supportedMediaCommands: number; + + type: MessageType; + + /** + * The video information. + */ + videoInfo: VideoInformation; + + /** + * The current stream volume. + */ + volume: Volume; +} +/** + * Common media metadata used as part of MediaInformation + */ +export class MediaMetadata { + constructor(type: MetadataType); + + /** + * The type of metadata + */ + metadataType: MetadataType; +} + +/** + * Represents the media information. + */ +export interface MediaInformation { + /** + * Partial list of break clips that includes current break clip that receiver + * is playing or ones that receiver will play shortly after; instead of sending + * whole list of clips. This is to avoid overflow of MediaStatus message. + */ + breakClips: BreakClip[]; + + /** + * List of breaks. + */ + breaks: Break[]; + + /** + * Typically the url of the media. + */ + contentId: string; + + /** + * The content MIME type. + */ + contentType: string; + + /** + * Optional media url; to allow using contentId for real id. If contentUrl + * is provided; it will be used as media url; otherwise the contentId will + * be used as the media url. + */ + contentUrl?: string; + + /** + * Application-specific media information. + */ + customData?: any; + + /** + * The media duration. + */ + duration?: number; + + /** + * Optional Media entity; provide Google Assistant deep link. + */ + entity?: string; + + /** + * The format of the HLS media segment. + */ + hlsSegmentFormat: HlsSegmentFormat; + + /** + * The media metadata. + */ + metadata: MediaMetadata; + + /** + * The stream type. + */ + streamType: StreamType; + + /** + * The style of text track. + */ + textTrackStyle: TextTrackStyle; + + /** + * The media tracks. + */ + tracks: Track[]; +} + +/** + * Media event LOAD request data. + */ +export interface LoadRequestData extends RequestData { + /** + * Array of trackIds that are active. If the array is not provided; the + * default tracks will be active. + */ + activeTrackIds: number[]; + + /** + * If the autoplay parameter is specified; the media player will begin + * playing the content when it is loaded. Even if autoplay is not + * specified;the media player implementation may choose to begin playback + * immediately. + */ + autoplay?: boolean; + + /** + * Optional user credentials. + */ + credentials?: string; + + /** + * Optional credentials type. The type 'cloud' is a reserved type used by + * load requests that were originated by voice assistant commands. + */ + credentialsType?: string; + + /** + * Seconds since beginning of content. If the content is live content; + * and currentTime is not specified; the stream will start at the live position. + */ + currentTime?: number; + + /** + * If the autoplay parameter is specified; the media player will begin playing + * the content when it is loaded. Even if autoplay is not specified; the media + * player implementation may choose to begin playback immediately. + */ + media: MediaInformation; + + /** + * The media playback rate. + */ + playbackRate?: number; + + /** + * Queue data. + */ + queueData: QueueData; +} + +/** + * LoadByEntity request data. + */ +export interface LoadByEntityRequestData { + /** + * Content entity information; typically represented by a stringified JSON object + */ + entity: string; + + /** + * Shuffle the items to play. + */ + shuffle?: boolean; + + /** + * Optional request source. It contain the assistent query that initiate the request. + */ + source?: string; +} + +/** + * Provides live seekable range with start and end time in seconds and two more + * attributes. + */ +export class LiveSeekableRange { + constructor( + start?: number, + end?: number, + isMovingWindow?: boolean, + isLiveDone?: boolean + ); + + /** + * A boolean value indicates whether a live stream is ended. If it is done; + * the end of live seekable range should stop updating. + */ + isLiveDone?: boolean; + + /** + * A boolean value indicates whether the live seekable range is a moving window. + * If false; it will be either a expanding range or a fixed range meaning live + * has ended. + */ + isMovingWindow?: boolean; +} + +/** + * Represents a data message containing item information for each requested ids. + */ +export interface ItemsInfo { + /** + * List of changed itemIds. + */ + items: QueueItem[]; + + /** + * The corresponding request id. + */ + requestId?: number; + + type: MessageType; +} + +/** + * An image that describes a receiver application or media item. + * This could be an application icon; cover art; or a thumbnail. + */ +export class Image { + constructor(url: string); + + /** + * The height of the image. + */ + height?: number; + + /** + * the URL to the image + */ + url: string; + + /** + * The width of the image + */ + width?: number; +} +/** Media event GET_STATUS request data. */ +export interface GetStatusRequestData extends RequestData { + /** + * The options of a GET_STATUS request. + */ + options: GetStatusOptions; +} + +/** + * Get items info request data. + */ +export class GetItemsInfoRequestData extends RequestData { + constructor(itemIds: number[]); + + /** + * List of item ids to be requested. + */ + itemIds: number[]; +} +/** + * A generic media description. + */ +export interface GenericMediaMetadata extends MediaMetadata { + /** + * Content images. Examples would include cover art or a thumbnail of the + * currently playing media. + */ + images: Image[]; + + /** + * ISO 8601 date and/or time when the content was released; e.g. 2014-02-10. + */ + releaseDate?: string; + + /** + * @deprecated - use @see{@link releaseDate} instead + */ + releaseYear?: number; + + /** + * Content subtitle. + */ + subtitle?: string; + + /** + * Content title. + */ + title?: string; +} + +/** + * Focus state change message. + */ +export interface FocusStateRequestData { + /** + * The focus state of the app. + */ + state: FocusState; +} + +/** Fetch items request data. */ +export class FetchItemsRequestData extends RequestData { + constructor(itemId: number, nextCount: number, prevCount: number); + + /** + * ID of the reference media item for fetching more items. + */ + itemId: number; + + /** + * Number of items after the reference item to be fetched. + */ + nextCount: number; + + /** + * Number of items before the reference item to be fetched. + */ + prevCount: number; +} + +/** + * Extended media status information + */ +export class ExtendedMediaStatus { + constructor( + playerState: MediaInformation, + opt_media?: MediaInformation + ); + + media: MediaInformation; + + playerState: ExtendedPlayerState; +} + +/** Event data for @see{@link EventType.ERROR} event. */ +export class ErrorEvent extends Event { + constructor(detailedErrorCode?: DetailedErrorCode, error?: any); + + /** + * An error code representing the cause of the error. + */ + detailedErrorCode?: DetailedErrorCode; + + /** + * The error object. + * This could be an Error object (e.g.; if an Error was thrown in an event handler) + * or an object with error information (e.g.; if the receiver received an invalid + * command). + */ + error?: any; +} + +export class ErrorData { + constructor(type: ErrorType); + + /** + * Application-specific data for this request. + * It enables the sender and receiver to easily extend the media protocol + * without having to use a new namespace with custom messages. + */ + customData?: any; + + /** + * Id of the request; used to correlate request/response. + */ + requestId?: number; +} + +/** Media event EDIT_TRACKS_INFO request data. */ +export interface EditTracksInfoRequestData extends RequestData { + /** + * Array of the Track trackIds that should be active. + * If it is not provided; the active tracks will not change. + * If the array is empty; no track will be active. + */ + activeTrackIds?: number[]; + + /** + * Flag to enable or disable text tracks. + * If false it will disable all text tracks; + * if true it will enable the first text track; or the previous active text tracks. + * This flag is ignored if activeTrackIds or language is provided. + */ + enableTextTracks?: boolean; + + /** + * Indicates that the provided language was not explicit user request; but rather + * inferred from used language in voice query. + * It allows receiver apps to use user saved preference instead of spoken language. + */ + isSuggestedLanguage?: boolean; + + /** + * Language for the tracks that should be active. The language field will take + * precedence over activeTrackIds if both are specified. + */ + language?: string; + + textTrackStyle?: TextTrackStyle; +} + +/** + * Media event EDIT_AUDIO_TRACKS request data. If language is not provided; + * the default audio track for the media will be enabled. + */ +export interface EditAudioTracksRequestData extends RequestData { + /** + * Indicates that the provided language was not explicit user request; + * but rather inferred from used language in voice query. + * It allows receiver apps to use user saved preference instead of spoken language. + */ + isSuggestedLanguage?: boolean; + + language?: string; +} + +/** DisplayStatus request data. */ +export interface DisplayStatusRequestData { + /** + * Optional request source. It contain the assistent query that initiate the request. + */ + source: string; +} + +/** CustomCommand request data. */ +export interface CustomCommandRequestData { + /** + * Custom Data; typically represented by a stringified JSON object. + */ + data: string; + + /** + * Optional request source. It contain the assistent query that initiate the request. + */ + source: string; +} + +export class BreakStatus { + constructor(currentBreakTime: number, currentBreakClipTime: number); + + /** + * Id of current break clip. + */ + breakClipId: string; + + /** + * Id of current break. + */ + breakId: string; + + /** + * Time in sec elapsed after current break clip starts. + */ + currentBreakClipTime: number; + + /** + * Time in sec elapsed after current break starts. + */ + currentBreakTime: number; + + /** + * The time in sec when this break clip becomes skippable. + * 5 means that end user can skip this break clip after 5 seconds. + * If this field is not defined; it means that current break clip is not skippable. + */ + whenSkippable: number; +} + +/** + * Represents break clip (e.g. a clip of ad during ad break) + */ +export class BreakClip { + constructor(id: string); + + /** + * Url of page that sender will display; when end user clicks link on sender UI; while receiver is playing this clip. + */ + clickThroughUrl?: string; + /** + * Typically the url of the break media (playing on the receiver). + */ + contentId?: string; + /** + * The content MIME type. + */ + contentType?: string; + /** + * Optional break media url; to allow using contentId for real id. + * If contentUrl is provided; it will be used as media url; + * otherwise the contentId will be used as the media url. + */ + contentUrl?: string; + /** + * Application-specific break clip data. + */ + customData?: any; + /** + * Duration of break clip in sec. + */ + duration?: number; + /** + * The format of the HLS media segment. + */ + hlsSegmentFormat?: HlsSegmentFormat; + /** + * Unique id of break clip. + */ + id: string; + /** + * Url of content that sender will display while receiver is playing this clip. + */ + posterUrl?: string; + /** + * Title of break clip. Sender might display this on its screen; if provided. + */ + title?: string; + /** + * VAST ad request configuration. Used if contentId or contentUrl is not provided. + */ + vastAdsRequest?: VastAdsRequest; + /** + * The time in sec when this break clip becomes skippable. + * 5 means that end user can skip this break clip after 5 seconds. + * If this field is not defined; it means that current break clip is not skippable. + */ + whenSkippable?: number; +} + +/** Represents break (e.g. ad break) included in main video. */ +export class Break { + constructor(id: string, breakClipIds: string[], position: number); + /** + * List of ids of break clip that this break includes. + */ + breakClipIds: string[]; + /** + * Duration of break in sec. + */ + duration?: number; + /** + * Unique id of break. + */ + id: string; + /** + * If true; indicates this is embedded break in main stream. + */ + + isEmbedded?: boolean; + /** + * Whether break is watched. + * Sender can change color of progress bar marker corresponding to this break once + * this field changes from false to true; + * denoting that the end-user already watched this break. + */ + isWatched: boolean; + + /** + * Where the break is located inside main video. -1 represents the end of main video. + */ + position: number; } diff --git a/types/chromecast-caf-receiver/cast.framework.system.d.ts b/types/chromecast-caf-receiver/cast.framework.system.d.ts index d055e252fb..1aacb05058 100644 --- a/types/chromecast-caf-receiver/cast.framework.system.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.system.d.ts @@ -1,198 +1,196 @@ import { EventType } from "./cast.framework.events"; -export = cast.framework.system; -declare namespace cast.framework.system { - type EventType = - // Fired when the system is ready. - | "READY" - // Fired when the application is terminated - | "SHUTDOWN" - // Fired when a new sender has connected. - | "SENDER_CONNECTED" - // Fired when a sender has disconnected. - | "SENDER_DISCONNECTED" - // Fired when there is a system error. - | "ERROR" - // Fired when the system volume has changed. - | "SYSTEM_VOLUME_CHANGED" - // Fired when the visibility of the application has changed - // (for example after a HDMI Input change or when the TV is turned - // off/on and the cast device is externally powered). - // Note that this API has the same effect as the webkitvisibilitychange event raised - // by your document, we provided it as CastReceiverManager API for convenience and - // to avoid a dependency on a webkit-prefixed event. - | "VISIBILITY_CHANGED" - // Fired when the standby state of the TV has changed. - // This event is related to the visibility chnaged event, as if the TV is in standby - // the visibility will be false, the visibility is more granular - // (as it also detects that the TV has selected a different channel) - // but it is not reliably detected in all TVs, - // standby can be used in those cases as most TVs implement it. - | "STANDBY_CHANGED" - | "MAX_VIDEO_RESOLUTION_CHANGED" - | "FEEDBACK_STARTED"; +export as namespace system +export type EventType = + // Fired when the system is ready. + | "READY" + // Fired when the application is terminated + | "SHUTDOWN" + // Fired when a new sender has connected. + | "SENDER_CONNECTED" + // Fired when a sender has disconnected. + | "SENDER_DISCONNECTED" + // Fired when there is a system error. + | "ERROR" + // Fired when the system volume has changed. + | "SYSTEM_VOLUME_CHANGED" + // Fired when the visibility of the application has changed + // (for example after a HDMI Input change or when the TV is turned + // off/on and the cast device is externally powered). + // Note that this API has the same effect as the webkitvisibilitychange event raised + // by your document, we provided it as CastReceiverManager API for convenience and + // to avoid a dependency on a webkit-prefixed event. + | "VISIBILITY_CHANGED" + // Fired when the standby state of the TV has changed. + // This event is related to the visibility chnaged event, as if the TV is in standby + // the visibility will be false, the visibility is more granular + // (as it also detects that the TV has selected a different channel) + // but it is not reliably detected in all TVs, + // standby can be used in those cases as most TVs implement it. + | "STANDBY_CHANGED" + | "MAX_VIDEO_RESOLUTION_CHANGED" + | "FEEDBACK_STARTED"; - type SystemState = - | "NOT_STARTED" - | "STARTING_IN_BACKGROUND" - | "STARTING" - | "READY" - | "STOPPING_IN_BACKGROUND" - | "STOPPING"; +export type SystemState = + | "NOT_STARTED" + | "STARTING_IN_BACKGROUND" + | "STARTING" + | "READY" + | "STOPPING_IN_BACKGROUND" + | "STOPPING"; - type StandbyState = "STANDBY" | "NOT_STANDBY" | "UNKNOWN"; +export type StandbyState = "STANDBY" | "NOT_STANDBY" | "UNKNOWN"; - type DisconnectReason = "REQUESTED_BY_SENDER" | "ERROR" | "UNKNOWN"; +export type DisconnectReason = "REQUESTED_BY_SENDER" | "ERROR" | "UNKNOWN"; + +/** + * Event dispatched by @see{@link CastReceiverManager} when the visibility of the application changes (HDMI input change; TV is turned off). + */ +export class VisibilityChangedEvent { + constructor(isVisible: boolean); /** - * Event dispatched by @see{@link CastReceiverManager} when the visibility of the application changes (HDMI input change; TV is turned off). + * Whether the Cast device is the active input or not. */ - class VisibilityChangedEvent { - constructor(isVisible: boolean); + isVisible: boolean; +} - /** - * Whether the Cast device is the active input or not. - */ - isVisible: boolean; - } +/** + * Represents the system volume data. + */ +export interface SystemVolumeData { + /** + * The level (from 0.0 to 1.0) of the system volume + */ + level: number; + + /** + * Whether the system volume is muted or not. + */ + muted: boolean; +} +/** + * Event dispatched by @see{CastReceiverManager} when the system volume changes. + */ +export class SystemVolumeChangedEvent extends Event { + constructor(volume: SystemVolumeData); + + /** + * The system volume data + */ + data: SystemVolumeData; +} +/** + * Event dispatched by @see{@link CastReceiverManager} when the TV enters/leaves the standby state. + */ +export class StandbyChangedEvent { + constructor(isStandby: boolean); + + isStandby: boolean; +} +/** + * Whether the TV is in standby or not. + */ +export interface ShutdownEvent extends Event { + [key: string]: any; +} + +/** + * Event dispatched by @see{@link CastReceiverManager} when a sender is disconnected. + */ +export class SenderDisconnectedEvent extends Event { + constructor(senderId: string, userAgent: string); + /** + * The ID of the sender connected. + */ + senderId: string; /** - * Represents the system volume data. + * The user agent of the sender. */ - interface SystemVolumeData { - /** - * The level (from 0.0 to 1.0) of the system volume - */ - level: number; - - /** - * Whether the system volume is muted or not. - */ - muted: boolean; - } + userAgent: string; + /** - * Event dispatched by @see{CastReceiverManager} when the system volume changes. + * The reason the sender was disconnected. */ - class SystemVolumeChangedEvent extends Event { - constructor(volume: SystemVolumeData); - - /** - * The system volume data - */ - data: SystemVolumeData; - } + reason?: DisconnectReason; +} + +/** + * Event dispatched by @see{@link CastReceiverManager} when a sender is connected. + */ +export class SenderConnectedEvent extends Event { + constructor(senderId: string, userAgent: string); /** - * Event dispatched by @see{@link CastReceiverManager} when the TV enters/leaves the standby state. + * The ID of the sender connected. */ - class StandbyChangedEvent { - constructor(isStandby: boolean); + senderId: string; - isStandby: boolean; - } /** - * Whether the TV is in standby or not. + * The user agent of the sender. */ - interface ShutdownEvent extends Event { - [key: string]: any; - } + userAgent: string; +} +/** + * Represents the data of a connected sender device. + */ +export interface Sender { /** - * Event dispatched by @see{@link CastReceiverManager} when a sender is disconnected. + * The sender Id. */ - class SenderDisconnectedEvent extends Event { - constructor(senderId: string, userAgent: string); - /** - * The ID of the sender connected. - */ - senderId: string; - - /** - * The user agent of the sender. - */ - userAgent: string; - - /** - * The reason the sender was disconnected. - */ - reason?: DisconnectReason; - } + id: string; /** - * Event dispatched by @see{@link CastReceiverManager} when a sender is connected. + * Indicate the sender supports large messages (>64KB) */ - class SenderConnectedEvent extends Event { - constructor(senderId: string, userAgent: string); - /** - * The ID of the sender connected. - */ - senderId: string; - - /** - * The user agent of the sender. - */ - userAgent: string; - } + largeMessageSupported?: boolean; /** - * Represents the data of a connected sender device. + * The userAgent of the sender. */ - interface Sender { - /** - * The sender Id. - */ - id: string; - - /** - * Indicate the sender supports large messages (>64KB) - */ - largeMessageSupported?: boolean; - - /** - * The userAgent of the sender. - */ - userAgent?: string; - } + userAgent?: string; +} + +/** + * Event dispatched by CastReceiverManager when the system is ready. + */ +export class ReadyEvent { + constructor(applicationData: ApplicationData); /** - * Event dispatched by CastReceiverManager when the system is ready. + * The application data */ - class ReadyEvent { - constructor(applicationData: ApplicationData); + data: ApplicationData; +} - /** - * The application data - */ - data: ApplicationData; - } +/** + * Event dispatched by @see{@link CastReceiverManager} when the system needs to update the restriction on maximum video resolution. + */ +export class MaxVideoResolutionChangedEvent extends Event { + constructor(height: number); /** - * Event dispatched by @see{@link CastReceiverManager} when the system needs to update the restriction on maximum video resolution. + * Maximum video resolution requested by the system. The value of 0 means there is no restriction. */ - class MaxVideoResolutionChangedEvent extends Event { - constructor(height: number); - - /** - * Maximum video resolution requested by the system. The value of 0 means there is no restriction. - */ - height: number; - } - /** Event dispatched by @see{@link CastReceiverManager} when the systems starts to create feedback report. */ - interface FeedbackStartedEvent extends Event { - [key: string]: any; - } - /** Event dispatched by @see{@link CastReceiverContext} which contains system information. */ - class Event { - constructor(type: EventType, data?: any); - type: EventType; - data?: any; - } - - /** Represents the data of the launched application. */ - interface ApplicationData { - id(): string; - launchingSenderId(): string; - name(): string; - namespaces(): string[]; - sessionId(): number; - } + height: number; +} +/** Event dispatched by @see{@link CastReceiverManager} when the systems starts to create feedback report. */ +export interface FeedbackStartedEvent extends Event { + [key: string]: any; +} +/** Event dispatched by @see{@link CastReceiverContext} which contains system information. */ +export class Event { + constructor(type: EventType, data?: any); + type: EventType; + data?: any; +} + +/** Represents the data of the launched application. */ +export interface ApplicationData { + id(): string; + launchingSenderId(): string; + name(): string; + namespaces(): string[]; + sessionId(): number; } diff --git a/types/chromecast-caf-receiver/cast.framework.ui.d.ts b/types/chromecast-caf-receiver/cast.framework.ui.d.ts index 77d93c8082..9647fdc0ef 100644 --- a/types/chromecast-caf-receiver/cast.framework.ui.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.ui.d.ts @@ -2,196 +2,194 @@ import { PlayerDataEventType } from "./cast.framework.ui"; import { MediaMetadata } from "./cast.framework.messages"; import { PlayerDataChangedEventHandler } from "./index"; -export = cast.framework.ui; -declare namespace cast.framework.ui { - type ContentType = "video" | "audio" | "image"; +export as namespace ui +export type ContentType = "video" | "audio" | "image"; - type State = - | "launching" - | "idle" - | "loading" - | "buffering" - | "paused" - | "playing"; +export type State = + | "launching" + | "idle" + | "loading" + | "buffering" + | "paused" + | "playing"; - type PlayerDataEventType = - | "ANY_CHANGE" - | "STATE_CHANGED" - | "IS_SEEKING_CHANGED" - | "DURATION_CHANGED" - | "CURRENT_TIME_CHANGED" - | "METADATA_CHANGED" - | "TITLE_CHANGED" - | "SUBTITLE_CHANGED" - | "THUMBNAIL_URL_CHANGED" - | "NEXT_TITLE_CHANGED" - | "NEXT_SUBTITLE_CHANGED" - | "NEXT_THUMBNAIL_URL_CHANGED" - | "PRELOADING_NEXT_CHANGED" - | "CONTENT_TYPE_CHANGED" - | "IS_LIVE_CHANGED" - | "BREAK_PERCENTAGE_POSITIONS_CHANGED" - | "IS_PLAYING_BREAK_CHANGED" - | "IS_BREAK_SKIPPABLE_CHANGED" - | "WHEN_SKIPPABLE_CHANGED" - | "NUMBER_BREAK_CLIPS_CHANGED" - | "CURRENT_BREAK_CLIP_NUMBER_CHANGED" - | "DISPLAY_STATUS_CHANGED"; +export type PlayerDataEventType = + | "ANY_CHANGE" + | "STATE_CHANGED" + | "IS_SEEKING_CHANGED" + | "DURATION_CHANGED" + | "CURRENT_TIME_CHANGED" + | "METADATA_CHANGED" + | "TITLE_CHANGED" + | "SUBTITLE_CHANGED" + | "THUMBNAIL_URL_CHANGED" + | "NEXT_TITLE_CHANGED" + | "NEXT_SUBTITLE_CHANGED" + | "NEXT_THUMBNAIL_URL_CHANGED" + | "PRELOADING_NEXT_CHANGED" + | "CONTENT_TYPE_CHANGED" + | "IS_LIVE_CHANGED" + | "BREAK_PERCENTAGE_POSITIONS_CHANGED" + | "IS_PLAYING_BREAK_CHANGED" + | "IS_BREAK_SKIPPABLE_CHANGED" + | "WHEN_SKIPPABLE_CHANGED" + | "NUMBER_BREAK_CLIPS_CHANGED" + | "CURRENT_BREAK_CLIP_NUMBER_CHANGED" + | "DISPLAY_STATUS_CHANGED"; + +/** + * Player data changed event. Provides the changed field (type); and new value. + */ +export class PlayerDataChangedEvent { + constructor(type: PlayerDataEventType, field: string, value: any); /** - * Player data changed event. Provides the changed field (type); and new value. + * The field name that was changed. */ - class PlayerDataChangedEvent { - constructor(type: PlayerDataEventType, field: string, value: any); + field: string; - /** - * The field name that was changed. - */ - field: string; + type: PlayerDataEventType; - type: PlayerDataEventType; - - /** - * The new field value. - */ - value: any; - } /** - * Player data binder. Bind a player data object to the player state. - * The player data will be updated to reflect correctly the current player state without firing any change event. + * The new field value. */ - class PlayerDataBinder { - constructor(playerData: PlayerData); - - /** - * Add listener to player data changes. - */ - addEventListener: ( - type: PlayerDataEventType, - listener: PlayerDataChangedEventHandler - ) => void; - - /** - * Remove listener to player data changes. - */ - removeEventListener: ( - type: PlayerDataEventType, - listener: PlayerDataChangedEventHandler - ) => void; - } - /** - * Player data. Provide the player media and break state. - */ - interface PlayerData { - /** - * Array of breaks positions in percentage. - */ - breakPercentagePositions: number[]; - - /** - * Content Type. - */ - contentType: ContentType; - - /** - * The number of the current playing break clip in the break. - */ - currentBreakClipNumber: number; - - /** - * Media current position in seconds; or break current position if playing break. - */ - currentTime: number; - - /** - * Whether the player metadata (ie: title; currentTime) should be displayed. - * This will be true if at least one field in the metadata should be displayed. - * In some cases; displayStatus will be true; but parts of the metadata should be hidden - * (ie: the media title while media is seeking). - * In these cases; additional css can be applied to hide those elements. - * For cases where the media is audio-only; this will almost always be true. - * In cases where the media is video; this will be true when: - * (1) the video is loading; buffering; or seeking - * (2) a play request was made in the last five seconds while media is already playing; - * (3) there is a request made to show the status in the last five seconds; or - * (4) the media was paused in the last five seconds. - */ - displayStatus: boolean; - - /** - * Media duration in seconds; Or break duration if playing break. - */ - duration: number; - - /** - * Indicate break clip can be skipped. - */ - isBreakSkippable: boolean; - - /** - * Indicate if the content is a live stream. - */ - isLive: boolean; - - /** - * Indicate that the receiver is playing a break. - */ - isPlayingBreak: boolean; - - /** - * Indicate the player is seeking (can be either during playing or pausing). - */ - isSeeking: boolean; - - /** - * Media metadata. - */ - metadata: MediaMetadata; - - /** - * Next Item subtitle. - */ - nextSubtitle: string; - - /** - * Next Item thumbnail url. - */ - nextThumbnailUrl: string; - - /** - * Next Item title. - */ - nextTitle: string; - - /** - * Number of break clips in current break. - */ - numberBreakClips: number; - - /** - * Flag to show/hide next item metadata. - */ - preloadingNext: boolean; - - /** - * Current player state. - */ - state: State; - - /** - * Content thumbnail url. - */ - thumbnailUrl: string; - - /** - * Content title. - */ - title: string; - - /** - * Provide the time a break is skipable - relative to current playback time. Undefined if not skippable. - */ - whenSkippable?: number; - } + value: any; +} +/** + * Player data binder. Bind a player data object to the player state. + * The player data will be updated to reflect correctly the current player state without firing any change event. + */ +export class PlayerDataBinder { + constructor(playerData: PlayerData); + + /** + * Add listener to player data changes. + */ + addEventListener: ( + type: PlayerDataEventType, + listener: PlayerDataChangedEventHandler + ) => void; + + /** + * Remove listener to player data changes. + */ + removeEventListener: ( + type: PlayerDataEventType, + listener: PlayerDataChangedEventHandler + ) => void; +} +/** + * Player data. Provide the player media and break state. + */ +export interface PlayerData { + /** + * Array of breaks positions in percentage. + */ + breakPercentagePositions: number[]; + + /** + * Content Type. + */ + contentType: ContentType; + + /** + * The number of the current playing break clip in the break. + */ + currentBreakClipNumber: number; + + /** + * Media current position in seconds; or break current position if playing break. + */ + currentTime: number; + + /** + * Whether the player metadata (ie: title; currentTime) should be displayed. + * This will be true if at least one field in the metadata should be displayed. + * In some cases; displayStatus will be true; but parts of the metadata should be hidden + * (ie: the media title while media is seeking). + * In these cases; additional css can be applied to hide those elements. + * For cases where the media is audio-only; this will almost always be true. + * In cases where the media is video; this will be true when: + * (1) the video is loading; buffering; or seeking + * (2) a play request was made in the last five seconds while media is already playing; + * (3) there is a request made to show the status in the last five seconds; or + * (4) the media was paused in the last five seconds. + */ + displayStatus: boolean; + + /** + * Media duration in seconds; Or break duration if playing break. + */ + duration: number; + + /** + * Indicate break clip can be skipped. + */ + isBreakSkippable: boolean; + + /** + * Indicate if the content is a live stream. + */ + isLive: boolean; + + /** + * Indicate that the receiver is playing a break. + */ + isPlayingBreak: boolean; + + /** + * Indicate the player is seeking (can be either during playing or pausing). + */ + isSeeking: boolean; + + /** + * Media metadata. + */ + metadata: MediaMetadata; + + /** + * Next Item subtitle. + */ + nextSubtitle: string; + + /** + * Next Item thumbnail url. + */ + nextThumbnailUrl: string; + + /** + * Next Item title. + */ + nextTitle: string; + + /** + * Number of break clips in current break. + */ + numberBreakClips: number; + + /** + * Flag to show/hide next item metadata. + */ + preloadingNext: boolean; + + /** + * Current player state. + */ + state: State; + + /** + * Content thumbnail url. + */ + thumbnailUrl: string; + + /** + * Content title. + */ + title: string; + + /** + * Provide the time a break is skipable - relative to current playback time. Undefined if not skippable. + */ + whenSkippable?: number; } diff --git a/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts b/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts index 08ce57cf86..6660a058ad 100644 --- a/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts +++ b/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts @@ -1,52 +1,20 @@ -import { - PlayerData, - PlayerDataBinder -} from "chromecast-caf-receiver/cast.framework.ui"; -import { - ReadyEvent, - ApplicationData -} from "chromecast-caf-receiver/cast.framework.system"; -import { - RequestEvent, - Event, - BreaksEvent -} from "chromecast-caf-receiver/cast.framework.events"; -import { - QueueBase, - TextTracksManager, - QueueManager, - PlayerManager -} from "chromecast-caf-receiver/cast.framework"; -import { - BreakSeekData, - BreakClipLoadInterceptorContext, - BreakManager -} from "chromecast-caf-receiver/cast.framework.breaks"; -import { - Break, - BreakClip, - LoadRequestData, - Track, - MediaMetadata -} from "chromecast-caf-receiver/cast.framework.messages"; - -const breaksEvent = new BreaksEvent('BREAK_STARTED'); +const breaksEvent = new cast.framework.events.BreaksEvent('BREAK_STARTED'); breaksEvent.breakId = 'some-break-id'; breaksEvent.breakClipId = 'some-break-clip-id'; -const track = new Track(1, "TEXT"); -const breakClip = new BreakClip("id"); -const adBreak = new Break("id", ["id"], 1); -const rEvent = new RequestEvent("BITRATE_CHANGED", { requestId: 2 }); -const pManager = new PlayerManager(); +const track = new cast.framework.messages.Track(1, "TEXT"); +const breakClip = new cast.framework.messages.BreakClip("id"); +const adBreak = new cast.framework.messages.Break("id", ["id"], 1); +const rEvent = new cast.framework.events.RequestEvent("BITRATE_CHANGED", { requestId: 2 }); +const pManager = new cast.framework.PlayerManager(); pManager.addEventListener("STALLED", () => { }); -const ttManager = new TextTracksManager(); -const qManager = new QueueManager(); -const qBase = new QueueBase(); +const ttManager = new cast.framework.TextTracksManager(); +const qManager = new cast.framework.QueueManager(); +const qBase = new cast.framework.QueueBase(); const items = qBase.fetchItems(1, 3, 4); -const breakSeekData = new BreakSeekData(0, 100, []); -const breakClipLoadContext = new BreakClipLoadInterceptorContext(adBreak); -const breakManager: BreakManager = { +const breakSeekData = new cast.framework.breaks.BreakSeekData(0, 100, []); +const breakClipLoadContext = new cast.framework.breaks.BreakClipLoadInterceptorContext(adBreak); +const breakManager: cast.framework.breaks.BreakManager = { getBreakById: () => adBreak, getBreakClipById: () => breakClip, getBreakClips: () => [breakClip], @@ -58,7 +26,7 @@ const breakManager: BreakManager = { setVastTrackingInterceptor: () => { } }; -const lrd: LoadRequestData = { +const lrd: cast.framework.messages.LoadRequestData = { requestId: 1, activeTrackIds: [1, 2], media: { @@ -75,7 +43,7 @@ const lrd: LoadRequestData = { queueData: {} }; -const appData: ApplicationData = { +const appData: cast.framework.system.ApplicationData = { id: () => "id", launchingSenderId: () => "launch-id", name: () => "name", @@ -83,9 +51,9 @@ const appData: ApplicationData = { sessionId: () => 1 }; -const readyEvent = new ReadyEvent(appData); +const readyEvent = new cast.framework.system.ReadyEvent(appData); const data = readyEvent.data; -const pData: PlayerData = { +const pData: cast.framework.ui.PlayerData = { breakPercentagePositions: [1], contentType: "video", currentBreakClipNumber: 2, @@ -96,7 +64,7 @@ const pData: PlayerData = { isLive: true, isPlayingBreak: false, isSeeking: true, - metadata: new MediaMetadata("GENERIC"), + metadata: new cast.framework.messages.MediaMetadata("GENERIC"), nextSubtitle: "sub", nextThumbnailUrl: "url", nextTitle: "title", @@ -107,5 +75,5 @@ const pData: PlayerData = { title: "title", whenSkippable: 321 }; -const binder = new PlayerDataBinder(pData); +const binder = new cast.framework.ui.PlayerDataBinder(pData); binder.addEventListener("ANY_CHANGE", e => { }); diff --git a/types/chromecast-caf-receiver/index.d.ts b/types/chromecast-caf-receiver/index.d.ts index 73a13f53ca..c716ad89ea 100644 --- a/types/chromecast-caf-receiver/index.d.ts +++ b/types/chromecast-caf-receiver/index.d.ts @@ -11,11 +11,14 @@ /// /// +import * as framework from "./cast.framework"; import { PlayerDataChangedEvent } from './cast.framework.ui'; import { NetworkRequestInfo } from './cast.framework'; import { Event } from './cast.framework.events'; + export as namespace cast; +export { framework }; export type EventHandler = (event: Event) => void; export type PlayerDataChangedEventHandler = ( event: PlayerDataChangedEvent From c0c4189a262e2b0607736dc8d042dcc9b891bc6f Mon Sep 17 00:00:00 2001 From: Kobi Cohen Date: Mon, 3 Dec 2018 12:04:55 +0200 Subject: [PATCH 36/66] updating isMatchWithCustomizer type to accept two more arguments: object and source per lodash docs https://lodash.com/docs/4.17.11#isMatchWith [add tests] --- types/lodash/lodash-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index 4f7f229fe6..9d2547dcf4 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -4205,7 +4205,7 @@ fp.now(); // $ExpectType number // _.isMatchWith { - const testIsMatchCustiomizerFn = (value: any, other: any, indexOrKey: number|string|symbol) => true; + const testIsMatchCustiomizerFn = (value: any, other: any, indexOrKey: number|string|symbol, object: object, source: object) => true; _.isMatchWith({}, {}, testIsMatchCustiomizerFn); // $ExpectType boolean _({}).isMatchWith({}, testIsMatchCustiomizerFn); // $ExpectType boolean From 77643fb3e533e7689a0b4a742c67b48e283ec353 Mon Sep 17 00:00:00 2001 From: craig bruce Date: Mon, 3 Dec 2018 21:29:50 +1100 Subject: [PATCH 37/66] fix lint issues --- .../cast.framework.breaks.d.ts | 2 - .../cast.framework.d.ts | 124 +++++++----------- .../cast.framework.ui.d.ts | 2 - types/chromecast-caf-receiver/index.d.ts | 17 +-- 4 files changed, 57 insertions(+), 88 deletions(-) diff --git a/types/chromecast-caf-receiver/cast.framework.breaks.d.ts b/types/chromecast-caf-receiver/cast.framework.breaks.d.ts index 5ece1f15e9..bce1d6b71d 100644 --- a/types/chromecast-caf-receiver/cast.framework.breaks.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.breaks.d.ts @@ -1,6 +1,5 @@ import { Break, BreakClip } from "./cast.framework.messages"; - export as namespace breaks export class BreakSeekData { constructor(seekFrom: number, seekTo: number, breaks: Break[]); @@ -88,4 +87,3 @@ export interface BreakManager { interceptor?: (trackingUrl: string) => void ): void; } - diff --git a/types/chromecast-caf-receiver/cast.framework.d.ts b/types/chromecast-caf-receiver/cast.framework.d.ts index 6e2be61eb0..13d2e52ce0 100644 --- a/types/chromecast-caf-receiver/cast.framework.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.d.ts @@ -3,34 +3,6 @@ import * as events from "./cast.framework.events"; import * as messages from "./cast.framework.messages"; import * as system from "./cast.framework.system"; import * as ui from "./cast.framework.ui"; -import { EventType } from "./cast.framework.events"; -import { - PlayerState, - PlayStringId, - ErrorType, - ErrorReason, - IdleReason, - MessageType, - Track, - TextTrackStyle, - QueueItem, - LoadRequestData, - QueueData, - Break, - LiveSeekableRange, - MediaInformation, - ErrorData, - RequestData -} from "./cast.framework.messages"; -import { BreakManager } from "./cast.framework.breaks"; -import { EventHandler, RequestHandler, BinaryHandler } from "./index"; -import { - EventType as SystemEventType, - ApplicationData, - Sender, - StandbyState, - SystemState -} from "./cast.framework.system"; export import breaks = breaks; export import events = events; @@ -59,12 +31,12 @@ export class TextTracksManager { /** * Adds text tracks to the list. */ - addTracks(tracks: Track[]): void; + addTracks(tracks: messages.Track[]): void; /** * Creates a text track. */ - createTrack(): Track; + createTrack(): messages.Track; /** * Gets all active text ids. @@ -74,27 +46,27 @@ export class TextTracksManager { /** * Gets all active text tracks. */ - getActiveTracks(): Track[]; + getActiveTracks(): messages.Track[]; /** * Returns the current text track style. */ - getTextTracksStyle(): TextTrackStyle; + getTextTracksStyle(): messages.TextTrackStyle; /** * Gets text track by id. */ - getTrackById(id: number): Track; + getTrackById(id: number): messages.Track; /** * Returns all text tracks. */ - getTracks(): Track[]; + getTracks(): messages.Track[]; /** * Gets text tracks by language. */ - getTracksByLanguage(language: string): Track[]; + getTracksByLanguage(language: string): messages.Track[]; /** * Sets text tracks to be active by id. @@ -109,7 +81,7 @@ export class TextTracksManager { /** * Sets text track style. */ - setTextTrackStyle(style: TextTrackStyle): void; + setTextTrackStyle(style: messages.TextTrackStyle): void; } /** @@ -121,7 +93,7 @@ export class QueueManager { /** * Returns the current queue item. */ - getCurrentItem(): QueueItem; + getCurrentItem(): messages.QueueItem; /** * Returns the index of the current queue item. @@ -131,12 +103,12 @@ export class QueueManager { /** * Returns the queue items. */ - getItems(): QueueItem[]; + getItems(): messages.QueueItem[]; /** * Inserts items into the queue. */ - insertItems(items: QueueItem[], insertBefore?: number): void; + insertItems(items: messages.QueueItem[], insertBefore?: number): void; /** * Removes items from the queue. @@ -151,7 +123,7 @@ export class QueueManager { /** * Updates existing queue items by matching itemId. */ - updateItems(items: QueueItem[]): void; + updateItems(items: messages.QueueItem[]): void; } /** @@ -167,7 +139,7 @@ export class QueueBase { itemId: number, nextCount: number, prevCount: number - ): QueueItem[] | Promise; + ): messages.QueueItem[] | Promise; /** * Initializes the queue with the requestData. This is called when a new LOAD request comes in to the receiver. @@ -175,13 +147,13 @@ export class QueueBase { * in the load request data. */ initialize( - requestData: LoadRequestData - ): QueueData | Promise; + requestData: messages.LoadRequestData + ): messages.QueueData | Promise; /** * Returns next items after the reference item; often the end of the current queue; called by the receiver MediaManager. */ - nextItems(itemId?: number): QueueItem[] | Promise; + nextItems(itemId?: number): messages.QueueItem[] | Promise; /** * Sets the current item with the itemId; called by the receiver MediaManager when it changes the current playing item. @@ -192,7 +164,7 @@ export class QueueBase { * A callback for informing the following items have been inserted into the receiver queue in this session. * A cloud based implementation can optionally choose to update its queue based on the new information. */ - onItemsInserted(items: QueueItem[], insertBefore?: number): void; + onItemsInserted(items: messages.QueueItem[], insertBefore?: number): void; /** * A callback for informing the following items have been removed from the receiver queue in this session. @@ -203,12 +175,12 @@ export class QueueBase { /** * Returns previous items before the reference item; often at the beginning of the queue; called by the receiver MediaManager. */ - prevItems(itemId?: number): QueueItem[] | Promise; + prevItems(itemId?: number): messages.QueueItem[] | Promise; /** * Shuffles the queue and returns new queue items. Returns null if the operation is not supported. */ - shuffle(): QueueItem[] | Promise; + shuffle(): messages.QueueItem[] | Promise; } /** @@ -221,7 +193,7 @@ export class PlayerManager { * Adds an event listener for player event. */ addEventListener: ( - eventType: EventType | EventType[], + eventType: events.EventType | events.EventType[], eventListener: EventHandler ) => void; @@ -250,12 +222,12 @@ export class PlayerManager { /** * Obtain the breaks (Ads) manager. */ - getBreakManager(): BreakManager; + getBreakManager(): breaks.BreakManager; /** * Returns list of breaks. */ - getBreaks(): Break[]; + getBreaks(): messages.Break[]; /** * Gets current time in sec of current media. @@ -270,12 +242,12 @@ export class PlayerManager { /** * Returns live seekable range with start and end time in seconds. The values are media time based. */ - getLiveSeekableRange(): LiveSeekableRange; + getLiveSeekableRange(): messages.LiveSeekableRange; /** * Gets media information of current media. */ - getMediaInformation(): MediaInformation; + getMediaInformation(): messages.MediaInformation; /** * Returns playback configuration. @@ -290,7 +262,7 @@ export class PlayerManager { /** * Gets player state. */ - getPlayerState(): PlayerState; + getPlayerState(): messages.PlayerState; /** * Get the preferred playback rate. (Can be used on shutdown event to save latest preferred playback rate to a persistent storage; @@ -313,7 +285,7 @@ export class PlayerManager { /** * Loads media. */ - load(loadRequest: LoadRequestData): Promise; + load(loadRequest: messages.LoadRequestData): Promise; /** * Pauses currently playing media. @@ -328,7 +300,7 @@ export class PlayerManager { /** * Requests a text string to be played back locally on the receiver device. */ - playString(stringId: PlayStringId, args?: string[]): Promise; + playString(stringId: messages.PlayStringId, args?: string[]): Promise; /** * Request Google Assistant to refresh the credentials. Only works if the original credentials came from the assistant. @@ -339,7 +311,7 @@ export class PlayerManager { * Removes the event listener added for given player event. If event listener is not added; it will be ignored. */ removeEventListener( - eventType: EventType | EventType[], + eventType: events.EventType | events.EventType[], eventListener: EventHandler ): void; @@ -354,15 +326,15 @@ export class PlayerManager { sendError( senderId: string, requestId: number, - type: ErrorType, - reason?: ErrorReason, + type: messages.ErrorType, + reason?: messages.ErrorReason, customData?: any ): void; /** * Send local media request. */ - sendLocalMediaRequest(request: RequestData): void; + sendLocalMediaRequest(request: messages.RequestData): void; /** * Sends a media status message to a specific sender. @@ -381,7 +353,7 @@ export class PlayerManager { * it is only needed if they want to make the player go to IDLE in special circumstances and the default idleReason does not reflect their intended * behavior. */ - setIdleReason(idleReason: IdleReason): void; + setIdleReason(idleReason: messages.IdleReason): void; /** * Sets MediaElement to use. If Promise of MediaElement is set; media begins playback after Promise is resolved. @@ -392,7 +364,7 @@ export class PlayerManager { * Sets media information. */ setMediaInformation( - mediaInformation: MediaInformation, + mediaInformation: messages.MediaInformation, opt_broadcast?: boolean ): void; @@ -403,7 +375,7 @@ export class PlayerManager { */ setMediaPlaybackInfoHandler( handler: ( - loadRequestData: LoadRequestData, + loadRequestData: messages.LoadRequestData, playbackConfig: PlaybackConfig ) => void ): void; @@ -413,7 +385,7 @@ export class PlayerManager { * of the media status. By default the media contentId is used as the content url. */ setMediaUrlResolver( - resolver: (loadRequestData: LoadRequestData) => void + resolver: (loadRequestData: messages.LoadRequestData) => void ): void; /** @@ -424,8 +396,8 @@ export class PlayerManager { * the load interceptor will be called for preload messages. */ setMessageInterceptor( - type: MessageType, - interceptor: (requestData: RequestData) => Promise + type: messages.MessageType, + interceptor: (requestData: messages.RequestData) => Promise ): void; /** @@ -652,7 +624,7 @@ export class CastReceiverContext { * Add listener to cast system events. */ addEventListener( - type: SystemEventType | SystemEventType[], + type: system.EventType | system.EventType[], handler: EventHandler ): void; @@ -670,7 +642,7 @@ export class CastReceiverContext { /** * Provides application information once the system is ready; otherwise it will be null. */ - getApplicationData(): ApplicationData; + getApplicationData(): system.ApplicationData; /** * Provides device capabilities information once the system is ready; otherwise it will be null. @@ -686,22 +658,22 @@ export class CastReceiverContext { /** * Get a sender by sender id */ - getSender(senderId: string): Sender; + getSender(senderId: string): system.Sender; /** * Gets a list of currently-connected senders. */ - getSenders(): Sender[]; + getSenders(): system.Sender[]; /** * Reports if the cast application's HDMI input is in standby. */ - getStandbyState(): StandbyState; + getStandbyState(): system.StandbyState; /** * Provides application information about the system state. */ - getSystemState(): SystemState; + getSystemState(): system.SystemState; /** * Reports if the cast application is the HDMI active input. @@ -731,7 +703,7 @@ export class CastReceiverContext { /** * Remove listener to cast system events. */ - removeEventListener(type: EventType, handler: EventHandler): void; + removeEventListener(type: system.EventType, handler: EventHandler): void; /** * Sends a message to a specific sender. @@ -783,10 +755,10 @@ export class CastReceiverContext { export class AudioTracksManager { constructor(params: any); getActiveId(): number; - getActiveTrack(): Track; - getTrackById(id: number): Track; - getTracks(): Track[]; - getTracksByLanguage(language: string): Track[]; + getActiveTrack(): messages.Track; + getTrackById(id: number): messages.Track; + getTracks(): messages.Track[]; + getTracksByLanguage(language: string): messages.Track[]; setActiveById(id: number): void; setActiveByLanguage(language: string): void; } diff --git a/types/chromecast-caf-receiver/cast.framework.ui.d.ts b/types/chromecast-caf-receiver/cast.framework.ui.d.ts index 9647fdc0ef..cd3fb79e2a 100644 --- a/types/chromecast-caf-receiver/cast.framework.ui.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.ui.d.ts @@ -1,7 +1,5 @@ import { PlayerDataEventType } from "./cast.framework.ui"; import { MediaMetadata } from "./cast.framework.messages"; -import { PlayerDataChangedEventHandler } from "./index"; - export as namespace ui export type ContentType = "video" | "audio" | "image"; diff --git a/types/chromecast-caf-receiver/index.d.ts b/types/chromecast-caf-receiver/index.d.ts index c716ad89ea..444dba0af4 100644 --- a/types/chromecast-caf-receiver/index.d.ts +++ b/types/chromecast-caf-receiver/index.d.ts @@ -13,15 +13,16 @@ import * as framework from "./cast.framework"; import { PlayerDataChangedEvent } from './cast.framework.ui'; -import { NetworkRequestInfo } from './cast.framework'; import { Event } from './cast.framework.events'; - export as namespace cast; export { framework }; -export type EventHandler = (event: Event) => void; -export type PlayerDataChangedEventHandler = ( - event: PlayerDataChangedEvent -) => void; -export type RequestHandler = (request: NetworkRequestInfo) => void; -export type BinaryHandler = (data: Uint8Array) => Uint8Array; + +declare global { + type EventHandler = (event: Event) => void; + type PlayerDataChangedEventHandler = ( + event: PlayerDataChangedEvent + ) => void; + type RequestHandler = (request: framework.NetworkRequestInfo) => void; + type BinaryHandler = (data: Uint8Array) => Uint8Array; +} From 470e25094b33b97ea72ec2a9041e79ae509d09fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Den=C3=A8le?= Date: Mon, 3 Dec 2018 12:07:53 +0100 Subject: [PATCH 38/66] JSDoc: describe default value of page.setCacheEnabled --- types/puppeteer/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index e48e29b7ec..1e71d1da08 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -1624,7 +1624,7 @@ export interface Page extends EventEmitter, FrameBase { /** * Determines whether cache is enabled on the page. - * @param enabled Whether or not to enable cache on the page. Defaults to true. + * @param [enabled=true] Whether or not to enable cache on the page. */ setCacheEnabled(enabled?: boolean): Promise; From f21619e43090a7a086f2ae54f021a0effa3ed59c Mon Sep 17 00:00:00 2001 From: polar-lukas Date: Mon, 3 Dec 2018 15:04:41 +0100 Subject: [PATCH 39/66] make iframeResizer default export "iframeResizer" is the default export of the typed library. Hence it should also be declared such. If you try to require iframeResizer as AMD module, the function "iframeResizer" is not provided within an object but as function. Using the provided types results in an undefined propery "iframeResizer" on the "define"d object. --- types/iframe-resizer/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/iframe-resizer/index.d.ts b/types/iframe-resizer/index.d.ts index 6e67a5b592..920c80b3a7 100644 --- a/types/iframe-resizer/index.d.ts +++ b/types/iframe-resizer/index.d.ts @@ -274,4 +274,4 @@ export interface IFrameScrollData { y: number; } -export function iframeResizer(options: IFrameOptions, target: string | HTMLElement): IFrameComponent[]; +export default function iframeResizer(options: IFrameOptions, target: string | HTMLElement): IFrameComponent[]; From d661dca171cdfa9265171c3dec4880521e07972b Mon Sep 17 00:00:00 2001 From: polar-lukas Date: Mon, 3 Dec 2018 15:24:07 +0100 Subject: [PATCH 40/66] iframe-resizer: update tests forgot to update the tests... --- types/iframe-resizer/iframe-resizer-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/iframe-resizer/iframe-resizer-tests.ts b/types/iframe-resizer/iframe-resizer-tests.ts index 218a7f71cd..1efe701f9a 100644 --- a/types/iframe-resizer/iframe-resizer-tests.ts +++ b/types/iframe-resizer/iframe-resizer-tests.ts @@ -1,4 +1,4 @@ -import { IFrameComponent, IFrameOptions, iframeResizer } from "iframe-resizer"; +import iframeResizer, { IFrameComponent, IFrameOptions } from "iframe-resizer"; function testOne(): void { const iframe: HTMLIFrameElement = document.createElement('iframe'); From f76c861cc9a2aeeadf2e6373313b4b24f9549ba8 Mon Sep 17 00:00:00 2001 From: Tyler Date: Mon, 3 Dec 2018 09:23:25 -0700 Subject: [PATCH 41/66] drop children prop --- types/react-flatpickr/index.d.ts | 1 - types/react-flatpickr/react-flatpickr-tests.tsx | 13 ------------- 2 files changed, 14 deletions(-) diff --git a/types/react-flatpickr/index.d.ts b/types/react-flatpickr/index.d.ts index 5e3b12fdf8..c867527b06 100644 --- a/types/react-flatpickr/index.d.ts +++ b/types/react-flatpickr/index.d.ts @@ -20,7 +20,6 @@ export interface DateTimePickerProps { onValueUpdate?: flatpickr.Options.Hook; onDayCreate?: flatpickr.Options.Hook; value?: string | Date | number | ReadonlyArray; - children?: JSX.Element | JSX.Element[]; } export default class DatePicker extends Component {} diff --git a/types/react-flatpickr/react-flatpickr-tests.tsx b/types/react-flatpickr/react-flatpickr-tests.tsx index c51f527707..7a1c64c266 100644 --- a/types/react-flatpickr/react-flatpickr-tests.tsx +++ b/types/react-flatpickr/react-flatpickr-tests.tsx @@ -40,16 +40,3 @@ const valueDateArrayElement = ( const valueNumberArrayElement = ( ); - -const wrappedElement = ( - - - -); - -const wrappedElements = ( - - - - -); From 525506704738c79063afbf3f333d3b897690f248 Mon Sep 17 00:00:00 2001 From: Crispino Date: Mon, 3 Dec 2018 21:38:27 -0300 Subject: [PATCH 42/66] Add mongoose's `deleteModel` function type definitions --- types/mongoose/index.d.ts | 28 +++++++++++++++++++--------- types/mongoose/mongoose-tests.ts | 1 + types/mongoose/v4/index.d.ts | 10 ++++++++++ types/mongoose/v4/mongoose-tests.ts | 1 + 4 files changed, 31 insertions(+), 9 deletions(-) diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 3672b75b8f..f08b8e0b5c 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -280,6 +280,16 @@ declare module "mongoose" { collection?: string ): U; + /** + * Removes the model named `name` from this connection, if it exists. You can + * use this function to clean up any models you created in your tests to + * prevent OverwriteModelErrors. + * + * @param name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp. + * @returns this + */ + deleteModel(name: string | RegExp): Connection; + /** Returns an array of model names created on this connection. */ modelNames(): string[]; @@ -511,7 +521,7 @@ declare module "mongoose" { /** * section error/notFound.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.DocumentNotFoundError - * + * * An instance of this error class will be returned when `save()` fails * because the underlying * document was not found. The constructor takes one parameter, the @@ -524,7 +534,7 @@ declare module "mongoose" { /** * section error/cast.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.CastError - * + * * An instance of this error class will be returned when mongoose failed to * cast a value. */ @@ -544,7 +554,7 @@ declare module "mongoose" { /** * section error/validation.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ValidationError - * + * * An instance of this error class will be returned when [validation](http://mongoosejs.com/docs/validation.html) failed. */ export class ValidationError extends Error { @@ -565,7 +575,7 @@ declare module "mongoose" { /** * section error/validator.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ValidatorError - * + * * A `ValidationError` has a hash of `errors` that contain individual `ValidatorError` instances */ export class ValidatorError extends Error { @@ -585,7 +595,7 @@ declare module "mongoose" { /** * section error/version.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.VersionError - * + * * An instance of this error class will be returned when you call `save()` after * the document in the database was changed in a potentially unsafe way. See * the [`versionKey` option](http://mongoosejs.com/docs/guide.html#versionKey) for more information. @@ -600,7 +610,7 @@ declare module "mongoose" { /** * section error/parallelSave.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ParallelSaveError - * + * * An instance of this error class will be returned when you call `save()` multiple * times on the same document in parallel. See the [FAQ](http://mongoosejs.com/docs/faq.html) for more * information. @@ -612,7 +622,7 @@ declare module "mongoose" { /** * section error/overwriteModel.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.OverwriteModelError - * + * * Thrown when a model with the given name was already registered on the connection. * See [the FAQ about `OverwriteModelError`](http://mongoosejs.com/docs/faq.html#overwrite-model-error). */ @@ -623,7 +633,7 @@ declare module "mongoose" { /** * section error/missingSchema.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.MissingSchemaError - * + * * Thrown when you try to access a model that has not been registered yet */ export class MissingSchemaError extends Error { @@ -633,7 +643,7 @@ declare module "mongoose" { /** * section error/divergentArray.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.DivergentArrayError - * + * * An instance of this error will be returned if you used an array projection * and then modified the array in an unsafe way. */ diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index f713ba8538..a660ce728f 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -145,6 +145,7 @@ conn1.close(function (err) {}); conn1.close(true, function (err) {}); conn1.collection('name').$format(999); conn1.model('myModel', new mongoose.Schema({}), 'myCol').find(); +conn1.deleteModel('myModel'); conn1.models.myModel.findOne().exec(); interface IStatics { staticMethod1: (a: number) => string; diff --git a/types/mongoose/v4/index.d.ts b/types/mongoose/v4/index.d.ts index ee3cd4c045..d8a9feb085 100644 --- a/types/mongoose/v4/index.d.ts +++ b/types/mongoose/v4/index.d.ts @@ -329,6 +329,16 @@ declare module "mongoose" { collection?: string ): U; + /** + * Removes the model named `name` from this connection, if it exists. You can + * use this function to clean up any models you created in your tests to + * prevent OverwriteModelErrors. + * + * @param name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp. + * @returns this + */ + deleteModel(name: string | RegExp): Connection; + /** Returns an array of model names created on this connection. */ modelNames(): string[]; diff --git a/types/mongoose/v4/mongoose-tests.ts b/types/mongoose/v4/mongoose-tests.ts index b2d2a834fd..633d3438a8 100644 --- a/types/mongoose/v4/mongoose-tests.ts +++ b/types/mongoose/v4/mongoose-tests.ts @@ -133,6 +133,7 @@ conn1.openSet('mongodb://localhost/test', 'db', { conn1.close().catch(function (err) {}); conn1.collection('name').$format(999); conn1.model('myModel', new mongoose.Schema({}), 'myCol').find(); +conn1.deleteModel('myModel'); interface IStatics { staticMethod1: (a: number) => string; } From b2e36c1f593ba01084bdb782c51df592dbfccbd9 Mon Sep 17 00:00:00 2001 From: Jan Dolezel Date: Tue, 4 Dec 2018 09:20:06 +0100 Subject: [PATCH 43/66] Updated types --- types/react-sortable-tree/index.d.ts | 70 +++++++++++-------- .../utils/tree-data-utils.d.ts | 18 ++++- 2 files changed, 54 insertions(+), 34 deletions(-) diff --git a/types/react-sortable-tree/index.d.ts b/types/react-sortable-tree/index.d.ts index bcc6596ee6..ed47df8460 100644 --- a/types/react-sortable-tree/index.d.ts +++ b/types/react-sortable-tree/index.d.ts @@ -46,6 +46,11 @@ export interface FullTree { export interface NodeData extends TreeNode, TreePath, TreeIndex { } +export interface FlatDataItem extends TreeNode, TreePath { + lowerSiblingsCounts: number[]; + parentNode: TreeItem; +} + export interface SearchData extends NodeData { searchQuery: any; } @@ -61,6 +66,11 @@ export interface OnVisibilityToggleData extends FullTree, TreeNode { expanded: boolean; } +export interface OnDragStateChangedData { + isDragging: boolean; + draggedNode: TreeItem; +} + interface PreviousAndNextLocation { prevTreeIndex: number; prevPath: NumberOrStringArray; @@ -96,7 +106,7 @@ export interface NodeRendererProps { toggleChildrenVisibility?(data: NodeData): void; buttons?: JSX.Element[]; className?: string; - style?: { [index: string]: any }; + style?: React.CSSProperties; title?: (data: NodeData) => JSX.Element | JSX.Element; subtitle?: (data: NodeData) => JSX.Element | JSX.Element; icons?: JSX.Element[]; @@ -109,12 +119,12 @@ export interface NodeRendererProps { connectDragPreview: ConnectDragPreview; connectDragSource: ConnectDragSource; - parentNode?: { [index: string]: any }; + parentNode?: TreeItem; startDrag: any; endDrag: any; isDragging: boolean; didDrop: boolean; - draggedNode?: { [index: string]: any }; + draggedNode?: TreeItem; isOver: boolean; canDrop?: boolean; } @@ -124,7 +134,7 @@ export type PlaceholderRenderer = React.ComponentClass export interface PlaceholderRendererProps { isOver: boolean; canDrop: boolean; - draggedNode: { [index: string]: any }; + draggedNode: TreeItem; } type NumberOrStringArray = Array; @@ -147,54 +157,52 @@ export interface TreeRendererProps { connectDropTarget: ConnectDropTarget; isOver: boolean; canDrop?: boolean; - draggedNode?: { [index: string]: any }; + draggedNode?: TreeItem; // used in dndManager - getPrevRow: any; // @TODO what is this method? + getPrevRow: () => FlatDataItem | null; node: TreeItem; path: NumberOrStringArray; } -export interface ThemeProps { - style?: { [index: string]: any }; - innerStyle?: { [index: string]: any }; +interface ThemeTreeProps { + style?: React.CSSProperties + innerStyle?: React.CSSProperties reactVirtualizedListProps?: Partial; scaffoldBlockPxWidth?: number; slideRegionSize?: number; rowHeight?: ((info: Index) => number) | number; - treeNodeRenderer?: TreeRenderer; nodeContentRenderer?: NodeRenderer; placeholderRenderer?: PlaceholderRenderer; } -export interface ReactSortableTreeProps { +export interface ThemeProps extends ThemeTreeProps { + treeNodeRenderer?: TreeRenderer; +} + +export interface ReactSortableTreeProps extends ThemeTreeProps { treeData: TreeItem[]; onChange(treeData: TreeItem[]): void; - style?: { [index: string]: any }; - className?: string; - innerStyle?: { [index: string]: any }; + getNodeKey?(data: TreeNode & TreeIndex): string | number; + generateNodeProps?(data: ExtendedNodeData): { [index: string]: any }; + onMoveNode?(data: NodeData & FullTree & OnMovePreviousAndNextLocation): void; + onVisibilityToggle?(data: OnVisibilityToggleData): void; + onDragStateChanged?(data: OnDragStateChangedData): void; maxDepth?: number; + rowDirection?: 'ltr' | 'rtl'; + canDrag?: ((data: ExtendedNodeData) => boolean) | boolean; + canDrop?(data: OnDragPreviousAndNextLocation & NodeData): boolean; + canNodeHaveChildren?(node: TreeItem): boolean; + theme?: ThemeProps; searchMethod?(data: SearchData): boolean; searchQuery?: string | any; searchFocusOffset?: number; - searchFinishCallback?(matches: NodeData[]): void; - generateNodeProps?(data: ExtendedNodeData): { [index: string]: any }; - getNodeKey?(data: TreeNode & TreeIndex): string | number; - onMoveNode?(data: NodeData & FullTree & OnMovePreviousAndNextLocation): void; - onVisibilityToggle?(data: OnVisibilityToggleData): void; - canDrag?: ((data: ExtendedNodeData) => boolean) | boolean; - canDrop?(data: OnDragPreviousAndNextLocation & NodeData): boolean; - reactVirtualizedListProps?: Partial; - rowHeight?: ((info: Index) => number) | number; - slideRegionSize?: number; - scaffoldBlockPxWidth?: number; - isVirtualized?: boolean; - nodeContentRenderer?: NodeRenderer; - dndType?: string; - placeholderRenderer?: PlaceholderRenderer; - theme?: ThemeProps; - shouldCopyOnOutsideDrop?: boolean | ((data: ShouldCopyData) => boolean); onlyExpandSearchedNodes?: boolean; + searchFinishCallback?(matches: NodeData[]): void; + dndType?: string; + shouldCopyOnOutsideDrop?: boolean | ((data: ShouldCopyData) => boolean); + className?: string; + isVirtualized?: boolean; } declare const SortableTree: React.ComponentClass; diff --git a/types/react-sortable-tree/utils/tree-data-utils.d.ts b/types/react-sortable-tree/utils/tree-data-utils.d.ts index b9c7bb94a0..19b9dcf177 100644 --- a/types/react-sortable-tree/utils/tree-data-utils.d.ts +++ b/types/react-sortable-tree/utils/tree-data-utils.d.ts @@ -1,4 +1,4 @@ -import { FullTree, TreePath, TreeItem, TreeIndex, SearchData, NodeData, TreeNode } from '..'; +import { FullTree, TreePath, TreeItem, TreeIndex, SearchData, NodeData, TreeNode, FlatDataItem } from '..'; export type GetNodeKeyFunction = (data: TreeIndex & TreeNode) => string | number; export type WalkAndMapFunctionParameters = FullTree & {getNodeKey: GetNodeKeyFunction, callback: Function, ignoreCollapsed?: boolean}; @@ -13,6 +13,11 @@ export function getVisibleNodeInfoAtIndex( }): TreeNode & TreePath & {lowerSiblingsCounts: number[]} | null; export function walk(data: WalkAndMapFunctionParameters): void; export function map(data: WalkAndMapFunctionParameters): TreeItem[]; +export function toggleExpandedForAll( + data: FullTree & { + expanded?: boolean, + }, +): TreeItem[]; export function changeNodeAtPath( data: FullTree & TreePath & { newNode: Function | any, @@ -26,12 +31,18 @@ export function removeNodeAtPath( ignoreCollapsed?: boolean, }, ): TreeItem[]; +export function removeNode( + data: FullTree & TreePath & { + getNodeKey: GetNodeKeyFunction, + ignoreCollapsed?: boolean, + }, +): (FullTree & TreeNode & TreeIndex) | null; export function getNodeAtPath( data: FullTree & TreePath & { getNodeKey: GetNodeKeyFunction, ignoreCollapsed?: boolean, }, -): TreeNode & TreeIndex | null; +): (TreeNode & TreeIndex) | null; export function addNodeUnderParent( data: FullTree & { newNode: TreeItem, @@ -39,6 +50,7 @@ export function addNodeUnderParent( getNodeKey: GetNodeKeyFunction, ignoreCollapsed?: boolean, expandParent?: boolean, + addAsFirstChild?: boolean, }, ): FullTree & TreeIndex; export function insertNode( @@ -56,7 +68,7 @@ export function getFlatDataFromTree( getNodeKey: GetNodeKeyFunction, ignoreCollapsed?: boolean, }, -): Array; +): Array; export function getTreeFromFlatData( data: { flatData: FlattenedData, From eb1f29cb8d023cb5ee81b85ecee3a3211456cdea Mon Sep 17 00:00:00 2001 From: Jan Dolezel Date: Tue, 4 Dec 2018 10:24:58 +0100 Subject: [PATCH 44/66] Fixed lint --- types/react-sortable-tree/index.d.ts | 4 ++-- types/react-sortable-tree/utils/tree-data-utils.d.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/types/react-sortable-tree/index.d.ts b/types/react-sortable-tree/index.d.ts index ed47df8460..0c0cc075e2 100644 --- a/types/react-sortable-tree/index.d.ts +++ b/types/react-sortable-tree/index.d.ts @@ -166,8 +166,8 @@ export interface TreeRendererProps { } interface ThemeTreeProps { - style?: React.CSSProperties - innerStyle?: React.CSSProperties + style?: React.CSSProperties; + innerStyle?: React.CSSProperties; reactVirtualizedListProps?: Partial; scaffoldBlockPxWidth?: number; slideRegionSize?: number; diff --git a/types/react-sortable-tree/utils/tree-data-utils.d.ts b/types/react-sortable-tree/utils/tree-data-utils.d.ts index 19b9dcf177..b80e82dd81 100644 --- a/types/react-sortable-tree/utils/tree-data-utils.d.ts +++ b/types/react-sortable-tree/utils/tree-data-utils.d.ts @@ -68,7 +68,7 @@ export function getFlatDataFromTree( getNodeKey: GetNodeKeyFunction, ignoreCollapsed?: boolean, }, -): Array; +): FlatDataItem[]; export function getTreeFromFlatData( data: { flatData: FlattenedData, From 7b8c006a78eed82402b8ba6b8decb88736aa5ef6 Mon Sep 17 00:00:00 2001 From: Simon Schick Date: Tue, 4 Dec 2018 07:53:23 -0800 Subject: [PATCH 45/66] feat(puppeteer): add device descriptors --- types/puppeteer/DeviceDescriptors.d.ts | 22 ++++++++++++++++++++++ types/puppeteer/puppeteer-tests.ts | 2 ++ types/puppeteer/tsconfig.json | 1 + 3 files changed, 25 insertions(+) create mode 100644 types/puppeteer/DeviceDescriptors.d.ts diff --git a/types/puppeteer/DeviceDescriptors.d.ts b/types/puppeteer/DeviceDescriptors.d.ts new file mode 100644 index 0000000000..e457748fda --- /dev/null +++ b/types/puppeteer/DeviceDescriptors.d.ts @@ -0,0 +1,22 @@ +declare namespace devices { + interface Viewport { + width: number; + height: number; + deviceScaleFactor: number; + isMobile: boolean; + hasTouch: boolean; + isLandscape: boolean; + } + + interface Device { + name: string; + userAgent: string; + viewport: Viewport; + } +} + +declare const devices: { + [key: string]: devices.Device; +}; + +export = devices; diff --git a/types/puppeteer/puppeteer-tests.ts b/types/puppeteer/puppeteer-tests.ts index b708f1bc0c..66f8575583 100644 --- a/types/puppeteer/puppeteer-tests.ts +++ b/types/puppeteer/puppeteer-tests.ts @@ -1,5 +1,6 @@ import * as puppeteer from "puppeteer"; import { TimeoutError } from "puppeteer/Errors"; +import * as Devices from "puppeteer/DeviceDescriptors"; // Accessibility @@ -118,6 +119,7 @@ puppeteer.launch().then(async browser => { }); await page.emulateMedia("screen"); + await page.emulate(Devices['test']); await page.pdf({ path: "page.pdf" }); await page.setRequestInterception(true); diff --git a/types/puppeteer/tsconfig.json b/types/puppeteer/tsconfig.json index f253604e14..57b57e65aa 100644 --- a/types/puppeteer/tsconfig.json +++ b/types/puppeteer/tsconfig.json @@ -21,6 +21,7 @@ }, "files": [ "Errors.d.ts", + "DeviceDescriptors.d.ts", "index.d.ts", "puppeteer-tests.ts" ] From 3161ba19195b79562c5d6d4dd03421a3cd81f339 Mon Sep 17 00:00:00 2001 From: "Lukaschenko, Konstantin" Date: Tue, 4 Dec 2018 17:23:02 +0100 Subject: [PATCH 46/66] added types for three-tds-loader. --- types/three-tds-loader/index.d.ts | 200 ++++++++++++++++++ .../three-tds-loader-tests.ts | 15 ++ types/three-tds-loader/tsconfig.json | 24 +++ types/three-tds-loader/tslint.json | 1 + 4 files changed, 240 insertions(+) create mode 100644 types/three-tds-loader/index.d.ts create mode 100644 types/three-tds-loader/three-tds-loader-tests.ts create mode 100644 types/three-tds-loader/tsconfig.json create mode 100644 types/three-tds-loader/tslint.json diff --git a/types/three-tds-loader/index.d.ts b/types/three-tds-loader/index.d.ts new file mode 100644 index 0000000000..379a2de8af --- /dev/null +++ b/types/three-tds-loader/index.d.ts @@ -0,0 +1,200 @@ +// Type definitions for three-tds-loader 1.1 +// Project: https://github.com/codetheorist/three-tds-loader +// Definitions by: Konstantin Lukaschenko +// Stefan Schönsee +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as THREE from 'three'; + +export default class TDSLoader { + constructor(three: typeof THREE); + + /** + * Load 3ds file from url. + * + * @param url URL for the file. + * @param onLoad onLoad callback, receives group object3D as argument. + * @param onProgress onProgress callback. + * @param onError onError callback. + */ + load: (url: string, onLoad: (object3D: THREE.Object3D) => void, onProgress?: (progress: ProgressEvent) => void, onError?: (event: ErrorEvent) => void) => void; + + /** + * Parse arraybuffer data and load 3ds file. + * + * @param arraybuffer Arraybuffer data to be loaded. + * @param path Path for external resources. + * @return Group loaded from 3ds file. + */ + parse: (arraybuffer: ArrayBuffer, path: string) => THREE.Object3D; + + /** + * Decode file content to read 3ds data. + * + * @param arraybuffer Arraybuffer data to be loaded. + */ + readFile: (arraybuffer: ArrayBuffer, path: string) => void; + + /** + * Read mesh data chunk. + * + * @param data Dataview in use. + */ + readMeshData: (data: DataView, path: string) => void; + + /** + * Read named object chunk. + * + * @param data Dataview in use. + */ + readNamedobject: (data: DataView) => void; + + /** + * Read material data chunk and add it to the material list. + * + * @param data Dataview in use. + */ + readMaterialEntry: (data: DataView, path: string) => void; + + /** + * Read mesh data chunk. + * + * @param data Dataview in use. + */ + readMesh: (data: DataView) => void; + + /** + * Read face array data chunk. + * + * @param data Dataview in use. + * @param mesh Mesh to be filled with the data read. + */ + readFaceArray: (data: DataView, mesh: THREE.Mesh) => void; + + /** + * Read texture map data chunk. + * + * @param data Dataview in use. + * @return Texture read from this data chunk. + */ + readMap: (data: DataView, path: string) => THREE.Texture; + + /** + * Read material group data chunk. + * + * @param data Dataview in use. + * @return object with name and index of the object. + */ + readMaterialGroup: (data: DataView) => object; + + /** + * Read a color value. + * + * @param data Dataview. + * @return Color value read.. + */ + readColor: (data: DataView) => THREE.Color; + + /** + * Read next chunk of data. + * + * @param data Dataview. + * @return Chunk of data read. + */ + readChunk: (data: DataView) => object; + + /** + * Set position to the end of the current chunk of data. + * + * @param chunk Data chunk. + */ + endChunk: (chunk: object) => void; + + /** + * Move to the next data chunk. + * + * @param data Dataview. + * @param chunk Data chunk. + */ + nextChunk: (data: DataView, chunk: object) => number; + + /** + * Reset dataview position. + */ + resetPosition: () => void; + + /** + * Read byte value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readByte: (data: DataView) => number; + + /** + * Read 32 bit float value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readFloat: (data: DataView) => number; + + /** + * Read 32 bit signed integer value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readInt: (data: DataView) => number; + + /** + * Read 16 bit signed integer value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readShort: (data: DataView) => number; + + /** + * Read 64 bit unsigned integer value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readDWord: (data: DataView) => number; + + /** + * Read 32 bit unsigned integer value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readWord: (data: DataView) => number; + + /** + * Read string value. + * + * @param data Dataview to read data from. + * @param maxLength Max size of the string to be read. + * @return Data read from the dataview. + */ + readString: (data: DataView, maxLength: number) => string; + + /** + * Set resource path used to determine the file path to attached resources. + * + * @param path Path to resources. + * @return Self for chaining. + */ + setPath: (path: string) => TDSLoader; + + /** + * Print debug message to the console. + * + * Is controlled by a flag to show or hide debug messages. + * + * @param message Debug message to print to the console. + */ + debugMessage: (message: string) => void; +} diff --git a/types/three-tds-loader/three-tds-loader-tests.ts b/types/three-tds-loader/three-tds-loader-tests.ts new file mode 100644 index 0000000000..f61eeb92e3 --- /dev/null +++ b/types/three-tds-loader/three-tds-loader-tests.ts @@ -0,0 +1,15 @@ +import * as THREE from 'three'; +import TDSLoader from 'three-tds-loader'; + +const loader = new TDSLoader(THREE); + +const onSuccess = (object3D: THREE.Object3D) => {}; +const onProgress = (progress: ProgressEvent) => {}; +const onError = (event: ErrorEvent) => {}; + +loader.load( + 'folder/file.3ds', + onSuccess, + onProgress, + onError +); diff --git a/types/three-tds-loader/tsconfig.json b/types/three-tds-loader/tsconfig.json new file mode 100644 index 0000000000..cab037513c --- /dev/null +++ b/types/three-tds-loader/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "three-tds-loader-tests.ts" + ] +} diff --git a/types/three-tds-loader/tslint.json b/types/three-tds-loader/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/three-tds-loader/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From bb24e03c2562980f80ff243656740865ce28b773 Mon Sep 17 00:00:00 2001 From: Vincent Pizzo Date: Tue, 4 Dec 2018 08:39:02 -0800 Subject: [PATCH 47/66] Message should accept string or function --- types/yup/index.d.ts | 58 ++++++++++++++++++++++-------------------- types/yup/yup-tests.ts | 46 +++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 28 deletions(-) diff --git a/types/yup/index.d.ts b/types/yup/index.d.ts index 821b0e3526..5d8713db68 100644 --- a/types/yup/index.d.ts +++ b/types/yup/index.d.ts @@ -5,6 +5,7 @@ // Moreton Bay Regional Council , // Sindre Seppola // Yash Kulshrestha +// Vincent Pizzo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -47,6 +48,9 @@ export type AnySchemaConstructor = | ArraySchemaConstructor | ObjectSchemaConstructor; +export type TestOptionsMessage = string + | ((params: object & Partial) => string); + export interface Schema { clone(): this; label(label: string): this; @@ -67,11 +71,11 @@ export interface Schema { withMutation(fn: (current: this) => void): void; default(value?: any): this; nullable(isNullable: boolean): this; - required(message?: string): this; + required(message?: TestOptionsMessage): this; notRequired(): this; - typeError(message?: string): this; - oneOf(arrayOfValues: any[], message?: string): this; - notOneOf(arrayOfValues: any[], message?: string): this; + typeError(message?: TestOptionsMessage): this; + oneOf(arrayOfValues: any[], message?: TestOptionsMessage): this; + notOneOf(arrayOfValues: any[], message?: TestOptionsMessage): this; when(keys: string | any[], builder: WhenOptions): this; test( name: string, @@ -102,20 +106,20 @@ export interface StringSchemaConstructor { } export interface StringSchema extends Schema { - min(limit: number | Ref, message?: string): StringSchema; - max(limit: number | Ref, message?: string): StringSchema; + min(limit: number | Ref, message?: TestOptionsMessage): StringSchema; + max(limit: number | Ref, message?: TestOptionsMessage): StringSchema; matches( regex: RegExp, messageOrOptions?: - | string - | { message?: string; excludeEmptyString?: boolean } + | TestOptionsMessage + | { message?: TestOptionsMessage; excludeEmptyString?: boolean } ): StringSchema; - email(message?: string): StringSchema; - url(message?: string): StringSchema; + email(message?: TestOptionsMessage): StringSchema; + url(message?: TestOptionsMessage): StringSchema; ensure(): StringSchema; - trim(message?: string): StringSchema; - lowercase(message?: string): StringSchema; - uppercase(message?: string): StringSchema; + trim(message?: TestOptionsMessage): StringSchema; + lowercase(message?: TestOptionsMessage): StringSchema; + uppercase(message?: TestOptionsMessage): StringSchema; } export interface NumberSchemaConstructor { @@ -124,13 +128,13 @@ export interface NumberSchemaConstructor { } export interface NumberSchema extends Schema { - min(limit: number | Ref, message?: string): NumberSchema; - max(limit: number | Ref, message?: string): NumberSchema; - lessThan(limit: number | Ref, message?: string): NumberSchema; - moreThan(limit: number | Ref, message?: string): NumberSchema; - positive(message?: string): NumberSchema; - negative(message?: string): NumberSchema; - integer(message?: string): NumberSchema; + min(limit: number | Ref, message?: TestOptionsMessage): NumberSchema; + max(limit: number | Ref, message?: TestOptionsMessage): NumberSchema; + lessThan(limit: number | Ref, message?: TestOptionsMessage): NumberSchema; + moreThan(limit: number | Ref, message?: TestOptionsMessage): NumberSchema; + positive(message?: TestOptionsMessage): NumberSchema; + negative(message?: TestOptionsMessage): NumberSchema; + integer(message?: TestOptionsMessage): NumberSchema; truncate(): NumberSchema; round(type: "floor" | "ceil" | "trunc" | "round"): NumberSchema; } @@ -149,8 +153,8 @@ export interface DateSchemaConstructor { } export interface DateSchema extends Schema { - min(limit: Date | string | Ref, message?: string): DateSchema; - max(limit: Date | string | Ref, message?: string): DateSchema; + min(limit: Date | string | Ref, message?: TestOptionsMessage): DateSchema; + max(limit: Date | string | Ref, message?: TestOptionsMessage): DateSchema; } export interface ArraySchemaConstructor { @@ -160,8 +164,8 @@ export interface ArraySchemaConstructor { export interface ArraySchema extends Schema { of(type: Schema): ArraySchema; - min(limit: number | Ref, message?: string): ArraySchema; - max(limit: number | Ref, message?: string): ArraySchema; + min(limit: number | Ref, message?: TestOptionsMessage): ArraySchema; + max(limit: number | Ref, message?: TestOptionsMessage): ArraySchema; ensure(): ArraySchema; compact(rejector?: (value: any) => boolean): ArraySchema; } @@ -177,7 +181,7 @@ export interface ObjectSchema extends Schema { noSortEdges?: Array<[string, string]> ): ObjectSchema; from(fromKey: string, toKey: string, alias?: boolean): ObjectSchema; - noUnknown(onlyKnownKeys?: boolean, message?: string): ObjectSchema; + noUnknown(onlyKnownKeys?: boolean, message?: TestOptionsMessage): ObjectSchema; transformKeys(callback: (key: any) => any): void; camelCase(): ObjectSchema; constantCase(): ObjectSchema; @@ -256,9 +260,7 @@ export interface TestOptions { /** * The validation error message */ - message?: - | string - | ((params: object & Partial) => string); + message?: TestOptionsMessage; /** * Values passed to message for interpolation diff --git a/types/yup/yup-tests.ts b/types/yup/yup-tests.ts index efef78d319..4a6ecae98f 100644 --- a/types/yup/yup-tests.ts +++ b/types/yup/yup-tests.ts @@ -126,10 +126,15 @@ mixed.default(() => ({ number: 5 })); mixed.default(); mixed.nullable(true); mixed.required(); +mixed.required('Foo'); +mixed.required(() => 'Foo'); mixed.notRequired(); // $ExpectType MixedSchema mixed.typeError("type error"); +mixed.typeError(() => "type error"); mixed.oneOf(["hello", "world"], "message"); +mixed.oneOf(["hello", "world"], () => "message"); mixed.notOneOf(["hello", "world"], "message"); +mixed.notOneOf(["hello", "world"], () => "message"); mixed.when("isBig", { is: value => true, then: yup.number().min(5), @@ -255,26 +260,56 @@ yup.object() const strSchema = yup.string(); // $ExpectType StringSchema strSchema.isValid("hello"); // => true strSchema.required(); +strSchema.required("req"); +strSchema.required(() => "req"); strSchema.min(5, "message"); +strSchema.min(5, () => "message"); strSchema.max(5, "message"); +strSchema.max(5, () => "message"); strSchema.matches(/(hi|bye)/); +strSchema.matches(/(hi|bye)/, "invalid"); +strSchema.matches(/(hi|bye)/, () => "invalid"); strSchema.email(); +strSchema.email("invalid"); +strSchema.email(() => "invalid"); strSchema.url(); +strSchema.url("bad url"); +strSchema.url(() => "bad url"); strSchema.ensure(); strSchema.trim(); +strSchema.trim("trimmed"); +strSchema.trim(() => "trimmed"); strSchema.lowercase(); +strSchema.lowercase("lower"); +strSchema.lowercase(() => "lower"); strSchema.uppercase(); +strSchema.uppercase("upper"); +strSchema.uppercase(() => "upper"); // Number schema const numSchema = yup.number(); // $ExpectType NumberSchema numSchema.isValid(10); // => true +numSchema.min(5); numSchema.min(5, "message"); +numSchema.min(5, () => "message"); +numSchema.max(5); numSchema.max(5, "message"); +numSchema.max(5, () => "message"); numSchema.positive(); +numSchema.positive("pos"); +numSchema.positive(() => "pos"); numSchema.negative(); +numSchema.negative("neg"); +numSchema.negative(() => "neg"); numSchema.lessThan(5); +numSchema.lessThan(5, "lt"); +numSchema.lessThan(5, () => "lt"); numSchema.moreThan(5); +numSchema.moreThan(5, "mt"); +numSchema.moreThan(5, () => "mt"); numSchema.integer(); +numSchema.integer("int"); +numSchema.integer(() => "int"); numSchema.truncate(); numSchema.round("floor"); numSchema @@ -293,17 +328,27 @@ dateSchema.min(new Date()); dateSchema.min("2017-11-12"); dateSchema.min(new Date(), "message"); dateSchema.min("2017-11-12", "message"); +dateSchema.min("2017-11-12", () => "message"); dateSchema.max(new Date()); dateSchema.max("2017-11-12"); dateSchema.max(new Date(), "message"); dateSchema.max("2017-11-12", "message"); +dateSchema.max("2017-11-12", () => "message"); // Array Schema const arrSchema = yup.array().of(yup.number().min(2)); arrSchema.isValid([2, 3]); // => true arrSchema.isValid([1, -24]); // => false arrSchema.required(); +arrSchema.required("req"); +arrSchema.required(() => "req"); arrSchema.ensure(); +arrSchema.max(5); +arrSchema.max(5, "max"); +arrSchema.max(5, () => "max"); +arrSchema.min(5); +arrSchema.min(5, "min"); +arrSchema.min(5, () => "min"); arrSchema.compact(value => value === null); yup.array(); // $ExpectType ArraySchema<{}> @@ -334,6 +379,7 @@ objSchema.from("prop", "myProp", true); objSchema.noUnknown(); objSchema.noUnknown(true); objSchema.noUnknown(true, "message"); +objSchema.noUnknown(true, () => "message"); objSchema.transformKeys(key => key.toUpperCase()); objSchema.camelCase(); objSchema.constantCase(); From b9ca29afba5459e1826c8427c961c724fea98c3a Mon Sep 17 00:00:00 2001 From: Mike Wickett Date: Tue, 4 Dec 2018 11:51:04 -0500 Subject: [PATCH 48/66] Add inlineLexer function to marked types --- types/marked/index.d.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/types/marked/index.d.ts b/types/marked/index.d.ts index d558348db9..7eddfb4919 100644 --- a/types/marked/index.d.ts +++ b/types/marked/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for Marked 0.4 +// Type definitions for Marked 0.5 // Project: https://github.com/markedjs/marked // Definitions by: William Orr // BendingBender // CrossR +// Mike Wickett // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace marked; @@ -34,6 +35,15 @@ declare namespace marked { */ function lexer(src: string, options?: MarkedOptions): TokensList; + /** + * @param src String of markdown source to be compiled + * @param links Array of links + * @param options Hash of options + * @return String of compiled HTML + */ + + function inlineLexer(src: string, links: string[], options?: MarkedOptions): string; + /** * Compiles markdown to HTML. * From b7a61e55c8406749b2ef9ef32ed612b9c0dd96b6 Mon Sep 17 00:00:00 2001 From: Konstantin Lukaschenko Date: Tue, 4 Dec 2018 22:30:53 +0100 Subject: [PATCH 49/66] enhance module definition. --- types/three-tds-loader/index.d.ts | 4 +++- types/three-tds-loader/three-tds-loader-tests.ts | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/types/three-tds-loader/index.d.ts b/types/three-tds-loader/index.d.ts index 379a2de8af..33e679a377 100644 --- a/types/three-tds-loader/index.d.ts +++ b/types/three-tds-loader/index.d.ts @@ -7,7 +7,9 @@ import * as THREE from 'three'; -export default class TDSLoader { +export = TDSLoader; + +declare class TDSLoader { constructor(three: typeof THREE); /** diff --git a/types/three-tds-loader/three-tds-loader-tests.ts b/types/three-tds-loader/three-tds-loader-tests.ts index f61eeb92e3..a4e9d61797 100644 --- a/types/three-tds-loader/three-tds-loader-tests.ts +++ b/types/three-tds-loader/three-tds-loader-tests.ts @@ -1,5 +1,5 @@ import * as THREE from 'three'; -import TDSLoader from 'three-tds-loader'; +import TDSLoader = require('three-tds-loader'); const loader = new TDSLoader(THREE); From 53ddbc865809cedd7e91bf173df78fe44735a7f2 Mon Sep 17 00:00:00 2001 From: Avi Vahl Date: Wed, 5 Dec 2018 00:47:46 +0200 Subject: [PATCH 50/66] puppeteer: allow disabling default viewport null disables the default viewport (verified locally). comment already mentions that, but it wasn't accepted in the type. --- types/puppeteer/index.d.ts | 2 +- types/puppeteer/puppeteer-tests.ts | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index ff05cc4de0..2051603f69 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -2044,7 +2044,7 @@ export interface BrowserOptions { * @default false */ isLandscape?: boolean; - }; + } | null; /** * Slows down Puppeteer operations by the specified amount of milliseconds. * Useful so that you can see what is going on. diff --git a/types/puppeteer/puppeteer-tests.ts b/types/puppeteer/puppeteer-tests.ts index b708f1bc0c..1f587d470e 100644 --- a/types/puppeteer/puppeteer-tests.ts +++ b/types/puppeteer/puppeteer-tests.ts @@ -200,6 +200,13 @@ puppeteer.launch().then(async browser => { browser.close(); })(); +// Launching with default viewport disabled +(async () => { + await puppeteer.launch({ + defaultViewport: null + }); +})(); + // Test v0.12 features (async () => { const browser = await puppeteer.launch({ From 89f8981d7941ccdc5ba0680ff05c2068e112abfe Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Tue, 4 Dec 2018 23:52:20 +0100 Subject: [PATCH 51/66] Add types for interpret --- types/interpret/index.d.ts | 26 ++++++++++++++++ types/interpret/interpret-tests.ts | 50 ++++++++++++++++++++++++++++++ types/interpret/tsconfig.json | 23 ++++++++++++++ types/interpret/tslint.json | 1 + 4 files changed, 100 insertions(+) create mode 100644 types/interpret/index.d.ts create mode 100644 types/interpret/interpret-tests.ts create mode 100644 types/interpret/tsconfig.json create mode 100644 types/interpret/tslint.json diff --git a/types/interpret/index.d.ts b/types/interpret/index.d.ts new file mode 100644 index 0000000000..de51c842f8 --- /dev/null +++ b/types/interpret/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for interpret 1.1 +// Project: https://github.com/tkellen/node-interpret +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export interface Hook { + (m: { extensions: string } | NodeModule): any; + install(m?: { extension: string; [key: string]: any }): void; +} + +export type RegisterFn = (hook: Hook) => void; + +export interface ExtensionDescriptor { + module: string; + register: RegisterFn; +} + +export type Extension = string | ExtensionDescriptor | Array; +export interface Extensions { + [extension: string]: Extension | null; +} + +export const extensions: Extensions; +export const jsVariants: Extensions; diff --git a/types/interpret/interpret-tests.ts b/types/interpret/interpret-tests.ts new file mode 100644 index 0000000000..2ac4cc0081 --- /dev/null +++ b/types/interpret/interpret-tests.ts @@ -0,0 +1,50 @@ +import { extensions, jsVariants, Extensions } from 'interpret'; + +// $ExpectType Extensions +extensions; +// $ExpectType Extensions +jsVariants; + +const myExts: Extensions = { + '.babel.js': [ + { + module: 'babel-register', + register(hook) { + hook({ extensions: '.js' }); + }, + }, + ], + '.co': 'coco', + '.coffee': ['coffeescript/register', 'coffee-script/register', 'coffeescript', 'coffee-script'], + '.esm.js': { + module: 'esm', + register(hook) { + const esmLoader = hook(module); + require.extensions['.js'] = esmLoader('module')._extensions['.js']; + }, + }, + '.js': null, + '.jsx': [ + { + module: 'node-jsx', + register(hook) { + hook.install({ extension: '.jsx', harmony: true }); + }, + }, + ], + '.toml': { + module: 'toml-require', + register(hook) { + hook.install(); + }, + }, + '.ts': [ + 'typescript-require', + { + module: '@babel/register', + register(hook) { + hook({ extensions: '.ts' }); + }, + }, + ], +}; diff --git a/types/interpret/tsconfig.json b/types/interpret/tsconfig.json new file mode 100644 index 0000000000..970cf59fd9 --- /dev/null +++ b/types/interpret/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "interpret-tests.ts" + ] +} diff --git a/types/interpret/tslint.json b/types/interpret/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/interpret/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From fe58906ce37ef41075bbf68e3209962d6a1dc3c1 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Wed, 5 Dec 2018 01:17:22 +0100 Subject: [PATCH 52/66] Add types for flagged-respawn --- .../flagged-respawn/flagged-respawn-tests.ts | 14 +++++++++++ types/flagged-respawn/index.d.ts | 24 +++++++++++++++++++ types/flagged-respawn/tsconfig.json | 23 ++++++++++++++++++ types/flagged-respawn/tslint.json | 1 + 4 files changed, 62 insertions(+) create mode 100644 types/flagged-respawn/flagged-respawn-tests.ts create mode 100644 types/flagged-respawn/index.d.ts create mode 100644 types/flagged-respawn/tsconfig.json create mode 100644 types/flagged-respawn/tslint.json diff --git a/types/flagged-respawn/flagged-respawn-tests.ts b/types/flagged-respawn/flagged-respawn-tests.ts new file mode 100644 index 0000000000..12f949f9fb --- /dev/null +++ b/types/flagged-respawn/flagged-respawn-tests.ts @@ -0,0 +1,14 @@ +import flaggedRespawn = require('flagged-respawn'); + +const flags = ['--flag']; + +flaggedRespawn(flags, process.argv, (ready, child, argv) => { + // $ExpectType boolean + ready; + // $ExpectType Process + child; + // $ExpectType string[] + argv; +}); +flaggedRespawn(flags, process.argv, '--flag', () => {}); +flaggedRespawn(flags, process.argv, ['--flag'], () => {}); diff --git a/types/flagged-respawn/index.d.ts b/types/flagged-respawn/index.d.ts new file mode 100644 index 0000000000..eea62b2e8c --- /dev/null +++ b/types/flagged-respawn/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for flagged-respawn 1.0 +// Project: https://github.com/js-cli/js-flagged-respawn +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export = flaggedRespawn; + +declare function flaggedRespawn( + flags: string[], + argv: string[], + callback: flaggedRespawn.Callback +): void; +declare function flaggedRespawn( + flags: string[], + argv: string[], + forcedFlags: string | string[], + callback: flaggedRespawn.Callback +): void; + +declare namespace flaggedRespawn { + type Callback = (ready: boolean, proc: NodeJS.Process, argv: string[]) => void; +} diff --git a/types/flagged-respawn/tsconfig.json b/types/flagged-respawn/tsconfig.json new file mode 100644 index 0000000000..91fce74324 --- /dev/null +++ b/types/flagged-respawn/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "flagged-respawn-tests.ts" + ] +} diff --git a/types/flagged-respawn/tslint.json b/types/flagged-respawn/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/flagged-respawn/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 57130b66948fb84ede0ee3f92dac60e45afd0c29 Mon Sep 17 00:00:00 2001 From: Craig Bruce Date: Wed, 5 Dec 2018 11:25:09 +1100 Subject: [PATCH 53/66] Add test to help differentiate between different import techniques --- .../chromecast-caf-receiver-tests.ts | 37 +++++++++++++------ 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts b/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts index 6660a058ad..8d12320e0a 100644 --- a/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts +++ b/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts @@ -1,29 +1,44 @@ -const breaksEvent = new cast.framework.events.BreaksEvent('BREAK_STARTED'); -breaksEvent.breakId = 'some-break-id'; -breaksEvent.breakClipId = 'some-break-clip-id'; +import { MediaMetadata } from "chromecast-caf-receiver/cast.framework.messages"; + +// The following test showcases how you can import individual types directly from the namespace: + +const mediaMetadata = new MediaMetadata(); +mediaMetadata.metadataType = "TV_SHOW"; + +// The following tests showcase how you can globally access 'cast' types using +// the nested namespace style. This is the preferred method as it +// conforms exactly to the CAF documentation. + +const breaksEvent = new cast.framework.events.BreaksEvent("BREAK_STARTED"); +breaksEvent.breakId = "some-break-id"; +breaksEvent.breakClipId = "some-break-clip-id"; const track = new cast.framework.messages.Track(1, "TEXT"); const breakClip = new cast.framework.messages.BreakClip("id"); const adBreak = new cast.framework.messages.Break("id", ["id"], 1); -const rEvent = new cast.framework.events.RequestEvent("BITRATE_CHANGED", { requestId: 2 }); +const rEvent = new cast.framework.events.RequestEvent("BITRATE_CHANGED", { + requestId: 2 +}); const pManager = new cast.framework.PlayerManager(); -pManager.addEventListener("STALLED", () => { }); +pManager.addEventListener("STALLED", () => {}); const ttManager = new cast.framework.TextTracksManager(); const qManager = new cast.framework.QueueManager(); const qBase = new cast.framework.QueueBase(); const items = qBase.fetchItems(1, 3, 4); const breakSeekData = new cast.framework.breaks.BreakSeekData(0, 100, []); -const breakClipLoadContext = new cast.framework.breaks.BreakClipLoadInterceptorContext(adBreak); +const breakClipLoadContext = new cast.framework.breaks.BreakClipLoadInterceptorContext( + adBreak +); const breakManager: cast.framework.breaks.BreakManager = { getBreakById: () => adBreak, getBreakClipById: () => breakClip, getBreakClips: () => [breakClip], getBreaks: () => [adBreak], getPlayWatchedBreak: () => true, - setBreakClipLoadInterceptor: () => { }, - setBreakSeekInterceptor: () => { }, - setPlayWatchedBreak: () => { }, - setVastTrackingInterceptor: () => { } + setBreakClipLoadInterceptor: () => {}, + setBreakSeekInterceptor: () => {}, + setPlayWatchedBreak: () => {}, + setVastTrackingInterceptor: () => {} }; const lrd: cast.framework.messages.LoadRequestData = { @@ -76,4 +91,4 @@ const pData: cast.framework.ui.PlayerData = { whenSkippable: 321 }; const binder = new cast.framework.ui.PlayerDataBinder(pData); -binder.addEventListener("ANY_CHANGE", e => { }); +binder.addEventListener("ANY_CHANGE", e => {}); From 6a11af78c9f8d8f78c9ae611464f305b11139e62 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Wed, 5 Dec 2018 01:30:16 +0100 Subject: [PATCH 54/66] Add types for v8flags --- types/v8flags/index.d.ts | 13 +++++++++++++ types/v8flags/tsconfig.json | 23 +++++++++++++++++++++++ types/v8flags/tslint.json | 1 + types/v8flags/v8flags-tests.ts | 6 ++++++ 4 files changed, 43 insertions(+) create mode 100644 types/v8flags/index.d.ts create mode 100644 types/v8flags/tsconfig.json create mode 100644 types/v8flags/tslint.json create mode 100644 types/v8flags/v8flags-tests.ts diff --git a/types/v8flags/index.d.ts b/types/v8flags/index.d.ts new file mode 100644 index 0000000000..409b51d60b --- /dev/null +++ b/types/v8flags/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for v8flags 3.1 +// Project: https://github.com/tkellen/node-v8flags +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = v8flags; + +declare function v8flags(cb: (err: any, flags: string[]) => void): void; + +declare namespace v8flags { + const configfile: string; + const configPath: string; +} diff --git a/types/v8flags/tsconfig.json b/types/v8flags/tsconfig.json new file mode 100644 index 0000000000..e0673d15d0 --- /dev/null +++ b/types/v8flags/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "v8flags-tests.ts" + ] +} diff --git a/types/v8flags/tslint.json b/types/v8flags/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/v8flags/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/v8flags/v8flags-tests.ts b/types/v8flags/v8flags-tests.ts new file mode 100644 index 0000000000..cc95ac734d --- /dev/null +++ b/types/v8flags/v8flags-tests.ts @@ -0,0 +1,6 @@ +import v8flags = require('v8flags'); + +v8flags((err, results) => { + // $ExpectType string[] + results; +}); From 5b92e6f79cd8c387921efa99dda8aa6b923f877d Mon Sep 17 00:00:00 2001 From: Craig Bruce Date: Wed, 5 Dec 2018 11:32:33 +1100 Subject: [PATCH 55/66] Had do disable tslint rules for global import in tests as it defeats the object --- .../chromecast-caf-receiver-tests.ts | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts b/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts index 8d12320e0a..0df790c5f7 100644 --- a/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts +++ b/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts @@ -2,33 +2,45 @@ import { MediaMetadata } from "chromecast-caf-receiver/cast.framework.messages"; // The following test showcases how you can import individual types directly from the namespace: -const mediaMetadata = new MediaMetadata(); +const mediaMetadata = new MediaMetadata("GENERIC"); mediaMetadata.metadataType = "TV_SHOW"; // The following tests showcase how you can globally access 'cast' types using // the nested namespace style. This is the preferred method as it // conforms exactly to the CAF documentation. +// tslint:disable-next-line const breaksEvent = new cast.framework.events.BreaksEvent("BREAK_STARTED"); breaksEvent.breakId = "some-break-id"; breaksEvent.breakClipId = "some-break-clip-id"; +// tslint:disable-next-line const track = new cast.framework.messages.Track(1, "TEXT"); +// tslint:disable-next-line const breakClip = new cast.framework.messages.BreakClip("id"); +// tslint:disable-next-line const adBreak = new cast.framework.messages.Break("id", ["id"], 1); +// tslint:disable-next-line const rEvent = new cast.framework.events.RequestEvent("BITRATE_CHANGED", { requestId: 2 }); +// tslint:disable-next-line const pManager = new cast.framework.PlayerManager(); pManager.addEventListener("STALLED", () => {}); +// tslint:disable-next-line const ttManager = new cast.framework.TextTracksManager(); +// tslint:disable-next-line const qManager = new cast.framework.QueueManager(); +// tslint:disable-next-line const qBase = new cast.framework.QueueBase(); const items = qBase.fetchItems(1, 3, 4); +// tslint:disable-next-line const breakSeekData = new cast.framework.breaks.BreakSeekData(0, 100, []); +// tslint:disable-next-line const breakClipLoadContext = new cast.framework.breaks.BreakClipLoadInterceptorContext( adBreak ); +// tslint:disable-next-line const breakManager: cast.framework.breaks.BreakManager = { getBreakById: () => adBreak, getBreakClipById: () => breakClip, @@ -41,6 +53,7 @@ const breakManager: cast.framework.breaks.BreakManager = { setVastTrackingInterceptor: () => {} }; +// tslint:disable-next-line const lrd: cast.framework.messages.LoadRequestData = { requestId: 1, activeTrackIds: [1, 2], @@ -58,6 +71,7 @@ const lrd: cast.framework.messages.LoadRequestData = { queueData: {} }; +// tslint:disable-next-line const appData: cast.framework.system.ApplicationData = { id: () => "id", launchingSenderId: () => "launch-id", @@ -66,8 +80,10 @@ const appData: cast.framework.system.ApplicationData = { sessionId: () => 1 }; +// tslint:disable-next-line const readyEvent = new cast.framework.system.ReadyEvent(appData); const data = readyEvent.data; +// tslint:disable-next-line const pData: cast.framework.ui.PlayerData = { breakPercentagePositions: [1], contentType: "video", @@ -79,6 +95,7 @@ const pData: cast.framework.ui.PlayerData = { isLive: true, isPlayingBreak: false, isSeeking: true, + // tslint:disable-next-line metadata: new cast.framework.messages.MediaMetadata("GENERIC"), nextSubtitle: "sub", nextThumbnailUrl: "url", @@ -90,5 +107,6 @@ const pData: cast.framework.ui.PlayerData = { title: "title", whenSkippable: 321 }; +// tslint:disable-next-line const binder = new cast.framework.ui.PlayerDataBinder(pData); binder.addEventListener("ANY_CHANGE", e => {}); From 57b78900c18241543bc0657972ae935769438015 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Wed, 5 Dec 2018 02:08:09 +0100 Subject: [PATCH 56/66] Add types for fined --- types/fined/fined-tests.ts | 18 ++++++++++++++++++ types/fined/index.d.ts | 23 +++++++++++++++++++++++ types/fined/tsconfig.json | 23 +++++++++++++++++++++++ types/fined/tslint.json | 1 + 4 files changed, 65 insertions(+) create mode 100644 types/fined/fined-tests.ts create mode 100644 types/fined/index.d.ts create mode 100644 types/fined/tsconfig.json create mode 100644 types/fined/tslint.json diff --git a/types/fined/fined-tests.ts b/types/fined/fined-tests.ts new file mode 100644 index 0000000000..5ee4e79bc6 --- /dev/null +++ b/types/fined/fined-tests.ts @@ -0,0 +1,18 @@ +import fined = require('fined'); + +// $ExpectType Result | null +fined({ path: 'path/to/file', extensions: ['.js', '.json'] }); + +const opts = { + name: '.app', + cwd: '.', + extensions: { + rc: 'default-rc-loader', + '.yml': 'default-yml-loader', + }, +}; + +fined({ path: '.' }, opts); +fined({ path: '~', extensions: { rc: 'some-special-rc-loader' } }, opts); +fined({ path: '~' }, {}); +fined({ path: '~' }, { extensions: '.ext' }); diff --git a/types/fined/index.d.ts b/types/fined/index.d.ts new file mode 100644 index 0000000000..e19bad318a --- /dev/null +++ b/types/fined/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for fined 1.1 +// Project: https://github.com/js-cli/fined#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = fined; + +declare function fined(path: string | fined.PathSpec, opts?: fined.PathSpec): fined.Result | null; + +declare namespace fined { + interface PathSpec { + path?: string; + name?: string; + extensions?: string | string[] | { [extension: string]: string }; + cwd?: string; + findUp?: boolean; + } + + interface Result { + path: string; + extension: string | { [extension: string]: string }; + } +} diff --git a/types/fined/tsconfig.json b/types/fined/tsconfig.json new file mode 100644 index 0000000000..ce11eba9be --- /dev/null +++ b/types/fined/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fined-tests.ts" + ] +} diff --git a/types/fined/tslint.json b/types/fined/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fined/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From c5b361c9d1cd5092ec3c4ebb3c946ea1e8cbb5b4 Mon Sep 17 00:00:00 2001 From: Junyoung Choi Date: Wed, 5 Dec 2018 12:55:08 +0900 Subject: [PATCH 57/66] Add unknown props to Node --- types/unist/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/unist/index.d.ts b/types/unist/index.d.ts index ee61686f93..a7f6cc639d 100644 --- a/types/unist/index.d.ts +++ b/types/unist/index.d.ts @@ -26,6 +26,8 @@ export interface Node { * Must not be present if a node is generated. */ position?: Position; + + [key: string]: unknown; } /** From 95f292b29e49669cea79eb318de4945b9bf9853a Mon Sep 17 00:00:00 2001 From: Junyoung Choi Date: Wed, 5 Dec 2018 12:55:18 +0900 Subject: [PATCH 58/66] Discard AnyNode type --- types/vfile-message/index.d.ts | 6 +----- types/vfile/index.d.ts | 6 +++--- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/types/vfile-message/index.d.ts b/types/vfile-message/index.d.ts index 908f72027b..5f4467e007 100644 --- a/types/vfile-message/index.d.ts +++ b/types/vfile-message/index.d.ts @@ -9,10 +9,6 @@ import * as Unist from 'unist'; declare namespace vfileMessage { - interface AnyNode extends Unist.Node { - [key: string]: unknown; - } - /** * Create a virtual message. */ @@ -25,7 +21,7 @@ declare namespace vfileMessage { * @param position Place at which the message occurred in a file (`Node`, `Position`, or `Point`, optional). * @param origin Place in code the message originates from (`string`, optional). */ - (reason: string | Error, position?: AnyNode | Unist.Position | Unist.Point, origin?: string): VFileMessage; + (reason: string | Error, position?: Unist.Node | Unist.Position | Unist.Point, origin?: string): VFileMessage; /** * Category of message. */ diff --git a/types/vfile/index.d.ts b/types/vfile/index.d.ts index efb07e288d..aec7ca88f9 100644 --- a/types/vfile/index.d.ts +++ b/types/vfile/index.d.ts @@ -98,7 +98,7 @@ declare namespace vfile { * @param position Place at which the message occurred in `vfile`. * @param ruleId Category of message. */ - message: (reason: string, position?: Unist.Point | Unist.Position | vfileMessage.AnyNode, ruleId?: string) => vfileMessage.VFileMessage; + message: (reason: string, position?: Unist.Point | Unist.Position | Unist.Node, ruleId?: string) => vfileMessage.VFileMessage; /** * Associates a fatal message with the file, then immediately throws it. * Note: fatal errors mean a file is no longer processable. @@ -107,7 +107,7 @@ declare namespace vfile { * @param position Place at which the message occurred in `vfile`. * @param ruleId Category of message. */ - fail: (reason: string, position?: Unist.Point | Unist.Position | vfileMessage.AnyNode, ruleId?: string) => never; + fail: (reason: string, position?: Unist.Point | Unist.Position | Unist.Node, ruleId?: string) => never; /** * Associates an informational message with the file, where `fatal` is set to `null`. * Calls `message()` internally. @@ -115,7 +115,7 @@ declare namespace vfile { * @param position Place at which the message occurred in `vfile`. * @param ruleId Category of message. */ - info: (reason: string, position?: Unist.Point | Unist.Position | vfileMessage.AnyNode, ruleId?: string) => vfileMessage.VFileMessage; + info: (reason: string, position?: Unist.Point | Unist.Position | Unist.Node, ruleId?: string) => vfileMessage.VFileMessage; } } From 980d2c30563cd8825c947ae72c33337307d0c3a6 Mon Sep 17 00:00:00 2001 From: dominikeinkemmer Date: Wed, 5 Dec 2018 14:03:01 +0900 Subject: [PATCH 59/66] add missing methods to typings --- types/jest-when/index.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/types/jest-when/index.d.ts b/types/jest-when/index.d.ts index af62a95830..f484502f4d 100644 --- a/types/jest-when/index.d.ts +++ b/types/jest-when/index.d.ts @@ -8,6 +8,11 @@ export interface PartialMockInstance { mockReturnValue: jest.MockInstance['mockReturnValue']; + mockReturnValueOnce: jest.MockInstance['mockReturnValueOnce']; + mockResolvedValue: jest.MockInstance['mockResolvedValue']; + mockResolvedValueOnce: jest.MockInstance['mockResolvedValueOnce']; + mockRejectedValue: jest.MockInstance['mockRejectedValue']; + mockRejectedValueOnce: jest.MockInstance['mockRejectedValueOnce']; } export interface When { From 78de2a5f211671214c2aa94c5f3e2adcac0f25b1 Mon Sep 17 00:00:00 2001 From: Robert Stigsson Date: Wed, 5 Dec 2018 08:25:02 +0100 Subject: [PATCH 60/66] recharts: moved ifOverflow-types to IfOverflowType. --- types/recharts/index.d.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/types/recharts/index.d.ts b/types/recharts/index.d.ts index 7054b18e08..d18a846c56 100644 --- a/types/recharts/index.d.ts +++ b/types/recharts/index.d.ts @@ -46,6 +46,7 @@ export type StackOffsetType = 'sign' | 'expand' | 'none' | 'wiggle' | 'silhouett export type LineType = 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | CurveFactory; +export type IfOverflowType = 'hidden' | 'visible' | 'discard' | 'extendDomain'; export type AxisInterval = number | 'preserveStart' | 'preserveEnd' | 'preserveStartEnd'; export type PickedCSSStyleDeclarationKeys = @@ -635,7 +636,7 @@ export interface ReferenceAreaProps extends Partial { yAxis?: object; isFront?: boolean; alwaysShow?: boolean; - ifOverflow?: 'hidden' | 'visible' | 'discard' | 'extendDomain'; + ifOverflow?: IfOverflowType; x1?: number | string; x2?: number | string; y1?: number | string; @@ -659,7 +660,7 @@ export interface ReferenceDotProps extends EventAttributes, Partial | React.ReactElement; From f047781c2fa912f136447ac7bcdd54140ff8fc0b Mon Sep 17 00:00:00 2001 From: Christian Sporer Date: Wed, 5 Dec 2018 08:27:11 +0100 Subject: [PATCH 61/66] Using real name in the definitions file as per "convention" (and it is now anyways visible on my profile) --- types/list-stream/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/list-stream/index.d.ts b/types/list-stream/index.d.ts index f92eb5f917..2b3fd1da28 100644 --- a/types/list-stream/index.d.ts +++ b/types/list-stream/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for list-stream 1.0 // Project: https://github.com/rvagg/list-stream -// Definitions by: IanStorm +// Definitions by: Christian Sporer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.7 From 3e46e7059c10dd0d23bbfe8e83e7f635d161d943 Mon Sep 17 00:00:00 2001 From: Christian Sporer Date: Wed, 5 Dec 2018 08:28:48 +0100 Subject: [PATCH 62/66] Explicit mentioning of support for "import-" and "require-style" by providing more tests, as per discussion (https://github.com/DefinitelyTyped/DefinitelyTyped/pull/30669#discussion_r238432884) --- types/list-stream/list-stream-tests.ts | 56 +----------------------- types/list-stream/tests/import-tests.ts | 54 +++++++++++++++++++++++ types/list-stream/tests/require-tests.ts | 54 +++++++++++++++++++++++ 3 files changed, 110 insertions(+), 54 deletions(-) create mode 100644 types/list-stream/tests/import-tests.ts create mode 100644 types/list-stream/tests/require-tests.ts diff --git a/types/list-stream/list-stream-tests.ts b/types/list-stream/list-stream-tests.ts index 3648097ad6..89b0d6c236 100644 --- a/types/list-stream/list-stream-tests.ts +++ b/types/list-stream/list-stream-tests.ts @@ -1,54 +1,2 @@ -import ListStream from "list-stream"; - -let chunk: any = "chunk"; -let listStream: ListStream; -let num = 1; - -listStream = ListStream((err: Error, data: any[]) => { - if (err) { throw err; } - console.log(data.length); - for (const date of data) { - console.log(date); - } -}); -listStream = ListStream({ objectMode: true }, (err: Error, data: any[]) => { - if (err) { throw err; } - console.log(data.length); - for (const date of data) { - console.log(date); - } -}); -listStream = new ListStream((err: Error, data: any[]) => { - if (err) { throw err; } - console.log(data.length); - for (const date of data) { - console.log(date); - } -}); -listStream = new ListStream({ objectMode: true }, (err: Error, data: any[]) => { - if (err) { throw err; } - console.log(data.length); - for (const date of data) { - console.log(date); - } -}); -listStream = ListStream.obj((err: Error, data: any[]) => { - if (err) { throw err; } - console.log(data.length); - for (const date of data) { - console.log(date); - } -}); - -listStream = ListStream.obj(); -listStream.write({ key: "value" }); - -listStream.append(chunk); - -listStream = listStream.duplicate(); - -listStream.end(); - -chunk = listStream.get(num); - -num = listStream.length; +import "./tests/import-tests"; +import "./tests/require-tests"; diff --git a/types/list-stream/tests/import-tests.ts b/types/list-stream/tests/import-tests.ts new file mode 100644 index 0000000000..3648097ad6 --- /dev/null +++ b/types/list-stream/tests/import-tests.ts @@ -0,0 +1,54 @@ +import ListStream from "list-stream"; + +let chunk: any = "chunk"; +let listStream: ListStream; +let num = 1; + +listStream = ListStream((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = ListStream({ objectMode: true }, (err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = new ListStream((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = new ListStream({ objectMode: true }, (err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = ListStream.obj((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); + +listStream = ListStream.obj(); +listStream.write({ key: "value" }); + +listStream.append(chunk); + +listStream = listStream.duplicate(); + +listStream.end(); + +chunk = listStream.get(num); + +num = listStream.length; diff --git a/types/list-stream/tests/require-tests.ts b/types/list-stream/tests/require-tests.ts new file mode 100644 index 0000000000..8966e1e5a3 --- /dev/null +++ b/types/list-stream/tests/require-tests.ts @@ -0,0 +1,54 @@ +import ListStream = require("list-stream"); + +let chunk: any = "chunk"; +let listStream: ListStream; +let num = 1; + +listStream = ListStream((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = ListStream({ objectMode: true }, (err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = new ListStream((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = new ListStream({ objectMode: true }, (err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = ListStream.obj((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); + +listStream = ListStream.obj(); +listStream.write({ key: "value" }); + +listStream.append(chunk); + +listStream = listStream.duplicate(); + +listStream.end(); + +chunk = listStream.get(num); + +num = listStream.length; From 50db82783af95ccf7ee14596963360a84b790393 Mon Sep 17 00:00:00 2001 From: Christian Sporer Date: Wed, 5 Dec 2018 08:39:16 +0100 Subject: [PATCH 63/66] Fixed "unused file" error while running `npm test` --- types/list-stream/list-stream-tests.ts | 4 ++-- types/list-stream/{tests => test}/import-tests.ts | 0 types/list-stream/{tests => test}/require-tests.ts | 0 types/list-stream/tsconfig.json | 2 ++ 4 files changed, 4 insertions(+), 2 deletions(-) rename types/list-stream/{tests => test}/import-tests.ts (100%) rename types/list-stream/{tests => test}/require-tests.ts (100%) diff --git a/types/list-stream/list-stream-tests.ts b/types/list-stream/list-stream-tests.ts index 89b0d6c236..8b6ae25435 100644 --- a/types/list-stream/list-stream-tests.ts +++ b/types/list-stream/list-stream-tests.ts @@ -1,2 +1,2 @@ -import "./tests/import-tests"; -import "./tests/require-tests"; +import "./test/import-tests"; +import "./test/require-tests"; diff --git a/types/list-stream/tests/import-tests.ts b/types/list-stream/test/import-tests.ts similarity index 100% rename from types/list-stream/tests/import-tests.ts rename to types/list-stream/test/import-tests.ts diff --git a/types/list-stream/tests/require-tests.ts b/types/list-stream/test/require-tests.ts similarity index 100% rename from types/list-stream/tests/require-tests.ts rename to types/list-stream/test/require-tests.ts diff --git a/types/list-stream/tsconfig.json b/types/list-stream/tsconfig.json index 060c211379..00fe9a2e23 100644 --- a/types/list-stream/tsconfig.json +++ b/types/list-stream/tsconfig.json @@ -18,6 +18,8 @@ "esModuleInterop": true }, "files": [ + "test/import-tests.ts", + "test/require-tests.ts", "index.d.ts", "list-stream-tests.ts" ] From 321271c1c3e0337fe42005e8e0425ad69664f77c Mon Sep 17 00:00:00 2001 From: Daniel Rose Date: Wed, 5 Dec 2018 09:21:57 +0100 Subject: [PATCH 64/66] Use standard dtslint settings. --- types/fleximap/index.d.ts | 2 +- types/fleximap/tslint.json | 5 +---- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/types/fleximap/index.d.ts b/types/fleximap/index.d.ts index 9bce180c66..8481134ffe 100644 --- a/types/fleximap/index.d.ts +++ b/types/fleximap/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for fleximap 0.9.10 +// Type definitions for fleximap 0.9 // Project: https://github.com/SocketCluster/fleximap // Definitions by: Daniel Rose // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/fleximap/tslint.json b/types/fleximap/tslint.json index 65c83fb1e3..f93cf8562a 100644 --- a/types/fleximap/tslint.json +++ b/types/fleximap/tslint.json @@ -1,6 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "dt-header": false - } + "extends": "dtslint/dt.json" } From e7b92554e7ca0731739069c8c02e43bfb2279ddd Mon Sep 17 00:00:00 2001 From: Junyoung Choi Date: Wed, 5 Dec 2018 17:27:19 +0900 Subject: [PATCH 65/66] Add me to contributors :smile: --- types/unist/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/unist/index.d.ts b/types/unist/index.d.ts index a7f6cc639d..2d7d37e17f 100644 --- a/types/unist/index.d.ts +++ b/types/unist/index.d.ts @@ -4,6 +4,7 @@ // Jun Lu // Hernan Rajchert // Titus Wormer +// Junyoung Choi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 3.0 From b725a1d28c75f0d59a76f4abe6da95e695a55977 Mon Sep 17 00:00:00 2001 From: Lukas Schmidt Date: Wed, 5 Dec 2018 13:37:16 +0100 Subject: [PATCH 66/66] iframe-resizer: declare namespace --- types/iframe-resizer/iframe-resizer-tests.ts | 8 +- types/iframe-resizer/index.d.ts | 580 ++++++++++--------- 2 files changed, 314 insertions(+), 274 deletions(-) diff --git a/types/iframe-resizer/iframe-resizer-tests.ts b/types/iframe-resizer/iframe-resizer-tests.ts index 1efe701f9a..2f459c16a7 100644 --- a/types/iframe-resizer/iframe-resizer-tests.ts +++ b/types/iframe-resizer/iframe-resizer-tests.ts @@ -1,9 +1,9 @@ -import iframeResizer, { IFrameComponent, IFrameOptions } from "iframe-resizer"; +import iframeResizer = require("iframe-resizer"); function testOne(): void { const iframe: HTMLIFrameElement = document.createElement('iframe'); - const options: IFrameOptions = {log: true}; - const components: IFrameComponent[] = iframeResizer(options, iframe); + const options: iframeResizer.IFrameOptions = {log: true}; + const components: iframeResizer.IFrameComponent[] = iframeResizer(options, iframe); if (components) { components.forEach(component => console.log(component.iFrameResizer)); } else { @@ -13,7 +13,7 @@ function testOne(): void { function testTwo(): void { const iframe: HTMLIFrameElement = document.createElement('iframe'); - const components: IFrameComponent[] = iframeResizer({ + const components: iframeResizer.IFrameComponent[] = iframeResizer({ initCallback: () => { console.log('Init'); }, diff --git a/types/iframe-resizer/index.d.ts b/types/iframe-resizer/index.d.ts index 920c80b3a7..5f3cb19c7d 100644 --- a/types/iframe-resizer/index.d.ts +++ b/types/iframe-resizer/index.d.ts @@ -3,275 +3,315 @@ // Definitions by: Armin Baljic // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// tslint:disable-next-line:interface-name -export interface IFrameObject { - close(): void; - moveToAnchor(anchor: string): void; - resize(): void; - sendMessage(message: any, targetOrigin?: string): void; +declare namespace iframeResizer { + // tslint:disable-next-line:interface-name + interface IFrameObject { + close(): void; + + moveToAnchor(anchor: string): void; + + resize(): void; + + sendMessage( + message: any, + targetOrigin?: string + ): void; + } + + // tslint:disable-next-line:interface-name + interface IFrameComponent extends HTMLIFrameElement { + iFrameResizer: IFrameObject; + } + + // tslint:disable-next-line:interface-name + interface IFrameOptions { + /** + * When enabled changes to the Window size or the DOM will cause the iFrame to resize to the new content size. + * Disable if using size method with custom dimensions. + */ + autoResize?: boolean; + /** + * Override the body background style in the iFrame. + */ + bodyBackground?: string; + /** + * Override the default body margin style in the iFrame. A string can be any valid value for the + * CSS margin attribute, for example '8px 3em'. A number value is converted into px. + */ + bodyMargin?: number | string; + /** + * Override the default body padding style in the iFrame. A string can be any valid value for the + * CSS margin attribute, for example '8px 3em'. A number value is converted into px. + */ + bodyPadding?: number | string; + /** + * When set to true, only allow incoming messages from the domain listed in the src property of the iFrame tag. + * If your iFrame navigates between different domains, ports or protocols; then you will need to + * provide an array of URLs or disable this option. + */ + checkOrigin?: boolean | string[]; + /** + * When enabled in page linking inside the iFrame and from the iFrame to the parent page will be enabled. + */ + inPageLinks?: boolean; + /** + * Height calculation method. + */ + heightCalculationMethod?: HeightCalculationMethod; + /** + * Set iFrame Id + */ + id?: string; + /** + * In browsers that don't support mutationObserver, such as IE10, the library falls back to using + * setInterval, to check for changes to the page size. + */ + interval?: number; + /** + * Setting the log option to true will make the scripts in both the host page and the iFrame output + * everything they do to the JavaScript console so you can see the communication between the two scripts. + */ + log?: boolean; + /** + * Set maximum height of iFrame. + */ + maxHeight?: number; + /** + * Set maximum width of iFrame. + */ + maxWidth?: number; + /** + * Set minimum height of iFrame. + */ + minHeight?: number; + /** + * Set minimum width of iFrame. + */ + minWidth?: number; + /** + * Listen for resize events from the parent page, or the iFrame. Select the 'child' value if the iFrame + * can be resized independently of the browser window. Selecting this value can cause issues with some + * height calculation methods on mobile devices. + */ + resizeFrom?: 'parent' | 'child'; + /** + * Enable scroll bars in iFrame. + */ + scrolling?: boolean | 'auto'; + /** + * Resize iFrame to content height. + */ + sizeHeight?: boolean; + /** + * Resize iFrame to content width. + */ + sizeWidth?: boolean; + /** + * Set the number of pixels the iFrame content size has to change by, before triggering a resize of the iFrame. + */ + tolerance?: number; + /** + * Width calculation method. + */ + widthCalculationMethod?: WidthCalculationMethod; + + /** + * Called when iFrame is closed via parentIFrame.close() or iframe.iframeResizer.close() methods. + */ + closedCallback?(iframeId: string): void; + + /** + * Initial setup callback function. + */ + initCallback?(iframe: IFrameComponent): void; + + /** + * Receive message posted from iFrame with the parentIFrame.sendMessage() method. + */ + messageCallback?(data: IFrameMessageData): void; + + /** + * Function called after iFrame resized. Passes in messageData object containing the iFrame, height, width + * and the type of event that triggered the iFrame to resize. + */ + resizedCallback?(data: IFrameResizedData): void; + + /** + * Called before the page is repositioned after a request from the iFrame, due to either an in page link, + * or a direct request from either parentIFrame.scrollTo() or parentIFrame.scrollToOffset(). + * If this callback function returns false, it will stop the library from repositioning the page, so that + * you can implement your own animated page scrolling instead. + */ + scrollCallback?(data: IFrameScrollData): boolean; + } + + // tslint:disable-next-line:interface-name + interface IFramePageOptions { + /** + * This option allows you to restrict the domain of the parent page, + * to prevent other sites mimicking your parent page. + */ + targetOrigin?: string; + + /** + * Receive message posted from the parent page with the iframe.iFrameResizer.sendMessage() method. + */ + messageCallback?(message: any): void; + + /** + * This function is called once iFrame-Resizer has been initialized after receiving a call from the parent page. + */ + readyCallback?(): void; + + /** + * These option can be used to override the option set in the parent page + */ + heightCalculationMethod?: HeightCalculationMethod | (() => number); + /** + * These option can be used to override the option set in the parent page + */ + widthCalculationMethod?: WidthCalculationMethod | (() => number); + } + + type HeightCalculationMethod = 'bodyOffset' | 'bodyScroll' | 'documentElementOffset' | 'documentElementScroll' | + 'max' | 'min' | 'grow' | 'lowestElement' | 'taggedElement'; + + type WidthCalculationMethod = 'bodyOffset' | 'bodyScroll' | 'documentElementOffset' | 'documentElementScroll' | + 'max' | 'min' | 'scroll' | 'rightMostElement' | 'taggedElement'; + + // tslint:disable-next-line:interface-name + interface IFramePage { + /** + * Turn autoResizing of the iFrame on and off. Returns bool of current state. + */ + autoResize(resize?: boolean): boolean; + + /** + * Remove the iFrame from the parent page. + */ + close(): void; + + /** + * Returns the ID of the iFrame that the page is contained in. + */ + getId(): string; + + /** + * Ask the containing page for its positioning coordinates. + * + * Your callback function will be recalled when the parent page is scrolled or resized. + * + * Pass false to disable the callback. + */ + getPageInfo(callback: ((data: PageInfo) => void) | false): void; + + /** + * Scroll the parent page to the coordinates x and y + */ + scrollTo( + x: number, + y: number + ): void; + + /** + * Scroll the parent page to the coordinates x and y relative to the position of the iFrame. + */ + scrollToOffset( + x: number, + y: number + ): void; + + /** + * Send data to the containing page, message can be any data type that can be serialized into JSON. The `targetOrigin` + * option is used to restrict where the message is sent to; to stop an attacker mimicking your parent page. + * See the MDN documentation on postMessage for more details. + */ + sendMessage( + message: any, + targetOrigin?: string + ): void; + + /** + * Change the method use to workout the height of the iFrame. + */ + setHeightCalculationMethod(method: HeightCalculationMethod): void; + + /** + * Change the method use to workout the width of the iFrame. + */ + setWidthCalculationMethod(method: WidthCalculationMethod): void; + + /** + * Set default target origin. + */ + setTargetOrigin(targetOrigin: string): void; + + /** + * Manually force iFrame to resize. To use passed arguments you need first to disable the `autoResize` option to + * prevent auto resizing and enable the `sizeWidth` option if you wish to set the width. + */ + size( + customHeight?: string, + customWidth?: string + ): void; + } + + interface PageInfo { + /** + * The height of the iframe in pixels + */ + iframeHeight: number; + /** + * The width of the iframe in pixels + */ + iframeWidth: number; + /** + * The height of the viewport in pixels + */ + clientHeight: number; + /** + * The width of the viewport in pixels + */ + clientWidth: number; + /** + * The number of pixels between the left edge of the containing page and the left edge of the iframe + */ + offsetLeft: number; + /** + * The number of pixels between the top edge of the containing page and the top edge of the iframe + */ + offsetTop: number; + /** + * The number of pixels between the left edge of the iframe and the left edge of the iframe viewport + */ + scrollLeft: number; + /** + * The number of pixels between the top edge of the iframe and the top edge of the iframe viewport + */ + scrollTop: number; + } + + // tslint:disable-next-line:interface-name + interface IFrameResizedData { + iframe: IFrameComponent; + height: number; + width: number; + type: string; + } + + // tslint:disable-next-line:interface-name + interface IFrameMessageData { + iframe: IFrameComponent; + message: any; + } + + // tslint:disable-next-line:interface-name + interface IFrameScrollData { + x: number; + y: number; + } } -// tslint:disable-next-line:interface-name -export interface IFrameComponent extends HTMLIFrameElement { - iFrameResizer: IFrameObject; -} - -// tslint:disable-next-line:interface-name -export interface IFrameOptions { - /** - * When enabled changes to the Window size or the DOM will cause the iFrame to resize to the new content size. - * Disable if using size method with custom dimensions. - */ - autoResize?: boolean; - /** - * Override the body background style in the iFrame. - */ - bodyBackground?: string; - /** - * Override the default body margin style in the iFrame. A string can be any valid value for the - * CSS margin attribute, for example '8px 3em'. A number value is converted into px. - */ - bodyMargin?: number | string; - /** - * Override the default body padding style in the iFrame. A string can be any valid value for the - * CSS margin attribute, for example '8px 3em'. A number value is converted into px. - */ - bodyPadding?: number | string; - /** - * When set to true, only allow incoming messages from the domain listed in the src property of the iFrame tag. - * If your iFrame navigates between different domains, ports or protocols; then you will need to - * provide an array of URLs or disable this option. - */ - checkOrigin?: boolean | string[]; - /** - * When enabled in page linking inside the iFrame and from the iFrame to the parent page will be enabled. - */ - inPageLinks?: boolean; - /** - * Height calculation method. - */ - heightCalculationMethod?: HeightCalculationMethod; - /** - * Set iFrame Id - */ - id?: string; - /** - * In browsers that don't support mutationObserver, such as IE10, the library falls back to using - * setInterval, to check for changes to the page size. - */ - interval?: number; - /** - * Setting the log option to true will make the scripts in both the host page and the iFrame output - * everything they do to the JavaScript console so you can see the communication between the two scripts. - */ - log?: boolean; - /** - * Set maximum height of iFrame. - */ - maxHeight?: number; - /** - * Set maximum width of iFrame. - */ - maxWidth?: number; - /** - * Set minimum height of iFrame. - */ - minHeight?: number; - /** - * Set minimum width of iFrame. - */ - minWidth?: number; - /** - * Listen for resize events from the parent page, or the iFrame. Select the 'child' value if the iFrame - * can be resized independently of the browser window. Selecting this value can cause issues with some - * height calculation methods on mobile devices. - */ - resizeFrom?: 'parent' | 'child'; - /** - * Enable scroll bars in iFrame. - */ - scrolling?: boolean | 'auto'; - /** - * Resize iFrame to content height. - */ - sizeHeight?: boolean; - /** - * Resize iFrame to content width. - */ - sizeWidth?: boolean; - /** - * Set the number of pixels the iFrame content size has to change by, before triggering a resize of the iFrame. - */ - tolerance?: number; - /** - * Width calculation method. - */ - widthCalculationMethod?: WidthCalculationMethod; - /** - * Called when iFrame is closed via parentIFrame.close() or iframe.iframeResizer.close() methods. - */ - closedCallback?(iframeId: string): void; - /** - * Initial setup callback function. - */ - initCallback?(iframe: IFrameComponent): void; - /** - * Receive message posted from iFrame with the parentIFrame.sendMessage() method. - */ - messageCallback?(data: IFrameMessageData): void; - /** - * Function called after iFrame resized. Passes in messageData object containing the iFrame, height, width - * and the type of event that triggered the iFrame to resize. - */ - resizedCallback?(data: IFrameResizedData): void; - /** - * Called before the page is repositioned after a request from the iFrame, due to either an in page link, - * or a direct request from either parentIFrame.scrollTo() or parentIFrame.scrollToOffset(). - * If this callback function returns false, it will stop the library from repositioning the page, so that - * you can implement your own animated page scrolling instead. - */ - scrollCallback?(data: IFrameScrollData): boolean; -} - -// tslint:disable-next-line:interface-name -export interface IFramePageOptions { - /** - * This option allows you to restrict the domain of the parent page, - * to prevent other sites mimicking your parent page. - */ - targetOrigin?: string; - /** - * Receive message posted from the parent page with the iframe.iFrameResizer.sendMessage() method. - */ - messageCallback?(message: any): void; - /** - * This function is called once iFrame-Resizer has been initialized after receiving a call from the parent page. - */ - readyCallback?(): void; - /** - * These option can be used to override the option set in the parent page - */ - heightCalculationMethod?: HeightCalculationMethod | (() => number); - /** - * These option can be used to override the option set in the parent page - */ - widthCalculationMethod?: WidthCalculationMethod | (() => number); -} - -export type HeightCalculationMethod = 'bodyOffset' | 'bodyScroll' | 'documentElementOffset' | 'documentElementScroll' | - 'max' | 'min' | 'grow' | 'lowestElement' | 'taggedElement'; - - export type WidthCalculationMethod = 'bodyOffset' | 'bodyScroll' | 'documentElementOffset' | 'documentElementScroll' | - 'max' | 'min' | 'scroll' | 'rightMostElement' | 'taggedElement'; - -// tslint:disable-next-line:interface-name -export interface IFramePage { - /** - * Turn autoResizing of the iFrame on and off. Returns bool of current state. - */ - autoResize(resize?: boolean): boolean; - /** - * Remove the iFrame from the parent page. - */ - close(): void; - /** - * Returns the ID of the iFrame that the page is contained in. - */ - getId(): string; - /** - * Ask the containing page for its positioning coordinates. - * - * Your callback function will be recalled when the parent page is scrolled or resized. - * - * Pass false to disable the callback. - */ - getPageInfo(callback: ((data: PageInfo) => void) | false): void; - /** - * Scroll the parent page to the coordinates x and y - */ - scrollTo(x: number, y: number): void; - /** - * Scroll the parent page to the coordinates x and y relative to the position of the iFrame. - */ - scrollToOffset(x: number, y: number): void; - /** - * Send data to the containing page, message can be any data type that can be serialized into JSON. The `targetOrigin` - * option is used to restrict where the message is sent to; to stop an attacker mimicking your parent page. - * See the MDN documentation on postMessage for more details. - */ - sendMessage(message: any, targetOrigin?: string): void; - /** - * Change the method use to workout the height of the iFrame. - */ - setHeightCalculationMethod(method: HeightCalculationMethod): void; - /** - * Change the method use to workout the width of the iFrame. - */ - setWidthCalculationMethod(method: WidthCalculationMethod): void; - /** - * Set default target origin. - */ - setTargetOrigin(targetOrigin: string): void; - /** - * Manually force iFrame to resize. To use passed arguments you need first to disable the `autoResize` option to - * prevent auto resizing and enable the `sizeWidth` option if you wish to set the width. - */ - size(customHeight?: string, customWidth?: string): void; -} - -export interface PageInfo { - /** - * The height of the iframe in pixels - */ - iframeHeight: number; - /** - * The width of the iframe in pixels - */ - iframeWidth: number; - /** - * The height of the viewport in pixels - */ - clientHeight: number; - /** - * The width of the viewport in pixels - */ - clientWidth: number; - /** - * The number of pixels between the left edge of the containing page and the left edge of the iframe - */ - offsetLeft: number; - /** - * The number of pixels between the top edge of the containing page and the top edge of the iframe - */ - offsetTop: number; - /** - * The number of pixels between the left edge of the iframe and the left edge of the iframe viewport - */ - scrollLeft: number; - /** - * The number of pixels between the top edge of the iframe and the top edge of the iframe viewport - */ - scrollTop: number; -} - -// tslint:disable-next-line:interface-name -export interface IFrameResizedData { - iframe: IFrameComponent; - height: number; - width: number; - type: string; -} - -// tslint:disable-next-line:interface-name -export interface IFrameMessageData { - iframe: IFrameComponent; - message: any; -} - -// tslint:disable-next-line:interface-name -export interface IFrameScrollData { - x: number; - y: number; -} - -export default function iframeResizer(options: IFrameOptions, target: string | HTMLElement): IFrameComponent[]; +declare function iframeResizer(options: iframeResizer.IFrameOptions, target: string | HTMLElement): iframeResizer.IFrameComponent[]; +export = iframeResizer; +export as namespace iframeResizer;