Merge branch 'master' into jest-type-inference

This commit is contained in:
Antoine Brault
2018-12-05 14:10:57 -05:00
committed by GitHub
120 changed files with 7221 additions and 4092 deletions
+72 -75
View File
@@ -1,92 +1,89 @@
import { Break, BreakClip } from "./cast.framework.messages";
export = cast.framework.breaks;
export as namespace breaks
export class BreakSeekData {
constructor(seekFrom: number, seekTo: number, breaks: Break[]);
declare namespace cast.framework.breaks {
class BreakSeekData {
constructor(seekFrom: number, seekTo: number, breaks: Break[]);
/**
* List of breaks
*/
breaks: Break[];
/**
* List of breaks
*/
breaks: Break[];
/**
* Current playback time
*/
seekFrom: number;
/**
* Current playback time
*/
seekFrom: number;
/**
* The time to seek to
*/
seekTo: number;
}
/**
* The time to seek to
*/
seekTo: number;
}
/** Provide context information for break clip load interceptor. */
export class BreakClipLoadInterceptorContext {
constructor(brk: Break);
/** Provide context information for break clip load interceptor. */
class BreakClipLoadInterceptorContext {
constructor(brk: Break);
/**
* The container break for the break clip
*/
break: Break;
}
/**
* The container break for the break clip
*/
break: Break;
}
/** Interface to manage breaks */
export interface BreakManager {
/**
* Get current media break by id.
*/
getBreakById(id: string): Break;
/** Interface to manage breaks */
interface BreakManager {
/**
* Get current media break by id.
*/
getBreakById(id: string): Break;
/**
* Get current media break clip by id
*/
getBreakClipById(id: string): BreakClip;
/**
* Get current media break clip by id
*/
getBreakClipById(id: string): BreakClip;
/** Get current media break clips. */
getBreakClips(): BreakClip[];
/** Get current media break clips. */
getBreakClips(): BreakClip[];
/** Get current media breaks. */
getBreaks(): Break[];
/** Get current media breaks. */
getBreaks(): Break[];
/** Returns true if watched breaks should be played. */
getPlayWatchedBreak(): boolean;
/** Returns true if watched breaks should be played. */
getPlayWatchedBreak(): boolean;
/**
* Provide an interceptor to allow developer to insert more break clips or modify current break clip before a break is started.
* If interceptor is null it will reset the interceptor to default one.
* By default VAST fetching and parsing logic in default interceptor.
* So if customized interceptor is set by developer;
* the VAST logic will be overridden and developers should implement their own VAST fetching and parsing logic in the provided interceptor.
*/
setBreakClipLoadInterceptor(
interceptor: (
breakClip: BreakClip,
breakClipLoaderContext?: BreakClipLoadInterceptorContext
) => void
): void;
/**
* Provide an interceptor to allow developer to insert more break clips or modify current break clip before a break is started.
* If interceptor is null it will reset the interceptor to default one.
* By default VAST fetching and parsing logic in default interceptor.
* So if customized interceptor is set by developer;
* the VAST logic will be overridden and developers should implement their own VAST fetching and parsing logic in the provided interceptor.
*/
setBreakClipLoadInterceptor(
interceptor: (
breakClip: BreakClip,
breakClipLoaderContext?: BreakClipLoadInterceptorContext
) => void
): void;
/**
* Provide an interceptor for developer to specify what breaks they want to play after seek.
*/
setBreakSeekInterceptor(
seekInterceptor: (breakSeekData: BreakSeekData) => void
): void;
/**
* Provide an interceptor for developer to specify what breaks they want to play after seek.
*/
setBreakSeekInterceptor(
seekInterceptor: (breakSeekData: BreakSeekData) => void
): void;
/**
* Set a flag to control if the watched client stitching break should be played.
*/
setPlayWatchedBreak(playWatchedBreak: boolean): void;
/**
* Set a flag to control if the watched client stitching break should be played.
*/
setPlayWatchedBreak(playWatchedBreak: boolean): void;
/**
* Provide an interceptor to modify VAST tracking URL before it is being sent to server.
* The input of the interceptor is a string of the tracking URL.
* The interceptor can either return a modified string of URL or a Promise of modified string of URL.
* The interceptor can also return null if you want to send the tracking URL by your own code instead of by CAF.
*/
setVastTrackingInterceptor(
interceptor?: (trackingUrl: string) => void
): void;
}
/**
* Provide an interceptor to modify VAST tracking URL before it is being sent to server.
* The input of the interceptor is a string of the tracking URL.
* The interceptor can either return a modified string of URL or a Promise of modified string of URL.
* The interceptor can also return null if you want to send the tracking URL by your own code instead of by CAF.
*/
setVastTrackingInterceptor(
interceptor?: (trackingUrl: string) => void
): void;
}
File diff suppressed because it is too large Load Diff
+390 -392
View File
@@ -4,423 +4,421 @@ import {
Track,
MediaStatus
} from "./cast.framework.messages";
export = cast.framework.events;
declare namespace cast.framework.events {
type EventType =
| "ALL"
| "ABORT"
| "CAN_PLAY"
| "CAN_PLAY_THROUGH"
| "DURATION_CHANGE"
| "EMPTIED"
| "ENDED"
| "LOADED_DATA"
| "LOADED_METADATA"
| "LOAD_START"
| "PAUSE"
| "PLAY"
| "PLAYING"
| "PROGRESS"
| "RATE_CHANGE"
| "SEEKED"
| "SEEKING"
| "STALLED"
| "TIME_UPDATE"
| "SUSPEND"
| "WAITING"
| "BITRATE_CHANGED"
| "BREAK_STARTED"
| "BREAK_ENDED"
| "BREAK_CLIP_LOADING"
| "BREAK_CLIP_STARTED"
| "BREAK_CLIP_ENDED"
| "BUFFERING"
| "CACHE_LOADED"
| "CACHE_HIT"
| "CACHE_INSERTED"
| "CLIP_STARTED"
| "CLIP_ENDED"
| "EMSG"
| "ERROR"
| "ID3"
| "MEDIA_STATUS"
| "MEDIA_FINISHED"
| "PLAYER_PRELOADING"
| "PLAYER_PRELOADING_CANCELLED"
| "PLAYER_LOAD_COMPLETE"
| "PLAYER_LOADING"
| "SEGMENT_DOWNLOADED"
| "REQUEST_SEEK"
| "REQUEST_LOAD"
| "REQUEST_STOP"
| "REQUEST_PAUSE"
| "REQUEST_PLAY"
| "REQUEST_PLAY_AGAIN"
| "REQUEST_PLAYBACK_RATE_CHANGE"
| "REQUEST_SKIP_AD"
| "REQUEST_VOLUME_CHANGE"
| "REQUEST_EDIT_TRACKS_INFO"
| "REQUEST_EDIT_AUDIO_TRACKS"
| "REQUEST_SET_CREDENTIALS"
| "REQUEST_LOAD_BY_ENTITY"
| "REQUEST_USER_ACTION"
| "REQUEST_DISPLAY_STATUS"
| "REQUEST_CUSTOM_COMMAND"
| "REQUEST_FOCUS_STATE"
| "REQUEST_QUEUE_LOAD"
| "REQUEST_QUEUE_INSERT"
| "REQUEST_QUEUE_UPDATE"
| "REQUEST_QUEUE_REMOVE"
| "REQUEST_QUEUE_REORDER"
| "REQUEST_QUEUE_GET_ITEM_RANGE"
| "REQUEST_QUEUE_GET_ITEMS"
| "REQUEST_QUEUE_GET_ITEM_IDS"
| "REQUEST_PRECACHE";
export as namespace events
export type EventType =
| "ALL"
| "ABORT"
| "CAN_PLAY"
| "CAN_PLAY_THROUGH"
| "DURATION_CHANGE"
| "EMPTIED"
| "ENDED"
| "LOADED_DATA"
| "LOADED_METADATA"
| "LOAD_START"
| "PAUSE"
| "PLAY"
| "PLAYING"
| "PROGRESS"
| "RATE_CHANGE"
| "SEEKED"
| "SEEKING"
| "STALLED"
| "TIME_UPDATE"
| "SUSPEND"
| "WAITING"
| "BITRATE_CHANGED"
| "BREAK_STARTED"
| "BREAK_ENDED"
| "BREAK_CLIP_LOADING"
| "BREAK_CLIP_STARTED"
| "BREAK_CLIP_ENDED"
| "BUFFERING"
| "CACHE_LOADED"
| "CACHE_HIT"
| "CACHE_INSERTED"
| "CLIP_STARTED"
| "CLIP_ENDED"
| "EMSG"
| "ERROR"
| "ID3"
| "MEDIA_STATUS"
| "MEDIA_FINISHED"
| "PLAYER_PRELOADING"
| "PLAYER_PRELOADING_CANCELLED"
| "PLAYER_LOAD_COMPLETE"
| "PLAYER_LOADING"
| "SEGMENT_DOWNLOADED"
| "REQUEST_SEEK"
| "REQUEST_LOAD"
| "REQUEST_STOP"
| "REQUEST_PAUSE"
| "REQUEST_PLAY"
| "REQUEST_PLAY_AGAIN"
| "REQUEST_PLAYBACK_RATE_CHANGE"
| "REQUEST_SKIP_AD"
| "REQUEST_VOLUME_CHANGE"
| "REQUEST_EDIT_TRACKS_INFO"
| "REQUEST_EDIT_AUDIO_TRACKS"
| "REQUEST_SET_CREDENTIALS"
| "REQUEST_LOAD_BY_ENTITY"
| "REQUEST_USER_ACTION"
| "REQUEST_DISPLAY_STATUS"
| "REQUEST_CUSTOM_COMMAND"
| "REQUEST_FOCUS_STATE"
| "REQUEST_QUEUE_LOAD"
| "REQUEST_QUEUE_INSERT"
| "REQUEST_QUEUE_UPDATE"
| "REQUEST_QUEUE_REMOVE"
| "REQUEST_QUEUE_REORDER"
| "REQUEST_QUEUE_GET_ITEM_RANGE"
| "REQUEST_QUEUE_GET_ITEMS"
| "REQUEST_QUEUE_GET_ITEM_IDS"
| "REQUEST_PRECACHE";
type DetailedErrorCode =
| "MEDIA_UNKNOWN"
| "MEDIA_ABORTED"
| "MEDIA_DECODE"
| "MEDIA_NETWORK"
| "MEDIA_SRC_NOT_SUPPORTED"
| "SOURCE_BUFFER_FAILURE"
| "MEDIAKEYS_UNKNOWN"
| "MEDIAKEYS_NETWORK"
| "MEDIAKEYS_UNSUPPORTED"
| "MEDIAKEYS_WEBCRYPTO"
| "NETWORK_UNKNOWN"
| "SEGMENT_NETWORK"
| "HLS_NETWORK_MASTER_PLAYLIST"
| "HLS_NETWORK_PLAYLIST"
| "HLS_NETWORK_NO_KEY_RESPONSE"
| "HLS_NETWORK_KEY_LOAD"
| "HLS_NETWORK_INVALID_SEGMENT"
| "HLS_SEGMENT_PARSING"
| "DASH_NETWORK"
| "DASH_NO_INIT"
| "SMOOTH_NETWORK"
| "SMOOTH_NO_MEDIA_DATA"
| "MANIFEST_UNKNOWN"
| "HLS_MANIFEST_MASTER"
| "HLS_MANIFEST_PLAYLIST"
| "DASH_MANIFEST_UNKNOWN"
| "DASH_MANIFEST_NO_PERIODS"
| "DASH_MANIFEST_NO_MIMETYPE"
| "DASH_INVALID_SEGMENT_INFO"
| "SMOOTH_MANIFEST"
| "SEGMENT_UNKNOWN"
| "TEXT_UNKNOWN"
| "APP"
| "BREAK_CLIP_LOADING_ERROR"
| "BREAK_SEEK_INTERCEPTOR_ERROR"
| "IMAGE_ERROR"
| "LOAD_INTERRUPTED"
| "GENERIC";
export type DetailedErrorCode =
| "MEDIA_UNKNOWN"
| "MEDIA_ABORTED"
| "MEDIA_DECODE"
| "MEDIA_NETWORK"
| "MEDIA_SRC_NOT_SUPPORTED"
| "SOURCE_BUFFER_FAILURE"
| "MEDIAKEYS_UNKNOWN"
| "MEDIAKEYS_NETWORK"
| "MEDIAKEYS_UNSUPPORTED"
| "MEDIAKEYS_WEBCRYPTO"
| "NETWORK_UNKNOWN"
| "SEGMENT_NETWORK"
| "HLS_NETWORK_MASTER_PLAYLIST"
| "HLS_NETWORK_PLAYLIST"
| "HLS_NETWORK_NO_KEY_RESPONSE"
| "HLS_NETWORK_KEY_LOAD"
| "HLS_NETWORK_INVALID_SEGMENT"
| "HLS_SEGMENT_PARSING"
| "DASH_NETWORK"
| "DASH_NO_INIT"
| "SMOOTH_NETWORK"
| "SMOOTH_NO_MEDIA_DATA"
| "MANIFEST_UNKNOWN"
| "HLS_MANIFEST_MASTER"
| "HLS_MANIFEST_PLAYLIST"
| "DASH_MANIFEST_UNKNOWN"
| "DASH_MANIFEST_NO_PERIODS"
| "DASH_MANIFEST_NO_MIMETYPE"
| "DASH_INVALID_SEGMENT_INFO"
| "SMOOTH_MANIFEST"
| "SEGMENT_UNKNOWN"
| "TEXT_UNKNOWN"
| "APP"
| "BREAK_CLIP_LOADING_ERROR"
| "BREAK_SEEK_INTERCEPTOR_ERROR"
| "IMAGE_ERROR"
| "LOAD_INTERRUPTED"
| "GENERIC";
type EndedReason =
| "END_OF_STREAM"
| "ERROR"
| "STOPPED"
| "INTERRUPTED"
| "SKIPPED"
| "BREAK_SWITCH";
export type EndedReason =
| "END_OF_STREAM"
| "ERROR"
| "STOPPED"
| "INTERRUPTED"
| "SKIPPED"
| "BREAK_SWITCH";
/**
* Event data for @see{@link EventType.SEGMENT_DOWNLOADED} event.
*/
export class SegmentDownloadedEvent extends Event {
constructor(downloadTime?: number, size?: number);
/**
* Event data for @see{@link EventType.SEGMENT_DOWNLOADED} event.
* The time it took to download the segment; in milliseconds.
*/
class SegmentDownloadedEvent extends Event {
constructor(downloadTime?: number, size?: number);
/**
* The time it took to download the segment; in milliseconds.
*/
downloadTime?: number;
/**
* The number of bytes in the segment.
*/
size?: number;
}
downloadTime?: number;
/**
* Event data for all events that represent requests made to the receiver.
* The number of bytes in the segment.
*/
class RequestEvent extends Event {
constructor(
type: EventType,
requestData?: RequestData,
senderId?: string
);
size?: number;
}
/**
* Event data for all events that represent requests made to the receiver.
*/
export class RequestEvent extends Event {
constructor(
type: EventType,
requestData?: RequestData,
senderId?: string
);
/**
* The data that was sent with the request.
*/
requestData?: RequestData;
/**
* The data that was sent with the request.
*/
requestData?: RequestData;
/**
* The sender id the request came from.
*/
senderId?: string;
}
/**
* Event data superexport class for all events dispatched by @see{@link PlayerManager}
*/
export class Event {
constructor(type: EventType);
/**
* Type of the event.
*/
type: EventType;
}
/**
* Event data for @see{@link EventType.MEDIA_STATUS} event.
*/
export class MediaStatusEvent extends Event {
constructor(type: EventType, mediaStatus?: MediaStatus);
/**
* The media status that was sent.
*/
mediaStatus?: MediaStatus;
}
/**
* Event data for pause events forwarded from the MediaElement.
*/
export class MediaPauseEvent extends Event {
constructor(currentMediaTime?: number, ended?: boolean);
/**
* Indicate if the media ended (indicates the pause was fired due to stream reached the end).
*/
ended?: boolean;
}
/**
* Event data for @see{@link EventType.MEDIA_FINISHED} event.
*/
export class MediaFinishedEvent extends Event {
constructor(currentMediaTime?: number, endedReason?: EndedReason);
/**
* The time when the media finished (in seconds). For an item in a queue; this value represents the time in the currently playing queue item ( where 0 means the queue item has just started).
*/
currentTime?: number;
/**
* The reason the media finished.
*/
endedReason?: EndedReason;
}
/**
* Event data for all events forwarded from the MediaElement.
*/
export class MediaElementEvent extends Event {
constructor(type: EventType, currentMediaTime?: number);
/**
* The time in the currently playing clip when the event was fired (in seconds). Undefined if playback has not started yet.
*/
currentMediaTime?: number;
}
/**
* Event data for all events pertaining to processing a load / preload request. made to the player.
*/
export class LoadEvent extends Event {
constructor(type: EventType, media?: MediaInformation);
/**
* Information about the media being loaded.
*/
media: MediaInformation;
}
/**
* Event data for @see{@link EventType.INBAND_TRACK_ADDED} event.
*/
export class InbandTrackAddedEvent {
constructor(track: Track);
/**
* Added track.
*/
track: Track;
}
/** Event data for @see{@link EventType.ID3} event. */
export class Id3Event extends Event {
constructor(segmentData: Uint8Array);
/**
* The segment data.
*/
segmentData: Uint8Array;
}
/**
* Event data for @see{@link EventType.EMSG} event.
*/
export class EmsgEvent extends Event {
constructor(emsgData: any);
/**
* The time that the event ends (in presentation time). Undefined if using legacy Dash support.
*/
endTime: any;
/**
* The duration of the event (in units of timescale). Undefined if using legacy Dash support.
*/
eventDuration: any;
/**
* A field identifying this instance of the message. Undefined if using legacy Dash support.
*/
id: any;
/**
* Body of the message. Undefined if using legacy Dash support.
*/
messageData: any;
/**
* The offset that the event starts; relative to the start of the segment this is contained in (in units of timescale). Undefined if using legacy Dash support.
*/
presentationTimeDelta: any;
/**
* The sender id the request came from.
*/
senderId?: string;
}
/**
* Identifies the message scheme. Undefined if using legacy Dash support.
*/
schemeIdUri: any;
/**
* Event data superclass for all events dispatched by @see{@link PlayerManager}
* The segment data. This is only defined if using legacy Dash support.
*/
class Event {
constructor(type: EventType);
segmentData: any;
/**
* Type of the event.
*/
type: EventType;
}
/**
* Event data for @see{@link EventType.MEDIA_STATUS} event.
* The time that the event starts (in presentation time). Undefined if using legacy Dash support.
*/
class MediaStatusEvent extends Event {
constructor(type: EventType, mediaStatus?: MediaStatus);
startTime: any;
/**
* The media status that was sent.
*/
mediaStatus?: MediaStatus;
}
/**
* Event data for pause events forwarded from the MediaElement.
* Provides the timescale; in ticks per second. Undefined if using legacy Dash support.
*/
class MediaPauseEvent extends Event {
constructor(currentMediaTime?: number, ended?: boolean);
timescale: any;
/**
* Indicate if the media ended (indicates the pause was fired due to stream reached the end).
*/
ended?: boolean;
}
/**
* Event data for @see{@link EventType.MEDIA_FINISHED} event.
*/
class MediaFinishedEvent extends Event {
constructor(currentMediaTime?: number, endedReason?: EndedReason);
/**
* The time when the media finished (in seconds). For an item in a queue; this value represents the time in the currently playing queue item ( where 0 means the queue item has just started).
*/
currentTime?: number;
/**
* The reason the media finished.
*/
endedReason?: EndedReason;
}
/**
* Event data for all events forwarded from the MediaElement.
*/
class MediaElementEvent extends Event {
constructor(type: EventType, currentMediaTime?: number);
/**
* The time in the currently playing clip when the event was fired (in seconds). Undefined if playback has not started yet.
*/
currentMediaTime?: number;
}
/**
* Event data for all events pertaining to processing a load / preload request. made to the player.
*/
class LoadEvent extends Event {
constructor(type: EventType, media?: MediaInformation);
/**
* Information about the media being loaded.
*/
media: MediaInformation;
}
/**
* Event data for @see{@link EventType.INBAND_TRACK_ADDED} event.
*/
class InbandTrackAddedEvent {
constructor(track: Track);
* Specifies the value for the event. Undefined if using legacy Dash support.
*/
value: any;
}
/**
* Event data for @see{@link EventType.CLIP_ENDED} event.
*/
export class ClipEndedEvent extends Event {
constructor(currentMediaTime: number, endedReason?: EndedReason);
/**
* Added track.
*/
track: Track;
}
/** Event data for @see{@link EventType.ID3} event. */
class Id3Event extends Event {
constructor(segmentData: Uint8Array);
/**
* The time in media (in seconds) when clip ended.
*/
currentMediaTime: number;
/**
* The segment data.
*/
segmentData: Uint8Array;
}
/**
* Event data for @see{@link EventType.EMSG} event.
* The reason the clip ended.
*/
class EmsgEvent extends Event {
constructor(emsgData: any);
endedReason?: EndedReason;
}
/**
* Event data for @see{@link EventType.CACHE_LOADED} event.
*/
export class CacheLoadedEvent extends Event {
constructor(media?: MediaInformation);
/**
* Information about the media being cached.
*/
media: MediaInformation;
}
export class CacheItemEvent extends Event {
constructor(type: EventType, url: string);
/**
* The URL of data fetched from cache
*/
url: string;
}
export class BufferingEvent extends Event {
constructor(isBuffering: boolean);
/**
* True if the player is entering a buffering state.
*/
isBuffering: boolean;
}
export class BreaksEvent extends Event {
constructor(
type: EventType,
currentMediaTime?: number,
index?: number,
total?: number,
whenSkippable?: number,
endedReason?: EndedReason,
breakClipId?: string,
breakId?: string
);
/**
* The break's id. Refer to Break.id
*/
breakId?: string;
/**
* The break clip's id. Refer to BreakClip.id
*/
breakClipId?: string;
/**
* The time in the currently playing media when the break event occurred.
*/
currentMediaTime?: number;
/**
* The reason the break clip ended.
*/
endedReason?: EndedReason;
/**
* Index of break clip; which starts from 1.
*/
index: number;
/**
* Total number of break clips.
*/
total: number;
/**
* When to skip current break clip in sec; after break clip begins to play.
*/
whenSkippable?: number;
}
/**
* Event data for @see {@link EventType.BITRATE_CHANGED} event.
*/
export class BitrateChangedEvent {
constructor(totalBitrate?: number);
/** The bitrate of the media (audio and video) in bits per second. */
totalBitrate: number;
}
export class ErrorEvent extends Event {
constructor(detailedErrorCode: DetailedErrorCode, error?: any);
/**
* The time that the event ends (in presentation time). Undefined if using legacy Dash support.
*/
endTime: any;
/**
* The duration of the event (in units of timescale). Undefined if using legacy Dash support.
*/
eventDuration: any;
/**
* A field identifying this instance of the message. Undefined if using legacy Dash support.
*/
id: any;
/**
* Body of the message. Undefined if using legacy Dash support.
*/
messageData: any;
/**
* The offset that the event starts; relative to the start of the segment this is contained in (in units of timescale). Undefined if using legacy Dash support.
*/
presentationTimeDelta: any;
/**
* Identifies the message scheme. Undefined if using legacy Dash support.
*/
schemeIdUri: any;
/**
* The segment data. This is only defined if using legacy Dash support.
*/
segmentData: any;
/**
* The time that the event starts (in presentation time). Undefined if using legacy Dash support.
*/
startTime: any;
/**
* Provides the timescale; in ticks per second. Undefined if using legacy Dash support.
*/
timescale: any;
/**
* Specifies the value for the event. Undefined if using legacy Dash support.
*/
value: any;
}
/**
* Event data for @see{@link EventType.CLIP_ENDED} event.
*/
class ClipEndedEvent extends Event {
constructor(currentMediaTime: number, endedReason?: EndedReason);
/**
* The time in media (in seconds) when clip ended.
*/
currentMediaTime: number;
/**
* The reason the clip ended.
*/
endedReason?: EndedReason;
}
/**
* Event data for @see{@link EventType.CACHE_LOADED} event.
*/
class CacheLoadedEvent extends Event {
constructor(media?: MediaInformation);
/**
* Information about the media being cached.
*/
media: MediaInformation;
}
class CacheItemEvent extends Event {
constructor(type: EventType, url: string);
/**
* The URL of data fetched from cache
*/
url: string;
}
class BufferingEvent extends Event {
constructor(isBuffering: boolean);
/**
* True if the player is entering a buffering state.
*/
isBuffering: boolean;
}
class BreaksEvent extends Event {
constructor(
type: EventType,
currentMediaTime?: number,
index?: number,
total?: number,
whenSkippable?: number,
endedReason?: EndedReason,
breakClipId?: string,
breakId?: string
);
/**
* The break's id. Refer to Break.id
*/
breakId?: string;
/**
* The break clip's id. Refer to BreakClip.id
*/
breakClipId?: string;
/**
* The time in the currently playing media when the break event occurred.
*/
currentMediaTime?: number;
/**
* The reason the break clip ended.
*/
endedReason?: EndedReason;
/**
* Index of break clip; which starts from 1.
*/
index: number;
/**
* Total number of break clips.
*/
total: number;
/**
* When to skip current break clip in sec; after break clip begins to play.
*/
whenSkippable?: number;
}
/**
* Event data for @see {@link EventType.BITRATE_CHANGED} event.
*/
class BitrateChangedEvent {
constructor(totalBitrate?: number);
/** The bitrate of the media (audio and video) in bits per second. */
totalBitrate: number;
}
class ErrorEvent extends Event {
constructor(detailedErrorCode: DetailedErrorCode, error?: any);
detailedErrorCode: DetailedErrorCode;
error?: any;
}
detailedErrorCode: DetailedErrorCode;
error?: any;
}
File diff suppressed because it is too large Load Diff
+160 -162
View File
@@ -1,198 +1,196 @@
import { EventType } from "./cast.framework.events";
export = cast.framework.system;
declare namespace cast.framework.system {
type EventType =
// Fired when the system is ready.
| "READY"
// Fired when the application is terminated
| "SHUTDOWN"
// Fired when a new sender has connected.
| "SENDER_CONNECTED"
// Fired when a sender has disconnected.
| "SENDER_DISCONNECTED"
// Fired when there is a system error.
| "ERROR"
// Fired when the system volume has changed.
| "SYSTEM_VOLUME_CHANGED"
// Fired when the visibility of the application has changed
// (for example after a HDMI Input change or when the TV is turned
// off/on and the cast device is externally powered).
// Note that this API has the same effect as the webkitvisibilitychange event raised
// by your document, we provided it as CastReceiverManager API for convenience and
// to avoid a dependency on a webkit-prefixed event.
| "VISIBILITY_CHANGED"
// Fired when the standby state of the TV has changed.
// This event is related to the visibility chnaged event, as if the TV is in standby
// the visibility will be false, the visibility is more granular
// (as it also detects that the TV has selected a different channel)
// but it is not reliably detected in all TVs,
// standby can be used in those cases as most TVs implement it.
| "STANDBY_CHANGED"
| "MAX_VIDEO_RESOLUTION_CHANGED"
| "FEEDBACK_STARTED";
export as namespace system
export type EventType =
// Fired when the system is ready.
| "READY"
// Fired when the application is terminated
| "SHUTDOWN"
// Fired when a new sender has connected.
| "SENDER_CONNECTED"
// Fired when a sender has disconnected.
| "SENDER_DISCONNECTED"
// Fired when there is a system error.
| "ERROR"
// Fired when the system volume has changed.
| "SYSTEM_VOLUME_CHANGED"
// Fired when the visibility of the application has changed
// (for example after a HDMI Input change or when the TV is turned
// off/on and the cast device is externally powered).
// Note that this API has the same effect as the webkitvisibilitychange event raised
// by your document, we provided it as CastReceiverManager API for convenience and
// to avoid a dependency on a webkit-prefixed event.
| "VISIBILITY_CHANGED"
// Fired when the standby state of the TV has changed.
// This event is related to the visibility chnaged event, as if the TV is in standby
// the visibility will be false, the visibility is more granular
// (as it also detects that the TV has selected a different channel)
// but it is not reliably detected in all TVs,
// standby can be used in those cases as most TVs implement it.
| "STANDBY_CHANGED"
| "MAX_VIDEO_RESOLUTION_CHANGED"
| "FEEDBACK_STARTED";
type SystemState =
| "NOT_STARTED"
| "STARTING_IN_BACKGROUND"
| "STARTING"
| "READY"
| "STOPPING_IN_BACKGROUND"
| "STOPPING";
export type SystemState =
| "NOT_STARTED"
| "STARTING_IN_BACKGROUND"
| "STARTING"
| "READY"
| "STOPPING_IN_BACKGROUND"
| "STOPPING";
type StandbyState = "STANDBY" | "NOT_STANDBY" | "UNKNOWN";
export type StandbyState = "STANDBY" | "NOT_STANDBY" | "UNKNOWN";
type DisconnectReason = "REQUESTED_BY_SENDER" | "ERROR" | "UNKNOWN";
export type DisconnectReason = "REQUESTED_BY_SENDER" | "ERROR" | "UNKNOWN";
/**
* Event dispatched by @see{@link CastReceiverManager} when the visibility of the application changes (HDMI input change; TV is turned off).
*/
export class VisibilityChangedEvent {
constructor(isVisible: boolean);
/**
* Event dispatched by @see{@link CastReceiverManager} when the visibility of the application changes (HDMI input change; TV is turned off).
* Whether the Cast device is the active input or not.
*/
class VisibilityChangedEvent {
constructor(isVisible: boolean);
isVisible: boolean;
}
/**
* Whether the Cast device is the active input or not.
*/
isVisible: boolean;
}
/**
* Represents the system volume data.
*/
export interface SystemVolumeData {
/**
* The level (from 0.0 to 1.0) of the system volume
*/
level: number;
/**
* Whether the system volume is muted or not.
*/
muted: boolean;
}
/**
* Event dispatched by @see{CastReceiverManager} when the system volume changes.
*/
export class SystemVolumeChangedEvent extends Event {
constructor(volume: SystemVolumeData);
/**
* The system volume data
*/
data: SystemVolumeData;
}
/**
* Event dispatched by @see{@link CastReceiverManager} when the TV enters/leaves the standby state.
*/
export class StandbyChangedEvent {
constructor(isStandby: boolean);
isStandby: boolean;
}
/**
* Whether the TV is in standby or not.
*/
export interface ShutdownEvent extends Event {
[key: string]: any;
}
/**
* Event dispatched by @see{@link CastReceiverManager} when a sender is disconnected.
*/
export class SenderDisconnectedEvent extends Event {
constructor(senderId: string, userAgent: string);
/**
* The ID of the sender connected.
*/
senderId: string;
/**
* Represents the system volume data.
* The user agent of the sender.
*/
interface SystemVolumeData {
/**
* The level (from 0.0 to 1.0) of the system volume
*/
level: number;
/**
* Whether the system volume is muted or not.
*/
muted: boolean;
}
userAgent: string;
/**
* Event dispatched by @see{CastReceiverManager} when the system volume changes.
* The reason the sender was disconnected.
*/
class SystemVolumeChangedEvent extends Event {
constructor(volume: SystemVolumeData);
/**
* The system volume data
*/
data: SystemVolumeData;
}
reason?: DisconnectReason;
}
/**
* Event dispatched by @see{@link CastReceiverManager} when a sender is connected.
*/
export class SenderConnectedEvent extends Event {
constructor(senderId: string, userAgent: string);
/**
* Event dispatched by @see{@link CastReceiverManager} when the TV enters/leaves the standby state.
* The ID of the sender connected.
*/
class StandbyChangedEvent {
constructor(isStandby: boolean);
senderId: string;
isStandby: boolean;
}
/**
* Whether the TV is in standby or not.
* The user agent of the sender.
*/
interface ShutdownEvent extends Event {
[key: string]: any;
}
userAgent: string;
}
/**
* Represents the data of a connected sender device.
*/
export interface Sender {
/**
* Event dispatched by @see{@link CastReceiverManager} when a sender is disconnected.
* The sender Id.
*/
class SenderDisconnectedEvent extends Event {
constructor(senderId: string, userAgent: string);
/**
* The ID of the sender connected.
*/
senderId: string;
/**
* The user agent of the sender.
*/
userAgent: string;
/**
* The reason the sender was disconnected.
*/
reason?: DisconnectReason;
}
id: string;
/**
* Event dispatched by @see{@link CastReceiverManager} when a sender is connected.
* Indicate the sender supports large messages (>64KB)
*/
class SenderConnectedEvent extends Event {
constructor(senderId: string, userAgent: string);
/**
* The ID of the sender connected.
*/
senderId: string;
/**
* The user agent of the sender.
*/
userAgent: string;
}
largeMessageSupported?: boolean;
/**
* Represents the data of a connected sender device.
* The userAgent of the sender.
*/
interface Sender {
/**
* The sender Id.
*/
id: string;
/**
* Indicate the sender supports large messages (>64KB)
*/
largeMessageSupported?: boolean;
/**
* The userAgent of the sender.
*/
userAgent?: string;
}
userAgent?: string;
}
/**
* Event dispatched by CastReceiverManager when the system is ready.
*/
export class ReadyEvent {
constructor(applicationData: ApplicationData);
/**
* Event dispatched by CastReceiverManager when the system is ready.
* The application data
*/
class ReadyEvent {
constructor(applicationData: ApplicationData);
data: ApplicationData;
}
/**
* The application data
*/
data: ApplicationData;
}
/**
* Event dispatched by @see{@link CastReceiverManager} when the system needs to update the restriction on maximum video resolution.
*/
export class MaxVideoResolutionChangedEvent extends Event {
constructor(height: number);
/**
* Event dispatched by @see{@link CastReceiverManager} when the system needs to update the restriction on maximum video resolution.
* Maximum video resolution requested by the system. The value of 0 means there is no restriction.
*/
class MaxVideoResolutionChangedEvent extends Event {
constructor(height: number);
/**
* Maximum video resolution requested by the system. The value of 0 means there is no restriction.
*/
height: number;
}
/** Event dispatched by @see{@link CastReceiverManager} when the systems starts to create feedback report. */
interface FeedbackStartedEvent extends Event {
[key: string]: any;
}
/** Event dispatched by @see{@link CastReceiverContext} which contains system information. */
class Event {
constructor(type: EventType, data?: any);
type: EventType;
data?: any;
}
/** Represents the data of the launched application. */
interface ApplicationData {
id(): string;
launchingSenderId(): string;
name(): string;
namespaces(): string[];
sessionId(): number;
}
height: number;
}
/** Event dispatched by @see{@link CastReceiverManager} when the systems starts to create feedback report. */
export interface FeedbackStartedEvent extends Event {
[key: string]: any;
}
/** Event dispatched by @see{@link CastReceiverContext} which contains system information. */
export class Event {
constructor(type: EventType, data?: any);
type: EventType;
data?: any;
}
/** Represents the data of the launched application. */
export interface ApplicationData {
id(): string;
launchingSenderId(): string;
name(): string;
namespaces(): string[];
sessionId(): number;
}
+179 -183
View File
@@ -1,197 +1,193 @@
import { PlayerDataEventType } from "./cast.framework.ui";
import { MediaMetadata } from "./cast.framework.messages";
import { PlayerDataChangedEventHandler } from "./index";
export = cast.framework.ui;
export as namespace ui
export type ContentType = "video" | "audio" | "image";
declare namespace cast.framework.ui {
type ContentType = "video" | "audio" | "image";
export type State =
| "launching"
| "idle"
| "loading"
| "buffering"
| "paused"
| "playing";
type State =
| "launching"
| "idle"
| "loading"
| "buffering"
| "paused"
| "playing";
export type PlayerDataEventType =
| "ANY_CHANGE"
| "STATE_CHANGED"
| "IS_SEEKING_CHANGED"
| "DURATION_CHANGED"
| "CURRENT_TIME_CHANGED"
| "METADATA_CHANGED"
| "TITLE_CHANGED"
| "SUBTITLE_CHANGED"
| "THUMBNAIL_URL_CHANGED"
| "NEXT_TITLE_CHANGED"
| "NEXT_SUBTITLE_CHANGED"
| "NEXT_THUMBNAIL_URL_CHANGED"
| "PRELOADING_NEXT_CHANGED"
| "CONTENT_TYPE_CHANGED"
| "IS_LIVE_CHANGED"
| "BREAK_PERCENTAGE_POSITIONS_CHANGED"
| "IS_PLAYING_BREAK_CHANGED"
| "IS_BREAK_SKIPPABLE_CHANGED"
| "WHEN_SKIPPABLE_CHANGED"
| "NUMBER_BREAK_CLIPS_CHANGED"
| "CURRENT_BREAK_CLIP_NUMBER_CHANGED"
| "DISPLAY_STATUS_CHANGED";
type PlayerDataEventType =
| "ANY_CHANGE"
| "STATE_CHANGED"
| "IS_SEEKING_CHANGED"
| "DURATION_CHANGED"
| "CURRENT_TIME_CHANGED"
| "METADATA_CHANGED"
| "TITLE_CHANGED"
| "SUBTITLE_CHANGED"
| "THUMBNAIL_URL_CHANGED"
| "NEXT_TITLE_CHANGED"
| "NEXT_SUBTITLE_CHANGED"
| "NEXT_THUMBNAIL_URL_CHANGED"
| "PRELOADING_NEXT_CHANGED"
| "CONTENT_TYPE_CHANGED"
| "IS_LIVE_CHANGED"
| "BREAK_PERCENTAGE_POSITIONS_CHANGED"
| "IS_PLAYING_BREAK_CHANGED"
| "IS_BREAK_SKIPPABLE_CHANGED"
| "WHEN_SKIPPABLE_CHANGED"
| "NUMBER_BREAK_CLIPS_CHANGED"
| "CURRENT_BREAK_CLIP_NUMBER_CHANGED"
| "DISPLAY_STATUS_CHANGED";
/**
* Player data changed event. Provides the changed field (type); and new value.
*/
export class PlayerDataChangedEvent {
constructor(type: PlayerDataEventType, field: string, value: any);
/**
* Player data changed event. Provides the changed field (type); and new value.
* The field name that was changed.
*/
class PlayerDataChangedEvent {
constructor(type: PlayerDataEventType, field: string, value: any);
field: string;
/**
* The field name that was changed.
*/
field: string;
type: PlayerDataEventType;
type: PlayerDataEventType;
/**
* The new field value.
*/
value: any;
}
/**
* Player data binder. Bind a player data object to the player state.
* The player data will be updated to reflect correctly the current player state without firing any change event.
* The new field value.
*/
class PlayerDataBinder {
constructor(playerData: PlayerData);
/**
* Add listener to player data changes.
*/
addEventListener: (
type: PlayerDataEventType,
listener: PlayerDataChangedEventHandler
) => void;
/**
* Remove listener to player data changes.
*/
removeEventListener: (
type: PlayerDataEventType,
listener: PlayerDataChangedEventHandler
) => void;
}
/**
* Player data. Provide the player media and break state.
*/
interface PlayerData {
/**
* Array of breaks positions in percentage.
*/
breakPercentagePositions: number[];
/**
* Content Type.
*/
contentType: ContentType;
/**
* The number of the current playing break clip in the break.
*/
currentBreakClipNumber: number;
/**
* Media current position in seconds; or break current position if playing break.
*/
currentTime: number;
/**
* Whether the player metadata (ie: title; currentTime) should be displayed.
* This will be true if at least one field in the metadata should be displayed.
* In some cases; displayStatus will be true; but parts of the metadata should be hidden
* (ie: the media title while media is seeking).
* In these cases; additional css can be applied to hide those elements.
* For cases where the media is audio-only; this will almost always be true.
* In cases where the media is video; this will be true when:
* (1) the video is loading; buffering; or seeking
* (2) a play request was made in the last five seconds while media is already playing;
* (3) there is a request made to show the status in the last five seconds; or
* (4) the media was paused in the last five seconds.
*/
displayStatus: boolean;
/**
* Media duration in seconds; Or break duration if playing break.
*/
duration: number;
/**
* Indicate break clip can be skipped.
*/
isBreakSkippable: boolean;
/**
* Indicate if the content is a live stream.
*/
isLive: boolean;
/**
* Indicate that the receiver is playing a break.
*/
isPlayingBreak: boolean;
/**
* Indicate the player is seeking (can be either during playing or pausing).
*/
isSeeking: boolean;
/**
* Media metadata.
*/
metadata: MediaMetadata;
/**
* Next Item subtitle.
*/
nextSubtitle: string;
/**
* Next Item thumbnail url.
*/
nextThumbnailUrl: string;
/**
* Next Item title.
*/
nextTitle: string;
/**
* Number of break clips in current break.
*/
numberBreakClips: number;
/**
* Flag to show/hide next item metadata.
*/
preloadingNext: boolean;
/**
* Current player state.
*/
state: State;
/**
* Content thumbnail url.
*/
thumbnailUrl: string;
/**
* Content title.
*/
title: string;
/**
* Provide the time a break is skipable - relative to current playback time. Undefined if not skippable.
*/
whenSkippable?: number;
}
value: any;
}
/**
* Player data binder. Bind a player data object to the player state.
* The player data will be updated to reflect correctly the current player state without firing any change event.
*/
export class PlayerDataBinder {
constructor(playerData: PlayerData);
/**
* Add listener to player data changes.
*/
addEventListener: (
type: PlayerDataEventType,
listener: PlayerDataChangedEventHandler
) => void;
/**
* Remove listener to player data changes.
*/
removeEventListener: (
type: PlayerDataEventType,
listener: PlayerDataChangedEventHandler
) => void;
}
/**
* Player data. Provide the player media and break state.
*/
export interface PlayerData {
/**
* Array of breaks positions in percentage.
*/
breakPercentagePositions: number[];
/**
* Content Type.
*/
contentType: ContentType;
/**
* The number of the current playing break clip in the break.
*/
currentBreakClipNumber: number;
/**
* Media current position in seconds; or break current position if playing break.
*/
currentTime: number;
/**
* Whether the player metadata (ie: title; currentTime) should be displayed.
* This will be true if at least one field in the metadata should be displayed.
* In some cases; displayStatus will be true; but parts of the metadata should be hidden
* (ie: the media title while media is seeking).
* In these cases; additional css can be applied to hide those elements.
* For cases where the media is audio-only; this will almost always be true.
* In cases where the media is video; this will be true when:
* (1) the video is loading; buffering; or seeking
* (2) a play request was made in the last five seconds while media is already playing;
* (3) there is a request made to show the status in the last five seconds; or
* (4) the media was paused in the last five seconds.
*/
displayStatus: boolean;
/**
* Media duration in seconds; Or break duration if playing break.
*/
duration: number;
/**
* Indicate break clip can be skipped.
*/
isBreakSkippable: boolean;
/**
* Indicate if the content is a live stream.
*/
isLive: boolean;
/**
* Indicate that the receiver is playing a break.
*/
isPlayingBreak: boolean;
/**
* Indicate the player is seeking (can be either during playing or pausing).
*/
isSeeking: boolean;
/**
* Media metadata.
*/
metadata: MediaMetadata;
/**
* Next Item subtitle.
*/
nextSubtitle: string;
/**
* Next Item thumbnail url.
*/
nextThumbnailUrl: string;
/**
* Next Item title.
*/
nextTitle: string;
/**
* Number of break clips in current break.
*/
numberBreakClips: number;
/**
* Flag to show/hide next item metadata.
*/
preloadingNext: boolean;
/**
* Current player state.
*/
state: State;
/**
* Content thumbnail url.
*/
thumbnailUrl: string;
/**
* Content title.
*/
title: string;
/**
* Provide the time a break is skipable - relative to current playback time. Undefined if not skippable.
*/
whenSkippable?: number;
}
@@ -1,64 +1,60 @@
import {
PlayerData,
PlayerDataBinder
} from "chromecast-caf-receiver/cast.framework.ui";
import {
ReadyEvent,
ApplicationData
} from "chromecast-caf-receiver/cast.framework.system";
import {
RequestEvent,
Event,
BreaksEvent
} from "chromecast-caf-receiver/cast.framework.events";
import {
QueueBase,
TextTracksManager,
QueueManager,
PlayerManager
} from "chromecast-caf-receiver/cast.framework";
import {
BreakSeekData,
BreakClipLoadInterceptorContext,
BreakManager
} from "chromecast-caf-receiver/cast.framework.breaks";
import {
Break,
BreakClip,
LoadRequestData,
Track,
MediaMetadata
} from "chromecast-caf-receiver/cast.framework.messages";
import { MediaMetadata } from "chromecast-caf-receiver/cast.framework.messages";
const breaksEvent = new BreaksEvent('BREAK_STARTED');
breaksEvent.breakId = 'some-break-id';
breaksEvent.breakClipId = 'some-break-clip-id';
// The following test showcases how you can import individual types directly from the namespace:
const track = new Track(1, "TEXT");
const breakClip = new BreakClip("id");
const adBreak = new Break("id", ["id"], 1);
const rEvent = new RequestEvent("BITRATE_CHANGED", { requestId: 2 });
const pManager = new PlayerManager();
pManager.addEventListener("STALLED", () => { });
const ttManager = new TextTracksManager();
const qManager = new QueueManager();
const qBase = new QueueBase();
const mediaMetadata = new MediaMetadata("GENERIC");
mediaMetadata.metadataType = "TV_SHOW";
// The following tests showcase how you can globally access 'cast' types using
// the nested namespace style. This is the preferred method as it
// conforms exactly to the CAF documentation.
// tslint:disable-next-line
const breaksEvent = new cast.framework.events.BreaksEvent("BREAK_STARTED");
breaksEvent.breakId = "some-break-id";
breaksEvent.breakClipId = "some-break-clip-id";
// tslint:disable-next-line
const track = new cast.framework.messages.Track(1, "TEXT");
// tslint:disable-next-line
const breakClip = new cast.framework.messages.BreakClip("id");
// tslint:disable-next-line
const adBreak = new cast.framework.messages.Break("id", ["id"], 1);
// tslint:disable-next-line
const rEvent = new cast.framework.events.RequestEvent("BITRATE_CHANGED", {
requestId: 2
});
// tslint:disable-next-line
const pManager = new cast.framework.PlayerManager();
pManager.addEventListener("STALLED", () => {});
// tslint:disable-next-line
const ttManager = new cast.framework.TextTracksManager();
// tslint:disable-next-line
const qManager = new cast.framework.QueueManager();
// tslint:disable-next-line
const qBase = new cast.framework.QueueBase();
const items = qBase.fetchItems(1, 3, 4);
const breakSeekData = new BreakSeekData(0, 100, []);
const breakClipLoadContext = new BreakClipLoadInterceptorContext(adBreak);
const breakManager: BreakManager = {
// tslint:disable-next-line
const breakSeekData = new cast.framework.breaks.BreakSeekData(0, 100, []);
// tslint:disable-next-line
const breakClipLoadContext = new cast.framework.breaks.BreakClipLoadInterceptorContext(
adBreak
);
// tslint:disable-next-line
const breakManager: cast.framework.breaks.BreakManager = {
getBreakById: () => adBreak,
getBreakClipById: () => breakClip,
getBreakClips: () => [breakClip],
getBreaks: () => [adBreak],
getPlayWatchedBreak: () => true,
setBreakClipLoadInterceptor: () => { },
setBreakSeekInterceptor: () => { },
setPlayWatchedBreak: () => { },
setVastTrackingInterceptor: () => { }
setBreakClipLoadInterceptor: () => {},
setBreakSeekInterceptor: () => {},
setPlayWatchedBreak: () => {},
setVastTrackingInterceptor: () => {}
};
const lrd: LoadRequestData = {
// tslint:disable-next-line
const lrd: cast.framework.messages.LoadRequestData = {
requestId: 1,
activeTrackIds: [1, 2],
media: {
@@ -75,7 +71,8 @@ const lrd: LoadRequestData = {
queueData: {}
};
const appData: ApplicationData = {
// tslint:disable-next-line
const appData: cast.framework.system.ApplicationData = {
id: () => "id",
launchingSenderId: () => "launch-id",
name: () => "name",
@@ -83,9 +80,11 @@ const appData: ApplicationData = {
sessionId: () => 1
};
const readyEvent = new ReadyEvent(appData);
// tslint:disable-next-line
const readyEvent = new cast.framework.system.ReadyEvent(appData);
const data = readyEvent.data;
const pData: PlayerData = {
// tslint:disable-next-line
const pData: cast.framework.ui.PlayerData = {
breakPercentagePositions: [1],
contentType: "video",
currentBreakClipNumber: 2,
@@ -96,7 +95,8 @@ const pData: PlayerData = {
isLive: true,
isPlayingBreak: false,
isSeeking: true,
metadata: new MediaMetadata("GENERIC"),
// tslint:disable-next-line
metadata: new cast.framework.messages.MediaMetadata("GENERIC"),
nextSubtitle: "sub",
nextThumbnailUrl: "url",
nextTitle: "title",
@@ -107,5 +107,6 @@ const pData: PlayerData = {
title: "title",
whenSkippable: 321
};
const binder = new PlayerDataBinder(pData);
binder.addEventListener("ANY_CHANGE", e => { });
// tslint:disable-next-line
const binder = new cast.framework.ui.PlayerDataBinder(pData);
binder.addEventListener("ANY_CHANGE", e => {});
+11 -7
View File
@@ -11,14 +11,18 @@
/// <reference path="./cast.framework.system.d.ts" />
/// <reference path="./cast.framework.ui.d.ts" />
import * as framework from "./cast.framework";
import { PlayerDataChangedEvent } from './cast.framework.ui';
import { NetworkRequestInfo } from './cast.framework';
import { Event } from './cast.framework.events';
export as namespace cast;
export type EventHandler = (event: Event) => void;
export type PlayerDataChangedEventHandler = (
event: PlayerDataChangedEvent
) => void;
export type RequestHandler = (request: NetworkRequestInfo) => void;
export type BinaryHandler = (data: Uint8Array) => Uint8Array;
export { framework };
declare global {
type EventHandler = (event: Event) => void;
type PlayerDataChangedEventHandler = (
event: PlayerDataChangedEvent
) => void;
type RequestHandler = (request: framework.NetworkRequestInfo) => void;
type BinaryHandler = (data: Uint8Array) => Uint8Array;
}
+9
View File
@@ -0,0 +1,9 @@
import createHash = require('create-hash');
const hash = createHash('sha224');
hash.update('synchronous write');
hash.digest();
hash.write('write to it as a stream');
hash.end();
hash.read();
+26
View File
@@ -0,0 +1,26 @@
// Type definitions for create-hash 1.2
// Project: https://github.com/crypto-browserify/createHash
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
/// <reference types="node" />
import { Hash } from 'crypto';
export = createHash;
declare function createHash(algo: createHash.Algorithm): Hash;
declare namespace createHash {
type Algorithm =
| 'md5'
| 'rmd160'
| 'ripemd160'
| 'sha'
| 'sha1'
| 'sha224'
| 'sha256'
| 'sha384'
| 'sha512';
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"create-hash-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
@@ -0,0 +1,19 @@
import { ExpiryManager } from "expirymanager";
const expiryManager = new ExpiryManager();
const keys = ['1', '2'];
expiryManager.expire(keys, 1);
expiryManager.unexpire(keys);
const expiry: number = expiryManager.getExpiry(keys[0]);
let expiredKeys = expiryManager.getExpiredKeys();
expiredKeys = expiryManager.getExpiredKeys(expiryManager.now());
expiredKeys = expiryManager.extractExpiredKeys();
expiredKeys = expiryManager.extractExpiredKeys(expiryManager.now());
expiryManager.clear();
+25
View File
@@ -0,0 +1,25 @@
// Type definitions for expirymanager 0.9
// Project: https://github.com/SocketCluster/expirymanager
// Definitions by: Daniel Rose <https://github.com/DanielRose>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export type Key = any;
export type Keys = Key[];
export class ExpiryManager {
constructor();
now(): number;
expire(keys: Keys, seconds: number): void;
unexpire(keys: Keys): void;
getExpiry(key: Key): number;
getKeysByExpiry(expiry: number): Keys;
getExpiredKeys(time?: number): Keys;
extractExpiredKeys(time?: number): Keys;
clear(): void;
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"expirymanager-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+18
View File
@@ -0,0 +1,18 @@
import fined = require('fined');
// $ExpectType Result | null
fined({ path: 'path/to/file', extensions: ['.js', '.json'] });
const opts = {
name: '.app',
cwd: '.',
extensions: {
rc: 'default-rc-loader',
'.yml': 'default-yml-loader',
},
};
fined({ path: '.' }, opts);
fined({ path: '~', extensions: { rc: 'some-special-rc-loader' } }, opts);
fined({ path: '~' }, {});
fined({ path: '~' }, { extensions: '.ext' });
+23
View File
@@ -0,0 +1,23 @@
// Type definitions for fined 1.1
// Project: https://github.com/js-cli/fined#readme
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = fined;
declare function fined(path: string | fined.PathSpec, opts?: fined.PathSpec): fined.Result | null;
declare namespace fined {
interface PathSpec {
path?: string;
name?: string;
extensions?: string | string[] | { [extension: string]: string };
cwd?: string;
findUp?: boolean;
}
interface Result {
path: string;
extension: string | { [extension: string]: string };
}
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"fined-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
@@ -0,0 +1,14 @@
import flaggedRespawn = require('flagged-respawn');
const flags = ['--flag'];
flaggedRespawn(flags, process.argv, (ready, child, argv) => {
// $ExpectType boolean
ready;
// $ExpectType Process
child;
// $ExpectType string[]
argv;
});
flaggedRespawn(flags, process.argv, '--flag', () => {});
flaggedRespawn(flags, process.argv, ['--flag'], () => {});
+24
View File
@@ -0,0 +1,24 @@
// Type definitions for flagged-respawn 1.0
// Project: https://github.com/js-cli/js-flagged-respawn
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
export = flaggedRespawn;
declare function flaggedRespawn(
flags: string[],
argv: string[],
callback: flaggedRespawn.Callback
): void;
declare function flaggedRespawn(
flags: string[],
argv: string[],
forcedFlags: string | string[],
callback: flaggedRespawn.Callback
): void;
declare namespace flaggedRespawn {
type Callback = (ready: boolean, proc: NodeJS.Process, argv: string[]) => void;
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"flagged-respawn-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+27
View File
@@ -0,0 +1,27 @@
import { FlexiMap } from "fleximap";
let flexiMap = new FlexiMap();
flexiMap = new FlexiMap({ arr: [] });
flexiMap = new FlexiMap([{ arr: [] }, { obj: {} }]);
flexiMap.set('keyA', {arr: [], obj: {}});
let result = flexiMap.get(['keyA', 'arr']);
flexiMap.add(['keyB1', 'keyB2', 'keyB3'], 123);
result = flexiMap.get(['keyB1', 'keyB2']);
const arr = [];
arr[5] = 'Hello world';
flexiMap.set(['keyC1', 'keyC2'], arr);
result = flexiMap.get(['keyC1', 'keyC2']);
flexiMap.set(['itemsA', 0], 'hello');
flexiMap.set(['itemsA', 2], 'world');
flexiMap.remove(['itemsA', 0]);
flexiMap.set(['itemsB', 0], 'a');
flexiMap.set(['itemsB', 1], 'b');
flexiMap.set(['itemsB', 2], 'c');
let splicedItems = flexiMap.splice(['itemsB'], 1, 1);
splicedItems = flexiMap.splice(['itemsB'], 1, 0, 'b2');
+38
View File
@@ -0,0 +1,38 @@
// Type definitions for fleximap 0.9
// Project: https://github.com/SocketCluster/fleximap
// Definitions by: Daniel Rose <https://github.com/DanielRose>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
export type KeyChain = any;
export class FlexiMap {
constructor(object?: any[] | object);
get(keyChain: KeyChain): any;
getRange(keyChain: KeyChain, fromIndex: number, toIndex: number): any;
getRaw(keyChain: KeyChain): any;
getAll(): any[] | object;
count(keyChain: KeyChain): number;
hasImmediateKey(key: string): boolean;
hasKey(keyChain: KeyChain): boolean;
hasType(keyChain: KeyChain, type: any): boolean;
hasValue(keyChain: KeyChain, value: any): boolean;
hasObject(keyChain: KeyChain, object: object): boolean;
set(keyChain: KeyChain, value: any): any;
add(keyChain: KeyChain, value: any): number;
concat(keyChain: KeyChain, value: any): any;
remove(keyChain: KeyChain): any;
removeRange(keyChain: KeyChain, fromIndex: number, toIndex: number): any[];
removeAll(): void;
splice(keyChain: KeyChain, index: number, count: number, ...items: any[]): any[];
pop(keyChain: KeyChain): any[];
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"fleximap-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+4 -4
View File
@@ -1,9 +1,9 @@
import { IFrameComponent, IFrameOptions, iframeResizer } from "iframe-resizer";
import iframeResizer = require("iframe-resizer");
function testOne(): void {
const iframe: HTMLIFrameElement = document.createElement('iframe');
const options: IFrameOptions = {log: true};
const components: IFrameComponent[] = iframeResizer(options, iframe);
const options: iframeResizer.IFrameOptions = {log: true};
const components: iframeResizer.IFrameComponent[] = iframeResizer(options, iframe);
if (components) {
components.forEach(component => console.log(component.iFrameResizer));
} else {
@@ -13,7 +13,7 @@ function testOne(): void {
function testTwo(): void {
const iframe: HTMLIFrameElement = document.createElement('iframe');
const components: IFrameComponent[] = iframeResizer({
const components: iframeResizer.IFrameComponent[] = iframeResizer({
initCallback: () => {
console.log('Init');
},
+310 -270
View File
@@ -3,275 +3,315 @@
// Definitions by: Armin Baljic <https://github.com/arminbaljic>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// tslint:disable-next-line:interface-name
export interface IFrameObject {
close(): void;
moveToAnchor(anchor: string): void;
resize(): void;
sendMessage(message: any, targetOrigin?: string): void;
declare namespace iframeResizer {
// tslint:disable-next-line:interface-name
interface IFrameObject {
close(): void;
moveToAnchor(anchor: string): void;
resize(): void;
sendMessage(
message: any,
targetOrigin?: string
): void;
}
// tslint:disable-next-line:interface-name
interface IFrameComponent extends HTMLIFrameElement {
iFrameResizer: IFrameObject;
}
// tslint:disable-next-line:interface-name
interface IFrameOptions {
/**
* When enabled changes to the Window size or the DOM will cause the iFrame to resize to the new content size.
* Disable if using size method with custom dimensions.
*/
autoResize?: boolean;
/**
* Override the body background style in the iFrame.
*/
bodyBackground?: string;
/**
* Override the default body margin style in the iFrame. A string can be any valid value for the
* CSS margin attribute, for example '8px 3em'. A number value is converted into px.
*/
bodyMargin?: number | string;
/**
* Override the default body padding style in the iFrame. A string can be any valid value for the
* CSS margin attribute, for example '8px 3em'. A number value is converted into px.
*/
bodyPadding?: number | string;
/**
* When set to true, only allow incoming messages from the domain listed in the src property of the iFrame tag.
* If your iFrame navigates between different domains, ports or protocols; then you will need to
* provide an array of URLs or disable this option.
*/
checkOrigin?: boolean | string[];
/**
* When enabled in page linking inside the iFrame and from the iFrame to the parent page will be enabled.
*/
inPageLinks?: boolean;
/**
* Height calculation method.
*/
heightCalculationMethod?: HeightCalculationMethod;
/**
* Set iFrame Id
*/
id?: string;
/**
* In browsers that don't support mutationObserver, such as IE10, the library falls back to using
* setInterval, to check for changes to the page size.
*/
interval?: number;
/**
* Setting the log option to true will make the scripts in both the host page and the iFrame output
* everything they do to the JavaScript console so you can see the communication between the two scripts.
*/
log?: boolean;
/**
* Set maximum height of iFrame.
*/
maxHeight?: number;
/**
* Set maximum width of iFrame.
*/
maxWidth?: number;
/**
* Set minimum height of iFrame.
*/
minHeight?: number;
/**
* Set minimum width of iFrame.
*/
minWidth?: number;
/**
* Listen for resize events from the parent page, or the iFrame. Select the 'child' value if the iFrame
* can be resized independently of the browser window. Selecting this value can cause issues with some
* height calculation methods on mobile devices.
*/
resizeFrom?: 'parent' | 'child';
/**
* Enable scroll bars in iFrame.
*/
scrolling?: boolean | 'auto';
/**
* Resize iFrame to content height.
*/
sizeHeight?: boolean;
/**
* Resize iFrame to content width.
*/
sizeWidth?: boolean;
/**
* Set the number of pixels the iFrame content size has to change by, before triggering a resize of the iFrame.
*/
tolerance?: number;
/**
* Width calculation method.
*/
widthCalculationMethod?: WidthCalculationMethod;
/**
* Called when iFrame is closed via parentIFrame.close() or iframe.iframeResizer.close() methods.
*/
closedCallback?(iframeId: string): void;
/**
* Initial setup callback function.
*/
initCallback?(iframe: IFrameComponent): void;
/**
* Receive message posted from iFrame with the parentIFrame.sendMessage() method.
*/
messageCallback?(data: IFrameMessageData): void;
/**
* Function called after iFrame resized. Passes in messageData object containing the iFrame, height, width
* and the type of event that triggered the iFrame to resize.
*/
resizedCallback?(data: IFrameResizedData): void;
/**
* Called before the page is repositioned after a request from the iFrame, due to either an in page link,
* or a direct request from either parentIFrame.scrollTo() or parentIFrame.scrollToOffset().
* If this callback function returns false, it will stop the library from repositioning the page, so that
* you can implement your own animated page scrolling instead.
*/
scrollCallback?(data: IFrameScrollData): boolean;
}
// tslint:disable-next-line:interface-name
interface IFramePageOptions {
/**
* This option allows you to restrict the domain of the parent page,
* to prevent other sites mimicking your parent page.
*/
targetOrigin?: string;
/**
* Receive message posted from the parent page with the iframe.iFrameResizer.sendMessage() method.
*/
messageCallback?(message: any): void;
/**
* This function is called once iFrame-Resizer has been initialized after receiving a call from the parent page.
*/
readyCallback?(): void;
/**
* These option can be used to override the option set in the parent page
*/
heightCalculationMethod?: HeightCalculationMethod | (() => number);
/**
* These option can be used to override the option set in the parent page
*/
widthCalculationMethod?: WidthCalculationMethod | (() => number);
}
type HeightCalculationMethod = 'bodyOffset' | 'bodyScroll' | 'documentElementOffset' | 'documentElementScroll' |
'max' | 'min' | 'grow' | 'lowestElement' | 'taggedElement';
type WidthCalculationMethod = 'bodyOffset' | 'bodyScroll' | 'documentElementOffset' | 'documentElementScroll' |
'max' | 'min' | 'scroll' | 'rightMostElement' | 'taggedElement';
// tslint:disable-next-line:interface-name
interface IFramePage {
/**
* Turn autoResizing of the iFrame on and off. Returns bool of current state.
*/
autoResize(resize?: boolean): boolean;
/**
* Remove the iFrame from the parent page.
*/
close(): void;
/**
* Returns the ID of the iFrame that the page is contained in.
*/
getId(): string;
/**
* Ask the containing page for its positioning coordinates.
*
* Your callback function will be recalled when the parent page is scrolled or resized.
*
* Pass false to disable the callback.
*/
getPageInfo(callback: ((data: PageInfo) => void) | false): void;
/**
* Scroll the parent page to the coordinates x and y
*/
scrollTo(
x: number,
y: number
): void;
/**
* Scroll the parent page to the coordinates x and y relative to the position of the iFrame.
*/
scrollToOffset(
x: number,
y: number
): void;
/**
* Send data to the containing page, message can be any data type that can be serialized into JSON. The `targetOrigin`
* option is used to restrict where the message is sent to; to stop an attacker mimicking your parent page.
* See the MDN documentation on postMessage for more details.
*/
sendMessage(
message: any,
targetOrigin?: string
): void;
/**
* Change the method use to workout the height of the iFrame.
*/
setHeightCalculationMethod(method: HeightCalculationMethod): void;
/**
* Change the method use to workout the width of the iFrame.
*/
setWidthCalculationMethod(method: WidthCalculationMethod): void;
/**
* Set default target origin.
*/
setTargetOrigin(targetOrigin: string): void;
/**
* Manually force iFrame to resize. To use passed arguments you need first to disable the `autoResize` option to
* prevent auto resizing and enable the `sizeWidth` option if you wish to set the width.
*/
size(
customHeight?: string,
customWidth?: string
): void;
}
interface PageInfo {
/**
* The height of the iframe in pixels
*/
iframeHeight: number;
/**
* The width of the iframe in pixels
*/
iframeWidth: number;
/**
* The height of the viewport in pixels
*/
clientHeight: number;
/**
* The width of the viewport in pixels
*/
clientWidth: number;
/**
* The number of pixels between the left edge of the containing page and the left edge of the iframe
*/
offsetLeft: number;
/**
* The number of pixels between the top edge of the containing page and the top edge of the iframe
*/
offsetTop: number;
/**
* The number of pixels between the left edge of the iframe and the left edge of the iframe viewport
*/
scrollLeft: number;
/**
* The number of pixels between the top edge of the iframe and the top edge of the iframe viewport
*/
scrollTop: number;
}
// tslint:disable-next-line:interface-name
interface IFrameResizedData {
iframe: IFrameComponent;
height: number;
width: number;
type: string;
}
// tslint:disable-next-line:interface-name
interface IFrameMessageData {
iframe: IFrameComponent;
message: any;
}
// tslint:disable-next-line:interface-name
interface IFrameScrollData {
x: number;
y: number;
}
}
// tslint:disable-next-line:interface-name
export interface IFrameComponent extends HTMLIFrameElement {
iFrameResizer: IFrameObject;
}
// tslint:disable-next-line:interface-name
export interface IFrameOptions {
/**
* When enabled changes to the Window size or the DOM will cause the iFrame to resize to the new content size.
* Disable if using size method with custom dimensions.
*/
autoResize?: boolean;
/**
* Override the body background style in the iFrame.
*/
bodyBackground?: string;
/**
* Override the default body margin style in the iFrame. A string can be any valid value for the
* CSS margin attribute, for example '8px 3em'. A number value is converted into px.
*/
bodyMargin?: number | string;
/**
* Override the default body padding style in the iFrame. A string can be any valid value for the
* CSS margin attribute, for example '8px 3em'. A number value is converted into px.
*/
bodyPadding?: number | string;
/**
* When set to true, only allow incoming messages from the domain listed in the src property of the iFrame tag.
* If your iFrame navigates between different domains, ports or protocols; then you will need to
* provide an array of URLs or disable this option.
*/
checkOrigin?: boolean | string[];
/**
* When enabled in page linking inside the iFrame and from the iFrame to the parent page will be enabled.
*/
inPageLinks?: boolean;
/**
* Height calculation method.
*/
heightCalculationMethod?: HeightCalculationMethod;
/**
* Set iFrame Id
*/
id?: string;
/**
* In browsers that don't support mutationObserver, such as IE10, the library falls back to using
* setInterval, to check for changes to the page size.
*/
interval?: number;
/**
* Setting the log option to true will make the scripts in both the host page and the iFrame output
* everything they do to the JavaScript console so you can see the communication between the two scripts.
*/
log?: boolean;
/**
* Set maximum height of iFrame.
*/
maxHeight?: number;
/**
* Set maximum width of iFrame.
*/
maxWidth?: number;
/**
* Set minimum height of iFrame.
*/
minHeight?: number;
/**
* Set minimum width of iFrame.
*/
minWidth?: number;
/**
* Listen for resize events from the parent page, or the iFrame. Select the 'child' value if the iFrame
* can be resized independently of the browser window. Selecting this value can cause issues with some
* height calculation methods on mobile devices.
*/
resizeFrom?: 'parent' | 'child';
/**
* Enable scroll bars in iFrame.
*/
scrolling?: boolean | 'auto';
/**
* Resize iFrame to content height.
*/
sizeHeight?: boolean;
/**
* Resize iFrame to content width.
*/
sizeWidth?: boolean;
/**
* Set the number of pixels the iFrame content size has to change by, before triggering a resize of the iFrame.
*/
tolerance?: number;
/**
* Width calculation method.
*/
widthCalculationMethod?: WidthCalculationMethod;
/**
* Called when iFrame is closed via parentIFrame.close() or iframe.iframeResizer.close() methods.
*/
closedCallback?(iframeId: string): void;
/**
* Initial setup callback function.
*/
initCallback?(iframe: IFrameComponent): void;
/**
* Receive message posted from iFrame with the parentIFrame.sendMessage() method.
*/
messageCallback?(data: IFrameMessageData): void;
/**
* Function called after iFrame resized. Passes in messageData object containing the iFrame, height, width
* and the type of event that triggered the iFrame to resize.
*/
resizedCallback?(data: IFrameResizedData): void;
/**
* Called before the page is repositioned after a request from the iFrame, due to either an in page link,
* or a direct request from either parentIFrame.scrollTo() or parentIFrame.scrollToOffset().
* If this callback function returns false, it will stop the library from repositioning the page, so that
* you can implement your own animated page scrolling instead.
*/
scrollCallback?(data: IFrameScrollData): boolean;
}
// tslint:disable-next-line:interface-name
export interface IFramePageOptions {
/**
* This option allows you to restrict the domain of the parent page,
* to prevent other sites mimicking your parent page.
*/
targetOrigin?: string;
/**
* Receive message posted from the parent page with the iframe.iFrameResizer.sendMessage() method.
*/
messageCallback?(message: any): void;
/**
* This function is called once iFrame-Resizer has been initialized after receiving a call from the parent page.
*/
readyCallback?(): void;
/**
* These option can be used to override the option set in the parent page
*/
heightCalculationMethod?: HeightCalculationMethod | (() => number);
/**
* These option can be used to override the option set in the parent page
*/
widthCalculationMethod?: WidthCalculationMethod | (() => number);
}
export type HeightCalculationMethod = 'bodyOffset' | 'bodyScroll' | 'documentElementOffset' | 'documentElementScroll' |
'max' | 'min' | 'grow' | 'lowestElement' | 'taggedElement';
export type WidthCalculationMethod = 'bodyOffset' | 'bodyScroll' | 'documentElementOffset' | 'documentElementScroll' |
'max' | 'min' | 'scroll' | 'rightMostElement' | 'taggedElement';
// tslint:disable-next-line:interface-name
export interface IFramePage {
/**
* Turn autoResizing of the iFrame on and off. Returns bool of current state.
*/
autoResize(resize?: boolean): boolean;
/**
* Remove the iFrame from the parent page.
*/
close(): void;
/**
* Returns the ID of the iFrame that the page is contained in.
*/
getId(): string;
/**
* Ask the containing page for its positioning coordinates.
*
* Your callback function will be recalled when the parent page is scrolled or resized.
*
* Pass false to disable the callback.
*/
getPageInfo(callback: ((data: PageInfo) => void) | false): void;
/**
* Scroll the parent page to the coordinates x and y
*/
scrollTo(x: number, y: number): void;
/**
* Scroll the parent page to the coordinates x and y relative to the position of the iFrame.
*/
scrollToOffset(x: number, y: number): void;
/**
* Send data to the containing page, message can be any data type that can be serialized into JSON. The `targetOrigin`
* option is used to restrict where the message is sent to; to stop an attacker mimicking your parent page.
* See the MDN documentation on postMessage for more details.
*/
sendMessage(message: any, targetOrigin?: string): void;
/**
* Change the method use to workout the height of the iFrame.
*/
setHeightCalculationMethod(method: HeightCalculationMethod): void;
/**
* Change the method use to workout the width of the iFrame.
*/
setWidthCalculationMethod(method: WidthCalculationMethod): void;
/**
* Set default target origin.
*/
setTargetOrigin(targetOrigin: string): void;
/**
* Manually force iFrame to resize. To use passed arguments you need first to disable the `autoResize` option to
* prevent auto resizing and enable the `sizeWidth` option if you wish to set the width.
*/
size(customHeight?: string, customWidth?: string): void;
}
export interface PageInfo {
/**
* The height of the iframe in pixels
*/
iframeHeight: number;
/**
* The width of the iframe in pixels
*/
iframeWidth: number;
/**
* The height of the viewport in pixels
*/
clientHeight: number;
/**
* The width of the viewport in pixels
*/
clientWidth: number;
/**
* The number of pixels between the left edge of the containing page and the left edge of the iframe
*/
offsetLeft: number;
/**
* The number of pixels between the top edge of the containing page and the top edge of the iframe
*/
offsetTop: number;
/**
* The number of pixels between the left edge of the iframe and the left edge of the iframe viewport
*/
scrollLeft: number;
/**
* The number of pixels between the top edge of the iframe and the top edge of the iframe viewport
*/
scrollTop: number;
}
// tslint:disable-next-line:interface-name
export interface IFrameResizedData {
iframe: IFrameComponent;
height: number;
width: number;
type: string;
}
// tslint:disable-next-line:interface-name
export interface IFrameMessageData {
iframe: IFrameComponent;
message: any;
}
// tslint:disable-next-line:interface-name
export interface IFrameScrollData {
x: number;
y: number;
}
export function iframeResizer(options: IFrameOptions, target: string | HTMLElement): IFrameComponent[];
declare function iframeResizer(options: iframeResizer.IFrameOptions, target: string | HTMLElement): iframeResizer.IFrameComponent[];
export = iframeResizer;
export as namespace iframeResizer;
+26
View File
@@ -0,0 +1,26 @@
// Type definitions for interpret 1.1
// Project: https://github.com/tkellen/node-interpret
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
export interface Hook {
(m: { extensions: string } | NodeModule): any;
install(m?: { extension: string; [key: string]: any }): void;
}
export type RegisterFn = (hook: Hook) => void;
export interface ExtensionDescriptor {
module: string;
register: RegisterFn;
}
export type Extension = string | ExtensionDescriptor | Array<string | ExtensionDescriptor>;
export interface Extensions {
[extension: string]: Extension | null;
}
export const extensions: Extensions;
export const jsVariants: Extensions;
+50
View File
@@ -0,0 +1,50 @@
import { extensions, jsVariants, Extensions } from 'interpret';
// $ExpectType Extensions
extensions;
// $ExpectType Extensions
jsVariants;
const myExts: Extensions = {
'.babel.js': [
{
module: 'babel-register',
register(hook) {
hook({ extensions: '.js' });
},
},
],
'.co': 'coco',
'.coffee': ['coffeescript/register', 'coffee-script/register', 'coffeescript', 'coffee-script'],
'.esm.js': {
module: 'esm',
register(hook) {
const esmLoader = hook(module);
require.extensions['.js'] = esmLoader('module')._extensions['.js'];
},
},
'.js': null,
'.jsx': [
{
module: 'node-jsx',
register(hook) {
hook.install({ extension: '.jsx', harmony: true });
},
},
],
'.toml': {
module: 'toml-require',
register(hook) {
hook.install();
},
},
'.ts': [
'typescript-require',
{
module: '@babel/register',
register(hook) {
hook({ extensions: '.ts' });
},
},
],
};
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"interpret-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+33
View File
@@ -0,0 +1,33 @@
// Type definitions for list-stream 1.0
// Project: https://github.com/rvagg/list-stream
// Definitions by: Christian Sporer <https://github.com/IanStorm>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.7
/// <reference types="node" />
import { Duplex, DuplexOptions } from "stream";
interface ListStreamMethod {
(callback?: (err: Error, data: any[]) => void): ListStream;
(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream;
}
interface ListStreamConstructor extends ListStreamMethod {
new(callback?: (err: Error, data: any[]) => void): ListStream;
new(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream;
obj: ListStreamMethod;
}
declare let ListStream: ListStreamConstructor;
interface ListStream extends Duplex {
append(chunk: any): void;
duplicate(): ListStream;
end(): void;
get(index: number): any;
length: number;
}
export = ListStream;
+2
View File
@@ -0,0 +1,2 @@
import "./test/import-tests";
import "./test/require-tests";
+54
View File
@@ -0,0 +1,54 @@
import ListStream from "list-stream";
let chunk: any = "chunk";
let listStream: ListStream;
let num = 1;
listStream = ListStream((err: Error, data: any[]) => {
if (err) { throw err; }
console.log(data.length);
for (const date of data) {
console.log(date);
}
});
listStream = ListStream({ objectMode: true }, (err: Error, data: any[]) => {
if (err) { throw err; }
console.log(data.length);
for (const date of data) {
console.log(date);
}
});
listStream = new ListStream((err: Error, data: any[]) => {
if (err) { throw err; }
console.log(data.length);
for (const date of data) {
console.log(date);
}
});
listStream = new ListStream({ objectMode: true }, (err: Error, data: any[]) => {
if (err) { throw err; }
console.log(data.length);
for (const date of data) {
console.log(date);
}
});
listStream = ListStream.obj((err: Error, data: any[]) => {
if (err) { throw err; }
console.log(data.length);
for (const date of data) {
console.log(date);
}
});
listStream = ListStream.obj();
listStream.write({ key: "value" });
listStream.append(chunk);
listStream = listStream.duplicate();
listStream.end();
chunk = listStream.get(num);
num = listStream.length;
+54
View File
@@ -0,0 +1,54 @@
import ListStream = require("list-stream");
let chunk: any = "chunk";
let listStream: ListStream;
let num = 1;
listStream = ListStream((err: Error, data: any[]) => {
if (err) { throw err; }
console.log(data.length);
for (const date of data) {
console.log(date);
}
});
listStream = ListStream({ objectMode: true }, (err: Error, data: any[]) => {
if (err) { throw err; }
console.log(data.length);
for (const date of data) {
console.log(date);
}
});
listStream = new ListStream((err: Error, data: any[]) => {
if (err) { throw err; }
console.log(data.length);
for (const date of data) {
console.log(date);
}
});
listStream = new ListStream({ objectMode: true }, (err: Error, data: any[]) => {
if (err) { throw err; }
console.log(data.length);
for (const date of data) {
console.log(date);
}
});
listStream = ListStream.obj((err: Error, data: any[]) => {
if (err) { throw err; }
console.log(data.length);
for (const date of data) {
console.log(date);
}
});
listStream = ListStream.obj();
listStream.write({ key: "value" });
listStream.append(chunk);
listStream = listStream.duplicate();
listStream.end();
chunk = listStream.get(num);
num = listStream.length;
+26
View File
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"test/import-tests.ts",
"test/require-tests.ts",
"index.d.ts",
"list-stream-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+1 -1
View File
@@ -1020,7 +1020,7 @@ declare module "../index" {
// isMatchWith
type isMatchWithCustomizer = (value: any, other: any, indexOrKey: PropertyName) => boolean;
type isMatchWithCustomizer = (value: any, other: any, indexOrKey: PropertyName, object: object, source: object) => boolean;
interface LoDashStatic {
/**
+1 -1
View File
@@ -4205,7 +4205,7 @@ fp.now(); // $ExpectType number
// _.isMatchWith
{
const testIsMatchCustiomizerFn = (value: any, other: any, indexOrKey: number|string|symbol) => true;
const testIsMatchCustiomizerFn = (value: any, other: any, indexOrKey: number|string|symbol, object: object, source: object) => true;
_.isMatchWith({}, {}, testIsMatchCustiomizerFn); // $ExpectType boolean
_({}).isMatchWith({}, testIsMatchCustiomizerFn); // $ExpectType boolean
+11 -1
View File
@@ -1,8 +1,9 @@
// Type definitions for Marked 0.4
// Type definitions for Marked 0.5
// Project: https://github.com/markedjs/marked
// Definitions by: William Orr <https://github.com/worr>
// BendingBender <https://github.com/BendingBender>
// CrossR <https://github.com/CrossR>
// Mike Wickett <https://github.com/mwickett>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export as namespace marked;
@@ -34,6 +35,15 @@ declare namespace marked {
*/
function lexer(src: string, options?: MarkedOptions): TokensList;
/**
* @param src String of markdown source to be compiled
* @param links Array of links
* @param options Hash of options
* @return String of compiled HTML
*/
function inlineLexer(src: string, links: string[], options?: MarkedOptions): string;
/**
* Compiles markdown to HTML.
*
+19 -9
View File
@@ -280,6 +280,16 @@ declare module "mongoose" {
collection?: string
): U;
/**
* Removes the model named `name` from this connection, if it exists. You can
* use this function to clean up any models you created in your tests to
* prevent OverwriteModelErrors.
*
* @param name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp.
* @returns this
*/
deleteModel(name: string | RegExp): Connection;
/** Returns an array of model names created on this connection. */
modelNames(): string[];
@@ -511,7 +521,7 @@ declare module "mongoose" {
/**
* section error/notFound.js
* https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.DocumentNotFoundError
*
*
* An instance of this error class will be returned when `save()` fails
* because the underlying
* document was not found. The constructor takes one parameter, the
@@ -524,7 +534,7 @@ declare module "mongoose" {
/**
* section error/cast.js
* https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.CastError
*
*
* An instance of this error class will be returned when mongoose failed to
* cast a value.
*/
@@ -544,7 +554,7 @@ declare module "mongoose" {
/**
* section error/validation.js
* https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ValidationError
*
*
* An instance of this error class will be returned when [validation](http://mongoosejs.com/docs/validation.html) failed.
*/
export class ValidationError extends Error {
@@ -565,7 +575,7 @@ declare module "mongoose" {
/**
* section error/validator.js
* https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ValidatorError
*
*
* A `ValidationError` has a hash of `errors` that contain individual `ValidatorError` instances
*/
export class ValidatorError extends Error {
@@ -585,7 +595,7 @@ declare module "mongoose" {
/**
* section error/version.js
* https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.VersionError
*
*
* An instance of this error class will be returned when you call `save()` after
* the document in the database was changed in a potentially unsafe way. See
* the [`versionKey` option](http://mongoosejs.com/docs/guide.html#versionKey) for more information.
@@ -600,7 +610,7 @@ declare module "mongoose" {
/**
* section error/parallelSave.js
* https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ParallelSaveError
*
*
* An instance of this error class will be returned when you call `save()` multiple
* times on the same document in parallel. See the [FAQ](http://mongoosejs.com/docs/faq.html) for more
* information.
@@ -612,7 +622,7 @@ declare module "mongoose" {
/**
* section error/overwriteModel.js
* https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.OverwriteModelError
*
*
* Thrown when a model with the given name was already registered on the connection.
* See [the FAQ about `OverwriteModelError`](http://mongoosejs.com/docs/faq.html#overwrite-model-error).
*/
@@ -623,7 +633,7 @@ declare module "mongoose" {
/**
* section error/missingSchema.js
* https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.MissingSchemaError
*
*
* Thrown when you try to access a model that has not been registered yet
*/
export class MissingSchemaError extends Error {
@@ -633,7 +643,7 @@ declare module "mongoose" {
/**
* section error/divergentArray.js
* https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.DivergentArrayError
*
*
* An instance of this error will be returned if you used an array projection
* and then modified the array in an unsafe way.
*/
+1
View File
@@ -145,6 +145,7 @@ conn1.close(function (err) {});
conn1.close(true, function (err) {});
conn1.collection('name').$format(999);
conn1.model('myModel', new mongoose.Schema({}), 'myCol').find();
conn1.deleteModel('myModel');
conn1.models.myModel.findOne().exec();
interface IStatics {
staticMethod1: (a: number) => string;
+10
View File
@@ -329,6 +329,16 @@ declare module "mongoose" {
collection?: string
): U;
/**
* Removes the model named `name` from this connection, if it exists. You can
* use this function to clean up any models you created in your tests to
* prevent OverwriteModelErrors.
*
* @param name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp.
* @returns this
*/
deleteModel(name: string | RegExp): Connection;
/** Returns an array of model names created on this connection. */
modelNames(): string[];
+1
View File
@@ -133,6 +133,7 @@ conn1.openSet('mongodb://localhost/test', 'db', {
conn1.close().catch(function (err) {});
conn1.collection('name').$format(999);
conn1.model('myModel', new mongoose.Schema({}), 'myCol').find();
conn1.deleteModel('myModel');
interface IStatics {
staticMethod1: (a: number) => string;
}
+22
View File
@@ -0,0 +1,22 @@
declare namespace devices {
interface Viewport {
width: number;
height: number;
deviceScaleFactor: number;
isMobile: boolean;
hasTouch: boolean;
isLandscape: boolean;
}
interface Device {
name: string;
userAgent: string;
viewport: Viewport;
}
}
declare const devices: {
[key: string]: devices.Device;
};
export = devices;
+107 -116
View File
@@ -1,4 +1,4 @@
// Type definitions for puppeteer 1.10
// Type definitions for puppeteer 1.11
// Project: https://github.com/GoogleChrome/puppeteer#readme
// Definitions by: Marvin Hagemeister <https://github.com/marvinhagemeister>
// Christopher Deutsch <https://github.com/cdeutsch>
@@ -398,6 +398,8 @@ export interface Cookie {
path: string;
/** The cookie Unix expiration time in seconds. */
expires: number;
/** The cookie size */
size: number;
/** The cookie http only flag. */
httpOnly: boolean;
/** The session cookie flag. */
@@ -414,7 +416,6 @@ export interface DeleteCookie {
url?: string;
domain?: string;
path?: string;
secure?: boolean;
}
export interface SetCookie {
@@ -512,6 +513,9 @@ export interface DirectNavigationOptions extends NavigationOptions {
referer?: string;
}
/** Accepts values labeled with units. If number, treat as pixels. */
export type LayoutDimension = string | number;
export type PDFFormat =
| "Letter"
| "Legal"
@@ -579,22 +583,21 @@ export interface PDFOptions {
* @default 'Letter'
*/
format?: PDFFormat;
/** Paper width, accepts values labeled with units. */
width?: string;
/** Paper height, accepts values labeled with units. */
height?: string;
/** Paper margins, defaults to none. */
/** Paper width. */
width?: LayoutDimension;
/** Paper height. */
height?: LayoutDimension;
/** Paper margins, defaults to none. */
margin?: {
/** Top margin, accepts values labeled with units. */
top?: string;
/** Right margin, accepts values labeled with units. */
right?: string;
/** Bottom margin, accepts values labeled with units. */
bottom?: string;
/** Left margin, accepts values labeled with units. */
left?: string;
/** Top margin. */
top?: LayoutDimension;
/** Right margin. */
right?: LayoutDimension;
/** Bottom margin. */
bottom?: LayoutDimension;
/** Left margin. */
left?: LayoutDimension;
};
/**
* Give any CSS @page size declared in the page priority over what is declared in width and
* height or format options.
@@ -1177,8 +1180,9 @@ export interface FrameBase extends Evalable {
/**
* Sets the page content.
* @param html HTML markup to assign to the page.
* @param options The navigation parameters.
*/
setContent(html: string): Promise<void>;
setContent(html: string, options?: NavigationOptions): Promise<void>;
/**
* This method fetches an element with `selector`, scrolls it into view if needed,
@@ -1395,11 +1399,11 @@ export interface AXNode {
/**
* Whether the checkbox is checked, or "mixed".
*/
checked: boolean | string;
checked: boolean | "mixed";
/**
* Whether the toggle button is checked, or "mixed".
*/
pressed: boolean | string;
pressed: boolean | "mixed";
/**
* The level of a heading.
*/
@@ -1620,9 +1624,9 @@ export interface Page extends EventEmitter, FrameBase {
/**
* Determines whether cache is enabled on the page.
* @param enabled Whether or not to enable cache on the page.
* @param [enabled=true] Whether or not to enable cache on the page.
*/
setCacheEnabled(enabled: boolean): Promise<void>;
setCacheEnabled(enabled?: boolean): Promise<void>;
/**
* Sets the cookies on the page.
@@ -1933,27 +1937,7 @@ export interface Target {
url(): string;
}
export interface LaunchOptions extends Timeoutable {
/**
* Whether to open chrome in appMode.
* @default false
*/
appMode?: boolean;
/**
* Whether to ignore HTTPS errors during navigation.
* @default false
*/
ignoreHTTPSErrors?: boolean;
/**
* Do not use `puppeteer.defaultArgs()` for launching Chromium.
* @default false
*/
ignoreDefaultArgs?: boolean | string[];
/**
* Whether to run Chromium in headless mode.
* @default true
*/
headless?: boolean;
export interface LaunchOptions extends ChromeArgOptions, BrowserOptions, Timeoutable {
/**
* Path to a Chromium executable to run instead of bundled Chromium. If
* executablePath is a relative path, then it is resolved relative to current
@@ -1961,10 +1945,73 @@ export interface LaunchOptions extends Timeoutable {
*/
executablePath?: string;
/**
* Slows down Puppeteer operations by the specified amount of milliseconds.
* Useful so that you can see what is going on.
* Do not use `puppeteer.defaultArgs()` for launching Chromium.
* @default false
*/
slowMo?: number;
ignoreDefaultArgs?: boolean | string[];
/**
* Close chrome process on Ctrl-C.
* @default true
*/
handleSIGINT?: boolean;
/**
* Close chrome process on SIGTERM.
* @default true
*/
handleSIGTERM?: boolean;
/**
* Close chrome process on SIGHUP.
* @default true
*/
handleSIGHUP?: boolean;
/**
* Whether to pipe browser process stdout and stderr into process.stdout and
* process.stderr.
* @default false
*/
dumpio?: boolean;
/**
* Specify environment variables that will be visible to Chromium.
* @default `process.env`.
*/
env?: {
[key: string]: string | boolean | number;
};
/**
* Connects to the browser over a pipe instead of a WebSocket.
* @default false
*/
pipe?: boolean;
}
export interface ChromeArgOptions {
/**
* Whether to run browser in headless mode.
* @default true unless the devtools option is true.
*/
headless?: boolean;
/**
* Additional arguments to pass to the browser instance.
* The list of Chromium flags can be found here.
*/
args?: string[];
/**
* Path to a User Data Directory.
*/
userDataDir?: string;
/**
* Whether to auto-open a DevTools panel for each tab.
* If this option is true, the headless option will be set false.
*/
devtools?: boolean;
}
export interface BrowserOptions {
/**
* Whether to ignore HTTPS errors during navigation.
* @default false
*/
ignoreHTTPSErrors?: boolean;
/**
* Sets a consistent viewport for each page. Defaults to an 800x600 viewport. null disables the default viewport.
*/
@@ -1988,7 +2035,6 @@ export interface LaunchOptions extends Timeoutable {
*/
isMobile?: boolean;
/**
*
* Specifies if viewport supports touch events.
* @default false
*/
@@ -1998,83 +2044,28 @@ export interface LaunchOptions extends Timeoutable {
* @default false
*/
isLandscape?: boolean;
};
} | null;
/**
* Additional arguments to pass to the Chromium instance. List of Chromium
* flags can be found here.
* Slows down Puppeteer operations by the specified amount of milliseconds.
* Useful so that you can see what is going on.
*/
args?: string[];
/**
* Close chrome process on Ctrl-C.
* @default true
*/
handleSIGINT?: boolean;
/**
* Close chrome process on SIGTERM.
* @default true
*/
handleSIGTERM?: boolean;
/**
* Close chrome process on SIGHUP.
* @default true
*/
handleSIGHUP?: boolean;
/**
* Whether to pipe browser process stdout and stderr into process.stdout and
* process.stderr.
* @default false
*/
dumpio?: boolean;
/** Path to a User Data Directory. */
userDataDir?: string;
/**
* Specify environment variables that will be visible to Chromium.
* @default `process.env`.
*/
env?: {
[key: string]: string | boolean | number;
};
/**
* Whether to auto-open DevTools panel for each tab. If this option is true, the headless option will be set false.
*/
devtools?: boolean;
/**
* Connects to the browser over a pipe instead of a WebSocket.
* @default false
*/
pipe?: boolean;
slowMo?: number;
}
export interface DefaultArgsOptions {
/**
* Whether to run browser in headless mode.
* @default true unless the devtools option is true.
*/
headless?: boolean;
/**
* Additional arguments to pass to the browser instance.
* The list of Chromium flags can be found here.
*/
args?: string[];
/**
* Path to a User Data Directory.
*/
userDataDir?: string;
/**
* Whether to auto-open a DevTools panel for each tab.
* If this option is true, the headless option will be set false.
*/
devtools?: boolean;
}
export interface ConnectOptions {
export interface ConnectOptions extends BrowserOptions {
/** A browser websocket endpoint to connect to. */
browserWSEndpoint?: string;
/**
* Whether to ignore HTTPS errors during navigation.
* @default false
* **Experimental** Specify a custom transport object for Puppeteer to use.
*/
ignoreHTTPSErrors?: boolean;
transport?: ConnectionTransport;
}
export interface ConnectionTransport {
send(message: string): void;
close(): void;
onmessage?(message: string): void;
onclose?(): void;
}
export interface CDPSession extends EventEmitter {
@@ -2119,7 +2110,7 @@ export interface CoverageEntry {
/** Attaches Puppeteer to an existing Chromium instance */
export function connect(options?: ConnectOptions): Promise<Browser>;
/** The default flags that Chromium will be launched with */
export function defaultArgs(options?: DefaultArgsOptions): string[];
export function defaultArgs(options?: ChromeArgOptions): string[];
/** Path where Puppeteer expects to find bundled Chromium */
export function executablePath(): string;
/** The method launches a browser instance with given arguments. The browser will be closed when the parent node.js process is closed. */
+9
View File
@@ -1,5 +1,6 @@
import * as puppeteer from "puppeteer";
import { TimeoutError } from "puppeteer/Errors";
import * as Devices from "puppeteer/DeviceDescriptors";
// Accessibility
@@ -118,6 +119,7 @@ puppeteer.launch().then(async browser => {
});
await page.emulateMedia("screen");
await page.emulate(Devices['test']);
await page.pdf({ path: "page.pdf" });
await page.setRequestInterception(true);
@@ -200,6 +202,13 @@ puppeteer.launch().then(async browser => {
browser.close();
})();
// Launching with default viewport disabled
(async () => {
await puppeteer.launch({
defaultViewport: null
});
})();
// Test v0.12 features
(async () => {
const browser = await puppeteer.launch({
+1
View File
@@ -21,6 +21,7 @@
},
"files": [
"Errors.d.ts",
"DeviceDescriptors.d.ts",
"index.d.ts",
"puppeteer-tests.ts"
]
+15 -15
View File
@@ -216,19 +216,19 @@ export class DateLocalizer {
format(value: FormatInput, format: string, culture: Culture): string;
}
export interface BigCalendarProps<T extends Event = Event> extends React.Props<BigCalendar<T>> {
export interface BigCalendarProps<TEvent extends Event = Event, TResource extends object = object> extends React.Props<BigCalendar<TEvent, TResource>> {
localizer: DateLocalizer;
date?: stringOrDate;
now?: Date;
view?: View;
events?: T[];
onNavigate?: (newDate: Date, action: Navigate) => void;
events?: TEvent[];
onNavigate?: (newDate: Date, view: View, action: Navigate) => void;
onView?: (view: View) => void;
onDrillDown?: (date: Date, view: View) => void;
onSelectSlot?: (slotInfo: { start: stringOrDate, end: stringOrDate, slots: Date[] | string[], action: 'select' | 'click' | 'doubleClick' }) => void;
onDoubleClickEvent?: (event: T, e: React.SyntheticEvent<HTMLElement>) => void;
onSelectEvent?: (event: T, e: React.SyntheticEvent<HTMLElement>) => void;
onDoubleClickEvent?: (event: TEvent, e: React.SyntheticEvent<HTMLElement>) => void;
onSelectEvent?: (event: TEvent, e: React.SyntheticEvent<HTMLElement>) => void;
onSelecting?: (range: { start: stringOrDate, end: stringOrDate }) => boolean | undefined | null;
selected?: any;
views?: Views;
@@ -243,7 +243,7 @@ export interface BigCalendarProps<T extends Event = Event> extends React.Props<B
step?: number;
timeslots?: number;
rtl?: boolean;
eventPropGetter?: EventPropGetter<T>;
eventPropGetter?: EventPropGetter<TEvent>;
slotPropGetter?: SlotPropGetter;
dayPropGetter?: DayPropGetter;
showMultiDayTimes?: boolean;
@@ -254,14 +254,14 @@ export interface BigCalendarProps<T extends Event = Event> extends React.Props<B
formats?: Formats;
components?: Components;
messages?: Messages;
titleAccessor?: keyof T | ((event: T) => string);
allDayAccessor?: keyof T | ((event: T) => boolean);
startAccessor?: keyof T | ((event: T) => Date);
endAccessor?: keyof T | ((event: T) => Date);
resourceAccessor?: keyof T | ((event: T) => any);
resources?: any[];
resourceIdAccessor?: keyof T | ((event: T) => any);
resourceTitleAccessor?: keyof T | ((event: T) => string);
titleAccessor?: keyof TEvent | ((event: TEvent) => string);
allDayAccessor?: keyof TEvent | ((event: TEvent) => boolean);
startAccessor?: keyof TEvent | ((event: TEvent) => Date);
endAccessor?: keyof TEvent | ((event: TEvent) => Date);
resourceAccessor?: keyof TEvent | ((event: TEvent) => any);
resources?: TResource[];
resourceIdAccessor?: keyof TResource | ((resource: TResource) => any);
resourceTitleAccessor?: keyof TResource | ((resource: TResource) => string);
defaultView?: View;
defaultDate?: Date;
className?: string;
@@ -278,7 +278,7 @@ export interface MoveOptions {
today: Date;
}
export default class BigCalendar<T extends Event = Event> extends React.Component<BigCalendarProps<T>> {
export default class BigCalendar<TEvent extends Event = Event, TResource extends object = object> extends React.Component<BigCalendarProps<TEvent, TResource>> {
components: {
dateCellWrapper: React.ComponentType,
dayWrapper: React.ComponentType,
@@ -17,13 +17,25 @@ class CalendarEvent {
start: Date;
end: Date;
desc: string;
resourceId?: string;
constructor(_title: string, _start: Date, _end: Date, _allDay?: boolean, _desc?: string) {
constructor(_title: string, _start: Date, _end: Date, _allDay?: boolean, _desc?: string, _resourceId?: string) {
this.title = _title;
this.allDay = _allDay || false;
this.start = _start;
this.end = _end;
this.desc = _desc || '';
this.resourceId = _resourceId;
}
}
class CalendarResource {
title: string;
id: string;
constructor(id: string, title: string) {
this.id = id;
this.title = title;
}
}
@@ -49,66 +61,70 @@ class CalendarEvent {
}
{
class MyCalendar extends BigCalendar<CalendarEvent, CalendarResource> {}
// Full API Example Test - based on API Documentation
// http://intljusticemission.github.io/react-big-calendar/examples/index.html#api
class FullAPIExample extends React.Component<BigCalendarProps<CalendarEvent>> {
class FullAPIExample extends React.Component<BigCalendarProps<CalendarEvent, CalendarResource>> {
render() {
return (
<BigCalendar
{...this.props}
date={new Date()}
view={'day'}
events={getEvents()}
onNavigate={(newDate: Date, action: Navigate) => { }}
onView={(view: View) => { }}
onSelectSlot={(slotInfo) => {
const start = slotInfo.start;
const end = slotInfo.end;
const slots = slotInfo.slots;
}}
onSelectEvent={(event) => { }}
onSelecting={(slotInfo) => {
const start = slotInfo.start;
const end = slotInfo.end;
return true;
}}
views={['day']}
toolbar={true}
popup={true}
popupOffset={20}
selectable={true}
step={20}
rtl={true}
eventPropGetter={(event, start, end, isSelected) => ({ className: 'some-class' })}
titleAccessor={'title'}
allDayAccessor={(event: any) => !!event.allDay}
startAccessor={'start'}
endAccessor={(event: any) => event.end || event.start}
min={new Date()}
max={new Date()}
scrollToTime={new Date()}
formats={{
dateFormat: "h a",
agendaDateFormat: (date: Date, culture?: string, localizer?: object) => "some-format",
dayRangeHeaderFormat: (range: DateRange, culture?: string, localizer?: object) => "some-format"
}}
messages={{}}
timeslots={24}
defaultView={'month'}
className={'my-calendar'}
elementProps={{ id: 'myCalendar' }}
components={{
event: Event,
agenda: {
event: EventAgenda
},
toolbar: Toolbar,
eventWrapper: EventWrapper,
}}
dayPropGetter={customDayPropGetter}
slotPropGetter={customSlotPropGetter}
defaultDate={new Date()}
/>
<MyCalendar {...this.props}
date={new Date()}
view={'day'}
events={getEvents()}
onNavigate={(newDate: Date, view: View, action: Navigate) => { }}
onView={(view: View) => { }}
onSelectSlot={(slotInfo) => {
const start = slotInfo.start;
const end = slotInfo.end;
const slots = slotInfo.slots;
}}
onSelectEvent={(event) => { }}
onSelecting={(slotInfo) => {
const start = slotInfo.start;
const end = slotInfo.end;
return true;
}}
views={['day']}
toolbar={true}
popup={true}
popupOffset={20}
selectable={true}
step={20}
rtl={true}
eventPropGetter={(event, start, end, isSelected) => ({ className: 'some-class' })}
titleAccessor={'title'}
allDayAccessor={(event: CalendarEvent) => !!event.allDay}
startAccessor={'start'}
endAccessor={(event: CalendarEvent) => event.end || event.start}
min={new Date()}
max={new Date()}
scrollToTime={new Date()}
formats={{
dateFormat: "h a",
agendaDateFormat: (date: Date, culture?: string, localizer?: object) => "some-format",
dayRangeHeaderFormat: (range: DateRange, culture?: string, localizer?: object) => "some-format"
}}
messages={{}}
timeslots={24}
defaultView={'month'}
className={'my-calendar'}
elementProps={{ id: 'myCalendar' }}
components={{
event: Event,
agenda: {
event: EventAgenda
},
toolbar: Toolbar,
eventWrapper: EventWrapper,
}}
dayPropGetter={customDayPropGetter}
slotPropGetter={customSlotPropGetter}
defaultDate={new Date()}
resources={getResources()}
resourceAccessor={event => event.resourceId}
resourceIdAccessor={resource => resource.id}
resourceTitleAccessor={resource => resource.title} />
);
}
}
@@ -132,10 +148,19 @@ function getEvents(): CalendarEvent[] {
new CalendarEvent('Happy Hour', new Date(2015, 3, 12, 17, 0, 0, 0), new Date(2015, 3, 12, 17, 30, 0, 0), undefined, 'Most important meal of the day'),
new CalendarEvent('Dinner', new Date(2015, 3, 12, 20, 0, 0, 0), new Date(2015, 3, 12, 21, 0, 0, 0)),
new CalendarEvent('Birthday Party', new Date(2015, 3, 13, 7, 0, 0), new Date(2015, 3, 13, 10, 30, 0)),
new CalendarEvent('Alice\'s break', new Date(2015, 3, 14, 20, 0, 0, 0), new Date(2015, 3, 14, 21, 0, 0, 0), undefined, undefined, "alice"),
new CalendarEvent('Bob\'s break', new Date(2015, 3, 15, 7, 0, 0), new Date(2015, 3, 15, 10, 30, 0), undefined, undefined, "bob"),
];
return events;
}
function getResources(): CalendarResource[] {
return [
new CalendarResource('alice', 'Alice'),
new CalendarResource('bob', 'Bob')
];
}
class EventAgenda extends React.Component<any, any> {
render() {
// const { label } = this.props;
+12 -5
View File
@@ -1,18 +1,25 @@
// Type definitions for react-flatpickr 3.2
// Type definitions for react-flatpickr 3.6
// Project: https://github.com/coderhaoxin/react-flatpickr
// Definitions by: begincalendar <https://github.com/begincalendar>
// snaveevans <https://github.com/snaveevans>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
import { Component } from 'react';
import flatpickr from 'flatpickr';
import { Component } from "react";
import flatpickr from "flatpickr";
export interface DateTimePickerProps {
defaultValue?: string;
options?: flatpickr.Options.Options;
onChange?: flatpickr.Options.Hook;
value?: string;
className?: string;
onOpen?: flatpickr.Options.Hook;
onClose?: flatpickr.Options.Hook;
onMonthChange?: flatpickr.Options.Hook;
onYearChange?: flatpickr.Options.Hook;
onReady?: flatpickr.Options.Hook;
onValueUpdate?: flatpickr.Options.Hook;
onDayCreate?: flatpickr.Options.Hook;
value?: string | Date | number | ReadonlyArray<string | Date | number>;
}
export default class DatePicker extends Component<DateTimePickerProps> {}
+33 -13
View File
@@ -1,22 +1,42 @@
import flatpickr from 'flatpickr';
import * as React from 'react';
import DatePicker from 'react-flatpickr';
import flatpickr from "flatpickr";
import * as React from "react";
import DatePicker from "react-flatpickr";
const noParamsElement = <DatePicker/>;
const noParamsElement = <DatePicker />;
const defaultValueElement = <DatePicker defaultValue={ 'Default value' }/>;
const defaultValueElement = <DatePicker defaultValue={"Default value"} />;
const options = {
dateFormat: 'YYYY-MM-DD'
dateFormat: "YYYY-MM-DD"
};
const optionsElement = <DatePicker options={ options }/>;
const optionsElement = <DatePicker options={options} />;
const onChange = (
selectedDates: Date[], dateStr: string, instance: flatpickr.Instance,
const hook = (
selectedDates: Date[],
dateStr: string,
instance: flatpickr.Instance,
elem: HTMLElement
) => null;
const onChangeElement = <DatePicker onChange={ onChange }/>;
const onChangeElement = <DatePicker onChange={hook} />;
const onOpenElement = <DatePicker onOpen={hook} />;
const onCloseElement = <DatePicker onClose={hook} />;
const onMonthChangeElement = <DatePicker onMonthChange={hook} />;
const onYearChangeElement = <DatePicker onYearChange={hook} />;
const onReadyElement = <DatePicker onReady={hook} />;
const onValueUpdateElement = <DatePicker onValueUpdate={hook} />;
const onDayCreateElement = <DatePicker onDayCreate={hook} />;
const valueElement = <DatePicker value={ 'Value' }/>;
const classNameElement = <DatePicker className={ 'Class name' }/>;
const valueStringElement = <DatePicker value={"2018-11-29T18:35:50.115Z"} />;
const valueDateElement = <DatePicker value={new Date()} />;
const valueNumberElement = <DatePicker value={1543516477474} />;
const valueStringArrayElement = (
<DatePicker
value={["2018-11-29T18:35:50.115Z", "2018-11-29T19:35:50.115Z"]}
/>
);
const valueDateArrayElement = (
<DatePicker value={[new Date(), new Date(1543516477474)]} />
);
const valueNumberArrayElement = (
<DatePicker value={[1543516477474, 1544549477474]} />
);
+39 -31
View File
@@ -46,6 +46,11 @@ export interface FullTree {
export interface NodeData extends TreeNode, TreePath, TreeIndex { }
export interface FlatDataItem extends TreeNode, TreePath {
lowerSiblingsCounts: number[];
parentNode: TreeItem;
}
export interface SearchData extends NodeData {
searchQuery: any;
}
@@ -61,6 +66,11 @@ export interface OnVisibilityToggleData extends FullTree, TreeNode {
expanded: boolean;
}
export interface OnDragStateChangedData {
isDragging: boolean;
draggedNode: TreeItem;
}
interface PreviousAndNextLocation {
prevTreeIndex: number;
prevPath: NumberOrStringArray;
@@ -96,7 +106,7 @@ export interface NodeRendererProps {
toggleChildrenVisibility?(data: NodeData): void;
buttons?: JSX.Element[];
className?: string;
style?: { [index: string]: any };
style?: React.CSSProperties;
title?: (data: NodeData) => JSX.Element | JSX.Element;
subtitle?: (data: NodeData) => JSX.Element | JSX.Element;
icons?: JSX.Element[];
@@ -109,12 +119,12 @@ export interface NodeRendererProps {
connectDragPreview: ConnectDragPreview;
connectDragSource: ConnectDragSource;
parentNode?: { [index: string]: any };
parentNode?: TreeItem;
startDrag: any;
endDrag: any;
isDragging: boolean;
didDrop: boolean;
draggedNode?: { [index: string]: any };
draggedNode?: TreeItem;
isOver: boolean;
canDrop?: boolean;
}
@@ -124,7 +134,7 @@ export type PlaceholderRenderer = React.ComponentClass<PlaceholderRendererProps>
export interface PlaceholderRendererProps {
isOver: boolean;
canDrop: boolean;
draggedNode: { [index: string]: any };
draggedNode: TreeItem;
}
type NumberOrStringArray = Array<string | number>;
@@ -147,54 +157,52 @@ export interface TreeRendererProps {
connectDropTarget: ConnectDropTarget;
isOver: boolean;
canDrop?: boolean;
draggedNode?: { [index: string]: any };
draggedNode?: TreeItem;
// used in dndManager
getPrevRow: any; // @TODO what is this method?
getPrevRow: () => FlatDataItem | null;
node: TreeItem;
path: NumberOrStringArray;
}
export interface ThemeProps {
style?: { [index: string]: any };
innerStyle?: { [index: string]: any };
interface ThemeTreeProps {
style?: React.CSSProperties;
innerStyle?: React.CSSProperties;
reactVirtualizedListProps?: Partial<ListProps>;
scaffoldBlockPxWidth?: number;
slideRegionSize?: number;
rowHeight?: ((info: Index) => number) | number;
treeNodeRenderer?: TreeRenderer;
nodeContentRenderer?: NodeRenderer;
placeholderRenderer?: PlaceholderRenderer;
}
export interface ReactSortableTreeProps {
export interface ThemeProps extends ThemeTreeProps {
treeNodeRenderer?: TreeRenderer;
}
export interface ReactSortableTreeProps extends ThemeTreeProps {
treeData: TreeItem[];
onChange(treeData: TreeItem[]): void;
style?: { [index: string]: any };
className?: string;
innerStyle?: { [index: string]: any };
getNodeKey?(data: TreeNode & TreeIndex): string | number;
generateNodeProps?(data: ExtendedNodeData): { [index: string]: any };
onMoveNode?(data: NodeData & FullTree & OnMovePreviousAndNextLocation): void;
onVisibilityToggle?(data: OnVisibilityToggleData): void;
onDragStateChanged?(data: OnDragStateChangedData): void;
maxDepth?: number;
rowDirection?: 'ltr' | 'rtl';
canDrag?: ((data: ExtendedNodeData) => boolean) | boolean;
canDrop?(data: OnDragPreviousAndNextLocation & NodeData): boolean;
canNodeHaveChildren?(node: TreeItem): boolean;
theme?: ThemeProps;
searchMethod?(data: SearchData): boolean;
searchQuery?: string | any;
searchFocusOffset?: number;
searchFinishCallback?(matches: NodeData[]): void;
generateNodeProps?(data: ExtendedNodeData): { [index: string]: any };
getNodeKey?(data: TreeNode & TreeIndex): string | number;
onMoveNode?(data: NodeData & FullTree & OnMovePreviousAndNextLocation): void;
onVisibilityToggle?(data: OnVisibilityToggleData): void;
canDrag?: ((data: ExtendedNodeData) => boolean) | boolean;
canDrop?(data: OnDragPreviousAndNextLocation & NodeData): boolean;
reactVirtualizedListProps?: Partial<ListProps>;
rowHeight?: ((info: Index) => number) | number;
slideRegionSize?: number;
scaffoldBlockPxWidth?: number;
isVirtualized?: boolean;
nodeContentRenderer?: NodeRenderer;
dndType?: string;
placeholderRenderer?: PlaceholderRenderer;
theme?: ThemeProps;
shouldCopyOnOutsideDrop?: boolean | ((data: ShouldCopyData) => boolean);
onlyExpandSearchedNodes?: boolean;
searchFinishCallback?(matches: NodeData[]): void;
dndType?: string;
shouldCopyOnOutsideDrop?: boolean | ((data: ShouldCopyData) => boolean);
className?: string;
isVirtualized?: boolean;
}
declare const SortableTree: React.ComponentClass<ReactSortableTreeProps>;
+15 -3
View File
@@ -1,4 +1,4 @@
import { FullTree, TreePath, TreeItem, TreeIndex, SearchData, NodeData, TreeNode } from '..';
import { FullTree, TreePath, TreeItem, TreeIndex, SearchData, NodeData, TreeNode, FlatDataItem } from '..';
export type GetNodeKeyFunction = (data: TreeIndex & TreeNode) => string | number;
export type WalkAndMapFunctionParameters = FullTree & {getNodeKey: GetNodeKeyFunction, callback: Function, ignoreCollapsed?: boolean};
@@ -13,6 +13,11 @@ export function getVisibleNodeInfoAtIndex(
}): TreeNode & TreePath & {lowerSiblingsCounts: number[]} | null;
export function walk(data: WalkAndMapFunctionParameters): void;
export function map(data: WalkAndMapFunctionParameters): TreeItem[];
export function toggleExpandedForAll(
data: FullTree & {
expanded?: boolean,
},
): TreeItem[];
export function changeNodeAtPath(
data: FullTree & TreePath & {
newNode: Function | any,
@@ -26,12 +31,18 @@ export function removeNodeAtPath(
ignoreCollapsed?: boolean,
},
): TreeItem[];
export function removeNode(
data: FullTree & TreePath & {
getNodeKey: GetNodeKeyFunction,
ignoreCollapsed?: boolean,
},
): (FullTree & TreeNode & TreeIndex) | null;
export function getNodeAtPath(
data: FullTree & TreePath & {
getNodeKey: GetNodeKeyFunction,
ignoreCollapsed?: boolean,
},
): TreeNode & TreeIndex | null;
): (TreeNode & TreeIndex) | null;
export function addNodeUnderParent(
data: FullTree & {
newNode: TreeItem,
@@ -39,6 +50,7 @@ export function addNodeUnderParent(
getNodeKey: GetNodeKeyFunction,
ignoreCollapsed?: boolean,
expandParent?: boolean,
addAsFirstChild?: boolean,
},
): FullTree & TreeIndex;
export function insertNode(
@@ -56,7 +68,7 @@ export function getFlatDataFromTree(
getNodeKey: GetNodeKeyFunction,
ignoreCollapsed?: boolean,
},
): Array<TreeNode & TreePath & {lowerSiblingsCounts: number[], parentNode: TreeItem}>;
): FlatDataItem[];
export function getTreeFromFlatData(
data: {
flatData: FlattenedData,
+5
View File
@@ -11,6 +11,7 @@
// Paul Melnikow <https://github.com/paulmelnikow>
// Harry Cruse <https://github.com/crusectrl>
// Andrew Palugniok <https://github.com/apalugniok>
// Robert Stigsson <https://github.com/RobertStigsson>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
@@ -45,6 +46,7 @@ export type StackOffsetType = 'sign' | 'expand' | 'none' | 'wiggle' | 'silhouett
export type LineType =
'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' |
'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | CurveFactory;
export type IfOverflowType = 'hidden' | 'visible' | 'discard' | 'extendDomain';
export type AxisInterval = number | 'preserveStart' | 'preserveEnd' | 'preserveStartEnd';
export type PickedCSSStyleDeclarationKeys =
@@ -634,6 +636,7 @@ export interface ReferenceAreaProps extends Partial<PresentationAttributes> {
yAxis?: object;
isFront?: boolean;
alwaysShow?: boolean;
ifOverflow?: IfOverflowType;
x1?: number | string;
x2?: number | string;
y1?: number | string;
@@ -657,6 +660,7 @@ export interface ReferenceDotProps extends EventAttributes, Partial<Presentation
yAxis?: ReferenceDotAxisConfiguration;
isFront?: boolean;
alwaysShow?: boolean;
ifOverflow?: IfOverflowType;
x?: number | string;
y?: number | string;
xAxisId?: string | number;
@@ -677,6 +681,7 @@ export interface ReferenceLineProps extends Partial<PresentationAttributes<numbe
yAxis?: object;
isFront?: boolean;
alwaysShow?: boolean;
ifOverflow?: IfOverflowType;
x?: number | string;
y?: number | string;
label?: string | number | ContentRenderer<any> | React.ReactElement<any>;
+16
View File
@@ -0,0 +1,16 @@
// Type definitions for ripemd160 2.0
// Project: https://github.com/crypto-browserify/ripemd160#readme
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import { Hash } from 'crypto';
export = RIPEMD160;
declare const RIPEMD160: RIPEMD160Static;
interface RIPEMD160Static {
new (): Hash;
}
+7
View File
@@ -0,0 +1,7 @@
import RIPEMD160 = require('ripemd160');
new RIPEMD160().update('42').digest('hex');
const ripemd160stream = new RIPEMD160();
ripemd160stream.end('42');
(ripemd160stream.read() as Buffer).toString('hex');
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"ripemd160-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+31
View File
@@ -0,0 +1,31 @@
// Type definitions for saslmechanisms 0.1
// Project: https://github.com/jaredhanson/js-sasl
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = Factory;
declare class Factory {
static Factory: typeof Factory;
use(name: string, mechanism: Factory.MechanismStatic): this;
use(mechanism: Factory.MechanismStatic): this;
create(mechanisms: string[]): Factory.Mechanism | null;
}
declare namespace Factory {
interface MechanismStatic {
new (): Mechanism;
prototype: {
[key: string]: any;
name: string;
};
}
interface Mechanism {
name: string;
response(cred: { [key: string]: any }): string;
challenge(chal: string): void;
}
}
@@ -0,0 +1,22 @@
import Fct = require('saslmechanisms');
import { Factory, MechanismStatic, Mechanism } from 'saslmechanisms';
const Mech: MechanismStatic = null as any;
const factory = new Fct();
new Factory();
new Factory.Factory();
// $ExpectType Factory
factory.use(Mech);
factory.use('Mech', Mech);
const mech: Mechanism | null = factory.create(['Mech']);
if (mech) {
// $ExpectType string
mech.name;
// $ExpectType string
mech.response({ foo: 'bar' });
// $ExpectType void
mech.challenge('challenge');
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"saslmechanisms-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+19
View File
@@ -0,0 +1,19 @@
// Type definitions for sc-auth 5.0
// Project: https://github.com/SocketCluster/sc-auth
// Definitions by: Daniel Rose <https://github.com/DanielRose>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
import { VerifyOptions, VerifyCallback, Secret, SignCallback, SignOptions } from "jsonwebtoken";
export interface SCAuthEngine {
verifyToken(signedToken: string, key: string | Buffer, options?: VerifyOptions, callback?: VerifyCallback): void;
signToken(token: string | object | Buffer, key: Secret, options?: SignOptions, callback?: SignCallback): void;
}
export class AuthEngine implements SCAuthEngine {
constructor();
verifyToken(signedToken: string, key: string | Buffer, options?: VerifyOptions, callback?: VerifyCallback): void;
signToken(token: string | object | Buffer, key: Secret, options?: SignOptions, callback?: SignCallback): void;
}
+102
View File
@@ -0,0 +1,102 @@
/**
* This mostly delegates to jwt, so using its tests as base
*/
import scAuth = require("sc-auth");
import fs = require("fs");
let signedToken = "";
let cert: Buffer;
interface TestObject {
foo: string;
}
const testObject = { foo: "bar" };
const authEngine = new scAuth.AuthEngine();
// sign with default (HMAC SHA256)
authEngine.signToken(testObject, "shhhhh");
// sign with default (HMAC SHA256) and single audience
authEngine.signToken(testObject, "shhhhh", { audience: "theAudience" });
// sign with default (HMAC SHA256) and multiple audiences
authEngine.signToken(testObject, "shhhhh", {
audience: ["audience1", "audience2"]
});
// sign with default (HMAC SHA256) and a keyid
authEngine.signToken(testObject, "shhhhh", { keyid: "theKeyId" });
// sign with RSA SHA256
cert = fs.readFileSync("private.key"); // get private key
authEngine.signToken(testObject, cert, { algorithm: "RS256" });
// sign with encrypted RSA SHA256 private key (only PEM encoding is supported)
const privKey: Buffer = fs.readFileSync("encrypted_private.key"); // get private key
const secret = { key: privKey.toString(), passphrase: "keypwd" };
authEngine.signToken(testObject, secret, { algorithm: "RS256" }); // the algorithm option is mandatory in this case
// sign asynchronously
authEngine.signToken(testObject, cert, { algorithm: "RS256" }, (err, token) => {
signedToken = token;
});
// verify a token symmetric
authEngine.verifyToken(signedToken, "shhhhh", {}, (err, decoded) => {
const result = decoded as TestObject;
console.log(result.foo); // bar
});
// use external time for verifying
authEngine.verifyToken(signedToken, "shhhhh", { clockTimestamp: 1 }, (err, decoded) => {
const result = decoded as TestObject;
console.log(result.foo); // bar
});
// invalid token
authEngine.verifyToken(signedToken, "wrong-secret", {}, (err, decoded) => {
console.log(err);
// decoded undefined
});
// verify a token asymmetric
cert = fs.readFileSync("public.pem"); // get public key
authEngine.verifyToken(signedToken, cert, {}, (err, decoded) => {
const result = decoded as TestObject;
console.log(result.foo); // bar
});
// verify audience
cert = fs.readFileSync("public.pem"); // get public key
authEngine.verifyToken(signedToken, cert, { audience: "urn:foo" }, (err, decoded) => {
// if audience mismatch, err == invalid audience
console.log(err);
});
// verify issuer
cert = fs.readFileSync("public.pem"); // get public key
authEngine.verifyToken(signedToken, cert, { audience: "urn:foo", issuer: "urn:issuer" }, (err, decoded) => {
// if issuer mismatch, err == invalid issuer
console.log(err);
});
// verify algorithm
cert = fs.readFileSync("public.pem"); // get public key
authEngine.verifyToken(signedToken, cert, { algorithms: ["RS256"] }, (err, decoded) => {
// if algorithm mismatch, err == invalid algorithm
console.log(err);
});
// verify without expiration check
cert = fs.readFileSync("public.pem"); // get public key
authEngine.verifyToken(signedToken, cert, { ignoreExpiration: true }, (err, decoded) => {
// if ignoreExpration == false and token is expired, err == expired token
console.log(err);
});
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"sc-auth-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+10
View File
@@ -0,0 +1,10 @@
import { EventEmitter } from "events";
import { SCBrokerClient } from "sc-broker";
import { mapperFunction } from ".";
export class ClientCluster extends EventEmitter {
constructor(clients: SCBrokerClient[]);
setMapper(mapper: mapperFunction): void;
getMapper(): mapperFunction;
}
+160
View File
@@ -0,0 +1,160 @@
// Type definitions for sc-broker-cluster 6.1
// Project: https://github.com/SocketCluster/sc-broker-cluster
// Definitions by: Daniel Rose <https://github.com/DanielRose>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
import { SCServerSocket, SCServer } from "socketcluster-server";
import { BrokerStartInfo, BrokerExitInfo } from "socketcluster";
import { SpliceOptions, QueryOptions } from "sc-broker";
import { SCChannel } from "sc-channel";
import { EventEmitter } from "events";
import { AsyncResultArrayCallback } from "async";
import { KeyChain, FlexiMap } from "fleximap";
import { Keys } from "expirymanager";
import { ClientCluster } from "./clientcluster";
export class AbstractDataClient extends EventEmitter {
constructor(dataClient: ClientCluster);
set(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void;
set(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void;
expire(keys: Keys, seconds: number, callback?: (err?: Error) => void): void;
unexpire(keys: Keys, callback?: (err?: Error) => void): void;
add(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void;
add(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void;
get(keyChain: KeyChain, callback: (err: Error | null, value: any) => void): void;
getRange(keyChain: KeyChain, fromIndex: number, toIndex: number, callback: (err: Error | null, value: any) => void): void;
getRange(keyChain: KeyChain, fromIndex: number, callback: (err: Error | null, value: any) => void): void;
getAll(callback: (err: Error | null, value: any[] | object) => void): void;
count(keyChain: KeyChain, callback: (err: Error | null, value: number) => void): void;
remove(keyChain: KeyChain, getValue?: boolean, callback?: (err?: Error) => void): void;
remove(keyChain: KeyChain, callback?: (err?: Error) => void): void;
removeRange(keyChain: KeyChain, fromIndex: number, toIndex?: number, getValue?: boolean, callback?: (err?: Error) => void): void;
removeRange(keyChain: KeyChain, fromIndex: number, toIndex?: number, callback?: (err?: Error) => void): void;
removeRange(keyChain: KeyChain, fromIndex: number, callback?: (err?: Error) => void): void;
removeAll(callback?: (err: Error) => void): void;
splice(keyChain: KeyChain, options?: SpliceOptions, callback?: (err?: Error) => void): void;
splice(keyChain: KeyChain, callback?: (err?: Error) => void): void;
pop(keyChain: KeyChain, callback: (err: Error | null, data: any) => void): void;
hasKey(keyChain: KeyChain, callback: (err: Error | null, data: boolean) => void): void;
extractKeys(keyChain: KeyChain): string[];
extractValues(keyChain: KeyChain): any[];
exec(query: (datamap: FlexiMap) => void, options?: QueryOptions, callback?: (err: Error | null, data: any) => void): void;
exec(query: (datamap: FlexiMap) => void, callback: (err: Error | null, data: any) => void): void;
}
export type handlerFunction = (data: any) => void;
export type mapperFunction = (keyChain: KeyChain, method: string, clientIds: number[]) => number | number[];
/**
* The exchange object is a top-level SCBrokerClient which lets you publish events and manipulate data within your brokers - It represents a cluster of 1 or more brokers.
*/
export class SCExchange extends AbstractDataClient {
constructor(privateClientCluster: ClientCluster, publicClientCluster: ClientCluster, ioClusterClient: Client);
send(data: any, mapIndex: number | string | string[] | null, callback?: (err?: Error) => void): void;
publish(channelName: string, data: any, callback: (err?: Error) => void): void;
subscribe(channelName: string): SCChannel;
unsubscribe(channelName: string): void;
channel(channelName: string): SCChannel;
destroyChannel(channelName: string): void;
subscriptions(includePending?: boolean): string[];
isSubscribed(channelName: string, includePending?: boolean): boolean;
watch(channelName: string, handler: handlerFunction): void;
unwatch(channelName: string, handler?: handlerFunction): void;
watchers(channelName: string): handlerFunction[];
setMapper(mapper: mapperFunction): void;
getMapper(): mapperFunction;
map(keyChain: KeyChain, method: string): { type: string; targets: Client[] };
destroy(): void;
}
export interface SCBrokerClusterServerOptions {
brokers: string[];
debug?: boolean;
inspect?: boolean;
instanceId?: string;
secretKey?: string;
expiryAccuracy?: number;
downgradeToUser: number | string;
appBrokerControllerPath?: string;
processTermTimeout?: number;
ipcAckTimeout?: number;
brokerOptions?: SCServer.SCServerOptions;
}
export class Server extends EventEmitter {
constructor(options: SCBrokerClusterServerOptions);
on(event: "brokerStart", listener: (brokerInfo: BrokerStartInfo) => void): this;
on(event: "brokerExit", listener: (brokerInfo: BrokerExitInfo) => void): this;
on(event: "brokerMessage", listener: (brokerId: string, data: any, callback: (err: Error | null, data: any) => void) => void): this;
on(event: "ready", listener: () => void): this;
on(event: "error", listener: (err?: Error) => void): this;
sendToBroker(brokerId: string, data: any, callback: (err: Error | null, data: any) => void): void;
killBrokers(): void;
destroy(): void;
}
export interface SCBrokerClusterClientOptions {
brokers: string[];
secretKey?: string;
pubSubBatchDuration?: number;
connectRetryErrorThreshold: number;
}
export interface MessagePacket {
channel: string;
data: any;
}
export class Client extends EventEmitter {
constructor(options: SCBrokerClusterClientOptions);
exchange(): SCExchange;
options: SCBrokerClusterClientOptions;
on(event: "error", listener: (err?: Error) => void): this;
on(event: "warning", listener: (warning?: Error) => void): this;
on(event: "ready", listener: () => void): this;
on(event: "message", listener: (packet: MessagePacket) => void): this;
destroy(callback: AsyncResultArrayCallback<SCExchange>): void;
subscribe(channel: string, callback: (err?: Error) => void): void;
unsubscribe(channel: string, callback: () => void): void;
unsubscribeAll(callback: () => void): void;
isSubscribed(channel: string, includePending: boolean): boolean;
subscribeSocket(socket: SCServerSocket, channel: string, callback?: (err?: Error) => void): void;
unsubscribeSocket(socket: SCServerSocket, channel: string, callback?: () => void): void;
setSCServer(scServer: SCServer): void;
}
@@ -0,0 +1,29 @@
import { Client } from "sc-broker-cluster";
import { SCServer, SCServerSocket } from "socketcluster-server";
import WebSocket = require("ws");
const client = new Client({
brokers: [],
secretKey: "secretKey",
pubSubBatchDuration: 100,
connectRetryErrorThreshold: 5
});
client.on("error", err => {});
client.on("warning", err => {});
const exchange = client.exchange();
const scServer = new SCServer();
client.setSCServer(scServer);
client.once("ready", () => {});
const wsSocket = new WebSocket("address");
const socket = new SCServerSocket("id", scServer, wsSocket);
client.subscribeSocket(socket, "channelName", err => {});
client.unsubscribeSocket(socket, "channelName");
const data: any = {};
exchange.publish("channelName", data, err => {});
+3
View File
@@ -0,0 +1,3 @@
import SCBroker = require("sc-broker/scbroker");
export = SCBroker;
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"clientcluster.d.ts",
"scbroker.d.ts",
"sc-broker-cluster-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+165
View File
@@ -0,0 +1,165 @@
// Type definitions for sc-broker 5.1
// Project: https://github.com/SocketCluster/sc-broker
// Definitions by: Daniel Rose <https://github.com/DanielRose>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
import { SCServer } from "socketcluster-server";
import { WorkerExitInfo } from "socketcluster";
import { EventEmitter } from "events";
import { KeyChain, FlexiMap } from "fleximap";
import { Keys, Key } from "expirymanager";
export interface SCBrokerServerOptions {
id?: string;
instanceId?: string;
debug?: boolean;
inspect?: boolean;
socketPath?: string;
port?: number;
expiryAccuracy?: number;
downgradeToUser: number | string;
brokerControllerPath?: string;
processTermTimeout?: number;
ipcAckTimeout?: number;
secretKey?: string;
brokerOptions?: SCServer.SCServerOptions;
}
export interface SCBrokerServer extends EventEmitter {
options: SCBrokerServerOptions;
socketPath?: string;
port?: number;
ipcAckTimeout: number;
on(event: "error", listener: (err?: Error) => void): this;
on(event: "brokerMessage", listener: (brokerId: string, data: any, callback: (err: Error | null, data: any) => void) => void): this;
on(event: "ready", listener: (data: any) => void): this;
on(event: "exit", listener: (data: WorkerExitInfo) => void): this;
sendToBroker(data: any, callback?: (err: Error | null, data: any, brokerId: string) => void): void;
}
export function createServer(options?: SCBrokerServerOptions): SCBrokerServer;
export interface AutoReconnectOptions {
initialDelay?: number;
randomness?: number;
multiplier?: number;
maxDelay?: number;
}
export interface SCBrokerClientOptions {
secretKey?: string;
timeout?: number;
socketPath?: string;
port?: number;
host?: string;
autoReconnect?: boolean;
autoReconnectOptions?: AutoReconnectOptions;
connectRetryErrorThreshold?: number;
pubSubBatchDuration?: number;
}
export interface QueryOptions {
baseKey?: KeyChain;
noAck?: boolean;
data?: any;
}
export interface SpliceOptions {
index?: number;
count?: number;
items?: any[];
getValue?: boolean;
noAck?: boolean;
}
export interface SCBrokerClient extends EventEmitter {
readonly CONNECTED: "connected";
readonly CONNECTING: "connecting";
readonly DISCONNECTED: "disconnected";
socketPath?: string;
port?: number;
host?: string;
autoReconnect: boolean;
autoReconnectOptions?: AutoReconnectOptions;
connectRetryErrorThreshold: number;
state: "connected" | "connecting" | "disconnected";
connectAttempts: number;
pendingReconnect: boolean;
pendingReconnectTimeout: number | null;
on(event: "error", listener: (err?: Error) => void): this;
on(event: "warning", listener: (warning?: Error) => void): this;
on(event: "ready", listener: (data: any) => void): this;
on(event: "message", listener: (channel: string, data: any) => void): this;
on(event: "subscribeFail", listener: (err: Error | null, channel: string) => void): this;
on(event: "subscribe", listener: (channel: string) => void): this;
on(event: "unsubscribe", listener: () => void): this;
isConnected(): boolean;
subscribe(channel: string, ackCallback: (err?: Error) => void, force?: boolean): void;
unsubscribe(channel: string, ackCallback: (err?: Error) => void): void;
subscriptions(includePending?: boolean): string[];
isSubscribed(channel: string, includePending?: boolean): boolean;
publish(channel: string, data: any, callback: (err?: Error) => void): void;
send(data: any, callback: (err?: Error) => void): void;
set(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void;
set(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void;
expire(keys: Keys, seconds: number, callback?: (err?: Error) => void): void;
unexpire(keys: Keys, callback?: (err?: Error) => void): void;
getExpiry(key: Key, callback?: (err?: Error) => void): number;
add(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void;
add(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void;
concat(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void;
concat(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void;
get(keyChain: KeyChain, callback: (err: Error | null, value: any) => void): void;
getRange(keyChain: KeyChain, fromIndex: number, toIndex: number, callback: (err: Error | null, value: any) => void): void;
getRange(keyChain: KeyChain, fromIndex: number, callback: (err: Error | null, value: any) => void): void;
getAll(callback: (err: Error | null, value: any[] | object) => void): void;
count(keyChain: KeyChain, callback: (err: Error | null, value: number) => void): void;
exec(query: (datamap: FlexiMap) => void, options?: QueryOptions, callback?: (err: Error | null, data: any) => void): void;
exec(query: (datamap: FlexiMap) => void, callback: (err: Error | null, data: any) => void): void;
query(query: (datamap: FlexiMap) => void, data?: any, callback?: (err: Error | null, data: any) => void): void;
query(query: (datamap: FlexiMap) => void, callback: (err: Error | null, data: any) => void): void;
remove(keyChain: KeyChain, getValue?: boolean, callback?: (err?: Error) => void): void;
remove(keyChain: KeyChain, callback?: (err?: Error) => void): void;
removeRange(keyChain: KeyChain, fromIndex: number, toIndex?: number, getValue?: boolean, callback?: (err?: Error) => void): void;
removeRange(keyChain: KeyChain, fromIndex: number, toIndex?: number, callback?: (err?: Error) => void): void;
removeRange(keyChain: KeyChain, fromIndex: number, callback?: (err?: Error) => void): void;
removeAll(callback?: (err: Error) => void): void;
splice(keyChain: KeyChain, options?: SpliceOptions, callback?: (err?: Error) => void): void;
splice(keyChain: KeyChain, callback?: (err?: Error) => void): void;
pop(keyChain: KeyChain, callback: (err: Error | null, data: any) => void): void;
hasKey(keyChain: KeyChain, callback: (err: Error | null, data: boolean) => void): void;
extractKeys(keyChain: KeyChain): string[];
extractValues(keyChain: KeyChain): any[];
end(callback: (err?: Error) => void): void;
}
export function createClient(options?: SCBrokerClientOptions): SCBrokerClient;
+58
View File
@@ -0,0 +1,58 @@
import { SCServer, SCServerSocket } from "socketcluster-server";
import SCBroker = require("sc-broker/scbroker");
import { FlexiMap } from "fleximap";
import { ExpiryManager } from "expirymanager";
////////////////////////////////////////////////////
/// SCBroker tests
////////////////////////////////////////////////////
const options: SCServer.SCServerOptions = { port: 80 };
let scBroker = new SCBroker();
scBroker = new SCBroker(options);
scBroker.options = { environment: "prod" };
const id: number = scBroker.id;
const instanceId: number = scBroker.instanceId;
const dataMap: FlexiMap = scBroker.dataMap;
const dataExpirer: ExpiryManager = scBroker.dataExpirer;
const subscriptions = scBroker.subscriptions;
const socket: SCServerSocket = subscriptions[1]["test"];
scBroker.on("subscribe", channel => {
const subscribeChannel: string = channel;
});
scBroker.on("unsubscribe", channel => {
const unsubscribeChannel: string = channel;
});
scBroker.on("publish", (channel, data) => {
const publishChannel: string = channel;
const publishData: any = data;
});
scBroker.on("masterMessage", (data, masterMessageResponse) => {
const masterMessageData: any = data;
masterMessageResponse(null, "test");
masterMessageResponse(new Error(), null);
});
scBroker.publish("testChannel", 123);
scBroker.exec(dataMap => {
dataMap.set(["main", "message"], "Message");
return dataMap.get(["main"]);
});
scBroker.sendToMaster("data");
scBroker.sendToMaster(123, (err, response) => {
if (!err) {
const answer = response;
}
});
class MyBroker extends SCBroker {
run() {
this.on("subscribe", channel => {});
}
}
+32
View File
@@ -0,0 +1,32 @@
import { EventEmitter } from "events";
import { SCServer, SCServerSocket } from "socketcluster-server";
import { FlexiMap, KeyChain } from "fleximap";
import { ExpiryManager } from "expirymanager";
export = SCBroker;
interface Subscriptions {
[socketId: number]: {
[channel: string]: SCServerSocket;
};
}
declare class SCBroker extends EventEmitter {
id: number;
options: SCServer.SCServerOptions;
instanceId: number;
dataMap: FlexiMap;
dataExpirer: ExpiryManager;
subscriptions: Subscriptions;
constructor(options?: SCServer.SCServerOptions);
on(event: "subscribe" | "unsubscribe", listener: (channel: string) => void): this;
on(event: "publish", listener: (channel: string, data: any) => void): this;
on(event: "masterMessage", listener: (data: any, respond: (err: Error | null, responseData: any) => void) => void): this;
publish(channel: string, message: any): void;
run(): void;
exec(query: (dataMap: FlexiMap, dataExpirer: ExpiryManager, subscriptions: Subscriptions) => any, baseKey?: KeyChain): any;
sendToMaster(data: any, callback?: (err: Error | null, responseData: any) => void): void;
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"scbroker.d.ts",
"sc-broker-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+45
View File
@@ -0,0 +1,45 @@
// Type definitions for sc-channel 1.2
// Project: https://github.com/SocketCluster/sc-channel
// Definitions by: Daniel Rose <https://github.com/DanielRose>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
import Emitter = require("component-emitter");
import { SCExchange, handlerFunction } from "sc-broker-cluster";
export interface SCChannelOptions {
waitForAuth?: boolean;
batch?: boolean;
data?: any;
}
export class SCChannel extends Emitter {
readonly PENDING: "pending";
readonly SUBSCRIBED: "subscribed";
readonly UNSUBSCRIBED: "unsubscribed";
name: string;
state: ChannelState;
waitForAuth: boolean;
batch: boolean;
data: any;
constructor(name: string, client: SCExchange, options?: SCChannelOptions);
setOptions(options?: SCChannelOptions): void;
getState(): "pending" | "subscribed" | "unsubscribed";
subscribe(options?: any): void;
unsubscribe(): void;
isSubscribed(includePending?: boolean): boolean;
publish(data: any, callback?: (err?: Error) => void): void;
watch(handler: handlerFunction): void;
unwatch(handler?: handlerFunction): void;
watchers(): handlerFunction[];
destroy(): void;
}
export type ChannelState = "pending" | "subscribed" | "unsubscribed";
+33
View File
@@ -0,0 +1,33 @@
import { SCChannel, SCChannelOptions } from "sc-channel";
import { handlerFunction, Client, SCBrokerClusterClientOptions } from "sc-broker-cluster";
const clientOptions: SCBrokerClusterClientOptions = { brokers: [], connectRetryErrorThreshold: 0 };
const client = new Client(clientOptions);
let channel = new SCChannel("channelName", client.exchange());
const channelOptions: SCChannelOptions = {};
channel = new SCChannel("channelName", client.exchange(), channelOptions);
channel.state = channel.PENDING;
channel.state = channel.SUBSCRIBED;
channel.state = channel.UNSUBSCRIBED;
const channelName: string = channel.name;
const handler: handlerFunction = () => { };
channel.watch(handler);
channel.unwatch();
channel.subscribe();
channel.subscribe(channelOptions);
channel.unsubscribe();
const data: any = channel.data;
channel.emit("subscribe", channelName);
channel.emit("unsubscribe", channelName);
channel.setOptions(channelOptions);
channel.publish(data);
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"sc-channel-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+26
View File
@@ -0,0 +1,26 @@
// Type definitions for sha.js 2.4
// Project: https://github.com/crypto-browserify/sha.js
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import { Hash } from 'crypto';
export = SHA;
declare function SHA(algorithm: string): Hash;
declare namespace SHA {
type Algorithm = 'sha' | 'sha1' | 'sha224' | 'sha256' | 'sha384' | 'sha512';
interface HashStatic {
new (): Hash;
}
const sha: HashStatic;
const sha1: HashStatic;
const sha224: HashStatic;
const sha256: HashStatic;
const sha384: HashStatic;
const sha512: HashStatic;
}
+15
View File
@@ -0,0 +1,15 @@
import shajs = require('sha.js');
shajs('sha256')
.update('42')
.digest('hex');
new shajs.sha().update('42').digest('hex');
new shajs.sha1().update('42').digest('hex');
new shajs.sha224().update('42').digest('hex');
new shajs.sha256().update('42').digest('hex');
new shajs.sha384().update('42').digest('hex');
new shajs.sha512().update('42').digest('hex');
const sha256stream = shajs('sha256');
sha256stream.end('42');
(sha256stream.read() as Buffer).toString('hex');
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"sha.js-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+23
View File
@@ -0,0 +1,23 @@
// Type definitions for socketcluster-client 13.0
// Project: https://github.com/SocketCluster/socketcluster-client
// Definitions by: Daniel Rose <https://github.com/DanielRose>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
import { SCAuthEngine } from "sc-auth";
import { SCServer } from "socketcluster-server";
export import SCClientSocket = require("./lib/scclientsocket");
export function create(options?: SCClientSocket.ClientOptions): SCClientSocket;
/** @deprecated */
export function connect(options?: SCClientSocket.ClientOptions): SCClientSocket;
export function destroy(socket: SCClientSocket): void;
export const clients: {
[id: string]: SCClientSocket;
};
export const version: string;
+251
View File
@@ -0,0 +1,251 @@
import Emitter = require("component-emitter");
import { SCServer } from "socketcluster-server";
import { SCAuthEngine } from "sc-auth";
import { SCChannel, SCChannelOptions, ChannelState } from "sc-channel";
import WebSocket = require("ws");
declare class SCClientSocket extends Emitter {
constructor(opts: SCClientSocket.ClientOptions);
id: string;
channels: {
[channelName: string]: SCChannel;
};
CONNECTING: "connecting";
OPEN: "open";
CLOSED: "closed";
state: SCClientSocket.States;
getState(): SCClientSocket.States;
AUTHENTICATED: "authenticated";
UNAUTHENTICATED: "unauthenticated";
authState: SCClientSocket.AuthStates;
PENDING: "pending";
pendingReconnect: boolean;
pendingReconnectTimeout: number;
getBytesReceived(): number;
deauthenticate(callback?: (err: Error) => void): void;
connect(): void;
open(): void;
disconnect(code?: number, data?: string | object): void;
reconnect(code?: number, data?: string | object): void;
destroy(code?: number, data?: string | object): void;
decodeBase64(encodedString: string): string;
encodeBase64(decodedString: string): string;
getAuthToken(): object | null;
authToken: object | null;
getSignedAuthToken(): string | null;
signedAuthToken: string | null;
// Perform client-initiated authentication by providing an encrypted token string.
authenticate(signedAuthToken: string, callback?: (err: Error, authStatus: SCClientSocket.AuthStatus) => void): void;
decode(message: any): any;
encode(object: any): any;
send(data: any): void;
emit(event: string, data: any, callback?: (err: Error, responseData: any) => void): void;
publish(channelName: string, data: any, callback?: (err: Error, ackData: any) => void): void;
subscribe(channelName: string, options?: SCChannelOptions): SCChannel;
unsubscribe(channelName: string): void;
channel(channelName: string, options?: SCChannelOptions): SCChannel;
destroyChannel(channelName: string): void;
subscriptions(includePending?: boolean): string[];
isSubscribed(channelName: string, includePending?: boolean): boolean;
processPendingSubscriptions(): void;
watch(channelName: string, handler: SCClientSocket.WatcherFunction): void;
unwatch(channelName: string, handler?: SCClientSocket.WatcherFunction): void;
watchers(channelName: string): SCClientSocket.WatcherFunction[];
on(event: "connecting", listener: () => void): this;
on(event: "connect", listener: (status: SCClientSocket.ConnectStatus, processSubscriptions: () => void) => void): this;
on(event: "connectAbort" | "disconnect" | "close", listener: (code: number, data: string | object) => void): this;
on(event: "kickOut", listener: (message: string, channelName: string) => void): this;
on(event: "authenticate", listener: (signedAuthToken: string | null) => void): this;
on(event: "deauthenticate", listener: (oldSignedToken: string | null) => void): this;
on(event: "authStateChange", listener: (stateChangeData: SCClientSocket.AuthStateChangeData) => void): this;
on(event: "removeAuthToken", listener: (oldToken: object | null) => void): this;
on(event: "subscribe" | "subscribeRequest", listener: (channelName: string, subscriptionOptions: SCChannelOptions) => void): this;
on(event: "subscribeStateChange", listener: (stateChangeData: SCClientSocket.SubscribeStateChangeData) => void): this;
on(event: "subscribeFail", listener: (err: Error, channelName: string, subscriptionOptions: SCChannelOptions) => void): this;
on(event: "unsubscribe", listener: (channelName: string) => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: "raw", listener: (data: any) => void): this;
on(event: "message", listener: (message: WebSocket.Data) => void): this;
// Implements Emitter interface
// tslint:disable:ban-types
// tslint:disable:adjacent-overload-signatures
on(event: string, listener: Function): this;
once(event: string, listener: Function): this;
off(event?: string, listener?: Function): this;
emit(event: string, ...args: any[]): boolean;
listeners(event: string): Function[];
hasListeners(event: string): boolean;
// tslint:enable:adjacent-overload-signatures
// tslint:enable:ban-types
}
export = SCClientSocket;
declare namespace SCClientSocket {
interface ClientOptions {
host?: string;
// Defaults to the current host (read from the URL).
hostname?: string;
// Defaults to false.
secure?: boolean;
// Defaults to 80 if !secure otherwise defaults to 443.
port?: number;
// The URL which SC uses to make the initial handshake for the WebSocket. Defaults to '/socketcluster/'.
path?: string;
// A map of key-value pairs which will be used as query parameters for the initial HTTP handshake which will initiate the WebSocket connection.
query?: string | { [key: string]: string };
// (milliseconds) - This is the timeout for getting a response to a SCSocket emit event (when a callback is provided).
ackTimeout?: number;
// (milliseconds)
connectTimeout?: number;
// Whether or not to automatically connect the socket as soon as it is created. Default is true.
autoConnect?: boolean;
// Whether or not to automatically reconnect the socket when it loses the connection.
autoReconnect?: boolean;
// Valid properties are: initialDelay (milliseconds), randomness (milliseconds), multiplier (decimal; default is 1.5) and maxDelay (milliseconds).
autoReconnectOptions?: AutoReconnectOptions;
// Whether or not a client automatically disconnects on page unload. If enabled, the client will disconnect when a user navigates away from the page.
// This can happen when a user closes the tab/window, clicks a link to leave the page, or types a new URL into the address bar. Defaults to true.
disconnectOnUnload?: boolean;
// Turn on/off per-message deflate compression. If this is true, you need to make sure that this property is also set to true on the server-side.
// Note that this option is only relevant when running the client from Node.js. Most modern browsers will automatically use perMessageDeflate so
// you only need to turn it on from the server-side.
perMessageDeflate?: boolean;
// Defaults to true; multiplexing allows you to reuse a socket instead of creating a second socket to the same address.
multiplex?: boolean;
// Defaults to null (0 milliseconds); this property affects channel subscription batching; it determines the period in milliseconds for batching
// multiple subscription requests together. It only affects channels that have the batch option set to true. A value of null or 0 means that all
// subscribe or unsubscribe requests which were made within the same call stack will be batched together. This property was introduced on the
// client-side in SC version 8 (both the client and server versions need to be >= 8.0.0). Note that there is also a separate property with the
// same name which can be configured on the server.
pubSubBatchDuration?: number;
// Whether or not to add a timestamp to the WebSocket handshake request.
timestampRequests?: boolean;
// The query parameter name to use to hold the timestamp.
timestampParam?: string;
// A custom engine to use for storing and loading JWT auth tokens on the client side.
authEngine?: SCAuthEngine | null;
// The name of the JWT auth token (provided to the authEngine - By default this is the localStorage variable name); defaults to 'socketCluster.authToken'.
authTokenName?: string;
// The type to use to represent binary on the client. Defaults to 'arraybuffer'.
binaryType?: string;
// Set this to false during debugging - Otherwise client connection will fail when using self-signed certificates.
rejectUnauthorized?: boolean;
// If you set this to true, any data/objects/arrays that you pass to the client socket will be cloned before being sent/queued up. If the socket
// is disconnected and you emit an event, it will be added to a queue which will be processed upon reconnection. The cloneData option is false
// by default; this means that if you emit/publish an object and that object changes somewhere else in your code before the queue is processed,
// then the changed version of that object will be sent out to the server.
cloneData?: boolean;
// This is true by default. If you set this to false, then the socket will not automatically try to subscribe to pending subscriptions on
// connect - Instead, you will have to manually invoke the processSubscriptions callback from inside the 'connect' event handler on the client side.
// See SCSocket Client API. This gives you more fine-grained control with regards to when pending subscriptions are processed after the socket
// connection is established (or re-established).
autoSubscribeOnConnect?: boolean;
// Lets you set a custom codec engine. This allows you to specify how data gets encoded before being sent over the wire and how it gets decoded
// once it reaches the other side. The codecEngine must be an object which exposes an encode(object) and a decode(encodedData) function.
// The encode function can return any data type - Commonly a string or a Buffer/ArrayBuffer. The decode function needs to return a JavaScript
// object which adheres to the SC protocol. The idea of using a custom codec is that it allows you to compress SC packets in any format you like
// (optimized for any use case) - By decoding these packets back into their original protocol form, SC will be able process them appropriately.
// Note that if you provide a codecEngine when creating a client socket see 'codecEngine', you will need to make sure that the server uses the
// same codec by passing the same engine to `worker.scServer.setCodecEngine(codecEngine)` when your SC worker initializes on the server side
// (see 'setCodecEngine' method here). The default codec engine used by SC is here.
codecEngine?: SCServer.SCCodecEngine | null;
// A prefix to add to the channel names.
channelPrefix?: string | null;
subscriptionRetryOptions?: object | null;
}
interface AutoReconnectOptions {
initialDelay?: number;
randomness?: number;
multiplier?: number;
maxDelay?: number;
}
interface AuthStatus {
isAuthenticated: AuthStates;
authError: Error;
}
interface AuthStateChangeData {
oldState: AuthStates;
newState: AuthStates;
}
interface ConnectStatus {
id: string;
pingTimeout: number;
isAuthenticated: boolean;
authToken?: object;
authError?: Error;
}
interface SubscribeStateChangeData {
channel: string;
oldState: ChannelState;
newState: ChannelState;
subscriptionOptions: SCChannelOptions;
}
type WatcherFunction = (data: any) => void;
type AuthStates = "authenticated" | "unauthenticated";
type States = "connecting" | "open" | "closed";
}
@@ -0,0 +1,75 @@
// Adapted from README
import { create, destroy } from "socketcluster-client";
import { ClientOptions } from "socketcluster-client/lib/scclientsocket";
const secureClientOptions: ClientOptions = {
hostname: "securedomain.com",
secure: true,
port: 443,
rejectUnauthorized: false
};
let socket = create(secureClientOptions);
socket.on("connect", () => {
console.log("CONNECTED");
});
// Listen to an event called 'rand' from the server
socket.on("rand", (num: any) => {
console.log("RANDOM: " + num);
});
const options: ClientOptions = {
path: "/socketcluster/",
port: 8000,
hostname: "127.0.0.1",
autoConnect: true,
secure: false,
rejectUnauthorized: false,
connectTimeout: 10000, // milliseconds
ackTimeout: 10000, // milliseconds
channelPrefix: null,
disconnectOnUnload: true,
multiplex: true,
autoReconnectOptions: {
initialDelay: 10000, // milliseconds
randomness: 10000, // milliseconds
multiplier: 1.5, // decimal
maxDelay: 60000 // milliseconds
},
authEngine: null,
codecEngine: null,
subscriptionRetryOptions: {},
query: {
yourparam: "hello"
}
};
socket = create(options);
socket.on("subscribe", channelname => {
console.log("subscribe:" + channelname);
});
socket.on("subscribeFail", channelname => {
console.log("subscribeFail:" + channelname);
});
socket.on("unsubscribe", channelname => {
console.log("unsubscribe:" + channelname);
});
socket.on("subscribeStateChange", data => {
console.log("subscribeStateChange:" + JSON.stringify(data));
});
socket.on("message", data => {
console.log("message:" + data);
});
const channels = socket.channels;
const testChannel = channels["test"];
const state = testChannel.getState();
destroy(socket);
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"lib/scclientsocket.d.ts",
"socketcluster-client-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+15
View File
@@ -0,0 +1,15 @@
// Type definitions for socketcluster-server 13.1
// Project: https://github.com/SocketCluster/socketcluster-server
// Definitions by: Daniel Rose <https://github.com/DanielRose>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
import { Server } from "http";
export import SCServer = require("./scserver");
export import SCServerSocket = require("./scserversocket");
export function listen(port?: number, options?: SCServer.SCServerOptions, listeningListener?: () => void): SCServer;
export function listen(port?: number, listeningListener?: () => void): SCServer;
export function attach(server: Server, options?: SCServer.SCServerOptions): SCServer;
+315
View File
@@ -0,0 +1,315 @@
import { EventEmitter } from "events";
import { Secret } from "jsonwebtoken";
import { ServerOptions } from "https";
import { IncomingMessage, Server } from "http";
import { SCAuthEngine } from "sc-auth";
import { SCExchange } from "sc-broker-cluster";
import WebSocket = require("ws");
import SCServerSocket = require("./scserversocket");
declare class SCServer extends EventEmitter {
readonly MIDDLEWARE_HANDSHAKE_WS: "handshakeWS";
readonly MIDDLEWARE_HANDSHAKE_SC: "handshakeSC";
readonly MIDDLEWARE_AUTHENTICATE: "authenticate";
readonly MIDDLEWARE_SUBSCRIBE: "subscribe";
readonly MIDDLEWARE_PUBLISH_IN: "publishIn";
readonly MIDDLEWARE_PUBLISH_OUT: "publishOut";
readonly MIDDLEWARE_EMIT: "emit";
options: SCServer.SCServerOptions;
exchange: SCExchange;
clients: {
[id: string]: SCServerSocket;
};
clientsCount: number;
pendingClients: {
[id: string]: SCServerSocket;
};
pendingClientsCount: number;
constructor(options?: SCServer.SCServerOptions);
on(event: "connection", listener: SCServer.connectionListenerFunction): this;
addMiddleware(type: "handshakeWS", middlewareFn: (req: IncomingMessage, next: SCServer.nextMiddlewareFunction) => void): void;
addMiddleware(type: "handshakeSC", middlewareFn: (req: SCServer.HandshakeSCRequest, next: SCServer.nextHandshakeSCMiddlewareFunction) => void): void;
addMiddleware(type: "authenticate", middlewareFn: (req: SCServer.AuthenticateRequest, next: SCServer.nextAuthenticateMiddlewareFunction) => void): void;
addMiddleware(type: "subscribe", middlewareFn: (req: SCServer.SubscribeRequest, next: SCServer.nextMiddlewareFunction) => void): void;
addMiddleware(type: "publishIn", middlewareFn: (req: SCServer.PublishInRequest, next: SCServer.nextMiddlewareFunction) => void): void;
addMiddleware(type: "publishOut", middlewareFn: (req: SCServer.PublishOutRequest, next: SCServer.nextMiddlewareFunction) => void): void;
addMiddleware(type: "emit", middlewareFn: (req: SCServer.EmitRequest, next: SCServer.nextMiddlewareFunction) => void): void;
setAuthEngine(authEngine: SCAuthEngine): void;
setCodecEngine(codecEngine: SCServer.SCCodecEngine): void;
}
export = SCServer;
declare namespace SCServer {
interface AuthToken {
[x: string]: any;
}
interface SCServerOptions {
// The port on which to listen for outside connections/requests
port?: number;
// Number of worker processes
workers?: number;
// Number of broker processes
brokers?: number;
// Should be either 'dev' or 'prod' - This affects the shutdown procedure
// when a 'SIGUSR2' signal is received by master. In 'dev', a SIGUSR2 will
// trigger an immediate shutdown of workers. In 'prod' workers will
// be terminated progressively in accordance with processTermTimeout.
environment?: string;
// Setting this to true will cause the master process to shut down when
// it receives a SIGUSR2 signal (instead of just the workers).
// If you're using nodemon, set this to true.
killMasterOnSignal?: boolean;
// A unique name for your app (this is used internally for
// various things such as the directory name in which to store socket
// file descriptors) - If you don't provide an appName, SC will
// generate a random one (UUID v4)
appName?: string;
// This can be the name of an npm module or a path to a Node.js module
// to use as the WebSocket server engine.
// You can now set this to 'sc-uws' for a massive speedup of at least 2x!
wsEngine?: string;
// An ID to associate with this specific instance of SC
// this may be useful if you are running an SC app on multiple
// hosts - You can access the instanceId from the Broker object
// (inside brokerController) - If you don't provide an instanceId,
// SC will generate a random one (UUID v4)
instanceId?: string;
// A key which various SC processes will use to interact with
// scBroker broker processes securely, defaults to a 256 bits
// cryptographically random hex string
secretKey?: string;
// The key which SC will use to encrypt/decrypt authTokens, defaults
// to a 256 bits cryptographically random hex string
// The default JWT algorithm used is 'HS256'.
// If you want to use RSA or ECDSA, you should provide a authPrivateKey
// and authPublicKey instead of authKey.
authKey?: Secret;
// perMessageDeflate compression. Note that this option is passed directly to the wsEngine's
// Server object. So if you're using 'ws' as the engine, you can pass an object instead of
// a boolean. Search for perMessageDeflate here:
// https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback
// Note that by default, per-message deflate only kicks in for messages > 1024 bytes.
perMessageDeflate?: boolean;
// If using an RSA or ECDSA algorithm to sign the authToken, you will need
// to provide an authPrivateKey and authPublicKey in PEM format (string or Buffer).
authPrivateKey?: Secret;
authPublicKey?: Secret;
// The default expiry for auth tokens in seconds
authDefaultExpiry?: number;
// The algorithm to use to sign and verify JWT tokens.
authAlgorithm?: string;
// Crash workers when an error happens - This is the most sensible default
crashWorkerOnError?: boolean;
// Reboot workers when they crash - This is a necessity
// in production but can be turned off for debugging
rebootWorkerOnCrash?: boolean;
// Kill/respawn a worker process if its memory consumption exceeds this
// threshold (in bytes) - If this is null (default), this behavior
// will be switched off
killWorkerMemoryThreshold?: number;
// Can be 'http' or 'https'
protocol?: "http" | "https";
// This is the same as the object provided to Node.js's https server
protocolOptions?: ServerOptions;
// A log level of 3 will log everything, 2 will show notices and errors,
// 1 will only log errors, 0 will log nothing
logLevel?: 0 | 1 | 2 | 3;
// In milliseconds, how long a client has to connect to SC before timing out
connectTimeout?: number;
// In milliseconds - If the socket handshake hasn't been completed before
// this timeout is reached, the new connection attempt will be terminated.
handshakeTimeout?: number;
// In milliseconds, the timeout for calling res(err, data) when
// your emit() call expects an ACK response from the other side
// (when callback is provided to emit)
ackTimeout?: number;
// In milliseconds, the timeout for calling res(err, data) when
// your sendToWorker, sendToBroker or sendToMaster (IPC) call
// expects an ACK response from the other process
// (when callback is provided)
ipcAckTimeout?: number;
// In milliseconds - If the socket cannot upgrade transport
// within this period, it will stop trying
socketUpgradeTimeout?: number;
// Origins which are allowed to connect to the real-time scServer
origins?: string;
// The maximum number of unique channels which a single
// socket can subscribe to
socketChannelLimit?: number;
// The interval in milliseconds on which to
// send a ping to the client to check that
// it is still alive
pingInterval?: number;
// How many milliseconds to wait without receiving a ping
// before closing the socket
pingTimeout?: number;
// Maximum amount of milliseconds to wait before force-killing
// a process after it was passed a 'SIGTERM' or 'SIGUSR2' signal
processTermTimeout?: number;
// Whether or not errors from child processes (workers and brokers)
// should be passed to the current master process
propagateErrors?: boolean;
// Whether or not warnings from child processes (workers and brokers)
// should be passed to the current master process
propagateWarnings?: number;
// Whether or not a 'warning' event should be emitted (and logged to console)
// whenever an action is blocked by a middleware function
middlewareEmitWarnings?: number;
// Lets you specify a host name to bind to - Defaults to
// 127.0.0.1 (localhost)
host?: string;
// The path to a file used to bootstrap worker processes
workerController?: string;
// The path to a file used to bootstrap broker processes
brokerController?: string;
// The path to a file used to bootstrap the workerCluster process
workerClusterController?: string;
// By default, SC will reboot all workers when it receives a 'SIGUSR2' signal -
// This can be used for updating workers with fresh source code in production
rebootOnSignal?: boolean;
// If you run your master process (server.js) as super user, this option
// lets you downgrade worker and broker processes to run under
// the specified user (with fewer permissions than master) - You can provide
// a Linux UID or username
downgradeToUser?: number | string;
// The URL path reserved by SocketCluster clients to interact with the server
path?: string;
// The root directory in which to store your socket files in Linux.
socketRoot?: string;
// Defaults to "rr", but can be set to "none"
schedulingPolicy?: "rr" | "none";
// Whether or not clients are allowed to publish messages to channels
allowClientPublish?: boolean;
// This option is passed to the Node.js HTTP server if provided
tcpSynBacklog?: number;
// SC keeps track of request per minutes internally - This allows you to change
// how often this gets updated
workerStatusInterval?: number;
// This allows you to batch multiple messages together when passing them across
// message brokers. This may improve the efficiency of your pub/sub operations.
// This value is in milliseconds. 5 is generally a safe value to set this to.
pubSubBatchDuration?: number;
// The default clustering/brokering engine (Node.js module name) which provides the
// SCWorker.exchange object and manages brokers behind the scenes.
// You shouldn't need to change this unless you want to build your own
// process clustering engine (which is difficult to do).
brokerEngine?: string;
wsEngineServerOptions?: WebSocket.ClientOptions;
maxPayload?: number;
pingTimeoutDisabled?: boolean;
authSignAsync?: boolean;
authVerifyAsync?: boolean;
httpServer?: Server;
}
interface SCServerSocketStatus {
id: string;
pingTimeout: number;
}
interface HandshakeSCRequest {
socket: SCServerSocket;
}
interface AuthenticateRequest {
socket: SCServerSocket;
authToken: AuthToken;
}
interface SubscribeRequest {
socket: SCServerSocket;
authTokenExpiredError?: Error;
channel?: string;
waitForAuth?: boolean;
data?: any;
}
interface PublishInRequest {
socket: SCServerSocket;
authTokenExpiredError?: Error;
channel?: string;
data?: any;
ackData?: any;
}
interface PublishOutRequest {
socket: SCServerSocket;
channel?: string;
data?: any;
useCache?: boolean;
}
interface EmitRequest {
socket: SCServerSocket;
authTokenExpiredError?: Error;
event: string;
data?: any;
}
type nextMiddlewareFunction = (error?: true | string | Error) => void;
type nextHandshakeSCMiddlewareFunction = (error?: true | string | Error | null, statusCode?: number) => void;
type nextAuthenticateMiddlewareFunction = (error?: true | string | Error | null, isBadToken?: boolean) => void;
type connectionListenerFunction = (scSocket: SCServerSocket, serverSocketStatus: SCServerSocketStatus) => void;
interface SCCodecEngine {
decode: (input: any) => any;
ncode: (object: any) => any;
}
}
+43
View File
@@ -0,0 +1,43 @@
import Emitter = require("component-emitter");
import { IncomingMessage } from "http";
import { SCExchange } from "sc-broker-cluster";
import { SignOptions } from "jsonwebtoken";
import WebSocket = require("ws");
import SCServer = require("./scserver");
declare class SCServerSocket extends Emitter {
readonly CONNECTING: "connecting";
readonly OPEN: "open";
readonly CLOSED: "closed";
readonly AUTHENTICATED: "authenticated";
readonly UNAUTHENTICATED: "unauthenticated";
id: string;
request: IncomingMessage;
remoteAddress: string;
remoteFamily: string;
remotePort: number;
exchange: SCExchange;
state: "connecting" | "open" | "closed";
authState: "authenticated" | "unauthenticated";
authToken?: SCServer.AuthToken;
constructor(id: string, server: SCServer, socket: WebSocket);
getState(): "connecting" | "open" | "closed";
disconnect(code?: number, data?: any): void;
send(data: any, options: { mask?: boolean; binary?: boolean; compress?: boolean; fin?: boolean }): void;
getAuthToken(): SCServer.AuthToken;
setAuthToken(data: SCServer.AuthToken, options?: SignOptions): void;
deauthenticate(): void;
kickOut(channel?: string, message?: string, callback?: () => void): void;
subscriptions(): string[];
isSubscribed(channel?: string): boolean;
}
export = SCServerSocket;
@@ -0,0 +1,39 @@
// Adapted from README
// Using with basic http(s) module (example)
import http = require("http");
import * as socketClusterServer from "socketcluster-server";
let httpServer = http.createServer();
let scServer = socketClusterServer.attach(httpServer);
scServer.on("connection", socket => {
// ... Handle new socket connections here
});
httpServer.listen(8000);
// Using with Express (example)
import serveStatic = require("serve-static");
import path = require("path");
import express = require("express");
const app = express();
app.use(serveStatic(path.resolve(__dirname, "public")));
httpServer = http.createServer();
// Attach express to our httpServer
httpServer.on("request", app);
// Attach socketcluster-server to our httpServer
scServer = socketClusterServer.attach(httpServer);
scServer.on("connection", socket => {
// ... Handle new socket connections here
});
httpServer.listen(8000);
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"scserver.d.ts",
"scserversocket.d.ts",
"socketcluster-server-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}

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