Merge github.com:DefinitelyTyped/DefinitelyTyped

This commit is contained in:
tsai phan 2017-07-06 12:35:40 +08:00
commit 8f0b5485dc
175 changed files with 8421 additions and 3041 deletions

View File

@ -138,6 +138,12 @@
"sourceRepoURL": "https://github.com/loopline-systems/electron-builder",
"asOfVersion": "2.8.0"
},
{
"libraryName": "eventemitter2",
"typingsPackageName": "eventemitter2",
"sourceRepoURL": "https://github.com/asyncly/EventEmitter2",
"asOfVersion": "4.1.0"
},
{
"libraryName": "EventEmitter3",
"typingsPackageName": "eventemitter3",
@ -420,6 +426,12 @@
"sourceRepoURL": "https://github.com/angular/protractor",
"asOfVersion": "4.0.0"
},
{
"libraryName": "qiniu",
"typingsPackageName": "qiniu",
"sourceRepoURL": "https://github.com/qiniu/nodejs-sdk",
"asOfVersion": "7.0.1"
},
{
"libraryName": "Raven JS",
"typingsPackageName": "raven-js",

View File

@ -17,7 +17,7 @@
"scripts": {
"compile-scripts": "tsc -p scripts",
"not-needed": "node scripts/not-needed.js",
"test": "node node_modules/types-publisher/bin/tester/test.js --run-from-definitely-typed --nProcesses 4",
"test": "node node_modules/types-publisher/bin/tester/test.js --run-from-definitely-typed --nProcesses 8",
"lint": "dtslint types"
},
"devDependencies": {

View File

@ -0,0 +1,30 @@
let obj0 = new ActiveXObject('ADODB.Command');
let obj1 = new ActiveXObject('ADODB.Connection');
let obj2 = new ActiveXObject('ADODB.Parameter');
let obj3 = new ActiveXObject('ADODB.Record');
let obj4 = new ActiveXObject('ADODB.Recordset');
let obj5 = new ActiveXObject('ADODB.Stream');
// open connection to an Excel file
let pathToExcelFile = 'C:\\path\\to\\excel\\file.xlsx';
let conn = new ActiveXObject('ADODB.Connection');
conn.Provider = 'Microsoft.ACE.OLEDB.12.0';
conn.ConnectionString =
'Data Source="' + pathToExcelFile + '";' +
'Extended Properties="Excel 12.0;HDR=Yes"';
conn.Open();
// create a Command to access the data
let cmd = new ActiveXObject('ADODB.Command');
cmd.CommandText = 'SELECT DISTINCT LastName, CityName FROM [Sheet1$]';
// get a Recordset
let rs = cmd.Execute();
// build a string from the Recordset
let s = rs.GetString(ADODB.StringFormatEnum.adClipString, -1, '\t', '\n', '(NULL)');
rs.Close();
WScript.Echo(s);

View File

@ -1,11 +1,9 @@
// Type definitions for Microsoft ActiveX Data Objects
// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/ms675532(v=vs.85).aspx
// Type definitions for Microsoft ActiveX Data Objects 6.1
// Project: https://msdn.microsoft.com/en-us/library/jj249010.aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace ADODB {
//Enums
const enum ADCPROP_ASYNCTHREADPRIORITY_ENUM {
adPriorityAboveNormal = 4,
adPriorityBelowNormal = 2,
@ -595,240 +593,415 @@ declare namespace ADODB {
adXactSyncPhaseOne = 1048576
}
//Interfaces
interface Command {
ActiveConnection: Connection;
Cancel: () => void;
CommandStream: any /*VT_UNKNOWN*/;
Cancel(): void;
CommandStream: any;
CommandText: string;
CommandTimeout: number;
CommandType: CommandTypeEnum;
CreateParameter: (Name?: string, Type?: DataTypeEnum, Direction?: ParameterDirectionEnum, Size?: number, Value?: any) => Parameter;
/**
* @param string [Name='']
* @param ADODB.DataTypeEnum [Type=0]
* @param ADODB.ParameterDirectionEnum [Direction=1]
* @param number [Size=0]
*/
CreateParameter(Name?: string, Type?: DataTypeEnum, Direction?: ParameterDirectionEnum, Size?: number, Value?: any): Parameter;
Dialect: string;
Execute: (RecordsAffected?: any, Parameters?: any, Options?: number) => Recordset;
/** @param number [Options=-1] */
Execute(RecordsAffected?: any, Parameters?: any, Options?: number): Recordset;
Name: string;
NamedParameters: boolean;
Parameters: Parameters;
readonly Parameters: Parameters;
Prepared: boolean;
Properties: Properties;
State: number;
readonly Properties: Properties;
readonly State: number;
}
interface Connection {
Attributes: number;
BeginTrans: () => number;
Cancel: () => void;
Close: () => void;
BeginTrans(): number;
Cancel(): void;
Close(): void;
CommandTimeout: number;
CommitTrans: () => void;
CommitTrans(): void;
ConnectionString: string;
ConnectionTimeout: number;
CursorLocation: CursorLocationEnum;
DefaultDatabase: string;
Errors: Errors;
Execute: (CommandText: string, RecordsAffected: any, Options?: number) => Recordset;
readonly Errors: Errors;
/** @param number [Options=-1] */
Execute(CommandText: string, RecordsAffected: any, Options?: number): Recordset;
IsolationLevel: IsolationLevelEnum;
Mode: ConnectModeEnum;
Open: (ConnectionString?: string, UserID?: string, Password?: string, Options?: number) => void;
OpenSchema: (Schema: SchemaEnum, Restrictions?: any, SchemaID?: any) => Recordset;
Properties: Properties;
/**
* @param string [ConnectionString='']
* @param string [UserID='']
* @param string [Password='']
* @param number [Options=-1]
*/
Open(ConnectionString?: string, UserID?: string, Password?: string, Options?: number): void;
OpenSchema(Schema: SchemaEnum, Restrictions?: any, SchemaID?: any): Recordset;
readonly Properties: Properties;
Provider: string;
RollbackTrans: () => void;
State: number;
Version: string;
RollbackTrans(): void;
readonly State: number;
readonly Version: string;
}
interface Error {
Description: string;
HelpContext: number;
HelpFile: string;
NativeError: number;
Number: number;
Source: string;
SQLState: string;
readonly Description: string;
readonly HelpContext: number;
readonly HelpFile: string;
readonly NativeError: number;
readonly Number: number;
readonly Source: string;
readonly SQLState: string;
}
interface Errors {
Clear: () => void;
Count: number;
Item: (Index: any) => Error;
Refresh: () => void;
Clear(): void;
readonly Count: number;
Item(Index: any): Error;
Refresh(): void;
}
interface Field {
ActualSize: number;
AppendChunk: (Data: any) => void;
readonly ActualSize: number;
AppendChunk(Data: any): void;
Attributes: number;
DataFormat: any /*VT_UNKNOWN*/;
DataFormat: any;
DefinedSize: number;
GetChunk: (Length: number) => any;
Name: string;
GetChunk(Length: number): any;
readonly Name: string;
NumericScale: number;
OriginalValue: any;
readonly OriginalValue: any;
Precision: number;
Properties: Properties;
Status: number;
readonly Properties: Properties;
readonly Status: number;
Type: DataTypeEnum;
UnderlyingValue: any;
readonly UnderlyingValue: any;
Value: any;
}
interface Fields {
_Append: (Name: string, Type: DataTypeEnum, DefinedSize?: number, Attrib?: FieldAttributeEnum) => void;
Append: (Name: string, Type: DataTypeEnum, DefinedSize?: number, Attrib?: FieldAttributeEnum, FieldValue?: any) => void;
CancelUpdate: () => void;
Count: number;
Delete: (Index: any) => void;
Item: (Index: any) => Field;
Refresh: () => void;
Resync: (ResyncValues?: ResyncEnum) => void;
Update: () => void;
/**
* @param number [DefinedSize=0]
* @param ADODB.FieldAttributeEnum [Attrib=-1]
*/
_Append(Name: string, Type: DataTypeEnum, DefinedSize?: number, Attrib?: FieldAttributeEnum): void;
/**
* @param number [DefinedSize=0]
* @param ADODB.FieldAttributeEnum [Attrib=-1]
*/
Append(Name: string, Type: DataTypeEnum, DefinedSize?: number, Attrib?: FieldAttributeEnum, FieldValue?: any): void;
CancelUpdate(): void;
readonly Count: number;
Delete(Index: any): void;
Item(Index: any): Field;
Refresh(): void;
/** @param ADODB.ResyncEnum [ResyncValues=2] */
Resync(ResyncValues?: ResyncEnum): void;
Update(): void;
}
interface Parameter {
AppendChunk: (Val: any) => void;
AppendChunk(Val: any): void;
Attributes: number;
Direction: ParameterDirectionEnum;
Name: string;
NumericScale: number;
Precision: number;
Properties: Properties;
readonly Properties: Properties;
Size: number;
Type: DataTypeEnum;
Value: any;
}
interface Parameters {
Append: (Object: any /*VT_DISPATCH*/) => void;
Count: number;
Delete: (Index: any) => void;
Item: (Index: any) => Parameter;
Refresh: () => void;
Append(Object: any): void;
readonly Count: number;
Delete(Index: any): void;
Item(Index: any): Parameter;
Refresh(): void;
}
interface Properties {
Count: number;
Item: (Index: any) => Property;
Refresh: () => void;
readonly Count: number;
Item(Index: any): Property;
Refresh(): void;
}
interface Property {
Attributes: number;
Name: string;
Type: DataTypeEnum;
readonly Name: string;
readonly Type: DataTypeEnum;
Value: any;
}
interface Record {
ActiveConnection: any;
Cancel: () => void;
Close: () => void;
CopyRecord: (Source?: string, Destination?: string, UserName?: string, Password?: string, Options?: CopyRecordOptionsEnum, Async?: boolean) => string;
DeleteRecord: (Source?: string, Async?: boolean) => void;
Fields: Fields;
GetChildren: () => Recordset;
Cancel(): void;
Close(): void;
/**
* @param string [Source='']
* @param string [Destination='']
* @param string [UserName='']
* @param string [Password='']
* @param ADODB.CopyRecordOptionsEnum [Options=-1]
* @param boolean [Async=false]
*/
CopyRecord(Source?: string, Destination?: string, UserName?: string, Password?: string, Options?: CopyRecordOptionsEnum, Async?: boolean): string;
/**
* @param string [Source='']
* @param boolean [Async=false]
*/
DeleteRecord(Source?: string, Async?: boolean): void;
readonly Fields: Fields;
GetChildren(): Recordset;
Mode: ConnectModeEnum;
MoveRecord: (Source?: string, Destination?: string, UserName?: string, Password?: string, Options?: MoveRecordOptionsEnum, Async?: boolean) => string;
Open: (Source: any, ActiveConnection: any, Mode?: ConnectModeEnum, CreateOptions?: RecordCreateOptionsEnum, Options?: RecordOpenOptionsEnum, UserName?: string, Password?: string) => void;
ParentURL: string;
Properties: Properties;
RecordType: RecordTypeEnum;
/**
* @param string [Source='']
* @param string [Destination='']
* @param string [UserName='']
* @param string [Password='']
* @param ADODB.MoveRecordOptionsEnum [Options=-1]
* @param boolean [Async=false]
*/
MoveRecord(Source?: string, Destination?: string, UserName?: string, Password?: string, Options?: MoveRecordOptionsEnum, Async?: boolean): string;
/**
* @param ADODB.ConnectModeEnum [Mode=0]
* @param ADODB.RecordCreateOptionsEnum [CreateOptions=-1]
* @param ADODB.RecordOpenOptionsEnum [Options=-1]
* @param string [UserName='']
* @param string [Password='']
*/
Open(Source: any, ActiveConnection: any, Mode?: ConnectModeEnum, CreateOptions?: RecordCreateOptionsEnum, Options?: RecordOpenOptionsEnum, UserName?: string, Password?: string): void;
readonly ParentURL: string;
readonly Properties: Properties;
readonly RecordType: RecordTypeEnum;
Source: any;
State: ObjectStateEnum;
readonly State: ObjectStateEnum;
}
interface Recordset {
_xClone: () => Recordset;
_xResync: (AffectRecords?: AffectEnum) => void;
_xSave: (FileName?: string, PersistFormat?: PersistFormatEnum) => void;
_xClone(): Recordset;
/** @param ADODB.AffectEnum [AffectRecords=3] */
_xResync(AffectRecords?: AffectEnum): void;
/**
* @param string [FileName='']
* @param ADODB.PersistFormatEnum [PersistFormat=0]
*/
_xSave(FileName?: string, PersistFormat?: PersistFormatEnum): void;
AbsolutePage: PositionEnum;
AbsolutePosition: PositionEnum;
ActiveCommand: any /*VT_DISPATCH*/;
ActiveConnection: any /*VT_DISPATCH*/;
AddNew: (FieldList?: any, Values?: any) => void;
BOF: boolean;
readonly ActiveCommand: any;
ActiveConnection: any;
AddNew(FieldList?: any, Values?: any): void;
readonly BOF: boolean;
Bookmark: any;
CacheSize: number;
Cancel: () => void;
CancelBatch: (AffectRecords?: AffectEnum) => void;
CancelUpdate: () => void;
Clone: (LockType?: LockTypeEnum) => Recordset;
Close: () => void;
Collect: (Index: any) => any; //Also has setter with parameters
CompareBookmarks: (Bookmark1: any, Bookmark2: any) => CompareEnum;
Cancel(): void;
/** @param ADODB.AffectEnum [AffectRecords=3] */
CancelBatch(AffectRecords?: AffectEnum): void;
CancelUpdate(): void;
/** @param ADODB.LockTypeEnum [LockType=-1] */
Clone(LockType?: LockTypeEnum): Recordset;
Close(): void;
Collect(Index: any): any;
CompareBookmarks(Bookmark1: any, Bookmark2: any): CompareEnum;
CursorLocation: CursorLocationEnum;
CursorType: CursorTypeEnum;
DataMember: string;
DataSource: any /*VT_UNKNOWN*/;
Delete: (AffectRecords?: AffectEnum) => void;
EditMode: EditModeEnum;
EOF: boolean;
Fields: Fields;
DataSource: any;
/** @param ADODB.AffectEnum [AffectRecords=1] */
Delete(AffectRecords?: AffectEnum): void;
readonly EditMode: EditModeEnum;
readonly EOF: boolean;
readonly Fields: Fields;
Filter: any;
Find: (Criteria: string, SkipRecords?: number, SearchDirection?: SearchDirectionEnum, Start?: any) => void;
GetRows: (Rows?: number, Start?: any, Fields?: any) => any;
GetString: (StringFormat?: StringFormatEnum, NumRows?: number, ColumnDelimeter?: string, RowDelimeter?: string, NullExpr?: string) => string;
/**
* @param number [SkipRecords=0]
* @param ADODB.SearchDirectionEnum [SearchDirection=1]
*/
Find(Criteria: string, SkipRecords?: number, SearchDirection?: SearchDirectionEnum, Start?: any): void;
/** @param number [Rows=-1] */
GetRows(Rows?: number, Start?: any, Fields?: any): any;
/**
* @param ADODB.StringFormatEnum [StringFormat=2]
* @param number [NumRows=-1]
* @param string [ColumnDelimeter='']
* @param string [RowDelimeter='']
* @param string [NullExpr='']
*/
GetString(StringFormat?: StringFormatEnum, NumRows?: number, ColumnDelimeter?: string, RowDelimeter?: string, NullExpr?: string): string;
Index: string;
LockType: LockTypeEnum;
MarshalOptions: MarshalOptionsEnum;
MaxRecords: number;
Move: (NumRecords: number, Start?: any) => void;
MoveFirst: () => void;
MoveLast: () => void;
MoveNext: () => void;
MovePrevious: () => void;
NextRecordset: (RecordsAffected?: any) => Recordset;
Open: (Source: any, ActiveConnection: any, CursorType?: CursorTypeEnum, LockType?: LockTypeEnum, Options?: number) => void;
PageCount: number;
Move(NumRecords: number, Start?: any): void;
MoveFirst(): void;
MoveLast(): void;
MoveNext(): void;
MovePrevious(): void;
NextRecordset(RecordsAffected?: any): Recordset;
/**
* @param ADODB.CursorTypeEnum [CursorType=-1]
* @param ADODB.LockTypeEnum [LockType=-1]
* @param number [Options=-1]
*/
Open(Source: any, ActiveConnection: any, CursorType?: CursorTypeEnum, LockType?: LockTypeEnum, Options?: number): void;
readonly PageCount: number;
PageSize: number;
Properties: Properties;
RecordCount: number;
Requery: (Options?: number) => void;
Resync: (AffectRecords?: AffectEnum, ResyncValues?: ResyncEnum) => void;
Save: (Destination: any, PersistFormat?: PersistFormatEnum) => void;
Seek: (KeyValues: any, SeekOption?: SeekEnum) => void;
readonly Properties: Properties;
readonly RecordCount: number;
/** @param number [Options=-1] */
Requery(Options?: number): void;
/**
* @param ADODB.AffectEnum [AffectRecords=3]
* @param ADODB.ResyncEnum [ResyncValues=2]
*/
Resync(AffectRecords?: AffectEnum, ResyncValues?: ResyncEnum): void;
/** @param ADODB.PersistFormatEnum [PersistFormat=0] */
Save(Destination: any, PersistFormat?: PersistFormatEnum): void;
/** @param ADODB.SeekEnum [SeekOption=1] */
Seek(KeyValues: any, SeekOption?: SeekEnum): void;
Sort: string;
Source: any /*VT_DISPATCH*/;
State: number;
Status: number;
Source: any;
readonly State: number;
readonly Status: number;
StayInSync: boolean;
Supports: (CursorOptions: CursorOptionEnum) => boolean;
Update: (Fields?: any, Values?: any) => void;
UpdateBatch: (AffectRecords?: AffectEnum) => void;
Supports(CursorOptions: CursorOptionEnum): boolean;
Update(Fields?: any, Values?: any): void;
/** @param ADODB.AffectEnum [AffectRecords=3] */
UpdateBatch(AffectRecords?: AffectEnum): void;
}
interface Stream {
Cancel: () => void;
Cancel(): void;
Charset: string;
Close: () => void;
CopyTo: (DestStream: Stream, CharNumber?: number) => void;
EOS: boolean;
Flush: () => void;
LineSeparator: LineSeparatorEnum;
LoadFromFile: (FileName: string) => void;
Mode: ConnectModeEnum;
Open: (Source: any, Mode?: ConnectModeEnum, Options?: StreamOpenOptionsEnum, UserName?: string, Password?: string) => void;
Position: number;
Read: (NumBytes?: number) => any;
ReadText: (NumChars?: number) => string;
SaveToFile: (FileName: string, Options?: SaveOptionsEnum) => void;
SetEOS: () => void;
Size: number;
SkipLine: () => void;
State: ObjectStateEnum;
Type: StreamTypeEnum;
Write: (Buffer: any) => void;
WriteText: (Data: string, Options?: StreamWriteEnum) => void;
}
Close(): void;
/** @param number [CharNumber=-1] */
CopyTo(DestStream: Stream, CharNumber?: number): void;
readonly EOS: boolean;
Flush(): void;
LineSeparator: LineSeparatorEnum;
LoadFromFile(FileName: string): void;
Mode: ConnectModeEnum;
/**
* @param ADODB.ConnectModeEnum [Mode=0]
* @param ADODB.StreamOpenOptionsEnum [Options=-1]
* @param string [UserName='']
* @param string [Password='']
*/
Open(Source: any, Mode?: ConnectModeEnum, Options?: StreamOpenOptionsEnum, UserName?: string, Password?: string): void;
Position: number;
/** @param number [NumBytes=-1] */
Read(NumBytes?: number): any;
/** @param number [NumChars=-1] */
ReadText(NumChars?: number): string;
/** @param ADODB.SaveOptionsEnum [Options=1] */
SaveToFile(FileName: string, Options?: SaveOptionsEnum): void;
SetEOS(): void;
readonly Size: number;
SkipLine(): void;
readonly State: ObjectStateEnum;
Type: StreamTypeEnum;
Write(Buffer: any): void;
/** @param ADODB.StreamWriteEnum [Options=0] */
WriteText(Data: string, Options?: StreamWriteEnum): void;
}
}
interface ActiveXObject {
new (progID: 'ADODB.Connection'): ADODB.Connection;
new (progID: 'ADODB.Record'): ADODB.Record;
new (progID: 'ADODB.Stream'): ADODB.Stream;
new (progID: 'ADODB.Command'): ADODB.Command;
new (progID: 'ADODB.Recordset'): ADODB.Recordset;
new (progID: 'ADODB.Parameter'): ADODB.Parameter;
on(obj: ADODB.Connection, event: 'BeginTransComplete', argNames: ['TransactionLevel', 'pError', 'adStatus', 'pConnection'], handler: (
this: ADODB.Connection, parameter: {
TransactionLevel: number, pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, pConnection: ADODB.Connection}) => void): void;
on(obj: ADODB.Connection, event: 'Disconnect', argNames: ['adStatus', 'pConnection'], handler: (
this: ADODB.Connection, parameter: {
adStatus: ADODB.EventStatusEnum, pConnection: ADODB.Connection}) => void): void;
on(obj: ADODB.Connection, event: 'ExecuteComplete', argNames: ['RecordsAffected', 'pError', 'adStatus', 'pCommand', 'pRecordset', 'pConnection'], handler: (
this: ADODB.Connection, parameter: {
RecordsAffected: number, pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, pCommand: ADODB.Command, pRecordset: ADODB.Recordset, pConnection: ADODB.Connection}) => void): void;
on(obj: ADODB.Connection, event: 'InfoMessage' | 'CommitTransComplete' | 'RollbackTransComplete' | 'ConnectComplete', argNames: ['pError', 'adStatus', 'pConnection'], handler: (
this: ADODB.Connection, parameter: {
pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, pConnection: ADODB.Connection}) => void): void;
on(obj: ADODB.Connection, event: 'WillConnect', argNames: ['ConnectionString', 'UserID', 'Password', 'Options', 'adStatus', 'pConnection'], handler: (
this: ADODB.Connection, parameter: {
ConnectionString: string, UserID: string, Password: string, Options: number, adStatus: ADODB.EventStatusEnum, pConnection: ADODB.Connection}) => void): void;
on(obj: ADODB.Connection, event: 'WillExecute', argNames: ['Source', 'CursorType', 'LockType', 'Options', 'adStatus', 'pCommand', 'pRecordset', 'pConnection'], handler: (
this: ADODB.Connection, parameter: {
Source: string, CursorType: ADODB.CursorTypeEnum, LockType: ADODB.LockTypeEnum, Options: number, adStatus: ADODB.EventStatusEnum, pCommand: ADODB.Command,
pRecordset: ADODB.Recordset, pConnection: ADODB.Connection}) => void): void;
on(obj: ADODB.Recordset, event: 'EndOfRecordset', argNames: ['fMoreData', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {
fMoreData: boolean, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'FetchComplete', argNames: ['pError', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {
pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'FetchProgress', argNames: ['Progress', 'MaxProgress', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {
Progress: number, MaxProgress: number, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'FieldChangeComplete', argNames: ['cFields', 'Fields', 'pError', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {
cFields: number, Fields: any, pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'RecordChangeComplete', argNames: ['adReason', 'cRecords', 'pError', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {
adReason: ADODB.EventReasonEnum, cRecords: number, pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'RecordsetChangeComplete' | 'MoveComplete', argNames: ['adReason', 'pError', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {
adReason: ADODB.EventReasonEnum, pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'WillChangeField', argNames: ['cFields', 'Fields', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {
cFields: number, Fields: any, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'WillChangeRecord', argNames: ['adReason', 'cRecords', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {
adReason: ADODB.EventReasonEnum, cRecords: number, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void;
on(obj: ADODB.Recordset, event: 'WillChangeRecordset' | 'WillMove', argNames: ['adReason', 'adStatus', 'pRecordset'], handler: (
this: ADODB.Recordset, parameter: {
adReason: ADODB.EventReasonEnum, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void;
set(obj: ADODB.Recordset, propertyName: 'Collect', parameterTypes: [any], newValue: any): void;
new(progid: 'ADODB.Command'): ADODB.Command;
new(progid: 'ADODB.Connection'): ADODB.Connection;
new(progid: 'ADODB.Parameter'): ADODB.Parameter;
new(progid: 'ADODB.Record'): ADODB.Record;
new(progid: 'ADODB.Recordset'): ADODB.Recordset;
new(progid: 'ADODB.Stream'): ADODB.Stream;
}
interface EnumeratorConstructor {
new(col: ADODB.Errors): ADODB.Error;
new(col: ADODB.Fields): ADODB.Field;
new(col: ADODB.Parameters): ADODB.Parameter;
new(col: ADODB.Properties): ADODB.Property;
}

View File

@ -0,0 +1 @@
{ "dependencies": { "activex-helpers": "*"}}

View File

@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strict": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-adodb-tests.ts"
]
}

View File

@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@ -1,18 +0,0 @@
//open connection to an Excel file
var pathToExcelFile = 'C:\\path\\to\\excel\\file.xlsx';
var conn = new ActiveXObject('ADODB.Connection');
conn.Provider = 'Microsoft.ACE.OLEDB.12.0';
conn.ConnectionString =
'Data Source="' + pathToExcelFile + '";' +
'Extended Properties="Excel 12.0;HDR=Yes"';
conn.Open();
//create a Command to access the data
var cmd = new ActiveXObject('ADODB.Command');
cmd.CommandText = 'SELECT DISTINCT LastName, CityName FROM [Sheet1$]';
//get a Recordset
var rs = cmd.Execute();
//build a string from the Recordset
var s = rs.GetString(ADODB.StringFormatEnum.adClipString, -1, '\t', '\n', '(NULL)');
rs.Close();
WScript.Echo(s);

View File

@ -1,205 +0,0 @@
// Type definitions for Microsoft Scripting Runtime
// Project: https://msdn.microsoft.com/en-us/library/bstcxhf7.aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace Scripting {
//Enums
const enum CompareMethod {
BinaryCompare = 0,
DatabaseCompare = 2,
TextCompare = 1
}
const enum DriveTypeConst {
CDRom = 4,
Fixed = 2,
RamDisk = 5,
Remote = 3,
Removable = 1,
UnknownType = 0
}
const enum FileAttribute {
Alias = 1024,
Archive = 32,
Compressed = 2048,
Directory = 16,
Hidden = 2,
Normal = 0,
ReadOnly = 1,
System = 4,
Volume = 8
}
const enum IOMode {
ForAppending = 8,
ForReading = 1,
ForWriting = 2
}
const enum SpecialFolderConst {
SystemFolder = 1,
TemporaryFolder = 2,
WindowsFolder = 0
}
const enum StandardStreamTypes {
StdErr = 2,
StdIn = 0,
StdOut = 1
}
const enum Tristate {
TristateFalse = 0,
TristateMixed = -2,
TristateTrue = -1,
TristateUseDefault = -2
}
//Interfaces
interface Dictionary {
Add: (Key: any, Item: any) => void;
CompareMode: CompareMethod;
Count: number;
Exists: (Key: any) => boolean;
HashVal: (Key: any) => any;
Item: (Key: any) => any; //Also has setter with parameters
Items: () => any;
Key: (Key: any) => any;
Keys: () => any;
Remove: (Key: any) => void;
RemoveAll: () => void;
}
interface Drive {
AvailableSpace: any;
DriveLetter: string;
DriveType: DriveTypeConst;
FileSystem: string;
FreeSpace: any;
IsReady: boolean;
Path: string;
RootFolder: Folder;
SerialNumber: number;
ShareName: string;
TotalSize: any;
VolumeName: string;
}
interface Drives {
Count: number;
Item: (Key: any) => Drive;
}
interface Encoder {
EncodeScriptFile: (szExt: string, bstrStreamIn: string, cFlags: number, bstrDefaultLang: string) => string;
}
interface File {
Attributes: FileAttribute;
Copy: (Destination: string, OverWriteFiles?: boolean) => void;
DateCreated: VarDate;
DateLastAccessed: VarDate;
DateLastModified: VarDate;
Delete: (Force?: boolean) => void;
Drive: Drive;
Move: (Destination: string) => void;
Name: string;
OpenAsTextStream: (IOMode?: IOMode, Format?: Tristate) => TextStream;
ParentFolder: Folder;
Path: string;
ShortName: string;
ShortPath: string;
Size: any;
Type: string;
}
interface Files {
Count: number;
Item: (Key: any) => File;
}
interface FileSystemObject {
BuildPath: (Path: string, Name: string) => string;
CopyFile: (Source: string, Destination: string, OverWriteFiles?: boolean) => void;
CopyFolder: (Source: string, Destination: string, OverWriteFiles?: boolean) => void;
CreateFolder: (Path: string) => Folder;
CreateTextFile: (FileName: string, Overwrite?: boolean, Unicode?: boolean) => TextStream;
DeleteFile: (FileSpec: string, Force?: boolean) => void;
DeleteFolder: (FolderSpec: string, Force?: boolean) => void;
DriveExists: (DriveSpec: string) => boolean;
Drives: Drives;
FileExists: (FileSpec: string) => boolean;
FolderExists: (FolderSpec: string) => boolean;
GetAbsolutePathName: (Path: string) => string;
GetBaseName: (Path: string) => string;
GetDrive: (DriveSpec: string) => Drive;
GetDriveName: (Path: string) => string;
GetExtensionName: (Path: string) => string;
GetFile: (FilePath: string) => File;
GetFileName: (Path: string) => string;
GetFileVersion: (FileName: string) => string;
GetFolder: (FolderPath: string) => Folder;
GetParentFolderName: (Path: string) => string;
GetSpecialFolder: (SpecialFolder: SpecialFolderConst) => Folder;
GetStandardStream: (StandardStreamType: StandardStreamTypes, Unicode?: boolean) => TextStream;
GetTempName: () => string;
MoveFile: (Source: string, Destination: string) => void;
MoveFolder: (Source: string, Destination: string) => void;
OpenTextFile: (FileName: string, IOMode?: IOMode, Create?: boolean, Format?: Tristate) => TextStream;
}
interface Folder {
Attributes: FileAttribute;
Copy: (Destination: string, OverWriteFiles?: boolean) => void;
CreateTextFile: (FileName: string, Overwrite?: boolean, Unicode?: boolean) => TextStream;
DateCreated: VarDate;
DateLastAccessed: VarDate;
DateLastModified: VarDate;
Delete: (Force?: boolean) => void;
Drive: Drive;
Files: Files;
IsRootFolder: boolean;
Move: (Destination: string) => void;
Name: string;
ParentFolder: Folder;
Path: string;
ShortName: string;
ShortPath: string;
Size: any;
SubFolders: Folders;
Type: string;
}
interface Folders {
Add: (Name: string) => Folder;
Count: number;
Item: (Key: any) => Folder;
}
interface TextStream {
AtEndOfLine: boolean;
AtEndOfStream: boolean;
Close: () => void;
Column: number;
Line: number;
Read: (Characters: number) => string;
ReadAll: () => string;
ReadLine: () => string;
Skip: (Characters: number) => void;
SkipLine: () => void;
Write: (Text: string) => void;
WriteBlankLines: (Lines: number) => void;
WriteLine: (Text?: string) => void;
}
}
interface ActiveXObject {
new (progID: 'Scripting.Dictionary'): Scripting.Dictionary;
new (progID: 'Scripting.FileSystemObject'): Scripting.FileSystemObject;
new (progID: 'Scripting.Encoder'): Scripting.Encoder;
}

View File

@ -1,8 +1,7 @@
//source -- https://msdn.microsoft.com/en-us/library/ebkhfaaz.aspx
// source -- https://msdn.microsoft.com/en-us/library/ebkhfaaz.aspx
//Generates a string describing the drive type of a given Drive object.
var showDriveType = (drive: Scripting.Drive) => {
// Generates a string describing the drive type of a given Drive object.
let showDriveType = (drive: Scripting.Drive) => {
switch (drive.DriveType) {
case Scripting.DriveTypeConst.Removable:
return 'Removeable';
@ -19,14 +18,13 @@ var showDriveType = (drive: Scripting.Drive) => {
}
};
//Generates a string describing the attributes of a file or folder.
var showFileAttributes = (file: Scripting.File) => {
var attr = file.Attributes;
// Generates a string describing the attributes of a file or folder.
let showFileAttributes = (file: Scripting.File) => {
let attr = file.Attributes;
if (attr === 0) {
return 'Normal';
}
var attributeStrings: string[] = [];
let attributeStrings: string[] = [];
if (attr & Scripting.FileAttribute.Directory) { attributeStrings.push('Directory'); }
if (attr & Scripting.FileAttribute.ReadOnly) { attributeStrings.push('Read-only'); }
if (attr & Scripting.FileAttribute.Hidden) { attributeStrings.push('Hidden'); }
@ -38,24 +36,22 @@ var showFileAttributes = (file: Scripting.File) => {
return attributeStrings.join(',');
};
//source --https://msdn.microsoft.com/en-us/library/ts2t8ybh(v=vs.84).aspx
var showFreeSpace = (drvPath: string) => {
var fso = new ActiveXObject('Scripting.FileSystemObject');
var d = fso.GetDrive(fso.GetDriveName(drvPath));
var s = 'Drive ' + drvPath + ' - ';
// source --https://msdn.microsoft.com/en-us/library/ts2t8ybh(v=vs.84).aspx
let showFreeSpace = (drvPath: string) => {
let fso = new ActiveXObject('Scripting.FileSystemObject');
let d = fso.GetDrive(fso.GetDriveName(drvPath));
let s = 'Drive ' + drvPath + ' - ';
s += d.VolumeName + '<br>';
s += 'Free Space: ' + d.FreeSpace / 1024 + ' Kbytes';
return (s);
};
// source -- https://msdn.microsoft.com/en-us/library/kaf6yaft(v=vs.84).aspx
let getALine = (filespec: string) => {
let fso = new ActiveXObject('Scripting.FileSystemObject');
let file = fso.OpenTextFile(filespec, Scripting.IOMode.ForReading, false);
//source -- https://msdn.microsoft.com/en-us/library/kaf6yaft(v=vs.84).aspx
var getALine = (filespec: string) => {
var fso = new ActiveXObject('Scripting.FileSystemObject');
var file = fso.OpenTextFile(filespec, Scripting.IOMode.ForReading, false);
var s = '';
let s = '';
while (!file.AtEndOfLine) {
s += file.Read(1);
}

465
types/activex-scripting/index.d.ts vendored Normal file
View File

@ -0,0 +1,465 @@
// Type definitions for Microsoft Scripting Runtime 1.0
// Project: https://msdn.microsoft.com/en-us/library/bstcxhf7.aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace Scripting {
const enum CompareMethod {
BinaryCompare = 0,
DatabaseCompare = 2,
TextCompare = 1
}
const enum DriveTypeConst {
CDRom = 4,
Fixed = 2,
RamDisk = 5,
Remote = 3,
Removable = 1,
UnknownType = 0
}
const enum FileAttribute {
Alias = 1024,
Archive = 32,
Compressed = 2048,
Directory = 16,
Hidden = 2,
Normal = 0,
ReadOnly = 1,
System = 4,
Volume = 8
}
const enum IOMode {
ForAppending = 8,
ForReading = 1,
ForWriting = 2
}
const enum SpecialFolderConst {
SystemFolder = 1,
TemporaryFolder = 2,
WindowsFolder = 0
}
const enum StandardStreamTypes {
StdErr = 2,
StdIn = 0,
StdOut = 1
}
const enum Tristate {
TristateFalse = 0,
TristateMixed = -2,
TristateTrue = -1,
TristateUseDefault = -2
}
/** Scripting.Dictionary */
interface Dictionary {
/** Add a new key and item to the dictionary. */
Add(Key: any, Item: any): void;
/** Set or get the string comparison method. */
CompareMode: CompareMethod;
/** Get the number of items in the dictionary. */
readonly Count: number;
/** Determine if a given key is in the dictionary. */
Exists(Key: any): boolean;
HashVal(Key: any): any;
/** Set or get the item for a given key */
Item(Key: any): any;
/** Get an array containing all items in the dictionary. */
Items(): any;
/** Change a key to a different key. */
Key(Key: any): any;
/** Get an array containing all keys in the dictionary. */
Keys(): any;
/** Remove a given key from the dictionary. */
Remove(Key: any): void;
/** Remove all information from the dictionary. */
RemoveAll(): void;
}
/** Drive Object */
interface Drive {
/** Get available space */
readonly AvailableSpace: any;
/** Drive letter */
readonly DriveLetter: string;
/** Drive type */
readonly DriveType: DriveTypeConst;
/** Filesystem type */
readonly FileSystem: string;
/** Get drive free space */
readonly FreeSpace: any;
/** Check if disk is available */
readonly IsReady: boolean;
/** Path */
readonly Path: string;
/** Root folder */
readonly RootFolder: Folder;
/** Serial number */
readonly SerialNumber: number;
/** Share name */
readonly ShareName: string;
/** Get total drive size */
readonly TotalSize: any;
/** Name of volume */
VolumeName: string;
}
/** Collection of drives associated with drive letters */
interface Drives {
/** Number of drives */
readonly Count: number;
/** Get drive */
Item(Key: any): Drive;
}
/** Script Encoder Object */
interface Encoder {
/** Call the Encoder determined by szExt, passing bstrStreamIn and optional arguments */
EncodeScriptFile(szExt: string, bstrStreamIn: string, cFlags: number, bstrDefaultLang: string): string;
}
/** File object */
interface File {
/** File attributes */
Attributes: FileAttribute;
/**
* Copy this file
* @param boolean [OverWriteFiles=true]
*/
Copy(Destination: string, OverWriteFiles?: boolean): void;
/** Date file was created */
readonly DateCreated: VarDate;
/** Date file was last accessed */
readonly DateLastAccessed: VarDate;
/** Date file was last modified */
readonly DateLastModified: VarDate;
/**
* Delete this file
* @param boolean [Force=false]
*/
Delete(Force?: boolean): void;
/** Get drive that contains file */
readonly Drive: Drive;
/** Move this file */
Move(Destination: string): void;
/** Get name of file */
Name: string;
/**
* Open a file as a TextStream
* @param Scripting.IOMode [IOMode=1]
* @param Scripting.Tristate [Format=0]
*/
OpenAsTextStream(IOMode?: IOMode, Format?: Tristate): TextStream;
/** Get folder that contains file */
readonly ParentFolder: Folder;
/** Path to the file */
readonly Path: string;
/** Short name */
readonly ShortName: string;
/** Short path */
readonly ShortPath: string;
/** File size */
readonly Size: any;
/** Type description */
readonly Type: string;
}
/** Collection of files in a folder */
interface Files {
/** Number of folders */
readonly Count: number;
/** Get file */
Item(Key: any): File;
}
/** FileSystem Object */
interface FileSystemObject {
/** Generate a path from an existing path and a name */
BuildPath(Path: string, Name: string): string;
/**
* Copy a file
* @param boolean [OverWriteFiles=true]
*/
CopyFile(Source: string, Destination: string, OverWriteFiles?: boolean): void;
/**
* Copy a folder
* @param boolean [OverWriteFiles=true]
*/
CopyFolder(Source: string, Destination: string, OverWriteFiles?: boolean): void;
/** Create a folder */
CreateFolder(Path: string): Folder;
/**
* Create a file as a TextStream
* @param boolean [Overwrite=true]
* @param boolean [Unicode=false]
*/
CreateTextFile(FileName: string, Overwrite?: boolean, Unicode?: boolean): TextStream;
/**
* Delete a file
* @param boolean [Force=false]
*/
DeleteFile(FileSpec: string, Force?: boolean): void;
/**
* Delete a folder
* @param boolean [Force=false]
*/
DeleteFolder(FolderSpec: string, Force?: boolean): void;
/** Check if a drive or a share exists */
DriveExists(DriveSpec: string): boolean;
/** Get drives collection */
readonly Drives: Drives;
/** Check if a file exists */
FileExists(FileSpec: string): boolean;
/** Check if a path exists */
FolderExists(FolderSpec: string): boolean;
/** Return the canonical representation of the path */
GetAbsolutePathName(Path: string): string;
/** Return base name from a path */
GetBaseName(Path: string): string;
/** Get drive or UNC share */
GetDrive(DriveSpec: string): Drive;
/** Return drive from a path */
GetDriveName(Path: string): string;
/** Return extension from path */
GetExtensionName(Path: string): string;
/** Get file */
GetFile(FilePath: string): File;
/** Return the file name from a path */
GetFileName(Path: string): string;
/** Retrieve the file version of the specified file into a string */
GetFileVersion(FileName: string): string;
/** Get folder */
GetFolder(FolderPath: string): Folder;
/** Return path to the parent folder */
GetParentFolderName(Path: string): string;
/** Get location of various system folders */
GetSpecialFolder(SpecialFolder: SpecialFolderConst): Folder;
/**
* Retrieve the standard input, output or error stream
* @param boolean [Unicode=false]
*/
GetStandardStream(StandardStreamType: StandardStreamTypes, Unicode?: boolean): TextStream;
/** Generate name that can be used to name a temporary file */
GetTempName(): string;
/** Move a file */
MoveFile(Source: string, Destination: string): void;
/** Move a folder */
MoveFolder(Source: string, Destination: string): void;
/**
* Open a file as a TextStream
* @param Scripting.IOMode [IOMode=1]
* @param boolean [Create=false]
* @param Scripting.Tristate [Format=0]
*/
OpenTextFile(FileName: string, IOMode?: IOMode, Create?: boolean, Format?: Tristate): TextStream;
}
/** Folder object */
interface Folder {
/** Folder attributes */
Attributes: FileAttribute;
/**
* Copy this folder
* @param boolean [OverWriteFiles=true]
*/
Copy(Destination: string, OverWriteFiles?: boolean): void;
/**
* Create a file as a TextStream
* @param boolean [Overwrite=true]
* @param boolean [Unicode=false]
*/
CreateTextFile(FileName: string, Overwrite?: boolean, Unicode?: boolean): TextStream;
/** Date folder was created */
readonly DateCreated: VarDate;
/** Date folder was last accessed */
readonly DateLastAccessed: VarDate;
/** Date folder was last modified */
readonly DateLastModified: VarDate;
/**
* Delete this folder
* @param boolean [Force=false]
*/
Delete(Force?: boolean): void;
/** Get drive that contains folder */
readonly Drive: Drive;
/** Get files collection */
readonly Files: Files;
/** True if folder is root */
readonly IsRootFolder: boolean;
/** Move this folder */
Move(Destination: string): void;
/** Get name of folder */
Name: string;
/** Get parent folder */
readonly ParentFolder: Folder;
/** Path to folder */
readonly Path: string;
/** Short name */
readonly ShortName: string;
/** Short path */
readonly ShortPath: string;
/** Sum of files and subfolders */
readonly Size: any;
/** Get folders collection */
readonly SubFolders: Folders;
/** Type description */
readonly Type: string;
}
/** Collection of subfolders in a folder */
interface Folders {
/** Create a new folder */
Add(Name: string): Folder;
/** Number of folders */
readonly Count: number;
/** Get folder */
Item(Key: any): Folder;
}
/** TextStream object */
interface TextStream {
/** Is the current position at the end of a line? */
readonly AtEndOfLine: boolean;
/** Is the current position at the end of the stream? */
readonly AtEndOfStream: boolean;
/** Close a text stream */
Close(): void;
/** Current column number */
readonly Column: number;
/** Current line number */
readonly Line: number;
/** Read a specific number of characters into a string */
Read(Characters: number): string;
/** Read the entire stream into a string */
ReadAll(): string;
/** Read an entire line into a string */
ReadLine(): string;
/** Skip a specific number of characters */
Skip(Characters: number): void;
/** Skip a line */
SkipLine(): void;
/** Write a string to the stream */
Write(Text: string): void;
/** Write a number of blank lines to the stream */
WriteBlankLines(Lines: number): void;
/**
* Write a string and an end of line to the stream
* @param string [Text='']
*/
WriteLine(Text?: string): void;
}
}
interface ActiveXObject {
set(obj: Scripting.Dictionary, propertyName: 'Item', parameterTypes: [any], newValue: any): void;
new(progid: 'Scripting.Dictionary'): Scripting.Dictionary;
new(progid: 'Scripting.Encoder'): Scripting.Encoder;
new(progid: 'Scripting.FileSystemObject'): Scripting.FileSystemObject;
}
interface EnumeratorConstructor {
new(col: Scripting.Dictionary): any;
new(col: Scripting.Drives): Scripting.Drive;
new(col: Scripting.Files): Scripting.File;
new(col: Scripting.Folders): Scripting.Folder;
}

View File

@ -0,0 +1 @@
{ "dependencies": { "activex-helpers": "*"}}

View File

@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strict": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-scripting-tests.ts"
]
}

View File

@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@ -1,31 +1,43 @@
//source -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms630826(v=vs.85).aspx
// source -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms630826(v=vs.85).aspx
// Convert a file
let commonDialog = new ActiveXObject('WIA.CommonDialog');
let img = commonDialog.ShowAcquireImage();
//Convert a file
var commonDialog = new ActiveXObject('WIA.CommonDialog');
var img = commonDialog.ShowAcquireImage();
if (img.FormatID !== WIA.FormatID.wiaFormatJPEG) {
var ip = new ActiveXObject('WIA.ImageProcess');
// when DefinitelyTyped supports Typescript 2.4 -- end of July 2017, replace these:
let jpegFormatID = '{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}';
if (img.FormatID !== jpegFormatID) {
let ip = new ActiveXObject('WIA.ImageProcess');
ip.Filters.Add(ip.FilterInfos.Item('Convert').FilterID);
ip.Filters.Item(1).Properties.Item('FormatID').Value = jpegFormatID;
img = ip.Apply(img);
}
// with this:
/*if (img.FormatID !== WIA.FormatID.wiaFormatJPEG) {
let ip = new ActiveXObject('WIA.ImageProcess');
ip.Filters.Add(ip.FilterInfos.Item('Convert').FilterID);
ip.Filters.Item(1).Properties.Item('FormatID').Value = WIA.FormatID.wiaFormatJPEG;
img = ip.Apply(img);
}
}*/
//Take a picture
var dev = commonDialog.ShowSelectDevice();
// Take a picture
let dev = commonDialog.ShowSelectDevice();
if (dev.Type === WIA.WiaDeviceType.CameraDeviceType) {
var itm = dev.ExecuteCommand(WIA.CommandID.wiaCommandTakePicture);
// when DefinitelyTyped supports Typescript 2.4 -- end of July 2017, replace these:
let commandID = '{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}';
let itm = dev.ExecuteCommand(commandID);
// with this:
// let itm = dev.ExecuteCommand(WIA.CommandID.wiaCommandTakePicture);
}
//Display detailed property information
// Display detailed property information
dev = commonDialog.ShowSelectDevice();
var e = new Enumerator<WIA.Property>(dev.Properties); //no foreach over ActiveX collections
let e = new Enumerator<WIA.Property>(dev.Properties); // no foreach over ActiveX collections
e.moveFirst();
while (!e.atEnd()) {
var p = e.item();
var s = p.Name + ' (' + p.PropertyID + ') = ';
let p = e.item();
let s = p.Name + ' (' + p.PropertyID + ') = ';
if (p.IsVector) {
s += '[vector of data]';
} else {
@ -48,8 +60,8 @@ while (!e.atEnd()) {
} else {
s += ' [valid values include: ';
}
var count = p.SubTypeValues.Count;
for (var i = 1; i <= count; i++) {
let count = p.SubTypeValues.Count;
for (let i = 1; i <= count; i++) {
s += p.SubTypeValues.Item(i);
if (i < count) {
s += ', ';
@ -63,9 +75,5 @@ while (!e.atEnd()) {
}
}
if (WScript) {
WScript.Echo(s);
} else if (window) {
window.alert(s);
}
}
WScript.Echo(s);
}

759
types/activex-wia/index.d.ts vendored Normal file
View File

@ -0,0 +1,759 @@
// Type definitions for Windows Image Acquisition 2.0
// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/ms630368(v=vs.85).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Typescript Version: 2.4
declare namespace WIA {
/** String versions of globally unique identifiers (GUIDs) that identify common Device and Item commands. */
// uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017)
/*const enum CommandID {
wiaCommandChangeDocument = '{04E725B0-ACAE-11D2-A093-00C04F72DC3C}',
wiaCommandDeleteAllItems = '{E208C170-ACAD-11D2-A093-00C04F72DC3C}',
wiaCommandSynchronize = '{9B26B7B2-ACAD-11D2-A093-00C04F72DC3C}',
wiaCommandTakePicture = '{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}',
wiaCommandUnloadDocument = '{1F3B3D8E-ACAE-11D2-A093-00C04F72DC3C}'
}*/
/** String versions of globally unique identifiers (GUIDs) that identify DeviceManager events. */
// uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017)
/*const enum EventID {
wiaEventDeviceConnected = '{A28BBADE-64B6-11D2-A231-00C04FA31809}',
wiaEventDeviceDisconnected = '{143E4E83-6497-11D2-A231-00C04FA31809}',
wiaEventItemCreated = '{4C8F4EF5-E14F-11D2-B326-00C04F68CE61}',
wiaEventItemDeleted = '{1D22A559-E14F-11D2-B326-00C04F68CE61}',
wiaEventScanEmailImage = '{C686DCEE-54F2-419E-9A27-2FC7F2E98F9E}',
wiaEventScanFaxImage = '{C00EB793-8C6E-11D2-977A-0000F87A926F}',
wiaEventScanFilmImage = '{9B2B662C-6185-438C-B68B-E39EE25E71CB}',
wiaEventScanImage = '{A6C5A715-8C6E-11D2-977A-0000F87A926F}',
wiaEventScanImage2 = '{FC4767C1-C8B3-48A2-9CFA-2E90CB3D3590}',
wiaEventScanImage3 = '{154E27BE-B617-4653-ACC5-0FD7BD4C65CE}',
wiaEventScanImage4 = '{A65B704A-7F3C-4447-A75D-8A26DFCA1FDF}',
wiaEventScanOCRImage = '{9D095B89-37D6-4877-AFED-62A297DC6DBE}',
wiaEventScanPrintImage = '{B441F425-8C6E-11D2-977A-0000F87A926F}'
}*/
/** String versions of globally unique identifiers (GUIDs) that indicate the file format of an image. */
// uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017)
/*const enum FormatID {
wiaFormatBMP = '{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}',
wiaFormatGIF = '{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}',
wiaFormatJPEG = '{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}',
wiaFormatPNG = '{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}',
wiaFormatTIFF = '{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}'
}*/
/** Miscellaneous string constants */
// uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017)
/*const enum Miscellaneous {
wiaAnyDeviceID = '*',
wiaIDUnknown = '{00000000-0000-0000-0000-000000000000}'
}*/
/**
* The WiaDeviceType enumeration specifies the type of device attached to a user's computer. Use the Type property on the DeviceInfo object or the Device
* object to obtain these values from the device.
*/
const enum WiaDeviceType {
CameraDeviceType = 2,
ScannerDeviceType = 1,
UnspecifiedDeviceType = 0,
VideoDeviceType = 3
}
/**
* A DeviceEvent's type is composed of bits from the WiaEventFlags enumeration. You can test a DeviceEvent's type by using the AND operation with DeviceEv
* ent.Type and a member from the WiaEventFlags enumeration.
*/
const enum WiaEventFlag {
ActionEvent = 2,
NotificationEvent = 1
}
/** The WiaImageBias enumeration helps specify what type of data the image is intended to represent. */
const enum WiaImageBias {
MaximizeQuality = 131072,
MinimizeSize = 65536
}
/** The WiaImageIntent enumeration helps specify what type of data the image is intended to represent. */
const enum WiaImageIntent {
ColorIntent = 1,
GrayscaleIntent = 2,
TextIntent = 4,
UnspecifiedIntent = 0
}
/**
* The WiaImagePropertyType enumeration specifies the type of the value of an image property. Image properties can be found in the Properties collection o
* f an ImageFile object.
*/
const enum WiaImagePropertyType {
ByteImagePropertyType = 1001,
LongImagePropertyType = 1004,
RationalImagePropertyType = 1006,
StringImagePropertyType = 1002,
UndefinedImagePropertyType = 1000,
UnsignedIntegerImagePropertyType = 1003,
UnsignedLongImagePropertyType = 1005,
UnsignedRationalImagePropertyType = 1007,
VectorOfBytesImagePropertyType = 1101,
VectorOfLongsImagePropertyType = 1103,
VectorOfRationalsImagePropertyType = 1105,
VectorOfUndefinedImagePropertyType = 1100,
VectorOfUnsignedIntegersImagePropertyType = 1102,
VectorOfUnsignedLongsImagePropertyType = 1104,
VectorOfUnsignedRationalsImagePropertyType = 1106
}
/**
* An Item's type is composed of bits from the WiaItemFlags enumeration. You can test an Item's type by using the AND operation with Item.Properties("Item
* Flags") and a member from the WiaItemFlags enumeration.
*/
const enum WiaItemFlag {
AnalyzeItemFlag = 16,
AudioItemFlag = 32,
BurstItemFlag = 2048,
DeletedItemFlag = 128,
DeviceItemFlag = 64,
DisconnectedItemFlag = 256,
FileItemFlag = 2,
FolderItemFlag = 4,
FreeItemFlag = 0,
GeneratedItemFlag = 16384,
HasAttachmentsItemFlag = 32768,
HPanoramaItemFlag = 512,
ImageItemFlag = 1,
RemovedItemFlag = -2147483648,
RootItemFlag = 8,
StorageItemFlag = 4096,
TransferItemFlag = 8192,
VideoItemFlag = 65536,
VPanoramaItemFlag = 1024
}
/**
* The WiaPropertyType enumeration specifies the type of the value of an item property. Item properties can be found in the Properties collection of a Dev
* ice or Item object.
*/
const enum WiaPropertyType {
BooleanPropertyType = 1,
BytePropertyType = 2,
ClassIDPropertyType = 15,
CurrencyPropertyType = 12,
DatePropertyType = 13,
DoublePropertyType = 11,
ErrorCodePropertyType = 7,
FileTimePropertyType = 14,
HandlePropertyType = 18,
IntegerPropertyType = 3,
LargeIntegerPropertyType = 8,
LongPropertyType = 5,
ObjectPropertyType = 17,
SinglePropertyType = 10,
StringPropertyType = 16,
UnsignedIntegerPropertyType = 4,
UnsignedLargeIntegerPropertyType = 9,
UnsignedLongPropertyType = 6,
UnsupportedPropertyType = 0,
VariantPropertyType = 19,
VectorOfBooleansPropertyType = 101,
VectorOfBytesPropertyType = 102,
VectorOfClassIDsPropertyType = 115,
VectorOfCurrenciesPropertyType = 112,
VectorOfDatesPropertyType = 113,
VectorOfDoublesPropertyType = 111,
VectorOfErrorCodesPropertyType = 107,
VectorOfFileTimesPropertyType = 114,
VectorOfIntegersPropertyType = 103,
VectorOfLargeIntegersPropertyType = 108,
VectorOfLongsPropertyType = 105,
VectorOfSinglesPropertyType = 110,
VectorOfStringsPropertyType = 116,
VectorOfUnsignedIntegersPropertyType = 104,
VectorOfUnsignedLargeIntegersPropertyType = 109,
VectorOfUnsignedLongsPropertyType = 106,
VectorOfVariantsPropertyType = 119
}
/**
* The WiaSubType enumeration specifies more detail about the property value. Use the SubType property on the Property object to obtain these values for t
* he property.
*/
const enum WiaSubType {
FlagSubType = 3,
ListSubType = 2,
RangeSubType = 1,
UnspecifiedSubType = 0
}
/**
* The CommonDialog control is an invisible-at-runtime control that contains all the methods that display a User Interface. A CommonDialog control can be
* created using "WIA.CommonDialog" in a call to CreateObject or by dropping a CommonDialog on a form.
*/
interface CommonDialog {
/**
* Displays one or more dialog boxes that enable the user to acquire an image from a hardware device for image acquisition and returns an ImageFile object
* on success, otherwise Nothing
* @param WIA.WiaDeviceType [DeviceType=0]
* @param WIA.WiaImageIntent [Intent=0]
* @param WIA.WiaImageBias [Bias=131072]
* @param string [FormatID='{00000000-0000-0000-0000-000000000000}']
* @param boolean [AlwaysSelectDevice=false]
* @param boolean [UseCommonUI=true]
* @param boolean [CancelError=false]
*/
ShowAcquireImage(
DeviceType?: WiaDeviceType, Intent?: WiaImageIntent, Bias?: WiaImageBias, FormatID?: string, AlwaysSelectDevice?: boolean, UseCommonUI?: boolean, CancelError?: boolean): ImageFile;
/** Launches the Windows Scanner and Camera Wizard and returns Nothing. Future versions may return a collection of ImageFile objects. */
ShowAcquisitionWizard(Device: Device): any;
/**
* Displays the properties dialog box for the specified Device
* @param boolean [CancelError=false]
*/
ShowDeviceProperties(Device: Device, CancelError?: boolean): void;
/**
* Displays the properties dialog box for the specified Item
* @param boolean [CancelError=false]
*/
ShowItemProperties(Item: Item, CancelError?: boolean): void;
/** Launches the Photo Printing Wizard with the absolute path of a specific file or Vector of absolute paths to files */
ShowPhotoPrintingWizard(Files: any): void;
/**
* Displays a dialog box that enables the user to select a hardware device for image acquisition. Returns the selected Device object on success, otherwise
* Nothing
* @param WIA.WiaDeviceType [DeviceType=0]
* @param boolean [AlwaysSelectDevice=false]
* @param boolean [CancelError=false]
*/
ShowSelectDevice(DeviceType?: WiaDeviceType, AlwaysSelectDevice?: boolean, CancelError?: boolean): Device;
/**
* Displays a dialog box that enables the user to select an item for transfer from a hardware device for image acquisition. Returns the selection as an It
* ems collection on success, otherwise Nothing
* @param WIA.WiaImageIntent [Intent=0]
* @param WIA.WiaImageBias [Bias=131072]
* @param boolean [SingleSelect=true]
* @param boolean [UseCommonUI=true]
* @param boolean [CancelError=false]
*/
ShowSelectItems(Device: Device, Intent?: WiaImageIntent, Bias?: WiaImageBias, SingleSelect?: boolean, UseCommonUI?: boolean, CancelError?: boolean): Items;
/**
* Displays a progress dialog box while transferring the specified Item to the local machine. See Item.Transfer for additional information.
* @param string [FormatID='{00000000-0000-0000-0000-000000000000}']
* @param boolean [CancelError=false]
*/
ShowTransfer(Item: Item, FormatID?: string, CancelError?: boolean): any;
}
/** The Device object represents an active connection to an imaging device. */
interface Device {
/** A collection of all commands for this imaging device */
readonly Commands: DeviceCommands;
/** Returns the DeviceID for this Device */
readonly DeviceID: string;
/** A collection of all events for this imaging device */
readonly Events: DeviceEvents;
/**
* Issues the command specified by CommandID to the imaging device. CommandIDs are device dependent. Valid CommandIDs for this Device are contained in the
* Commands collection.
*/
ExecuteCommand(CommandID: string): Item;
/** Returns the Item object specified by ItemID if it exists */
GetItem(ItemID: string): Item;
/** A collection of all items for this imaging device */
readonly Items: Items;
/** A collection of all properties for this imaging device */
readonly Properties: Properties;
/** Returns the Type of Device */
readonly Type: WiaDeviceType;
/** Returns the underlying IWiaItem interface for this Device object */
readonly WiaItem: any;
}
/** The DeviceCommand object describes a CommandID that can be used when calling ExecuteCommand on a Device or Item object. */
interface DeviceCommand {
/** Returns the commandID for this Command */
readonly CommandID: string;
/** Returns the command Description */
readonly Description: string;
/** Returns the command Name */
readonly Name: string;
}
/**
* The DeviceCommands object is a collection of all the supported DeviceCommands for an imaging device. See the Commands property of a Device or Item obje
* ct for more details on determining the collection of supported device commands.
*/
interface DeviceCommands {
/** Returns the number of members in the collection */
readonly Count: number;
/** Returns the specified item in the collection by position */
Item(Index: number): DeviceCommand;
}
/** The DeviceEvent object describes an EventID that can be used when calling RegisterEvent or RegisterPersistentEvent on a DeviceManager object. */
interface DeviceEvent {
/** Returns the event Description */
readonly Description: string;
/** Returns the EventID for this Event */
readonly EventID: string;
/** Returns the event Name */
readonly Name: string;
/** Returns the Type of this Event */
readonly Type: WiaEventFlag;
}
/**
* The DeviceEvents object is a collection of all the supported DeviceEvent for an imaging device. See the Events property of a Device object for more det
* ails on determining the collection of supported device events.
*/
interface DeviceEvents {
/** Returns the number of members in the collection */
readonly Count: number;
/** Returns the specified item in the collection by position */
Item(Index: number): DeviceEvent;
}
/**
* The DeviceInfo object is a container that describes the unchanging (static) properties of an imaging device that is currently connected to the computer
* .
*/
interface DeviceInfo {
/** Establish a connection with this device and return a Device object */
Connect(): Device;
/** Returns the DeviceID for this Device */
readonly DeviceID: string;
/** A collection of all properties for this imaging device that are applicable when the device is not connected */
readonly Properties: Properties;
/** Returns the Type of Device */
readonly Type: WiaDeviceType;
}
/**
* The DeviceInfos object is a collection of all the imaging devices currently connected to the computer. See the DeviceInfos property on the DeviceManage
* r object for detail on accessing the DeviceInfos object.
*/
interface DeviceInfos {
/** Returns the number of members in the collection */
readonly Count: number;
/** Returns the specified item in the collection either by position or Device ID */
Item(Index: any): DeviceInfo;
}
/**
* The DeviceManager control is an invisible-at-runtime control that manages the imaging devices connected to the computer. A DeviceManager control can be
* created using "WIA.DeviceManager" in a call to CreateObject or by dropping a DeviceManager on a form.
*/
interface DeviceManager {
/** A collection of all imaging devices connected to this computer */
readonly DeviceInfos: DeviceInfos;
/**
* Registers the specified EventID for the specified DeviceID. If DeviceID is "*" then OnEvent will be called whenever the event specified occurs for any
* device. Otherwise, OnEvent will only be called if the event specified occurs on the device specified.
* @param string [DeviceID='*']
*/
RegisterEvent(EventID: string, DeviceID?: string): void;
/**
* Registers the specified Command to launch when the specified EventID for the specified DeviceID occurs. Command can be either a ClassID or the full pat
* h name and the appropriate command-line arguments needed to invoke the application.
* @param string [DeviceID='*']
*/
RegisterPersistentEvent(Command: string, Name: string, Description: string, Icon: string, EventID: string, DeviceID?: string): void;
/**
* Unregisters the specified EventID for the specified DeviceID. UnregisterEvent should only be called for EventID and DeviceID for which you called Regis
* terEvent.
* @param string [DeviceID='*']
*/
UnregisterEvent(EventID: string, DeviceID?: string): void;
/**
* Unregisters the specified Command for the specified EventID for the specified DeviceID. UnregisterPersistentEvent should only be called for the Command
* , Name, Description, Icon, EventID and DeviceID for which you called RegisterPersistentEvent.
* @param string [DeviceID='*']
*/
UnregisterPersistentEvent(Command: string, Name: string, Description: string, Icon: string, EventID: string, DeviceID?: string): void;
}
/**
* The Filter object represents a unit of modification on an ImageFile. To use a Filter, add it to the Filters collection, then set the filter's propertie
* s and finally use the Apply method of the ImageProcess object to filter an ImageFile.
*/
interface Filter {
/** Returns a Description of what the filter does */
readonly Description: string;
/** Returns the FilterID for this Filter */
readonly FilterID: string;
/** Returns the Filter Name */
readonly Name: string;
/** A collection of all properties for this filter */
readonly Properties: Properties;
}
/**
* The FilterInfo object is a container that describes a Filter object without requiring a Filter to be Added to the process chain. See the FilterInfos pr
* operty on the ImageProcess object for details on accessing FilterInfo objects.
*/
interface FilterInfo {
/** Returns a technical Description of what the filter does and how to use it in a filter chain */
readonly Description: string;
/** Returns the FilterID for this filter */
readonly FilterID: string;
/** Returns the FilterInfo Name */
readonly Name: string;
}
/**
* The FilterInfos object is a collection of all the available FilterInfo objects. See the FilterInfos property on the ImageProcess object for detail on a
* ccessing the FilterInfos object.
*/
interface FilterInfos {
/** Returns the number of members in the collection */
readonly Count: number;
/** Returns the specified item in the collection either by position or name */
Item(Index: any): FilterInfo;
}
/** The Filters object is a collection of the Filters that will be applied to an ImageFile when you call the Apply method on the ImageProcess object. */
interface Filters {
/**
* Appends/Inserts a new Filter of the specified FilterID into a Filter collection
* @param number [Index=0]
*/
Add(FilterID: string, Index?: number): void;
/** Returns the number of members in the collection */
readonly Count: number;
/** Returns the specified item in the collection by position or FilterID */
Item(Index: number): Filter;
/** Removes the designated filter */
Remove(Index: number): void;
}
/**
* The Formats object is a collection of supported FormatIDs that you can use when calling Transfer on an Item object or ShowTransfer on a CommonDialog ob
* ject for this Item.
*/
interface Formats {
/** Returns the number of members in the collection */
readonly Count: number;
/** Returns the specified item in the collection by position */
Item(Index: number): string;
}
/**
* The ImageFile object is a container for images transferred to your computer when you call Transfer or ShowTransfer. It also supports image files throug
* h LoadFile. An ImageFile object can be created using "WIA.ImageFile" in a call to CreateObject.
*/
interface ImageFile {
/** Returns/Sets the current frame in the image */
ActiveFrame: number;
/** Returns the raw image bits as a Vector of Long values */
readonly ARGBData: Vector;
/** Returns the raw image file as a Vector of Bytes */
readonly FileData: Vector;
/** Returns the file extension for this image file type */
readonly FileExtension: string;
/** Returns the FormatID for this file type */
readonly FormatID: string;
/** Returns the number of frames in the image */
readonly FrameCount: number;
/** Returns the Height of the image in pixels */
readonly Height: number;
/** Returns the Horizontal pixels per inch of the image */
readonly HorizontalResolution: number;
/** Indicates if the pixel format has an alpha component */
readonly IsAlphaPixelFormat: boolean;
/** Indicates whether the image is animated */
readonly IsAnimated: boolean;
/** Indicates if the pixel format is extended (16 bits/channel) */
readonly IsExtendedPixelFormat: boolean;
/** Indicates if the pixel data is an index into a palette or the actual color data */
readonly IsIndexedPixelFormat: boolean;
/** Loads the ImageFile object with the specified File */
LoadFile(Filename: string): void;
/** Returns the depth of the pixels of the image in bits per pixel */
readonly PixelDepth: number;
/** A collection of all properties for this image */
readonly Properties: Properties;
/** Save the ImageFile object to the specified File */
SaveFile(Filename: string): void;
/** Returns the Vertical pixels per inch of the image */
readonly VerticalResolution: number;
/** Returns the Width of the image in pixels */
readonly Width: number;
}
/** The ImageProcess object manages the filter chain. An ImageProcess object can be created using "WIA.ImageProcess" in a call to CreateObject. */
interface ImageProcess {
/** Takes the specified ImageFile and returns the new ImageFile with all the filters applied on success */
Apply(Source: ImageFile): ImageFile;
/** A collection of all available filters */
readonly FilterInfos: FilterInfos;
/** A collection of the filters to be applied in this process */
readonly Filters: Filters;
}
/**
* The Item object is a container for an item on an imaging device object. See the Items property on the Device or Item object for details on accessing It
* em objects.
*/
interface Item {
/** A collection of all commands for this item */
readonly Commands: DeviceCommands;
/** Issues the command specified by CommandID. CommandIDs are device dependent. Valid CommandIDs for this Item are contained in the Commands collection. */
ExecuteCommand(CommandID: string): Item;
/** A collection of all supported format types for this item */
readonly Formats: Formats;
/** Returns the ItemID for this Item */
readonly ItemID: string;
/** A collection of all child items for this item */
readonly Items: Items;
/** A collection of all properties for this item */
readonly Properties: Properties;
/**
* Returns an ImageFile object, in this version, in the format specified in FormatID if supported, otherwise using the preferred format for this imaging d
* evice. Future versions may return a collection of ImageFile objects.
* @param string [FormatID='{00000000-0000-0000-0000-000000000000}']
*/
Transfer(FormatID?: string): any;
/** Returns the underlying IWiaItem interface for this Item object */
readonly WiaItem: any;
}
/** The Items object contains a collection of Item objects. See the Items property on the Device or Item object for details on accessing the Items object. */
interface Items {
/** Adds a new Item with the specified Name and Flags. The Flags value is created by using the OR operation with members of the WiaItemFlags enumeration. */
Add(Name: string, Flags: number): void;
/** Returns the number of members in the collection */
readonly Count: number;
/** Returns the specified item in the collection by position */
Item(Index: number): Item;
/** Removes the designated Item */
Remove(Index: number): void;
}
/**
* The Properties object is a collection of all the Property objects associated with a given Device, DeviceInfo, Filter, ImageFile or Item object. See the
* Properties property on any of these objects for detail on accessing the Properties object.
*/
interface Properties {
/** Returns the number of members in the collection */
readonly Count: number;
/** Indicates whether the specified Property exists in the collection */
Exists(Index: any): boolean;
/** Returns the specified item in the collection either by position or name. */
Item(Index: any): Property;
}
/**
* The Property object is a container for a property associated with a Device, DeviceInfo, Filter, ImageFile or Item object. See the Properties property o
* n any of these objects for details on accessing Property objects.
*/
interface Property {
/** Indicates whether the Property Value is read only */
readonly IsReadOnly: boolean;
/** Indicates whether the Property Value is a vector */
readonly IsVector: boolean;
/** Returns the Property Name */
readonly Name: string;
/** Returns the PropertyID of this Property */
readonly PropertyID: number;
/** Returns the SubType of the Property, if any */
readonly SubType: WiaSubType;
/** Returns the default Property Value if the SubType is not UnspecifiedSubType */
readonly SubTypeDefault: any;
/** Returns the maximum valid Property Value if the SubType is RangeSubType */
readonly SubTypeMax: number;
/** Returns the minimum valid Property Value if the SubType is RangeSubType */
readonly SubTypeMin: number;
/** Returns the step increment of Property Values if the SubType is RangeSubType */
readonly SubTypeStep: number;
/** Returns a Vector of valid Property Values if the SubType is ListSubType or valid flag Values that can be ored together if the SubType is FlagSubType */
readonly SubTypeValues: Vector;
/** Returns either a WiaPropertyType or a WiaImagePropertyType */
readonly Type: number;
/** Returns/Sets the Property Value */
Value: any;
}
/**
* The Rational object is a container for the rational values found in Exif tags. It is a supported element type of the Vector object and may be created u
* sing "WIA.Rational" in a call to CreateObject.
*/
interface Rational {
/** Returns/Sets the Rational Value Denominator */
Denominator: number;
/** Returns/Sets the Rational Value Numerator */
Numerator: number;
/** Returns the Rational Value as a Double */
readonly Value: number;
}
/**
* The Vector object is a collection of values of the same type. It is used throughout the library in many different ways. The Vector object may be create
* d using "WIA.Vector" in a call to CreateObject.
*/
interface Vector {
/**
* If Index is not zero, Inserts a new element into the Vector collection before the specified Index. If Index is zero, Appends a new element to the Vecto
* r collection.
* @param number [Index=0]
*/
Add(Value: any, Index?: number): void;
/** Returns/Sets the Vector of Bytes as an array of bytes */
BinaryData: any;
/** Removes all elements. */
Clear(): void;
/** Returns the number of members in the vector */
readonly Count: number;
/** Returns/Sets the Vector of Integers from a Date */
Date: VarDate;
/**
* Used to get the Thumbnail property of an ImageFile which is an image file, The thumbnail property of an Item which is RGB data, or creating an ImageFil
* e from raw ARGB data. Returns an ImageFile object on success. See the Picture method for more details.
* @param number [Width=0]
* @param number [Height=0]
*/
ImageFile(Width?: number, Height?: number): ImageFile;
/** Returns/Sets the specified item in the vector by position */
Item(Index: number): any;
/**
* If the Vector of Bytes contains an image file, then Width and Height are ignored. Otherwise a Vector of Bytes must be RGB data and a Vector of Longs mu
* st be ARGB data. Returns a Picture object on success. See the ImageFile method for more details.
* @param number [Width=0]
* @param number [Height=0]
*/
Picture(Width?: number, Height?: number): any;
/** Removes the designated element and returns it if successful */
Remove(Index: number): any;
/**
* Stores the string Value into the Vector of Bytes including the NULL terminator. Value may be truncated unless Resizable is True. The string will be sto
* red as an ANSI string unless Unicode is True, in which case it will be stored as a Unicode string.
* @param boolean [Resizable=true]
* @param boolean [Unicode=true]
*/
SetFromString(Value: string, Resizable?: boolean, Unicode?: boolean): void;
/**
* Returns a Vector of Bytes as a String
* @param boolean [Unicode=true]
*/
String(Unicode?: boolean): string;
}
}
interface ActiveXObject {
on(obj: WIA.DeviceManager, event: 'OnEvent', argNames: ['EventID', 'DeviceID', 'ItemID'], handler: (
this: WIA.DeviceManager, parameter: {
EventID: string, DeviceID: string, ItemID: string}) => void): void;
set(obj: WIA.Vector, propertyName: 'Item', parameterTypes: [number], newValue: any): void;
new(progid: 'WIA.CommonDialog'): WIA.CommonDialog;
new(progid: 'WIA.DeviceManager'): WIA.DeviceManager;
new(progid: 'WIA.ImageFile'): WIA.ImageFile;
new(progid: 'WIA.ImageProcess'): WIA.ImageProcess;
new(progid: 'WIA.Rational'): WIA.Rational;
new(progid: 'WIA.Vector'): WIA.Vector;
}
interface EnumeratorConstructor {
new(col: WIA.DeviceCommands): WIA.DeviceCommand;
new(col: WIA.DeviceEvents): WIA.DeviceEvent;
new(col: WIA.DeviceInfos): WIA.DeviceInfo;
new(col: WIA.FilterInfos): WIA.FilterInfo;
new(col: WIA.Filters): WIA.Filter;
new(col: WIA.Formats): string;
new(col: WIA.Items): WIA.Item;
new(col: WIA.Properties): WIA.Property;
new(col: WIA.Vector): any;
}

View File

@ -0,0 +1 @@
{ "dependencies": { "activex-helpers": "*"}}

View File

@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strict": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-wia-tests.ts"
]
}

View File

@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@ -1,379 +0,0 @@
// Type definitions for Microsoft Windows Image Acquisition Library v2.0
// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/ms630827(v=vs.85).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace WIA {
//Enums
type CommandID =
"'{04E725B0-ACAE-11D2-A093-00C04F72DC3C}'" //wiaCommandChangeDocument
| "'{E208C170-ACAD-11D2-A093-00C04F72DC3C}'" //wiaCommandDeleteAllItems
| "'{9B26B7B2-ACAD-11D2-A093-00C04F72DC3C}'" //wiaCommandSynchronize
| "'{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}'" //wiaCommandTakePicture
| "'{1F3B3D8E-ACAE-11D2-A093-00C04F72DC3C}'"; //wiaCommandUnloadDocument
const CommandID: {
wiaCommandChangeDocument: CommandID,
wiaCommandDeleteAllItems: CommandID,
wiaCommandSynchronize: CommandID,
wiaCommandTakePicture: CommandID,
wiaCommandUnloadDocument: CommandID
};
type EventID =
"'{A28BBADE-64B6-11D2-A231-00C04FA31809}'" //wiaEventDeviceConnected
| "'{143E4E83-6497-11D2-A231-00C04FA31809}'" //wiaEventDeviceDisconnected
| "'{4C8F4EF5-E14F-11D2-B326-00C04F68CE61}'" //wiaEventItemCreated
| "'{1D22A559-E14F-11D2-B326-00C04F68CE61}'" //wiaEventItemDeleted
| "'{C686DCEE-54F2-419E-9A27-2FC7F2E98F9E}'" //wiaEventScanEmailImage
| "'{C00EB793-8C6E-11D2-977A-0000F87A926F}'" //wiaEventScanFaxImage
| "'{9B2B662C-6185-438C-B68B-E39EE25E71CB}'" //wiaEventScanFilmImage
| "'{A6C5A715-8C6E-11D2-977A-0000F87A926F}'" //wiaEventScanImage
| "'{FC4767C1-C8B3-48A2-9CFA-2E90CB3D3590}'" //wiaEventScanImage2
| "'{154E27BE-B617-4653-ACC5-0FD7BD4C65CE}'" //wiaEventScanImage3
| "'{A65B704A-7F3C-4447-A75D-8A26DFCA1FDF}'" //wiaEventScanImage4
| "'{9D095B89-37D6-4877-AFED-62A297DC6DBE}'" //wiaEventScanOCRImage
| "'{B441F425-8C6E-11D2-977A-0000F87A926F}'"; //wiaEventScanPrintImage
const EventID: {
wiaEventDeviceConnected: EventID,
wiaEventDeviceDisconnected: EventID,
wiaEventItemCreated: EventID,
wiaEventItemDeleted: EventID,
wiaEventScanEmailImage: EventID,
wiaEventScanFaxImage: EventID,
wiaEventScanFilmImage: EventID,
wiaEventScanImage: EventID,
wiaEventScanImage2: EventID,
wiaEventScanImage3: EventID,
wiaEventScanImage4: EventID,
wiaEventScanOCRImage: EventID,
wiaEventScanPrintImage: EventID
};
type FormatID =
"'{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}'" //wiaFormatBMP
| "'{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}'" //wiaFormatGIF
| "'{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}'" //wiaFormatJPEG
| "'{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}'" //wiaFormatPNG
| "'{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}'"; //wiaFormatTIFF
const FormatID: {
wiaFormatBMP: FormatID,
wiaFormatGIF: FormatID,
wiaFormatJPEG: FormatID,
wiaFormatPNG: FormatID,
wiaFormatTIFF: FormatID
};
type Miscellaneous =
"'*'" //wiaAnyDeviceID
| "'{00000000-0000-0000-0000-000000000000}'"; //wiaIDUnknown
const Miscellaneous: {
wiaAnyDeviceID: Miscellaneous,
wiaIDUnknown: Miscellaneous
};
const enum WiaDeviceType {
CameraDeviceType = 2,
ScannerDeviceType = 1,
UnspecifiedDeviceType = 0,
VideoDeviceType = 3
}
const enum WiaEventFlag {
ActionEvent = 2,
NotificationEvent = 1
}
const enum WiaImageBias {
MaximizeQuality = 131072,
MinimizeSize = 65536
}
const enum WiaImageIntent {
ColorIntent = 1,
GrayscaleIntent = 2,
TextIntent = 4,
UnspecifiedIntent = 0
}
const enum WiaImagePropertyType {
ByteImagePropertyType = 1001,
LongImagePropertyType = 1004,
RationalImagePropertyType = 1006,
StringImagePropertyType = 1002,
UndefinedImagePropertyType = 1000,
UnsignedIntegerImagePropertyType = 1003,
UnsignedLongImagePropertyType = 1005,
UnsignedRationalImagePropertyType = 1007,
VectorOfBytesImagePropertyType = 1101,
VectorOfLongsImagePropertyType = 1103,
VectorOfRationalsImagePropertyType = 1105,
VectorOfUndefinedImagePropertyType = 1100,
VectorOfUnsignedIntegersImagePropertyType = 1102,
VectorOfUnsignedLongsImagePropertyType = 1104,
VectorOfUnsignedRationalsImagePropertyType = 1106
}
const enum WiaItemFlag {
AnalyzeItemFlag = 16,
AudioItemFlag = 32,
BurstItemFlag = 2048,
DeletedItemFlag = 128,
DeviceItemFlag = 64,
DisconnectedItemFlag = 256,
FileItemFlag = 2,
FolderItemFlag = 4,
FreeItemFlag = 0,
GeneratedItemFlag = 16384,
HasAttachmentsItemFlag = 32768,
HPanoramaItemFlag = 512,
ImageItemFlag = 1,
RemovedItemFlag = -2147483648,
RootItemFlag = 8,
StorageItemFlag = 4096,
TransferItemFlag = 8192,
VideoItemFlag = 65536,
VPanoramaItemFlag = 1024
}
const enum WiaPropertyType {
BooleanPropertyType = 1,
BytePropertyType = 2,
ClassIDPropertyType = 15,
CurrencyPropertyType = 12,
DatePropertyType = 13,
DoublePropertyType = 11,
ErrorCodePropertyType = 7,
FileTimePropertyType = 14,
HandlePropertyType = 18,
IntegerPropertyType = 3,
LargeIntegerPropertyType = 8,
LongPropertyType = 5,
ObjectPropertyType = 17,
SinglePropertyType = 10,
StringPropertyType = 16,
UnsignedIntegerPropertyType = 4,
UnsignedLargeIntegerPropertyType = 9,
UnsignedLongPropertyType = 6,
UnsupportedPropertyType = 0,
VariantPropertyType = 19,
VectorOfBooleansPropertyType = 101,
VectorOfBytesPropertyType = 102,
VectorOfClassIDsPropertyType = 115,
VectorOfCurrenciesPropertyType = 112,
VectorOfDatesPropertyType = 113,
VectorOfDoublesPropertyType = 111,
VectorOfErrorCodesPropertyType = 107,
VectorOfFileTimesPropertyType = 114,
VectorOfIntegersPropertyType = 103,
VectorOfLargeIntegersPropertyType = 108,
VectorOfLongsPropertyType = 105,
VectorOfSinglesPropertyType = 110,
VectorOfStringsPropertyType = 116,
VectorOfUnsignedIntegersPropertyType = 104,
VectorOfUnsignedLargeIntegersPropertyType = 109,
VectorOfUnsignedLongsPropertyType = 106,
VectorOfVariantsPropertyType = 119
}
const enum WiaSubType {
FlagSubType = 3,
ListSubType = 2,
RangeSubType = 1,
UnspecifiedSubType = 0
}
//Interfaces
interface CommonDialog {
ShowAcquireImage: (DeviceType?: WiaDeviceType, Intent?: WiaImageIntent, Bias?: WiaImageBias, FormatID?: string, AlwaysSelectDevice?: boolean, UseCommonUI?: boolean, CancelError?: boolean) => ImageFile;
ShowAcquisitionWizard: (Device: Device) => any;
ShowDeviceProperties: (Device: Device, CancelError?: boolean) => void;
ShowItemProperties: (Item: Item, CancelError?: boolean) => void;
ShowPhotoPrintingWizard: (Files: any) => void;
ShowSelectDevice: (DeviceType?: WiaDeviceType, AlwaysSelectDevice?: boolean, CancelError?: boolean) => Device;
ShowSelectItems: (Device: Device, Intent?: WiaImageIntent, Bias?: WiaImageBias, SingleSelect?: boolean, UseCommonUI?: boolean, CancelError?: boolean) => Items;
ShowTransfer: (Item: Item, FormatID?: string, CancelError?: boolean) => any;
}
interface Device {
Commands: DeviceCommands;
DeviceID: string;
Events: DeviceEvents;
ExecuteCommand: (CommandID: string) => Item;
GetItem: (ItemID: string) => Item;
Items: Items;
Properties: Properties;
Type: WiaDeviceType;
WiaItem: any /*VT_UNKNOWN*/;
}
interface DeviceCommand {
CommandID: string;
Description: string;
Name: string;
}
interface DeviceCommands {
Count: number;
Item: (Index: number) => DeviceCommand;
}
interface DeviceEvent {
Description: string;
EventID: string;
Name: string;
Type: WiaEventFlag;
}
interface DeviceEvents {
Count: number;
Item: (Index: number) => DeviceEvent;
}
interface DeviceInfo {
Connect: () => Device;
DeviceID: string;
Properties: Properties;
Type: WiaDeviceType;
}
interface DeviceInfos {
Count: number;
Item: (Index: any) => DeviceInfo;
}
interface DeviceManager {
DeviceInfos: DeviceInfos;
RegisterEvent: (EventID: string, DeviceID?: string) => void;
RegisterPersistentEvent: (Command: string, Name: string, Description: string, Icon: string, EventID: string, DeviceID?: string) => void;
UnregisterEvent: (EventID: string, DeviceID?: string) => void;
UnregisterPersistentEvent: (Command: string, Name: string, Description: string, Icon: string, EventID: string, DeviceID?: string) => void;
}
interface Filter {
Description: string;
FilterID: string;
Name: string;
Properties: Properties;
}
interface FilterInfo {
Description: string;
FilterID: string;
Name: string;
}
interface FilterInfos {
Count: number;
Item: (Index: any) => FilterInfo;
}
interface Filters {
Add: (FilterID: string, Index?: number) => void;
Count: number;
Item: (Index: number) => Filter;
Remove: (Index: number) => void;
}
interface Formats {
Count: number;
Item: (Index: number) => string;
}
interface ImageFile {
ActiveFrame: number;
ARGBData: Vector;
FileData: Vector;
FileExtension: string;
FormatID: string;
FrameCount: number;
Height: number;
HorizontalResolution: number;
IsAlphaPixelFormat: boolean;
IsAnimated: boolean;
IsExtendedPixelFormat: boolean;
IsIndexedPixelFormat: boolean;
LoadFile: (Filename: string) => void;
PixelDepth: number;
Properties: Properties;
SaveFile: (Filename: string) => void;
VerticalResolution: number;
Width: number;
}
interface ImageProcess {
Apply: (Source: ImageFile) => ImageFile;
FilterInfos: FilterInfos;
Filters: Filters;
}
interface Item {
Commands: DeviceCommands;
ExecuteCommand: (CommandID: string) => Item;
Formats: Formats;
ItemID: string;
Items: Items;
Properties: Properties;
Transfer: (FormatID?: string) => any;
WiaItem: any /*VT_UNKNOWN*/;
}
interface Items {
Add: (Name: string, Flags: number) => void;
Count: number;
Item: (Index: number) => Item;
Remove: (Index: number) => void;
}
interface Properties {
Count: number;
Exists: (Index: any) => boolean;
Item: (Index: any) => Property;
}
interface Property {
IsReadOnly: boolean;
IsVector: boolean;
Name: string;
PropertyID: number;
SubType: WiaSubType;
SubTypeDefault: any;
SubTypeMax: number;
SubTypeMin: number;
SubTypeStep: number;
SubTypeValues: Vector;
Type: number;
Value: any;
}
interface Rational {
Denominator: number;
Numerator: number;
Value: number;
}
interface Vector {
Add: (Value: any, Index?: number) => void;
BinaryData: any;
Clear: () => void;
Count: number;
Date: VarDate;
ImageFile: (Width?: number, Height?: number) => ImageFile;
Item: (Index: number) => any; //Also has setter with parameters
Picture: (Width?: number, Height?: number) => any;
Remove: (Index: number) => any;
SetFromString: (Value: string, Resizable?: boolean, Unicode?: boolean) => void;
String: (Unicode?: boolean) => string;
}
}
interface ActiveXObject {
new (progID: 'WIA.Rational'): WIA.Rational;
new (progID: 'WIA.Vector'): WIA.Vector;
new (progID: 'WIA.ImageFile'): WIA.ImageFile;
new (progID: 'WIA.ImageProcess'): WIA.ImageProcess;
new (progID: 'WIA.CommonDialog'): WIA.CommonDialog;
new (progID: 'WIA.DeviceManager'): WIA.DeviceManager;
}

View File

@ -1,24 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom",
"scripthost"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-windows-image-acquisition-tests.ts"
]
}

View File

@ -15,9 +15,7 @@
/// <reference types="node" />
import * as fs from 'fs';
import * as stream from 'stream';
import * as express from 'express';
import * as glob from 'glob';
declare function archiver(format: archiver.Format, options?: archiver.ArchiverOptions): archiver.Archiver;
@ -46,7 +44,7 @@ declare namespace archiver {
glob(pattern: string, options?: glob.IOptions, data?: EntryData): this;
finalize(): this;
pipe(stream: fs.WriteStream | express.Response): void;
pipe(stream: stream.Writable): void;
setFormat(format: string): this;
setModule(module: Function): this;

View File

@ -7,7 +7,8 @@ const management = new auth0.ManagementClient({
const auth = new auth0.AuthenticationClient({
domain: '{YOUR_ACCOUNT}.auth0.com',
clientId: '{OPTIONAL_CLIENT_ID}'
clientId: '{OPTIONAL_CLIENT_ID}',
clientSecret: '{OPTIONAL_CLIENT_SECRET}'
});
// Using a callback.

View File

@ -1,4 +1,4 @@
// Type definitions for auth0 3.0
// Type definitions for auth0 2.3
// Project: https://github.com/auth0/node-auth0
// Definitions by: Wilson Hobbs <https://github.com/wbhob>, Seth Westphal <https://github.com/westy92>, Amiram Korach <https://github.com/amiram>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@ -83,6 +83,7 @@ export interface Identity {
export interface AuthenticationClientOptions {
clientId?: string;
clientSecret?: string;
domain: string;
}
@ -131,6 +132,16 @@ export interface ResetPasswordEmailOptions {
connection: string;
}
export interface ClientCredentialsGrantOptions {
audience: string;
}
export interface PasswordGrantOptions {
username: string;
password: string;
realm?: string;
}
export interface ObjectWithId {
id: string;
}
@ -187,7 +198,8 @@ export interface UnlinkAccountsResponse {
export interface LinkAccountsData {
user_id: string;
connection_id: string;
connection_id?: string;
provider?: string;
}
export interface Token {
@ -254,8 +266,11 @@ export class AuthenticationClient {
getProfile(accessToken: string): Promise<any>;
getProfile(accessToken: string, cb: (err: Error, message: string) => void): void;
getCredentialsGrant(scope: string): Promise<any>;
getCredentialsGrant(scope: string, cb: (err: Error, message: string) => void): void;
clientCredentialsGrant(options: ClientCredentialsGrantOptions): Promise<any>;
clientCredentialsGrant(options: ClientCredentialsGrantOptions, cb: (err: Error, response: any) => void): void;
passwordGrant(options: PasswordGrantOptions): Promise<any>;
passwordGrant(options: PasswordGrantOptions, cb: (err: Error, response: any) => void): void;
}

View File

@ -51,12 +51,14 @@ var lineData: LinearChartData = {
datasets: [
{
label: 'Accepted',
type: 'bar',
fillColor: 'rgba(220,220,220,0.2)',
strokeColor: 'rgba(220,220,220,1)',
pointColor: 'rgba(220,220,220,1)',
pointStrokeColor: '#fff',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(220,220,220,1)',
borderColor: "#9b0391",
data: [65, 59, 80, 81, 56, 55, 40]
},
{
@ -67,7 +69,8 @@ var lineData: LinearChartData = {
pointStrokeColor: '#fff',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(151,187,205,1)',
data: [28, 48, 40, 19, 86, 27, 90]
data: [28, 48, 40, 19, 86, 27, 90],
yAxisID: 'quarantined'
}
]
};
@ -85,6 +88,21 @@ var myLineChart = new Chart(ctx).Line(lineData, {
datasetStroke: true,
datasetStrokeWidth: 2,
datasetFill: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
position: "left",
"id": "users"
}, {
position: "right",
"id": "ratio",
ticks: {
min: -13
}
}]
},
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].lineColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
});
@ -129,6 +147,10 @@ var myBarChart = new Chart(ctx).Bar(barData, {
barStrokeWidth: 2,
barValueSpacing: 5,
barDatasetSpacing: 1,
legend: {
display: true,
position: 'bottom'
},
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].lineColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
});
@ -369,4 +391,3 @@ var my2ndRadarChart = new Chart(ctx).Radar(radarData, partialOpts);
var my2ndPolarAreaChart = new Chart(ctx).PolarArea(polarAreaData, partialOpts);
var my2ndPieChart = new Chart(ctx).Pie(pieData, partialOpts);
var my2ndDoughnutChart = new Chart(ctx).Doughnut(pieData, partialOpts);

View File

@ -1,13 +1,18 @@
// Type definitions for Chart.js
// Project: https://github.com/nnnick/Chart.js
// Definitions by: Steve Fenton <https://github.com/Steve-Fenton>
// Alessio Fanelli <https://github.com/FanaHOVA>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface ChartDataSet {
label: string;
fillColor: string;
strokeColor: string;
type?: string;
yAxisID?: string;
xAxisID?: string;
borderColor?: string;
/* Line, Radar */
pointColor?: string;
pointStrokeColor?: string;
@ -17,6 +22,8 @@ interface ChartDataSet {
/* Bar */
highlightFill?: string;
highlightStroke?: string;
backgroundColorHover?: string;
data: number[];
}
@ -80,8 +87,44 @@ interface ChartOptions extends ChartSettings {
scaleGridLineColor?: string;
scaleGridLineWidth?: number;
scaleShowHorizontalLines?: boolean;
scaleShowVerticalLines?: boolean;
scaleShowVerticalLines?: boolean;
legendTemplate?: string;
tooltips?: ChartTooltips;
legend?: ChartLegend;
scales?: ChartScales;
title?: ChartTitle;
}
interface ChartTooltips {
mode?: string;
intersect?: boolean;
}
interface ChartLegend {
display?: boolean;
position?: string;
}
interface ChartScales {
xAxes?: Array<ChartScalesOptions>;
yAxes?: Array<ChartScalesOptions>;
}
interface ChartScalesOptions {
stacked?: boolean;
position?: string;
id?: string;
ticks?: ScaleTicksOptions;
}
interface ScaleTicksOptions {
min?: number;
max?: number;
}
interface ChartTitle {
display?: boolean;
text?: string;
}
interface PointsAtEvent {
@ -137,7 +180,7 @@ interface BarChartOptions extends ChartOptions {
barShowStroke?: boolean;
barStrokeWidth?: number;
barValueSpacing?: number;
barDatasetSpacing?: number;
barDatasetSpacing?: number;
}
interface RadarChartOptions extends ChartSettings {

View File

@ -306,3 +306,5 @@ $.parseHTML(html, null, true);
* Not in doc
*/
$el.toArray();
cheerio.html($el);

View File

@ -263,7 +263,7 @@ interface CheerioElement {
nodeValue: string;
}
interface CheerioAPI extends CheerioSelector {
interface CheerioAPI extends CheerioSelector, CheerioStatic {
load(html: string, options?: CheerioOptionsInterface): CheerioStatic;
load(element: CheerioElement, options?: CheerioOptionsInterface): CheerioStatic;
}

View File

@ -26,6 +26,27 @@ class Readme {
.then(() => process.exit());
}
requesterCallback() {
const randomRequester = new cote.Requester({
name: 'Random Requester',
namespace: 'rnd',
key: 'a certain key',
requests: ['randomRequest']
});
const req = {
type: 'randomRequest',
payload: {
val: Math.floor(Math.random() * 10)
}
};
randomRequester.send(req, res => {
console.log(res);
process.exit();
});
}
responder() {
const randomResponder = new cote.Responder({
name: 'Random Responder',
@ -34,19 +55,49 @@ class Readme {
respondsTo: ['randomRequest']
});
randomResponder.on('randomRequest', (req: cote.Action<{ val: number }>) => {
interface RandomRequest {
type: 'randomRequest';
payload: { val: number };
}
randomResponder.on('randomRequest', (req: RandomRequest) => {
const answer = Math.floor(Math.random() * 10);
console.log('request', req.payload.val, 'answering with', answer);
return Promise.resolve(answer);
});
}
responderCallback() {
const randomResponder = new cote.Responder({
name: 'Random Responder',
namespace: 'rnd',
key: 'a certain key',
respondsTo: ['randomRequest']
});
interface RandomRequest {
type: 'randomRequest';
payload: { val: number };
}
randomResponder.on('randomRequest', (req: RandomRequest, callback: (answer: number) => void) => {
const answer = Math.floor(Math.random() * 10);
console.log('request', req.payload.val, 'answering with', answer);
callback(answer);
});
}
mongooseResponder() {
const UserModel = require('UserModel'); // a promise-based model API
const userResponder = new cote.Responder({ name: 'User Responder' });
userResponder.on('find', (req: cote.Action<{ username: string }>) => UserModel.findOne(req.payload));
interface Find {
type: 'find';
payload: { username: string };
}
userResponder.on('find', (req: Find) => UserModel.findOne(req.payload));
}
mongooseRequester() {
@ -67,16 +118,16 @@ class Readme {
});
setInterval(() => {
const action = {
const event = {
type: 'randomUpdate',
payload: {
val: Math.floor(Math.random() * 1000)
}
};
console.log('emitting', action);
console.log('emitting', event);
randomPublisher.publish('randomUpdate', action);
randomPublisher.publish('randomUpdate', event);
}, 3000);
}
@ -141,7 +192,7 @@ class Readme {
key: 'conversion backend'
});
responder.on('convert', (req) => {
responder.on('convert', (req: any) => {
return conversionRequester.send(req); // proxy the request
});
}
@ -157,11 +208,16 @@ class Readme {
eur_usd: 1.10
};
responder.on('convert', (req: cote.Action<{
amount: number,
from: string,
to: string
}>) => {
interface Convert {
type: 'convert';
payload: {
amount: number,
from: string,
to: string
};
}
responder.on('convert', (req: Convert) => {
const { payload } = req;
return Promise.resolve(payload.amount * rates[`${payload.from}_${payload.to}`]);
});
@ -183,3 +239,213 @@ class Readme {
const req = new cote.Requester({ name: 'req' }, { broadcast: '255.255.255.255' });
}
}
/**
* Fixes for initial errors and shortcomings.
* @see https://github.com/makepost/DefinitelyTyped/projects/1
*/
class InitialObservations {
event() {
const event: cote.Event = { type: 'someEvent' };
}
eventEmitter() {
const quitter = new cote.Requester({ name: 'Quitter' });
quitter.onAny(() => process.exit);
const indecisive = new cote.Responder({ name: 'Indecisive' });
const callback = <T>(x: T) => Promise.resolve(x);
indecisive.on('choice', callback);
indecisive.off('choice', callback);
const techno = new cote.Publisher({ name: 'Techno' });
techno.removeAllListeners();
const village = new cote.Subscriber({ name: 'Village' });
const doHelp = () => { };
village.many('wolf', 2, doHelp);
village.emit('wolf');
village.emit('wolf');
const emptyArray = village.listenersAny();
village.emit('wolf'); // no reaction
const eternity = new cote.Sockend(null as any, { name: 'Eternity' });
const handler = () => {
if (Math.random() === Number.MIN_VALUE) {
console.log('It happened.');
eternity.offAny(handler);
}
};
eternity.addListener('request', handler);
const monitor = new cote.Monitor({
name: 'Monitor',
port: 8025
});
monitor.setMaxListeners(1);
monitor.once('foobar', () => {
monitor.removeAllListeners();
monitor.once('foobar', () => {
console.log('Not a warning.');
});
});
}
advertisement() {
// Incorrect:
// const requester = new cote.Requester({
// name: 'Requester',
// respondsTo: ['foo']
// })
// Incorrect:
// const responder = new cote.Responder({
// name: 'Responder',
// subscribesTo: ['bar']
// })
// Incorrect:
// const publisher = new cote.Publisher({
// name: 'Publisher',
// requests: ['baz']
// })
// Incorrect:
// const subscriber = new cote.Subscriber({
// name: 'Subscriber',
// broadcasts: ['qux']
// })
}
discovery() {
new cote.Responder({ name: 'LocalUnlessForwarded' }, { address: '127.0.0.1' });
new cote.Publisher({ name: 'PassionateGreeter' }, { helloInterval: 100 });
new cote.Requester({ name: 'Optimist' }, {
checkInterval: 1e5,
nodeTimeout: 1e6
});
new cote.Subscriber({ name: 'Hachiko' }, { masterTimeout: 9 * 365 * 24 * 60 * 60 * 1000 });
new cote.Monitor({ name: 'HelloService', port: 2345 }, {
monitor: false,
statusLogsEnabled: false
});
new cote.Monitor({ name: 'OfflineLogger', port: 2346 }, {
disableScreen: true,
helloLogsEnabled: false,
log: true
});
new cote.Responder({ name: 'HearsNoneAbove' }, { ignoreProcess: true });
new cote.Requester({ name: 'OwnStatusReporter' }, { statusInterval: 100 });
}
callbackApi() {
// Added to Readme above, near respective Promise examples.
}
timeBalancedRequester() {
const randomRequester = new cote.TimeBalancedRequester({
name: 'Random Requester',
namespace: 'rnd',
key: 'a certain key',
requests: ['randomRequest']
});
const req = {
type: 'randomRequest',
payload: {
val: Math.floor(Math.random() * 10)
}
};
randomRequester.send(req)
.then(console.log)
.catch(console.log)
.then(() => process.exit());
}
pendingBalancedRequester() {
const randomRequester = new cote.PendingBalancedRequester({
name: 'Random Requester',
namespace: 'rnd',
key: 'a certain key',
requests: ['randomRequest']
});
const req = {
type: 'randomRequest',
payload: {
val: Math.floor(Math.random() * 10)
}
};
randomRequester.send(req)
.then(console.log)
.catch(console.log)
.then(() => process.exit());
}
lifecycle() {
const key = Math.random().toString();
const requester = new cote.Requester({
name: `${key} requester`,
key
});
const responder = new cote.Responder({
name: `${key} responder`,
key
});
responder.on('cote:added', ({ advertisement, type }) => {
console.log({
advertisement: {
broadcasts: advertisement.broadcasts,
key: advertisement.key,
name: advertisement.name,
namespace: advertisement.namespace,
requests: advertisement.requests,
respondsTo: advertisement.respondsTo,
subscribesTo: advertisement.subscribesTo
},
type
});
requester.close();
});
responder.on('cote:removed', ({ advertisement, type }) => {
console.assert(advertisement.name === `${key} requester`);
console.log({
advertisement: {
broadcasts: advertisement.broadcasts,
key: advertisement.key,
name: advertisement.name,
namespace: advertisement.namespace,
requests: advertisement.requests,
respondsTo: advertisement.respondsTo,
subscribesTo: advertisement.subscribesTo
},
type
});
responder.close();
});
}
monitorAdvertisement() {
const name = 'Service';
const port = undefined;
new cote.Monitor({ name, port });
new cote.Monitor({ name });
}
}

290
types/cote/index.d.ts vendored
View File

@ -3,11 +3,12 @@
// Definitions by: makepost <https://github.com/makepost>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import { EventEmitter2 } from "eventemitter2";
import * as SocketIO from "socket.io";
import { Stream } from "stream";
import { Server } from "http";
export class Requester {
export abstract class Component extends EventEmitter2 {
constructor(
/**
* Configuration which controls the data being advertised for auto-discovery.
@ -20,21 +21,59 @@ export class Requester {
discoveryOptions?: DiscoveryOptions
);
/**
* Closes socket and stops discovery.
*/
close(): void;
}
export class Requester extends Component {
constructor(
/**
* Configuration which controls the data being advertised for auto-discovery.
*/
advertisement: RequesterAdvertisement,
/**
* Controls the network-layer configuration and environments for components.
*/
discoveryOptions?: DiscoveryOptions
);
/**
* Queues a request until a Responder is available, and once so, delivers
* the request. Requests are dispatched to Responders in a round-robin way.
*
* @param action Request.
* @param event Request.
*/
send<T>(action: Action<T>): Promise<any>;
send<T extends Event>(event: T): Promise<any>;
/**
* Queues a request until a Responder is available, and once so, delivers
* the request. Requests are dispatched to Responders in a round-robin way.
*
* @param event Request.
* @param callback Function to execute after getting a result.
*/
send<T extends Event>(event: T, callback: (result: any) => void): void;
}
export class Responder {
/**
* Configuration which controls the data being advertised for auto-discovery.
*/
export interface RequesterAdvertisement extends Advertisement {
/**
* Request types that a Requester can send.
*/
requests?: string[];
}
export class Responder extends Component {
constructor(
/**
* Configuration which controls the data being advertised for auto-discovery.
*/
advertisement: Advertisement,
advertisement: ResponderAdvertisement,
/**
* Controls the network-layer configuration and environments for components.
@ -42,24 +81,47 @@ export class Responder {
discoveryOptions?: DiscoveryOptions
);
/**
* Listens to internal `cote:added` and `cote:removed` events.
*
* @param listener Callback.
*/
on(
type: 'cote:added' | 'cote:removed',
listener: (event: Status) => void
): this;
/**
* Responds to certain requests from a Requester.
*
* @param type Type. May be wildcarded or namespaced like in EventEmitter2.
* @param listener Callback. Should return a result.
*/
on<T>(
type: string,
listener: (action: Action<T>) => Promise<any>
): void;
on<T extends Event>(
type: string | string[],
listener: (
((event: T, callback: (result: any) => void) => void) |
((event: T) => Promise<any>)
)
): this;
}
export class Publisher {
/**
* Configuration which controls the data being advertised for auto-discovery.
*/
export interface ResponderAdvertisement extends Advertisement {
/**
* Request types that a Responder can listen to.
*/
respondsTo?: string[];
}
export class Publisher extends Component {
constructor(
/**
* Configuration which controls the data being advertised for auto-discovery.
*/
advertisement: Advertisement,
advertisement: PublisherAdvertisement,
/**
* Controls the network-layer configuration and environments for components.
@ -72,20 +134,30 @@ export class Publisher {
* there are no Subscribers listening, the event is lost.
*
* @param type EventEmitter-compatible type.
* @param action Request.
* @param event Request.
*/
publish<T>(
publish<T extends Event>(
type: string,
action: Action<T>
event: T
): void;
}
export class Subscriber {
/**
* Configuration which controls the data being advertised for auto-discovery.
*/
export interface PublisherAdvertisement extends Advertisement {
/**
* Event types that a Publisher can publish.
*/
broadcasts?: string[];
}
export class Subscriber extends Component {
constructor(
/**
* Configuration which controls the data being advertised for auto-discovery.
*/
advertisement: Advertisement,
advertisement: SubscriberAdvertisement,
/**
* Controls the network-layer configuration and environments for components.
@ -99,13 +171,23 @@ export class Subscriber {
* @param type Type. May be wildcarded or namespaced like in EventEmitter2.
* @param listener Callback. Returns nothing.
*/
on<T>(
type: string,
listener: (action: Action<T>) => void
): void;
on<T extends Event>(
type: string | string[],
listener: (event: T) => void
): this;
}
export class Sockend {
/**
* Configuration which controls the data being advertised for auto-discovery.
*/
export interface SubscriberAdvertisement extends Advertisement {
/**
* Event types that a Subscriber can listen to.
*/
subscribesTo?: string[];
}
export class Sockend extends Component {
/**
* Exposes APIs directly to front-end. Make sure to use namespaces.
*/
@ -115,7 +197,7 @@ export class Sockend {
/**
* Configuration which controls the data being advertised for auto-discovery.
*/
advertisement: Advertisement,
advertisement: SockendAdvertisement,
/**
* Controls the network-layer configuration and environments for components.
@ -124,12 +206,17 @@ export class Sockend {
);
}
export class Monitor {
/**
* Configuration which controls the data being advertised for auto-discovery.
*/
export interface SockendAdvertisement extends ResponderAdvertisement, PublisherAdvertisement { }
export class Monitor extends Component {
constructor(
/**
* Configuration which controls the data being advertised for auto-discovery.
*/
advertisement: Advertisement,
advertisement: MonitorAdvertisement,
/**
* Controls the network-layer configuration and environments for components.
@ -140,6 +227,16 @@ export class Monitor {
)
}
/**
* Configuration which controls the data being advertised for auto-discovery.
*/
export interface MonitorAdvertisement extends Advertisement {
/**
* Port for Monitor to listen on. By default will start searching from 8000.
*/
port?: number | string;
}
/**
* Displays the cote ecosystem running in your environment in a nice graph.
*
@ -151,16 +248,58 @@ export function MonitoringTool(port: number): {
};
/**
* Flux standard action.
* @see https://github.com/acdlite/flux-standard-action
* Takes average response times of each connected socket and balances requests
* among them accordingly.
*/
export interface Action<T> {
type: string;
payload: T;
error?: boolean;
meta?: {};
export class TimeBalancedRequester extends Requester {
/**
* How long to wait for response before neglecting its calculation time,
* in milliseconds.
*/
CALCULATION_TIMEOUT: number;
/**
* How many requests to make before exploring a random server for response
* time improvement.
*/
MAX_REQUESTS: number;
/**
* How often to check whether a response arrived. Readonly because used in
* constructor right after being set.
*/
readonly SAMPLE_INTERVAL: number;
}
/**
* Keeps track of open, pending requests for each known Responder. Each new
* request goes to the Responder with the minimum open requests.
*/
export class PendingBalancedRequester extends Requester { }
/**
* Event is nothing but object with `type`.
*/
export interface Event {
type: string;
}
/**
* Internal `cote:added` and `cote:removed` events.
*/
export interface Status extends Event {
advertisement: StatusAdvertisement;
}
/**
* Advertisement in internal `cote:added` and `cote:removed` events.
*/
export interface StatusAdvertisement extends
RequesterAdvertisement,
ResponderAdvertisement,
PublisherAdvertisement,
SubscriberAdvertisement { }
/**
* Configuration which controls the data being advertised for auto-discovery.
*/
@ -180,32 +319,81 @@ export interface Advertisement {
* to communicate. Think of it as `${environment}_${key}`.
*/
key?: string;
/**
* Request types that a Requester can send.
*/
requests?: string[];
/**
* Response types that a Responder can listen to.
*/
respondsTo?: string[];
/**
* Event types that a Publisher can publish.
*/
broadcasts?: string[];
/**
* Event types that a Subscriber can listen to.
*/
subscribesTo?: string[];
}
/**
* Controls the network-layer configuration and environments for components.
*/
export interface DiscoveryOptions {
/**
* Multicast address if using multicast.
*/
multicast?: string;
/**
* Broadcast address if using broadcast.
*/
broadcast?: string;
/**
* Address to bind to.
*/
address?: string;
/**
* How often to broadcast a hello packet in milliseconds.
*/
helloInterval?: number;
/**
* How often to to check for missing nodes in milliseconds.
*/
checkInterval?: number;
/**
* Consider a node dead if not seen in this many milliseconds.
*/
nodeTimeout?: number;
/**
* Consider a master node dead if not seen in this many milliseconds.
*/
masterTimeout?: number;
/**
* Skips key equality checks when logging.
*/
monitor?: boolean;
/**
* If false, disables `helloLogsEnabled` and `statusLogsEnabled` no matter
* what value they have, and also own hello log.
*/
log?: boolean;
/**
* Notifies when another service goes online.
*/
helloLogsEnabled?: boolean;
/**
* Notifies when another service goes online or offline. If false, disables
* `helloLogsEnabled` as well.
*/
statusLogsEnabled?: boolean;
/**
* Ignores messages from other services within the same process.
*/
ignoreProcess?: boolean;
/**
* Prevents Monitor from drawing.
*/
disableScreen?: boolean;
/**
* Milliseconds between emissions of own status for monitoring.
*/
statusInterval?: number;
}

5
types/cote/package.json Normal file
View File

@ -0,0 +1,5 @@
{
"dependencies": {
"eventemitter2": "^4.1.0"
}
}

View File

@ -0,0 +1,11 @@
import * as dedent from 'dedent';
const lines: string = dedent`
first
second
third
`;
const text: string = dedent(`
A test argument.
`);

10
types/dedent/index.d.ts vendored Normal file
View File

@ -0,0 +1,10 @@
// Type definitions for dedent 0.7
// Project: https://github.com/dmnd/dedent
// Definitions by: Douglas Duteil <https://github.com/douglasduteil>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = dedent;
declare function dedent(literals: string): string;
declare function dedent(literals: TemplateStringsArray, ...placeholders: any[]): string;
declare namespace dedent {}

View File

@ -17,6 +17,6 @@
},
"files": [
"index.d.ts",
"qiniu-tests.ts"
"dedent-tests.ts"
]
}

View File

@ -0,0 +1,46 @@
import Draggabilly from 'draggabilly';
const elem = document.querySelector('.draggable') as Element;
const draggieA = new Draggabilly('.test');
const draggieB = new Draggabilly(elem);
const draggie = new Draggabilly(elem, {
axis: 'x',
containment: true,
grid: [20, 20],
handle: '.handle'
});
const draggiePosX: number = draggie.position.x;
const draggiePosY: number = draggie.position.y;
draggie.on( 'dragMove', (event, pointer, moveVector) => {
const pointerPageX: number = pointer.pageX;
const pointePageY: number = pointer.pageY;
const moveVectorX: number = moveVector.x;
const moveVectorY: number = moveVector.y;
});
draggie.on( 'dragStart', (event, pointer) => {});
draggie.on( 'dragEnd', (event, pointer) => {});
draggie.on( 'pointerDown', (event, pointer) => {});
draggie.on( 'pointerMove', (event, pointer, moveVector) => {});
draggie.on( 'pointerUp', (event, pointer) => {});
draggie.on( 'staticClick', (event, pointer) => {});
draggie.off('dragMove', (event, pointer, moveVector) => {});
draggie.once('dragMove', (event, pointer, moveVector) => {});
draggie.enable();
draggie.disable();
draggie.destroy();

45
types/draggabilly/index.d.ts vendored Normal file
View File

@ -0,0 +1,45 @@
// Type definitions for draggabilly 2.1
// Project: http://draggabilly.desandro.com/
// Definitions by: Jason Wu <https://github.com/jaydubu/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
export interface Position {
x: number;
y: number;
}
export interface DraggabillyOptions {
axis?: 'x' | 'y';
containment?: Element | string | boolean;
grid?: [number, number];
handle?: string;
}
export type DraggabillyClickEventName = 'dragStart' | 'dragEnd' | 'pointerDown' | 'pointerUp' | 'staticClick';
export type DraggabillyMoveEventName = 'dragMove' | 'pointerMove';
export default class Draggabilly {
position: Position;
constructor(element: Element | string, options?: DraggabillyOptions);
on(eventName: DraggabillyClickEventName, listener: (event: Event, pointer: MouseEvent | Touch) => void): Draggabilly;
on(eventName: DraggabillyMoveEventName, listener: (event: Event, pointer: MouseEvent | Touch, moveVector: Position) => void): Draggabilly;
off(eventName: DraggabillyClickEventName, listener: (event: Event, pointer: MouseEvent | Touch) => void): Draggabilly;
off(eventName: DraggabillyMoveEventName, listener: (event: Event, pointer: MouseEvent | Touch, moveVector: Position) => void): Draggabilly;
once(eventName: DraggabillyClickEventName, listener: (event: Event, pointer: MouseEvent | Touch) => void): Draggabilly;
once(eventName: DraggabillyMoveEventName, listener: (event: Event, pointer: MouseEvent | Touch, moveVector: Position) => void): Draggabilly;
enable(): void;
disable(): void;
destroy(): void;
}

View File

@ -3,12 +3,11 @@
"module": "commonjs",
"lib": [
"es6",
"dom",
"scripthost"
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
@ -19,6 +18,6 @@
},
"files": [
"index.d.ts",
"activex-data-objects-tests.ts"
"draggabilly-tests.ts"
]
}
}

View File

@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@ -1,11 +1,8 @@
import * as packager from "electron-packager";
function callback(err: Error, appPath: string) {
const
msg = err.message,
index = appPath.indexOf("test");
const msg = err.message;
const index = appPath.indexOf("test");
}
packager({
@ -13,29 +10,27 @@ packager({
name: "myapplication",
platform: "win32",
arch: "all",
version: "0.34.0"
electronVersion: "0.34.0"
}, callback);
packager({
dir: ".",
name: "myapplication",
version: "0.34.0",
electronVersion: "0.34.0",
all: true
}, callback);
const pkger = require("electron-packager");
pkger({
packager({
dir: ".",
name: "myapplication",
platform: "win32",
arch: "all",
version: "0.34.0"
electronVersion: "0.34.0"
}, callback);
pkger({
packager({
dir: ".",
name: "myapplication",
version: "0.34.0",
electronVersion: "0.34.0",
all: true
}, callback);

View File

@ -1,115 +1,204 @@
// Type definitions for electron-packager v5.1.0
// Project: https://github.com/maxogden/electron-packager
// Type definitions for electron-packager 8.7
// Project: https://github.com/electron-userland/electron-packager
// Definitions by: Maxime LUCE <https://github.com/SomaticIT/>
// Juan Jimenez-Anca <https://github.com/cortopy>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
declare namespace ElectronPackager {
export = electronPackager;
/**
* This will:
* - Find or download the correct release of Electron
* - Use that version of electron to create a app in <out>/<appname>-<platform>-<arch>
*
* You should be able to launch the app on the platform you built for. If not, check your settings and try again.
*
* @param opts - Options to configure packaging.
* @param callback - Callback which is called when packaging is done or an error occured.
*/
declare function electronPackager(opts: electronPackager.Options, callback: electronPackager.finalCallback): void;
declare namespace electronPackager {
/**
* Callback which is called when electron-packager is done.
*
* @param err - Contains errors if any.
* @param appPaths - Path(s) to the newly created application(s).
*/
type finalCallback = (err: Error, appPaths: string|string[]) => void;
type ignoreFunction = (path: string) => boolean;
type onCompleteFn = (buildPath: string, electronVersion: string, platform: string, arch: string, callbackFn: () => void) => void;
type arch = "ia32" | "x64" | "armv7l" | "all";
type packageManager = "npm" | "cnpm" | "yarn";
type platform = "linux" | "win32" | "darwin" | "mas" | "all";
interface AsarOptions {
ordering?: string;
unpack?: string;
unpackDir?: string;
}
interface ElectronDownloadOptions {
cache?: string;
mirror?: string;
quiet?: boolean;
strictSSL?: boolean;
}
interface ElectronOsXSignOptions {
identity?: string;
entitlements?: string;
"entitlements-inherit"?: string;
}
/**
* Object (also known as a "hash") of application metadata to embed into the executable
*/
interface Win32Metadata {
CompanyName?: string;
FileDescription?: string;
OriginalFilename?: string;
ProductName?: string;
InternalName?: string;
"requested-execution-level": any;
"application-manifest": any;
}
/** Electron-packager Options. */
export interface Options {
interface Options {
/** The source directory. */
dir: string;
/** The application name. */
name: string;
/**
* Allowed values: linux, win32, darwin, all. Not required if `all` is used.
* Arbitrary combinations of individual platforms are also supported via a comma-delimited string or array of strings.
* Optional list of methods to call on completion of each process
*/
platform?: string | string[];
/** Allowed values: ia32, x64, all Not required if `all` is used. */
arch?: string;
/** Electron version (without the "v"). See https://github.com/atom/electron/releases. */
version: string;
afterCopy?: onCompleteFn[];
afterExtract?: onCompleteFn[];
afterPrune?: onCompleteFn[];
/** Shortcut for `--arch=all --platform=all`. */
all?: boolean;
/**
* The human-readable copyright line for the app. Maps to the LegalCopyright metadata property on Windows, and NSHumanReadableCopyright on OS X.
*/
appCopyright?: string;
/**
* The release version of the application. By default the version property in the package.json is used but it can be overridden with this argument.
* If neither are provided, the version of Electron will be used. Maps to the ProductVersion metadata property on Windows, and CFBundleShortVersionString on OS X.
*/
appVersion?: string;
/**
* The target system architecture(s) to build for. Not required if the all option is set.
* If arch is set to all, all supported architectures for the target platforms specified by platform will be built.
* Arbitrary combinations of individual architectures are also supported via a comma-delimited string or array of strings.
* The non-all values correspond to the architecture names used by Electron releases. This value is not restricted to the official set if download.mirror is set.
*/
arch?: arch;
/**
* Whether to package the application's source code into an archive, using Electron's archive format
*/
asar?: boolean | AsarOptions;
/**
* The build version of the application. Defaults to the value of appVersion.
* Maps to the FileVersion metadata property on Windows, and CFBundleVersion on OS X.
*/
buildVersion?: string;
/**
* Whether symlinks should be dereferenced during the copying of the application source.
*/
derefSymlinks?: boolean;
/**
* If present, passes custom options to electron-download
*/
download?: ElectronDownloadOptions;
/**
* The Electron version with which the app is built (without the leading 'v') - for example, 1.4.13
*/
electronVersion?: string;
/**
* One or more files to be copied directly into the app's Contents/Resources directory for OS X target platforms, and the resources directory for other target platforms.
*/
extraResource?: string | string[];
/**
* The local path to the icon file, if the target platform supports setting embedding an icon.
*/
icon?: string;
/**
* One or more additional regular expression patterns which specify which files to ignore when copying files to create the app bundle(s).
* The regular expressions are matched against the absolute path of a given file/directory to be copied.
*/
ignore?: RegExp | RegExp[] | ignoreFunction;
/**
* The application name. If omitted, it will use the productName or name value from the nearest package.json
*/
name?: string;
/** The output directory. */
out?: string;
/**
* Currently you must look for conversion tools in order to supply an icon in the format required by the platform:
* - OS X: `.icns`
* - Windows: `.ico`
*
* For Linux builds, this option is not required, as the dock/window list icon is set via the icon option in the BrowserWindow contructor.
* Setting the icon in the file manager is not currently supported.
*
* If the file extension is omitted, it is auto-completed to the correct extension based on the platform,
* including when `--platform=all` is in effect.
* Whether to replace an already existing output directory for a given platform (true) or skip recreating it (false).
*/
icon?: string;
/** The bundle identifier to use in the app plist. */
"app-bundle-id"?: string;
/** The release version to set for the app. */
"app-version"?: string;
/** The build version to set for the app (OS X only). */
"build-version"?: string;
/** The bundle identifier to use in the app helper plist. */
"helper-bundle-id"?: string;
/** Object hash of application metadata to embed into the executable (Windows only). */
"version-string"?: VersionString;
/** The directory of cached electron downloads. Defaults to "$HOME/.electron". */
cache?: string;
/** Do not copy files into App whose filenames regex .match this string. */
ignore?: RegExp;
/** Runs `npm prune --production` on the app. */
prune?: boolean;
/** If output directory for a platform already exists, replaces it rather than skipping it. */
overwrite?: boolean;
/** Packages the source code within your app into an archive. */
asar?: boolean;
/** Unpacks the files to app.asar.unpacked directory whose filenames regex .match this string. */
"asar-unpack"?: string;
/** Should contain the identity to be used when running `codesign` (OS X only). */
sign?: string;
}
/** Object hash of application metadata to embed into the executable (Windows only). */
export interface VersionString {
CompanyName?: string;
LegalCopyright?: string;
FileDescription?: string;
OriginalFilename?: string;
FileVersion?: string;
ProductVersion?: string;
ProductName?: string;
InternalName?: string;
}
/** Electron-packager done callback. */
export interface Callback {
/**
* Callback which is called when electron-packager is done.
*
* @param err - Contains errors if any.
* @param appPath - Path(s) to the newly created application(s).
* The package manager used to prune devDependencies modules from the outputted Electron app
*/
(err: Error, appPath: string|string[]): void
}
/** Electron-packager function */
export interface Packager {
packageManager?: packageManager;
/**
* This will:
* - Find or download the correct release of Electron
* - Use that version of electron to create a app in <out>/<appname>-<platform>-<arch>
*
* You should be able to launch the app on the platform you built for. If not, check your settings and try again.
*
* @param opts - Options to configure packaging.
* @param callback - Callback which is called when packaging is done or an error occured.
* The target platform(s) to build for. Not required if the all option is set.
*/
(opts: Options, callback: Callback): void;
platform?: platform;
/**
* Runs the package manager command to remove all of the packages specified in the devDependencies section of package.json from the outputted Electron app.
*/
prune?: boolean;
/**
* If true, disables printing informational and warning messages to the console when packaging the application. This does not disable errors.
*/
quiet?: boolean;
/**
* The base directory to use as a temp directory. Set to false to disable use of a temporary directory.
*/
tmpdir?: string | false;
/**
* OS X/Mac App Store targets only
*/
/**
* The bundle identifier to use in the application's plist.
*/
appBundleId?: string;
/**
* The application category type, as shown in the Finder via View Arrange by Application Category when viewing the Applications directory.
*/
appCategoryType?: string;
/**
* When the value is a String, the filename of a plist file. Its contents are added to the app's plist.
* When the value is an Object, an already-parsed plist data structure that is merged into the app's plist.
*/
extendInfo?: string | {[property: string]: any};
/**
* The bundle identifier to use in the application helper's plist.
*/
helperBundleId?: string;
/**
* If present, signs OS X target apps when the host platform is OS X and XCode is installed.
*/
osxSign?: boolean | ElectronOsXSignOptions;
/**
* The URL protocol scheme(s) to associate the app with
*/
protocol?: string;
/**
* The descriptive name(s) of the URL protocol scheme(s) specified via the protocol option.
* Maps to the CFBundleURLName metadata property.
*/
protocolName?: string[];
/**
* Windows targets only
*/
win32metadata?: Win32Metadata;
}
}
declare module "electron-packager" {
const packager: ElectronPackager.Packager;
export = packager;
}
interface NodeRequireFunction {
(id: "electron-packager"): ElectronPackager.Packager;
}

View File

@ -0,0 +1,5 @@
{ "extends": "dtslint/dt.json",
"rules": {
"no-conditional-assignment": false
}
}

View File

@ -64,6 +64,6 @@ declare module "email-templates" {
* @param {EmailTemplateCallback|Object} locals The variables or callback function.
* @param {EmailTemplateCallback} callback The callback function.
*/
render(locals: EmailTemplateCallback|Object, callback?: EmailTemplateCallback): void;
render(locals: EmailTemplateCallback|Object, callback?: EmailTemplateCallback): void | Promise<EmailTemplateResults>;
}
}

View File

@ -2449,6 +2449,7 @@ declare namespace Ember {
function observersFor(obj: any, path: string): any[];
function onLoad(name: string, callback: Function): void;
const onError: Error;
function onerror(error: any): void;
function overrideChains(obj: any, keyName: string, m: any): boolean;
// ReSharper disable once DuplicatingLocalDeclaration
const platform: {
@ -2480,6 +2481,7 @@ declare namespace Ember {
throttle(target: any, method: Function | string, ...args: any[]): void;
queues: any[];
};
function runInDebug(fn: Function): void;
function runLoadHooks(name: string, object: any): void;
function sendEvent(obj: any, eventName: string, params?: any[], actions?: any[]): boolean;
function set(obj: any, keyName: string, value: any): any;

View File

@ -1,101 +0,0 @@
// Example for CommonJS/AMD
/*
import eventemitter2 = require("eventemitter2");
var EventEmitter2 = eventemitter2.EventEmitter2;
class Child extends eventemitter2.EventEmitter2 {
}
*/
// This class definition doesn't work in CommonJS/AMD.
class Child extends EventEmitter2 {
}
var server = new EventEmitter2();
function testConfiguration() {
var foo = new EventEmitter2({
wildcard: true,
delimiter: '::',
newListener: false,
maxListeners: 20,
verboseMemoryLeak: true
});
var bar = new EventEmitter2({});
var bazz = new EventEmitter2();
}
function testAddListener() {
server.addListener('data', function (value1: any, value2: any, value3: any) {
console.log('The event was raised!');
});
server.addListener('data', function (value: any) {
console.log('The event was raised!');
});
}
function testOn() {
server.on('data', function (value1: any, value2: any, value3: any) {
console.log('The event was raised!');
});
server.on('data', function (value: any) {
console.log('The event was raised!');
});
}
function testOnAny() {
server.onAny(function (value: any) {
console.log('All events trigger this.');
});
}
function testOffAny() {
server.offAny(function (value: any) {
console.log('The event was raised!');
});
}
function testOnce() {
server.once('get', function (value: any) {
console.log('Ah, we have our first value!');
});
}
function testMany() {
server.many('get', 4, function (value: any) {
console.log('This event will be listened to exactly four times.');
});
}
function testRemoveListener() {
var callback = function (value: any) {
console.log('someone connected!');
};
server.on('get', callback);
server.removeListener('get', callback);
}
function testRemoveAllListeners() {
server.removeAllListeners(["test::event", "another::test::event"]);
server.removeAllListeners("test");
server.removeAllListeners();
}
function testSetMaxListeners() {
server.setMaxListeners(40);
}
function testListeners() {
console.log(server.listeners('get'));
}
function testListenersAny() {
console.log(server.listenersAny()[0]);
}
function testEmit() {
server.emit('foo.bazz');
server.emit(['foo', 'bar']);
}

View File

@ -1,258 +0,0 @@
// Type definitions for EventEmitter2 v2.2.0
// Project: https://github.com/asyncly/EventEmitter2
// Definitions by: ryiwamoto <https://github.com/ryiwamoto/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface EventEmitter2Configuration {
/**
* use wildcards
*/
wildcard?: boolean;
/**
* the delimiter used to segment namespaces, defaults to `.`.
*/
delimiter?: string;
/**
* if you want to emit the newListener event set to true.
*/
newListener?: boolean;
/**
* max listeners that can be assigned to an event, default 10.
*/
maxListeners?: number;
/**
* show event name in memory leak message when more than maximum amount of listeners is assigned, default false
*/
verboseMemoryLeak?: boolean;
}
declare class EventEmitter2 {
/**
* @param conf
*/
constructor(conf?: EventEmitter2Configuration);
/**
* Adds a listener to the end of the listeners array for the specified event.
* @param event
* @param listener
*/
addListener(event: string, listener: Function): EventEmitter2;
/**
* Adds a listener to the end of the listeners array for the specified event.
* @param event
* @param listener
*/
on(event: string | string[], listener: Function): EventEmitter2;
/**
* Adds a listener that will be fired when any event is emitted.
* @param listener
*/
onAny(listener: Function): EventEmitter2;
/**
* Removes the listener that will be fired when any event is emitted.
* @param listener
*/
offAny(listener?: Function): EventEmitter2;
/**
* Adds a one time listener for the event.
* The listener is invoked only the first time the event is fired, after which it is removed.
* @param event
* @param listener
*/
once(event: string, listener: Function): EventEmitter2;
/**
* Adds a listener that will execute n times for the event before being removed.
* The listener is invoked only the first n times the event is fired, after which it is removed.
* @param event
* @param timesToListen
* @param listener
*/
many(event: string, timesToListen: number, listener: Function): EventEmitter2;
/**
* Remove a listener from the listener array for the specified event.
* Caution: changes array indices in the listener array behind the listener.
* @param event
* @param listener
*/
removeListener(event: string, listener: Function): EventEmitter2;
/**
* Remove a listener from the listener array for the specified event.
* Caution: changes array indices in the listener array behind the listener.
* @param event
* @param listener
*/
off(event: string, listener: Function): EventEmitter2;
/**
* Removes all listeners, or those of the specified event.
* @param event
*/
removeAllListeners(event?: string): EventEmitter2;
/**
* Removes all listeners, or those of the specified event.
* @param events
*/
removeAllListeners(events: string[]): EventEmitter2;
/**
* By default EventEmitters will print a warning if more than 10 listeners are added to it.
* This is a useful default which helps finding memory leaks.
* Obviously not all Emitters should be limited to 10. This function allows that to be increased.
* Set to zero for unlimited.
* @param n
*/
setMaxListeners(n: number): void;
/**
* Returns an array of listeners for the specified event. This array can be manipulated, e.g. to remove listeners.
* @param event
*/
listeners(event: string): Function[];
/**
* Returns an array of listeners that are listening for any event that is specified.
* This array can be manipulated, e.g. to remove listeners.
*/
listenersAny(): Function[];
/**
* Execute each of the listeners that may be listening for the specified event name in order with the list of arguments.
* @param event
* @param args
*/
emit(event: string | string[], ...args: any[]): boolean;
/**
* Execute each of the listeners that may be listening for the specified event name in order with the list of arguments.
* @param event
*/
emit(event: string[]): boolean;
}
declare module "eventemitter2" {
export class EventEmitter2 {
/**
* @param conf
*/
constructor(conf?: EventEmitter2Configuration);
/**
* Adds a listener to the end of the listeners array for the specified event.
* @param event
* @param listener
*/
addListener(event: string, listener: Function): EventEmitter2;
/**
* Adds a listener to the end of the listeners array for the specified event.
* @param event
* @param listener
*/
on(event: string | string[], listener: Function): EventEmitter2;
/**
* Adds a listener that will be fired when any event is emitted.
* @param listener
*/
onAny(listener: Function): EventEmitter2;
/**
* Removes the listener that will be fired when any event is emitted.
* @param listener
*/
offAny(listener: Function): EventEmitter2;
/**
* Adds a one time listener for the event.
* The listener is invoked only the first time the event is fired, after which it is removed.
* @param event
* @param listener
*/
once(event: string, listener: Function): EventEmitter2;
/**
* Adds a listener that will execute n times for the event before being removed.
* The listener is invoked only the first n times the event is fired, after which it is removed.
* @param event
* @param timesToListen
* @param listener
*/
many(event: string, timesToListen: number, listener: Function): EventEmitter2;
/**
* Remove a listener from the listener array for the specified event.
* Caution: changes array indices in the listener array behind the listener.
* @param event
* @param listener
*/
removeListener(event: string, listener: Function): EventEmitter2;
/**
* Remove a listener from the listener array for the specified event.
* Caution: changes array indices in the listener array behind the listener.
* @param event
* @param listener
*/
off(event: string, listener: Function): EventEmitter2;
/**
* Removes all listeners, or those of the specified event.
* @param event
*/
removeAllListeners(event?: string): EventEmitter2;
/**
* Removes all listeners, or those of the specified event.
* @param events
*/
removeAllListeners(events: string[]): EventEmitter2;
/**
* By default EventEmitters will print a warning if more than 10 listeners are added to it.
* This is a useful default which helps finding memory leaks.
* Obviously not all Emitters should be limited to 10. This function allows that to be increased.
* Set to zero for unlimited.
* @param n
*/
setMaxListeners(n: number): void;
/**
* Returns an array of listeners for the specified event. This array can be manipulated, e.g. to remove listeners.
* @param event
*/
listeners(event: string): Function[];
/**
* Returns an array of listeners that are listening for any event that is specified.
* This array can be manipulated, e.g. to remove listeners.
*/
listenersAny(): Function[];
/**
* Execute each of the listeners that may be listening for the specified event name in order with the list of arguments.
* @param event
* @param args
*/
emit(event: string | string[], ...args: any[]): boolean;
/**
* Execute each of the listeners that may be listening for the specified event name in order with the list of arguments.
* @param event
*/
emit(event: string[]): boolean;
}
}

View File

@ -239,9 +239,9 @@ interface Request extends http.IncomingMessage, Express.Request {
* // => "json"
*/
accepts(): string[];
accepts(type: string): string | boolean;
accepts(type: string[]): string | boolean;
accepts(...type: string[]): string | boolean;
accepts(type: string): string | false;
accepts(type: string[]): string | false;
accepts(...type: string[]): string | false;
/**
* Returns the first accepted charset of the specified character sets,
@ -252,9 +252,9 @@ interface Request extends http.IncomingMessage, Express.Request {
* @param charset
*/
acceptsCharsets(): string[];
acceptsCharsets(charset: string): string | boolean;
acceptsCharsets(charset: string[]): string | boolean;
acceptsCharsets(...charset: string[]): string | boolean;
acceptsCharsets(charset: string): string | false;
acceptsCharsets(charset: string[]): string | false;
acceptsCharsets(...charset: string[]): string | false;
/**
* Returns the first accepted encoding of the specified encodings,
@ -265,9 +265,9 @@ interface Request extends http.IncomingMessage, Express.Request {
* @param encoding
*/
acceptsEncodings(): string[];
acceptsEncodings(encoding: string): string | boolean;
acceptsEncodings(encoding: string[]): string | boolean;
acceptsEncodings(...encoding: string[]): string | boolean;
acceptsEncodings(encoding: string): string | false;
acceptsEncodings(encoding: string[]): string | false;
acceptsEncodings(...encoding: string[]): string | false;
/**
* Returns the first accepted language of the specified languages,
@ -279,9 +279,9 @@ interface Request extends http.IncomingMessage, Express.Request {
* @param lang
*/
acceptsLanguages(): string[];
acceptsLanguages(lang: string): string | boolean;
acceptsLanguages(lang: string[]): string | boolean;
acceptsLanguages(...lang: string[]): string | boolean;
acceptsLanguages(lang: string): string | false;
acceptsLanguages(lang: string[]): string | false;
acceptsLanguages(...lang: string[]): string | false;
/**
* Parse Range header field,

View File

@ -51,22 +51,22 @@ namespace express_tests {
router.route('/users')
.get((req, res, next) => {
let types: string[] = req.accepts();
let type: string | boolean = req.accepts('json');
let type: string | false = req.accepts('json');
type = req.accepts(['json', 'text']);
type = req.accepts('json', 'text');
let charsets: string[] = req.acceptsCharsets();
let charset: string | boolean = req.acceptsCharsets('utf-8');
let charset: string | false = req.acceptsCharsets('utf-8');
charset = req.acceptsCharsets(['utf-8', 'utf-16']);
charset = req.acceptsCharsets('utf-8', 'utf-16');
let encodings: string[] = req.acceptsEncodings();
let encoding: string | boolean = req.acceptsEncodings('gzip');
let encoding: string | false = req.acceptsEncodings('gzip');
encoding = req.acceptsEncodings(['gzip', 'deflate']);
encoding = req.acceptsEncodings('gzip', 'deflate');
let languages: string[] = req.acceptsLanguages();
let language: string | boolean = req.acceptsLanguages('en');
let language: string | false = req.acceptsLanguages('en');
language = req.acceptsLanguages(['en', 'ja']);
language = req.acceptsLanguages('en', 'ja');

View File

@ -2,6 +2,7 @@
// Project: https://github.com/chmln/flatpickr
// Definitions by: James Birtles <https://github.com/UnwrittenFun>
// Rowell Heria <https://github.com/rowellx68>
// Michael Wagner <https://github.com/wagich>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function flatpickr(element: string | Element | HTMLElement, options?: Flatpickr.Options): Flatpickr;
@ -21,6 +22,11 @@ declare class Flatpickr {
set(option: string, value: any): void;
setDate(date: Flatpickr.DateString | Flatpickr.DateString[], triggerChange?: boolean, dateFormat?: string): void;
toggle(): void;
static localize(locale: string | Flatpickr.Locale): void;
static l10ns: {
default: Flatpickr.Locale;
};
}
declare namespace Flatpickr {
@ -63,6 +69,30 @@ declare namespace Flatpickr {
utc?: boolean;
weekNumbers?: boolean;
wrap?: boolean;
locale?: string | Locale;
}
interface Locale {
weekdays?: {
shorthand?: string[];
longhand?: string[];
};
months?: {
shorthand?: string[];
longhand?: string[];
};
firstDayOfWeek?: number;
weekAbbreviation?: string;
rangeSeparator?: string;
am?: string;
pm?: string;
ordinal?: ((nth: number) => string) | string;
scrollTitle?: string;
toggleTitle?: string;
}
type DateString = Date | string;

View File

@ -23,3 +23,17 @@ var result1: boolean = isError(sample1);
var result2: boolean = isFSA(sample1);
var result3: boolean = isError(sample2);
var result4: boolean = isFSA(sample2);
declare function alert (message: string): void
function unwrapAction(action: { type: string }) {
if (isFSA(action)) {
if (isError(action)) {
alert(action.payload!.message)
}
return action.payload
}
}
var result5: TextPayload = unwrapAction(sample1)
var result6: Error = unwrapAction(sample2)

View File

@ -5,7 +5,7 @@
export interface ErrorAction extends Action<Error> {
error: boolean;
error: true;
}
export interface Action<T> {
@ -14,16 +14,16 @@ export interface Action<T> {
error?: boolean;
}
// Usage: var action: Action<sring> & AnyMeta;
/** Usage: `var action: Action<string> & AnyMeta;` */
export interface AnyMeta {
meta: any
}
// Usage: var action: Action<sring> & TypedMeta<string>;
/** Usage: `var action: Action<string> & TypedMeta<string>;` */
export interface TypedMeta<T> {
meta: T
}
export declare function isFSA(action: any): boolean;
export declare function isFSA(action: any): action is Action<any>;
export declare function isError(action: any): boolean;
export declare function isError(action: any): action is ErrorAction;

View File

@ -47,7 +47,7 @@ declare namespace gapi.auth2 {
/**
* Get permission from the user to access the specified scopes offline.
*/
grantOfflineAccess(options: {
grantOfflineAccess(options?: {
scope?: string;
prompt?: "select_account" | "consent";
app_package_name?: string;

View File

@ -1,8 +1,29 @@
import * as Hls from 'hls.js';
function process(playlist: string) {
return playlist;
}
class pLoader extends Hls.DefaultConfig.loader {
constructor(config: Hls.LoaderConfig) {
super(config);
const load = this.load.bind(this);
this.load = (context: Hls.LoaderContext, cfg: Hls.LoaderConfig, callbacks: Hls.LoaderCallbacks) => {
if (context.type === 'manifest') {
const onSuccess = callbacks.onSuccess;
callbacks.onSuccess = (response: Hls.LoaderResponse, stats: Hls.LoaderStats, context: Hls.LoaderContext) => {
response.data = process(response.data as string);
onSuccess(response, stats, context);
};
}
load(context, config, callbacks);
};
}
}
if (Hls.isSupported()) {
const video = <HTMLVideoElement> document.getElementById('video');
const hls = new Hls();
const hls = new Hls({ pLoader });
const version: string = Hls.version;
hls.loadSource('http://www.streambox.fr/playlists/test_001/stream.m3u8');
hls.attachMedia(video);

View File

@ -4,6 +4,22 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
declare class Loader {
constructor(config: Hls.LoaderConfig)
/**
* Start retrieving content located at given URL (HTTP GET).
*/
load(context: Hls.LoaderContext, config: Hls.LoaderConfig, callbacks: Hls.LoaderCallbacks): void;
/**
* Abort any loading in progress.
*/
abort(): void;
/**
* Destroy loading context.
*/
destroy(): void;
}
declare namespace Hls {
/**
* Hls events
@ -385,6 +401,410 @@ declare namespace Hls {
const version: string;
interface Config {
/**
* (default: true)
* if set to true, start level playlist and first fragments will be loaded automatically, after triggering of Hls.Events.MANIFEST_PARSED event
* if set to false, an explicit API call (hls.startLoad(startPosition=-1)) will be needed to start quality level/fragment loading.
*/
autoStartLoad: boolean;
/**
* (default -1)
* if set to -1, playback will start from initialTime=0 for VoD and according to liveSyncDuration/liveSyncDurationCount config params for Live
* otherwise, playback will start from predefined value. (unless stated otherwise in autoStartLoad=false mode : in that case startPosition can be overrided using hls.startLoad(startPosition)).
*/
startPosition: number;
/**
* (default: false)
* if set to true, the adaptive algorithm with limit levels usable in auto-quality by the HTML video element dimensions (width and height)
* if set to false, levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration.
*/
capLevelToPlayerSize: boolean;
/**
* (default: false)
* setting config.debug = true; will turn on debug logs on JS console.
* a logger object could also be provided for custom logging: config.debug = customLogger;
*/
debug: boolean;
/**
* (default: undefined)
* if audio codec is not signaled in variant manifest, or if only a stream manifest is provided, hls.js tries to guess audio codec by parsing audio sampling rate in ADTS header.
* If sampling rate is less or equal than 22050 Hz, then hls.js assumes it is HE-AAC, otherwise it assumes it is AAC-LC.
* This could result in bad guess, leading to audio decode error, ending up in media error.
* It is possible to hint default audiocodec to hls.js by configuring this value as below:
* mp4a.40.2 (AAC-LC) or
* mp4a.40.5 (HE-AAC) or
* undefined (guess based on sampling rate)
*/
defaultAudioCodec: string;
/**
* (default: 1)
* number of segments needed to start a playback of Live stream.
*/
initialLiveManifestSize: number;
/**
* (default: 30 seconds)
* Maximum buffer length in seconds. If buffer length is/become less than this value, a new fragment will be loaded.
* This is the guaranteed buffer length hls.js will try to reach, regardless of maxBufferSize.
*/
maxBufferLength: number;
/**
* (default 600s)
* Maximum buffer length in seconds. Hls.js will never exceed this value, even if maxBufferSize is not reached yet.
* hls.js tries to buffer up to a maximum number of bytes (60 MB by default) rather than to buffer up to a maximum nb of seconds.
* This is to mimic the browser behaviour (the buffer eviction algorithm is starting after the browser detects that video buffer size reaches a limit in bytes)
* maxBufferLength is the minimum guaranteed buffer length that hls.js will try to achieve, even if that value exceeds the amount of bytes 60 MB of memory.
* maxMaxBufferLength acts as a capping value, as if bitrate is really low, you could need more than one hour of buffer to fill 60 MB.
*/
maxMaxBufferLength: number;
/**
* (default: 60 MB)
* 'Minimum' maximum buffer size in bytes. If buffer size upfront is bigger than this value, no fragment will be loaded
*/
maxBufferSize: number;
/**
* (default: 0.5 seconds)
* 'Maximum' inter-fragment buffer hole tolerance that hls.js can cope with when searching for the next fragment to load. When switching between quality level,
* fragments might not be perfectly aligned.
* This could result in small overlapping or hole in media buffer. This tolerance factor helps cope with this.
*/
maxBufferHole: number;
/**
* (default: 4s)
*
* ABR algorithm will always try to choose a quality level that should avoid rebuffering. In case no quality level with this criteria can
* be found (lets say for example that buffer length is 1s, but fetching a fragment at lowest quality is predicted to take around 2s ...
* ie we can forecast around 1s of rebuffering ...) then ABR algorithm will try to find a level that should guarantee less than
* maxStarvationDelay of buffering.
*/
maxStarvationDelay: number;
/**
* (default: 2s)
* In case playback is stalled, and a buffered range is available upfront, less than maxSeekHole seconds from current media position,
* hls.js will jump over this buffer hole to reach the beginning of this following buffered range.
* maxSeekHole allows to configure this jumpable threshold.
*/
maxSeekHole: number;
/**
* (default: 0.5s)
* media element is expected to play and if currentTime has not moved for more than lowBufferWatchdogPeriod and if there are less than maxBufferHole seconds buffered upfront,
* hls.js will try to nudge playhead to recover playback
*/
lowBufferWatchdogPeriod: number;
/**
* (default: 3s)
* if media element is expected to play and if currentTime has not moved for more than highBufferWatchdogPeriod and if there are more than maxBufferHole seconds buffered upfront,
* hls.js will try to nudge playhead to recover playback
*/
highBufferWatchdogPeriod: number;
/**
* (default: 0.1s)
* In case playback continues to stall after first playhead nudging, currentTime will be nudged evenmore following nudgeOffset to try to restore playback.
* media.currentTime += (nb nudge retry -1)*nudgeOffset
*/
nudgeOffset: number;
/**
* (default: 3s)
* In case playback continues to stall after first playhead nudging, currentTime will be nudged evenmore following nudgeOffset to try to restore playback.
* media.currentTime += (nb nudge retry -1)*nudgeOffset
*/
nudgeMaxRetry: number;
/**
* (default 0.2s)
* This tolerance factor is used during fragment lookup.
* Instead of checking whether buffered.end is located within [start, end] range, frag lookup will be done by checking within [start-maxFragLookUpTolerance, end-maxFragLookUpTolerance] range.
* This tolerance factor is used to cope with situations like:
* buffered.end = 9.991
* frag[0] : [0,10]
* frag[1] : [10,20]
* buffered.end is within frag[0] range, but as we are close to frag[1], frag[1] should be choosen instead
* If maxFragLookUpTolerance = 0.2, this lookup will be adjusted to
* frag[0] : [-0.2,9.8]
* frag[1] : [9.8,19.8]
* This time, buffered.end is within frag[1] range, and frag[1] will be the next fragment to be loaded, as expected
*/
maxLoadingDelay: number;
/**
* (default 4s)
*
* max video loading delay used in automatic start level selection : in that mode ABR controller will ensure that video loading time (ie
* the time to fetch the first fragment at lowest quality level + the time to fetch the fragment at the appropriate quality level is less
* than maxLoadingDelay )
*/
maxFragLookUpTolerance: number;
/**
* (default: 3)
* edge of live delay, expressed in multiple of EXT-X-TARGETDURATION. if set to 3, playback will start from fragment N-3, N being the last fragment of the live playlist.
* Decreasing this value is likely to cause playback stalls.
*/
liveSyncDurationCount: number;
/**
* (default: undefined)
* Alternative parameter to liveSyncDurationCount, expressed in seconds vs number of segments.
* If defined in the configuration object, liveSyncDuration will take precedence over the default liveSyncDurationCount.
* You can't define this parameter and either liveSyncDurationCount or liveMaxLatencyDurationCount in your configuration object at the same time.
* A value too low (inferior to ~3 segment durations) is likely to cause playback stalls.
*/
liveSyncDuration: number;
/**
* (default: Infinity)
* maximum delay allowed from edge of live, expressed in multiple of EXT-X-TARGETDURATION.
* If set to 10, the player will seek back to liveSyncDurationCount whenever the next fragment to be loaded is older than N-10, N being the last fragment of the live playlist.
* If set, this value must be stricly superior to liveSyncDurationCount a value too close from liveSyncDurationCount is likely to cause playback stalls.
*/
liveMaxLatencyDurationCount: number;
/**
* (default: undefined)
* Alternative parameter to liveMaxLatencyDurationCount, expressed in seconds vs number of segments.
* If defined in the configuration object, liveMaxLatencyDuration will take precedence over the default liveMaxLatencyDurationCount.
* If set, this value must be stricly superior to liveSyncDuration which must be defined as well.
* You can't define this parameter and either liveSyncDurationCount or liveMaxLatencyDurationCount in your configuration object at the same time.
* A value too close from liveSyncDuration is likely to cause playback stalls.
*/
liveMaxLatencyDuration: number;
/**
* (default: true)
* Enable WebWorker (if available on browser) for TS demuxing/MP4 remuxing, to improve performance and avoid lag/frame drops.
*/
enableWorker: boolean;
/**
* (default: true)
* Enable to use JavaScript version AES decryption for fallback of WebCrypto API.
*/
enableSoftwareAES: boolean;
/**
* (default: undefined)
* When set, use this level as the default hls.startLevel. Keep in mind that the startLevel set with the API takes precedence over
* config.startLevel configuration parameter.
*/
startLevel: number;
/**
* (default: 10000ms for level and manifest)
* URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted.
* It is up to the application to catch this event and treat it as needed.
*/
manifestLoadingTimeOut: number;
/**
* (default: 3)
* Max number of load retries.
*/
manifestLoadingMaxRetry: number;
/**
* (default: 1000 ms)
* Initial delay between XMLHttpRequest error and first load retry (in ms).
* Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff).
* Prefetch start fragment although media not attached.
*/
manifestLoadingRetryDelay: number;
/**
* (default: 64000 ms)
* Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met.
*/
manifestLoadingMaxRetryTimeout: number;
/**
* (default: 60000ms for fragment)
* URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted.
* It is up to the application to catch this event and treat it as needed.
*/
levelLoadingTimeOut: number;
/**
* (default: 3)
* Max number of load retries.
*/
levelLoadingMaxRetry: number;
/**
* (default: 1000 ms)
* Initial delay between XMLHttpRequest error and first load retry (in ms).
* Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff).
* Prefetch start fragment although media not attached.
*/
levelLoadingRetryDelay: number;
/**
* (default: 64000 ms)
* Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met.
*/
levelLoadingMaxRetryTimeout: number;
/**
* (default: 60000ms for fragment)
* URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted.
* It is up to the application to catch this event and treat it as needed.
*/
fragLoadingTimeOut: number;
/**
* (default: 3)
* Max number of load retries.
*/
fragLoadingMaxRetry: number;
/**
* (default: 1000 ms)
* Initial delay between XMLHttpRequest error and first load retry (in ms).
* Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff).
* Prefetch start fragment although media not attached.
*/
fragLoadingRetryDelay: number;
/**
* (default: 64000 ms)
* Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met.
*/
fragLoadingMaxRetryDelay: number;
/**
* (default: false)
* Start prefetching start fragment although media not attached yet. Max number of append retries.
*/
startFragPrefech: boolean;
/**
* (default: 3)
* Max number of sourceBuffer.appendBuffer() retry upon error. Such error could happen in loop with UHD streams, when internal buffer is full. (Quota Exceeding Error will be triggered).
* In that case we need to wait for the browser to evict some data before being able to append buffer correctly.
*/
appendErrorMaxRetry: number;
/**
* (default: standard XMLHttpRequest-based URL loader)
* Override standard URL loader by a custom one. Could be useful for P2P or stubbing (testing).
* Use this, if you want to overwrite both the fragment and the playlist loader.
* Note: If fLoader or pLoader are used, they overwrite loader!
*/
loader: typeof Loader;
/**
* (default: undefined)
* This enables the manipulation of the fragment loader.
* Note: This will overwrite the default loader, as well as your own loader function.
*/
fLoader?: typeof Loader;
/**
* (default: undefined)
* This enables the manipulation of the playlist loader.
* Note: This will overwrite the default loader, as well as your own loader function.
*/
pLoader?: typeof Loader;
/**
* (default: undefined)
* XMLHttpRequest customization callback for default XHR based loader.
* Parameter should be a function with two arguments (xhr: XMLHttpRequest, url: string).
* If xhrSetup is specified, default loader will invoke it before calling xhr.send(). This allows user to easily modify/setup XHR.
*/
xhrSetup?(xhr: XMLHttpRequest, url: string): void;
/**
* (default: undefined)
* Fetch customization callback for Fetch based loader.
* Parameter should be a function with two arguments (context and Request Init Params).
* If fetchSetup is specified and Fetch loader is used, fetchSetup will be triggered to instantiate Request Object. This allows user to easily tweak Fetch loader.
*/
fetchSetup?(context: any, initParams: any): Request;
/**
* (default: internal ABR controller)
* Customized Adaptive Bitrate Streaming Controller.
* Parameter should be a class providing 2 getters, 2 setters and a destroy() method:
* get/set nextAutoLevel: return next auto-quality level/force next auto-quality level that should be returned (currently used for emergency switch down)
* get/set autoLevelCapping: capping/max level value that could be used by ABR Controller
* destroy(): should clean-up all used resources
*/
abrController: AbrController;
/**
* (default: internal track timeline controller)
* Customized text track syncronization controller.
* Parameter should be a class with a destroy() method:
* destroy() : should clean-up all used resources
*/
timelineController: TimelineController;
/**
* (default: true)
* whether or not to enable CEA-708 captions
*/
enableCEA708Captions: boolean;
/**
* (default: English)
* Label for the text track generated for CEA-708 captions track 1. This is how it will appear in the browser's native menu for subtitles and captions.
*/
captionsTextTrack1Label: string;
/**
* (default: en)
* RFC 3066 language code for the text track generated for CEA-708 captions track 1.
*/
captionsTextTrack1LanguagedCode: string;
/**
* (default: Spanish)
* Label for the text track generated for CEA-708 captions track 2. This is how it will appear in the browser's native menu for subtitles and captions.
*/
captionsTextTrack2Label: string;
/**
* (default: es)
* RFC 3066 language code for the text track generated for CEA-708 captions track 2.
*/
captionsTextTrack2LanguageCode: string;
/**
* (default: false)
* If a segment's video track is shorter than its audio track by > min(maxSeekHole, maxBufferHole), extend the final video frame's duration to match the audio track's duration.
* This helps playback continue in certain cases that might otherwise get stuck.
*/
stretchShortVideoTrack: boolean;
/**
* (default: true)
* Whether or not to force having a key frame in the first AVC sample after a discontinuity.
* If set to true, after a discontinuity, the AVC samples without any key frame will be dropped until finding one that contains a key frame.
* If set to false, all AVC samples will be kept, which can help avoid holes in the stream. Setting this parameter to false can also generate decoding weirdness when switching level or seeking.
*/
forceKeyFrameOnDiscontinuity: boolean;
/**
* (default: 5.0)
* Fast bitrate Exponential moving average half-life, used to compute average bitrate for Live streams.
* Half of the estimate is based on the last abrEwmaFastLive seconds of sample history. Each of the sample is weighted by the fragment loading duration.
* parameter should be a float greater than 0
*/
abrEwmaFastLive: number;
/**
* (default: 9.0)
* Slow bitrate Exponential moving average half-life, used to compute average bitrate for Live streams.
* Half of the estimate is based on the last abrEwmaSlowLive seconds of sample history. Each of the sample is weighted by the fragment loading duration.
* parameter should be a float greater than abrEwmaFastLive
*/
arbEwmaSlowLive: number;
/**
* (default: 4.0)
* Fast bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams.
* Half of the estimate is based on the last abrEwmaFastVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration.
* parameter should be a float greater than 0
*/
arbEwmaFastVod: number;
/**
* (default: 15.0)
* Slow bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams.
* Half of the estimate is based on the last abrEwmaSlowVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration.
* parameter should be a float greater than abrEwmaFastVoD
*/
arbEwmaSlowVod: number;
/**
* (default: 500000)
* Default bandwidth estimate in bits/second prior to collecting fragment bandwidth samples.
* parameter should be a float
*/
arbEwmaDefaultEstimate: number;
/**
* (default: 0.8)
* Scale factor to be applied against measured bandwidth average, to determine whether we can stay on current or lower quality level.
* If abrBandWidthFactor * bandwidth average < level.bitrate then ABR can switch to that level providing that it is equal or less than current level.
*/
arbBandWidthFactor: number;
/**
* (default: 0.7)
* Scale factor to be applied against measured bandwidth average, to determine whether we can switch up to a higher quality level.
* If abrBandWidthUpFactor * bandwidth average < level.bitrate then ABR can switch up to that quality level.
*/
arbBandWidthUpFactor: number;
/**
* (default: false)
* max bitrate used in ABR by avg measured bitrate i.e. if bitrate signaled in variant manifest for a given level is 2Mb/s but average bitrate measured on this level is 2.5Mb/s,
* then if config value is set to true, ABR will use 2.5 Mb/s for this quality level.
*/
abrMaxWithRealBitrate: boolean;
/**
* (default: 0)
* Return the capping/min bandwidth value that could be used by automatic level selection algorithm.
* Useful when browser or tab of the browser is not in the focus and bandwidth drops
*/
minAutoBitrate: number;
}
interface OptionalConfig {
/**
* (default: true)
* if set to true, start level playlist and first fragments will be loaded automatically, after triggering of Hls.Events.MANIFEST_PARSED event
@ -647,19 +1067,19 @@ declare namespace Hls {
* Use this, if you want to overwrite both the fragment and the playlist loader.
* Note: If fLoader or pLoader are used, they overwrite loader!
*/
loader?: any;
loader?: typeof Loader;
/**
* (default: undefined)
* This enables the manipulation of the fragment loader.
* Note: This will overwrite the default loader, as well as your own loader function.
*/
fLoader?: any;
fLoader?: typeof Loader;
/**
* (default: undefined)
* This enables the manipulation of the playlist loader.
* Note: This will overwrite the default loader, as well as your own loader function.
*/
pLoader?: any;
pLoader?: typeof Loader;
/**
* (default: undefined)
* XMLHttpRequest customization callback for default XHR based loader.
@ -1121,18 +1541,6 @@ declare namespace Hls {
length?: number;
}
interface Loader {
load(context: LoaderContext, config: LoaderConfig, callbacks: LoaderCallbacks): void;
/**
* Abort any loading in progress.
*/
abort(): void;
/**
* Destroy loading context.
*/
destroy(): void;
}
interface LoaderContext {
/**
* target URL
@ -1200,7 +1608,7 @@ declare class Hls {
/**
* Constructor. Can be provided an HlsConfig object as default properties and or overrides
*/
constructor(config?: Hls.Config)
constructor(config?: Hls.OptionalConfig)
/**
* return array of available quality levels
*/

View File

@ -6,13 +6,14 @@ i18n.init({
en: {
translation: {
helloWorld: 'Hello, world!',
helloWorldInterpolated: 'Hello, {{name}}!'
helloWorldInterpolated: 'Hello, {{name}}!',
uppercaseFormatted: '{{text^uppercase}} just uppercased',
}
},
ru: {
translation: {
helloWorld: 'Привет, мир!',
helloWorldInterpolated: 'Привет, {{name}}!'
helloWorldInterpolated: 'Привет, {{name}}!',
}
}
},
@ -31,23 +32,29 @@ i18n.init({
contextSeparator: '_',
saveMissing: true,
saveMissingTo: 'all',
missingKeyHandler: (lng:string, ns:string, key:string, fallbackValue:string) => {
missingKeyHandler: (lng: string, ns: string, key: string, fallbackValue: string) => {
console.log('Lng: ' + lng + ', ns: ' + ns + ', key' + key + ', fallbackValue: ' + fallbackValue);
},
parseMissingKeyHandler: (key:string) => {
parseMissingKeyHandler: (key: string) => {
console.log(key);
},
appendNamespaceToMissingKey: true,
returnNull: false,
returnEmptyString: false,
returnObjects: false,
returnedObjectHandler: (key:string, value:string, options:any) => {
returnedObjectHandler: (key: string, value: string, options: any) => {
},
joinArrays: '\n',
overloadTranslationOptionHandler: (args:any[]) => {
overloadTranslationOptionHandler: (args: any[]) => {
return <i18n.TranslationOptions>{}
},
interpolation: <i18n.InterpolationOptions>{},
interpolation: {
format: function(value, format, lng) {
if (format === 'uppercase') return value.toUpperCase();
return value;
},
formatSeparator: '^',
},
detection: null,
backend: null,
cache: null,
@ -77,6 +84,10 @@ i18n.t('helloWorldInterpolated', <i18n.TranslationOptions> {
name: "world"
});
i18n.t('uppercaseFormatted', <i18n.TranslationOptions> {
text: 'can you hear me',
});
i18n.t('helloSingleFallbackLng', <i18n.TranslationOptions> {
fallbackLng: 'en'
});

View File

@ -1,11 +1,10 @@
// Type definitions for i18next v2.3.5
// Type definitions for i18next v8.4.2
// Project: http://i18next.com
// Definitions by: Michael Ledin <https://github.com/mxl>, Budi Irawan <https://github.com/deerawan>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Sources: https://github.com/i18next/i18next/
declare namespace i18n {
interface ResourceStore {
[language: string]: ResourceStoreLanguage;
@ -25,7 +24,12 @@ declare namespace i18n {
type FallbackLng = string | string[] | FallbackLngObjList;
type FormatFunction = (value: any, format: string, lng: string) => string;
interface InterpolationOptions {
format?: FormatFunction;
formatSeparator?: string;
escape?: (str: string) => string;
escapeValue?: boolean;
prefix?: string;
suffix?: string;
@ -99,40 +103,28 @@ declare namespace i18n {
}
type TranslationFunction = (key: string, options?: TranslationOptions) => string;
type LoadCallback = (error: any, t: TranslationFunction) => void;
interface I18n {
//constructor(options?: Options, callback?: (err: any, t: TranslationFunction) => void);
init(options?: Options&ReactOptions, callback?: (err: any, t: TranslationFunction) => void): I18n;
loadResources(callback?: (err: any) => void): void;
language: string;
languages: string[];
// api
init(options?: Options & ReactOptions, callback?: LoadCallback): I18n;
use(module: any): I18n;
changeLanguage(lng: string, callback?: (err: any, t: TranslationFunction) => void): void;
getFixedT(lng?: string, ns?: string | string[]): TranslationFunction;
t(key: string, options?: TranslationOptions): string | any | Array<any>;
t(key: string, options?: TranslationOptions): string | any | any[];
exists(key: string, options?: TranslationOptions): boolean;
getFixedT(lng?: string, ns?: string | string[]): TranslationFunction;
changeLanguage(lng: string, callback?: LoadCallback): void;
language: string;
languages: string[];
loadNamespaces(ns: string[], callback?: LoadCallback): void;
loadLanguages(lngs: string[], callback?: LoadCallback): void;
reloadResources(lng?: string[], ns?: string[]): void;
setDefaultNamespace(ns: string): void;
loadNamespaces(ns: string[], callback?: () => void): void;
loadLanguages(lngs: string[], callback?: () => void): void;
dir(lng?: string): string;
createInstance(options?: Options, callback?: (err: any, t: TranslationFunction) => void): I18n;
cloneInstance(options?: Options, callback?: (err: any, t: TranslationFunction) => void): I18n;
format: FormatFunction; // introduced in v8.4.0;
// instance creation
createInstance(options?: Options, callback?: LoadCallback): I18n;
cloneInstance(options?: Options, callback?: LoadCallback): I18n;
// events
on(event: string, listener: () => void): void;
on(initialized: 'initialized', listener: (options: i18n.Options) => void): void;
on(loaded: 'loaded', listener: (loaded: any) => void): void;
@ -141,8 +133,20 @@ declare namespace i18n {
on(added: 'added', listener: (lng: string, ns: string) => void): void;
on(removed: 'removed', listener: (lng: string, ns: string) => void): void;
on(languageChanged: 'languageChanged', listener: (lng: string) => void): void;
off(event: string, listener: () => void): void;
// resource handling
getResource(lng: string, ns: string, key: string, options?: {
keySeparator?: string,
}): ResourceStore;
addResource(lng: string, ns: string, key: string, value: string, options?: {
keySeparator?: string,
silent?: boolean,
}): void;
addResources(lng: string, ns: string, resources: ResourceStore): void;
addResourceBundle(lng: string, ns: string, resources: ResourceStore, deep: boolean, overwrite: boolean): void;
hasResourceBundle(lng: string, ns: string): boolean;
getResourceBundle(lng: string, ns: string): ResourceStore;
removeResourceBundle(lng: string, ns: string): void;
options: Options;
}

7
types/is-alphanumerical/index.d.ts vendored Normal file
View File

@ -0,0 +1,7 @@
// Type definitions for is-alphanumerical 1.0
// Project: https://github.com/wooorm/is-alphanumerical/
// Definitions by: Vu Tran <https://github.com/vutran>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function isAlphanumerical(val: string | boolean | number): boolean;
export = isAlphanumerical;

View File

@ -0,0 +1,7 @@
import isAlphanumerical = require('is-alphanumerical');
isAlphanumerical('a');
isAlphanumerical('z');
isAlphanumerical('0');
isAlphanumerical('9');
isAlphanumerical('💩');

View File

@ -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",
"is-alphanumerical-tests.ts"
]
}

View File

@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

1510
types/jquery/index.d.ts vendored

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1202,14 +1202,13 @@ function examples() {
// Attach a done, fail, and progress handler for the asyncEvent
$.when(asyncEvent()).then(
function(status) {
status === 3;
alert(status + ', things are going well');
},
function(status) {
alert(status + ', you fail this time');
},
function(status) {
// $('body').append(status);
$('body').append(status);
},
);
}
@ -1233,9 +1232,7 @@ function examples() {
// Use the object as a Promise
_obj.done(function(name) {
_obj.hello(name); // Will alert "Hello John"
});
/// TODO: This doesn't work even though .done() returns this
// .hello('Karl'); // Will alert "Hello Karl"
}).hello('Karl'); // Will alert "Hello Karl"
}
function deferred_then_0() {
@ -1392,7 +1389,7 @@ function examples() {
function each_2() {
$('button').click(function() {
$('div').each(function(index, element) {
// element == this
// element == this;
$(element).css('backgroundColor', 'yellow');
if ($(this).is('#stop')) {
$('span').text('Stopped at div index #' + index);
@ -3757,13 +3754,13 @@ function examples() {
function offset_0() {
var p = $('p:last');
var offset = p.offset();
var offset = p.offset()!;
p.html('left: ' + offset.left + ', top: ' + offset.top);
}
function offset_1() {
$('*', document.body).click(function(event) {
var offset = $(this).offset();
var offset = $(this).offset()!;
event.stopPropagation();
$('#result').text(this.tagName +
' coords ( ' + offset.left + ', ' + offset.top + ' )');

View File

@ -2,8 +2,9 @@
"extends": "dtslint/dt.json",
"rules": {
"ban-types": false,
"no-misused-new": false,
"callable-types": false,
"no-empty-interface": false,
"callable-types": false
"no-misused-new": false,
"space-before-function-paren": false
}
}

184
types/jsdom/index.d.ts vendored
View File

@ -12,17 +12,17 @@ import * as tough from 'tough-cookie';
import { Script } from 'vm';
export class JSDOM {
static fromURL(url: string | Buffer | jsdom.BinaryData, options?: jsdom.FromUrlOptions | object): Promise<JSDOM>;
static fromURL(url: string, options?: FromUrlOptions): Promise<JSDOM>;
static fromFile(url: string | Buffer | jsdom.BinaryData, options?: jsdom.Options | object): Promise<JSDOM>;
static fromFile(url: string, options?: FromFileOptions): Promise<JSDOM>;
static fragment(html: string): DocumentFragment;
constructor(html?: string | Buffer | jsdom.BinaryData, options?: jsdom.Options | object);
constructor(html?: string | Buffer | BinaryData, options?: ConstructorOptions);
readonly window: jsdom.Window;
readonly virtualConsole: jsdom.VirtualConsole;
readonly cookieJar: jsdom.CookieJar;
readonly window: DOMWindow;
readonly virtualConsole: VirtualConsole;
readonly cookieJar: CookieJar;
/**
* The serialize() method will return the HTML serialization of the document, including the doctype.
@ -42,97 +42,87 @@ export class JSDOM {
*/
runVMScript(script: Script): void;
reconfigure(settings: jsdom.ReconfigureSettings | object): void;
reconfigure(settings: ReconfigureSettings): void;
}
// Alias DOM Window so we can extend from it and still name the type Window
// tslint:disable-next-line strict-export-declare-modifiers
type DOMWindow = Window;
export namespace jsdom {
interface FromUrlOptions extends Pick<FromUrlOptions._Impl, keyof FromUrlOptions._Impl> { }
namespace FromUrlOptions {
interface _Impl {
/**
* referrer just affects the value read from document.referrer.
* It defaults to no referrer (which reflects as the empty string).
*/
referrer: string;
/**
* userAgent affects the value read from navigator.userAgent, as well as the User-Agent header sent while fetching subresources.
* It defaults to `Mozilla/5.0 (${process.platform}) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/${jsdomVersion}`.
*/
userAgent: string;
/**
* includeNodeLocations preserves the location info produced by the HTML parser,
* allowing you to retrieve it with the nodeLocation() method (described below).
* It defaults to false to give the best performance,
* and cannot be used with an XML content type since our XML parser does not support location info.
*/
includeNodeLocations: boolean;
runScripts: 'dangerously' | 'outside-only';
resources: 'usable';
virtualConsole: VirtualConsole;
cookieJar: CookieJar;
beforeParse(window: jsdom.Window): void;
}
}
interface Options extends Pick<Options._Impl, keyof Options._Impl> { }
namespace Options {
interface _Impl extends FromUrlOptions._Impl {
/**
* url sets the value returned by window.location, document.URL, and document.documentURI,
* and affects things like resolution of relative URLs within the document
* and the same-origin restrictions and referrer used while fetching subresources.
* It defaults to "about:blank".
*/
url: string;
/**
* contentType affects the value read from document.contentType, and how the document is parsed: as HTML or as XML.
* Values that are not "text/html" or an XML mime type will throw. It defaults to "text/html".
*/
contentType: string;
}
}
interface Window extends DOMWindow {
ran: number;
eval(script: string): void;
}
type BinaryData = ArrayBuffer | DataView | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array;
class VirtualConsole extends EventEmitter {
on<K extends keyof Console>(method: K, callback: Console[K]): this;
on(event: 'jsdomError', callback: (e: Error) => void): this;
sendTo(console: Console, options?: VirtualConsole.SendToOptions | object): this;
}
namespace VirtualConsole {
interface SendToOptions extends Pick<SendToOptions._Impl, keyof SendToOptions._Impl> { }
namespace SendToOptions {
interface _Impl {
omitJSDOMErrors: boolean;
}
}
}
class CookieJar extends tough.CookieJar { }
const toughCookie: typeof tough;
interface ReconfigureSettings extends Pick<ReconfigureSettings._Impl, keyof ReconfigureSettings._Impl> { }
namespace ReconfigureSettings {
interface _Impl {
windowTop: DOMWindow;
url: string;
}
}
export interface Options {
/**
* referrer just affects the value read from document.referrer.
* It defaults to no referrer (which reflects as the empty string).
*/
referrer?: string;
/**
* userAgent affects the value read from navigator.userAgent, as well as the User-Agent header sent while fetching subresources.
* It defaults to `Mozilla/5.0 (${process.platform}) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/${jsdomVersion}`.
*/
userAgent?: string;
/**
* includeNodeLocations preserves the location info produced by the HTML parser,
* allowing you to retrieve it with the nodeLocation() method (described below).
* It defaults to false to give the best performance,
* and cannot be used with an XML content type since our XML parser does not support location info.
*/
includeNodeLocations?: boolean;
runScripts?: 'dangerously' | 'outside-only';
resources?: 'usable';
virtualConsole?: VirtualConsole;
cookieJar?: CookieJar;
beforeParse?(window: DOMWindow): void;
}
export type FromUrlOptions = Options;
export type FromFileOptions = Options & {
/**
* url sets the value returned by window.location, document.URL, and document.documentURI,
* and affects things like resolution of relative URLs within the document
* and the same-origin restrictions and referrer used while fetching subresources.
* It will default to a file URL corresponding to the given filename, instead of to "about:blank".
*/
url?: string;
/**
* contentType affects the value read from document.contentType, and how the document is parsed: as HTML or as XML.
* Values that are not "text/html" or an XML mime type will throw. It will default to "application/xhtml+xml" if
* the given filename ends in .xhtml or .xml; otherwise it will continue to default to "text/html".
*/
contentType?: string;
};
export type ConstructorOptions = Options & {
/**
* url sets the value returned by window.location, document.URL, and document.documentURI,
* and affects things like resolution of relative URLs within the document
* and the same-origin restrictions and referrer used while fetching subresources.
* It defaults to "about:blank".
*/
url?: string;
/**
* contentType affects the value read from document.contentType, and how the document is parsed: as HTML or as XML.
* Values that are not "text/html" or an XML mime type will throw. It defaults to "text/html".
*/
contentType?: string;
};
export interface DOMWindow extends Window { eval(script: string): void; }
export type BinaryData = ArrayBuffer | DataView | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array;
export class VirtualConsole extends EventEmitter {
on<K extends keyof Console>(method: K, callback: Console[K]): this;
on(event: 'jsdomError', callback: (e: Error) => void): this;
sendTo(console: Console, options?: VirtualConsoleSendToOptions): this;
}
export interface VirtualConsoleSendToOptions {
omitJSDOMErrors: boolean;
}
export class CookieJar extends tough.CookieJar { }
export const toughCookie: typeof tough;
export interface ReconfigureSettings {
windowTop?: DOMWindow;
url?: string;
}

View File

@ -1,5 +1,5 @@
import { jsdom, JSDOM } from 'jsdom';
import { CookieJar, MemoryCookieStore } from 'tough-cookie';
import { JSDOM, VirtualConsole, CookieJar, FromUrlOptions, FromFileOptions, DOMWindow } from 'jsdom';
import { CookieJar as ToughCookieJar, MemoryCookieStore } from 'tough-cookie';
import { Script } from 'vm';
function test_basic_usage() {
@ -37,7 +37,7 @@ function test_executing_scripts3() {
}
function test_virtualConsole() {
const virtualConsole = new jsdom.VirtualConsole();
const virtualConsole = new VirtualConsole();
const dom = new JSDOM(``, { virtualConsole });
virtualConsole.on('error', () => { });
@ -54,9 +54,9 @@ function test_virtualConsole() {
function test_cookieJar() {
const store = {} as MemoryCookieStore;
const options = {} as CookieJar.Options;
const options = {} as ToughCookieJar.Options;
const cookieJar = new jsdom.CookieJar(store, options);
const cookieJar = new CookieJar(store, options);
const dom = new JSDOM(``, { cookieJar });
}
@ -111,11 +111,11 @@ function test_runVMScript() {
dom.runVMScript(s);
dom.runVMScript(s);
dom.window.ran === 3;
(<any> dom.window).ran === 3;
}
function test_reconfigure() {
const myFakeTopForTesting = {} as Window;
const myFakeTopForTesting = {} as DOMWindow;
const dom = new JSDOM();
@ -129,7 +129,7 @@ function test_reconfigure() {
}
function test_fromURL() {
const options = {} as jsdom.FromUrlOptions;
const options = {} as FromUrlOptions;
JSDOM.fromURL('https://example.com/', options).then(dom => {
console.log(dom.serialize());
@ -137,7 +137,7 @@ function test_fromURL() {
}
function test_fromFile() {
const options = {} as jsdom.Options;
const options = {} as FromFileOptions;
JSDOM.fromFile('stuff.html', options).then(dom => {
console.log(dom.serialize());

19
types/jsonp/index.d.ts vendored Normal file
View File

@ -0,0 +1,19 @@
// Type definitions for jsonp 0.2
// Project: https://github.com/LearnBoost/jsonp
// Definitions by: Savva Surenkov <https://github.com/surenkov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = jsonp;
declare function jsonp(url: string, options?: Options, cb?: RequestCallback): CancelFn;
declare function jsonp(url: string, callback?: RequestCallback): CancelFn;
type CancelFn = () => void;
type RequestCallback = (error: Error | null, data: any) => void;
interface Options {
param?: string;
prefix?: string;
name?: string;
timeout?: number;
}

View File

@ -0,0 +1,28 @@
import jsonp = require('jsonp');
/**
* Dummy response callback.
*/
const print = (err: Error | null, data: any) =>
console.log(err !== null ? err.message : data);
/**
* Tests jsonp request with default parameters.
*/
const cancel1 = jsonp('https://jsonplaceholder.typicode.com/posts/1', print);
cancel1();
/**
* Tests parametrized jsonp request.
*/
const cancel2 = jsonp(
'https://jsonplaceholder.typicode.com/posts/1',
{
param: 'cb',
timeout: 40000,
prefix: '_jsonp',
name: 'func',
},
print,
);
cancel2();

21
types/jsonp/tsconfig.json Normal file
View File

@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": ["../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"jsonp-tests.ts"
]
}

6
types/jsonp/tslint.json Normal file
View File

@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"ban-types": false
}
}

View File

@ -401,14 +401,14 @@ declare namespace Knex {
comment(val: string): TableBuilder;
specificType(columnName: string, type: string): ColumnBuilder;
primary(columnNames: string[]): TableBuilder;
index(columnNames: string[], indexName?: string, indexType?: string): TableBuilder;
unique(columnNames: string[], indexName?: string): TableBuilder;
index(columnNames: (string | Raw)[], indexName?: string, indexType?: string): TableBuilder;
unique(columnNames: (string | Raw)[], indexName?: string): TableBuilder;
foreign(column: string): ForeignConstraintBuilder;
foreign(columns: string[]): MultikeyForeignConstraintBuilder;
dropForeign(columnNames: string[], foreignKeyName?: string): TableBuilder;
dropUnique(columnNames: string[], indexName?: string): TableBuilder;
dropUnique(columnNames: (string | Raw)[], indexName?: string): TableBuilder;
dropPrimary(constraintName?: string): TableBuilder;
dropIndex(columnNames: string[], indexName?: string): TableBuilder;
dropIndex(columnNames: (string | Raw)[], indexName?: string): TableBuilder;
}
interface CreateTableBuilder extends TableBuilder {

View File

@ -40,35 +40,35 @@ declare namespace L {
*
* Default value: {}
*/
polyline?: DrawOptions.PolylineOptions;
polyline?: DrawOptions.PolylineOptions | false;
/**
* Polygon draw handler options. Set to false to disable handler.
*
* Default value: {}
*/
polygon?: DrawOptions.PolygonOptions;
polygon?: DrawOptions.PolygonOptions | false;
/**
* Rectangle draw handler options. Set to false to disable handler.
*
* Default value: {}
*/
rectangle?: DrawOptions.RectangleOptions;
rectangle?: DrawOptions.RectangleOptions | false;
/**
* Circle draw handler options. Set to false to disable handler.
*
* Default value: {}
*/
circle?: DrawOptions.CircleOptions;
circle?: DrawOptions.CircleOptions | false;
/**
* Marker draw handler options. Set to false to disable handler.
*
* Default value: {}
*/
marker?: DrawOptions.MarkerOptions;
marker?: DrawOptions.MarkerOptions | false;
}
interface EditOptions {
@ -85,14 +85,14 @@ declare namespace L {
*
* Default value: null
*/
edit?: DrawOptions.EditHandlerOptions;
edit?: DrawOptions.EditHandlerOptions | false;
/**
* Delete handler options. Set to false to disable handler.
*
* Default value: null
*/
remove?: DrawOptions.DeleteHandlerOptions;
remove?: DrawOptions.DeleteHandlerOptions | false;
}
interface Draw extends Control {

View File

@ -45,3 +45,27 @@ map.on(L.Draw.Event.CREATED, (e: L.DrawEvents.Created) => {
let examplePolygon: L.LatLngLiteral[] = [{lng: 0, lat: 0}, {lng: 10, lat: 0}, {lng: 10, lat: 10}, {lng: 0, lat: 10}, {lng: 0, lat: 0}];
let examplePolygonArea: number = L.GeometryUtil.geodesicArea(examplePolygon);
L.GeometryUtil.readableArea(examplePolygonArea, true);
function testBooleanControlOptions() {
const drawControl = new L.Control.Draw({
position: 'topleft' ,
draw: {
polygon: {
allowIntersection: false,
drawError: {
color: '#b00b00',
timeout: 1000
},
shapeOptions: {
color: '#bada55'
},
showArea: true
},
polyline: {},
circle: false
},
edit: {
featureGroup: drawnItems
}
});
}

View File

@ -399,7 +399,7 @@ declare namespace L {
class Layer extends Evented {
constructor(options?: LayerOptions);
addTo(map: Map): this;
addTo(map: Map|LayerGroup): this;
remove(): this;
removeFrom(map: Map): this;
getPane(name?: string): HTMLElement | undefined;

87
types/license-checker/index.d.ts vendored Normal file
View File

@ -0,0 +1,87 @@
// Type definitions for license-checker 11.0
// Project: https://github.com/davglass/license-checker
// Definitions by: Rogier Schouten <https://github.com/rogierschouten>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/**
* Options struct for the init() function
*/
export interface InitOpts {
/**
* Path to start checking dependencies from
*/
start: string;
/**
* only show production dependencies
*/
production?: boolean;
/**
* only show development dependencies
*/
development?: boolean;
/**
* report guessed licenses as unknown licenses
*/
unknown?: boolean;
/**
* only list packages with unknown or guessed licenses
*/
onlyunknown?: boolean;
/**
* to add a custom Format file in JSON
*/
customPath?: string;
/**
* exclude modules which licenses are in the comma-separated list from the output
*/
exclude?: string[];
/**
* Use chalk to colorize the licenses member of each returned module info. Unknown licenses become red.
*/
color?: boolean;
/**
* output the location of the license files as relative paths
*/
relativeLicensePath?: boolean;
}
/**
* Information about one dependency
*/
export interface ModuleInfo {
/**
* licenses, either one string or an array of multiple licenses
*/
licenses: string | string[];
/**
* Repository URL
*/
repository: string;
/**
* Publisher name
*/
publisher?: string;
/**
* Publisher e-mail
*/
email?: string;
/**
* Publisher URL
*/
url?: string;
/**
* Path to license file, if available
*/
licenseFile?: string;
}
export interface ModuleInfos {
[packageName: string]: ModuleInfo;
}
/**
* Run the license check
* @param opts specifies the path to the module to check dependencies of
* @param callback
*/
export function init(opts: InitOpts, callback: (err: Error, ret: ModuleInfos) => void): void;

View File

@ -0,0 +1,13 @@
// From README.md:
import * as checker from 'license-checker';
checker.init({
start: '/path/to/start/looking'
}, (err: Error, json: checker.ModuleInfos): void => {
if (err) {
// Handle error
} else {
// The sorted json data
}
});

View File

@ -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",
"license-checker-tests.ts"
]
}

View File

@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@ -1,6 +1,6 @@
// Type definitions for Lo-Dash 4.14
// Project: http://lodash.com/
// Definitions by: Brian Zengel <https://github.com/bczengel>, Ilya Mochalov <https://github.com/chrootsu>, Stepan Mikhaylyuk <https://github.com/stepancar>, Eric L Anderson <https://github.com/ericanderson>
// Definitions by: Brian Zengel <https://github.com/bczengel>, Ilya Mochalov <https://github.com/chrootsu>, Stepan Mikhaylyuk <https://github.com/stepancar>, Eric L Anderson <https://github.com/ericanderson>, AJ Richardson <https://github.com/aj-r>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
@ -485,7 +485,7 @@ declare namespace _ {
* @param array The array to compact.
* @return (Array) Returns the new array of filtered values.
*/
compact<T>(array?: List<T | null | undefined> | null | undefined): T[];
compact<T>(array?: List<T | null | undefined | false | "" | 0> | null | undefined): T[];
}
interface LoDashImplicitArrayWrapperBase<T, TArray extends T[] | null | undefined, TWrapper> {
@ -9604,7 +9604,6 @@ declare namespace _ {
some<TResult>(
predicate?: ListIterator<TResult, boolean>|DictionaryIterator<TResult, boolean>|NumericDictionaryIterator<T, boolean>|ObjectIterator<any, boolean>
): boolean;
/**
* @see _.some
*/
@ -12011,7 +12010,12 @@ declare namespace _ {
*
* @return Returns true if value is correctly classified, else false.
*/
isArray<T>(value?: any): value is T[];
isArray(value?: any): value is any[];
/**
* DEPRECATED
*/
isArray<T>(value?: any): value is any[];
}
interface LoDashImplicitWrapperBase<T, TWrapper> {
@ -12080,7 +12084,22 @@ declare namespace _ {
* _.isArrayLike(_.noop);
* // => false
*/
isArrayLike<T>(value?: any): value is T[];
isArrayLike<T>(value: T & string & number): boolean; // should only match if T = any
/**
* @see _.isArrayLike
*/
isArrayLike(value?: Function): value is never;
/**
* @see _.isArrayLike
*/
isArrayLike<T>(value: T | Function): value is T & { length: number };
/**
* DEPRECATED
*/
isArrayLike<T>(value?: any): value is any[];
}
interface LoDashImplicitWrapperBase<T, TWrapper> {
@ -12123,7 +12142,22 @@ declare namespace _ {
* _.isArrayLikeObject(_.noop);
* // => false
*/
isArrayLikeObject<T>(value?: any): value is T[];
isArrayLikeObject<T>(value: T & string & number): boolean; // should only match if T = any
/**
* @see _.isArrayLike
*/
isArrayLikeObject(value?: Function | string | boolean | number): value is never;
/**
* @see _.isArrayLike
*/
isArrayLikeObject<T>(value: T | Function | string | boolean | number): value is T & { length: number };
/**
* DEPRECATED
*/
isArrayLikeObject<T>(value?: any): value is any[];
}
interface LoDashImplicitWrapperBase<T, TWrapper> {
@ -13283,6 +13317,48 @@ declare namespace _ {
toPlainObject<TResult extends {}>(): LoDashImplicitObjectWrapper<TResult>;
}
//_.toFinite
interface LoDashStatic {
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
toFinite(value: any): number;
}
interface LoDashImplicitWrapperBase<T, TWrapper> {
/**
* @see _.toFinite
*/
toFinite(): LoDashImplicitWrapper<number>;
}
interface LoDashExplicitWrapperBase<T, TWrapper> {
/**
* @see _.toFinite
*/
toFinite(): LoDashExplicitWrapper<number>;
}
//_.toInteger
interface LoDashStatic {
/**

View File

@ -207,6 +207,8 @@ namespace TestChunk {
namespace TestCompact {
let array: TResult[] | null | undefined = [] as any;
let list: _.List<TResult> | null | undefined = [] as any;
let array2: Array<TResult | null | undefined | false | "" | 0> | null | undefined = any;
let list2: _.List<TResult | null | undefined | false | "" | 0> | null | undefined = any;
{
let result: TResult[];
@ -214,6 +216,8 @@ namespace TestCompact {
result = _.compact<TResult>();
result = _.compact<TResult>(array);
result = _.compact<TResult>(list);
result = _.compact(array2);
result = _.compact(list2);
}
{
@ -6899,18 +6903,13 @@ namespace TestisArguments {
// _.isArray
namespace TestIsArray {
{
let value: number|string[]|boolean[] = [];
let value: number|string[]|boolean[] = any;
if (_.isArray<string>(value)) {
let result: string[] = value;
if (_.isArray(value)) {
value; // $ExpectType boolean[] | string[]
}
else {
if (_.isArray<boolean>(value)) {
let result: boolean[] = value;
}
else {
let result: number = value;
}
value; // $ExpectType number
}
}
@ -6935,13 +6934,13 @@ namespace TestIsArray {
// _.isArrayBuffer
namespace TestIsArrayBuffer {
{
let value: ArrayBuffer|number = 0;
let value: ArrayBuffer|number = any;
if (_.isArrayBuffer(value)) {
let result: ArrayBuffer = value;
value; // $ExpectType ArrayBuffer
}
else {
let result: number = value;
value; // $ExpectType number
}
}
@ -6966,18 +6965,59 @@ namespace TestIsArrayBuffer {
// _.isArrayLike
namespace TestIsArrayLike {
{
let value: number|string[]|boolean[] = [];
let value: string | string[] | { [index: number]: boolean, length: number } | [number, boolean]
| number | Function | { length: string } | { a: string }
= any;
if (_.isArrayLike<string>(value)) {
let result: string[] = value;
if (_.isArrayLike(value)) {
let result: string | string[] | { [index: number]: boolean, length: number } | [number, boolean] = value;
}
else {
if (_.isArrayLike<boolean>(value)) {
let result: boolean[] = value;
}
else {
let result: number = value;
}
let result: number | Function | { length: string } | { a: string; } = value;
}
}
{
let value: boolean[] = any;
if (_.isArrayLike(value)) {
let result: boolean[] = value;
}
else {
value; // $ExpectType never
}
}
{
let value: Function = any;
if (_.isArrayLike(value)) {
value; // $ExpectType never
}
else {
value; // $ExpectType Function
}
}
{
let value: { a: string } = any;
if (_.isArrayLike(value)) {
let result: { a: string, length: number } = value;
}
else {
value; // $ExpectType { a: string; }
}
}
{
let value: any = any;
if (_.isArrayLike(value)) {
value; // $ExpectType any
}
else {
value; // $ExpectType any
}
}
@ -7002,18 +7042,59 @@ namespace TestIsArrayLike {
// _.isArrayLikeObject
namespace TestIsArrayLikeObject {
{
let value: number|string[]|boolean[] = [];
let value: string[] | { [index: number]: boolean, length: number } | [number, boolean]
| number | string | Function | { length: string } | { a: string }
= any;
if (_.isArrayLikeObject<string>(value)) {
let result: string[] = value;
if (_.isArrayLikeObject(value)) {
let result: string[] | { [index: number]: boolean, length: number } | [number, boolean] = value;
}
else {
if (_.isArrayLikeObject<boolean>(value)) {
let result: boolean[] = value;
}
else {
let result: number = value;
}
let result: string | number | Function | { length: string; } | { a: string; } = value;
}
}
{
let value: boolean[] = any;
if (_.isArrayLikeObject(value)) {
let result: boolean[] = value;
}
else {
value; // $ExpectType never
}
}
{
let value: string | Function = any;
if (_.isArrayLikeObject(value)) {
value; // $ExpectType never
}
else {
value; // $ExpectType string | Function
}
}
{
let value: { a: string } = any;
if (_.isArrayLikeObject(value)) {
let result: { a: string, length: number } = value;
}
else {
value; // $ExpectType { a: string; }
}
}
{
let value: any = any;
if (_.isArrayLikeObject(value)) {
value; // $ExpectType any
}
else {
value; // $ExpectType any
}
}
@ -7933,13 +8014,36 @@ namespace TestToPlainObject {
}
}
// _.toFinite
namespace TestToFinite {
{
let result: number;
result = _.toFinite(true);
result = _.toFinite(1);
result = _.toFinite('3.2');
result = _.toFinite([]);
result = _.toFinite({});
}
{
let result: _.LoDashImplicitWrapper<number>;
result = _(true).toFinite();
result = _(1).toFinite();
result = _('3.2').toFinite();
result = _([1]).toFinite();
result = _<string>([]).toFinite();
result = _({}).toFinite();
}
}
// _.toInteger
namespace TestToInteger {
{
let result: number;
result = _.toInteger(true);
result = _.toInteger(1);
result = _.toInteger('a');
result = _.toInteger('3.2');
result = _.toInteger([]);
result = _.toInteger({});
}

2
types/lodash/toFinite/index.d.ts vendored Normal file
View File

@ -0,0 +1,2 @@
import { toFinite } from "../index";
export = toFinite;

View File

@ -248,6 +248,7 @@
"thru/index.d.ts",
"times/index.d.ts",
"toArray/index.d.ts",
"toFinite/index.d.ts",
"toInteger/index.d.ts",
"toLength/index.d.ts",
"toLower/index.d.ts",

View File

@ -1,4 +1,4 @@
// Type definitions for Mapbox GL JS v0.39.0
// Type definitions for Mapbox GL JS v0.39.1
// Project: https://github.com/mapbox/mapbox-gl-js
// Definitions by: Dominik Bruderer <https://github.com/dobrud>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@ -706,7 +706,7 @@ declare namespace mapboxgl {
angleWidth(p: Point): number;
angleWithSep(x: number, y: number): number;
convert(a: Array<number> | Point): Point;
}
@ -1045,7 +1045,7 @@ declare namespace mapboxgl {
export interface CirclePaint {
"circle-radius"?: number | StyleFunction;
"circle-radius-transition"?: Transition;
"circle-color"?: string;
"circle-color"?: string | StyleFunction;
"circle-blur"?: number | StyleFunction;
"circle-opacity"?: number | StyleFunction;
"circle-translate"?: number[];

View File

@ -50,9 +50,11 @@ declare namespace massive {
count(criteria: object): Promise<string>;
where(query: string, params: any[] | object): Promise<T[]>;
search(criteria: SearchCriteria, queryOptions?: QueryOptions): Promise<any>;
save(data: object | object[]): Promise<T> | Promise<T[]>;
insert(data: object | object[]): Promise<T> | Promise<T[]>;
update(dataOrCriteria: object | object[], changesMap?: object): Promise<T> | Promise<T[]>;
save(data: object): Promise<T>;
insert(data: object): Promise<T>;
insert(data: object[]): Promise<T[]>;
update(dataOrCriteria: object, changesMap?: object): Promise<T>;
update(dataOrCriteria: object[], changesMap?: object): Promise<T[]>;
destroy(criteria: object): Promise<T[]>;
}

View File

@ -8,6 +8,7 @@
// Aurelién Allienne <https://github.com/allienna>
// Matthias Schlesinger <https://github.com/schlesingermatthias>
// Jonathon Kelly <https://github.com/InsidersByte>
// Artyom Stukans <https://github.com/artyomsv>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@ -1057,6 +1058,7 @@ declare namespace __MaterialUI {
title?: React.ReactNode;
titleBackground?: string;
titlePosition?: "top" | "bottom";
titleStyle?: React.CSSProperties;
onTouchTap?: TouchTapEventHandler;
}
export class GridTile extends React.Component<GridTileProps> {

View File

@ -1,6 +1,7 @@
// Type definitions for MongoDB v2.2
// Project: https://github.com/mongodb/node-mongodb-native/tree/2.2
// Definitions by: Federico Caselli <https://github.com/CaselIT>
// Alan Marcell <https://github.com/alanmarcell>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@ -585,10 +586,10 @@ export interface Collection<TSchema = Default> {
rename(newName: string, callback: MongoCallback<Collection<TSchema>>): void;
rename(newName: string, options?: { dropTarget?: boolean }): Promise<Collection<TSchema>>;
rename(newName: string, options: { dropTarget?: boolean }, callback: MongoCallback<Collection<TSchema>>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#replaceOne
replaceOne(filter: Object, doc: Object, callback: MongoCallback<UpdateWriteOpResult>): void;
replaceOne(filter: Object, doc: Object, options?: ReplaceOneOptions): Promise<UpdateWriteOpResult>;
replaceOne(filter: Object, doc: Object, options: ReplaceOneOptions, callback: MongoCallback<UpdateWriteOpResult>): void;
//http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#replaceOne
replaceOne(filter: Object, doc: Object, callback: MongoCallback<UpdateWriteOpResult & { ops: Array<any> }>): void;
replaceOne(filter: Object, doc: Object, options?: ReplaceOneOptions): Promise<UpdateWriteOpResult & { ops: Array<any> }>;
replaceOne(filter: Object, doc: Object, options: ReplaceOneOptions, callback: MongoCallback<UpdateWriteOpResult & { ops: Array<any> }>): void;
//http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#save
/** @deprecated Use insertOne, insertMany, updateOne or updateMany */
save(doc: Object, callback: MongoCallback<WriteOpResult>): void;

View File

@ -2,9 +2,17 @@
// Project: https://github.com/larryprice/mongoose-simple-random
// Definitions by: My Self <https://github.com/me>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="mongoose" />
// tslint:disable-next-line no-single-declare-module
declare module 'mongoose-simple-random' {
import mongoose = require('mongoose');
// Dummy function allows to avoid hard to kill or fix tslint warning
// (exporting pluginFunc will make this a non-importable module)
function pluginFunc(schema: mongoose.Schema): void;
// Let allows typescript to still use ES2015 style imports
let plugin: typeof pluginFunc;
export = plugin;
}
declare module "mongoose" {
interface Model<T extends Document> extends NodeJS.EventEmitter, ModelProperties {
findRandom(conditions: Object, projection?: Object | null, options?: Object | null, callback?: (err: any, res: T[]) => void)

View File

@ -1,4 +1,5 @@
import * as mongoose from 'mongoose';
import * as mongoose_simple_random from "mongoose-simple-random";
// test compatibility with other libraries - from @types/mongoose
import * as _ from 'lodash';
@ -13,3 +14,5 @@ mongoose.Model.findRandom({
}, {}, { limit: 1 }, (error, data) => {
if (error) { console.error("Error!"); } else { console.log("Success!"); }
});
mongoose.plugin(mongoose_simple_random);

View File

@ -4,6 +4,7 @@
// Hans Bakker <https://github.com/wind-rider>
// Shantanu Bhadoria <https://github.com/shantanubhadoria>
// Luke Libraro <https://github.com/lukel99>
// Dan Chao <https://github.com/bioball>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
@ -88,6 +89,8 @@ export declare class Characteristic extends events.EventEmitter {
notify(notify: boolean, callback?: (error: string) => void): void;
discoverDescriptors(callback?: (error: string, descriptors: Descriptor[]) => void): void;
toString(): string;
subscribe(callback?: (error: string) => void): void;
unsubscribe(callback?: (error: string) => void): void;
on(event: string, listener: Function): this;
on(event: string, option: boolean, listener: Function): this;

View File

@ -87,6 +87,10 @@ characteristic.on("write", true, (error: string): void => {});
characteristic.on("broadcast", (state: string): void => {});
characteristic.on("notify", (state: string): void => {});
characteristic.on("descriptorsDiscover", (descriptors: noble.Descriptor[]): void => {});
characteristic.subscribe();
characteristic.subscribe((error: string) => {});
characteristic.unsubscribe();
characteristic.unsubscribe((error: string) => {});
var descriptor: noble.Descriptor = new noble.Descriptor();
descriptor.uuid = "";

68
types/node/index.d.ts vendored
View File

@ -8,6 +8,7 @@
// Wilco Bakker <https://github.com/WilcoBakker>
// Nicolas Voigt <https://github.com/octo-sniffle>
// Chigozirim C. <https://github.com/smac89>
// Flarna <https://github.com/Flarna>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
@ -1730,7 +1731,7 @@ declare module "readline" {
export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): ReadLine;
export function createInterface(options: ReadLineOptions): ReadLine;
export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void;
export function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number): void;
export function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void;
export function clearLine(stream: NodeJS.WritableStream, dir: number): void;
export function clearScreenDown(stream: NodeJS.WritableStream): void;
@ -4518,3 +4519,68 @@ declare module "_debugger" {
new (): ClientInstance
}
}
/**
* Async Hooks module: https://nodejs.org/api/async_hooks.html
*/
declare module "async_hooks" {
/**
* Returns the asyncId of the current execution context.
*/
export function currentId(): number;
/**
* Returns the ID of the resource responsible for calling the callback that is currently being executed.
*/
export function triggerId(): number;
export interface HookCallbacks {
/**
* Called when a class is constructed that has the possibility to emit an asynchronous event.
* @param asyncId a unique ID for the async resource
* @param type the type of the async resource
* @param triggerId the unique ID of the async resource in whose execution context this async resource was created
* @param resource reference to the resource representing the async operation, needs to be released during destroy
*/
init?(asyncId: number, type: string, triggerId: number, resource: Object): void;
/**
* When an asynchronous operation is initiated or completes a callback is called to notify the user.
* The before callback is called just before said callback is executed.
* @param asyncId the unique identifier assigned to the resource about to execute the callback.
*/
before?(asyncId: number): void;
/**
* Called immediately after the callback specified in before is completed.
* @param asyncId the unique identifier assigned to the resource which has executed the callback.
*/
after?(asyncId: number): void;
/**
* Called after the resource corresponding to asyncId is destroyed
* @param asyncId a unique ID for the async resource
*/
destroy?(asyncId: number): void;
}
export interface AsyncHook {
/**
* Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop.
*/
enable(): this;
/**
* Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled.
*/
disable(): this;
}
/**
* Registers functions to be called for different lifetime events of each async operation.
* @param options the callbacks to register
* @return an AsyncHooks instance used for disabling and enabling hooks
*/
export function createHook(options: HookCallbacks): AsyncHook;
}

View File

@ -26,6 +26,7 @@ import * as timers from "timers";
import * as repl from "repl";
import * as v8 from "v8";
import * as dns from "dns";
import * as async_hooks from "async_hooks";
// Specifically test buffer module regression.
import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer";
@ -1409,6 +1410,7 @@ namespace readline_tests {
let x: number;
let y: number;
readline.cursorTo(stream, x);
readline.cursorTo(stream, x, y);
}
@ -2504,3 +2506,19 @@ client.connect(8888, 'localhost');
client.listbreakpoints((err, body, packet) => {
});
////////////////////////////////////////////////////
/// AsyncHooks tests : https://nodejs.org/api/async_hooks.html
////////////////////////////////////////////////////
namespace async_hooks_tests {
const hooks: async_hooks.HookCallbacks = {
init: (asyncId: number, type: string, triggerId: number, resource: object) => void {},
before: (asyncId: number) => void {},
after: (asyncId: number) => void {},
destroy: (asyncId: number) => void {}
};
const asyncHook = async_hooks.createHook(hooks);
asyncHook.enable().disable().enable();
}

View File

@ -3514,6 +3514,12 @@ declare module 'paper' {
* @param highlight [optional] -
*/
constructor(color: Gradient, origin: Point, destination: Point, highlight?: Point);
/**
* Creates a RGB Color object.
* @param hex - the RGB color in hex, i.e. #000000
*/
constructor(hex: string);
/**
* The type of the color as a string.

View File

@ -1,6 +1,7 @@
// Type definitions for passport-jwt 2.0
// Project: https://github.com/themikenicholson/passport-jwt
// Definitions by: TANAKA Koichi <https://github.com/mugeso/>
// Alex Young <https://github.com/alsiola/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import {Strategy as PassportStrategy} from 'passport-strategy';
@ -12,7 +13,7 @@ export declare class Strategy extends PassportStrategy {
}
export interface StrategyOptions {
secretOrKey: string;
secretOrKey: string | Buffer;
jwtFromRequest: JwtFromRequestFunction;
issuer?: string;
audience?: string;

View File

@ -33,5 +33,6 @@ opts.jwtFromRequest = ExtractJwt.fromUrlQueryParameter('param_name');
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('param_name');
opts.jwtFromRequest = ExtractJwt.fromExtractors([ExtractJwt.fromHeader('x-api-key'), ExtractJwt.fromBodyField('field_name'), ExtractJwt.fromUrlQueryParameter('param_name')]);
opts.jwtFromRequest = (req: Request) => { return req.query.token; };
opts.secretOrKey = new Buffer('secret');
declare function findUser(condition: {id: string}, callback: (error: any, user :any) => void): void;

View File

@ -19,8 +19,8 @@ declare module 'mongoose' {
// statics
interface PassportLocalModel<T extends Document> extends Model<T> {
authenticate(): (username: string, password: string, cb: (err: any, res: T, error: any) => void) => void;
serializeUser(): (user: PassportLocalModel<T>, cb: (err: any) => void) => void;
deserializeUser(): (username: string, cb: (err: any) => void) => void;
serializeUser(): (user: PassportLocalModel<T>, cb: (err: any, id?: any) => void) => void;
deserializeUser(): (username: string, cb: (err: any, user?: any) => void) => void;
register(user: T, password: string, cb: (err: any, account: any) => void): void;
findByUsername(username: string, selectHashSaltFields: boolean, cb: (err: any, account: any) => void): any;
createStrategy(): passportLocal.Strategy;

2
types/pg/index.d.ts vendored
View File

@ -71,7 +71,7 @@ export declare class Pool extends events.EventEmitter {
connect(): Promise<Client>;
connect(callback: (err: Error, client: Client, done: () => void) => void): void;
end(): Promise<void>;
end(callback?: () => void): Promise<void>;
query(queryStream: QueryConfig & stream.Readable): stream.Readable;
query(queryTextOrConfig: string | QueryConfig): Promise<QueryResult>;

View File

@ -74,3 +74,8 @@ pool.connect((err, client, done) => {
pool.on('error', (err, client) => {
console.error('idle client error', err.message, err.stack)
})
pool.end();
pool.end(() => {
console.log("pool is closed");
});

View File

@ -199,25 +199,6 @@ declare namespace PIXI {
// display
interface ApplicationOptions extends RendererOptions {
view?: HTMLCanvasElement;
transparent?: boolean;
autoResize?: boolean;
antialias?: boolean;
resolution?: number;
clearBeforeRender?: boolean;
backgroundColor?: number;
roundPixels?: boolean;
context?: WebGLRenderingContext;
preserveDrawingBuffer?: boolean;
legacy?: boolean;
width?: number;
height?: number;
forceCanvas?: boolean;
sharedTicker?: boolean;
sharedLoader?: boolean;
}
class Application {
constructor(options?: ApplicationOptions)
constructor(width?: number, height?: number, options?: ApplicationOptions, noWebGL?: boolean, sharedTicker?: boolean, sharedLoader?: boolean);
@ -725,18 +706,91 @@ declare namespace PIXI {
}
// renderers
interface RendererOptions {
view?: HTMLCanvasElement;
transparent?: boolean;
autoResize?: boolean;
antialias?: boolean;
resolution?: number;
clearBeforeRender?: boolean;
backgroundColor?: number;
roundPixels?: boolean;
context?: WebGLRenderingContext;
/**
* the width of the renderers view [default=800]
*/
width?: number;
/**
* the height of the renderers view [default=600]
*/
height?: number;
/**
* the canvas to use as a view, optional
*/
view?: HTMLCanvasElement;
/**
* If the render view is transparent, [default=false]
*/
transparent?: boolean;
/**
* sets antialias (only applicable in chrome at the moment) [default=false]
*/
antialias?: boolean;
/**
* enables drawing buffer preservation, enable this if you need to call toDataUrl on the webgl context [default=false]
*/
preserveDrawingBuffer?: boolean;
/**
* The resolution / device pixel ratio of the renderer, retina would be 2 [default=1]
*/
resolution?: number;
/**
* prevents selection of WebGL renderer, even if such is present [default=false]
*/
forceCanvas?: boolean;
/**
* The background color of the rendered area (shown if not transparent) [default=0x000000]
*/
backgroundColor?: number;
/**
* This sets if the renderer will clear the canvas or not before the new render pass. [default=true]
*/
clearBeforeRender?: boolean;
/**
* If true Pixi will Math.floor() x/ y values when rendering, stopping pixel interpolation. [default=false]
*/
roundPixels?: boolean;
/**
* forces FXAA antialiasing to be used over native FXAA is faster, but may not always look as great ** webgl only** [default=false]
*/
forceFXAA?: boolean;
/**
* `true` to ensure compatibility with older / less advanced devices. If you experience unexplained flickering try setting this to true. **webgl only** [default=false]
*/
legacy?: boolean;
/**
* Depricated
*/
context?: WebGLRenderingContext;
/**
* Depricated
*/
autoResize?: boolean;
}
interface ApplicationOptions extends RendererOptions {
/**
* `true` to use PIXI.ticker.shared, `false` to create new ticker. [default=false]
*/
sharedTicker?: boolean;
/**
* `true` to use PIXI.loaders.shared, `false` to create new Loader.
*/
sharedLoader?: boolean;
}
class SystemRenderer extends utils.EventEmitter {
constructor(system: string, options?: RendererOptions);
@ -825,20 +879,7 @@ declare namespace PIXI {
resize(width: number, height: number): void;
destroy(): void;
}
interface WebGLRendererOptions {
view?: HTMLCanvasElement;
transparent?: boolean;
autoResize?: boolean;
antialias?: boolean;
forceFXAA?: boolean;
resolution?: number;
clearBeforeRender?: boolean;
backgroundColor?: number;
preserveDrawingBuffer?: boolean;
roundPixels?: boolean;
legacy?: boolean;
width?: number;
height?: number;
interface WebGLRendererOptions extends RendererOptions {
}
class WebGLRenderer extends SystemRenderer {
// plugintarget mixin start
@ -2512,12 +2553,18 @@ declare namespace PIXI {
protected maxItemsPerFrame: number;
protected itemsLeft: number;
beginFrame(): void;
allowedToUpload(): boolean;
}
class TimeLimiter {
constructor(maxMilliseconds: number);
protected maxMilliseconds: number;
protected frameStart: number;
beginFrame(): void;
allowedToUpload(): boolean;
}
}
@ -2713,6 +2760,11 @@ declare namespace PIXI {
function isWebGLSupported(): boolean;
function sign(n: number): number;
function removeItems<T>(arr: T[], startIdx: number, removeCount: number): void;
function correctBlendMode(blendMode: number, premultiplied: boolean): number;
function premultiplyTint(tint: number, alpha: number): number;
function premultiplyRgba(rgb: Float32Array | number[], alpha: number, out?: Float32Array, premultiply?: boolean): Float32Array;
function premultiplyTintToRgba(tint: number, alpha: number, out?: Float32Array, premultiply?: boolean): Float32Array;
const premultiplyBlendMode: number[][];
const TextureCache: any;
const BaseTextureCache: any;

View File

@ -1,11 +1,11 @@
// Type definitions for promise.prototype.finally v2.0.1
// Type definitions for promise.prototype.finally 2.0
// Project: https://github.com/matthew-andrews/Promise.prototype.finally
// Definitions by: Slava Shpitalny <https://github.com/slavik57>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare global {
interface Promise<T> {
finally<U>(onFinally?: () => U | Promise<U>): Promise<T>;
finally<U>(onFinally?: () => U | PromiseLike<U>): Promise<T>;
}
}

Some files were not shown because too many files have changed in this diff Show More