Merge remote-tracking branch 'upstream/master' into AlexJ-OutlookMigration

This commit is contained in:
Alex Jerabek
2018-06-11 13:56:48 -07:00
72 changed files with 7884 additions and 603 deletions
+1 -1
View File
@@ -247,7 +247,7 @@ new Chartist.Pie('.ct-chart', {
value: 70,
name: 'Series 3',
className: 'my-custom-class-three',
meta: 'Meta Three'
meta: { description: 'Meta Three' }
}]
});
+2 -2
View File
@@ -1,6 +1,6 @@
// Type definitions for Chartist v0.9.81
// Project: https://github.com/gionkunz/chartist-js
// Definitions by: Matt Gibbs <https://github.com/mtgibbs>, Simon Pfeifer <https://github.com/psimonski>, Cassey Lottman <https://github.com/clottman>, Anastasiia Antonova <https://github.com/affilnost>
// Definitions by: Matt Gibbs <https://github.com/mtgibbs>, Simon Pfeifer <https://github.com/psimonski>, Cassey Lottman <https://github.com/clottman>, Anastasiia Antonova <https://github.com/affilnost>, Sunny Juneja <https://github.com/sunnyrjuneja>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace Chartist {
@@ -101,7 +101,7 @@ declare namespace Chartist {
value?: number;
data?: Array<number>;
className?: string;
meta?: string; // I assume this could probably be a number as well?
meta?: any;
}
interface IChartistBase<T extends IChartOptions> {
@@ -0,0 +1,92 @@
import { Break, BreakClip } from "./cast.framework.messages";
export = cast.framework.breaks;
declare namespace cast.framework.breaks {
class BreakSeekData {
constructor(seekFrom: number, seekTo: number, breaks: Break[]);
/**
* List of breaks
*/
breaks: Break[];
/**
* Current playback time
*/
seekFrom: number;
/**
* The time to seek to
*/
seekTo: number;
}
/** Provide context information for break clip load interceptor. */
class BreakClipLoadInterceptorContext {
constructor(brk: Break);
/**
* The container break for the break clip
*/
break: Break;
}
/** Interface to manage breaks */
interface BreakManager {
/**
* Get current media break by id.
*/
getBreakById(id: string): Break;
/**
* Get current media break clip by id
*/
getBreakClipById(id: string): BreakClip;
/** Get current media break clips. */
getBreakClips(): BreakClip[];
/** Get current media breaks. */
getBreaks(): Break[];
/** Returns true if watched breaks should be played. */
getPlayWatchedBreak(): boolean;
/**
* Provide an interceptor to allow developer to insert more break clips or modify current break clip before a break is started.
* If interceptor is null it will reset the interceptor to default one.
* By default VAST fetching and parsing logic in default interceptor.
* So if customized interceptor is set by developer;
* the VAST logic will be overridden and developers should implement their own VAST fetching and parsing logic in the provided interceptor.
*/
setBreakClipLoadInterceptor(
interceptor: (
breakClip: BreakClip,
breakClipLoaderContext?: BreakClipLoadInterceptorContext
) => void
): void;
/**
* Provide an interceptor for developer to specify what breaks they want to play after seek.
*/
setBreakSeekInterceptor(
seekInterceptor: (breakSeekData: BreakSeekData) => void
): void;
/**
* Set a flag to control if the watched client stitching break should be played.
*/
setPlayWatchedBreak(playWatchedBreak: boolean): void;
/**
* Provide an interceptor to modify VAST tracking URL before it is being sent to server.
* The input of the interceptor is a string of the tracking URL.
* The interceptor can either return a modified string of URL or a Promise of modified string of URL.
* The interceptor can also return null if you want to send the tracking URL by your own code instead of by CAF.
*/
setVastTrackingInterceptor(
interceptor?: (trackingUrl: string) => void
): void;
}
}
+783
View File
@@ -0,0 +1,783 @@
import { EventType } from "./cast.framework.events";
import {
PlayerState,
PlayStringId,
ErrorType,
ErrorReason,
IdleReason,
MessageType,
Track,
TextTrackStyle,
QueueItem,
LoadRequestData,
QueueData,
Break,
LiveSeekableRange,
MediaInformation,
ErrorData,
RequestData
} from "./cast.framework.messages";
import { BreakManager } from "./cast.framework.breaks";
import { EventHandler, RequestHandler, BinaryHandler } from "./index";
import {
EventType as SystemEventType,
ApplicationData,
Sender,
StandbyState,
SystemState
} from "./cast.framework.system";
export = cast.framework;
type HTMLMediaElement = any;
declare namespace cast.framework {
type LoggerLevel =
| "DEBUG"
| "VERBOSE"
| "INFO"
| "WARNING"
| "ERROR"
| "NONE";
type ContentProtection = "NONE" | "CLEARKEY" | "PLAYREADY" | "WIDEVINE";
/**
* Manages text tracks.
*/
class TextTracksManager {
constructor(params?: any);
/**
* Adds text tracks to the list.
*/
addTracks(tracks: Track[]): void;
/**
* Creates a text track.
*/
createTrack(): Track;
/**
* Gets all active text ids.
*/
getActiveIds(): number[];
/**
* Gets all active text tracks.
*/
getActiveTracks(): Track[];
/**
* Returns the current text track style.
*/
getTextTracksStyle(): TextTrackStyle;
/**
* Gets text track by id.
*/
getTrackById(id: number): Track;
/**
* Returns all text tracks.
*/
getTracks(): Track[];
/**
* Gets text tracks by language.
*/
getTracksByLanguage(language: string): Track[];
/**
* Sets text tracks to be active by id.
*/
setActiveByIds(newIds: number[]): void;
/**
* Sets text tracks to be active by language.
*/
setActiveByLanguage(language: string): void;
/**
* Sets text track style.
*/
setTextTrackStyle(style: TextTrackStyle): void;
}
/**
* QueueManager exposes several queue manipulation APIs to developers.
*/
class QueueManager {
constructor(params?: any);
/**
* Returns the current queue item.
*/
getCurrentItem(): QueueItem;
/**
* Returns the index of the current queue item.
*/
getCurrentItemIndex(): number;
/**
* Returns the queue items.
*/
getItems(): QueueItem[];
/**
* Inserts items into the queue.
*/
insertItems(items: QueueItem[], insertBefore?: number): void;
/**
* Removes items from the queue.
*/
removeItems(itemIds: number[]): void;
/**
* Sets whether to limit the number of queue items to be reported in Media Status (default is true).
*/
setQueueStatusLimit(limitQueueItemsInStatus: boolean): void;
/**
* Updates existing queue items by matching itemId.
*/
updateItems(items: QueueItem[]): void;
}
/**
* Base implementation of a queue.
*/
class QueueBase {
/**
* Fetches a window of items using the specified item id as reference; called by the receiver MediaManager when it needs more queue items;
* often as a request from senders. If only one of nextCount and prevCount is non-zero; fetchItems should only return items after or before
* the reference item; if both nextCount and prevCount are non-zero; a window of items including the reference item should be returned.
*/
fetchItems(
itemId: number,
nextCount: number,
prevCount: number
): QueueItem[] | Promise<QueueItem[]>;
/**
* Initializes the queue with the requestData. This is called when a new LOAD request comes in to the receiver.
* If this returns or resolves to null; our default queueing implementation will create a queue based on queueData.items or the single media
* in the load request data.
*/
initialize(
requestData: LoadRequestData
): QueueData | Promise<QueueData>;
/**
* Returns next items after the reference item; often the end of the current queue; called by the receiver MediaManager.
*/
nextItems(itemId?: number): QueueItem[] | Promise<QueueItem[]>;
/**
* Sets the current item with the itemId; called by the receiver MediaManager when it changes the current playing item.
*/
onCurrentItemIdChanged(itemId: number): void;
/**
* A callback for informing the following items have been inserted into the receiver queue in this session.
* A cloud based implementation can optionally choose to update its queue based on the new information.
*/
onItemsInserted(items: QueueItem[], insertBefore?: number): void;
/**
* A callback for informing the following items have been removed from the receiver queue in this session.
* A cloud based implementation can optionally choose to update its queue based on the new information.
*/
onItemsRemoved(itemIds: number[]): void;
/**
* Returns previous items before the reference item; often at the beginning of the queue; called by the receiver MediaManager.
*/
prevItems(itemId?: number): QueueItem[] | Promise<QueueItem[]>;
/**
* Shuffles the queue and returns new queue items. Returns null if the operation is not supported.
*/
shuffle(): QueueItem[] | Promise<QueueItem[]>;
}
/**
* Controls and monitors media playback.
*/
class PlayerManager {
constructor(params?: any);
/**
* Adds an event listener for player event.
*/
addEventListener: (
eventType: EventType | EventType[],
eventListener: EventHandler
) => void;
/**
* Sends a media status message to all senders (broadcast). Applications use this to send a custom state change.
*/
broadcastStatus(
includeMedia?: boolean,
requestId?: number,
customData?: any,
includeQueueItems?: boolean
): void;
getAudioTracksManager(): AudioTracksManager;
/**
* Returns current time in sec in currently-playing break clip.
*/
getBreakClipCurrentTimeSec(): number;
/**
* Returns duration in sec of currently-playing break clip.
*/
getBreakClipDurationSec(): number;
/**
* Obtain the breaks (Ads) manager.
*/
getBreakManager(): BreakManager;
/**
* Returns list of breaks.
*/
getBreaks(): Break[];
/**
* Gets current time in sec of current media.
*/
getCurrentTimeSec(): number;
/**
* Gets duration in sec of currently playing media.
*/
getDurationSec(): number;
/**
* Returns live seekable range with start and end time in seconds. The values are media time based.
*/
getLiveSeekableRange(): LiveSeekableRange;
/**
* Gets media information of current media.
*/
getMediaInformation(): MediaInformation;
/**
* Returns playback configuration.
*/
getPlaybackConfig(): PlaybackConfig;
/**
* Returns current playback rate.
*/
getPlaybackRate(): number;
/**
* Gets player state.
*/
getPlayerState(): PlayerState;
/**
* Get the preferred playback rate. (Can be used on shutdown event to save latest preferred playback rate to a persistent storage;
* so it can be used in next session in the cast options).
*/
getPreferredPlaybackRate(): number;
/**
* Get the preferred text track language.
*/
getPreferredTextLanguage(): string;
/**
* Obtain QueueManager API.
*/
getQueueManager(): QueueManager;
getTextTracksManager(): TextTracksManager;
/**
* Loads media.
*/
load(loadRequest: LoadRequestData): Promise<void>;
/**
* Pauses currently playing media.
*/
pause(): void;
/**
* Plays currently paused media.
*/
play(): void;
/**
* Requests a text string to be played back locally on the receiver device.
*/
playString(stringId: PlayStringId, args?: string[]): Promise<ErrorData>;
/**
* Request Google Assistant to refresh the credentials. Only works if the original credentials came from the assistant.
*/
refreshCredentials(): Promise<void>;
/**
* Removes the event listener added for given player event. If event listener is not added; it will be ignored.
*/
removeEventListener(
eventType: EventType | EventType[],
eventListener: EventHandler
): void;
/**
* Seeks in current media.
*/
seek(seekTime: number): void;
/**
* Sends an error to a specific sender
*/
sendError(
senderId: string,
requestId: number,
type: ErrorType,
reason?: ErrorReason,
customData?: any
): void;
/**
* Send local media request.
*/
sendLocalMediaRequest(request: RequestData): void;
/**
* Sends a media status message to a specific sender.
*/
sendStatus(
senderId: string,
requestId: number,
includeMedia?: boolean,
customData?: any,
includeQueueItems?: boolean
): void;
/**
* Sets the IDLE reason. This allows applications that want to force the IDLE state to indicate the reason that made the player going to IDLE state
* (a custom error; for example). The idle reason will be sent in the next status message. NOTE: Most applications do not need to set this value;
* it is only needed if they want to make the player go to IDLE in special circumstances and the default idleReason does not reflect their intended
* behavior.
*/
setIdleReason(idleReason: IdleReason): void;
/**
* Sets MediaElement to use. If Promise of MediaElement is set; media begins playback after Promise is resolved.
*/
setMediaElement(mediaElement: HTMLMediaElement): void;
/**
* Sets media information.
*/
setMediaInformation(
mediaInformation: MediaInformation,
opt_broadcast?: boolean
): void;
/**
* Sets a handler to return or modify PlaybackConfig; for a specific load request. The handler paramaters are the load request data
* and default playback config for the receiver (provided in the context options). The handler should returns a modified playback config;
* or null to prevent the media from playing. The return value can be a promise to allow waiting for data from the server.
*/
setMediaPlaybackInfoHandler(
handler: (
loadRequestData: LoadRequestData,
playbackConfig: PlaybackConfig
) => void
): void;
/**
* Sets a handler to return the media url for a load request. This handler can be used to avoid having the media content url published as part
* of the media status. By default the media contentId is used as the content url.
*/
setMediaUrlResolver(
resolver: (loadRequestData: LoadRequestData) => void
): void;
/**
* Provide an interceptor of incoming and outgoing messages.
* The interceptor can update the request data; and return updated data; a promise of
* updated data if need to get more data from the server; or null if the request should not be handled.
* Note that if load message interceptor is provided; and no interceptor is provided for preload -
* the load interceptor will be called for preload messages.
*/
setMessageInterceptor(
type: MessageType,
interceptor: (requestData: RequestData) => Promise<any>
): void;
/**
* Sets playback configuration on the PlayerManager.
*/
setPlaybackConfig(playbackConfig: PlaybackConfig): void;
/**
* Set the preferred playback rate for follow up load or media items. The preferred playback rate will be updated automatically to the latest
* playback rate that was provided by a load request or explicit set of playback rate.
*/
setPreferredPlaybackRate(preferredPlaybackRate: number): void;
/**
* Set the preferred text track language. The preferred text track language will be updated automatically to the latest enabled language
* by a load request or explicit change to text tracks. (Should be called only in idle state; and Will only apply to next loaded media).
*/
setPreferredTextLanguage(preferredTextLanguage: string): void;
/**
* Stops currently playing media.
*/
stop(): void;
}
/**
* Configuration to customize playback behavior.
*/
class PlaybackConfig {
/**
* Duration of buffered media in seconds to start buffering.
*/
autoPauseDuration?: number;
/**
* Duration of buffered media in seconds to start/resume playback after auto-paused due to buffering.
*/
autoResumeDuration?: number;
/**
* Minimum number of buffered segments to start/resume playback.
*/
autoResumeNumberOfSegments?: number;
/**
* A function to customize request to get a caption segment.
*/
captionsRequestHandler?: RequestHandler;
/**
* Initial bandwidth in bits in per second.
*/
initialBandwidth?: number;
/**
* Custom license data.
*/
licenseCustomData?: string;
/**
* Handler to process license data. The handler is passed the license data; and returns the modified license data.
*/
licenseHandler?: BinaryHandler;
/**
* A function to customize request to get a license.
*/
licenseRequestHandler?: RequestHandler;
/**
* Url for acquiring the license.
*/
licenseUrl?: string;
/**
* Handler to process manifest data. The handler is passed the manifest; and returns the modified manifest.
*/
manifestHandler?: (manifest: string) => string;
/**
* A function to customize request to get a manifest.
*/
manifestRequestHandler?: RequestHandler;
/**
* Preferred protection system to use for decrypting content.
*/
protectionSystem: ContentProtection;
/**
* Handler to process segment data. The handler is passed the segment data; and returns the modified segment data.
*/
segmentHandler?: BinaryHandler;
/**
* A function to customize request information to get a media segment.
*/
segmentRequestHandler?: RequestHandler;
/**
* Maximum number of times to retry a network request for a segment.
*/
segmentRequestRetryLimit?: number;
}
/**
* HTTP(s) Request/Response information.
*/
class NetworkRequestInfo {
/**
* The content of the request. Can be used to modify license request body.
*/
content: Uint8Array;
/**
* An object containing properties that you would like to send in the header.
*/
headers: any;
/**
* The URL requested.
*/
url: string;
/**
* Indicates whether CORS Access-Control requests should be made using credentials such as cookies or authorization headers.
*/
withCredentials: boolean;
}
/** Cast receiver context options. All options are optionals. */
class CastReceiverOptions {
/**
* Optional map of custom messages namespaces to initialize and their types.
* Custom messages namespaces need to be initiated before the application started;
* so it is best to provide the namespaces in the receiver options.
* (The default type of a message bus is JSON; if not provided here).
*/
customNamespaces?: any;
/**
* Sender id used for local requests. Default value is 'local'.
*/
localSenderId?: string;
/**
* Maximum time in seconds before closing an idle sender connection.
* Setting this value enables a heartbeat message to keep the connection alive.
* Used to detect unresponsive senders faster than typical TCP timeouts.
* The minimum value is 5 seconds; there is no upper bound enforced but practically it's minutes before platform TCP timeouts come into play.
* Default value is 10 seconds.
*/
maxInactivity?: number;
/**
* Optional media element to play content with. Default behavior is to use the first found media element in the page.
*/
mediaElement?: HTMLMediaElement;
/**
* Optional playback configuration.
*/
playbackConfig?: PlaybackConfig;
/**
* If this is true; the watched client stitching break will also be played.
*/
playWatchedBreak?: boolean;
/**
* Preferred value for player playback rate. It is used if playback rate value is not provided in the load request.
*/
preferredPlaybackRate?: number;
/**
* Preferred text track language. It is used if no active track is provided in the load request.
*/
preferredTextLanguage?: string;
/**
* Optional queue implementation.
*/
queue?: QueueBase;
/**
* Text that represents the application status.
* It should meet internationalization rules as may be displayed by the sender application.
*/
statusText?: string;
/**
* A bitmask of media commands supported by the application.
* LOAD; PLAY; STOP; GET_STATUS must always be supported.
* If this value is not provided; then PAUSE; SEEK; STREAM_VOLUME; STREAM_MUTE are assumed to be supported too.
*/
supportedCommands?: number;
/**
* Indicate that MPL should be used for DASH content.
*/
useLegacyDashSupport?: boolean;
/**
* An integer used as an internal version number.
* This number is used only to distinguish between receiver releases and higher numbers do not necessarily have to represent newer releases.
*/
versionCode?: number;
}
/** Manages loading of underlying libraries and initializes underlying cast receiver SDK. */
class CastReceiverContext {
/** Returns the CastReceiverContext singleton instance. */
static getInstance(): CastReceiverContext;
constructor(params: any);
/**
* Sets message listener on custom message channel.
*/
addCustomMessageListener(
namespace: string,
listener: EventHandler
): void;
/**
* Add listener to cast system events.
*/
addEventListener(
type: SystemEventType | SystemEventType[],
handler: EventHandler
): void;
/**
* Checks if the given media params of video or audio streams are supported by the platform.
*/
canDisplayType(
mimeType: string,
codecs?: string,
width?: number,
height?: number,
framerate?: number
): boolean;
/**
* Provides application information once the system is ready; otherwise it will be null.
*/
getApplicationData(): ApplicationData;
/**
* Provides device capabilities information once the system is ready; otherwise it will be null.
* If an empty object is returned; the device does not expose any capabilities information.
*/
getDeviceCapabilities(): any;
/**
* Get Player instance that can control and monitor media playback.
*/
getPlayerManager(): PlayerManager;
/**
* Get a sender by sender id
*/
getSender(senderId: string): Sender;
/**
* Gets a list of currently-connected senders.
*/
getSenders(): Sender[];
/**
* Reports if the cast application's HDMI input is in standby.
*/
getStandbyState(): StandbyState;
/**
* Provides application information about the system state.
*/
getSystemState(): SystemState;
/**
* Reports if the cast application is the HDMI active input.
*/
getVisibilityState(): any;
/**
* When the application calls start; the system will send the ready event to indicate
* that the application information is ready and the application can send messages as soon as there is one sender connected.
*/
isSystemReady(): boolean;
/**
* Start loading player js. This can be used to start loading the players js code in early stage of starting the receiver before calling start.
* This function is a no-op if players were already loaded (start was called).
*/
loadPlayerLibraries(useLegacyDashSupport?: boolean): void;
/**
* Remove a message listener on custom message channel.
*/
removeCustomMessageListener(
namespace: string,
listener: EventHandler
): void;
/**
* Remove listener to cast system events.
*/
removeEventListener(type: EventType, handler: EventHandler): void;
/**
* Sends a message to a specific sender.
*/
sendCustomMessage(
namespace: string,
senderId: string,
message: any
): void;
/**
* This function should be called in response to the feedbackstarted event if the application
* add debug state information to log in the feedback report.
* It takes in a parameter ‘message’ that is a string that represents the debug information that the application wants to log.
*/
sendFeedbackMessage(feedbackMessage: string): void;
/**
* Sets the application state. The application should call this when its state changes.
* If undefined or set to an empty string; the value of the Application Name established during application
* registration is used for the application state by default.
*/
setApplicationState(statusText: string): void;
/**
* Sets the receiver inactivity timeout.
* It is recommended to set the maximum inactivity value when calling Start and not changing it.
* This API is just provided for development/debugging purposes.
*/
setInactivityTimeout(maxInactivity: number): void;
/**
* Sets the log verbosity level.
*/
setLoggerLevel(level: LoggerLevel): void;
/**
* Initializes system manager and media manager; so that receiver app can receive requests from senders.
*/
start(options?: CastReceiverOptions): CastReceiverContext;
/**
* Shutdown receiver application.
*/
stop(): void;
}
/** Manages audio tracks. */
class AudioTracksManager {
constructor(params: any);
getActiveId(): number;
getActiveTrack(): Track;
getTrackById(id: number): Track;
getTracks(): Track[];
getTracksByLanguage(language: string): Track[];
setActiveById(id: number): void;
setActiveByLanguage(language: string): void;
}
}
+420
View File
@@ -0,0 +1,420 @@
import {
RequestData,
MediaInformation,
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";
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";
/**
* Event data for @see{@link EventType.SEGMENT_DOWNLOADED} event.
*/
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;
}
/**
* Event data for all events that represent requests made to the receiver.
*/
class RequestEvent extends Event {
constructor(
type: EventType,
requestData?: RequestData,
senderId?: string
);
/**
* The data that was sent with the request.
*/
requestData?: RequestData;
/**
* The sender id the request came from.
*/
senderId?: string;
}
/**
* Event data superclass for all events dispatched by @see{@link PlayerManager}
*/
class Event {
constructor(type: EventType);
/**
* Type of the event.
*/
type: EventType;
}
/**
* Event data for @see{@link EventType.MEDIA_STATUS} event.
*/
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.
*/
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.
*/
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);
/**
* Added track.
*/
track: Track;
}
/** Event data for @see{@link EventType.ID3} event. */
class Id3Event extends Event {
constructor(segmentData: Uint8Array);
/**
* The segment data.
*/
segmentData: Uint8Array;
}
/**
* Event data for @see{@link EventType.EMSG} event.
*/
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;
/**
* 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
);
/**
* 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;
}
}
File diff suppressed because it is too large Load Diff
+198
View File
@@ -0,0 +1,198 @@
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";
type SystemState =
| "NOT_STARTED"
| "STARTING_IN_BACKGROUND"
| "STARTING"
| "READY"
| "STOPPING_IN_BACKGROUND"
| "STOPPING";
type StandbyState = "STANDBY" | "NOT_STANDBY" | "UNKNOWN";
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).
*/
class VisibilityChangedEvent {
constructor(isVisible: boolean);
/**
* Whether the Cast device is the active input or not.
*/
isVisible: boolean;
}
/**
* Represents the system volume data.
*/
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.
*/
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.
*/
class StandbyChangedEvent {
constructor(isStandby: boolean);
isStandby: boolean;
}
/**
* Whether the TV is in standby or not.
*/
interface ShutdownEvent extends Event {
[key: string]: any;
}
/**
* Event dispatched by @see{@link CastReceiverManager} when a sender is disconnected.
*/
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;
}
/**
* Event dispatched by @see{@link CastReceiverManager} when a sender is connected.
*/
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;
}
/**
* Represents the data of a connected sender device.
*/
interface Sender {
/**
* The sender Id.
*/
id: string;
/**
* Indicate the sender supports large messages (>64KB)
*/
largeMessageSupported?: boolean;
/**
* The userAgent of the sender.
*/
userAgent?: string;
}
/**
* Event dispatched by CastReceiverManager when the system is ready.
*/
class ReadyEvent {
constructor(applicationData: ApplicationData);
/**
* The application data
*/
data: ApplicationData;
}
/**
* Event dispatched by @see{@link CastReceiverManager} when the system needs to update the restriction on maximum video resolution.
*/
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;
}
}
+197
View File
@@ -0,0 +1,197 @@
import { PlayerDataEventType } from "./cast.framework.ui";
import { MediaMetadata } from "./cast.framework.messages";
import { PlayerDataChangedEventHandler } from "./index";
export = cast.framework.ui;
declare namespace cast.framework.ui {
type ContentType = "video" | "audio" | "image";
type State =
| "launching"
| "idle"
| "loading"
| "buffering"
| "paused"
| "playing";
type PlayerDataEventType =
| "ANY_CHANGE"
| "STATE_CHANGED"
| "IS_SEEKING_CHANGED"
| "DURATION_CHANGED"
| "CURRENT_TIME_CHANGED"
| "METADATA_CHANGED"
| "TITLE_CHANGED"
| "SUBTITLE_CHANGED"
| "THUMBNAIL_URL_CHANGED"
| "NEXT_TITLE_CHANGED"
| "NEXT_SUBTITLE_CHANGED"
| "NEXT_THUMBNAIL_URL_CHANGED"
| "PRELOADING_NEXT_CHANGED"
| "CONTENT_TYPE_CHANGED"
| "IS_LIVE_CHANGED"
| "BREAK_PERCENTAGE_POSITIONS_CHANGED"
| "IS_PLAYING_BREAK_CHANGED"
| "IS_BREAK_SKIPPABLE_CHANGED"
| "WHEN_SKIPPABLE_CHANGED"
| "NUMBER_BREAK_CLIPS_CHANGED"
| "CURRENT_BREAK_CLIP_NUMBER_CHANGED"
| "DISPLAY_STATUS_CHANGED";
/**
* Player data changed event. Provides the changed field (type); and new value.
*/
class PlayerDataChangedEvent {
constructor(type: PlayerDataEventType, field: string, value: any);
/**
* The field name that was changed.
*/
field: string;
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.
*/
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;
}
}
@@ -0,0 +1,106 @@
import {
PlayerData,
PlayerDataBinder
} from "chromecast-caf-receiver/cast.framework.ui";
import {
ReadyEvent,
ApplicationData
} from "chromecast-caf-receiver/cast.framework.system";
import {
RequestEvent,
Event
} from "chromecast-caf-receiver/cast.framework.events";
import {
QueueBase,
TextTracksManager,
QueueManager,
PlayerManager
} from "chromecast-caf-receiver/cast.framework";
import {
BreakSeekData,
BreakClipLoadInterceptorContext,
BreakManager
} from "chromecast-caf-receiver/cast.framework.breaks";
import {
Break,
BreakClip,
LoadRequestData,
Track,
MediaMetadata
} from "chromecast-caf-receiver/cast.framework.messages";
const 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 items = qBase.fetchItems(1, 3, 4);
const breakSeekData = new BreakSeekData(0, 100, []);
const breakClipLoadContext = new BreakClipLoadInterceptorContext(adBreak);
const breakManager: BreakManager = {
getBreakById: () => adBreak,
getBreakClipById: () => breakClip,
getBreakClips: () => [breakClip],
getBreaks: () => [adBreak],
getPlayWatchedBreak: () => true,
setBreakClipLoadInterceptor: () => {},
setBreakSeekInterceptor: () => {},
setPlayWatchedBreak: () => {},
setVastTrackingInterceptor: () => {}
};
const lrd: LoadRequestData = {
requestId: 1,
activeTrackIds: [1, 2],
media: {
tracks: [],
textTrackStyle: {},
streamType: "BUFFERED",
metadata: { metadataType: "GENERIC" },
hlsSegmentFormat: "AAC",
contentId: "id",
contentType: "type",
breakClips: [breakClip],
breaks: [adBreak]
},
queueData: {}
};
const appData: ApplicationData = {
id: () => "id",
launchingSenderId: () => "launch-id",
name: () => "name",
namespaces: () => ["namespace"],
sessionId: () => 1
};
const readyEvent = new ReadyEvent(appData);
const data = readyEvent.data;
const pData: PlayerData = {
breakPercentagePositions: [1],
contentType: "video",
currentBreakClipNumber: 2,
currentTime: 1234,
displayStatus: true,
duration: 222,
isBreakSkippable: false,
isLive: true,
isPlayingBreak: false,
isSeeking: true,
metadata: new MediaMetadata("GENERIC"),
nextSubtitle: "sub",
nextThumbnailUrl: "url",
nextTitle: "title",
numberBreakClips: 3,
preloadingNext: false,
state: "paused",
thumbnailUrl: "url",
title: "title",
whenSkippable: 321
};
const binder = new PlayerDataBinder(pData);
binder.addEventListener("ANY_CHANGE", e => {});
+24
View File
@@ -0,0 +1,24 @@
// Type definitions for chromecast-caf-receiver 3.x
// Project: https://github.com/googlecast
// Definitions by: Craig Bruce <https://github.com/craigrbruce>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
/// <reference path="./cast.framework.d.ts" />
/// <reference path="./cast.framework.breaks.d.ts" />
/// <reference path="./cast.framework.events.d.ts" />
/// <reference path="./cast.framework.messages.d.ts" />
/// <reference path="./cast.framework.system.d.ts" />
/// <reference path="./cast.framework.ui.d.ts" />
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;
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es6"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": ["../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"strictFunctionTypes": false,
"esModuleInterop": true
},
"files": [
"index.d.ts",
"chromecast-caf-receiver-tests.ts",
"cast.framework.d.ts",
"cast.framework.breaks.d.ts",
"cast.framework.events.d.ts",
"cast.framework.messages.d.ts",
"cast.framework.system.d.ts",
"cast.framework.ui.d.ts"
]
}
@@ -0,0 +1,5 @@
{
"extends": "dtslint/dt.json",
"rules": {
}
}
@@ -0,0 +1,13 @@
declare let button: DevExpress.AspNetCore.BootstrapButton;
button.on('click', e => {});
button.doClick();
button.once('click', e => {});
declare let accordion: DevExpress.AspNetCore.BootstrapAccordion;
accordion.on('init', e => {});
const firstGroup = accordion.getGroup(0);
if (firstGroup) {
const groupText = firstGroup.getText();
const item = firstGroup.getItemByName('item10');
item && item.getEnabled();
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"devexpress-aspnetcore-bootstrap-tests.ts"
]
}
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+1 -1
View File
@@ -2368,7 +2368,7 @@ declare module 'ember' {
function Exception(message: string): void;
class SafeString {
constructor(str: string);
static toString(): string;
toString(): string;
}
function parse(string: string): any;
function print(ast: any): void;
-2
View File
@@ -24,8 +24,6 @@
"only-arrow-functions": false,
"no-submodule-imports": false,
"no-unnecessary-class": false,
// false positives
"unified-signatures": false
}
+30 -8
View File
@@ -1,17 +1,39 @@
import EventSource = require("eventsource");
const eventSource = new EventSource("http://foobar");
eventSource.onmessage = (x: any) => {};
eventSource.onerror = (x: any) => {};
eventSource.onopen = (x: any) => {};
eventSource.addEventListener = (type: string, x: any) => {};
let readyState: number = eventSource.readyState;
let closedState: number = eventSource.CLOSED;
closedState = EventSource.CLOSED;
let connectingState: number = eventSource.CONNECTING;
connectingState = EventSource.CONNECTING;
let openState: number = eventSource.OPEN;
openState = EventSource.OPEN;
let url: string = eventSource.url;
let withCredentials: boolean = eventSource.withCredentials;
eventSource.onmessage = (event: Event) => {};
eventSource.onerror = (event: Event) => {};
eventSource.onopen = (event: Event) => {};
eventSource.addEventListener = (type: string, listener: (e: Event) => void) => {};
eventSource.dispatchEvent = (event: Event) => true;
eventSource.removeEventListener = (type: string, listener: (e: Event) => void) => {};
eventSource.close();
import EventSourcePolyfill = require("eventsource/lib/eventsource-polyfill");
const eventSourcePolyfill = new EventSourcePolyfill("http://foobar");
eventSourcePolyfill.onmessage = (x: any) => {};
eventSourcePolyfill.onerror = (x: any) => {};
eventSourcePolyfill.onopen = (x: any) => {};
eventSourcePolyfill.addEventListener = (type: string, x: any) => {};
readyState = eventSourcePolyfill.readyState;
closedState = eventSource.CLOSED;
closedState = EventSource.CLOSED;
connectingState = eventSource.CONNECTING;
connectingState = EventSource.CONNECTING;
openState = eventSource.OPEN;
openState = EventSource.OPEN;
url = eventSourcePolyfill.url;
withCredentials = eventSource.withCredentials;
eventSourcePolyfill.onmessage = (event: Event) => {};
eventSourcePolyfill.onerror = (event: Event) => {};
eventSourcePolyfill.onopen = (event: Event) => {};
eventSourcePolyfill.addEventListener = (type: string, listener: (e: Event) => void) => {};
eventSourcePolyfill.dispatchEvent = (event: Event) => true;
eventSourcePolyfill.removeEventListener = (type: string, listener: (e: Event) => void) => {};
eventSourcePolyfill.close();
+14 -7
View File
@@ -1,22 +1,29 @@
// Type definitions for eventsource 1.0
// Project: http://github.com/EventSource/eventsource
// Definitions by: Scott Lee Davis <https://github.com/scottleedavis>
// Ali Afroozeh <https://github.com/afroozeh>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
// TypeScript Version: 2.8
declare class EventSource {
static readonly CLOSED: number;
static readonly CONNECTING: number;
static readonly OPEN: number;
constructor(url: string, eventSourceInitDict?: EventSource.EventSourceInitDict);
static CLOSED: EventSource.ReadyState;
static CONNECTING: EventSource.ReadyState;
static OPEN: EventSource.ReadyState;
url: string;
readyState: EventSource.ReadyState;
readonly CLOSED: number;
readonly CONNECTING: number;
readonly OPEN: number;
readonly url: string;
readonly readyState: number;
readonly withCredentials: boolean;
onopen: EventListener;
onmessage: EventListener;
onerror: EventListener;
addEventListener(type: string, listener: EventListener): void;
dispatchEvent(evt: Event): boolean;
removeEventListener(type: string, listener?: EventListener): void;
close(): void;
}
+12 -6
View File
@@ -1,16 +1,22 @@
declare class EventSource {
static readonly CLOSED: number;
static readonly CONNECTING: number;
static readonly OPEN: number;
constructor(url: string, eventSourceInitDict?: EventSource.EventSourceInitDict);
static CLOSED: EventSource.ReadyState;
static CONNECTING: EventSource.ReadyState;
static OPEN: EventSource.ReadyState;
url: string;
readyState: EventSource.ReadyState;
readonly CLOSED: number;
readonly CONNECTING: number;
readonly OPEN: number;
readonly url: string;
readonly readyState: number;
readonly withCredentials: boolean;
onopen: EventListener;
onmessage: EventListener;
onerror: EventListener;
addEventListener(type: string, listener: EventListener): void;
dispatchEvent(evt: Event): boolean;
removeEventListener(type: string, listener?: EventListener): void;
close(): void;
}
+8
View File
@@ -0,0 +1,8 @@
// Type definitions for intl-locales-supported 1.0
// Project: https://github.com/yahoo/intl-locales-supported
// Definitions by: Edward Sammut Alessi <https://github.com/Slessi>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = areIntlLocalesSupported;
declare function areIntlLocalesSupported(locales: string | string[]): boolean;
@@ -0,0 +1,4 @@
import areIntlLocalesSupported = require("intl-locales-supported");
areIntlLocalesSupported("en-GB");
areIntlLocalesSupported([ "en-GB", "en-US" ]);
@@ -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",
"intl-locales-supported-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+6
View File
@@ -13,6 +13,7 @@
// Ahn <https://github.com/AhnpGit>
// Josh Goldberg <https://github.com/joshuakgoldberg>
// Bradley Ayers <https://github.com/bradleyayers>
// Andrew Makarov <https://github.com/r3nya>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -473,6 +474,11 @@ declare namespace jest {
* to test what arguments it was last called with.
*/
toHaveBeenLastCalledWith(...params: any[]): R;
/**
* If you have a mock function, you can use `.toHaveBeenNthCalledWith`
* to test what arguments it was nth called with.
*/
toHaveBeenNthCalledWith(nthCall: number, ...params: any[]): R;
/**
* Used to check that an object has a `.length` property
* and it is set to a certain numeric value.
+6
View File
@@ -731,3 +731,9 @@ test('moduleName 2', () => {
const moduleName = require('../moduleName');
expect(moduleName()).toEqual(2);
});
describe('toHaveBeenNthCalledWith', () => {
const fn = jest.fn();
expect(fn).toHaveBeenNthCalledWith(3, "foo");
});
+3 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for jsreport-html-to-xlsx 1.4
// Type definitions for jsreport-html-to-xlsx 2.0
// Project: https://github.com/jsreport/jsreport-html-to-xlsx
// Definitions by: My Self <https://github.com/me>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -8,7 +8,9 @@ import { ExtensionDefinition } from 'jsreport-core';
import { Options as BaseOptions } from 'jsreport-xlsx';
declare module 'jsreport-core' {
type htmlEngine = 'phantom' | 'chrome';
interface Template {
htmlToXlsx: { htmlEngine: htmlEngine; };
recipe: 'html-to-xlsx' | string;
}
}
+24
View File
@@ -0,0 +1,24 @@
// Type definitions for jsreport-html-to-xlsx 1.4
// Project: https://github.com/jsreport/jsreport-html-to-xlsx
// Definitions by: My Self <https://github.com/me>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import { ExtensionDefinition } from 'jsreport-core';
import { Options as BaseOptions } from 'jsreport-xlsx';
declare module 'jsreport-core' {
interface Template {
recipe: 'html-to-xlsx' | string;
}
}
declare namespace JsReportHtml2Xlsx {
interface Options extends BaseOptions {
strategy: string;
}
}
declare function JsReportHtml2Xlsx(options?: Partial<JsReportHtml2Xlsx.Options>): ExtensionDefinition;
export = JsReportHtml2Xlsx;
@@ -0,0 +1,19 @@
import JsReport = require('jsreport-core');
import JsreportHtml2Xlsx = require('jsreport-html-to-xlsx');
import JsreportXlsx = require('jsreport-xlsx');
const jsreport = JsReport();
jsreport.use(JsreportXlsx());
jsreport.use(JsreportHtml2Xlsx());
(async () => {
const content = `<table><tr><td>test</td></tr></table>`;
await jsreport.init();
const resp = await jsreport.render({
template: {
content,
engine: 'none',
recipe: 'xlsx'
}
});
})();
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"esnext"
],
"strictFunctionTypes": true,
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../../",
"typeRoots": [
"../../"
],
"paths": {
"jsreport-html-to-xlsx": [ "jsreport-html-to-xlsx/v1" ]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"jsreport-html-to-xlsx-tests.ts"
]
}
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+1 -1
View File
@@ -27,7 +27,7 @@ declare module 'leaflet' {
drawMarker?: boolean;
markerClass?: any;
circleStyle?: PathOptions;
markerStyle?: PathOptions;
markerStyle?: PathOptions | MarkerOptions;
followCircleStyle?: PathOptions;
followMarkerStyle?: PathOptions;
icon?: string;
+133 -74
View File
@@ -1,114 +1,173 @@
// Type definitions for Libxmljs v0.14.2
// Project: https://github.com/polotek/libxmljs
// Type definitions for Libxmljs 0.18
// Project: https://github.com/libxmljs/libxmljs
// Definitions by: François de Campredon <https://github.com/fdecampredon>
// ComFreek <https://github.com/ComFreek>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node"/>
import { EventEmitter } from 'events';
export const version: string;
export const libxml_version: string;
export const libxml_parser_version: string;
// tslint:disable-next-line:strict-export-declare-modifiers
interface ParseOptions {
[optionName: string]: string;
}
import events = require('events');
export function parseXml(source: string, options?: ParseOptions): Document;
export function parseXmlString(source: string, options?: ParseOptions): Document;
export declare function parseXml(source: string): XMLDocument;
export declare function parseHtml(source: string): HTMLDocument;
export declare function parseXmlString(source: string, options?: { [key: string]: string }): XMLDocument;
export declare function parseHtmlString(source: string): HTMLDocument;
export function parseHtml(source: string, options?: ParseOptions): Document;
export function parseHtmlString(source: string, options?: ParseOptions): Document;
export function parseHtmlFragment(source: string, options?: ParseOptions): Document;
export function memoryUsage(): number;
export function nodeCount(): number;
export declare class XMLDocument {
constructor(version: number, encoding: string);
child(idx: number): Element | undefined;
export class Document {
/**
* Create a new XML Document
* @param version XML document version, defaults to 1.0
* @param encoding Encoding, defaults to utf8
*/
constructor(version?: number, encoding?: string);
errors: SyntaxError[];
child(idx: number): Element|null;
childNodes(): Element[];
errors(): SyntaxError[];
encoding(): string;
encoding(enc: string): void;
encoding(enc: string): this;
find(xpath: string): Element[];
get(xpath: string): Element | undefined;
node(name: string, content: string): Element;
root(): Element;
toString(): string;
validate(xsdDoc: XMLDocument): boolean;
validationErrors: XmlError[];
version(): Number;
get(xpath: string): Element|null;
node(name: string, content?: string): Element;
root(): Element|null;
root(newRoot: Node): Node;
toString(formatted?: boolean): string;
type(): 'document';
version(): string;
setDtd(name: string, ext: string, sys: string): void;
getDtd(): {
name: string;
externalId: string;
systemId: string;
};
}
export declare class HTMLDocument extends XMLDocument {
export class Node {
doc(): Document;
parent(): Element|Document;
/**
* The namespace or null in case of comment nodes
*/
namespace(): Namespace|null;
/**
* An array of namespaces that the object belongs to.
*
* @param local If it is true, only the namespace declarations local to this
* node are returned, rather than all of the namespaces in scope
* at this node (including the ones from the parent elements).
*/
namespaces(local?: boolean): Namespace[];
prevSibling(): Node|null;
nextSibling(): Node|null;
type(): 'comment'|'element'|'text'|'attribute';
remove(): this;
clone(): this;
/**
* Serializes the node to a string. The string will contain all contents of the node formatted as XML and can be used to print the node.
*/
toString(format?: boolean|{
declaration: boolean;
selfCloseEmpty: boolean;
whitespace: boolean;
type: 'xml'|'html'|'xhtml'
}): string;
}
export declare class Element {
constructor(doc: XMLDocument, name: string, content?: string);
export class Element extends Node {
constructor(doc: Document, name: string, content?: string);
node(name: string, content?: string): Element;
name(): string;
name(newName: string): void;
name(newName: string): this;
text(): string;
attr(name: string): Attribute;
attr(attr: Attribute): void;
attr(attrObject: { [key: string]: string; }): void;
text(newText: string): this;
attr(name: string): Attribute|null;
attr(attrObject: { [key: string]: string; }): this;
attrs(): Attribute[];
parent(): Element;
doc(): XMLDocument;
child(idx: number): Element | undefined;
childNodes(): Element[];
addChild(child: Element): Element;
nextSibling(): Element;
nextElement(): Element;
addNextSibling(siblingNode: Element): Element;
prevSibling(): Element;
prevElement(): Element;
addPrevSibling(siblingNode: Element): Element;
find(xpath: string): Element[];
find(xpath: string, ns_uri: string): Element[];
find(xpath: string, namespaces: { [key: string]: string; }): Element[];
get(xpath: string): Element | undefined;
get(xpath: string, ns_uri: string): Element | undefined;
get(xpath: string, ns_uri: { [key: string]: string; }): Element | undefined;
defineNamespace(href: string): Namespace;
defineNamespace(prefix: string, href: string): Namespace;
namespace(): Namespace;
namespace(ns: Namespace): void;
namespace(href: string): void;
namespace(prefix: string, href: string): void;
remove(): void;
doc(): Document;
child(idx: number): Node | null;
childNodes(): Node[];
/**
* @return The original element, not the child.
*/
addChild(child: Element): this;
prevElement(): Element|null;
nextElement(): Element|null;
addNextSibling(siblingNode: Node): Node;
find(xpath: string, ns_uri?: string): Node[];
find(xpath: string, namespaces: { [key: string]: string; }): Node[];
get(xpath: string, ns_uri?: string): Element|null;
defineNamespace(prefixOrHref: string, hrefInCaseOfPrefix?: string): Namespace;
namespace(): Namespace|null;
namespace(newNamespace: Namespace): this;
namespace(prefixOrHref: string, hrefInCaseOfPrefix?: string): Namespace;
replace(replacement: string): string;
replace(replacement: Element): Element;
path(): string;
type(): string;
}
export declare class Attribute {
constructor(node: Element, name: string, value: string);
constructor(node: Element, name: string, value: string, ns: Namespace);
export class Attribute {
name(): string;
namespace(): Namespace;
namespace(ns: Namespace): Namespace;
nextSibling(): Attribute;
node(): Element;
prevSibling(): Attribute;
remove(): void;
value(): string;
value(newValue: string): Attribute;
namespace(): Namespace;
remove(): void;
}
export declare class Namespace {
constructor(node: Element, prefix: string, href: string);
export class Namespace {
href(): string;
prefix(): string;
}
export declare class SaxParser extends events.EventEmitter {
export class SaxParser extends EventEmitter {
constructor();
parseString(source: string): boolean;
}
export declare class SaxPushParser extends events.EventEmitter {
export class SaxPushParser extends EventEmitter {
constructor();
push(source: string): boolean;
}
export interface XmlError {
domain: number;
code: number;
message: string;
level: number;
file?: string;
export interface SyntaxError {
domain: number|null;
code: number|null;
message: string|null;
level: number|null;
file: string|null;
line: number|null;
/**
* 1-based column number, 0 if not applicable/available.
*/
column: number;
line: number;
str1: number|null;
str2: number|null;
str3: number|null;
int1: number|null;
}
+20 -19
View File
@@ -1,7 +1,6 @@
import * as libxmljs from 'libxmljs';
var libxmljs = require("libxmljs");
var xml = '<?xml version="1.0" encoding="UTF-8"?>' +
const xml = '<?xml version="1.0" encoding="UTF-8"?>' +
'<root>' +
'<child foo="bar">' +
'<grandchild baz="fizbuzz">grandchild content</grandchild>' +
@@ -9,40 +8,42 @@ var xml = '<?xml version="1.0" encoding="UTF-8"?>' +
'<sibling>with content!</sibling>' +
'</root>';
var xmlDoc = libxmljs.parseXml(xml);
const xmlDoc = libxmljs.parseXml(xml);
// xpath queries
var gchild = xmlDoc.get('//grandchild');
const gchild = xmlDoc.get('//grandchild')!;
console.log(gchild.text()); // prints "grandchild content"
var children = xmlDoc.root().childNodes();
var child = children[0];
const children = xmlDoc.root()!.childNodes();
const child = children[0] as libxmljs.Element;
console.log(child.attr('foo').value()); // prints "bar"
console.log(child.attr('foo')!.value()); // prints "bar"
var parser = new libxmljs.SaxParser();
const parser = new libxmljs.SaxParser();
parser.on('startDocument', null);
parser.on('startElement', null);
parser.on('startDocument', () => 0);
parser.on('startElement', () => 0);
var parser2 = new libxmljs.SaxPushParser();
const parser2 = new libxmljs.SaxPushParser();
// connect any callbacks here
parser2
.on('startDocument', null)
.on('startElement', null)
.on('startDocument', () => 0)
.on('startElement', () => 0);
var xmlChunk: any;
const xmlChunk = '';
while(xmlChunk) {
while (xmlChunk) {
parser2.push(xmlChunk);
}
var doc = new libxmljs.Document();
doc.node('root')
const doc = new libxmljs.Document();
((doc.node('root')
.node('child').attr({foo: 'bar'})
.node('grandchild', 'grandchild content').attr({baz: 'fizbuzz'})
.parent()
.parent()
) as libxmljs.Element).parent()
.node('sibling', 'with content!');
const {name, externalId, systemId} = doc.getDtd();
+1 -1
View File
@@ -6,7 +6,7 @@
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
+1 -79
View File
@@ -1,79 +1 @@
{
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
}
}
{ "extends": "dtslint/dt.json" }
+17 -39
View File
@@ -1,59 +1,37 @@
// Type definitions for node-libxslt
// Type definitions for node-libxslt 0.7
// Project: https://github.com/albanm/node-libxslt
// Definitions by: Alejandro Sánchez <https://github.com/alejo90>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="libxmljs" />
// TypeScript Version: 2.2
import * as xmljs from 'libxmljs';
import {
ApplyCallback,
ApplyResult,
ApplyStringCallback,
OutputFormat,
ParseCallback
} from './internal-types';
export const libxmljs: typeof xmljs;
type OutputFormat = 'document' | 'string';
export interface ApplyOptions {
outputFormat?: OutputFormat;
noWrapParams?: boolean;
}
type ApplyResult = string | xmljs.XMLDocument;
type ApplyCallback = (err: Error, result: ApplyResult) => void;
type ApplyStringCallback = (err: Error, result: string) => void;
type ApplyDocumentCallback = (err: Error, result: xmljs.XMLDocument) => void;
export interface Stylesheet {
apply(source: string, params?: Object): string;
apply(source: string, params: Object, options: ApplyOptions): ApplyResult;
apply(source: string, params: Object, options: ApplyOptions, callback: ApplyCallback): void;
apply(source: string, callback: ApplyStringCallback): void;
apply(source: xmljs.XMLDocument, params?: Object): xmljs.XMLDocument;
apply(source: xmljs.XMLDocument, params: Object, options: ApplyOptions): ApplyResult;
apply(source: xmljs.XMLDocument, params: Object, options: ApplyOptions, callback: ApplyCallback): void;
apply(source: xmljs.XMLDocument, callback: ApplyDocumentCallback): void;
applyToFile(sourcePath: string, params: Object, options: ApplyOptions, callback: ApplyStringCallback): void;
apply(source: string, params?: object): string;
apply(source: string|xmljs.Document, params: object, options: ApplyOptions): ApplyResult;
apply(source: string|xmljs.Document, params: object, options: ApplyOptions, callback: ApplyCallback): void;
apply(source: string|xmljs.Document, callback: ApplyStringCallback): void;
apply(source: xmljs.Document, params?: object): xmljs.Document;
applyToFile(sourcePath: string, params: object, options: ApplyOptions, callback: ApplyStringCallback): void;
applyToFile(sourcePath: string, callback: ApplyStringCallback): void;
}
type ParseCallback = (err: Error, stylesheet: Stylesheet) => void;
export function parse(source: string): Stylesheet;
export function parse(source: string, callback: ParseCallback): void;
export function parse(source: xmljs.XMLDocument): Stylesheet;
export function parse(source: xmljs.XMLDocument, callback: ParseCallback): void;
export function parse(source: string|xmljs.Document): Stylesheet;
export function parse(source: string|xmljs.Document, callback: ParseCallback): void;
export function parseFile(sourcePath: string, callback: ParseCallback): void;
+11
View File
@@ -0,0 +1,11 @@
import * as xmljs from 'libxmljs';
import { Stylesheet } from './index';
export type OutputFormat = 'document' | 'string';
export type ApplyResult = string | xmljs.Document;
export type ApplyCallback = (err: Error, result: ApplyResult) => void;
export type ApplyStringCallback = (err: Error, result: string) => void;
export type ApplyDocumentCallback = (err: Error, result: xmljs.Document) => void;
export type ParseCallback = (err: Error, stylesheet: Stylesheet) => void;
+2 -2
View File
@@ -1,7 +1,7 @@
import * as libxslt from 'libxslt';
import * as libxmljs from 'libxmljs';
const document: libxmljs.XMLDocument = libxslt.libxmljs.parseXmlString('<xml></xml>');
const document: libxmljs.Document = libxslt.libxmljs.parseXmlString('<xml></xml>');
let stylesheet: libxslt.Stylesheet;
@@ -36,7 +36,7 @@ applyOptions = {
let transformedString: string;
let transformedDocument: libxmljs.XMLDocument;
let transformedDocument: libxmljs.Document;
transformedString = stylesheet.apply('<xml></xml>');
+1
View File
@@ -18,6 +18,7 @@
},
"files": [
"index.d.ts",
"internal-types.d.ts",
"libxslt-tests.ts"
]
}
+1 -79
View File
@@ -1,79 +1 @@
{
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
}
}
{ "extends": "dtslint/dt.json" }
+1
View File
@@ -2,6 +2,7 @@
// Project: https://github.com/zeit/next.js
// Definitions by: Drew Hays <https://github.com/dru89>
// Brice BERNARD <https://github.com/brikou>
// Scott Jones <https://github.com/scottdj92>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
+9 -5
View File
@@ -9,10 +9,7 @@ export interface EventChangeOptions {
}
export type RouterCallback = () => void;
export interface SingletonRouter {
readyCallbacks: RouterCallback[];
ready(cb: RouterCallback): void;
export interface RouterProps {
// router properties
readonly components: {
[key: string]: { Component: React.ComponentType<any>; err: any };
@@ -53,9 +50,16 @@ export interface SingletonRouter {
onRouteChangeError?(error: any, url: string): void;
}
export interface SingletonRouter {
router: RouterProps;
readyCallbacks: RouterCallback[];
ready(cb: RouterCallback): void;
}
export function withRouter<T extends {}>(
Component: React.ComponentType<T & { router: SingletonRouter }>,
Component: React.ComponentType<T & SingletonRouter>,
): React.ComponentType<T>;
export const Singleton: SingletonRouter;
export type ImperativeRouter = RouterProps;
export default Singleton;
+21 -21
View File
@@ -13,8 +13,8 @@ Router.ready(() => {
// Access readonly properties of the router.
Object.keys(Router.components).forEach(key => {
const c = Router.components[key];
Object.keys(Router.router.components).forEach(key => {
const c = Router.router.components[key];
c.err.isAnAny;
return <c.Component />;
@@ -26,51 +26,51 @@ function split(routeLike: string) {
});
}
if (Router.asPath) {
split(Router.asPath);
split(Router.asPath);
if (Router.router.asPath) {
split(Router.router.asPath);
split(Router.router.asPath);
}
split(Router.pathname);
split(Router.router.pathname);
const query = `?${qs.stringify(Router.query)}`;
const query = `?${qs.stringify(Router.router.query)}`;
// Assign some callback methods.
Router.onAppUpdated = (nextRoute: string) => console.log(nextRoute);
Router.onRouteChangeStart = (url: string) =>
Router.router.onAppUpdated = (nextRoute: string) => console.log(nextRoute);
Router.router.onRouteChangeStart = (url: string) =>
console.log("Route is starting to change.", url);
Router.onBeforeHistoryChange = (as: string) =>
Router.router.onBeforeHistoryChange = (as: string) =>
console.log("History hasn't changed yet.", as);
Router.onRouteChangeComplete = (url: string) =>
Router.router.onRouteChangeComplete = (url: string) =>
console.log("Route chaneg is complete.", url);
Router.onRouteChangeError = (err: any, url: string) =>
Router.router.onRouteChangeError = (err: any, url: string) =>
console.log("Route is starting to change.", url, err);
// Call methods on the router itself.
Router.reload("/route").then(() => console.log("route was reloaded"));
Router.back();
Router.router.reload("/route").then(() => console.log("route was reloaded"));
Router.router.back();
Router.push("/route").then((success: boolean) =>
Router.router.push("/route").then((success: boolean) =>
console.log("route push success: ", success),
);
Router.push("/route", "/asRoute").then((success: boolean) =>
Router.router.push("/route", "/asRoute").then((success: boolean) =>
console.log("route push success: ", success),
);
Router.push("/route", "/asRoute", { shallow: false }).then((success: boolean) =>
Router.router.push("/route", "/asRoute", { shallow: false }).then((success: boolean) =>
console.log("route push success: ", success),
);
Router.replace("/route").then((success: boolean) =>
Router.router.replace("/route").then((success: boolean) =>
console.log("route replace success: ", success),
);
Router.replace("/route", "/asRoute").then((success: boolean) =>
Router.router.replace("/route", "/asRoute").then((success: boolean) =>
console.log("route replace success: ", success),
);
Router.replace("/route", "/asRoute", {
Router.router.replace("/route", "/asRoute", {
shallow: false,
}).then((success: boolean) => console.log("route replace success: ", success));
Router.prefetch("/route").then(Component => {
Router.router.prefetch("/route").then(Component => {
const element = <Component />;
});
+3 -1
View File
@@ -1,5 +1,7 @@
import { Object } from './object';
export class DiffBinaryFile {
type: number;
type: Object.TYPE;
data: string;
datalen: number;
inflatedlen: number;
+22 -7
View File
@@ -3,20 +3,35 @@ import { Repository } from './repository';
import { Buf } from './buf';
export class Object {
static size(type: number): number;
static lookup(repo: Repository, id: Oid, type: number): Promise<Object>;
static lookupPrefix(repo: Repository, id: Oid, len: number, type: number): Promise<Object>;
static string2type(str: string): number;
static type2string(type: number): string;
static typeisloose(type: number): number;
static size(type: Object.TYPE): number;
static lookup(repo: Repository, id: Oid, type: Object.TYPE): Promise<Object>;
static lookupPrefix(repo: Repository, id: Oid, len: number, type: Object.TYPE): Promise<Object>;
static string2Type(str: string): Object.TYPE;
static type2String(type: Object.TYPE): string;
static typeisloose(type: Object.TYPE): number;
dup(): Promise<Object>;
free(): void;
id(): Oid;
lookupByPath(path: string, type: number): Promise<Object>;
lookupByPath(path: string, type: Object.TYPE): Promise<Object>;
owner(): Repository;
peel(targetType: number): Promise<Object>;
shortId(): Promise<Buf>;
type(): number;
}
export namespace Object {
const enum TYPE {
ANY = -2,
BAD = -1,
EXT1 = 0,
COMMIT = 1,
TREE = 2,
BLOB = 3,
TAG = 4,
EXT2 = 5,
OFS_DELTA = 6,
REF_DELTA = 7
}
}
+2 -1
View File
@@ -1,7 +1,8 @@
import { Oid } from './oid';
import { Object } from './object';
export class OdbExpandId {
id: Oid;
length: number;
type: number;
type: Object.TYPE;
}
+2 -1
View File
@@ -1,6 +1,7 @@
import { Oid } from './oid';
import { OdbObject } from './odb-object';
import { OdbExpandId } from './odb-expand-id';
import { Object } from './object';
export namespace Odb {
const enum STREAM {
@@ -17,6 +18,6 @@ export class Odb {
free(): void;
read(id: Oid): Promise<OdbObject>;
write(data: Buffer, len: number, type: number): Promise<Oid>;
write(data: Buffer, len: number, type: Object.TYPE): Promise<Oid>;
expandIds(ids: OdbExpandId, count: number): number;
}
+1 -1
View File
@@ -41,7 +41,7 @@ export class Reference {
isTag(): number;
name(): string;
owner(): Repository;
peel(type: number): Promise<Object>;
peel(type: Object.TYPE): Promise<Object>;
rename(newName: string, force: number, logMessage: string): Promise<Reference>;
resolve(): Promise<Reference>;
setTarget(id: Oid, logMessage: string): Promise<Reference>;
+13 -47
View File
@@ -1,6 +1,6 @@
// Type definitions for qrcode 0.8.2
// Type definitions for qrcode 1.2
// Project: https://github.com/soldair/node-qrcode
// Definitions by: York Yao <https://github.com/plantain-00/>
// Definitions by: York Yao <https://github.com/plantain-00>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
@@ -22,7 +22,7 @@ export interface QRCodeOptions {
* Helper function used internally to convert a kanji to its Shift JIS value.
* Provide this function if you need support for Kanji mode.
*/
toSJISFunc?: Function;
toSJISFunc?: (codePoint: string) => number;
}
export interface QRCodeToDataURLOptions extends QRCodeRenderersOptions {
@@ -40,7 +40,7 @@ export interface QRCodeToDataURLOptions extends QRCodeRenderersOptions {
};
}
export interface QRCodeToStringOptions extends QRCodeOptions {
export interface QRCodeToStringOptions extends QRCodeRenderersOptions {
/**
* Output format.
* Default: utf8
@@ -127,10 +127,6 @@ export interface QRCode {
*/
export function create(text: string | QRCodeSegment[], options: QRCodeOptions): QRCode;
/**
* Draws qr code symbol to canvas.
*/
export function toCanvas(canvasElement: HTMLCanvasElement, text: string | QRCodeSegment[]): Promise<any>;
/**
* Draws qr code symbol to canvas.
*/
@@ -138,15 +134,11 @@ export function toCanvas(canvasElement: HTMLCanvasElement, text: string | QRCode
/**
* Draws qr code symbol to canvas.
*/
export function toCanvas(canvasElement: HTMLCanvasElement, text: string | QRCodeSegment[], options: QRCodeOptions): Promise<any>;
export function toCanvas(canvasElement: HTMLCanvasElement, text: string | QRCodeSegment[], options?: QRCodeOptions): Promise<any>;
/**
* Draws qr code symbol to canvas.
*/
export function toCanvas(canvasElement: HTMLCanvasElement, text: string | QRCodeSegment[], options: QRCodeOptions, callback: (error: Error) => void): void;
/**
* Draws qr code symbol to canvas.
*/
export function toCanvas(text: string | QRCodeSegment[]): Promise<any>;
/**
* Draws qr code symbol to canvas.
*/
@@ -154,15 +146,11 @@ export function toCanvas(text: string | QRCodeSegment[], callback: (error: Error
/**
* Draws qr code symbol to canvas.
*/
export function toCanvas(text: string | QRCodeSegment[], options: QRCodeOptions): Promise<any>;
export function toCanvas(text: string | QRCodeSegment[], options?: QRCodeOptions): Promise<any>;
/**
* Draws qr code symbol to canvas.
*/
export function toCanvas(text: string | QRCodeSegment[], options: QRCodeOptions, callback: (error: Error, canvas: HTMLCanvasElement) => void): void;
/**
* Draws qr code symbol to node canvas.
*/
export function toCanvas(canvas: any, text: string | QRCodeSegment[]): Promise<any>;
/**
* Draws qr code symbol to node canvas.
*/
@@ -170,16 +158,12 @@ export function toCanvas(canvas: any, text: string | QRCodeSegment[], callback:
/**
* Draws qr code symbol to node canvas.
*/
export function toCanvas(canvas: any, text: string | QRCodeSegment[], options: QRCodeOptions): Promise<any>;
export function toCanvas(canvas: any, text: string | QRCodeSegment[], options?: QRCodeOptions): Promise<any>;
/**
* Draws qr code symbol to node canvas.
*/
export function toCanvas(canvas: any, text: string | QRCodeSegment[], options: QRCodeOptions, callback: (error: Error) => void): void;
/**
* Returns a Data URI containing a representation of the QR Code image.
*/
export function toDataURL(canvasElement: HTMLCanvasElement, text: string | QRCodeSegment[]): Promise<any>;
/**
* Returns a Data URI containing a representation of the QR Code image.
*/
@@ -187,15 +171,12 @@ export function toDataURL(canvasElement: HTMLCanvasElement, text: string | QRCod
/**
* Returns a Data URI containing a representation of the QR Code image.
*/
export function toDataURL(canvasElement: HTMLCanvasElement, text: string | QRCodeSegment[], options: QRCodeToDataURLOptions): Promise<any>;
export function toDataURL(canvasElement: HTMLCanvasElement, text: string | QRCodeSegment[], options?: QRCodeToDataURLOptions): Promise<any>;
/**
* Returns a Data URI containing a representation of the QR Code image.
*/
export function toDataURL(canvasElement: HTMLCanvasElement, text: string | QRCodeSegment[], options: QRCodeToDataURLOptions, callback: (error: Error, url: string) => void): void;
/**
* Returns a Data URI containing a representation of the QR Code image.
*/
export function toDataURL(text: string | QRCodeSegment[]): Promise<any>;
/**
* Returns a Data URI containing a representation of the QR Code image.
*/
@@ -203,17 +184,12 @@ export function toDataURL(text: string | QRCodeSegment[], callback: (error: Erro
/**
* Returns a Data URI containing a representation of the QR Code image.
*/
export function toDataURL(text: string | QRCodeSegment[], options: QRCodeToDataURLOptions): Promise<any>;
export function toDataURL(text: string | QRCodeSegment[], options?: QRCodeToDataURLOptions): Promise<any>;
/**
* Returns a Data URI containing a representation of the QR Code image.
*/
export function toDataURL(text: string | QRCodeSegment[], options: QRCodeToDataURLOptions, callback: (error: Error, url: string) => void): void;
/**
* Returns a string representation of the QR Code.
* If choosen output format is svg it will returns a string containing xml code.
*/
export function toString(text: string | QRCodeSegment[]): Promise<any>;
/**
* Returns a string representation of the QR Code.
* If choosen output format is svg it will returns a string containing xml code.
@@ -223,19 +199,13 @@ export function toString(text: string | QRCodeSegment[], callback: (error: Error
* Returns a string representation of the QR Code.
* If choosen output format is svg it will returns a string containing xml code.
*/
export function toString(text: string | QRCodeSegment[], options: QRCodeToStringOptions): Promise<any>;
export function toString(text: string | QRCodeSegment[], options?: QRCodeToStringOptions): Promise<any>;
/**
* Returns a string representation of the QR Code.
* If choosen output format is svg it will returns a string containing xml code.
*/
export function toString(text: string | QRCodeSegment[], options: QRCodeToStringOptions, callback: (error: Error, string: string) => void): void;
/**
* Saves QR Code to image file.
* If options.type is not specified, the format will be guessed from file extension.
* Recognized extensions are png, svg, txt.
*/
export function toFile(path: string, text: string | QRCodeSegment[]): Promise<any>;
/**
* Saves QR Code to image file.
* If options.type is not specified, the format will be guessed from file extension.
@@ -247,7 +217,7 @@ export function toFile(path: string, text: string | QRCodeSegment[], callback: (
* If options.type is not specified, the format will be guessed from file extension.
* Recognized extensions are png, svg, txt.
*/
export function toFile(path: string, text: string | QRCodeSegment[], options: QRCodeToFileOptions): Promise<any>;
export function toFile(path: string, text: string | QRCodeSegment[], options?: QRCodeToFileOptions): Promise<any>;
/**
* Saves QR Code to image file.
* If options.type is not specified, the format will be guessed from file extension.
@@ -255,10 +225,6 @@ export function toFile(path: string, text: string | QRCodeSegment[], options: QR
*/
export function toFile(path: string, text: string | QRCodeSegment[], options: QRCodeToFileOptions, callback: (error: Error) => void): void;
/**
* Writes QR Code image to stream. Only works with png format for now.
*/
export function toFileStream(stream: stream.Writable, text: string | QRCodeSegment[]): Promise<any>;
/**
* Writes QR Code image to stream. Only works with png format for now.
*/
@@ -266,7 +232,7 @@ export function toFileStream(stream: stream.Writable, text: string | QRCodeSegme
/**
* Writes QR Code image to stream. Only works with png format for now.
*/
export function toFileStream(stream: stream.Writable, text: string | QRCodeSegment[], options: QRCodeOptions): Promise<any>;
export function toFileStream(stream: stream.Writable, text: string | QRCodeSegment[], options?: QRCodeOptions): Promise<any>;
/**
* Writes QR Code image to stream. Only works with png format for now.
*/
+10 -10
View File
@@ -2,31 +2,31 @@ import * as QRCode from 'qrcode';
const canvas = document.getElementById('canvas') as HTMLCanvasElement;
QRCode.toCanvas(canvas, 'sample text', function (error) {
if (error) console.error(error)
QRCode.toCanvas(canvas, 'sample text', (error) => {
if (error) console.error(error);
console.log('success!');
});
QRCode.toDataURL('I am a pony!', function (err, url) {
QRCode.toDataURL('I am a pony!', (err, url) => {
console.log(url);
});
QRCode.toDataURL('some text', { errorCorrectionLevel: 'H' }, function (err, url) {
QRCode.toDataURL('some text', { errorCorrectionLevel: 'H' }, (err, url) => {
console.log(url);
});
QRCode.toDataURL('some text', { version: 2 }, function (err, url) {
QRCode.toDataURL('some text', { version: 2 }, (err, url) => {
console.log(url);
});
QRCode.toDataURL([
{ data: 'ABCDEFG', mode: 'alphanumeric' },
{ data: '0123456', mode: 'numeric' }
], function (err, url) {
], (err, url) => {
console.log(url);
});
QRCode.toCanvas('text', { errorCorrectionLevel: 'H' }, function (err, canvas) {
QRCode.toCanvas('text', { errorCorrectionLevel: 'H' }, (err, canvas) => {
if (err) throw err;
});
@@ -36,11 +36,11 @@ QRCode.toDataURL('text', {
rendererOpts: {
quality: 0.3
}
}, function (err, url) {
}, (err, url) => {
if (err) throw err;
});
QRCode.toString('http://www.google.com', function (err, string) {
QRCode.toString('http://www.google.com', (err, string) => {
if (err) throw err;
console.log(string);
});
@@ -50,7 +50,7 @@ QRCode.toFile('path/to/filename.png', 'Some text', {
dark: '#00F', // Blue dots
light: '#0000' // Transparent background
}
}, function (err) {
}, (err) => {
if (err) throw err;
console.log('done');
});
+1 -74
View File
@@ -1,79 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
"unified-signatures": false
}
}
+661
View File
@@ -0,0 +1,661 @@
// Type definitions for re-base 3.2
// Project: https://github.com/tylermcginnis/re-base#readme
// Definitions by: jordandrako <https://github.com/jordandrako>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
export interface RebaseBinding {
context: object;
endpoint: string;
id: number;
method: string;
}
export interface SyncStateOptions {
/**
* The context of your component.
*/
context: object;
/**
* The state property you want to sync with Firebase; can be an
* arbitrarily nested property a là `foo.bar`.
*/
state: string;
/**
* A default value to set when the Firebase endpoint has no value (i.e.,
* on init) (use this if you want a value other than an empty object or
* empty array)
*/
defaultValue?: string | boolean | number | object;
/**
* Returns the Firebase data at the specified endpoint as an Array
* instead of an Object.
*/
asArray?: boolean;
/**
* Will keep any firebase generated keys intact when manipulating data
* using the asArray option.
*/
keepKeys?: boolean;
/**
* Queries to be used with your read operations. See
* [Query Options](https://github.com/tylermcginnis/re-base#queries)
* for more details.
*/
queries?: object;
/**
* The callback function that will be invoked when the initial listener
* is established with Firebase. Typically used (with syncState) to
* change this.state.loading to false.
*/
then?: () => void;
/**
* A callback function that will be invoked if the current user does
* not have read or write permissions at the location.
*/
onFailure?: () => void;
}
export interface BindToStateOptions {
/**
* The context of your component.
*/
context: object;
/**
* The state property you want to sync with Firebase; can be an
* arbitrarily nested property a là `foo.bar` (no arrays).
*/
state: string;
/**
* Returns the Firebase data at the specified endpoint as an Array
* instead of an Object.
*/
asArray?: boolean;
/**
* Queries to be used with your read operations. See
* [Query Options](https://github.com/tylermcginnis/re-base#queries)
* for more details.
*/
queries?: object;
/**
* The callback function that will be invoked when the initial listener
* is established with Firebase. Typically used (with bindToState) to
* change this.state.loading to false.
*/
then?: () => void;
/**
* A callback function that will be invoked if the current user does
* not have read permissions at the location.
*/
onFailure?: () => void;
}
export interface ListenToOptions {
/**
* The context of your component.
*/
context: object;
/**
* Returns the Firebase data at the specified endpoint as an Array
* instead of an Object.
*/
asArray?: boolean;
/**
* The callback function that will be invoked with the data from the
* specified endpoint when the endpoint changes.
*/
then: (result: any) => void;
/**
* The callback function that will be invoked if the current user does
* not have read permissions at the location.
*/
onFailure?: (error: any) => void;
/**
* Queries to be used with your read operations. See
* [Query Options](https://github.com/tylermcginnis/re-base#queries)
* for more details.
*/
queries?: object;
}
export interface FetchOptions {
/**
* The context of your component.
*/
context: object;
/**
* Returns the Firebase data at the specified endpoint as an Array
* instead of an Object.
*/
asArray?: boolean;
/**
* The callback function that will be invoked with the data from the
* specified endpoint when the endpoint changes.
*/
then?: (result: any) => void;
/**
* The callback function that will be invoked with an error that occurs
* reading data from the specified endpoint.
*/
onFailure?: () => void;
/**
* Queries to be used with your read operations. See
* [Query Options](https://github.com/tylermcginnis/re-base#queries)
* for more details.
*/
queries?: object;
}
export interface PostOptions {
/**
* The data you're wanting to persist to Firebase.
*/
data: any;
/**
* A callback that will get invoked once the new data has been saved to
* Firebase. If there is an error, it will be the only argument to this
* function.
*/
then?: (result: any) => void;
}
export interface PushOptions {
/**
* The data you're wanting to persist to Firebase.
*/
data: any;
/**
* A callback that will get invoked once the new data has been saved to
* Firebase. If there is an error, it will be the only argument to this
* function.
*/
then?: (result: any) => void;
}
export interface UpdateOptions {
/**
* The data you're wanting to persist to Firebase.
*/
data: any;
/**
* A callback that will get invoked once the new data has been saved to
* Firebase. If there is an error, it will be the only argument to this
* function.
*/
then?: (result: any) => void;
}
export interface bindDocOptions {
/**
* The context of your component.
*/
context: object;
/**
* A property name on your state to bind your document to, if omitted
* the document will be merged into your existing state.
*/
state?: string;
/**
* A callback that will be called when the listener is set, use for
* loading indicators.
*/
then?: () => void;
/**
* A callback that will be called with any errors such as permissions
* errors.
*/
onFailure?: () => void;
}
export interface listenToDocOptions {
/**
* The context of your component.
*/
context: object;
/**
* A callback that will be called when the listener is set, use for
* loading indicators.
*/
then?: () => void;
/**
* A callback that will be called with any errors such as permissions
* errors.
*/
onFailure?: () => void;
}
export interface bindCollectionOptions {
/**
* The context of your component.
*/
context: object;
/**
* The state property to bind the collection to.
*/
state?: string;
/**
* A function that receives the created ref as its only argument. You
* can chain any Firestore queries you want to perform. See
* [Using Firestore Queries](https://github.com/tylermcginnis/re-base#firestorequeries).
*/
query?: () => void;
/**
* Will embed firestore generated document ids inside each document in
* your collections on the `id` property.
*/
withIds?: boolean;
/**
* will embed the DocumentReference inside each document in your
* collection on the `ref` property.
*/
withRefs?: boolean;
/**
* A callback that will be called when the listener is set, use for
* loading indicators.
*/
then?: () => void;
/**
* A callback that will be called with any errors such as permissions
* errors.
*/
onFailure?: () => void;
}
export interface listenToCollectionOptions {
/**
* The context of your component.
*/
context: object;
/**
* A callback that will be called with the data.
*/
then: () => void;
/**
* A function that receives the created ref as its only argument. You
* can chain any Firestore queries you want to perform. See
* [Using Firestore Queries](https://github.com/tylermcginnis/re-base#firestorequeries).
*/
query?: () => void;
/**
* Will embed firestore generated document ids inside each document in
* your collections on the `id` property.
*/
withIds?: boolean;
/**
* will embed the DocumentReference inside each document in your
* collection on the `ref` property.
*/
withRefs?: boolean;
/**
* A callback that will be called with any errors such as permissions
* errors.
*/
onFailure?: () => void;
}
export interface getOptions {
/**
* A function that receives the created ref as its only argument. You
* can chain any Firestore queries you want to perform. See
* [Using Firestore Queries](https://github.com/tylermcginnis/re-base#firestorequeries).
*/
query?: () => void;
/**
* Will embed firestore generated document ids inside each document in
* your collections on the `id` property.
*/
withIds?: boolean;
/**
* will embed the DocumentReference inside each document in your
* collection on the `ref` property.
*/
withRefs?: boolean;
}
export interface removeFromCollectionOptions {
/**
* A function that receives the created ref as its only argument. You
* can chain any Firestore queries you want to perform. See
* [Using Firestore Queries](https://github.com/tylermcginnis/re-base#firestorequeries).
*/
query?: () => void;
}
export interface syncDocOptions {
/**
* The context of your component.
*/
context: object;
/**
* The state property to sync.
*/
state: string;
/**
* A callback that will be called when the listener is set, use for
* loading indicators.
*/
then?: () => void;
/**
* A callback that will be called with any errors such as permissions
* errors.
*/
onFailure?: () => void;
}
export interface Rebase {
/**
* This property contains the initialized firebase app that was passed
* into re-base. You can access any of the firebase services that you
* are using off this object. For instance, if you want to use some
* firebase database methods that re-base doesn't have helpers for or
* if you are using the auth service and want to quickly access it off
* of re-base.
*/
initializedApp: object;
/**
* This property contains an object that you can use when adding data
* that will be converted to a timestamp by Firebase. See
* [the docs](https://firebase.google.com/docs/reference/js/firebase.database.ServerValue)
* for more info.
*/
timestamp: object;
/**
* Allows you to set up two way data binding between your component's
* state and your Firebase. Whenever your Firebase changes, your
* component's state will change. Whenever your component's state
* changes, Firebase will change.
* @param endpoint The relative Firebase endpoint to which you'd like
* to bind your component's state.
* @param options syncState Options.
* @returns An object which you can pass to `removeBinding` if you want
* to remove the listener while the component is still mounted.
*/
syncState(endpoint: string, options: SyncStateOptions): RebaseBinding;
/**
* One way data binding from Firebase to your component's state. Allows
* you to bind a component's state property to a Firebase endpoint so
* whenever that Firebase endpoint changes, your component's state will
* be updated with that change.
* @param endpoint The relative Firebase endpoint that you'd like to
* bind to your component's state.
* @param options bindToState Options.
* @returns An object which you can pass to `removeBinding` if you want
* to remove the listener while the component is still mounted.
*/
bindToState(endpoint: string, options: BindToStateOptions): RebaseBinding;
/**
* Allows you to listen to Firebase endpoints without binding those
* changes to a state property. Instead, a callback will be invoked
* with the newly updated data.
* @param endpoint The relative Firebase endpoint which contains the
* data with which you'd like to invoke your callback function.
* @param options listenTo Options.
* @returns An object which you can pass to `removeBinding` when your
* component unmounts to remove the Firebase listeners.
*/
listenTo(endpoint: string, options: ListenToOptions): RebaseBinding;
/**
* Allows you to retrieve the data from a Firebase endpoint just once
* without subscribing or listening for data changes.
* @param endpoint The relative Firebase endpoint which contains the
* data you're wanting to fetch.
* @param options fetch Options.
* @returns A Firebase [Promise](https://firebase.google.com/docs/reference/js/firebase.Promise)
* which resolves when the write is complete and rejects if there is an
* error.
*/
fetch(endpoint: string, options: FetchOptions): Promise<any>;
/**
* Allows you to update a Firebase endpoint with new data. *Replace all
* the data at this endpoint with the new data*.
* @param endpoint The relative Firebase endpoint that you'd like to
* update with the new data.
* @param options post Options.
* @returns A Firebase [Promise](https://firebase.google.com/docs/reference/js/firebase.Promise)
* which resolves when the write is complete and rejects if there is an
* error.
*/
post(endpoint: string, options: PostOptions): Promise<any>;
/**
* Allows you to add data to a Firebase endpoint. *Adds data to a child
* of the endpoint with a new Firebase push key*.
* @param endpoint The relative Firebase endpoint that you'd like to
* push the new data to.
* @param options push Options.
* @returns A Firebase [ThenableReference](https://firebase.google.com/docs/reference/js/firebase.database.ThenableReference)
* which is defined by Firebase as a "Combined Promise and reference;
* resolves when write is complete, but can be used immediately as the
* reference to the child location."
*/
push(endpoint: string, options: PushOptions): Promise<any>;
/**
* Allows you to update data at a Firebase endpoint changing only the
* properties you pass to it. **Warning: calling update with
* `options.data` being null will remove all the data at that
* endpoint**.
* @param endpoint The relative Firebase endpoint that you'd like to
* update.
* @param options update Options.
* @returns A Firebase [Promise](https://firebase.google.com/docs/reference/js/firebase.Promise)
* which resolves when the write is complete and rejects if there is an
* error.
*/
update(endpoint: string, options: UpdateOptions): Promise<any>;
/**
* Allows you to delete all data at the endpoint location.
* @param endpoint The relative Firebase endpoint that you'd like to
* delete data from.
* @param callback A callback that will get invoked once the data is
* successfully removed Firebase. If there is an error, it will be the
* only argument to this function.
* @returns A Firebase [Promise](https://firebase.google.com/docs/reference/js/firebase.Promise)
* which resolves when the write is complete and rejects if there is an
* error.
*/
remove(
endpoint: string,
callback?: (result: Promise<any>) => void
): Promise<any>;
/**
* Bind a document to your component. When then document changes in
* firestore, your component will re-render with the latest data.
* @param refOrPath DocumentReference or path.
* @param options bindDoc Options.
* @returns An object which you can pass to `removeBinding` if you want
* to remove the listener while the component is still mounted.
*/
bindDoc(refOrPath: object | string, options: bindDocOptions): object;
/**
* Listen to a document, when the data changes it will invoke a
* callback passing it the new data from Firestore.
* @param refOrPath DocumentReference or path.
* @param options listenToDoc Options.
* @returns An object which you can pass to `removeBinding` if you want
* to remove the listener while the component is still mounted.
*/
listenToDoc(
refOrPath: object | string,
options: listenToDocOptions
): object;
/**
* Bind a collection to a state property in your component. When then
* collection changes in firestore, your component will re-render with
* the latest data.
* @param refOrPath CollectionReference or path.
* @param options bindCollection Options.
* @returns An object which you can pass to `removeBinding` if you want
* to remove the listener while the component is still mounted.
*/
bindCollection(
refOrPath: object | string,
options: bindCollectionOptions
): RebaseBinding;
/**
* Listen to a collection, when the data changes it will invoke a
* callback passing it the new data from Firestore.
* @param refOrPath CollectionReference or path.
* @param options listenToCollection Options.
* @returns An object which you can pass to `removeBinding` if you want
* to remove the listener while the component is still mounted.
*/
listenToCollection(
refOrPath: object | string,
options: listenToCollectionOptions
): RebaseBinding;
/**
* Fetch either a Collection or Document.
* @param refOrPath CollectionReference, DocumentReference or path.
* @param options get Options.
* @returns A Promise thats resolve with the resulting data or rejects
* if the document/collection does not exist or there are any read
* errors.
*/
get(
refOrPath: object | object | string,
options: listenToCollectionOptions
): Promise<any>;
/**
* Add a new Document to a Collection.
* @param refOrPath CollectionReference or path.
* @param data The document data.
* @param id The id for the document. If omitted, the Firestore will
* generate an id for you.
* @returns A Promise thats resolve with the resulting data or rejects
* if the document/collection does not exist or there are any read
* errors.
*/
addToCollection(
refOrPath: object | string,
data: object,
id?: string
): Promise<any>;
/**
* Update an existing document.
* @param refOrPath DocumentReference or path.
* @param data The document data.
* @returns A Promise thats resolve with the resulting data or rejects
* if the document/collection does not exist or there are any read
* errors.
*/
updateDoc(refOrPath: object | string, data: object): Promise<any>;
/**
* Deletes a document.
* @param refOrPath DocumentReference or path.
* @param data The document data.
* @returns A Promise thats resolve with the resulting data or rejects
* if the document/collection does not exist or there are any read
* errors.
*/
removeDoc(refOrPath: object | string, data: object): Promise<any>;
/**
* Removes documents from a collection. If no query is supplied, it
* will remove all the documents. If a query is supplied, it will only
* remove documents that match the query.
* @param refOrPath CollectionReference or path.
* @param options removeFromCollection Options.
* @returns A Promise thats resolve with the resulting data or rejects
* if the document/collection does not exist or there are any read
* errors.
*/
removeFromCollection(
refOrPath: object | string,
options: removeFromCollectionOptions
): Promise<any>;
/**
* Syncs a component's local state with a document in Firestore.
* @param refOrPath DocumentReference or path.
* @param options removeFromCollection Options.
* @returns A Promise thats resolve with the resulting data or rejects
* if the document/collection does not exist or there are any read
* errors.
*/
syncDoc(refOrPath: object | string, options: syncDocOptions): object;
/**
* Clean up a listener. Listeners are automatically cleaned up when
* components unmount, however if you wish to remove a listener while
* the component is still mounted this will allow you to do that. An
* example would be if you want to start listening to a new document or
* change a query on all collection in response to a prop change.
* @param ref The return value of syncState`, `bindToState`, `listenTo`,
* `listenToCollection`, `bindCollection`, `listenToDoc`, `bindDoc` or
* `syncDoc`.
*/
removeBinding(ref: object): void;
/**
* Removes every Firebase/Firestore listener.
*/
reset(): void;
}
/**
* Accepts an initialized firebase/firestore database object.
* @param database Initialized firebase/firestore
* database.
* @return An instance of re-base.
*/
export function createClass(database: object): Rebase;
+10
View File
@@ -0,0 +1,10 @@
import * as rebase from "re-base";
const database = {};
const base = rebase.createClass(database);
const bar = {};
const _ref = base.syncState("foo", {
context: bar,
state: "foo"
});
+16
View File
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es6"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictFunctionTypes": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": ["../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": ["index.d.ts", "re-base-tests.ts"]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+122 -62
View File
@@ -1,71 +1,131 @@
// Type definitions for react-calendar-timeline v0.8.1
// Type definitions for react-calendar-timeline v0.16.3
// Project: https://github.com/namespace-ee/react-calendar-timeline
// Definitions by: Rajab Shakirov <https://github.com/radziksh>
// Alex Maclean <https://github.com/acemac>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
/// <reference types="react"/>
declare module "react-calendar-timeline" {
interface ReactCalendarTimeline {
groups: {
id: number;
title: any; // string | Element (React.ClassicComponentClass<any>);
}[];
items:{
id: number;
group: number;
title?: any; // string | Element (React.ClassicComponentClass<any>);
start_time: any;
end_time: any;
canMove?: boolean;
canResize?: boolean;
canChangeGroup?: boolean;
className?: string;
}[];
keys?:{
groupIdKey: string;
groupTitleKey: string;
itemIdKey: string;
itemTitleKey: string;
itemGroupKey: string;
itemTimeStartKey: string;
itemTimeEndKey: string;
};
sidebarWidth?: number;
dragSnap?: number;
minResizeWidth?: number;
fixedHeader?: "fixed" | "none";
zIndexStart?: number;
lineHeight?: number;
headerLabelGroupHeight?: number;
headerLabelHeight?: number;
itemHeightRatio?: number;
minZoom?: number;
maxZoom?: number;
canMove?: boolean;
canChangeGroup?: boolean;
canResize?: boolean;
useResizeHandle?: boolean;
stackItems?: boolean;
traditionalZoom?: boolean;
itemTouchSendsClick?: boolean;
onItemMove?(itemId:any, dragTime:any, newGroupOrder:any): any;
onItemResize?(itemId:any, newResizeEnd:any): any;
onItemSelect?(itemId:any): any;
onItemClick?(itemId:any): any;
onCanvasClick?(groupId:any, time:any, e:any): any;
onItemDoubleClick?(itemId:any): any;
moveResizeValidator?(action:any, itemId:any, time:any): any;
defaultTimeStart?: any;
defaultTimeEnd?: any;
visibleTimeStart?: number;
visibleTimeEnd?: number;
onTimeChange?(visibleTimeStart:any, visibleTimeEnd:any): any;
onTimeInit?(visibleTimeStart:any, visibleTimeEnd:any): any;
onBoundsChange?(canvasTimeStart:any, canvasTimeEnd:any): any;
children?: any;
}
let ReactCalendarTimeline : React.ClassicComponentClass<ReactCalendarTimeline>;
export default ReactCalendarTimeline;
export interface TimelineGroup {
id: number;
title: React.ReactNode;
rightTitle?: React.ReactNode;
}
export interface TimelineItem {
id: number;
group: number;
title?: React.ReactNode;
start_time: any;
end_time: any;
canMove?: boolean;
canResize?: boolean | "left" | "right" | "both";
canChangeGroup?: boolean;
className?: string;
itemProps?: {};
}
export interface TimelineContext {
visibletimeStart: number,
visibleTimeEnd: number,
timelineWidth: number
}
export interface TimelineTimeSteps {
second: number,
minute: number,
hour: number,
day: number,
month: number,
year: number
}
export interface TimelineHeaderLabelFormat {
yearShort: string,
yearLong: string,
monthShort: string,
monthMedium: string,
monthMediumLong: string,
monthLong: string,
dayShort: string,
dayLong: string,
hourShort: string,
hourMedium: string,
hourMediumLong: string,
hourLong: string,
time: string
}
export interface ReactCalendarTimelineProps {
groups: TimelineGroup[];
items: TimelineItem[];
keys?:{
groupIdKey: string;
groupTitleKey: string;
itemIdKey: string;
itemTitleKey: string;
itemGroupKey: string;
itemTimeStartKey: string;
itemTimeEndKey: string;
};
defaultTimeStart?: any;
defaultTimeEnd?: any;
visibleTimeStart?: any;
visibleTimeEnd?: any;
selected?: number[];
sidebarWidth?: number;
sidebarContent?: React.ReactNode;
rightSidebarWidth?: number;
rightSidebarContent?: React.ReactNode;
dragSnap?: number;
minResizeWidth?: number;
stickyOffset?: number;
stickyHeader?: boolean;
headerRef?: any;
lineHeight?: number;
headerLabelGroupHeight?: number;
headerLabelHeight?: number;
itemHeightRatio?: number;
minZoom?: number;
maxZoom?: number;
clickTolerance?: number;
canMove?: boolean;
canChangeGroup?: boolean;
canResize?: boolean | "left" | "right" | "both";
useResizeHandle?: boolean;
showCursorLine?: boolean;
stackItems?: boolean;
traditionalZoom?: boolean;
itemTouchSendsClick?: boolean;
timeSteps?: TimelineTimeSteps,
onItemMove?(itemId: number, dragTime: number, newGroupOrder: number): any;
onItemResize?(itemId: number, newResizeEnd: number, edge: "left" | "right"): any;
onItemSelect?(itemId: number, e: any, time: number): any;
onItemClick?(itemId: number, e: any, time: number): any;
onItemDoubleClick?(itemId: number, e: any, time: number): any;
onCanvasClick?(groupId:number, time:number, e:any): any;
onCanvasDoubleClick?(group: TimelineGroup, time: number, e: any): any;
onCanvasContextMenu?(group: TimelineGroup, time: number, e: any): any;
onZoom?(timelineContext: TimelineContext): any;
moveResizeValidator?(action:"move" | "resize", itemId: number, time: number, resizeEdge: "left" | "right"): any;
headerLabelFormats?: TimelineHeaderLabelFormat,
subHeaderLabelFormats?: TimelineHeaderLabelFormat,
onTimeChange?(visibleTimeStart: number, visibleTimeEnd: number, updateScrollCanvas: (start: number, end: number) => void): any;
onTimeInit?(canvasTimeStart: number, canvasTimeEnd: number): any;
onBoundsChange?(canvasTimeStart: number, canvasTimeEnd: number): any;
itemRenderer?: (props: {item: TimelineItem, context: TimelineContext}) => React.ReactElement<{}>;
groupRenderer?: (props: {group: TimelineGroup, isRightSidebar: boolean}) => React.ReactElement<{}>;
minimumWidthForItemContentVisibility?: number;
children?: any;
}
export const defaultHeaderLabelFormats: TimelineHeaderLabelFormat;
export const defaultSubHeaderLabelFormats: TimelineHeaderLabelFormat;
let ReactCalendarTimeline : React.ClassicComponentClass<ReactCalendarTimelineProps>;
export default ReactCalendarTimeline;
}
+1
View File
@@ -137,6 +137,7 @@ export interface AuthorizeParams {
nonce?: string;
audience?: string;
scope?: string;
connection?: string;
}
export interface ClearSessionParams {
+1
View File
@@ -30,6 +30,7 @@ export interface DatePickerProps {
placeholder?: string;
modalOnResponderTerminationRequest?(e: any): boolean;
is24Hour?: boolean;
getDateStr?: (date: Date) => string;
style?: any;
customStyles?: any;
minuteInterval?: number;
+15 -7
View File
@@ -1,11 +1,18 @@
// Type definitions for react-native-material-textfield 0.12
// Project: https://github.com/n4kz/react-native-material-textfield
// Definitions by: Ville Venäläinen <https://github.com/mindhivefi>
// Kyle Roach <https://github.com/iRoachie>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
// TypeScript Version: 2.6
import * as React from 'react';
import { TextInputProps, TextStyle, ViewStyle, View } from 'react-native';
import {
StyleProp,
TextInputProps,
TextStyle,
ViewStyle,
View
} from 'react-native';
export interface TextFieldProps extends TextInputProps {
animationDuration?: number;
@@ -17,9 +24,10 @@ export interface TextFieldProps extends TextInputProps {
labelPadding?: number;
inputContainerPadding?: number;
labelTextStyle?: TextStyle;
titleTextStyle?: TextStyle;
affixTextStyle?: TextStyle;
style?: StyleProp<TextStyle>;
labelTextStyle?: StyleProp<TextStyle>;
titleTextStyle?: StyleProp<TextStyle>;
affixTextStyle?: StyleProp<TextStyle>;
tintColor?: string;
textColor?: string;
@@ -47,8 +55,8 @@ export interface TextFieldProps extends TextInputProps {
prefix?: string;
suffix?: string;
containerStyle?: ViewStyle;
inputContainerStyle?: ViewStyle;
containerStyle?: StyleProp<ViewStyle>;
inputContainerStyle?: StyleProp<ViewStyle>;
onPress?(event: Event): void;
onChangeText?(text: string): void;
@@ -1,13 +1,15 @@
import * as React from 'react';
import { View, Text } from 'react-native';
import { View } from 'react-native';
import { TextField } from 'react-native-material-textfield';
const Example = () =>
const Example = () => (
<View>
<TextField
label="Example"
multiline
placeholder="Text when field is empty"
value="Initial value"
style={{ fontSize: 10 }}
/>
</View>;
</View>
);
+4
View File
@@ -45,6 +45,10 @@ export interface CarouselProps<T> extends React.Props<ScrollViewProps> {
* Width in pixels of your slides, must be the same for all of them
* Note: Required with horizontal carousel
*/
/**
* Reverses the direction of scroll. Uses scale transforms of -1.
*/
inverted?: boolean;
itemWidth?: number;
/**
* Height in pixels of carousel's items, must be the same for all of them
+8 -2
View File
@@ -1078,6 +1078,12 @@ export type ReturnKeyTypeAndroid = "none" | "previous";
export type ReturnKeyTypeIOS = "default" | "google" | "join" | "route" | "yahoo" | "emergency-call";
export type ReturnKeyTypeOptions = ReturnKeyType | ReturnKeyTypeAndroid | ReturnKeyTypeIOS
export interface TextInputFocusEventData {
target: number,
text: string,
eventCount: number
}
/**
* @see https://facebook.github.io/react-native/docs/textinput.html#props
*/
@@ -1159,7 +1165,7 @@ export interface TextInputProps
/**
* Callback that is called when the text input is blurred
*/
onBlur?: () => void;
onBlur?: (e: NativeSyntheticEvent<TextInputFocusEventData>) => void;
/**
* Callback that is called when the text input's text changes.
@@ -1198,7 +1204,7 @@ export interface TextInputProps
/**
* Callback that is called when the text input is focused
*/
onFocus?: () => void;
onFocus?: (e: NativeSyntheticEvent<TextInputFocusEventData>) => void;
/**
* Callback that is called when the text input selection is changed.
+22 -1
View File
@@ -49,8 +49,10 @@ import {
NativeModules,
MaskedViewIOS,
TextInput,
TextInputFocusEventData,
InputAccessoryView,
StatusBar
StatusBar,
NativeSyntheticEvent
} from "react-native";
declare module "react-native" {
@@ -447,6 +449,25 @@ class TextInputRefTest extends React.Component<{}, {username: string}> {
}
}
class TextInputFocusBlurEventTest extends React.Component {
handleOnBlur(e: NativeSyntheticEvent<TextInputFocusEventData>) {
}
handleOnFocus(e: NativeSyntheticEvent<TextInputFocusEventData>) {
}
render() {
return (
<View>
<TextInput
onBlur={(e: NativeSyntheticEvent<TextInputFocusEventData>) => this.handleOnBlur(e)}
onFocus={(e: NativeSyntheticEvent<TextInputFocusEventData>) => this.handleOnFocus(e)}
/>
</View>
)
}
}
class StatusBarTest extends React.Component {
render() {
StatusBar.setBarStyle("dark-content", true);
+5
View File
@@ -130,6 +130,11 @@ export class InsufficientStorageError extends DefinedHttpError { }
export class BandwidthLimitExceededError extends DefinedHttpError { }
export class NotExtendedError extends DefinedHttpError { }
export class NetworkAuthenticationRequiredError extends DefinedHttpError { }
export class PayloadTooLargeError extends DefinedHttpError { }
export class UriTooLongError extends DefinedHttpError { }
export class MisdirectedRequestError extends DefinedHttpError { }
export class UnavailableForLegalReasonsError extends DefinedHttpError { }
export class LoopDetectedError extends DefinedHttpError { }
export class BadDigestError extends DefinedRestError { }
export class BadMethodError extends DefinedRestError { }
@@ -62,6 +62,12 @@ httpError = new restifyErrors.InsufficientStorageError();
httpError = new restifyErrors.BandwidthLimitExceededError();
httpError = new restifyErrors.NotExtendedError();
httpError = new restifyErrors.NetworkAuthenticationRequiredError();
httpError = new restifyErrors.PayloadTooLargeError();
httpError = new restifyErrors.UriTooLongError();
httpError = new restifyErrors.MisdirectedRequestError();
httpError = new restifyErrors.UnavailableForLegalReasonsError();
httpError = new restifyErrors.LoopDetectedError();
httpError = new restifyErrors.NetworkAuthenticationRequiredError();
// RestErrors
let restError = new restifyErrors.BadDigestError();
+37
View File
@@ -0,0 +1,37 @@
// Type definitions for rolling-rate-limiter 0.1
// Project: https://github.com/peterkhayes/rolling-rate-limiter
// Definitions by: Jonas Lochmann <https://github.com/l-jonas>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = RollingRateLimiter;
declare function RollingRateLimiter(options: RollingRateLimiter.InMemoryOptions): RollingRateLimiter.SyncOrAsyncLimiter;
declare function RollingRateLimiter(options: RollingRateLimiter.WithRedisOptions): RollingRateLimiter.AsyncLimiter;
declare namespace RollingRateLimiter {
interface GeneralOptions {
interval: number;
maxInInterval: number;
minDifference?: number;
}
interface WithRedisOptions extends GeneralOptions {
redis: CompatibleRedisClient;
namespace?: string;
}
interface CompatibleRedisClient {
multi: () => any;
}
type InMemoryOptions = GeneralOptions;
type AsyncLimiterWithToken = (token: string, callback: AsyncLimiterCallback) => void;
type AsyncLimiterWithoutToken = (callback: AsyncLimiterCallback) => void;
type AsyncLimiterCallback = (err: any, timeLeft: number, actionsLeft: number) => void;
type AsyncLimiter = AsyncLimiterWithToken & AsyncLimiterWithToken;
type SyncLimiter = (token?: string) => number;
type SyncOrAsyncLimiter = SyncLimiter & AsyncLimiter;
}
@@ -0,0 +1,36 @@
import * as RateLimiter from 'rolling-rate-limiter';
/*
Setup:
*/
const limiter = RateLimiter({
// in miliseconds
interval: 1000,
maxInInterval: 10,
// optional: the minimum time (in miliseconds) between any two actions
minDifference: 100
});
/*
Action:
*/
function attemptAction(userId: string) {
// Argument should be a unique identifier for a user if one exists.
// If none is provided, the limiter will not differentiate between users.
const timeLeft = limiter(userId);
if (timeLeft > 0) {
// limit was exceeded, action should not be allowed
// timeLeft is the number of ms until the next action will be allowed
// note that this can be treated as a boolean, since 0 is falsy
} else {
// limit was not exceeded, action should be allowed
}
}
/*
Note that the in-memory version can also operate asynchronously.
The syntax is identical to the redis implementation below.
*/
+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",
"rolling-rate-limiter-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+169 -38
View File
@@ -8,6 +8,7 @@
// Kyle Kamperschroer <https://github.com/kkamperschroer>
// Kensuke Hoshikawa <https://github.com/starhoshi>
// Thomas Bruun <https://github.com/bruun>
// Gal Talmor <https://github.com/galtalmor>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
@@ -481,7 +482,7 @@ declare namespace Stripe {
/**
* ID of the Connect Application that earned the fee. [Expandable]
*/
application: string; //TODO: Implement IApplication interface and reference type here for expansion:- "string | IApplication"
application: string | applications.IApplication;
/**
* Balance transaction that describes the impact of this collected application
@@ -737,12 +738,17 @@ declare namespace Stripe {
* charge if a partial refund was issued), positive integer or zero.
*/
amount_refunded: number;
/**
* ID of the Connect application that created the charge. [Expandable]
*/
application?: string | applications.IApplication | null;
/**
* The application fee (if any) for the charge. See the Connect documentation
* for details. [Expandable]
*/
application_fee?: string | applicationFees.IApplicationFee;
application_fee?: string | applicationFees.IApplicationFee | null;
/**
* ID of the balance transaction that describes the impact of this charge on
@@ -767,25 +773,33 @@ declare namespace Stripe {
/**
* ID of the customer this charge is for if one exists. [Expandable]
*/
customer: string | customers.ICustomer;
customer: string | customers.ICustomer | null;
description?: string;
/**
* The account (if any) the charge was made on behalf of, with an automatic
* transfer. See the [Connect documentation]
* <https://stripe.com/docs/connect/destination-charges> for details.
* [Expandable]
*/
destination?: string | accounts.IAccount | null;
/**
* Details about the dispute if the charge has been disputed.
*/
dispute?: disputes.IDispute;
dispute?: disputes.IDispute | null;
/**
* Error code explaining reason for charge failure if available (see the errors section for a list of
* codes: https://stripe.com/docs/api#errors).
*/
failure_code: string;
failure_code: string | null;
/**
* Message to user further explaining reason for charge failure if available.
*/
failure_message: string;
failure_message: string | null;
/**
* Hash with information on fraud assessments for the charge.
@@ -805,16 +819,30 @@ declare namespace Stripe {
/**
* ID of the invoice this charge is for if one exists. [Expandable]
*/
invoice: string | invoices.IInvoice;
invoice: string | invoices.IInvoice | null;
livemode: boolean;
metadata: IMetadata;
/**
* The Stripe account ID for which these funds are intended. Automatically
* set if you use the destination parameter. For details, see [Creating
* Separate Charges and Transfers]
* <https://stripe.com/docs/connect/charges-transfers#on-behalf-of>.
*/
on_behalf_of?: string | null;
/**
* ID of the order this charge is for if one exists. [Expandable]
*/
order: string | orders.IOrder;
order: string | orders.IOrder | null;
/**
* Details about whether the payment was accepted, and why. See
* understanding declines for details. [Expandable]
*/
outcome?: charges.IOutcome;
/**
* true if the charge succeeded, or was successfully authorized for later capture.
@@ -824,12 +852,12 @@ declare namespace Stripe {
/**
* This is the email address that the receipt for this charge was sent to.
*/
receipt_email: string;
receipt_email: string | null;
/**
* This is the transaction number that appears on email receipts sent for this charge.
*/
receipt_number: string;
receipt_number: string | null;
/**
* Whether or not the charge has been fully refunded. If the charge is only partially refunded,
@@ -842,10 +870,15 @@ declare namespace Stripe {
*/
refunds: IChargeRefunds;
/**
* ID of the review associated with this charge if one exists. [Expandable]
*/
review?: string | reviews.IReview | null;
/**
* Shipping information for the charge.
*/
shipping?: IShippingInformation;
shipping?: IShippingInformation | null;
/**
* For most Stripe users, the source of every charge is a credit or debit card.
@@ -858,13 +891,13 @@ declare namespace Stripe {
* from another Stripe account. See the Connect documentation for details.
* [Expandable]
*/
source_transfer: string | transfers.ITransfer;
source_transfer: string | transfers.ITransfer | null;
/**
* Extra information about a charge. This will appear on your customer’s
* credit card statement.
*/
statement_descriptor: string;
statement_descriptor: string | null;
/**
* The status of the payment is either "succeeded", "pending", or "failed".
@@ -875,7 +908,15 @@ declare namespace Stripe {
* ID of the transfer to the destination account (only applicable if the
* charge was created using the destination parameter). [Expandable]
*/
transfer: string | transfers.ITransfer;
transfer?: string | transfers.ITransfer;
/**
* A string that identifies this transaction as part of a group.
* See the [Connect documentation]
* <https://stripe.com/docs/connect/charges-transfers#grouping-transactions>
* for details.
*/
transfer_group?: string | null;
}
interface IChargeCreationOptions extends IDataOptionsWithMetadata {
@@ -1056,6 +1097,48 @@ declare namespace Stripe {
}
}
interface IOutcome {
/**
* The value reversed_after_approval indicates the payment was blocked by Stripe after
* bank authorization, and may temporarily appear as “pending” on a cardholder’s statement.
*/
network_status: "approved_by_network" | "declined_by_network" | "not_sent_to_network" | "reversed_after_approval";
/**
* An enumerated value providing a more detailed explanation of the outcome’s type. Charges
* blocked by Radar’s default block rule have the value highest_risk_level. Charges placed
* in review by Radar’s default review rule have the value elevated_risk_level. Charges
* authorized, blocked, or placed in review by custom rules have the value rule. See
* understanding declines for more details.
*/
reason: string | null;
/**
* Stripe’s evaluation of the riskiness of the payment. Possible values for evaluated
* payments are normal, elevated, highest. For non-card payments, and card-based payments
* predating the public assignment of risk levels, this field will have the value not_assessed.
* In the event of an error in the evaluation, this field will have the value unknown.
*/
risk_level?: string | null;
/**
* The ID of the Radar rule that matched the payment, if applicable. [Expandable]
*/
rule?: string | string[] | null;
/**
* See [understanding declines]<https://stripe.com/docs/declines> and
* [Radar reviews]<https://stripe.com/docs/radar/review> for details.
*/
type: "authorized" | "manual_review" | "issuer_declined" | "blocked" | "invalid";
/**
* A human-readable description of the outcome type and reason, designed for you (the
* recipient of the payment), not your customer.
*/
seller_message: string;
}
interface IChargeRefunds extends IList<refunds.IRefund>, resources.ChargeRefunds { }
}
@@ -4092,7 +4175,7 @@ declare namespace Stripe {
* in the card object if the card belongs to an account or recipient
* instead.
*/
customer?: string | customers.ICustomer;
customer?: string | customers.ICustomer | null;
/**
* Only applicable on accounts (not customers or recipients). This
@@ -4126,7 +4209,7 @@ declare namespace Stripe {
/**
* The card number
*/
number: string;
number?: string;
/**
* Card brand. Can be Visa, American Express, MasterCard, Discover, JCB, Diners Club, or Unknown.
@@ -4140,20 +4223,20 @@ declare namespace Stripe {
*/
funding: "credit" | "debit" | "prepaid" | "unknown";
last4: string;
address_city: string;
address_city: string | null;
/**
* Billing address country, if provided when creating card
*/
address_country: string;
address_line1: string;
address_country: string | null;
address_line1: string | null;
/**
* If address_line1 was provided, results of the check: pass, fail, unavailable, or unchecked.
*/
address_line1_check: string;
address_line2: string;
address_state: string;
address_line1_check: string | null;
address_line2: string | null;
address_state: string | null;
address_zip: string;
/**
@@ -4175,7 +4258,7 @@ declare namespace Stripe {
/**
* (For Apple Pay integrations only.) The last four digits of the device account number.
*/
dynamic_last4: string;
dynamic_last4: string | null;
/**
* Cardholder name
@@ -4194,7 +4277,7 @@ declare namespace Stripe {
* If the card number is tokenized, this is the method that was
* used. Can be "apple_pay" or "android_pay".
*/
tokenization_method: "apple_pay" | "android_pay";
tokenization_method: "apple_pay" | "android_pay" | null;
}
interface ICardUpdateOptions extends IDataOptionsWithMetadata {
@@ -4944,6 +5027,54 @@ declare namespace Stripe {
}
}
namespace reviews {
interface IReview extends IResourceObject {
/**
* String representing the object’s type. Objects of the same type share the same value.
*/
object: "review";
/**
* The charge associated with this review. [Expandable]
*/
charge: string | charges.ICharge;
/**
* Time at which the object was created. Measured in seconds since the Unix epoch.
*/
created: number;
/**
* Has the value true if the object exists in live mode or the value false if the object exists in test mode.
*/
livemode: boolean;
/**
* If true, the review needs action.
*/
open: boolean;
/**
* The reason the review is currently open or closed.
*/
reason: "rule" | "manual" | "approved" | "refunded" | "refunded_as_fraud" | "disputed";
}
}
namespace applications {
interface IApplication extends IResourceObject {
/**
* String representing the object’s type. Objects of the same type share the same value.
*/
object: "application";
/**
* String representing the application’s name.
*/
name: string;
}
}
class StripeResource {
constructor(stripe: Stripe, urlData: any);
}
@@ -5388,18 +5519,18 @@ declare namespace Stripe {
* Once entirely refunded, a charge can't be refunded again.
* This method will throw an error when called on an already-refunded charge, or when trying to refund more money than is left on a charge.
*/
create(data: refunds.IRefundCreationOptions, options: HeaderOptions, response?: IResponseFn<refunds.IRefund>): Promise<refunds.IRefund>;
create(data: refunds.IRefundCreationOptions, response?: IResponseFn<refunds.IRefund>): Promise<refunds.IRefund>;
create(options: HeaderOptions, response?: IResponseFn<refunds.IRefund>): Promise<refunds.IRefund>;
create(response?: IResponseFn<refunds.IRefund>): Promise<refunds.IRefund>;
create?(data: refunds.IRefundCreationOptions, options: HeaderOptions, response?: IResponseFn<refunds.IRefund>): Promise<refunds.IRefund>;
create?(data: refunds.IRefundCreationOptions, response?: IResponseFn<refunds.IRefund>): Promise<refunds.IRefund>;
create?(options: HeaderOptions, response?: IResponseFn<refunds.IRefund>): Promise<refunds.IRefund>;
create?(response?: IResponseFn<refunds.IRefund>): Promise<refunds.IRefund>;
/**
* Retrieves the details of an existing refund.
*/
retrieve(id: string, data: IDataOptions, options: HeaderOptions, response?: IResponseFn<refunds.IRefund>): Promise<refunds.IRefund>;
retrieve(id: string, data: IDataOptions, response?: IResponseFn<refunds.IRefund>): Promise<refunds.IRefund>;
retrieve(id: string, options: HeaderOptions, response?: IResponseFn<refunds.IRefund>): Promise<refunds.IRefund>;
retrieve(id: string, response?: IResponseFn<refunds.IRefund>): Promise<refunds.IRefund>;
retrieve?(id: string, data: IDataOptions, options: HeaderOptions, response?: IResponseFn<refunds.IRefund>): Promise<refunds.IRefund>;
retrieve?(id: string, data: IDataOptions, response?: IResponseFn<refunds.IRefund>): Promise<refunds.IRefund>;
retrieve?(id: string, options: HeaderOptions, response?: IResponseFn<refunds.IRefund>): Promise<refunds.IRefund>;
retrieve?(id: string, response?: IResponseFn<refunds.IRefund>): Promise<refunds.IRefund>;
/**
@@ -5408,18 +5539,18 @@ declare namespace Stripe {
*
* This request only accepts metadata as an argument.
*/
update(id: string, data: IDataOptionsWithMetadata, options: HeaderOptions, response?: IResponseFn<refunds.IRefund>): Promise<refunds.IRefund>;
update(id: string, data: IDataOptionsWithMetadata, response?: IResponseFn<refunds.IRefund>): Promise<refunds.IRefund>;
update?(id: string, data: IDataOptionsWithMetadata, options: HeaderOptions, response?: IResponseFn<refunds.IRefund>): Promise<refunds.IRefund>;
update?(id: string, data: IDataOptionsWithMetadata, response?: IResponseFn<refunds.IRefund>): Promise<refunds.IRefund>;
/**
* Returns a list of all refunds you’ve previously created. The refunds are returned in sorted order,
* with the most recent refunds appearing first.
* For convenience, the 10 most recent refunds are always available by default on the charge object.
*/
list(data: refunds.IRefundListOptions, options: HeaderOptions, response?: IResponseFn<IList<refunds.IRefund>>): Promise<IList<refunds.IRefund>>;
list(data: refunds.IRefundListOptions, response?: IResponseFn<IList<refunds.IRefund>>): Promise<IList<refunds.IRefund>>;
list(options: HeaderOptions, response?: IResponseFn<IList<refunds.IRefund>>): Promise<IList<refunds.IRefund>>;
list(response?: IResponseFn<IList<refunds.IRefund>>): Promise<IList<refunds.IRefund>>;
list?(data: refunds.IRefundListOptions, options: HeaderOptions, response?: IResponseFn<IList<refunds.IRefund>>): Promise<IList<refunds.IRefund>>;
list?(data: refunds.IRefundListOptions, response?: IResponseFn<IList<refunds.IRefund>>): Promise<IList<refunds.IRefund>>;
list?(options: HeaderOptions, response?: IResponseFn<IList<refunds.IRefund>>): Promise<IList<refunds.IRefund>>;
list?(response?: IResponseFn<IList<refunds.IRefund>>): Promise<IList<refunds.IRefund>>;
}
class Coupons extends StripeResource {