diff --git a/angularjs/angular-animate.d.ts b/angularjs/angular-animate.d.ts index f68cd60d14..60f595672f 100644 --- a/angularjs/angular-animate.d.ts +++ b/angularjs/angular-animate.d.ts @@ -43,7 +43,7 @@ declare namespace angular.animate { * @param container the container element that will capture each of the animation events that are fired on itself as well as among its children * @param callback the callback function that will be fired when the listener is triggered */ - on(event: string, container: JQuery, callback: Function): void; + on(event: string, container: JQuery, callback: (element?: JQuery, phase?: string) => any): void; /** * Deregisters an event listener based on the event which has been associated with the provided element. @@ -52,7 +52,7 @@ declare namespace angular.animate { * @param container the container element the event listener was placed on * @param callback the callback function that was registered as the listener */ - off(event: string, container?: JQuery, callback?: Function): void; + off(event: string, container?: JQuery, callback?: (element?: JQuery, phase?: string) => any): void; /** * Associates the provided element with a host parent element to allow the element to be animated even if it exists outside of the DOM structure of the Angular application. diff --git a/backbone/backbone-global.d.ts b/backbone/backbone-global.d.ts index 4736e3de23..9cf1cb49b8 100644 --- a/backbone/backbone-global.d.ts +++ b/backbone/backbone-global.d.ts @@ -147,7 +147,6 @@ declare namespace Backbone { /*private*/ set(attributeName: string, value: any, options?: ModelSetOptions): Model; set(obj: any, options?: ModelSetOptions): Model; - change(): any; changedAttributes(attributes?: any): any[]; clear(options?: Silenceable): any; clone(): Model; @@ -388,7 +387,6 @@ declare namespace Backbone { $(selector: any): JQuery; render(): View; remove(): View; - make(tagName: any, attributes?: any, content?: any): any; delegateEvents(events?: EventsHash): any; delegate(eventName: string, selector: string, listener: Function): View; undelegateEvents(): any; diff --git a/bootstrap-fileinput/bootstrap-fileinput.d.ts b/bootstrap-fileinput/bootstrap-fileinput.d.ts new file mode 100644 index 0000000000..fadfadd612 --- /dev/null +++ b/bootstrap-fileinput/bootstrap-fileinput.d.ts @@ -0,0 +1,1039 @@ +// Type definitions for bootstrap-fileinput +// Project: https://github.com/kartik-v/bootstrap-fileinput +// Definitions by: Ché Coxshall +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface JQuery { + fileinput: (options?: BootstrapFileInput.FileInputOptions) => JQuery; +} + + +declare module BootstrapFileInput { + interface FileInputOptions { + /** + Language configuration for the plugin to enable the plugin to display messages for your locale (you must set the ISO code for the language). + You can have multiple language widgets on the same page. + The locale JS file for the language code must be defined as mentioned in the translations section: http://plugins.krajee.com/file-input#translations + */ + language?: string; + /** + Whether to display the file caption. + Defaults to true. + */ + showCaption?: boolean; + /** + Whether to display the file preview. + Defaults to true. + */ + showPreview?: boolean; + /** + Whether to display the file remove/clear button. + Defaults to true. + */ + showRemove?: boolean; + /** + Whether to display the file upload button. + Defaults to true. + This will default to a form submit button, unless the uploadUrl is specified. + */ + showUpload?: boolean; + /** + Whether to display the file upload cancel button. + Defaults to true. + This will be only enabled and displayed when an AJAX upload is in process. + */ + showCancel?: boolean; + /** + Whether to display the close icon in the preview. + Defaults to true. + This will be only parsed when showPreview is true or when you are using the {close} tag in your preview templates. + */ + showClose?: boolean; + /** + Whether to persist display of the uploaded file thumbnails in the preview window (for ajax uploads) until the remove/clear button is pressed. + Defaults to true. + When set to false, a next batch of files selected for upload will clear these thumbnails from preview. + */ + showUploadedThumbs?: boolean; + /** + Whether to automatically replace the files in the preview after the maxFileCount limit is reached and a new set of file(s) is/are selected. + This will only work if a valid maxFileCount is set. + Defaults to false. + */ + autoReplace?: boolean; + /** + Any additional CSS class to append to the caption container. + */ + captionClass?: string; + /** + Any additional CSS class to append to the preview container. + */ + previewClass?: string; + /** + Any additional CSS class to append to the main plugin container. + */ + mainClass?: string; + /** + The initial preview content to be displayed. + You can pass the minimal HTML markup for displaying your image, text, or file. + If set as a string, this will display a single file in the initial preview if there is no delimiter. You can set a delimiter (as defined in initialDelimiter) to show multiple files in initial preview. + If set as an array, it will display all files in the array as an initial preview (useful for multiple file upload scenarios). + The following CSS classes will need to be added for displaying each file type as per the plugin style theme: + image files: Include CSS class file-preview-image + text files: Include CSS class file-preview-text + other files: Include CSS class file-preview-other + */ + initialPreview?: string | any[]; + /** + the count of initial preview items that will be added to the count of files selected in preview. This is applicable when displaying the right caption, when overwriteInitial is set to false. + */ + initialPreviewCount?: number; + /** + the delimiter to be used for splitting the initial preview content as individual file thumbnails (applicable only if initialPreview is passed as a string instead of array). Defaults to *$$*. + */ + initialPreviewDelimiter?: string; + /** + the configuration for setting up important properties for each initialPreview item (that is setup as part of initialPreview). + */ + initialPreviewConfig?: PreviewConfig[]; + /** + whether the delete button will be displayed for each thumbnail that has been created with initialPreview. + */ + initialPreviewShowDelete?: boolean; + /** + whether the file thumbnail should be removed from preview on error. Defaults to false. + */ + removeFromPreviewOnError?: boolean; + /** + this will be a list of tags used in thumbnail templates that will be replaced dynamically within the thumbnail markup, when the thumbnail is rendered. + */ + previewThumbTags?: { [key: string]: string; } + /** + this is an extension of previewThumbTags specifically for initial preview content - but will be configured as an array of objects corresponding to each initial preview thumbnail. The initial preview thumbnails set via initialPreview will read this configuration for replacing tags. + */ + initialPreviewThumbTags?: { [key: string]: string; } + /** + the extra data that will be passed as data to the initial preview delete url/AJAX server call via POST. + This will be overridden by the initialPreviewConfig['extra'] property. + This property is only applicable for ajax deletions in initial preview and when you have set a value for initialPreviewConfig['url'] or deleteUrl. + This can be setup either as an object (associative array of keys and values) or as a function callback. + Note + The ajax delete action will send the following data to server via POST: + key: the key setting as setup in initialPreviewConfig['key'] + any other extra data passed as key: value pairs either via initialPreviewConfig['extra'] OR deleteExtraData if former is not set. + */ + deleteExtraData?: {} | { (): {} }; + /** + the URL for deleting the image/content in the initial preview via AJAX post response. This will be overridden by the initialPreviewConfig['url'] property. + Note + The ajax delete action will send the following data to server via POST: + key: the key setting as setup in initialPreviewConfig['key'] + any other extra data passed as key: value pairs either via initialPreviewConfig['extra'] OR deleteExtraData if former is not set. + */ + deleteUrl?: string; + /** + the initial preview caption text to be displayed. + If you do not set a value here and initialPreview is set to true this will default to "{preview-file-count} files selected", where {preview-file-count} is the count of the files passed in initialPreview. + */ + initialCaption?: string; + /** + whether you wish to overwrite the initial preview content and caption setup. + This defaults to true, whereby, any initialPreview content set will be overwritten, when new file is uploaded or when files are cleared. + Setting it to false will help displaying a saved image or file from database always - useful especially when using the multiple file upload feature. + */ + overwriteInitial?: boolean; + /** + the templates configuration for rendering each part of the layout. + */ + layoutTemplates?: LayoutTemplates; + /** + the templates configuration for rendering each preview file type. + */ + previewTemplates?: PreviewTemplates; + /** + the list of allowed file types for upload. + This by default is set to null which means the plugin supports all file types for upload. + If an invalid file type is found, then a validation error message as set in msgInvalidFileType will be raised. + Note: + You need to be careful in case you are setting both allowedFileTypes and allowedFileExtensions. In this case, the allowedFileTypes property is validated first and generally precedes the allowedFileExtensions setting (and the latter validation maybe skipped). + */ + allowedFileTypes?: ("image" | "html" | "text" | "video" | "audio" | "flash" | "object")[]; + /** + the list of allowed file extensions for upload. + This by default is set to null which means the plugin supports all file extensions for upload. + If an invalid file extension is found, then a validation error message as set in msgInvalidFileExtension will be raised. + Note: + You need to be careful in case you are setting both allowedFileTypes and allowedFileExtensions. In this case, the allowedFileTypes property is validated first and generally precedes the allowedFileExtensions setting (and the latter validation maybe skipped). + */ + allowedFileExtensions?: string[]; + /** + the list of allowed preview types for your widget. + This by default supports all file types for preview. + The plugin by default treats each file as an object if it does not match any of the previous types. + To disable this behavior, you can remove object from the list of allowedPreviewTypes OR fine tune it through allowedPreviewMimeTypes. + To disable content preview for all file-types and show the previewIcon instead as a thumbnail, set this to null, empty, or false. + */ + allowedPreviewTypes?: ("image" | "html" | "text" | "video" | "audio" | "flash" | "object")[]; + /** + the list of allowed mime types for preview. + This is set to null by default which means all possible mime types are allowed. + This setting works in combination with allowedPreviewTypes to filter only the needed file types allowed for preview. + */ + allowedPreviewMimeTypes?: string[]; + /** + the default content / markup to show by default in the preview window whenever the files are cleared or the input is cleared. + This can be useful for use cases like showing the default user profile picture or profile image before upload to overwrite. + This is a bit different from initialPreview in the sense, that the initialPreview content will always be displayed unless it is deleted or overwritten based on overwriteInitial. + The defaultPreviewContent on the other hand will only be shown ONLY on initialization OR whenever you clear the preview. + At other times when files have been selected this will be overwritten temporarily until file(s) selected is/are cleared. + This property can be useful to display for example a default user profile picture (or saved picture) in the preview window unless the user selects a picture. + */ + defaultPreviewContent?: string; + /** + the list of additional custom tags that will be replaced in the layout templates. + */ + customLayoutTags?: {}; + /** + the list of additional custom tags that will be replaced in the preview templates. + */ + customPreviewTags?: {}; + /** + the format settings (width and height) for rendering each preview file type. + */ + previewSettings?: PreviewSettings; + /** + the settings to validate and identify each file type when a file is selected for upload. + This is a list of callbacks, which accepts the file mime type and file name as a parameter. + */ + fileTypeSettings?: FileTypeSettings; + /** + the icon to be shown in each preview file thumbnail when an unreadable file type for preview is detected. Defaults to  . + */ + previewFileIcon?: string; + /** + the CSS class to be applied to the preview file icon container. Defaults to file-icon-4x. + */ + previewFileIconClass?: string; + /** + the preview icon markup settings for each file extension (type). + You need to set this as key: value pairs, where the key corresponds to a file extension (e.g. doc, docx, xls etc.), and the value corresponds to the markup of the icon to be rendered. + If this is not set OR a file extension is not set here, the preview will default to previewFileIcon. + Note that displaying the icons instead of file content is controlled via allowedPreviewTypes and allowedPreviewMimeTypes + */ + previewFileIconSettings?: PreviewFileIconSettings; + /** + the extensions to be auto derived for each file extension (type). + This is useful if you want to set the same icon for multiple file extension types. + You need to set this as `key: value` pairs, where the key corresponds to a file extension as set in previewFileIconSettings (e.g. doc, docx, xls etc.). + The value will be a function callback that accepts the following parameter: + ext: string, the file extension (without the . [dot]) of the file currently selected in the preview. + You can configure the callback to match the set of file extensions (via regex or similar) for each `key` and return a boolean output if the file extension matches. + */ + previewFileExtSettings?: PreviewFileExtSettings; + /** + the CSS class for the each of the button labels for browse, remove, upload, and cancel. + Defaults to hidden-xs, which automatically hides the button labels for small screen devices and renders as smaller iconic buttons to fit to the screen. + */ + buttonLabelClass?: string; + /** + the label to display for the file picker/browse button. Defaults to Browse …. + */ + browseLabel?: string; + /** + the icon to display before the label for the file picker/browse button. Defaults to  . + */ + browseIcon?: string; + /** + the CSS class for the file picker/browse button. Defaults to btn btn-primary. + */ + browseClass?: string; + /** + the label to display for the file remove button. Defaults to Remove. + */ + removeLabel?: string; + /** + the icon to display before the label for the file picker/remove button. Defaults to  . + */ + removeIcon?: string; + /** + the CSS class for the file remove button. Defaults to btn btn-default. + */ + removeClass?: string; + /** + the title to display on hover for the file remove button. Defaults to Clear selected files. + */ + removeTitle?: string; + /** + the label to display for the file upload button. Defaults to Upload. + */ + uploadLabel?: string; + /** + the icon to display before the label for the file upload button. Defaults to  . + */ + uploadIcon?: string; + /** + the CSS class for the file upload button. Defaults to btn btn-default. + */ + uploadClass?: string; + /** + the title to display on hover for the file remove button. + Defaults to Upload selected files. + */ + uploadTitle?: string; + /** + the URL for the upload processing action (typically for ajax based processing). + Defaults to null. + If this is not set or null, then the upload button action will default to form submission. + NOTE: + This is MANDATORY if you want to use advanced features like drag & drop, append/remove files, selectively upload files via ajax etc. + The plugin automatically send $_FILES data to the server with the input `name` attribute as the key if provided. + If input name is not set, the key defaults to file-data. + */ + uploadUrl?: string; + /** + whether the batch upload of multiple files will be asynchronous/in parallel. + Defaults to true. + */ + uploadAsync?: boolean; + /** + the extra data that will be passed as data to the url/AJAX server call via POST. + This property is only applicable for ajax uploads and when you have set a value for uploadUrl. + This can be setup either as an object (associative array of keys and values) or as a function callback. + As an object, it can be set for example as: + { id: 100, value: '100 Details' } + Note that for uploading individual file via thumbnail, the function callback can also receive the thumbnail previewId and index as parameters. These are described below: + previewId: the identifier for the preview file container (only available when uploading each thumbnail file) + index: the zero-based sequential index of the loaded file in the preview list (only available when uploading each thumbnail file) + */ + uploadExtraData?: {} | ((previewId?: string, index?: number) => {}); + /** + the minimum allowed image height in px if you are uploading image files. + Defaults to null which means no limit on image height. + */ + minImageHeight?: number; + /** + the maximum allowed image width in px if you are uploading image files. + Defaults to null which means no limit on image width. + Note that if you set resizeImage property to true, then the entire image will be resized within this width (depending on resizePreference). + */ + maxImageWidth?: number; + /** + the maximum allowed image height in px if you are uploading image files. + Defaults to null which means no limit on image height. + Note that if you set resizeImage property to true, then the entire image will be resized within this height (depending on resizePreference). + */ + maxImageHeight?: number; + /** + whether to add ability to resize uploaded images. Defaults to false. + Note that resizing images requires HTML5 canvas support which is supported on most modern browsers. + In addition, you must include the JavaScript-Canvas-to-Blob plugin by blueimp by including canvas-to-blob.js in your application. + This JS file must be loaded before fileinput.js on the page. + The JavaScript-Canvas-to-Blob source files are available in js/plugins folder of bootstrap-fileinput project page. + The canvas-to-blob.js plugin is a polyfill for canvas.toBlob method and is needed for allowing the resized image files via HTML5 canvas to be returned as a blob + */ + resizeImage?: boolean; + /** + preference to resize the image based on width or height. + Defaults to width. + This property is parsed only when resizeImage is true. + If set to width, the maxImageWidth property is first tested and if image size is greater than this, then the image is resized to maxImageWidth. + The image height is resized and adjusted in the same ratio as width. + In case, the image width is already less than maxImageWidth then the maxImageHeight property is used to resize and width is adjusted in same ratio. + This will behave conversely, when resizePreference is set to height - the maxImageHeight will be first tested against image height and then the rest of steps will be similarly parsed with preference given to height instead of width as before. + */ + resizePreference?: "width" | "height"; + /** + the quality of the resized image. This must be a decimal number between 0.00 to 1.00. + Defaults to 0.92. + */ + resizeImageQuality?: number; + /** + the default image mime type of the converted image after resize. + Defaults to image/jpeg. + */ + resizeDefaultImageType?: string; + /** + the maximum file size for upload in KB. + If set to 0, it means size allowed is unlimited. + Defaults to 0. + */ + maxFileSize?: number; + /** + the minimum number of files allowed for each multiple upload. + If set to 0, it means number of files are optional. + Defaults to 0. + */ + minFileCount?: number; + /** + the maximum number of files allowed for each multiple upload. + If set to 0, it means number of files allowed is unlimited. + Defaults to 0. + */ + maxFileCount?: number; + /** + whether to include initial preview file count (server uploaded files) in validating minFileCount and maxFileCount. + Defaults to false. + */ + validateInitialCount?: boolean; + /** + the message that will be displayed when ZERO files are found. + Defaults to No. + */ + msgNo?: string; + /** + the message that will be displayed within the progress bar when file upload is aborted or cancelled. + Defaults to Cancelled. + */ + msgCancelled?: string; + /** + the title displayed (before the file name) on hover of the zoom button for zooming the file content in a modal window. + This is currently applicable only for text file previews. + Defaults to View details. + */ + msgZoomTitle?: string; + /** + the heading of the modal dialog that displays the zoomed file content. + This is currently applicable only for text file previews. + Defaults to Detailed Preview. + */ + msgZoomModalHeading?: string; + /** + the message to be displayed when the file size exceeds maximum size. + Defaults to: + File "{name}" ({size} KB) exceeds maximum allowed upload size of {maxSize} KB. Please retry your upload! + where: + {name}: will be replaced by the file name being uploaded + {size}: will be replaced by the uploaded file size + {maxSize}: will be replaced by the maxFileSize parameter. + */ + msgSizeTooLarge?: string; + /** + message to be displayed when the file count is less than the minimum count as set in minFileCount. + Defaults to: + You must select at least {n} {files} to upload. Please retry your upload! + where: + {n}: will be replaced by the allowed minimum files as set in minFileCount. + {files}: will be replaced with fileSingle or filePlural properties in locale file depending on the minFileCount. + */ + msgFilesTooLess?: string; + /** + the message to be displayed when the file count exceeds maximum count as set in maxFileCount. + Defaults to: + Number of files selected for upload ({n}) exceeds maximum allowed limit of {m}. Please retry your upload! + where: + {n}: will be replaced by number of files selected for upload + {m}: will be replaced by the allowed maximum files as set in maxFileCount + */ + msgFilesTooMany?: string; + /** + the exception message to be displayed when the file selected is not found by the FileReader. + Defaults to: + File "{name}" not found! + where: + {name}: will be replaced by the file name being uploaded + */ + msgFileNotFound?: string; + /** + the exception message to be displayed when the file selected is not allowed to be accessed due to a security exception. + Defaults to: + Security restrictions prevent reading the file "{name}". + where: + {name}: will be replaced by the file name being uploaded + */ + msgFileSecured?: string; + /** + the exception message to be displayed when the file selected is not readable by the FileReader API. + Defaults to: + File "{name}" is not readable. + where: + {name}: will be replaced by the file name being uploaded + */ + msgFileNotReadable?: string; + /** + the exception message to be displayed when the file preview upload is aborted. + Defaults to: + File preview aborted for "{name}". + where: + {name}: will be replaced by the file name being uploaded + */ + msgFilePreviewAborted?: string; + /** + the exception message to be displayed for any other error when previewing the file. + Defaults to: + An error occurred while reading the file "{name}". + where: + {name}: will be replaced by the file name being uploaded + */ + msgFilePreviewError?: string; + /** + the message to be displayed when the file type is not in one of the file types set in allowedFileTypes. + Defaults to: + Invalid type for file "{name}". Only "{types}" files are supported. + where: + {name}: will be replaced by the file name being uploaded + {types}: will be replaced by the comma separated list of types defined in allowedFileTypes. + */ + msgInvalidFileType?: string; + /** + the message to be displayed when the file type is not in one of the file extensions set in allowedFileExtensions. + Defaults to: + Invalid extension for file "{name}". Only "{extensions}" files are supported. + where: + {name}: will be replaced by the file name being uploaded + {extensions}: will be replaced by the comma separated list of extensions defined in allowedFileExtensions. + */ + msgInvalidFileExtension?: string; + /** + the message to be displayed when an ongoing ajax file upload is aborted by pressing the Cancel button. + Defaults to The file upload was aborted. + If this is set to null or empty, the internal ajax error message will be displayed - Defaults to File Upload Error. + */ + msgUploadAborted?: string; + /** + the exception message to be displayed within the caption container (instead of msgFilesSelected), when a validation error is encountered. + Defaults to File Upload Error. + */ + msgValidationError?: string; + /** + the css class for the validation error message displayed in the caption container. + Defaults to text-danger. + */ + msgValidationErrorClass?: string; + /** + the icon to be displayed before the validation error in the caption container. + Defaults to + */ + msgValidationErrorIcon?: string; + /** + the css class for the error message to be displayed in the preview window when the file size exceeds maxSize. + Defaults to file-error-message. + */ + msgErrorClass?: string; + /** + the message displayed when the files are getting read and loaded for preview. + Defaults to + Loading file {index} of {files} … + The following special variables will be replaced: + {index}: the sequence number of the current file being loaded. + {files}: the total number of files selected for upload. + */ + msgLoading?: string; + /** + the progress message displayed as each file is loaded for preview. + Defaults to: + Loading file {index} of {files} - {name} - {percent}% completed. + The following variables will be replaced: + {index}: the sequence number of the current file being loaded. + {files}: the total number of files selected for upload. + {percent}: the percentage of file read and loaded. + {name}: the name of the current file being loaded. + */ + msgProgress?: string; + /** + the progress message displayed in caption window when multiple (more than one) files are selected. + Defaults to: + {n} files selected. + The following variables will be replaced: + {n}: the number of files selected. + */ + msgSelected?: string; + /** + the message displayed when a folder has been dragged to the drop zone. + Defaults to: + Drag & drop files only! {n} folder(s) dropped were skipped. + The following variables will be replaced: + {n}: the number of folders dropped. + */ + msgFoldersNotAllowed?: string; + /** + the exception message to be displayed when the file selected for preview is an image and its width is less than the minImageWidth setting. + Defaults to: + Width of image file "{name}" must be at least {size} px. + where: + {name}: will be replaced by the file name being uploaded. + {size}: will be replaced by the minImageWidth setting. + */ + msgImageWidthSmall?: string; + /** + the exception message to be displayed when the file selected for preview is an image and its height is less than the minImageHeight setting. + Defaults to: + Height of image file "{name}" must be at least {size} px. + where: + {name}: will be replaced by the file name being uploaded. + {size}: will be replaced by the minImageHeight setting. + */ + msgImageHeightSmall?: string; + /** + the exception message to be displayed when the file selected for preview is an image and its width exceeds the maxImageWidth setting. + Defaults to: + Width of image file "{name}" cannot exceed {size} px. + where: + {name}: will be replaced by the file name being uploaded. + {size}: will be replaced by the maxImageWidth setting. + */ + msgImageWidthLarge?: string; + /** + the exception message to be displayed when the file selected for preview is an image and its height exceeds the maxImageHeight setting. + Defaults to: + Height of image file "{name}" cannot exceed {size} px. + where: + {name}: will be replaced by the file name being uploaded. + {size}: will be replaced by the maxImageHeight setting. + */ + msgImageHeightLarge?: string; + /** + the upload progress bar CSS class to be applied when AJAX upload is in process (applicable only for ajax uploads). + Defaults to progress-bar progress-bar-success progress-bar-striped active. + */ + progressClass?: string; + /** + the upload progress bar CSS class to be applied when AJAX upload is in process (applicable only for ajax uploads). + Defaults to progress-bar progress-bar-success progress-bar-striped active. + */ + progressCompleteClass?: string; + /** + the upload progress bar CSS class to be applied when AJAX upload is cancelled or aborted. + Defaults to progress-bar progress-bar-danger. + */ + progressErrorClass?: string; + /** + the type of files that are to be displayed in the preview window. + Defaults to image. + Can be one of the following: + image: Only image type files will be shown in preview. + text: Only text type files will be shown in preview. + any: Both image and text files content will be shown in preview. + Files other than image or text will be displayed as a thumbnail with the filename in the preview window. + */ + previewFileType?: "image" | "text" | "any"; + /** + the icon for zooming the file content in a new modal dialog. + This is currently applicable only for text file previews. + Defaults to + */ + zoomIndicator?: string; + /** + the identifier for the container element displaying the error (e.g. '#id'). + If not set, will default to the container with CSS class kv-fileinput-error inside the preview container (identified by elPreviewContainer). + The msgErrorClass will be automatically appended to this container before displaying the error. + */ + elErrorContainer?: string; + /** + the identifier for the container element containing the caption (e.g. '#id'). + If not set, will default to the container with CSS class file-caption inside the main plugin container. + */ + elCaptionContainer?: string; + /** + the identifier for the container element containing the caption text (e.g. '#id'). + If not set, will default to the container with CSS class file-caption-name inside the main plugin container. + */ + elCaptionText?: string; + /** + the identifier for the container element containing the preview (e.g. '#id'). + If not set, will default to the container with CSS class file-preview inside the main plugin container. + */ + elPreviewContainer?: string; + /** + the identifier for the element containing the preview image thumbnails (e.g. '#id'). + If not set, will default to the container with CSS class file-preview-thumbnails inside the main plugin container. + */ + elPreviewImage?: string; + /** + the identifier for the element containing the preview progress status (e.g. '#id'). + If not set, will default to the container with CSS class file-preview-status inside the main plugin container. + */ + elPreviewStatus?: string; + /** + a callback to convert the filename as a slug string eliminating special characters. + If not set, it will use the plugin's own internal slugDefault method. + This callback function includes the filename as parameter and must return a converted filename string. + */ + slugCallback?: (filename: string) => string; + /** + whether to enable a drag and drop zone for dragging and dropping files to. + This is available only for ajax based uploads. + Defaults to true. + */ + dropZoneEnabled?: boolean; + /** + title to be displayed in the drag and drop zone. + This is available only for ajax based uploads. + Defaults to: + Drag & drop files here …. + */ + dropZoneTitle?: string; + /** + CSS class for the drag & drop zone title. + Defaults to file-drop-zone-title. + */ + dropZoneTitleClass?: string; + /** + configuration for setting up file actions for newly selected file thumbnails in the preview window. + */ + fileActionsettings?: FileActionSettings; + /** + markup for additional action buttons to display within the initial preview thumbnails (for example displaying an image edit button). + The following tag can be used in the markup and will be automatically replaced: + {dataKey}: Will be replaced with the key set within initialPreviewConfig. + */ + otherActionButtons?: string; + /** + the encoding to be used while reading a text file. + Applicable only for previewing text files. + Defaults to UTF-8. + */ + textEncoding?: string; + /** + additional ajax settings to pass to the plugin before submitting the ajax request for upload. + Applicable only for ajax uploads. + This can be useful to pass additional tokens to headers or one can use it for setting other ajax options for advanced cases. + Refer the jQuery ajax documentation for the various settings you can configure. + */ + ajaxSettings?: JQueryAjaxSettings; + /** + additional ajax settings to pass to the plugin before submitting the delete ajax request in each initial preview thumbnail. + Applicable only for ajax uploads. + This can be useful to pass additional tokens to headers or one can use it for setting other ajax options for advanced cases. + Refer the jQuery ajax documentation for the various settings you can configure. + */ + ajaxDeleteSettings?: JQueryAjaxSettings; + /** + whether to show details of the error stack from the server log when an error is encountered via ajax response. + Defaults to true. + */ + showAjaxErrorDetails?: boolean; + } + + interface PreviewConfig { + /** + the caption or filename to display for each initial preview item content. + */ + caption: string; + /** + the CSS width of the image/ content displayed. + */ + width: string; + /** + the URL for deleting the image/ content in the initial preview via AJAX post response.This will default to deleteUrl if not set. + */ + url: string; + /** + the key that will be passed as data to the url via AJAX POST. + */ + key: string | {}; + /** + the additional frame css class to set for the file's thumbnail frame. + */ + frameClass: string; + /** + the HTML attribute settings (set as key:value pairs) for the thumbnail frame. + */ + frameAttr: {}; + /** + the extra data that will be passed as data to the initial preview delete url / AJAX server call via POST.This will default to deleteExtraData if not set. + */ + extra: {} | Function; + } + + interface LayoutTemplates { + /** + the template for rendering the widget with caption. + The following tags will be parsed and replaced automatically: + {class}: the CSS class as set in the mainClass property. + {close}: will be replaced with the close (cross) icon (by default on top right of the preview window). The layout template to control this markup is layoutTemplates.close. + {preview}: the content parsed by the previewTemplate and will be displayed only if showPreview is true. + {caption}: the content parsed by the captionTemplate and will be displayed only if showCaption is true. + {remove}: the file remove/clear button and will be displayed only if showRemove is true. + {upload}: the file upload button and will be displayed only if showUpload is true. + {cancel}: the file upload cancel button that will be displayed when AJAX upload is in process to abort the AJAX upload. + {browse}: the main file browse button to select your files for input. + */ + main1?: string; + /** + the template for rendering the widget without caption. + The following tags will be parsed and replaced automatically: + {class}: the CSS class as set in the mainClass property. + {close}: will be replaced with the close (cross) icon (by default on top right of the preview window). The layout template to control this markup is layoutTemplates.close. + {preview}: the content parsed by the previewTemplate and will be displayed only if showPreview is true. + {caption}: the content parsed by the captionTemplate and will be displayed only if showCaption is true. + {remove}: the file remove/clear button and will be displayed only if showRemove is true. + {upload}: the file upload button and will be displayed only if showUpload is true. + {cancel}: the file upload cancel button that will be displayed when AJAX upload is in process to abort the AJAX upload. + {browse}: the main file browse button to select your files for input. + */ + main2?: string; + /** + the template for rendering the preview. + The following tags will be parsed and replaced automatically: + {class}: the CSS class as set in the previewClass property. + */ + preview?: string; + /** + the icon to render before the caption text. + */ + icon?: string; + /** + the template for rendering the caption. + The following tags will be parsed and replaced automatically: + {class}: the CSS class as set in the captionClass property. + */ + caption?: string; + /** + the template for rendering the modal (for text file preview zooming). + */ + modal?: string; + /** + the template for the progress bar when upload is in progress (for batch/mass uploads and within each preview thumbnail for async/single uploads). + The upload progress bar when displayed within each thumbnail will be wrapped inside a container having a CSS class of `file-thumb-progress`. + The following tags will be parsed and replaced automatically: + {percent}: will be replaced with the upload progress percentage. + */ + progress?: string; + /** + the template for the footer section of each file preview thumbnail. + The following tags will be parsed and replaced automatically: + {actions}: will be replaced with the output of the actions template. + {class}: the CSS class as set in the progressClass or progressCompleteClass property (depending on the progress percentage). + */ + footer?: string; + /** + the template for the file action buttons to be displayed within the thumbnail footer. + The following tags will be parsed and replaced automatically: + {upload}: will be replaced with the output of the actionUpload template. + {delete}: will be replaced with the output of the actionDelete template. + */ + actions?: string; + /** + the template for the file delete action button within the thumbnail footer. + The following tags will be parsed and replaced automatically: + {removeClass}: the css class for the remove button. Will be replaced with the removeClass set within fileActionSettings. + {removeIcon}: the icon for the remove button. Will be replaced with the removeIcon set within fileActionSettings. + {removeTitle}: the title to display on hover for the remove button. Will be replaced with the removeTitle set within fileActionSettings. + {dataUrl}: the URL for deleting the file thumbnail for initialPreview content only. Will be replaced with the url set within initialPreviewConfig. + {dataKey}: the key (additional data) that will be passed to the URL above via POST to the AJAX call. Will be replaced with the key set within initialPreviewConfig. + */ + actionDelete?: string; + /** + the template for the file upload action button within the thumbnail footer. + The following tags will be parsed and replaced automatically: + {uploadClass}: the css class for the upload button. Will be replaced with the uploadClass set within fileActionSettings. + {uploadIcon}: the icon for the upload button. Will be replaced with the uploadIcon set within fileActionSettings. + {uploadTitle}: the title to display on hover for the upload button. Will be replaced with the uploadTitle set within fileActionSettings. + */ + actionUpload?: string; + /** + The template for upload, remove, and cancel buttons. + The following tags will be parsed and replaced automatically: + {type}: the HTML button type, defaults to button for most buttons and submit for form based uploads. + {title}: the title to display on button hover. + {css}: the CSS class for the button. This is derived from settings for uploadClass or removeClass or cancelClass. + {status}: the disabled status for the button if available (else will be blank). + {icon}: the button icon as identified by uploadIcon or removeIcon or cancelIcon. + {label}: the button label as identified by uploadLabel or removeLabel or cancelLabel. + */ + btnDefault?: string; + /** + The template for upload button when used with ajax (i.e. when uploadUrl is set). + The following tags will be parsed and replaced automatically: + {type}: the HTML button type, defaults to button for most buttons and submit for form based uploads. + {title}: the title to display on button hover. + {css}: the CSS class for the button. This is derived from settings for uploadClass. + {status}: the disabled status for the button if available (else will be blank). + {icon}: the button icon as identified by uploadIcon. + {label}: the button label as identified by uploadLabel. + {href}: applicable only for Upload button for ajax uploads and will be replaced with the uploadUrl property. + */ + btnLink?: string; + /** + The template for the browse button. + {type}: the HTML button type, defaults to button for most buttons and submit for form based uploads. + {title}: the title to display on button hover. + {css}: the CSS class for the button. This is derived from settings for browseClass. + {status}: the disabled status for the button if available (else will be blank). + {icon}: the button icon as identified by browseIcon. + {label}: the button label as identified by browseLabel. + */ + btnBrowse?: string; + } + + interface PreviewTemplates { + /** + the preview template for image files. + The following tags will be parsed and replaced automatically: + {previewId}: will be replaced with the generated identifier for the preview frame container. + {data}: will be replaced with the data source for each preview type. + {width}: will be replaced with the width for the file type as set in previewSettings. + {height}: will be replaced with the height for the file type as set in previewSettings. + {caption}: will be replaced with the file name. + {type}: will be replaced with the file type. + */ + image?: string; + /** + the preview template for text files. + The following tags will be parsed and replaced automatically: + {previewId}: will be replaced with the generated identifier for the preview frame container. + {data}: will be replaced with the data source for each preview type. + {width}: will be replaced with the width for the file type as set in previewSettings. + {height}: will be replaced with the height for the file type as set in previewSettings. + {caption}: will be replaced with the file name. + {type}: will be replaced with the file type. + {dialog}: Will be replaced with the JS code to launch the modal dialog. + {zoomTitle}: This will be replaced with the msgZoomTitle property. This is the title that is displayed on hover of the zoom button (which on clicking will display the text file). + {zoomInd}: This will be replaced with the zoomIndicator property. This is the title that is displayed on hover of the zoom button (which on clicking will display the text file). + {heading}: This represents the modal dialog heading title. This will be replaced with the msgZoomModalHeading property. + */ + text?: string; + /** + the preview template for html files. + The following tags will be parsed and replaced automatically: + {previewId}: will be replaced with the generated identifier for the preview frame container. + {data}: will be replaced with the data source for each preview type. + {width}: will be replaced with the width for the file type as set in previewSettings. + {height}: will be replaced with the height for the file type as set in previewSettings. + {caption}: will be replaced with the file name. + {type}: will be replaced with the file type. + */ + html?: string; + /** + the preview template for video files (supported by HTML 5 video tag). + The following tags will be parsed and replaced automatically: + {previewId}: will be replaced with the generated identifier for the preview frame container. + {data}: will be replaced with the data source for each preview type. + {width}: will be replaced with the width for the file type as set in previewSettings. + {height}: will be replaced with the height for the file type as set in previewSettings. + {caption}: will be replaced with the file name. + {type}: will be replaced with the file type. + */ + video?: string; + /** + the preview template for audio files (supported by HTML 5 audio tag). + The following tags will be parsed and replaced automatically: + {previewId}: will be replaced with the generated identifier for the preview frame container. + {data}: will be replaced with the data source for each preview type. + {width}: will be replaced with the width for the file type as set in previewSettings. + {height}: will be replaced with the height for the file type as set in previewSettings. + {caption}: will be replaced with the file name. + {type}: will be replaced with the file type. + */ + audio?: string; + /** + the preview template for flash files (supported currently on webkit browsers). + The following tags will be parsed and replaced automatically: + {previewId}: will be replaced with the generated identifier for the preview frame container. + {data}: will be replaced with the data source for each preview type. + {width}: will be replaced with the width for the file type as set in previewSettings. + {height}: will be replaced with the height for the file type as set in previewSettings. + {caption}: will be replaced with the file name. + {type}: will be replaced with the file type. + */ + flash?: string; + /** + the preview template for all other files - by default treated as object. To disable this behavior, configure the allowedPreviewTypes property. + The following tags will be parsed and replaced automatically: + {previewId}: will be replaced with the generated identifier for the preview frame container. + {data}: will be replaced with the data source for each preview type. + {width}: will be replaced with the width for the file type as set in previewSettings. + {height}: will be replaced with the height for the file type as set in previewSettings. + {caption}: will be replaced with the file name. + {type}: will be replaced with the file type. + */ + object?: string; + /** + this template is used ONLY for rendering the initialPreview markup content passed directly as a raw format. + The following tags will be parsed and replaced automatically: + {content}: will be replaced with the raw HTML markup as set in initialPreview.. + */ + generic?: string; + } + + interface PreviewSettings { + image?: { width?: string; height?: string; }; + html?: { width?: string; height?: string; }; + text?: { width?: string; height?: string; }; + video?: { width?: string; height?: string; }; + audio?: { width?: string; height?: string; }; + flash?: { width?: string; height?: string; }; + object?: { width?: string; height?: string; }; + other?: { width?: string; height?: string; }; + } + + interface FileTypeSettings { + image: (vType: string, vName: string) => boolean; + html: (vType: string, vName: string) => boolean; + text: (vType: string, vName: string) => boolean; + video: (vType: string, vName: string) => boolean; + audio: (vType: string, vName: string) => boolean; + flash: (vType: string, vName: string) => boolean; + object: (vType: string, vName: string) => boolean; + other: (vType: string, vName: string) => boolean; + } + + interface PreviewFileIconSettings { + [key: string]: string; + } + + interface PreviewFileExtSettings { + [key: string]: (ext: string) => boolean; + } + + interface FileActionSettings { + /** + icon for remove button to be displayed in each file thumbnail. + */ + removeIcon: string; + /** + CSS class for the remove button in each file thumbnail. + */ + removeClass: string; + /** + title for remove button in each file thumbnail. + */ + removeTitle: string; + /** + icon for upload button to be displayed in each file thumbnail. + */ + uploadIcon: string; + /** + CSS class for the remove button in each file thumbnail. + */ + uploadClass: string; + /** + title for remove button in each file thumbnail. + */ + uploadTitle: string; + /** + an indicator (HTML markup) for new pending upload displayed in each file thumbnail. + */ + indicatorNew: string; + /** + an indicator (HTML markup) for successful upload displayed in each file thumbnail. + */ + indicatorSuccess: string; + /** + an indicator (HTML markup) for error in upload displayed in each file thumbnail. + */ + indicatorError: string; + /** + an indicator (HTML markup) for ongoing upload displayed in each file thumbnail. + */ + indicatorLoading: string; + /** + title to display on hover of indicator for new pending upload in each file thumbnail. + */ + indicatorNewTitle: string; + /** + title to display on hover of indicator for successful in each file thumbnail. + */ + indicatorSuccessTitle: string; + /** + title to display on hover of indicator for error in upload in each file thumbnail. + */ + indicatorErrorTitle: string; + /** + title to display on hover of indicator for ongoing upload in each file thumbnail. + */ + indicatorLoadingTitle: string; + } +} \ No newline at end of file diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index f7dd206708..ce6efe3869 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Electron v1.2.3 +// Type definitions for Electron v1.2.4 // Project: http://electron.atom.io/ // Definitions by: jedmao , rhysd , Milan Burda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -34,7 +34,7 @@ declare namespace Electron { /** * Emitted when the application has finished basic startup. * On Windows and Linux, the will-finish-launching event - * is the same as the ready event; on OS X, this event represents + * is the same as the ready event; on macOS, this event represents * the applicationWillFinishLaunching notification of NSApplication. * You would usually set up listeners for the open-file and open-url events here, * and start the crash reporter and auto updater. @@ -81,7 +81,7 @@ declare namespace Electron { * * You should call event.preventDefault() if you want to handle this event. * - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ on(event: 'open-file', listener: (event: Event, url: string) => void): this; /** @@ -90,12 +90,12 @@ declare namespace Electron { * * You should call event.preventDefault() if you want to handle this event. * - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ on(event: 'open-url', listener: (event: Event, url: string) => void): this; /** * Emitted when the application is activated, which usually happens when clicks on the applications’s dock icon. - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ on(event: 'activate', listener: Function): this; /** @@ -197,18 +197,18 @@ declare namespace Electron { }): void; /** * On Linux, focuses on the first visible window. - * On OS X, makes the application the active app. + * On macOS, makes the application the active app. * On Windows, focuses on the application’s first window. */ focus(): void; /** * Hides all application windows without minimizing them. - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ hide(): void; /** * Shows application windows after they were hidden. Does not automatically focus them. - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ show(): void; /** @@ -257,36 +257,36 @@ declare namespace Electron { * Adds path to recent documents list. * * This list is managed by the system, on Windows you can visit the list from - * task bar, and on Mac you can visit it from dock menu. + * task bar, and on macOS you can visit it from dock menu. * - * Note: This is only implemented on OS X and Windows. + * Note: This is only implemented on macOS and Windows. */ addRecentDocument(path: string): void; /** * Clears the recent documents list. * - * Note: This is only implemented on OS X and Windows. + * Note: This is only implemented on macOS and Windows. */ clearRecentDocuments(): void; /** * Sets the current executable as the default handler for a protocol (aka URI scheme). - * Once registered, all links with your-protocol:// will be openend with the current executable. + * Once registered, all links with your-protocol:// will be opened with the current executable. * The whole link, including protocol, will be passed to your application as a parameter. * - * Note: This is only implemented on OS X and Windows. - * On OS X, you can only register protocols that have been added to your app's info.plist. + * Note: This is only implemented on macOS and Windows. + * On macOS, you can only register protocols that have been added to your app's info.plist. */ setAsDefaultProtocolClient(protocol: string): void; /** * Removes the current executable as the default handler for a protocol (aka URI scheme). * - * Note: This is only implemented on OS X and Windows. + * Note: This is only implemented on macOS and Windows. */ removeAsDefaultProtocolClient(protocol: string): void; /** * @returns Whether the current executable is the default handler for a protocol (aka URI scheme). * - * Note: This is only implemented on OS X and Windows. + * Note: This is only implemented on macOS and Windows. */ isDefaultProtocolClient(protocol: string): boolean; /** @@ -315,13 +315,13 @@ declare namespace Electron { * @param webpageURL The webpage to load in a browser if no suitable app is * installed on the resuming device. The scheme must be http or https. * - * Note: This API is only available on Mac. + * Note: This API is only available on macOS. */ setUserActivity(type: string, userInfo: Object, webpageURL?: string): void; /** * @returns The type of the currently running activity. * - * Note: This API is only available on Mac. + * Note: This API is only available on macOS. */ getCurrentActivityType(): string; /** @@ -343,7 +343,7 @@ declare namespace Electron { disableHardwareAcceleration(): void; commandLine: CommandLine; /** - * Note: This API is only available on Mac. + * Note: This API is only available on macOS. */ dock: Dock; } @@ -393,49 +393,49 @@ declare namespace Electron { /** * Cancel the bounce of id. * - * Note: This API is only available on Mac. + * Note: This API is only available on macOS. */ cancelBounce(id: number): void; /** * Bounces the Downloads stack if the filePath is inside the Downloads folder. * - * Note: This API is only available on Mac. + * Note: This API is only available on macOS. */ downloadFinished(filePath: string): void; /** * Sets the string to be displayed in the dock’s badging area. * - * Note: This API is only available on Mac. + * Note: This API is only available on macOS. */ setBadge(text: string): void; /** * Returns the badge string of the dock. * - * Note: This API is only available on Mac. + * Note: This API is only available on macOS. */ getBadge(): string; /** * Hides the dock icon. * - * Note: This API is only available on Mac. + * Note: This API is only available on macOS. */ hide(): void; /** * Shows the dock icon. * - * Note: This API is only available on Mac. + * Note: This API is only available on macOS. */ show(): void; /** * Sets the application dock menu. * - * Note: This API is only available on Mac. + * Note: This API is only available on macOS. */ setMenu(menu: Menu): void; /** * Sets the image associated with this dock icon. * - * Note: This API is only available on Mac. + * Note: This API is only available on macOS. */ setIcon(icon: NativeImage | string): void; } @@ -615,17 +615,17 @@ declare namespace Electron { on(event: 'app-command', listener: (event: Event, command: string) => void): this; /** * Emitted when scroll wheel event phase has begun. - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ on(event: 'scroll-touch-begin', listener: Function): this; /** * Emitted when scroll wheel event phase has ended. - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ on(event: 'scroll-touch-end', listener: Function): this; /** * Emitted on 3-finger swipe. - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ on(event: 'swipe', listener: (event: Event, direction: SwipeDirection) => void): this; on(event: string, listener: Function): this; @@ -650,15 +650,21 @@ declare namespace Electron { * Adds devtools extension located at path. The extension will be remembered * so you only need to call this API once, this API is not for programming use. * @returns The extension's name. + * + * Note: This API cannot be called before the ready event of the app module is emitted. */ static addDevToolsExtension(path: string): string; /** * Remove a devtools extension. * @param name The name of the devtools extension to remove. + * + * Note: This API cannot be called before the ready event of the app module is emitted. */ static removeDevToolsExtension(name: string): void; /** * @returns devtools extensions. + * + * Note: This API cannot be called before the ready event of the app module is emitted. */ static getDevToolsExtensions(): DevToolsExtensions; /** @@ -713,6 +719,10 @@ declare namespace Electron { * @returns Whether the window is visible to the user. */ isVisible(): boolean; + /** + * @returns Whether the window is a modal window. + */ + isModal(): boolean; /** * Maximizes the window. */ @@ -752,7 +762,7 @@ declare namespace Electron { * not included within the aspect ratio calculations. * This API already takes into account the difference between a window’s size and its content size. * - * Note: This API is available only on OS X. + * Note: This API is available only on macOS. */ setAspectRatio(aspectRatio: number, extraSize?: Dimension): void; /** @@ -805,31 +815,31 @@ declare namespace Electron { isResizable(): boolean; /** * Sets whether the window can be moved by user. On Linux does nothing. - * Note: This API is available only on OS X and Windows. + * Note: This API is available only on macOS and Windows. */ setMovable(movable: boolean): void; /** - * Note: This API is available only on OS X and Windows. + * Note: This API is available only on macOS and Windows. * @returns Whether the window can be moved by user. On Linux always returns true. */ isMovable(): boolean; /** * Sets whether the window can be manually minimized by user. On Linux does nothing. - * Note: This API is available only on OS X and Windows. + * Note: This API is available only on macOS and Windows. */ setMinimizable(minimizable: boolean): void; /** - * Note: This API is available only on OS X and Windows. + * Note: This API is available only on macOS and Windows. * @returns Whether the window can be manually minimized by user. On Linux always returns true. */ isMinimizable(): boolean; /** * Sets whether the window can be manually maximized by user. On Linux does nothing. - * Note: This API is available only on OS X and Windows. + * Note: This API is available only on macOS and Windows. */ setMaximizable(maximizable: boolean): void; /** - * Note: This API is available only on OS X and Windows. + * Note: This API is available only on macOS and Windows. * @returns Whether the window can be manually maximized by user. On Linux always returns true. */ isMaximizable(): boolean; @@ -843,11 +853,11 @@ declare namespace Electron { isFullScreenable(): boolean; /** * Sets whether the window can be manually closed by user. On Linux does nothing. - * Note: This API is available only on OS X and Windows. + * Note: This API is available only on macOS and Windows. */ setClosable(closable: boolean): void; /** - * Note: This API is available only on OS X and Windows. + * Note: This API is available only on macOS and Windows. * @returns Whether the window can be manually closed by user. On Linux always returns true. */ isClosable(): boolean; @@ -883,8 +893,8 @@ declare namespace Electron { */ getTitle(): string; /** - * Changes the attachment point for sheets on Mac OS X. - * Note: This API is available only on OS X. + * Changes the attachment point for sheets on macOS. + * Note: This API is available only on macOS. */ setSheetOffset(offsetY: number, offsetX?: number): void; /** @@ -904,7 +914,7 @@ declare namespace Electron { */ isKiosk(): boolean; /** - * The native type of the handle is HWND on Windows, NSView* on OS X, + * The native type of the handle is HWND on Windows, NSView* on macOS, * and Window (unsigned long) on Linux. * @returns The platform-specific handle of the window as Buffer. */ @@ -929,22 +939,22 @@ declare namespace Electron { /** * Sets the pathname of the file the window represents, and the icon of the * file will show in window's title bar. - * Note: This API is available only on OS X. + * Note: This API is available only on macOS. */ setRepresentedFilename(filename: string): void; /** - * Note: This API is available only on OS X. + * Note: This API is available only on macOS. * @returns The pathname of the file the window represents. */ getRepresentedFilename(): string; /** * Specifies whether the window’s document has been edited, and the icon in * title bar will become grey when set to true. - * Note: This API is available only on OS X. + * Note: This API is available only on macOS. */ setDocumentEdited(edited: boolean): void; /** - * Note: This API is available only on OS X. + * Note: This API is available only on macOS. * @returns Whether the window's document has been edited. */ isDocumentEdited(): boolean; @@ -969,7 +979,7 @@ declare namespace Electron { reload(): void; /** * Sets the menu as the window top menu. - * Note: This API is not available on OS X. + * Note: This API is not available on macOS. */ setMenu(menu: Menu): void; /** @@ -992,11 +1002,11 @@ declare namespace Electron { setOverlayIcon(overlay: NativeImage, description: string): void; /** * Sets whether the window should have a shadow. On Windows and Linux does nothing. - * Note: This API is available only on OS X. + * Note: This API is available only on macOS. */ setHasShadow(hasShadow: boolean): void; /** - * Note: This API is available only on OS X. + * Note: This API is available only on macOS. * @returns whether the window has a shadow. On Windows and Linux always returns true. */ hasShadow(): boolean; @@ -1008,12 +1018,12 @@ declare namespace Electron { setThumbarButtons(buttons: ThumbarButton[]): boolean; /** * Same as webContents.showDefinitionForSelection(). - * Note: This API is available only on OS X. + * Note: This API is available only on macOS. */ showDefinitionForSelection(): void; /** * Changes window icon. - * Note: This API is not available on OS X. + * Note: This API is not available on macOS. */ setIcon(icon: NativeImage): void; /** @@ -1058,6 +1068,20 @@ declare namespace Electron { * Note: This API is available only on Windows. */ setFocusable(focusable: boolean): void; + /** + * Sets parent as current window's parent window, + * passing null will turn current window into a top-level window. + * Note: This API is not available on Windows. + */ + setParentWindow(parent: BrowserWindow): void; + /** + * @returns The parent window. + */ + getParentWindow(): BrowserWindow; + /** + * @returns All child windows. + */ + getChildWindows(): BrowserWindow[]; } type SwipeDirection = 'up' | 'right' | 'down' | 'left'; @@ -1176,7 +1200,7 @@ declare namespace Electron { */ directWrite?: boolean; /** - * Enables scroll bounce (rubber banding) effect on OS X. + * Enables scroll bounce (rubber banding) effect on macOS. * Default: false. */ scrollBounce?: boolean; @@ -1328,13 +1352,13 @@ declare namespace Electron { alwaysOnTop?: boolean; /** * Whether the window should show in fullscreen. - * When explicitly set to false the fullscreen button will be hidden or disabled on OS X. + * When explicitly set to false the fullscreen button will be hidden or disabled on macOS. * Default: false. */ fullscreen?: boolean; /** * Whether the window can be put into fullscreen mode. - * On OS X, also whether the maximize/zoom button should toggle full screen mode or maximize window. + * On macOS, also whether the maximize/zoom button should toggle full screen mode or maximize window. * Default: true. */ fullscreenable?: boolean; @@ -1367,6 +1391,16 @@ declare namespace Electron { * Default: true. */ frame?: boolean; + /** + * Specify parent window. + * Default: null. + */ + parent?: BrowserWindow; + /** + * Whether this is a modal window. This only works when the window is a child window. + * Default: false. + */ + modal?: boolean; /** * Whether the web view accepts a single mouse-down event that simultaneously activates the window. * Default: false. @@ -1394,7 +1428,7 @@ declare namespace Electron { backgroundColor?: string; /** * Whether window should have a shadow. - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. * Default: true. */ hasShadow?: boolean; @@ -1620,7 +1654,7 @@ declare namespace Electron { /** * You are required to call this method before using other crashReporter APIs. * - * Note: On OS X, Electron uses a new crashpad client, which is different from breakpad + * Note: On macOS, Electron uses a new crashpad client, which is different from breakpad * on Windows and Linux. To enable the crash collection feature, you are required to call * the crashReporter.start API to initialize crashpad in the main process and in each * renderer process from which you wish to collect crash reports. @@ -1843,7 +1877,7 @@ declare namespace Electron { /** * The value will be returned when user cancels the dialog instead of clicking the buttons of the dialog. * By default it is the index of the buttons that have "cancel" or "no" as label, - * or 0 if there is no such buttons. On OS X and Windows the index of "Cancel" button + * or 0 if there is no such buttons. On macOS and Windows the index of "Cancel" button * will always be used as cancelId, not matter whether it is already specified. */ cancelId?: number; @@ -2084,7 +2118,7 @@ declare namespace Electron { } type MenuItemType = 'normal' | 'separator' | 'submenu' | 'checkbox' | 'radio'; - type MenuItemRole = 'undo' | 'redo' | 'cut' | 'copy' | 'paste' | 'pasteandmatchstyle' | 'selectall' | 'delete' | 'minimize' | 'close'; + type MenuItemRole = 'undo' | 'redo' | 'cut' | 'copy' | 'paste' | 'pasteandmatchstyle' | 'selectall' | 'delete' | 'minimize' | 'close' | 'quit' | 'togglefullscreen'; type MenuItemRoleMac = 'about' | 'hide' | 'hideothers' | 'unhide' | 'front' | 'zoom' | 'window' | 'help' | 'services'; interface MenuItemOptions { @@ -2108,13 +2142,13 @@ declare namespace Electron { * * Platform notice: * On Linux and Windows, the Command key would not have any effect, - * you can use CommandOrControl which represents Command on OS X and Control on + * you can use CommandOrControl which represents Command on macOS and Control on * Linux and Windows to define some accelerators. * - * Use Alt instead of Option. The Option key only exists on OS X, whereas + * Use Alt instead of Option. The Option key only exists on macOS, whereas * the Alt key is available on all platforms. * - * The Super key is mapped to the Windows key on Windows and Linux and Cmd on OS X. + * The Super key is mapped to the Windows key on Windows and Linux and Cmd on macOS. * * Available modifiers: * Command (or Cmd for short) @@ -2200,16 +2234,20 @@ declare namespace Electron { */ constructor(); /** - * Sets menu as the application menu on OS X. On Windows and Linux, the menu + * Sets menu as the application menu on macOS. On Windows and Linux, the menu * will be set as each window's top menu. */ static setApplicationMenu(menu: Menu): void; + /** + * @returns The application menu if set, or null if not set. + */ + static getApplicationMenu(): Menu; /** * Sends the action to the first responder of application. * This is used for emulating default Cocoa menu behaviors, * usually you would just use the role property of MenuItem. * - * Note: This method is OS X only. + * Note: This method is macOS only. */ static sendActionToFirstResponder(action: string): void; /** @@ -2219,7 +2257,7 @@ declare namespace Electron { */ static buildFromTemplate(template: MenuItemOptions[]): Menu; /** - * Popups this menu as a context menu in the browserWindow. You can optionally + * Pops up this menu as a context menu in the browserWindow. You can optionally * provide a (x,y) coordinate to place the menu at, otherwise it will be placed * at the current mouse cursor position. * @param x Horizontal coordinate where the menu will be placed. @@ -2276,8 +2314,8 @@ declare namespace Electron { */ toDataURL(): string; /** - * The native type of the handle is NSImage* on OS X. - * Note: This is only implemented on OS X. + * The native type of the handle is NSImage* on macOS. + * Note: This is only implemented on macOS. * @returns The platform-specific handle of the image as Buffer. */ getNativeHandle(): Buffer; @@ -3072,26 +3110,34 @@ declare namespace Electron { /** * @returns If the system is in Dark Mode. * - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ isDarkMode(): boolean; /** - * Subscribes to native notifications of OS X, callback will be called when the corresponding event happens. + * Subscribes to native notifications of macOS, callback will be called when the corresponding event happens. * The id of the subscriber is returned, which can be used to unsubscribe the event. * - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ subscribeNotification(event: string, callback: (event: Event, userInfo: Object) => void): number; /** * Removes the subscriber with id. * - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ unsubscribeNotification(id: number): void; + /** + * Same as subscribeNotification, but uses NSNotificationCenter for local defaults. + */ + subscribeLocalNotification(event: string, callback: (event: Event, userInfo: Object) => void): number; + /** + * Same as unsubscribeNotification, but removes the subscriber from NSNotificationCenter. + */ + unsubscribeLocalNotification(id: number): void; /** * Get the value of key in system preferences. * - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ getUserDefault(key: string, type: 'string' | 'boolean' | 'integer' | 'float' | 'double' | 'url' | 'array' | 'dictionary'): any; /** @@ -3112,17 +3158,17 @@ declare namespace Electron { interface Tray extends NodeJS.EventEmitter { /** * Emitted when the tray icon is clicked. - * Note: The bounds payload is only implemented on OS X and Windows. + * Note: The bounds payload is only implemented on macOS and Windows. */ on(event: 'click', listener: (modifiers: Modifiers, bounds: Bounds) => void): this; /** * Emitted when the tray icon is right clicked. - * Note: This is only implemented on OS X and Windows. + * Note: This is only implemented on macOS and Windows. */ on(event: 'right-click', listener: (modifiers: Modifiers, bounds: Bounds) => void): this; /** * Emitted when the tray icon is double clicked. - * Note: This is only implemented on OS X and Windows. + * Note: This is only implemented on macOS and Windows. */ on(event: 'double-click', listener: (modifiers: Modifiers, bounds: Bounds) => void): this; /** @@ -3142,27 +3188,27 @@ declare namespace Electron { on(event: 'balloon-closed', listener: Function): this; /** * Emitted when any dragged items are dropped on the tray icon. - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ on(event: 'drop', listener: Function): this; /** * Emitted when dragged files are dropped in the tray icon. - * Note: This is only implemented on OS X + * Note: This is only implemented on macOS */ on(event: 'drop-files', listener: (event: Event, files: string[]) => void): this; /** * Emitted when a drag operation enters the tray icon. - * Note: This is only implemented on OS X + * Note: This is only implemented on macOS */ on(event: 'drag-enter', listener: Function): this; /** * Emitted when a drag operation exits the tray icon. - * Note: This is only implemented on OS X + * Note: This is only implemented on macOS */ on(event: 'drag-leave', listener: Function): this; /** * Emitted when a drag operation ends on the tray or ends at another location. - * Note: This is only implemented on OS X + * Note: This is only implemented on macOS */ on(event: 'drag-end', listener: Function): this; on(event: string, listener: Function): this; @@ -3188,12 +3234,12 @@ declare namespace Electron { setToolTip(toolTip: string): void; /** * Sets the title displayed aside of the tray icon in the status bar. - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ setTitle(title: string): void; /** * Sets whether the tray icon is highlighted when it is clicked. - * Note: This is only implemented on OS X. + * Note: This is only implemented on macOS. */ setHighlightMode(highlight: boolean): void; /** @@ -3206,16 +3252,20 @@ declare namespace Electron { content?: string; }): void; /** - * Popups the context menu of tray icon. When menu is passed, + * Pops up the context menu of tray icon. When menu is passed, * the menu will showed instead of the tray's context menu. * The position is only available on Windows, and it is (0, 0) by default. - * Note: This is only implemented on OS X and Windows. + * Note: This is only implemented on macOS and Windows. */ popUpContextMenu(menu?: Menu, position?: Point): void; /** * Sets the context menu for this icon. */ setContextMenu(menu: Menu): void; + /** + * @returns The bounds of this tray icon. + */ + getBounds(): Bounds; } interface Modifiers { @@ -3692,7 +3742,7 @@ declare namespace Electron { savePage(fullPath: string, saveType: 'HTMLOnly' | 'HTMLComplete' | 'MHTML', callback?: (eror: Error) => void): boolean; /** * Shows pop-up dictionary that searches the selected word on the page. - * Note: This API is available only on OS X. + * Note: This API is available only on macOS. */ showDefinitionForSelection(): void; /** @@ -3721,11 +3771,11 @@ declare namespace Electron { interface ContextMenuParams { /** - * x coodinate + * x coordinate */ x: number; /** - * y coodinate + * y coordinate */ y: number; /** @@ -4482,7 +4532,7 @@ declare namespace Electron { sendInputEvent(event: SendInputEvent): void /** * Shows pop-up dictionary that searches the selected word on the page. - * Note: This API is available only on OS X. + * Note: This API is available only on macOS. */ showDefinitionForSelection(): void; /** @@ -4873,7 +4923,7 @@ declare namespace NodeJS { * Sets the file descriptor soft limit to maxDescriptors or the OS hard limit, * whichever is lower for the current process. * - * Note: This API is only available on Mac and Linux. + * Note: This API is only available on macOS and Linux. */ setFdLimit(maxDescriptors: number): void; /** diff --git a/hammerjs/hammerjs.d.ts b/hammerjs/hammerjs.d.ts index 80487c134c..bfc6e7cb4f 100644 --- a/hammerjs/hammerjs.d.ts +++ b/hammerjs/hammerjs.d.ts @@ -39,7 +39,7 @@ interface HammerStatic DIRECTION_VERTICAL: number; DIRECTION_ALL: number; - Manager: HammerManager; + Manager: HammerManagerConstructor; Input: HammerInput; TouchAction: TouchAction; @@ -95,10 +95,12 @@ interface HammerOptions extends HammerDefaults } +interface HammerManagerConstructor { + new( element:HTMLElement, options?:any ):HammerManager; +} + interface HammerManager { - new( element:HTMLElement, options?:any ):HammerManager; - add( recogniser:Recognizer ):Recognizer; add( recogniser:Recognizer ):HammerManager; add( recogniser:Recognizer[] ):Recognizer; diff --git a/inversify-binding-decorators/inversify-binding-decorators-tests.ts b/inversify-binding-decorators/inversify-binding-decorators-tests.ts new file mode 100644 index 0000000000..9b0dff520e --- /dev/null +++ b/inversify-binding-decorators/inversify-binding-decorators-tests.ts @@ -0,0 +1,159 @@ +/// + +import { inject, Kernel } from "inversify"; +import { autoProvide, makeProvideDecorator, makeFluentProvideDecorator } from "inversify-binding-decorators"; + +module decorator { + let kernel = new Kernel(); + let provide = makeProvideDecorator(kernel); + + interface INinja { + fight(): string; + sneak(): string; + } + + interface IKatana { + hit(): string; + } + + interface IShuriken { + throw(): string; + } + + let TYPE = { + IKatana: "IKatana", + INinja: "INinja", + IShuriken: "IShuriken" + }; + + @provide(TYPE.IKatana) + class Katana implements IKatana { + public hit() { + return "cut!"; + } + } + + @provide(TYPE.IShuriken) + class Shuriken implements IShuriken { + public throw() { + return "hit!"; + } + } + + @provide(TYPE.INinja) + class Ninja implements INinja { + + private _katana: IKatana; + private _shuriken: IShuriken; + + public constructor( + @inject("IKatana") katana: IKatana, + @inject("IShuriken") shuriken: IShuriken + ) { + this._katana = katana; + this._shuriken = shuriken; + } + + public fight() { return this._katana.hit(); }; + public sneak() { return this._shuriken.throw(); }; + + } + + let ninja = kernel.get(TYPE.INinja); + console.log(ninja); + +} + +module fluent_decorator { + let kernel = new Kernel(); + let provide = makeFluentProvideDecorator(kernel); + + let provideSingleton = function(identifier: string) { + return provide(identifier).inSingletonScope().done(); + }; + + let provideTransient = function(identifier: string) { + return provide(identifier).done(); + }; + + interface INinja { + fight(): string; + sneak(): string; + } + + interface IKatana { + hit(): string; + } + + interface IShuriken { + throw(): string; + } + + let TYPE = { + IKatana: "IKatana", + INinja: "INinja", + IShuriken: "IShuriken" + }; + + @provideSingleton(TYPE.IKatana) + class Katana implements IKatana { + private _mark: any; + public constructor() { + this._mark = Math.random(); + } + public hit() { + return "cut! " + this._mark; + } + } + + @provideTransient(TYPE.IShuriken) + class Shuriken implements IShuriken { + private _mark: any; + public constructor() { + this._mark = Math.random(); + } + public throw() { + return "hit! " + this._mark; + } + } + + @provideTransient(TYPE.INinja) + class Ninja implements INinja { + + private _katana: IKatana; + private _shuriken: IShuriken; + + public constructor( + @inject("IKatana") katana: IKatana, + @inject("IShuriken") shuriken: IShuriken + ) { + this._katana = katana; + this._shuriken = shuriken; + } + + public fight() { return this._katana.hit(); }; + public sneak() { return this._shuriken.throw(); }; + + } + + let ninja = kernel.get(TYPE.INinja); + console.log(ninja); + +} + +module auto_provide { + + let warriors = { + Ninja: class Ninja {}, + Samurai: class Samurai {} + }; + + let weapons = { + Katana: class Katana {}, + Shuriken: class Shuriken {}, + }; + + let kernel = new Kernel(); + autoProvide(kernel, warriors, weapons); + +} diff --git a/inversify-binding-decorators/inversify-binding-decorators.d.ts b/inversify-binding-decorators/inversify-binding-decorators.d.ts new file mode 100644 index 0000000000..623b6c32c7 --- /dev/null +++ b/inversify-binding-decorators/inversify-binding-decorators.d.ts @@ -0,0 +1,55 @@ +// Type definitions for inversify 1.0.0-beta.5 +// Project: https://github.com/inversify/inversify-binding-decorators +// Definitions by: inversify +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare namespace inversifyBindingDecorators { + + interface IProvideInSyntax extends IProvideDoneSyntax { + inSingletonScope(): IProvideWhenOnSyntax; + } + + interface IProvideDoneSyntax { + done(): (target: any) => any; + } + + interface IProvideOnSyntax extends IProvideDoneSyntax { + onActivation(fn: (context: inversify.interfaces.Context, injectable: T) => T): IProvideWhenSyntax; + } + + interface IProvideInWhenOnSyntax extends IProvideInSyntax, IProvideWhenSyntax, IProvideOnSyntax {} + + interface IProvideWhenOnSyntax extends IProvideWhenSyntax, IProvideOnSyntax {} + + interface IProvideWhenSyntax extends IProvideDoneSyntax { + when(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax; + whenTargetNamed(name: string): IProvideOnSyntax; + whenTargetTagged(tag: string, value: any): IProvideOnSyntax; + whenInjectedInto(parent: (Function|string)): IProvideOnSyntax; + whenParentNamed(name: string): IProvideOnSyntax; + whenParentTagged(tag: string, value: any): IProvideOnSyntax; + whenAnyAncestorIs(ancestor: (Function|string)): IProvideOnSyntax; + whenNoAncestorIs(ancestor: (Function|string)): IProvideOnSyntax; + whenAnyAncestorNamed(name: string): IProvideOnSyntax; + whenAnyAncestorTagged(tag: string, value: any): IProvideOnSyntax; + whenNoAncestorNamed(name: string): IProvideOnSyntax; + whenNoAncestorTagged(tag: string, value: any): IProvideOnSyntax; + whenAnyAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax; + whenNoAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax; + } + + export function autoProvide(kernel: inversify.interfaces.Kernel, ...modules: any[]): void; + + export function makeProvideDecorator(kernel: inversify.interfaces.Kernel): + (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => (target: any) => any; + + export function makeFluentProvideDecorator(kernel: inversify.interfaces.Kernel): + (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => IProvideInWhenOnSyntax; + +} + +declare module "inversify-binding-decorators" { + export = inversifyBindingDecorators; +} diff --git a/inversify-express-utils/inversify-express-utils-tests.ts b/inversify-express-utils/inversify-express-utils-tests.ts new file mode 100644 index 0000000000..1d421e397a --- /dev/null +++ b/inversify-express-utils/inversify-express-utils-tests.ts @@ -0,0 +1,89 @@ +/// + +import { InversifyExpressServer, Controller, Get, All, Delete, Head, Put, Patch, Post, Method } from "inversify-express-utils"; +import * as express from "express"; +import { Kernel } from "inversify"; + +module server { + let kernel = new Kernel(); + let server = new InversifyExpressServer(kernel); + + server + .setConfig((app) => { + app.use((req: express.Request, res: express.Response, next: express.NextFunction) => { + console.log("hello world"); + next(); + }); + }) + .setErrorConfig((app) => { + app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => { + console.error(err.stack); + res.status(500).send("Something broke!"); + }); + }) + .build() + .listen(3000, "localhost"); +} + +module decorators { + + @Controller("/") + class TestController { + + @Get("/") + public testGet() { return "GET"; } + + @All("/") + public testAll() { return "ALL"; } + + @Delete("/") + public testDelete() { return "DELETE"; } + + @Head("/") + public testHead() { return "HEAD"; } + + @Put("/") + public testPut() { return "PUT"; } + + @Patch("/") + public testPatch() { return "PATCH"; } + + @Post("/") + public testPost() { return "POST"; } + + @Method("foo", "/") + public testMethod() { return "METHOD:FOO"; } + } + + function m1(req: express.Request, res: express.Response, next: express.NextFunction) { next(); } + function m2(req: express.Request, res: express.Response, next: express.NextFunction) { next(); } + function m3(req: express.Request, res: express.Response, next: express.NextFunction) { next(); } + + @Controller("/", m1, m2, m3) + class TestMiddlewareController { + + @Get("/", m1, m2, m3) + public testGet() { return "GET"; } + + @All("/", m1, m2, m3) + public testAll() { return "ALL"; } + + @Delete("/", m1, m2, m3) + public testDelete() { return "DELETE"; } + + @Head("/", m1, m2, m3) + public testHead() { return "HEAD"; } + + @Put("/", m1, m2, m3) + public testPut() { return "PUT"; } + + @Patch("/", m1, m2, m3) + public testPatch() { return "PATCH"; } + + @Post("/", m1, m2, m3) + public testPost() { return "POST"; } + + @Method("foo", "/", m1, m2, m3) + public testMethod() { return "METHOD:FOO"; } + } +} diff --git a/inversify-express-utils/inversify-express-utils.d.ts b/inversify-express-utils/inversify-express-utils.d.ts new file mode 100644 index 0000000000..aa9a20d23c --- /dev/null +++ b/inversify-express-utils/inversify-express-utils.d.ts @@ -0,0 +1,50 @@ +// Type definitions for inversify 1.0.0-alpha.4 +// Project: https://github.com/inversify/inversify-express-utils +// Definitions by: inversify +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "inversify-express-utils" { + + import * as express from "express"; + import * as inversify from "inversify"; + + interface IInversifyExpressServerConstructor { + new(kernel: inversify.interfaces.Kernel): IInversifyExpressServer; + } + + interface IInversifyExpressServer { + setConfig(fn: IConfigFunction): IInversifyExpressServer; + setErrorConfig(fn: IConfigFunction): IInversifyExpressServer; + build(): express.Application; + } + + interface IConfigFunction { + (app: express.Application): void; + } + + interface IHandlerDecoratorFactory { + (path: string, ...middleware: express.RequestHandler[]): IHandlerDecorator; + } + + interface IHandlerDecorator { + (target: any, key: string, value: any): void; + } + + export interface IController {} + + export var InversifyExpressServer: IInversifyExpressServerConstructor; + + export var Controller: (path: string, ...middleware: express.RequestHandler[]) => (target: any) => void; + + export var All: IHandlerDecoratorFactory; + export var Get: IHandlerDecoratorFactory; + export var Post: IHandlerDecoratorFactory; + export var Put: IHandlerDecoratorFactory; + export var Patch: IHandlerDecoratorFactory; + export var Head: IHandlerDecoratorFactory; + export var Delete: IHandlerDecoratorFactory; + export var Method: (method: string, path: string, ...middleware: express.RequestHandler[]) => IHandlerDecorator; +} diff --git a/inversify-logger-middleware/inversify-logger-middleware-tests.ts b/inversify-logger-middleware/inversify-logger-middleware-tests.ts new file mode 100644 index 0000000000..c9c7d5c8a8 --- /dev/null +++ b/inversify-logger-middleware/inversify-logger-middleware-tests.ts @@ -0,0 +1,59 @@ +/// + +declare var kernel: inversify.interfaces.Kernel; + +import { makeLoggerMiddleware, textSerializer } from "inversify-logger-middleware"; + +interface ILoggerOutput { + entry: T; +} + +let makeStringRenderer = function (loggerOutput: ILoggerOutput) { + return function (entry: inversifyLoggerMiddleware.ILogEntry) { + loggerOutput.entry = textSerializer(entry); + }; +}; + +let makeObjRenderer = function (loggerOutput: ILoggerOutput) { + return function (entry: inversifyLoggerMiddleware.ILogEntry) { + loggerOutput.entry = entry; + }; +}; + +let options: inversifyLoggerMiddleware.ILoggerSettings = { + request: { + bindings: { + activated: true, + cache: true, + constraint: true, + dynamicValue: true, + factory: true, + implementationType: true, + onActivation: true, + provider: true, + scope: true, + serviceIdentifier: true, + type: true + }, + serviceIdentifier: true, + target: { + metadata: true, + name: true, + serviceIdentifier: true + } + }, + time: true +}; + +let logger = makeLoggerMiddleware(); +kernel.applyMiddleware(logger); + +let loggerOutput1: ILoggerOutput = { entry: null }; +let stringRenderer1 = makeStringRenderer(loggerOutput1); +let logger1 = makeLoggerMiddleware(options, stringRenderer1); +kernel.applyMiddleware(logger1); + +let loggerOutput2: ILoggerOutput = { entry: null }; +let objRenderer2 = makeObjRenderer(loggerOutput2); +let logger2 = makeLoggerMiddleware(options, objRenderer2); +kernel.applyMiddleware(logger2); diff --git a/inversify-logger-middleware/inversify-logger-middleware.d.ts b/inversify-logger-middleware/inversify-logger-middleware.d.ts new file mode 100644 index 0000000000..3aa4ccca18 --- /dev/null +++ b/inversify-logger-middleware/inversify-logger-middleware.d.ts @@ -0,0 +1,59 @@ +// Type definitions for inversify 1.0.0-beta.6 +// Project: https://github.com/inversify/inversify-logger-middleware +// Definitions by: inversify +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare namespace inversifyLoggerMiddleware { + + export interface ILoggerSettings { + request?: IRequestLoggerSettings; + time?: boolean; + } + + export interface IRequestLoggerSettings { + serviceIdentifier?: boolean; + bindings?: IBindingLoggerSettings; + target?: ITargetLoggerSettings; + } + + export interface IBindingLoggerSettings { + activated?: boolean; + serviceIdentifier?: boolean; + implementationType?: boolean; + factory?: boolean; + provider?: boolean; + constraint?: boolean; + onActivation?: boolean; + cache?: boolean; + dynamicValue?: boolean; + scope?: boolean; + type?: boolean; + } + + export interface ITargetLoggerSettings { + serviceIdentifier?: boolean; + name?: boolean; + metadata?: boolean; + } + + export interface ILogEntry { + error: boolean; + exception: any; + multiInject: boolean; + results: any[]; + rootRequest: inversify.interfaces.Request; + serviceIdentifier: any; + target: any; + time: string; + } + + export function makeLoggerMiddleware(settings?: ILoggerSettings, renderer?: (out: ILogEntry) => void): inversify.interfaces.Middleware; + export function textSerializer(entry: ILogEntry): string; + +} + +declare module "inversify-logger-middleware" { + export = inversifyLoggerMiddleware; +} diff --git a/inversify/inversify-global-tests.ts b/inversify/inversify-global-tests.ts index c39b231b91..e2ead555d4 100644 --- a/inversify/inversify-global-tests.ts +++ b/inversify/inversify-global-tests.ts @@ -1,39 +1,65 @@ -/// +/// +/// -namespace global_module_test { +let injectable = inversify.injectable; +let inject = inversify.inject; +let tagged = inversify.tagged; +let named = inversify.named; +let Kernel = inversify.Kernel; +let KernelModule = inversify.KernelModule; +let targetName = inversify.targetName; +let multiInject = inversify.multiInject; +let traverseAncerstors = inversify.traverseAncerstors; +let taggedConstraint = inversify.taggedConstraint; +let namedConstraint = inversify.namedConstraint; +let typeConstraint = inversify.typeConstraint; +let makePropertyMultiInjectDecorator = inversify.makePropertyMultiInjectDecorator; +let makePropertyInjectTaggedDecorator = inversify.makePropertyInjectTaggedDecorator; +let makePropertyInjectNamedDecorator = inversify.makePropertyInjectNamedDecorator; +let makePropertyInjectDecorator = inversify.makePropertyInjectDecorator; - interface INinja { +module external_module_test { + + interface Warrior { fight(): string; sneak(): string; } - interface IKatana { + interface Weapon { hit(): string; } - interface IShuriken { + interface ThrowableWeapon extends Weapon { throw(): string; } - class Katana implements IKatana { + @injectable() + class Katana implements Weapon { public hit() { return "cut!"; } } - class Shuriken implements IShuriken { + @injectable() + class Shuriken implements ThrowableWeapon { public throw() { return "hit!"; } + public hit() { + return "hit!"; + } } - @inversify.inject("IKatana", "IShuriken") - class Ninja implements INinja { + @injectable() + class Ninja implements Warrior { - private _katana: IKatana; - private _shuriken: IShuriken; + private _katana: Weapon; + private _shuriken: ThrowableWeapon; - public constructor(katana: IKatana, shuriken: IShuriken) { + public constructor( + @inject("Weapon") katana: Weapon, + @inject("ThrowableWeapon") shuriken: ThrowableWeapon + ) { this._katana = katana; this._shuriken = shuriken; } @@ -43,62 +69,73 @@ namespace global_module_test { } - let kernel = new inversify.Kernel(); - kernel.bind("INinja").to(Ninja); - kernel.bind("IKatana").to(Katana); - kernel.bind("IShuriken").to(Shuriken).inSingletonScope(); + let kernel: inversify.interfaces.Kernel = new Kernel(); + kernel.bind("Warrior").to(Ninja); + kernel.bind("Weapon").to(Katana); + kernel.bind("ThrowableWeapon").to(Shuriken).inSingletonScope(); - let ninja = kernel.get("INinja"); + let ninja = kernel.get("Warrior"); console.log(ninja); // Unbind - kernel.unbind("INinja"); + kernel.unbind("Warrior"); kernel.unbindAll(); // Kernel modules - let module: inversify.IKernelModule = (k: inversify.IKernel) => { - k.bind("INinja").to(Ninja); - k.bind("IKatana").to(Katana).inTransientScope(); - k.bind("IShuriken").to(Shuriken).inSingletonScope(); - }; + let warriors: inversify.interfaces.KernelModule = new KernelModule((bind: inversify.interfaces.Bind) => { + bind("Warrior").to(Ninja); + }); - let options: inversify.IKernelOptions = { - middleware: [], - modules: [module] - }; + let weapons: inversify.interfaces.KernelModule = new KernelModule((bind: inversify.interfaces.Bind) => { + bind("Weapon").to(Katana); + bind("ThrowableWeapon").to(Shuriken); + }); - kernel = new inversify.Kernel(options); - let ninja2 = kernel.get("INinja"); + kernel = new Kernel(); + kernel.load(warriors, weapons); + let ninja2 = kernel.get("Warrior"); console.log(ninja2); + // middleware + function logger(planAndResolve: inversify.interfaces.PlanAndResolve): inversify.interfaces.PlanAndResolve { + return (args: inversify.interfaces.PlanAndResolveArgs) => { + let start = new Date().getTime(); + let result = planAndResolve(args); + let end = new Date().getTime(); + console.log(end - start); + return result; + }; + } + + kernel.applyMiddleware(logger, logger); + // binding types - kernel.bind("IKatana").to(Katana); - kernel.bind("IKatana").toValue(new Katana()); + kernel.bind("Weapon").to(Katana); + kernel.bind("Weapon").toConstantValue(new Katana()); + kernel.bind("Weapon").toDynamicValue(() => { return new Katana(); }); - kernel.bind>("IKatana").toConstructor(Katana); + kernel.bind>("Weapon").toConstructor(Katana); - kernel.bind>("IKatana").toFactory((context) => { + kernel.bind>("Weapon").toFactory((context) => { return () => { - return kernel.get("IKatana"); + return kernel.get("Weapon"); }; }); - kernel.bind>("IKatana").toAutoFactory(); + kernel.bind>("Weapon").toAutoFactory("Weapon"); - kernel.bind>("IKatana").toProvider((context) => { + kernel.bind>("Weapon").toProvider((context) => { return () => { - return new Promise((resolve) => { - let katana = kernel.get("IKatana"); + return new Promise((resolve) => { + let katana = kernel.get("Weapon"); resolve(katana); }); }; }); - kernel.bind("IKatana").to(Katana).proxy((katanaToBeInjected: IKatana) => { - // BLOCK http://stackoverflow.com/questions/35906938/how-to-enable-harmony-proxies-in-gulp-mocha - /* + kernel.bind("Weapon").to(Katana).onActivation((context: inversify.interfaces.Context, katanaToBeInjected: Weapon) => { let handler = { - apply: function(target, thisArgument, argumentsList) { + apply: function(target: any, thisArgument: any, argumentsList: any[]) { console.log(`Starting: ${performance.now()}`); let result = target.apply(thisArgument, argumentsList); console.log(`Finished: ${performance.now()}`); @@ -106,88 +143,301 @@ namespace global_module_test { } }; return new Proxy(katanaToBeInjected, handler); - */ - return katanaToBeInjected; }); - interface IWeapon {} - interface ISamurai { - katana: IWeapon; - shuriken: IWeapon; - } - - @inversify.inject("IWeapon", "IWeapon") - class Samurai implements ISamurai { - public katana: IWeapon; - public shuriken: IWeapon; + @injectable() + class Samurai implements Warrior { + public katana: Weapon; + public shuriken: ThrowableWeapon; public constructor( - @inversify.tagged("canThrow", false) katana: IWeapon, - @inversify.tagged("canThrow", true) shuriken: IWeapon + @inject("Weapon") @tagged("canThrow", false) katana: Weapon, + @inject("ThrowableWeapon") @tagged("canThrow", true) shuriken: ThrowableWeapon ) { this.katana = katana; this.shuriken = shuriken; } + public fight() { return this.katana.hit(); }; + public sneak() { return this.shuriken.throw(); }; } kernel.bind("Samurai").to(Samurai); - kernel.bind("IWeapon").to(Katana).whenTargetTagged("canThrow", false); - kernel.bind("IWeapon").to(Shuriken).whenTargetTagged("canThrow", true); + kernel.bind("IWeapon").to(Katana).whenTargetTagged("canThrow", false); + kernel.bind("ThrowableWeapon").to(Shuriken).whenTargetTagged("canThrow", true); - let throwable = inversify.tagged("canThrow", true); - let notThrowable = inversify.tagged("canThrow", false); + let throwable = tagged("canThrow", true); + let notThrowable = tagged("canThrow", false); - @inversify.inject("IWeapon", "IWeapon") - class Samurai2 implements ISamurai { - public katana: IWeapon; - public shuriken: IWeapon; + @injectable() + class Samurai2 implements Samurai { + public katana: Weapon; + public shuriken: ThrowableWeapon; public constructor( - @throwable("canThrow", false) katana: IWeapon, - @notThrowable("canThrow", true) shuriken: IWeapon + @inject("Weapon") @throwable katana: Weapon, + @inject("ThrowableWeapon") @notThrowable shuriken: ThrowableWeapon ) { this.katana = katana; this.shuriken = shuriken; } + public fight() { return this.katana.hit(); }; + public sneak() { return this.shuriken.throw(); }; } - @inversify.inject("IWeapon", "IWeapon") - class Samurai3 implements ISamurai { - public katana: IWeapon; - public shuriken: IWeapon; + @injectable() + class Samurai3 implements Samurai { + public katana: Weapon; + public shuriken: ThrowableWeapon; public constructor( - @inversify.named("strong") katana: IWeapon, - @inversify.named("weak") shuriken: IWeapon + @inject("Weapon") @named("strong") katana: Weapon, + @inject("ThrowableWeapon") @named("weak") shuriken: ThrowableWeapon ) { this.katana = katana; this.shuriken = shuriken; } + public fight() { return this.katana.hit(); }; + public sneak() { return this.shuriken.throw(); }; } - kernel.bind("ISamurai").to(Samurai3); - kernel.bind("IWeapon").to(Katana).whenTargetNamed("strong"); - kernel.bind("IWeapon").to(Shuriken).whenTargetNamed("weak"); + kernel.bind("Warrior").to(Samurai3); + kernel.bind("Weapon").to(Katana).whenTargetNamed("strong"); + kernel.bind("Weapon").to(Shuriken).whenTargetNamed("weak"); - @inversify.inject("IWeapon", "IWeapon") - @inversify.paramNames("katana", "shuriken") - class Samurai4 implements ISamurai { - public katana: IWeapon; - public shuriken: IWeapon; + @injectable() + class Samurai4 implements Samurai { + public katana: Weapon; + public shuriken: ThrowableWeapon; public constructor( - katana: IWeapon, - shuriken: IWeapon + @inject("Weapon") @targetName("katana") katana: Weapon, + @inject("ThrowableWeapon") @targetName("shuriken") shuriken: ThrowableWeapon ) { this.katana = katana; this.shuriken = shuriken; } + public fight() { return this.katana.hit(); }; + public sneak() { return this.shuriken.throw(); }; } - kernel.bind("ISamurai").to(Samurai4); + kernel.bind("Warrior").to(Samurai4); - kernel.bind("IWeapon").to(Katana).when((request: inversify.IRequest) => { + kernel.bind("Weapon").to(Katana).when((request: inversify.interfaces.Request) => { return request.target.name.equals("katana"); }); - kernel.bind("IWeapon").to(Shuriken).when((request: inversify.IRequest) => { + kernel.bind("Weapon").to(Shuriken).when((request: inversify.interfaces.Request) => { return request.target.name.equals("shuriken"); }); + // custom constraints + let whenParentNamedCanThrowConstraint = (request: inversify.interfaces.Request) => { + return namedConstraint("canThrow")(request.parentRequest); + }; + + let whenAnyAncestorIsConstraint = (request: inversify.interfaces.Request) => { + return traverseAncerstors(request, typeConstraint(Ninja)); + }; + + let whenAnyAncestorTaggedConstraint = (request: inversify.interfaces.Request) => { + return traverseAncerstors(request, taggedConstraint("canThrow")(true)); + }; + + kernel.bind("Weapon").to(Shuriken).when(whenParentNamedCanThrowConstraint); + kernel.bind("Weapon").to(Shuriken).when(whenAnyAncestorIsConstraint); + kernel.bind("Weapon").to(Shuriken).when(whenAnyAncestorTaggedConstraint); + + // Constraint helpers + kernel.bind("Weapon").to(Shuriken).whenInjectedInto(Ninja); + kernel.bind("Weapon").to(Shuriken).whenInjectedInto("INinja"); + kernel.bind("Weapon").to(Shuriken).whenParentNamed("chinese"); + kernel.bind("Weapon").to(Shuriken).whenParentTagged("canThrow", true); + kernel.bind("Weapon").to(Shuriken).whenTargetNamed("strong"); + kernel.bind("Weapon").to(Shuriken).whenTargetTagged("canThrow", true); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs(Ninja); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorNamed("strong"); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorTagged("canThrow", true); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorMatches(whenParentNamedCanThrowConstraint); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs(Ninja); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorNamed("strong"); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorTagged("canThrow", true); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorMatches(whenParentNamedCanThrowConstraint); + + // multi-injection + @injectable() + class Samurai5 implements Warrior { + public katana: Weapon; + public shuriken: Weapon; + public constructor( + @multiInject("Weapon") wpns: Weapon[] + ) { + this.katana = wpns[0]; + this.shuriken = wpns[1]; + } + public fight() { return this.katana.hit(); }; + public sneak() { return this.shuriken.hit(); }; + } + + // symbols + let SYMBOLS = { + ThrowableWeapon: Symbol("ThrowableWeapon"), + Warrior: Symbol("Warrior"), + Weapon: Symbol("Weapon"), + }; + + @injectable() + class Ninja1 implements Warrior { + + private _katana: Weapon; + private _shuriken: ThrowableWeapon; + + public constructor( + @inject(SYMBOLS.Weapon) katana: Weapon, + @inject(SYMBOLS.ThrowableWeapon) shuriken: ThrowableWeapon + ) { + this._katana = katana; + this._shuriken = shuriken; + } + + public fight() { return this._katana.hit(); }; + public sneak() { return this._shuriken.throw(); }; + + } + + let kernel3 = new Kernel(); + kernel3.bind(SYMBOLS.Warrior).to(Ninja); + kernel3.bind(SYMBOLS.Weapon).to(Katana); + kernel3.bind(SYMBOLS.ThrowableWeapon).to(Shuriken).inSingletonScope(); + + let ninja4 = kernel3.get("Warrior"); + console.log(ninja4); + + // classes + + @injectable() + class Ninja2 implements Warrior { + + private _katana: Katana; + private _shuriken: Shuriken; + + public constructor( + katana: Katana, + shuriken: Shuriken + ) { + this._katana = katana; + this._shuriken = shuriken; + } + + public fight() { return this._katana.hit(); }; + public sneak() { return this._shuriken.throw(); }; + + } + + let kernel4 = new Kernel(); + kernel4.bind(Ninja).to(Ninja); + kernel4.bind(Katana).to(Katana); + kernel4.bind(Shuriken).to(Shuriken).inSingletonScope(); + + let ninja5 = kernel4.get(Ninja); + console.log(ninja5); + +} + +module property_injection { + + let kernel = new Kernel(); + + let TYPES = { Weapon: "Weapon" }; + + interface Weapon { + durability: number; + use(): void; + } + + @injectable() + class Sword implements Weapon { + public durability: number; + public constructor() { + this.durability = 100; + } + public use() { + this.durability = this.durability - 10; + } + } + + @injectable() + class WarHammer implements Weapon { + public durability: number; + public constructor() { + this.durability = 100; + } + public use() { + this.durability = this.durability - 10; + } + } + + let propertyMultiInject = makePropertyMultiInjectDecorator(kernel); + + class Warrior1 { + @propertyMultiInject(TYPES.Weapon) + public weapons: Weapon[]; + } + + let propertyInject = makePropertyInjectDecorator(kernel); + + interface Service { + count: number; + increment(): void; + } + + @injectable() + class SomeService implements Service { + public count: number; + public constructor() { + this.count = 0; + } + public increment() { + this.count = this.count + 1; + } + } + + class SomeWebComponent { + @propertyInject("Service") + private _service: Service; + public doSomething() { + let count = this._service.count; + this._service.increment(); + return count; + } + } + + let propertyInjectNammed = makePropertyInjectNamedDecorator(kernel); + + class Warrior2 { + + @propertyInjectNammed(TYPES.Weapon, "not-throwwable") + @named("not-throwwable") + public primaryWeapon: Weapon; + + @propertyInjectNammed(TYPES.Weapon, "throwwable") + @named("throwwable") + public secondaryWeapon: Weapon; + + } + + let propertyInjectTagged = makePropertyInjectTaggedDecorator(kernel); + + class Warrior3 { + + @propertyInjectTagged(TYPES.Weapon, "throwwable", false) + @tagged("throwwable", false) + public primaryWeapon: Weapon; + + @propertyInjectTagged(TYPES.Weapon, "throwwable", true) + @tagged("throwwable", true) + public secondaryWeapon: Weapon; + + } + + kernel.snapshot(); + kernel.restore(); + } diff --git a/inversify/inversify-tests.ts b/inversify/inversify-tests.ts index 23af8db21f..9b5de8fa0e 100644 --- a/inversify/inversify-tests.ts +++ b/inversify/inversify-tests.ts @@ -1,46 +1,62 @@ -/// +/// +/// import { Kernel, - inject, tagged, named, paramNames, - IKernel, IKernelOptions, INewable, - IKernelModule, IFactory, IProvider, IRequest + injectable, tagged, named, targetName, + inject, multiInject, traverseAncerstors, + taggedConstraint, namedConstraint, typeConstraint, + makePropertyMultiInjectDecorator, + makePropertyInjectTaggedDecorator, + makePropertyInjectNamedDecorator, + makePropertyInjectDecorator, + KernelModule, interfaces } from "inversify"; -namespace external_module_test { +import * as Proxy from "harmony-proxy"; - interface INinja { +module external_module_test { + + interface Warrior { fight(): string; sneak(): string; } - interface IKatana { + interface Weapon { hit(): string; } - interface IShuriken { + interface ThrowableWeapon extends Weapon { throw(): string; } - class Katana implements IKatana { + @injectable() + class Katana implements Weapon { public hit() { return "cut!"; } } - class Shuriken implements IShuriken { + @injectable() + class Shuriken implements ThrowableWeapon { public throw() { return "hit!"; } + public hit() { + return "hit!"; + } } - @inject("IKatana", "IShuriken") - class Ninja implements INinja { + @injectable() + class Ninja implements Warrior { - private _katana: IKatana; - private _shuriken: IShuriken; + private _katana: Weapon; + private _shuriken: ThrowableWeapon; - public constructor(katana: IKatana, shuriken: IShuriken) { + public constructor( + @inject("Weapon") katana: Weapon, + @inject("ThrowableWeapon") shuriken: ThrowableWeapon + ) { this._katana = katana; this._shuriken = shuriken; } @@ -50,62 +66,73 @@ namespace external_module_test { } - let kernel = new Kernel(); - kernel.bind("INinja").to(Ninja); - kernel.bind("IKatana").to(Katana); - kernel.bind("IShuriken").to(Shuriken).inSingletonScope(); + let kernel: interfaces.Kernel = new Kernel(); + kernel.bind("Warrior").to(Ninja); + kernel.bind("Weapon").to(Katana); + kernel.bind("ThrowableWeapon").to(Shuriken).inSingletonScope(); - let ninja = kernel.get("INinja"); + let ninja = kernel.get("Warrior"); console.log(ninja); // Unbind - kernel.unbind("INinja"); + kernel.unbind("Warrior"); kernel.unbindAll(); // Kernel modules - let module: IKernelModule = (k: IKernel) => { - k.bind("INinja").to(Ninja); - k.bind("IKatana").to(Katana).inTransientScope(); - k.bind("IShuriken").to(Shuriken).inSingletonScope(); - }; + let warriors: interfaces.KernelModule = new KernelModule((bind: interfaces.Bind) => { + bind("Warrior").to(Ninja); + }); - let options: IKernelOptions = { - middleware: [], - modules: [module] - }; + let weapons: interfaces.KernelModule = new KernelModule((bind: interfaces.Bind) => { + bind("Weapon").to(Katana); + bind("ThrowableWeapon").to(Shuriken); + }); - kernel = new Kernel(options); - let ninja2 = kernel.get("INinja"); + kernel = new Kernel(); + kernel.load(warriors, weapons); + let ninja2 = kernel.get("Warrior"); console.log(ninja2); + // middleware + function logger(planAndResolve: interfaces.PlanAndResolve): interfaces.PlanAndResolve { + return (args: interfaces.PlanAndResolveArgs) => { + let start = new Date().getTime(); + let result = planAndResolve(args); + let end = new Date().getTime(); + console.log(end - start); + return result; + }; + } + + kernel.applyMiddleware(logger, logger); + // binding types - kernel.bind("IKatana").to(Katana); - kernel.bind("IKatana").toValue(new Katana()); + kernel.bind("Weapon").to(Katana); + kernel.bind("Weapon").toConstantValue(new Katana()); + kernel.bind("Weapon").toDynamicValue(() => { return new Katana(); }); - kernel.bind>("IKatana").toConstructor(Katana); + kernel.bind>("Weapon").toConstructor(Katana); - kernel.bind>("IKatana").toFactory((context) => { + kernel.bind>("Weapon").toFactory((context) => { return () => { - return kernel.get("IKatana"); + return kernel.get("Weapon"); }; }); - kernel.bind>("IKatana").toAutoFactory(); + kernel.bind>("Weapon").toAutoFactory("Weapon"); - kernel.bind>("IKatana").toProvider((context) => { + kernel.bind>("Weapon").toProvider((context) => { return () => { - return new Promise((resolve) => { - let katana = kernel.get("IKatana"); + return new Promise((resolve) => { + let katana = kernel.get("Weapon"); resolve(katana); }); }; }); - kernel.bind("IKatana").to(Katana).proxy((katanaToBeInjected: IKatana) => { - // BLOCK http://stackoverflow.com/questions/35906938/how-to-enable-harmony-proxies-in-gulp-mocha - /* + kernel.bind("Weapon").to(Katana).onActivation((context: interfaces.Context, katanaToBeInjected: Weapon) => { let handler = { - apply: function(target, thisArgument, argumentsList) { + apply: function(target: any, thisArgument: any, argumentsList: any[]) { console.log(`Starting: ${performance.now()}`); let result = target.apply(thisArgument, argumentsList); console.log(`Finished: ${performance.now()}`); @@ -113,88 +140,302 @@ namespace external_module_test { } }; return new Proxy(katanaToBeInjected, handler); - */ - return katanaToBeInjected; }); - interface IWeapon {} - interface ISamurai { - katana: IWeapon; - shuriken: IWeapon; - } - @inject("IWeapon", "IWeapon") - class Samurai implements ISamurai { - public katana: IWeapon; - public shuriken: IWeapon; + @injectable() + class Samurai implements Warrior { + public katana: Weapon; + public shuriken: ThrowableWeapon; public constructor( - @tagged("canThrow", false) katana: IWeapon, - @tagged("canThrow", true) shuriken: IWeapon + @inject("Weapon") @tagged("canThrow", false) katana: Weapon, + @inject("ThrowableWeapon") @tagged("canThrow", true) shuriken: ThrowableWeapon ) { this.katana = katana; this.shuriken = shuriken; } + public fight() { return this.katana.hit(); }; + public sneak() { return this.shuriken.throw(); }; } kernel.bind("Samurai").to(Samurai); - kernel.bind("IWeapon").to(Katana).whenTargetTagged("canThrow", false); - kernel.bind("IWeapon").to(Shuriken).whenTargetTagged("canThrow", true); + kernel.bind("IWeapon").to(Katana).whenTargetTagged("canThrow", false); + kernel.bind("ThrowableWeapon").to(Shuriken).whenTargetTagged("canThrow", true); let throwable = tagged("canThrow", true); let notThrowable = tagged("canThrow", false); - @inject("IWeapon", "IWeapon") - class Samurai2 implements ISamurai { - public katana: IWeapon; - public shuriken: IWeapon; + @injectable() + class Samurai2 implements Samurai { + public katana: Weapon; + public shuriken: ThrowableWeapon; public constructor( - @throwable("canThrow", false) katana: IWeapon, - @notThrowable("canThrow", true) shuriken: IWeapon + @inject("Weapon") @throwable katana: Weapon, + @inject("ThrowableWeapon") @notThrowable shuriken: ThrowableWeapon ) { this.katana = katana; this.shuriken = shuriken; } + public fight() { return this.katana.hit(); }; + public sneak() { return this.shuriken.throw(); }; } - @inject("IWeapon", "IWeapon") - class Samurai3 implements ISamurai { - public katana: IWeapon; - public shuriken: IWeapon; + @injectable() + class Samurai3 implements Samurai { + public katana: Weapon; + public shuriken: ThrowableWeapon; public constructor( - @named("strong") katana: IWeapon, - @named("weak") shuriken: IWeapon + @inject("Weapon") @named("strong") katana: Weapon, + @inject("ThrowableWeapon") @named("weak") shuriken: ThrowableWeapon ) { this.katana = katana; this.shuriken = shuriken; } + public fight() { return this.katana.hit(); }; + public sneak() { return this.shuriken.throw(); }; } - kernel.bind("ISamurai").to(Samurai3); - kernel.bind("IWeapon").to(Katana).whenTargetNamed("strong"); - kernel.bind("IWeapon").to(Shuriken).whenTargetNamed("weak"); + kernel.bind("Warrior").to(Samurai3); + kernel.bind("Weapon").to(Katana).whenTargetNamed("strong"); + kernel.bind("Weapon").to(Shuriken).whenTargetNamed("weak"); - @inject("IWeapon", "IWeapon") - @paramNames("katana", "shuriken") - class Samurai4 implements ISamurai { - public katana: IWeapon; - public shuriken: IWeapon; + @injectable() + class Samurai4 implements Samurai { + public katana: Weapon; + public shuriken: ThrowableWeapon; public constructor( - katana: IWeapon, - shuriken: IWeapon + @inject("Weapon") @targetName("katana") katana: Weapon, + @inject("ThrowableWeapon") @targetName("shuriken") shuriken: ThrowableWeapon ) { this.katana = katana; this.shuriken = shuriken; } + public fight() { return this.katana.hit(); }; + public sneak() { return this.shuriken.throw(); }; } - kernel.bind("ISamurai").to(Samurai4); + kernel.bind("Warrior").to(Samurai4); - kernel.bind("IWeapon").to(Katana).when((request: IRequest) => { + kernel.bind("Weapon").to(Katana).when((request: interfaces.Request) => { return request.target.name.equals("katana"); }); - kernel.bind("IWeapon").to(Shuriken).when((request: IRequest) => { + kernel.bind("Weapon").to(Shuriken).when((request: interfaces.Request) => { return request.target.name.equals("shuriken"); }); + // custom constraints + let whenParentNamedCanThrowConstraint = (request: interfaces.Request) => { + return namedConstraint("canThrow")(request.parentRequest); + }; + + let whenAnyAncestorIsConstraint = (request: interfaces.Request) => { + return traverseAncerstors(request, typeConstraint(Ninja)); + }; + + let whenAnyAncestorTaggedConstraint = (request: interfaces.Request) => { + return traverseAncerstors(request, taggedConstraint("canThrow")(true)); + }; + + kernel.bind("Weapon").to(Shuriken).when(whenParentNamedCanThrowConstraint); + kernel.bind("Weapon").to(Shuriken).when(whenAnyAncestorIsConstraint); + kernel.bind("Weapon").to(Shuriken).when(whenAnyAncestorTaggedConstraint); + + // Constraint helpers + kernel.bind("Weapon").to(Shuriken).whenInjectedInto(Ninja); + kernel.bind("Weapon").to(Shuriken).whenInjectedInto("INinja"); + kernel.bind("Weapon").to(Shuriken).whenParentNamed("chinese"); + kernel.bind("Weapon").to(Shuriken).whenParentTagged("canThrow", true); + kernel.bind("Weapon").to(Shuriken).whenTargetNamed("strong"); + kernel.bind("Weapon").to(Shuriken).whenTargetTagged("canThrow", true); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs(Ninja); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorNamed("strong"); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorTagged("canThrow", true); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorMatches(whenParentNamedCanThrowConstraint); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs(Ninja); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorNamed("strong"); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorTagged("canThrow", true); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorMatches(whenParentNamedCanThrowConstraint); + + // multi-injection + @injectable() + class Samurai5 implements Warrior { + public katana: Weapon; + public shuriken: Weapon; + public constructor( + @multiInject("Weapon") wpns: Weapon[] + ) { + this.katana = wpns[0]; + this.shuriken = wpns[1]; + } + public fight() { return this.katana.hit(); }; + public sneak() { return this.shuriken.hit(); }; + } + + // symbols + let SYMBOLS = { + ThrowableWeapon: Symbol("ThrowableWeapon"), + Warrior: Symbol("Warrior"), + Weapon: Symbol("Weapon"), + }; + + @injectable() + class Ninja1 implements Warrior { + + private _katana: Weapon; + private _shuriken: ThrowableWeapon; + + public constructor( + @inject(SYMBOLS.Weapon) katana: Weapon, + @inject(SYMBOLS.ThrowableWeapon) shuriken: ThrowableWeapon + ) { + this._katana = katana; + this._shuriken = shuriken; + } + + public fight() { return this._katana.hit(); }; + public sneak() { return this._shuriken.throw(); }; + + } + + let kernel3 = new Kernel(); + kernel3.bind(SYMBOLS.Warrior).to(Ninja); + kernel3.bind(SYMBOLS.Weapon).to(Katana); + kernel3.bind(SYMBOLS.ThrowableWeapon).to(Shuriken).inSingletonScope(); + + let ninja4 = kernel3.get("Warrior"); + console.log(ninja4); + + // classes + + @injectable() + class Ninja2 implements Warrior { + + private _katana: Katana; + private _shuriken: Shuriken; + + public constructor( + katana: Katana, + shuriken: Shuriken + ) { + this._katana = katana; + this._shuriken = shuriken; + } + + public fight() { return this._katana.hit(); }; + public sneak() { return this._shuriken.throw(); }; + + } + + let kernel4 = new Kernel(); + kernel4.bind(Ninja).to(Ninja); + kernel4.bind(Katana).to(Katana); + kernel4.bind(Shuriken).to(Shuriken).inSingletonScope(); + + let ninja5 = kernel4.get(Ninja); + console.log(ninja5); + +} + +module property_injection { + + let kernel = new Kernel(); + + let TYPES = { Weapon: "Weapon" }; + + interface Weapon { + durability: number; + use(): void; + } + + @injectable() + class Sword implements Weapon { + public durability: number; + public constructor() { + this.durability = 100; + } + public use() { + this.durability = this.durability - 10; + } + } + + @injectable() + class WarHammer implements Weapon { + public durability: number; + public constructor() { + this.durability = 100; + } + public use() { + this.durability = this.durability - 10; + } + } + + let propertyMultiInject = makePropertyMultiInjectDecorator(kernel); + + class Warrior1 { + @propertyMultiInject(TYPES.Weapon) + public weapons: Weapon[]; + } + + let propertyInject = makePropertyInjectDecorator(kernel); + + interface Service { + count: number; + increment(): void; + } + + @injectable() + class SomeService implements Service { + public count: number; + public constructor() { + this.count = 0; + } + public increment() { + this.count = this.count + 1; + } + } + + class SomeWebComponent { + @propertyInject("Service") + private _service: Service; + public doSomething() { + let count = this._service.count; + this._service.increment(); + return count; + } + } + + let propertyInjectNammed = makePropertyInjectNamedDecorator(kernel); + + class Warrior2 { + + @propertyInjectNammed(TYPES.Weapon, "not-throwwable") + @named("not-throwwable") + public primaryWeapon: Weapon; + + @propertyInjectNammed(TYPES.Weapon, "throwwable") + @named("throwwable") + public secondaryWeapon: Weapon; + + } + + let propertyInjectTagged = makePropertyInjectTaggedDecorator(kernel); + + class Warrior3 { + + @propertyInjectTagged(TYPES.Weapon, "throwwable", false) + @tagged("throwwable", false) + public primaryWeapon: Weapon; + + @propertyInjectTagged(TYPES.Weapon, "throwwable", true) + @tagged("throwwable", true) + public secondaryWeapon: Weapon; + + } + + kernel.snapshot(); + kernel.restore(); + } diff --git a/inversify/inversify.d.ts b/inversify/inversify.d.ts index 79cd4e3dec..41200ae470 100644 --- a/inversify/inversify.d.ts +++ b/inversify/inversify.d.ts @@ -1,141 +1,277 @@ -// Type definitions for inversify 2.0.0-alpha.3 +// Type definitions for inversify 2.0.0-beta.9 // Project: https://github.com/inversify/InversifyJS // Definitions by: inversify -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// +interface Symbol { + toString(): string; + valueOf(): Object; +} + +interface SymbolConstructor { + (description?: string|number): Symbol; +} + +declare var Symbol: SymbolConstructor; + declare namespace inversify { - interface IKernelConstructor { - new(options?: IKernelOptions): IKernel; + namespace interfaces { + + export interface KernelConstructor { + new(): Kernel; + } + + export interface KernelModuleConstructor { + new(registry: (bind: Bind) => void): KernelModule; + } + + export interface Newable { + new(...args: any[]): T; + } + + export type ServiceIdentifier = (string|Symbol|Newable); + + export interface Binding extends Clonable> { + guid: string; + moduleId: string; + activated: boolean; + serviceIdentifier: ServiceIdentifier; + implementationType: Newable; + factory: FactoryCreator; + provider: ProviderCreator; + constraint: (request: Request) => boolean; + onActivation: (context: Context, injectable: T) => T; + cache: T; + dynamicValue: () => T; + scope: number; // BindingScope + type: number; // BindingType + } + + export interface Factory extends Function { + (...args: any[]): (((...args: any[]) => T)|T); + } + + export interface FactoryCreator extends Function { + (context: Context): Factory; + } + + export interface Provider extends Function { + (): Promise; + } + + export interface ProviderCreator extends Function { + (context: Context): Provider; + } + + export interface PlanAndResolve { + (args: PlanAndResolveArgs): T[]; + } + + export interface PlanAndResolveArgs { + multiInject: boolean; + serviceIdentifier: ServiceIdentifier; + target: Target; + contextInterceptor: (contexts: Context) => Context; + } + + export interface Middleware extends Function { + (next: PlanAndResolve): PlanAndResolve; + } + + export interface Context { + guid: string; + kernel: Kernel; + plan: Plan; + addPlan(plan: Plan): void; + } + + export interface ReflectResult { + [key: string]: Metadata[]; + } + + export interface Metadata { + key: string; + value: any; + } + + export interface Plan { + parentContext: Context; + rootRequest: Request; + } + + export interface Planner { + createContext(kernel: Kernel): Context; + createPlan(parentContext: Context, binding: Binding, target: Target): Plan; + getBindings(kernel: Kernel, serviceIdentifier: ServiceIdentifier): Binding[]; + getActiveBindings(parentRequest: Request, target: Target): Binding[]; + } + + export interface QueryableString { + startsWith(searchString: string): boolean; + endsWith(searchString: string): boolean; + contains(searchString: string): boolean; + equals(compareString: string): boolean; + value(): string; + } + + export interface Request { + guid: string; + serviceIdentifier: ServiceIdentifier; + parentContext: Context; + parentRequest: Request; + childRequests: Request[]; + target: Target; + bindings: Binding[]; + addChildRequest( + serviceIdentifier: ServiceIdentifier, + bindings: (Binding|Binding[]), + target: Target + ): Request; + } + + export interface Target { + guid: string; + serviceIdentifier: ServiceIdentifier; + name: QueryableString; + metadata: Array; + hasTag(key: string): boolean; + isArray(): boolean; + matchesArray(name: string|Symbol|Newable): boolean; + isNamed(): boolean; + isTagged(): boolean; + matchesNamedTag(name: string): boolean; + matchesTag(key: string): (value: any) => boolean; + } + + export interface Resolver { + resolve(context: Context): T; + } + + export interface Kernel { + guid: string; + bind(serviceIdentifier: ServiceIdentifier): BindingToSyntax; + unbind(serviceIdentifier: ServiceIdentifier): void; + unbindAll(): void; + isBound(serviceIdentifier: ServiceIdentifier): boolean; + get(serviceIdentifier: ServiceIdentifier): T; + getNamed(serviceIdentifier: ServiceIdentifier, named: string): T; + getTagged(serviceIdentifier: ServiceIdentifier, key: string, value: any): T; + getAll(serviceIdentifier: ServiceIdentifier): T[]; + load(...modules: KernelModule[]): void; + unload(...modules: KernelModule[]): void; + applyMiddleware(...middleware: Middleware[]): void; + getServiceIdentifierAsString(serviceIdentifier: ServiceIdentifier): string; + snapshot(): void; + restore(): void; + } + + export interface Bind extends Function { + (serviceIdentifier: ServiceIdentifier): BindingToSyntax; + } + + export interface KernelModule { + guid: string; + registry: (bind: Bind) => void; + } + + export interface KernelSnapshot { + bindings: Lookup>; + middleware: PlanAndResolve; + } + + export interface Clonable { + clone(): T; + } + + export interface Lookup extends Clonable> { + add(serviceIdentifier: ServiceIdentifier, value: T): void; + get(serviceIdentifier: ServiceIdentifier): Array; + remove(serviceIdentifier: ServiceIdentifier): void; + removeByModuleId(moduleId: string): void; + hasKey(serviceIdentifier: ServiceIdentifier): boolean; + } + + export interface KeyValuePair { + serviceIdentifier: ServiceIdentifier; + value: Array; + } + + export interface BindingInSyntax { + inSingletonScope(): BindingWhenOnSyntax; + } + + export interface BindingInWhenOnSyntax extends BindingInSyntax, BindingWhenOnSyntax {} + + export interface BindingOnSyntax { + onActivation(fn: (context: Context, injectable: T) => T): BindingWhenSyntax; + } + + export interface BindingToSyntax { + to(constructor: { new(...args: any[]): T; }): BindingInWhenOnSyntax; + toConstantValue(value: T): BindingWhenOnSyntax; + toDynamicValue(func: () => T): BindingWhenOnSyntax; + toConstructor(constructor: Newable): BindingWhenOnSyntax; + toFactory(factory: FactoryCreator): BindingWhenOnSyntax; + toFunction(func: T): BindingWhenOnSyntax; + toAutoFactory(serviceIdentifier: ServiceIdentifier): BindingWhenOnSyntax; + toProvider(provider: ProviderCreator): BindingWhenOnSyntax; + } + + export interface BindingWhenOnSyntax extends BindingWhenSyntax, BindingOnSyntax {} + + export interface BindingWhenSyntax { + when(constraint: (request: Request) => boolean): BindingOnSyntax; + whenTargetNamed(name: string): BindingOnSyntax; + whenTargetTagged(tag: string, value: any): BindingOnSyntax; + whenInjectedInto(parent: (Function|string)): BindingOnSyntax; + whenParentNamed(name: string): BindingOnSyntax; + whenParentTagged(tag: string, value: any): BindingOnSyntax; + whenAnyAncestorIs(ancestor: (Function|string)): BindingOnSyntax; + whenNoAncestorIs(ancestor: (Function|string)): BindingOnSyntax; + whenAnyAncestorNamed(name: string): BindingOnSyntax; + whenAnyAncestorTagged(tag: string, value: any): BindingOnSyntax; + whenNoAncestorNamed(name: string): BindingOnSyntax; + whenNoAncestorTagged(tag: string, value: any): BindingOnSyntax; + whenAnyAncestorMatches(constraint: (request: Request) => boolean): BindingOnSyntax; + whenNoAncestorMatches(constraint: (request: Request) => boolean): BindingOnSyntax; + } + } - export interface IKernel { - bind(runtimeIdentifier: string): IBindingToSyntax; - unbind(runtimeIdentifier: string): void; - unbindAll(): void; - get(runtimeIdentifier: string): T; - getAll(runtimeIdentifier: string): T[]; - } + export var Kernel: interfaces.KernelConstructor; + export var KernelModule: interfaces.KernelModuleConstructor; + export var decorate: (decorator: (ClassDecorator|ParameterDecorator), target: any, parameterIndex?: number) => void; + export function injectable(): (typeConstructor: any) => void; + export function tagged(metadataKey: string, metadataValue: any): (target: any, targetKey: string, index?: number) => any; + export function named(name: string): (target: any, targetKey: string, index?: number) => any; + export function targetName(name: string): (target: any, targetKey: string, index: number) => any; + export function inject(serviceIdentifier: interfaces.ServiceIdentifier): (target: any, targetKey: string, index?: number) => any; - export interface IKernelOptions { - middleware?: IMiddleware[]; - modules?: IKernelModule[]; - } + export function multiInject( + serviceIdentifier: interfaces.ServiceIdentifier + ): (target: any, targetKey: string, index?: number) => any; - interface IMiddleware extends Function { - (...args: any[]): any; - } + export function makePropertyInjectDecorator(kernel: interfaces.Kernel): + (serviceIdentifier: (string|Symbol|interfaces.Newable)) => (proto: any, key: string) => void; - export interface IKernelModule extends Function { - (kernel: IKernel): void; - } + export function makePropertyInjectNamedDecorator(kernel: interfaces.Kernel): + (serviceIdentifier: (string|Symbol|interfaces.Newable), named: string) => (proto: any, key: string) => void; - interface IBindingToSyntax { - to(constructor: { new(...args: any[]): T; }): IBindingInWhenProxySyntax; - toValue(value: T): IBindingInWhenProxySyntax; - toConstructor(constructor: INewable): IBindingInWhenProxySyntax; - toFactory(factory: IFactoryCreator): IBindingInWhenProxySyntax; - toAutoFactory(): IBindingInWhenProxySyntax; - toProvider(provider: IProviderCreator): IBindingInWhenProxySyntax; - } + export function makePropertyInjectTaggedDecorator(kernel: interfaces.Kernel): + (serviceIdentifier: (string|Symbol|interfaces.Newable), key: string, value: any) => (proto: any, propertyName: string) => void; - interface IBindingInWhenProxySyntax { - inTransientScope(): IBindingInWhenProxySyntax; - inSingletonScope(): IBindingInWhenProxySyntax; - when(constraint: (request: IRequest) => boolean): IBindingInWhenProxySyntax; - whenTargetNamed(name: string): IBindingInWhenProxySyntax; - whenTargetTagged(tag: string, value: any): IBindingInWhenProxySyntax; - proxy(fn: (injectable: T) => T): IBindingInWhenProxySyntax; - } + export function makePropertyMultiInjectDecorator(kernel: interfaces.Kernel): + (serviceIdentifier: (string|Symbol|interfaces.Newable)) => (proto: any, key: string) => void; - export interface IFactory extends Function { - (): T; - } + // constraint helpers + export var traverseAncerstors: (request: interfaces.Request, constraint: (request: interfaces.Request) => boolean) => boolean; + export var taggedConstraint: (tag: string) => (value: any) => (request: interfaces.Request) => boolean; + export var namedConstraint: (value: any) => (request: interfaces.Request) => boolean; + export var typeConstraint: (type: (Function|string)) => (request: interfaces.Request) => boolean; - interface IFactoryCreator extends Function { - (context: IContext): IFactory; - } - - export interface INewable { - new(...args: any[]): T; - } - - export interface IProvider extends Function { - (): Promise; - } - - interface IProviderCreator extends Function { - (context: IContext): IProvider; - } - - export interface IContext { - kernel: IKernel; - plan: IPlan; - addPlan(plan: IPlan): void; - } - - export interface IPlan { - parentContext: IContext; - rootRequest: IRequest; - } - - export interface IRequest { - service: string; - parentContext: IContext; - parentRequest: IRequest; - childRequests: IRequest[]; - target: ITarget; - bindings: IBinding[]; - addChildRequest( - service: string, - bindings: (IBinding|IBinding[]), - target: ITarget): IRequest; - } - - export interface IBinding { - runtimeIdentifier: string; - implementationType: INewable; - factory: IFactoryCreator; - provider: IProviderCreator; - constraint: (request: IRequest) => boolean; - proxyMaker: (injectable: T) => T; - cache: T; - scope: number; // BindingScope - type: number; // BindingType - } - - export interface ITarget { - service: IQueryableString; - name: IQueryableString; - metadata: Array; - isArray(): boolean; - isNamed(): boolean; - isTagged(): boolean; - matchesName(name: string): boolean; - matchesTag(name: IMetadata): boolean; - } - - export interface IQueryableString { - startsWith(searchString: string): boolean; - endsWith(searchString: string): boolean; - contains(searchString: string): boolean; - equals(compareString: string): boolean; - value(): string; - } - - export interface IMetadata { - key: string; - value: any; - } - - export var Kernel: IKernelConstructor; - export var decorate: any; - export function inject(...typeIdentifiers: string[]): (typeConstructor: any) => void; - export var tagged: any; - export var named: any; - export var paramNames: any; } declare module "inversify" { diff --git a/jquery-truncate-html/jquery-truncate-html-tests.ts b/jquery-truncate-html/jquery-truncate-html-tests.ts new file mode 100644 index 0000000000..e20f9c22ee --- /dev/null +++ b/jquery-truncate-html/jquery-truncate-html-tests.ts @@ -0,0 +1,14 @@ +/// + + +function truncateHtmlString(): string { + return $.truncate('

Stuff and Nonsense

', { + length: 13 + }); +} + +function truncateVirtualElement (): JQuery { + return $('

Stuff and Nonsense

').truncate({ + length: 13 + }); +} diff --git a/jquery-truncate-html/jquery-truncate-html.d.ts b/jquery-truncate-html/jquery-truncate-html.d.ts new file mode 100644 index 0000000000..e410716b0a --- /dev/null +++ b/jquery-truncate-html/jquery-truncate-html.d.ts @@ -0,0 +1,22 @@ +// Type definitions for jQuery-truncate-html.js +// Project: https://github.com/kbwood/timeentry +// Definitions by: Abraão Alves +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface TruncateOptions{ + length?: number; + stripTags?: boolean; + words?: boolean; + noBreaks?: boolean; + ellipsis?: string; +} + +interface JQuery{ + truncate(options: TruncateOptions) : JQuery; +} + +interface JQueryStatic { + truncate(html: string, options: TruncateOptions) : string; +} diff --git a/jwt-simple/jwt-simple-0.2.0-tests.ts b/jwt-simple/jwt-simple-0.2.0-tests.ts new file mode 100644 index 0000000000..8a0cc59c52 --- /dev/null +++ b/jwt-simple/jwt-simple-0.2.0-tests.ts @@ -0,0 +1,12 @@ +/// + +import jwt = require('jwt-simple'); +var payload = { foo: 'bar' }; +var secret:string = 'xxx'; + +// encode +var token = jwt.encode(payload, secret); + +// decode +var decoded = jwt.decode(token, secret); +console.log(decoded); //=> { foo: 'bar' } \ No newline at end of file diff --git a/jwt-simple/jwt-simple-0.2.0.d.ts b/jwt-simple/jwt-simple-0.2.0.d.ts new file mode 100644 index 0000000000..0ee3cc6799 --- /dev/null +++ b/jwt-simple/jwt-simple-0.2.0.d.ts @@ -0,0 +1,22 @@ +// Type definitions for jwt-simple v0.2.0 +// Project: https://github.com/hokaccha/node-jwt-simple +// Definitions by: Ken Fukuyama +// Definitions: https://github.com/borisyankov/DefinitelyTyped +declare module "jwt-simple" { + /** + * Decode jwt + * @param token + * @param key + * @param noVerify + * @api public + */ + export function decode(token:any, key:string, noVerify?:boolean):any; + /** + * Encode jwt + * @param payload + * @param key + * @param algorithm default is HS256 + * @api public + */ + export function encode(payload:any, key:string, algorithm?:string):string; +} diff --git a/jwt-simple/jwt-simple.d.ts b/jwt-simple/jwt-simple.d.ts index 208c7e6beb..ea78b13e88 100644 --- a/jwt-simple/jwt-simple.d.ts +++ b/jwt-simple/jwt-simple.d.ts @@ -1,6 +1,6 @@ -// Type definitions for jwt-simple v0.2.0 +// Type definitions for jwt-simple v0.5.0 // Project: https://github.com/hokaccha/node-jwt-simple -// Definitions by: Ken Fukuyama +// Definitions by: Ken Fukuyama , Gael Magnan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "jwt-simple" { /** @@ -8,15 +8,17 @@ declare module "jwt-simple" { * @param token * @param key * @param noVerify + * @param algorithm default is HS256 * @api public */ - export function decode(token:any, key:string, noVerify?:boolean):any; + export function decode(token:any, key:string, noVerify?:boolean, algorithm?:string):any; /** * Encode jwt * @param payload * @param key * @param algorithm default is HS256 + * @param options * @api public */ - export function encode(payload:any, key:string, algorithm?:string):string; + export function encode(payload:any, key:string, algorithm?:string, options?:any):string; } diff --git a/koa-compress/koa-compress-tests.ts b/koa-compress/koa-compress-tests.ts new file mode 100644 index 0000000000..564fd53e2c --- /dev/null +++ b/koa-compress/koa-compress-tests.ts @@ -0,0 +1,16 @@ +/// +/// + +import * as Koa from "koa"; +import compress = require("koa-compress"); + +const app = new Koa(); + +app.use(compress({ + filter: (ctype) => { + return /text/i.test(ctype) + }, + threshold: 2048 +})); + +app.listen(80) \ No newline at end of file diff --git a/koa-compress/koa-compress.d.ts b/koa-compress/koa-compress.d.ts new file mode 100644 index 0000000000..c4cd2af582 --- /dev/null +++ b/koa-compress/koa-compress.d.ts @@ -0,0 +1,41 @@ +// Type definitions for koa-compress v2.x +// Project: https://github.com/koajs/compress +// Definitions by: Jerry Chin +// Definitions: https://github.com/hellopao/DefinitelyTyped + +/* =================== USAGE =================== + + import compress = require("koa-compress"); + var Koa = require('koa'); + + var app = new Koa(); + app.use(compress()); + + =============================================== */ +/// +/// + +declare module "koa-compress" { + + import * as Koa from "koa"; + import * as zlib from "zlib"; + + interface CompressOptions extends zlib.ZlibOptions { + /** + * An optional function that checks the response content type to decide whether to compress. By default, it uses compressible. + */ + filter?: (content_type: string) => boolean; + + /** + * Minimum response size in bytes to compress. Default 1024 bytes or 1kb. + */ + threshold?: number + } + + /** + * Compress middleware for Koa + */ + function compress(options?: CompressOptions): { (ctx: Koa.Context, next?: () => any): any }; + + export = compress; +} diff --git a/node_zeromq/zmq-tests.ts b/node_zeromq/zmq-tests.ts index a62d97a6ca..0c7e031a12 100644 --- a/node_zeromq/zmq-tests.ts +++ b/node_zeromq/zmq-tests.ts @@ -42,3 +42,12 @@ function test5() { sock.monitor(); sock.monitor(10); } + +function test6() { + var sock = zmq.socket(zmq.types.dealer); + sock.bind('tcp://127.0.0.1', err => { + sock.send("some work"); + }); + sock.pause(); + sock.resume(); +} diff --git a/node_zeromq/zmq.d.ts b/node_zeromq/zmq.d.ts index 636a014aa6..838c3c6cd4 100644 --- a/node_zeromq/zmq.d.ts +++ b/node_zeromq/zmq.d.ts @@ -184,6 +184,19 @@ declare module 'zmq' { */ on(eventName: string, callback: (...buffer: Buffer[]) => void): void; + /** + * Set socket to pause mode + * no data will be emit until resume() is called + * all send() calls will be queued + */ + pause(): void; + + /** + * Set a socket back to normal work mode + * triggers a _flushReads and _flushWrites + */ + resume(): void; + // Socket Options _fd: any; _ioevents: any; diff --git a/openlayers/openlayers-tests.ts b/openlayers/openlayers-tests.ts index a2152b11ad..4937d52516 100644 --- a/openlayers/openlayers-tests.ts +++ b/openlayers/openlayers-tests.ts @@ -358,6 +358,14 @@ var imageWMS: ol.source.ImageWMS = new ol.source.ImageWMS({ serverType: stringValue, url:stringValue }); + +// +// ol.source.Source +// +const source = imageWMS as ol.source.Source; +voidValue = source.refresh(); +projection = source.getProjection(); + // // ol.source.TileWMS // @@ -367,6 +375,9 @@ var tileWMS: ol.source.TileWMS = new ol.source.TileWMS({ url:stringValue }); +tileWMS.updateParams(tileWMS.getParams()); +stringValue = tileWMS.getGetFeatureInfoUrl([0, 0], 1, "EPSG:4326", {}); + // // ol.source.WMTS // @@ -546,3 +557,7 @@ var modify: ol.interaction.Modify = new ol.interaction.Modify({ var draw: ol.interaction.Draw = new ol.interaction.Draw({ type: "Point" }) + +const select: ol.interaction.Select = new ol.interaction.Select({ + layers: (layer: ol.layer.Layer) => true, +}); diff --git a/openlayers/openlayers.d.ts b/openlayers/openlayers.d.ts index d1ec613314..fafaaa186b 100644 --- a/openlayers/openlayers.d.ts +++ b/openlayers/openlayers.d.ts @@ -552,12 +552,12 @@ declare namespace olx { interface SelectOptions { addCondition?: ol.events.ConditionType; condition?: ol.events.ConditionType; - layers?: Array; + layers?: Array | ((layer: ol.layer.Layer) => boolean); style?: ol.style.Style | Array | ol.style.StyleFunction; removeCondition?: ol.events.ConditionType; toggleCondition?: ol.events.ConditionType; multi?: boolean; - features?: ol.Collection + features?: ol.Collection; filter?: ol.interaction.SelectFilterFunction; wrapX?: boolean; } @@ -4085,76 +4085,117 @@ declare namespace ol { namespace source { - class BingMaps { + class BingMaps extends TileImage { } - class Cluster { + class CartoDB extends XYZ { } - class Image { + class Cluster extends Vector { } - class ImageCanvas { + class Image extends Source { + } + + class ImageArcGISRest extends Image { + } + + class ImageCanvas extends Image { } class ImageEvent { } - class ImageMapGuide { + class ImageMapGuide extends Image { } - class ImageStatic { + class ImageStatic extends Image { } - class ImageVector { + class ImageVector extends ImageCanvas { } - class ImageWMS { + class ImageWMS extends Image { constructor(options: olx.ImageWMSOptions); } - class MapQuest { + class MapQuest extends XYZ { constructor(options: any); } - class OSM { + class OSM extends XYZ { } - class Source { + class Source extends ol.Object { + /** + * Get the projection of the source. + * @return Projection. + */ + getProjection(): ol.proj.Projection; + + /** + * Refreshes the source and finally dispatches a 'change' event. + */ + refresh(): void; } - class Stamen { + class Stamen extends XYZ { } - class Tile { + class Tile extends Source { } - class TileArcGISRest { + class TileArcGISRest extends TileImage { } - class TileDebug { + class TileDebug extends Tile { } class TileEvent { } - class TileImage { + class TileImage extends UrlTile { } - class TileJSON { + class TileJSON extends TileImage { } - class TileUTFGrid { + class TileUTFGrid extends Tile { } - class TileVector { - } - - class TileWMS { + class TileWMS extends TileImage { constructor(options: olx.TileWMSOptions); + + /** + * Update the user-provided (WMS request) parameters. + */ + updateParams(params: any): void; + + /** + * Get the user-provided (WMS request) params, i.e. those passed to the constructor through the "params" option, and possibly updated using the updateParams method. + */ + getParams(): any; + + /** + * Return the GetFeatureInfo URL for the passed coordinate, resolution, and + * projection. Return `undefined` if the GetFeatureInfo URL cannot be + * constructed. + * @param coordinate Coordinate. + * @param resolution Resolution. + * @param rojection Projection. + * @param params GetFeatureInfo params. `INFO_FORMAT` at least should + * be provided. If `QUERY_LAYERS` is not provided then the layers specified + * in the `LAYERS` parameter will be used. `VERSION` should not be + * specified here. + * @return GetFeatureInfo URL. + */ + getGetFeatureInfoUrl(coordinate: ol.Coordinate, resolution: number, projection: ol.proj.ProjectionLike, params: {}): string; } - class Vector { + class UrlTile extends Tile { + } + + class Vector extends Source { constructor(opts?: olx.source.VectorOptions) /** * Add a single feature to the source. If you want to add a batch of features at once, @@ -4198,14 +4239,17 @@ declare namespace ol { class VectorEvent { } - class WMTS { + class VectorTile extends UrlTile { + } + + class WMTS extends TileImage { constructor(options: olx.source.WMTSOptions); } - class XYZ { + class XYZ extends TileImage { } - class Zoomify { + class Zoomify extends TileImage { } // Namespaces diff --git a/react-slick/react-slick-test.tsx b/react-slick/react-slick-test.tsx new file mode 100644 index 0000000000..c351419401 --- /dev/null +++ b/react-slick/react-slick-test.tsx @@ -0,0 +1,31 @@ +/// +/// +/// + +import * as React from "react" +import * as ReactDOM from "react-dom" +import * as Slider from "react-slick" + +class SliderTest extends React.Component, {}> { + + render() { + let settings = { + speed: 500, + slidesToShow: 8, + slidesToScroll: 1, + draggable: false, + infinite: false + }; + + return ( +
+ +

Slide1

+

Slide2

+
+
+ ) + } +} + +ReactDOM.render(, document.body); diff --git a/react-slick/react-slick.d.ts b/react-slick/react-slick.d.ts new file mode 100644 index 0000000000..43c9cdcf69 --- /dev/null +++ b/react-slick/react-slick.d.ts @@ -0,0 +1,50 @@ +// Type definitions for react-slick +// Project: https://github.com/akiran/react-slick +// Definitions by: Andrey Balokha +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface __config { + className?: string + adaptiveHeight?: boolean + arrows?: boolean + autoplay?: boolean + autoplaySpeed?: number // integer + centerMode?: boolean + centerPadding?: string | any + cssEase?: string | any + dots?: boolean + dotsClass?: string + draggable?: boolean + easing?: string + fade?: boolean + focusOnSelect?: boolean + infinite?: boolean // should the gallery wrap around it's contents + initialSlide?: number // int + lazyLoad?: boolean + rtl?: boolean + slide?: string + slidesToShow?: number // int + slidesToScroll?: number // int + speed?: number //int + swipe?: boolean + swipeToSlide?: boolean + touchMove?: boolean + touchThreshold?: number // int + variableWidth?: boolean + useCSS?: boolean + vertical?: boolean + afterChange?: (() => void) + beforeChange?: (() => void) + slickGoTo?: number // int +} + +interface Slider extends __config { + responsive?: { breakpoint: number; settings: __config}[] +} + +declare module "react-slick" { + var Slider: __React.ClassicComponentClass; + export = Slider; +} diff --git a/resumablejs/resumablejs-tests.ts b/resumablejs/resumablejs-tests.ts new file mode 100644 index 0000000000..e2e9d180d4 --- /dev/null +++ b/resumablejs/resumablejs-tests.ts @@ -0,0 +1,33 @@ +/// + +import { Resumable, ResumableFile } from 'resumablejs'; + +let resumable: Resumable = new Resumable({chunkSize: 123}); +let resumableDefaultOpts: Resumable = new Resumable({}); +resumable.addFile(null, null); +resumable.assignBrowse(document.getElementById("test"), true); +resumable.assignBrowse([document.getElementById("test")], true); +resumable.assignDrop(document.getElementById("test")); +resumable.assignDrop([document.getElementById("test")]); +resumable.unAssignDrop(document.getElementById("test")); +resumable.unAssignDrop([document.getElementById("test")]); +resumable.cancel(); +let defaults: Object = resumable.defaults; +let events: any[] = resumable.events; +let files: any[] = resumable.files; +resumable.fire(); +let {} = resumable.getFromUniqueIdentifier('test'); +let {} = resumable.getOpt('test'); +let size: number = resumable.getSize(); +resumable.handleChangeEvent(null); +resumable.handleDropEvent(null); +let isUploading: boolean = resumable.isUploading(); +resumable.on('test', function() {}); +let opts: Object = resumable.opts; +resumable.pause(); +let progress:number = resumable.progress(); +resumable.removeFile(null); +let support: boolean = resumable.support; +resumable.upload(); +resumable.uploadNextChunk(); +let version:number = resumable.version; \ No newline at end of file diff --git a/resumablejs/resumablejs.d.ts b/resumablejs/resumablejs.d.ts new file mode 100644 index 0000000000..c87d669a07 --- /dev/null +++ b/resumablejs/resumablejs.d.ts @@ -0,0 +1,374 @@ +// Type definitions for Resumable.js v1.0.2 +// Project: https://github.com/23/resumable.js +// Definitions by: Daniel McAssey +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Resumable { + interface ConfigurationHash { + /** + * The target URL for the multipart POST request. This can be a string or a function that allows you you to construct and return a value, based on supplied params. (Default: /) + **/ + target?: string; + /** + * The size in bytes of each uploaded chunk of data. The last uploaded chunk will be at least this size and up to two the size, see Issue #51 for details and reasons. (Default: 1*1024*1024) + **/ + chunkSize?: number; + /** + * Force all chunks to be less or equal than chunkSize. Otherwise, the last chunk will be greater than or equal to chunkSize. (Default: false) + **/ + forceChunkSize?: boolean; + /** + * Number of simultaneous uploads (Default: 3) + **/ + simultaneousUploads?: number; + /** + * The name of the multipart POST parameter to use for the file chunk (Default: file) + **/ + fileParameterName?: string; + /** + * The name of the chunk index (base-1) in the current upload POST parameter to use for the file chunk (Default: resumableChunkNumber) + */ + chunkNumberParameterName?: string; + /** + * The name of the total number of chunks POST parameter to use for the file chunk (Default: resumableTotalChunks) + */ + totalChunksParameterName?: string; + /** + * The name of the general chunk size POST parameter to use for the file chunk (Default: resumableChunkSize) + */ + chunkSizeParameterName?: string; + /** + * The name of the total file size number POST parameter to use for the file chunk (Default: resumableTotalSize) + */ + totalSizeParameterName?: string; + /** + * The name of the unique identifier POST parameter to use for the file chunk (Default: resumableIdentifier) + */ + identifierParameterName?: string; + /** + * The name of the original file name POST parameter to use for the file chunk (Default: resumableFilename) + */ + fileNameParameterName?: string; + /** + * The name of the file's relative path POST parameter to use for the file chunk (Default: resumableRelativePath) + */ + relativePathParameterName?: string; + /** + * The name of the current chunk size POST parameter to use for the file chunk (Default: resumableCurrentChunkSize) + */ + currentChunkSizeParameterName?: string; + /** + * The name of the file type POST parameter to use for the file chunk (Default: resumableType) + */ + typeParameterName?: string; + /** + * Extra parameters to include in the multipart POST with data. This can be an object or a function. If a function, it will be passed a ResumableFile and a ResumableChunk object (Default: {}) + **/ + query?: Object; + /** + * Method for chunk test request. (Default: 'GET') + **/ + testMethod?: string; + /** + * Method for chunk upload request. (Default: 'POST') + **/ + uploadMethod?: string; + /** + * Extra prefix added before the name of each parameter included in the multipart POST or in the test GET. (Default: '') + **/ + parameterNamespace?: string; + /** + * Extra headers to include in the multipart POST with data. This can be an object or a function that allows you to construct and return a value, based on supplied file (Default: {}) + **/ + headers?: Object | ((file: ResumableFile) => Object); + /** + * Method to use when POSTing chunks to the server (multipart or octet) (Default: multipart) + **/ + method?: string; + /** + * Prioritize first and last chunks of all files. This can be handy if you can determine if a file is valid for your service from only the first or last chunk. For example, photo or video meta data is usually located in the first part of a file, making it easy to test support from only the first chunk. (Default: false) + **/ + prioritizeFirstAndLastChunk?: boolean; + /** + * Make a GET request to the server for each chunks to see if it already exists. If implemented on the server-side, this will allow for upload resumes even after a browser crash or even a computer restart. (Default: true) + **/ + testChunks?: boolean; + /** + * Optional function to process each chunk before testing & sending. Function is passed the chunk as parameter, and should call the preprocessFinished method on the chunk when finished. (Default: null) + **/ + preprocess?: (chunk: ResumableChunk) => ResumableChunk; + /** + * Override the function that generates unique identifiers for each file. (Default: null) + **/ + generateUniqueIdentifier?: () => string; + /** + * Indicates how many files can be uploaded in a single session. Valid values are any positive integer and undefined for no limit. (Default: undefined) + **/ + maxFiles?: number; + /** + * A function which displays the please upload n file(s) at a time message. (Default: displays an alert box with the message Please n one file(s) at a time.) + **/ + maxFilesErrorCallback?: (files: ResumableFile, errorCount: number) => void; + /** + * The minimum allowed file size. (Default: undefined) + **/ + minFileSize?: boolean; + /** + * A function which displays an error a selected file is smaller than allowed. (Default: displays an alert for every bad file.) + **/ + minFileSizeErrorCallback?:(file: ResumableFile, errorCount: number) => void; + /** + * The maximum allowed file size. (Default: undefined) + **/ + maxFileSize?: boolean; + /** + * A function which displays an error a selected file is larger than allowed. (Default: displays an alert for every bad file.) + **/ + maxFileSizeErrorCallback?: (file: ResumableFile, errorCount: number) => void; + /** + * The file types allowed to upload. An empty array allow any file type. (Default: []) + **/ + fileType?: string[]; + /** + * A function which displays an error a selected file has type not allowed. (Default: displays an alert for every bad file.) + **/ + fileTypeErrorCallback?: (file: ResumableFile, errorCount: number) => void; + /** + * The maximum number of retries for a chunk before the upload is failed. Valid values are any positive integer and undefined for no limit. (Default: undefined) + **/ + maxChunkRetries?: number; + /** + * The number of milliseconds to wait before retrying a chunk on a non-permanent error. Valid values are any positive integer and undefined for immediate retry. (Default: undefined) + **/ + chunkRetryInterval?: number; + /** + * Standard CORS requests do not send or set any cookies by default. In order to include cookies as part of the request, you need to set the withCredentials property to true. (Default: false) + **/ + withCredentials?: boolean; + } + + class Resumable { + constructor(options:ConfigurationHash); + + /** + * A boolean value indicator whether or not Resumable.js is supported by the current browser. + **/ + support: boolean; + /** + * A hash object of the configuration of the Resumable.js instance. + **/ + opts: ConfigurationHash; + /** + * An array of ResumableFile file objects added by the user (see full docs for this object type below). + **/ + files: ResumableFile[]; + + defaults: ConfigurationHash; + + events: Event[]; + version: number; + + /** + * Assign a browse action to one or more DOM nodes. Pass in true to allow directories to be selected (Chrome only). + **/ + assignBrowse(domNode: Element, isDirectory: boolean): void; + assignBrowse(domNodes: Element[], isDirectory: boolean): void; + /** + * Assign one or more DOM nodes as a drop target. + **/ + assignDrop(domNode: Element): void; + assignDrop(domNodes: Element[]): void; + unAssignDrop(domNode: Element): void; + unAssignDrop(domNodes: Element[]): void; + /** + * Start or resume uploading. + **/ + upload(): void; + uploadNextChunk(): void; + /** + * Pause uploading. + **/ + pause(): void; + /** + * Cancel upload of all ResumableFile objects and remove them from the list. + **/ + cancel(): void; + fire(): void; + /** + * Returns a float between 0 and 1 indicating the current upload progress of all files. + **/ + progress(): number; + /** + * Returns a boolean indicating whether or not the instance is currently uploading anything. + **/ + isUploading(): boolean; + /** + * Add a HTML5 File object to the list of files. + **/ + addFile(file: File, event: Event): void; + /** + * Cancel upload of a specific ResumableFile object on the list from the list. + **/ + removeFile(file: ResumableFile): void; + /** + * Look up a ResumableFile object by its unique identifier. + **/ + getFromUniqueIdentifier(uniqueIdentifier: string): void; + /** + * Returns the total size of the upload in bytes. + **/ + getSize(): number; + getOpt(o: string): any; + + // Events + /** + * Change event handler + **/ + handleChangeEvent(e: Event): void; + + /** + * Drop event handler + **/ + handleDropEvent(e: Event): void; + + /** + * A specific file was completed. + **/ + on(event: 'fileSuccess', callback: (file: ResumableFile) => void): void; + /** + * Uploading progressed for a specific file. + **/ + on(event: 'fileProgress', callback: (file: ResumableFile) => void): void; + /** + * A new file was added. Optionally, you can use the browser event object from when the file was added. + **/ + on(event: 'fileAdded', callback: (file: ResumableFile, event: DragEvent) => void): void; + /** + * New files were added. + **/ + on(event: 'filesAdded', callback: (files: ResumableFile[]) => void): void; + /** + * Something went wrong during upload of a specific file, uploading is being retried. + **/ + on(event: 'fileRetry', callback: (file: ResumableFile) => void): void; + /** + * An error occurred during upload of a specific file. + **/ + on(event: 'fileError', callback: (file: ResumableFile, message: string) => void): void; + /** + * Upload has been started on the Resumable object. + **/ + on(event: 'uploadStart', callback: () => void): void; + /** + * Uploading completed. + **/ + on(event: 'complete', callback: () => void): void; + /** + * Uploading progress. + **/ + on(event: 'progress', callback: () => void): void; + /** + * An error, including fileError, occurred. + **/ + on(event: 'error', callback: (message: string, file: ResumableFile) => void): void; + /** + * Uploading was paused. + **/ + on(event: 'pause', callback: () => void): void; + /** + * Triggers before the items are cancelled allowing to do any processing on uploading files. + **/ + on(event: 'beforeCancel', callback: () => void): void; + /** + * Uploading was canceled. + **/ + on(event: 'cancel', callback: () => void): void; + /** + * Started preparing file for upload + **/ + on(event: 'chunkingStart', callback: (file: ResumableFile) => void): void; + /** + * Show progress in file preparation + **/ + on(event: 'chunkingProgress', callback: (file: ResumableFile, ratio: number) => void): void; + /** + * File is ready for upload + **/ + on(event: 'chunkingComplete', callback: (file: ResumableFile) => void): void; + /** + * Listen to all the events listed above with the same callback function. + **/ + on(event: 'catchAll', callback: () => void): void; + /** + * Listen for event from Resumable.js (see below) + **/ + on(event: string, callback: Function): void; + } + + interface ResumableFile { + /** + * A back-reference to the parent Resumable object. + **/ + resumableObj: Resumable; + /** + * The correlating HTML5 File object. + **/ + file: File; + /** + * The name of the file. + **/ + fileName: string; + /** + * The relative path to the file (defaults to file name if relative path doesn't exist) + **/ + relativePath: string; + /** + * Size in bytes of the file. + **/ + size: number; + /** + * A unique identifier assigned to this file object. This value is included in uploads to the server for reference, but can also be used in CSS classes etc when building your upload UI. + **/ + uniqueIdentifier: string; + /** + * An array of ResumableChunk items. You shouldn't need to dig into these. + **/ + chunks: ResumableChunk[]; + + + /** + * Returns a float between 0 and 1 indicating the current upload progress of the file. If relative is true, the value is returned relative to all files in the Resumable.js instance. + **/ + progress: (relative: boolean) => number; + /** + * Abort uploading the file. + **/ + abort: () => void; + /** + * Abort uploading the file and delete it from the list of files to upload. + **/ + cancel: () => void; + /** + * Retry uploading the file. + **/ + retry: () => void; + /** + * Rebuild the state of a ResumableFile object, including reassigning chunks and XMLHttpRequest instances. + **/ + bootstrap: () => void; + /** + * Returns a boolean indicating whether file chunks is uploading. + **/ + isUploading: () => boolean; + /** + * Returns a boolean indicating whether the file has completed uploading and received a server response. + **/ + isComplete: () => boolean; + } + + interface ResumableChunk {} +} + +declare module 'resumablejs' { + export = Resumable; +} diff --git a/revalidator/revalidator-tests.ts b/revalidator/revalidator-tests.ts new file mode 100644 index 0000000000..b65c9f971b --- /dev/null +++ b/revalidator/revalidator-tests.ts @@ -0,0 +1,3 @@ +/// + +revalidator.validate(null, null, null); \ No newline at end of file diff --git a/revalidator/revalidator.d.ts b/revalidator/revalidator.d.ts new file mode 100644 index 0000000000..63f492e9c3 --- /dev/null +++ b/revalidator/revalidator.d.ts @@ -0,0 +1,48 @@ +// Type definitions for revalidator 0.3.1 +// Project: https://github.com/flatiron/revalidator +// Definitions by: Jason Turner +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module Revalidator { + interface RevalidatorStatic { + validate(object: any, schema: ISchema, options: any): IReturnMessage; + } + + interface IErrrorProperty { + property: string; + message: string; + } + + interface IReturnMessage { + valid: boolean; + errors: IErrrorProperty[]; + } + + interface ISchema { + required?: boolean; + type: string; + pattern?: any; + maxLength?: number; + minLength?: number; + minimum?: number; + maximum?: number; + allowEmpty: boolean; + exclusiveMinimum: number; + exclusiveMaximum?: number; + divisibleBy?: number; + minItems?: number; + maxItems?: number; + uniqueItems?: boolean; + enum?: any; + format?: string; + conform?: (data:any) => boolean; + depdendencies?: string; + + } +} + +declare var revalidator: Revalidator.RevalidatorStatic; + +declare module "revalidator" { + export = revalidator; +} \ No newline at end of file diff --git a/sequelize/sequelize.d.ts b/sequelize/sequelize.d.ts index cc0ff0b4ff..38072ee079 100644 --- a/sequelize/sequelize.d.ts +++ b/sequelize/sequelize.d.ts @@ -2595,7 +2595,6 @@ declare module "sequelize" { * Transaction to run query under */ transaction? : Transaction; - } /** @@ -2652,13 +2651,7 @@ declare module "sequelize" { /** * Options used for Instance.save method */ - interface InstanceSaveOptions { - - /** - * An optional array of strings, representing database columns. If fields is provided, only those columns - * will be validated and saved. - */ - fields? : string[]; + interface InstanceSaveOptions extends FieldsOptions, LoggingOptions, ReturningOptions, SearchPathOptions { /** * If true, the updatedAt timestamp will not be updated. @@ -2667,23 +2660,6 @@ declare module "sequelize" { */ silent? : boolean; - /** - * If false, validations won't be run. - * - * Defaults to true - */ - validate? : boolean; - - /** - * A function that gets executed while running the query to log the sql. - */ - logging? : boolean | Function; - - /** - * Transaction to run the query in - */ - transaction? : Transaction; - } /** @@ -2907,6 +2883,50 @@ declare module "sequelize" { } + interface LoggingOptions { + /** + * A function that gets executed while running the query to log the sql. + */ + + logging?: boolean | Function; + + /** + * Print query execution time in milliseconds when logging SQL. + */ + benchmark?: boolean; + } + + interface SearchPathOptions { + /** + * Transaction to run query under + */ + transaction? : Transaction; + + /** + * An optional parameter to specify the schema search_path (Postgres only) + */ + searchPath? : string; + } + + interface ReturningOptions { + /** + * Append RETURNING * to get back auto generated values (Postgres only) + */ + returning? : boolean; + } + + interface FieldsOptions { + /** + * Run validations before the row is inserted + */ + validate? : boolean; + + /** + * The fields to insert / update. Defaults to all fields + */ + fields? : string[]; + } + // // Model // ~~~~~~~ @@ -2917,47 +2937,44 @@ declare module "sequelize" { /** * Options to pass to Model on drop */ - interface DropOptions { + interface DropOptions extends LoggingOptions { /** * Also drop all objects depending on this table, such as views. Only works in postgres */ cascade?: boolean; - /** - * A function that gets executed while running the query to log the sql. - */ - logging?: boolean | Function; - } /** * Schema Options provided for applying a schema to a model */ - interface SchemaOptions { + interface SchemaOptions extends LoggingOptions { /** * The character(s) that separates the schema name from the table name */ schemaDelimeter? : string; - /** - * A function that gets executed while running the query to log the sql. - */ - logging? : Function | boolean; - } + /** + * GetTableName Options + */ + interface GetTableNameOptions extends LoggingOptions { + // no addition properties + } + /** * AddScope Options for Model.addScope */ interface AddScopeOptions { - + /** * If a scope of the same name already exists, should it be overwritten? */ override: boolean; - + } /** @@ -3125,7 +3142,7 @@ declare module "sequelize" { * * A hash of options to describe the scope of the search */ - interface FindOptions { + interface FindOptions extends LoggingOptions, SearchPathOptions { /** * A hash of attributes to describe your search. See above for examples. @@ -3172,11 +3189,6 @@ declare module "sequelize" { */ offset?: number; - /** - * Transaction to run query under - */ - transaction? : Transaction; - /** * Lock the selected rows. Possible options are transaction.LOCK.UPDATE and transaction.LOCK.SHARE. * Postgres also supports transaction.LOCK.KEY_SHARE, transaction.LOCK.NO_KEY_UPDATE and specific model @@ -3189,11 +3201,6 @@ declare module "sequelize" { */ raw? : boolean; - /** - * A function that gets executed while running the query to log the sql. - */ - logging? : boolean | Function; - /** * having ?!? */ @@ -3210,7 +3217,7 @@ declare module "sequelize" { /** * Options for Model.count method */ - interface CountOptions { + interface CountOptions extends LoggingOptions, SearchPathOptions { /** * A hash of search attributes. @@ -3238,19 +3245,12 @@ declare module "sequelize" { * TODO: Check? */ group? : Object; - - /** - * A function that gets executed while running the query to log the sql. - */ - logging? : boolean | Function; - - transaction?: Transaction; } /** * Options for Model.build method */ - interface BuildOptions { + interface BuildOptions extends ReturningOptions { /** * If set to true, values will ignore field and virtual setters. @@ -3268,43 +3268,23 @@ declare module "sequelize" { * TODO: See set */ include? : Array | IncludeOptions>; - } /** * Options for Model.create method */ - interface CreateOptions extends BuildOptions { - - /** - * If set, only columns matching those in fields will be saved - */ - fields? : string[]; + interface CreateOptions extends BuildOptions, InstanceSaveOptions { /** * On Duplicate */ onDuplicate? : string; - - /** - * Transaction to run query under - */ - transaction? : Transaction; - - /** - * A function that gets executed while running the query to log the sql. - */ - logging? : boolean | Function; - - silent? : boolean; - - returning? : boolean; } /** * Options for Model.findOrInitialize method */ - interface FindOrInitializeOptions { + interface FindOrInitializeOptions extends LoggingOptions { /** * A hash of search attributes. @@ -3320,65 +3300,35 @@ declare module "sequelize" { * Transaction to run query under */ transaction? : Transaction; + } + + /** + * Options for Model.findOrInitialize method + */ + interface FindCreateFindOptions { /** - * A function that gets executed while running the query to log the sql. + * A hash of search attributes. */ - logging? : boolean | Function; + where : string | WhereOptions; + /** + * Default values to use if building a new instance + */ + defaults? : TAttributes; } /** * Options for Model.upsert method */ - interface UpsertOptions { - - /** - * Run validations before the row is inserted - */ - validate? : boolean; - - /** - * The fields to insert / update. Defaults to all fields - */ - fields? : string[]; - - /** - * A function that gets executed while running the query to log the sql. - */ - logging? : boolean | Function; - - /** - * Transaction to run query under - */ - transaction? : Transaction; - - /** - * An optional parameter to specify the schema search_path (Postgres only) - */ - searchPath? : string; - - /** - * Print query execution time in milliseconds when logging SQL. - */ - benchmark? : boolean; + interface UpsertOptions extends FieldsOptions, LoggingOptions, SearchPathOptions { } /** * Options for Model.bulkCreate method */ - interface BulkCreateOptions { - /** - * Fields to insert (defaults to all fields) - */ - fields? : string[]; - - /** - * Should each row be subject to validation before it is inserted. The whole insert will fail if one row - * fails validation - */ - validate? : boolean; + interface BulkCreateOptions extends FieldsOptions, LoggingOptions, SearchPathOptions, ReturningOptions { /** * Run before / after bulk create hooks? @@ -3403,28 +3353,12 @@ declare module "sequelize" { * mariadb). By default, all fields are updated. */ updateOnDuplicate? : string[]; - - /** - * Transaction to run query under - */ - transaction? : Transaction; - - /** - * A function that gets executed while running the query to log the sql. - */ - logging? : boolean | Function; - } /** * The options passed to Model.destroy in addition to truncate */ - interface TruncateOptions { - - /** - * Transaction to run query under - */ - transaction? : Transaction; + interface TruncateOptions extends LoggingOptions, SearchPathOptions { /** * Only used in conjuction with TRUNCATE. Truncates all tables that have foreign-key references to the @@ -3433,12 +3367,6 @@ declare module "sequelize" { * Defaults to false; */ cascade? : boolean; - - /** - * A function that gets executed while running the query to log the sql. - */ - logging? : boolean | Function; - } /** @@ -3483,7 +3411,7 @@ declare module "sequelize" { /** * Options for Model.restore */ - interface RestoreOptions { + interface RestoreOptions extends LoggingOptions { /** * Filter the restore @@ -3506,11 +3434,6 @@ declare module "sequelize" { */ limit? : number; - /** - * A function that gets executed while running the query to log the sql. - */ - logging? : boolean | Function; - /** * Transaction to run query under */ @@ -3521,26 +3444,13 @@ declare module "sequelize" { /** * Options used for Model.update */ - interface UpdateOptions { + interface UpdateOptions extends FieldsOptions, LoggingOptions, ReturningOptions { /** * Options to describe the scope of the search. */ where: WhereOptions; - /** - * Fields to update (defaults to all fields) - */ - fields? : string[]; - - /** - * Should each row be subject to validation before it is inserted. The whole insert will fail if one row - * fails validation. - * - * Defaults to true - */ - validate? : boolean; - /** * Run before / after bulk update hooks? * @@ -3563,32 +3473,26 @@ declare module "sequelize" { */ individualHooks? : boolean; - /** - * Return the affected rows (only for postgres) - */ - returning? : boolean; - /** * How many rows to update (only for mysql and mariadb) */ limit? : number; - /** - * A function that gets executed while running the query to log the sql. - */ - logging? : boolean | Function; - /** * Transaction to run query under */ transaction? : Transaction; + /** + * If true, the updatedAt timestamp will not be updated. + */ + silent? : boolean; } /** * Options used for Model.aggregate */ - interface AggregateOptions extends QueryOptions { + interface AggregateOptions extends LoggingOptions { /** * A hash of search attributes. @@ -3606,6 +3510,17 @@ declare module "sequelize" { */ distinct? : boolean; + /** + * The transaction that the query should be executed under + */ + transaction?: Transaction; + + /** + * When `true`, the first returned value of `aggregateFunction` is cast to `dataType` and returned. + * If additional attributes are specified, along with `group` clauses, set `plain` to `false` to return all values of all returned rows. + * Defaults to `true` + */ + plain?: boolean; } /** @@ -3661,7 +3576,7 @@ declare module "sequelize" { * subscribers_1, subscribers_2) * @param options.logging=false A function that gets executed while running the query to log the sql. */ - getTableName( options? : { logging : Function } ) : string | Object; + getTableName( options? : GetTableNameOptions ) : string | Object; /** * Add a new scope to the model. This is especially useful for adding scopes with includes, when the model you want to include is not available at the time this model is defined. @@ -3801,7 +3716,7 @@ declare module "sequelize" { * instance. */ findOne( options? : FindOptions ) : Promise; - find( optionz? : FindOptions ) : Promise; + find( options? : FindOptions ) : Promise; /** * Run an aggregation method on the specified field @@ -3909,6 +3824,12 @@ declare module "sequelize" { */ findOrCreate( options : FindOrInitializeOptions ) : Promise; + /** + * A more performant findOrCreate that will not work under a transaction (at least not in postgres) + * Will execute a find call, if empty then attempt to create, if unique constraint then attempt to find again + */ + findCreateFind( options : FindCreateFindOptions ) : Promise; + /** * Insert or update a single row. An update will be executed if a row which matches the supplied values on * either the primary key or a unique key is found. Note that the unique index must be defined in your @@ -4493,7 +4414,7 @@ declare module "sequelize" { * * @see Options */ - interface QueryOptions { + interface QueryOptions extends SearchPathOptions, ReturningOptions { /** * If true, sequelize will not try to format the results of the query, or build an instance of a model from @@ -4501,10 +4422,6 @@ declare module "sequelize" { */ raw?: boolean; - /** - * The transaction that the query should be executed under - */ - transaction?: Transaction; /** * The type of query you are executing. The query type affects how results are formatted before they are @@ -4533,6 +4450,12 @@ declare module "sequelize" { */ replacements? : Object | string[]; + /** + * Either an object of named bind parameter in the format `$param` or an array of unnamed + * bind parameter to replace `$1`, `$2`, ... in your SQL. + */ + bind?: Object | string[]; + /** * Force the query to use the write pool, regardless of the query type. * @@ -4543,7 +4466,7 @@ declare module "sequelize" { /** * A function that gets executed while running the query to log the sql. */ - logging? : Function; + logging? : boolean | Function; /** * A sequelize instance used to build the return instance @@ -4555,8 +4478,24 @@ declare module "sequelize" { */ model? : Model; - // TODO: force, cascade + /** + * Set of flags that control when a query is automatically retried. + */ + retry? : {match?: string[], max?: number}; + /** + * If false do not prepend the query with the search_path (Postgres only) + */ + supportsSearchPath? : boolean; + + /** + * Map returned fields to model's fields if `options.model` or `options.instance` is present. + * Mapping will occur before building the model instance. + */ + mapToModel? : boolean; + + // TODO: force, cascade + fieldMap? : { [key: string]: string; } } /** @@ -6197,4 +6136,4 @@ declare module "sequelize" { export = sequelize; -} \ No newline at end of file +} diff --git a/soap/soap-tests.ts b/soap/soap-tests.ts index 8010d7285e..100bacf2f5 100644 --- a/soap/soap-tests.ts +++ b/soap/soap-tests.ts @@ -11,7 +11,10 @@ const wsdlOptions = { name: 'value' }; soap.createClient(url, wsdlOptions, function(err: any, client: soap.Client) { let securityOptions = { 'hasTimeStamp': false }; client.setSecurity(new soap.WSSecurity('user', 'password', securityOptions)); + let defaults = {'rejectUnauthorized': false}; + client.setSecurity(new soap.ClientSSLSecurity('/path/to/key', '/path/to/cert', '/path/to/ca',defaults)); client.addSoapHeader({}); + client.setEndpoint('http://localhost'); client['create']({ name: 'value' }, function(err, result) { // result is an object }); diff --git a/soap/soap.d.ts b/soap/soap.d.ts index fa26cbf04c..6fcd1b703f 100644 --- a/soap/soap.d.ts +++ b/soap/soap.d.ts @@ -8,13 +8,19 @@ declare module 'soap' { import * as events from 'events'; - class WSSecurity { + interface Security { + } + class WSSecurity implements Security { constructor(username: string, password: string, options: any); } + class ClientSSLSecurity implements Security { + constructor(key: string, cert: string, ca: string, defaults: any); + } interface Client extends events.EventEmitter { - setSecurity(s: WSSecurity): void; + setSecurity(s: Security): void; [method: string]: (args: any, fn: (err: any, result: any) => void, options?: any, extraHeaders?: any) => void; addSoapHeader(headJSON: any): void; + setEndpoint(endpoint: string): void; } function createClient(wsdlPath: string, options: any, fn: (err: any, client: Client) => void): void; diff --git a/umbraco/umbraco-services.d.ts b/umbraco/umbraco-services.d.ts index 10710492ab..8b7609c859 100644 --- a/umbraco/umbraco-services.d.ts +++ b/umbraco/umbraco-services.d.ts @@ -494,6 +494,10 @@ declare namespace umbraco.services { width?: number; /*strips the modal from any animation and wrappers, used when you want to inject a dialog into an existing container*/ inline?: boolean; + /** + * It will set this value as a property on the dialog controller's scope as $scope.dialogData + */ + dialogData?: any; } /** diff --git a/underscore/underscore.d.ts b/underscore/underscore.d.ts index 4b4f9da700..761d9bca06 100644 --- a/underscore/underscore.d.ts +++ b/underscore/underscore.d.ts @@ -289,7 +289,7 @@ interface UnderscoreStatic { detect( object: _.Dictionary, iterator: _.ObjectIterator, - context?: any): T; + context?: any): T; /** * @see _.find @@ -918,15 +918,15 @@ interface UnderscoreStatic { **/ zip(...arrays: any[]): any[]; - /** - * The opposite of zip. Given a number of arrays, returns a series of new arrays, the first - * of which contains all of the first elements in the input arrays, the second of which - * contains all of the second elements, and so on. Use with apply to pass in an array - * of arrays - * @param arrays The arrays to unzip. - * @return Unzipped version of `arrays`. - **/ - unzip(...arrays: any[][]): any[][]; + /** + * The opposite of zip. Given a number of arrays, returns a series of new arrays, the first + * of which contains all of the first elements in the input arrays, the second of which + * contains all of the second elements, and so on. Use with apply to pass in an array + * of arrays + * @param arrays The arrays to unzip. + * @return Unzipped version of `arrays`. + **/ + unzip(...arrays: any[][]): any[][]; /** * Converts arrays into objects. Pass either a single list of [key, value] pairs, or a @@ -3520,7 +3520,7 @@ interface UnderscoreStatic { **/ keys(object: any): string[]; - /** + /** * Retrieve all the names of object's own and inherited properties. * @param object Retrieve the key or property names from this object. * @return List of all the property names on `object`. @@ -3541,30 +3541,30 @@ interface UnderscoreStatic { **/ values(object: any): any[]; - /** - * Like map, but for objects. Transform the value of each property in turn. - * @param object The object to transform - * @param iteratee The function that transforms property values - * @param context The optional context (value of `this`) to bind to - * @return a new _.Dictionary of property values - */ - mapObject(object: _.Dictionary, iteratee: (val: T, key: string, object: _.Dictionary) => U, context?: any): _.Dictionary; + /** + * Like map, but for objects. Transform the value of each property in turn. + * @param object The object to transform + * @param iteratee The function that transforms property values + * @param context The optional context (value of `this`) to bind to + * @return a new _.Dictionary of property values + */ + mapObject(object: _.Dictionary, iteratee: (val: T, key: string, object: _.Dictionary) => U, context?: any): _.Dictionary; - /** - * Like map, but for objects. Transform the value of each property in turn. - * @param object The object to transform - * @param iteratee The function that tranforms property values - * @param context The optional context (value of `this`) to bind to - */ - mapObject(object: any, iteratee: (val: any, key: string, object: any) => T, context?: any): _.Dictionary; + /** + * Like map, but for objects. Transform the value of each property in turn. + * @param object The object to transform + * @param iteratee The function that tranforms property values + * @param context The optional context (value of `this`) to bind to + */ + mapObject(object: any, iteratee: (val: any, key: string, object: any) => T, context?: any): _.Dictionary; - /** - * Like map, but for objects. Retrieves a property from each entry in the object, as if by _.property - * @param object The object to transform - * @param iteratee The property name to retrieve - * @param context The optional context (value of `this`) to bind to - */ - mapObject(object: any, iteratee: string, context?: any): _.Dictionary; + /** + * Like map, but for objects. Retrieves a property from each entry in the object, as if by _.property + * @param object The object to transform + * @param iteratee The property name to retrieve + * @param context The optional context (value of `this`) to bind to + */ + mapObject(object: any, iteratee: string, context?: any): _.Dictionary; /** * Convert an object into a list of [key, value] pairs. @@ -3713,12 +3713,12 @@ interface UnderscoreStatic { **/ property(key: string): (object: Object) => any; - /** + /** * Returns a function that will itself return the value of a object key property. * @param key The object to get the property value from. * @return Function which accept a key property in `object` and returns its value. **/ - propertyOf(object: Object): (key: string) => any; + propertyOf(object: Object): (key: string) => any; /** * Performs an optimized deep comparison between the two objects, @@ -3964,7 +3964,7 @@ interface UnderscoreStatic { * If the value of the named property is a function then invoke it; otherwise, return it. * @param object Object to maybe invoke function `property` on. * @param property The function by name to invoke on `object`. - * @param defaultValue The value to be returned in case `property` doesn't exist or is undefined. + * @param defaultValue The value to be returned in case `property` doesn't exist or is undefined. * @return The result of invoking the function `property` on `object. **/ result(object: any, property: string, defaultValue?:any): any; @@ -4447,7 +4447,7 @@ interface Underscore { **/ zip(...arrays: any[][]): any[][]; - /** + /** * Wrapped type `any[][]`. * @see _.unzip **/ @@ -4612,11 +4612,11 @@ interface Underscore { **/ keys(): string[]; - /** + /** * Wrapped type `object`. * @see _.allKeys **/ - allKeys(): string[]; + allKeys(): string[]; /** * Wrapped type `object`. @@ -4705,7 +4705,7 @@ interface Underscore { **/ property(): (object: Object) => any; - /** + /** * Wrapped type `object`. * @see _.propertyOf **/ @@ -4759,7 +4759,7 @@ interface Underscore { **/ isFunction(): boolean; - /** + /** * Wrapped type `object`. * @see _.isError **/ @@ -5365,7 +5365,7 @@ interface _Chain { **/ zip(...arrays: any[][]): _Chain; - /** + /** * Wrapped type `any[][]`. * @see _.unzip **/ @@ -5530,7 +5530,7 @@ interface _Chain { **/ keys(): _Chain; - /** + /** * Wrapped type `object`. * @see _.allKeys **/ @@ -5623,7 +5623,7 @@ interface _Chain { **/ property(): _Chain; - /** + /** * Wrapped type `object`. * @see _.propertyOf **/ @@ -5677,7 +5677,7 @@ interface _Chain { **/ isFunction(): _Chain; - /** + /** * Wrapped type `object`. * @see _.isError **/ diff --git a/webrtc/RTCPeerConnection-tests.ts b/webrtc/RTCPeerConnection-tests.ts index ea850f8724..9cd8087947 100644 --- a/webrtc/RTCPeerConnection-tests.ts +++ b/webrtc/RTCPeerConnection-tests.ts @@ -3,8 +3,28 @@ let voidpromise: Promise; -var config: RTCConfiguration = - { iceServers: [{ urls: "stun.l.google.com:19302" }] }; +var minimalConfig: RTCConfiguration = {}; +var config: RTCConfiguration = { + iceServers: [ + { + // Single url + urls: "stun.l.google.com:19302" + }, + { + // List of urls and credentials + urls: ["another-stun.example.com"], + username: "dude", + credential: "pass", + credentialType: "token" + }, + ], + iceTransportPolicy: "relay", + bundlePolicy: "max-compat", + rtcpMuxPolicy: "negotiate", + peerIdentity: "dude", + certificates: [{expires: 1337}], + iceCandidatePoolSize: 5 +}; var constraints: RTCMediaConstraints = { mandatory: { offerToReceiveAudio: true, offerToReceiveVideo: true } }; diff --git a/webrtc/RTCPeerConnection.d.ts b/webrtc/RTCPeerConnection.d.ts index dcd36d9aec..66b92c2416 100644 --- a/webrtc/RTCPeerConnection.d.ts +++ b/webrtc/RTCPeerConnection.d.ts @@ -3,13 +3,7 @@ // Definitions by: Ken Smith // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // -// Definitions taken from http://dev.w3.org/2011/webrtc/editor/webrtc.html -// -// For example code see: -// https://code.google.com/p/webrtc/source/browse/stable/samples/js/apprtc/js/main.js -// -// For a generic implementation see that deals with browser differences, see: -// https://code.google.com/p/webrtc/source/browse/stable/samples/js/base/adapter.js +// W3 Spec: https://www.w3.org/TR/webrtc/#idl-def-RTCIceServer /// @@ -20,17 +14,46 @@ // TODO(2): get Typescript to have union types as WebRtc uses them. // https://typescript.codeplex.com/workitem/1364 -interface RTCConfiguration { - iceServers: RTCIceServer[]; +// https://www.w3.org/TR/webrtc/#idl-def-RTCIceTransportPolicy +type RTCIceTransportPolicy = 'public' | 'relay' | 'all'; + +// https://www.w3.org/TR/webrtc/#idl-def-RTCBundlePolicy +type RTCBundlePolicy = 'balanced' | 'max-compat' | 'max-bundle'; + +// https://www.w3.org/TR/webrtc/#idl-def-RTCRtcpMuxPolicy +type RTCRtcpMuxPolicy = 'negotiate' | 'require'; + +// https://www.w3.org/TR/webrtc/#idl-def-RTCCertificate +interface RTCCertificate { + expires: number; } + +// https://www.w3.org/TR/webrtc/#idl-def-RTCConfiguration +// https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/RTCPeerConnection#RTCConfiguration_dictionary +interface RTCConfiguration { + iceServers ?: RTCIceServer[]; // optional according to mozilla docs + iceTransportPolicy ?: RTCIceTransportPolicy; // default = 'all' + bundlePolicy ?: RTCBundlePolicy; // default = 'balanced' + rtcpMuxPolicy ?: RTCRtcpMuxPolicy; // default = 'require' + peerIdentity ?: string; // default = null + certificates ?: RTCCertificate[]; // default is auto-generated + iceCandidatePoolSize ?: number; // default = 0 +} + declare var RTCConfiguration: { prototype: RTCConfiguration; new (): RTCConfiguration; }; +// https://www.w3.org/TR/webrtc/#idl-def-RTCIceCredentialType +type RTCIceCredentialType = 'password' | 'token'; + +// https://www.w3.org/TR/webrtc/#idl-def-RTCIceServer interface RTCIceServer { - urls: string; + urls: string | string[]; + username?: string; credential?: string; + credentialType?: RTCIceCredentialType; // default = 'password' } declare var RTCIceServer: { prototype: RTCIceServer; @@ -42,7 +65,7 @@ interface mozRTCPeerConnection extends RTCPeerConnection { } declare var mozRTCPeerConnection: { prototype: mozRTCPeerConnection; - new (settings: RTCPeerConnectionConfig, + new (settings?: RTCConfiguration, constraints?:RTCMediaConstraints): mozRTCPeerConnection; }; // webkit (Chrome) specific prefixes. @@ -50,7 +73,7 @@ interface webkitRTCPeerConnection extends RTCPeerConnection { } declare var webkitRTCPeerConnection: { prototype: webkitRTCPeerConnection; - new (settings: RTCPeerConnectionConfig, + new (settings?: RTCConfiguration, constraints?:RTCMediaConstraints): webkitRTCPeerConnection; }; diff --git a/winrt/winrt.d.ts b/winrt/winrt.d.ts index 841007f601..bc4e41cd24 100644 --- a/winrt/winrt.d.ts +++ b/winrt/winrt.d.ts @@ -8201,6 +8201,7 @@ declare namespace Windows { getDataPlanStatus(): Windows.Networking.Connectivity.DataPlanStatus; getLocalUsage(StartTime: Date, EndTime: Date): Windows.Networking.Connectivity.DataUsage; getLocalUsage(StartTime: Date, EndTime: Date, States: Windows.Networking.Connectivity.RoamingStates): Windows.Networking.Connectivity.DataUsage; + getSignalBars(): Windows.Foundation.IReference; } export class ConnectionCost implements Windows.Networking.Connectivity.IConnectionCost { approachingDataLimit: boolean; @@ -8267,6 +8268,7 @@ declare namespace Windows { getDataPlanStatus(): Windows.Networking.Connectivity.DataPlanStatus; getLocalUsage(StartTime: Date, EndTime: Date): Windows.Networking.Connectivity.DataUsage; getLocalUsage(StartTime: Date, EndTime: Date, States: Windows.Networking.Connectivity.RoamingStates): Windows.Networking.Connectivity.DataUsage; + getSignalBars(): Windows.Foundation.IReference; } export class LanIdentifier implements Windows.Networking.Connectivity.ILanIdentifier { infrastructureId: Windows.Networking.Connectivity.LanIdentifierData; @@ -11344,15 +11346,18 @@ declare namespace Windows { } export interface ILauncherOptions { contentType: string; + desiredRemainingView: Windows.UI.ViewManagement.ViewSizePreference; displayApplicationPicker: boolean; fallbackUri: Windows.Foundation.Uri; preferredApplicationDisplayName: string; preferredApplicationPackageFamilyName: string; treatAsUntrusted: boolean; uI: Windows.System.LauncherUIOptions; + } export class LauncherOptions implements Windows.System.ILauncherOptions { contentType: string; + desiredRemainingView: Windows.UI.ViewManagement.ViewSizePreference; displayApplicationPicker: boolean; fallbackUri: Windows.Foundation.Uri; preferredApplicationDisplayName: string; @@ -11594,87 +11599,96 @@ declare namespace Windows { } declare namespace Windows { export module UI { - export module ViewManagement { - export enum ApplicationViewState { - fullScreenLandscape, - filled, - snapped, - fullScreenPortrait, - } + export module ViewManagement { + export enum ViewSizePreference { + default = 0, + useLess = 1, + useHalf = 2, + useMore = 3, + useMinimum = 4, + useNone = 5 + } + + export enum ApplicationViewState { + fullScreenLandscape, + filled, + snapped, + fullScreenPortrait, + } + + /** + * Defines an instance of a window (app view) and the information that describes it. + **/ + export class ApplicationView { + /** + * Gets the window (app view) for the current app. + **/ + static getForCurrentView(): ApplicationView; /** - * Defines an instance of a window (app view) and the information that describes it. + * Attempts to unsnap a previously snapped app. This call will only succeed when the app is running in the foreground. **/ - export class ApplicationView { - /** - * Gets the window (app view) for the current app. - **/ - static getForCurrentView(): ApplicationView; - - /** - * Attempts to unsnap a previously snapped app. This call will only succeed when the app is running in the foreground. - **/ - static tryUnsnap(): boolean; - - /** - * Gets the state of the current app view. - **/ - static value: Windows.UI.ViewManagement.ApplicationViewState; - - /** - * Indicates whether the app terminates when the last window is closed. - **/ - static terminateAppOnFinalViewClose: boolean; - - /** - * Gets the current orientation of the window (app view) with respect to the display. - **/ - orientation: ApplicationViewOrientation; - - /** - * Gets or sets the displayed title of the window. - **/ - title: string; - - /** - * Gets or sets whether screen capture is enabled for the window (app view). - **/ - isScreenCaptureEnabled: boolean; - - /** - * Gets whether the window (app view) is on the Windows lock screen. - **/ - isOnLockScreen: boolean; - - /** - * Gets whether the window(app view) is full screen or not. - **/ - isFullScreen: boolean; - - /** - * Gets the current ID of the window (app view) . - **/ - id: number; - - /** - * Gets whether the current window (app view) is adjacent to the right edge of the screen. - **/ - adjacentToRightDisplayEdge: boolean; - - /** - * Gets whether the current window (app view) is adjacent to the left edge of the screen. - **/ - adjacentToLeftDisplayEdge: number; - - /** - * Gets the title bar of the app. - **/ - titleBar: ApplicationViewTitleBar; - } + static tryUnsnap(): boolean; /** - * Defines the set of display orientation modes for a window (app view). + * Gets the state of the current app view. **/ + static value: Windows.UI.ViewManagement.ApplicationViewState; + + /** + * Indicates whether the app terminates when the last window is closed. + **/ + static terminateAppOnFinalViewClose: boolean; + + /** + * Gets the current orientation of the window (app view) with respect to the display. + **/ + orientation: ApplicationViewOrientation; + + /** + * Gets or sets the displayed title of the window. + **/ + title: string; + + /** + * Gets or sets whether screen capture is enabled for the window (app view). + **/ + isScreenCaptureEnabled: boolean; + + /** + * Gets whether the window (app view) is on the Windows lock screen. + **/ + isOnLockScreen: boolean; + + /** + * Gets whether the window(app view) is full screen or not. + **/ + isFullScreen: boolean; + + /** + * Gets the current ID of the window (app view) . + **/ + id: number; + + /** + * Gets whether the current window (app view) is adjacent to the right edge of the screen. + **/ + adjacentToRightDisplayEdge: boolean; + + /** + * Gets whether the current window (app view) is adjacent to the left edge of the screen. + **/ + adjacentToLeftDisplayEdge: number; + + /** + * Gets the title bar of the app. + **/ + titleBar: ApplicationViewTitleBar; + } + + /** + * Defines the set of display orientation modes for a window (app view). + **/ export enum ApplicationViewOrientation { landscape, portrait diff --git a/ws/ws.d.ts b/ws/ws.d.ts index 83ba9dec92..d9a1338d21 100644 --- a/ws/ws.d.ts +++ b/ws/ws.d.ts @@ -110,7 +110,7 @@ declare module "ws" { constructor(options?: IServerOptions, callback?: Function); - close(): void; + close(cb?: () => {}): void; handleUpgrade(request: http.ServerRequest, socket: net.Socket, upgradeHead: Buffer, callback: (client: WebSocket) => void): void; diff --git a/wu/wu.d.ts b/wu/wu.d.ts index fa7aa9db2c..90f6475ee8 100644 --- a/wu/wu.d.ts +++ b/wu/wu.d.ts @@ -50,7 +50,7 @@ declare namespace Wu { slice(iter: Iterable): WuIterable; slice(start: number, iter: Iterable): WuIterable; slice(start: number, stop: number, iter: Iterable): WuIterable; - some(fn: Filter, iter: Iterable): WuIterable; + some(fn: Filter, iter: Iterable): boolean; spreadMap(fn: (...x: any[]) => T, iter: Iterable): WuIterable; take(n: number, iter: Iterable): WuIterable; takeWhile(fn: Filter, iter: Iterable): WuIterable; @@ -100,7 +100,7 @@ declare namespace Wu { slice(): WuIterable; slice(start: number): WuIterable; slice(start: number, stop: number): WuIterable; - some(fn: Filter): WuIterable; + some(fn: Filter): boolean; spreadMap(fn: (...x: any[]) => T, iter: Iterable): WuIterable; take(n: number): WuIterable; takeWhile(fn: Filter): WuIterable; diff --git a/z-schema/z-schema.d.ts b/z-schema/z-schema.d.ts index 317a92247c..4f189f95b3 100644 --- a/z-schema/z-schema.d.ts +++ b/z-schema/z-schema.d.ts @@ -37,9 +37,33 @@ declare namespace ZSchema { } export class Validator { - public static registerFormat(name: string, validator: (value: any) => boolean): void; + + /** + * Register a custom format. + * + * @param name - name of the custom format + * @param validatorFunction - custom format validator function. + * Returns `true` if `value` matches the custom format. + */ + public static registerFormat(formatName: string, validatorFunction: (value: any) => boolean): void; + + /** + * Unregister a format. + * + * @param name - name of the custom format + */ public static unregisterFormat(name: string): void; + + /** + * Get the list of all registered formats. + * + * Both the names of the burned-in formats and the custom format names are + * returned by this function. + * + * @returns {string[]} the list of all registered format names. + */ public static getRegisteredFormats(): string[]; + public static getDefaultOptions(): Options; constructor(options: Options);