diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..5993e03 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,13 @@ +# Auto detect text files and perform EOL normalization +* text=auto + +# Custom +*.ts text +*.jade text +*.md text +*.js text +*.cmd text eol=crlf +*.sln text eol=crlf +*.csproj text eol=crlf +*.jsproj text eol=crlf +*.njsproj text eol=crlf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..159ac76 --- /dev/null +++ b/.gitignore @@ -0,0 +1,192 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.sln.docstates + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +x64/ +build/ +bld/ +[Bb]in/ +[Oo]bj/ + +# Roslyn cache directories +*.ide/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +#NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opensdf +*.sdf +*.cachefile + +# Visual Studio profiler +*.psess +*.vsp +*.vspx + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding addin-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +## TODO: Comment the next line if you want to checkin your +## web deploy settings but do note that will include unencrypted +## passwords +#*.pubxml + +# NuGet Packages Directory +packages/* +## TODO: If the tool you use requires repositories.config +## uncomment the next line +#!packages/repositories.config + +# Enable "build/" folder in the NuGet Packages folder since +# NuGet packages use it for MSBuild targets. +# This line needs to be after the ignore of the build folder +# (and the packages folder if the line above has been uncommented) +!packages/build/ + +# Windows Azure Build Output +csx/ +*.build.csdef + +# Windows Store app package directory +AppPackages/ + +# Others +sql/ +*.Cache +ClientBin/ +[Ss]tyle[Cc]op.* +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# LightSwitch generated files +GeneratedArtifacts/ +_Pvt_Extensions/ +ModelManifest.xml + +node_modules/ \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 91816d7..0305bd6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,9 +1,40 @@ -## Contributing -TypeScript is currently accepting contributions in the form of bug fixes. A bug must have an issue tracking it in the issue tracker that has been approved ("Milestone == Community") by the TypeScript team. Your pull request should include a link to the bug that you are fixing. If you’ve submitted a PR for a bug, please post a comment in the bug to avoid duplication of effort. - -New samples will not be accepted at this time. - -## Legal -You will need to complete a Contributor License Agreement (CLA). Briefly, this agreement testifies that you are granting us permission to use the submitted change according to the terms of the project’s license, and that the work being submitted is under appropriate copyright. - -Please submit a Contributor License Agreement (CLA) before submitting a pull request. Download the agreement ([Microsoft Contribution License Agreement.docx](https://www.codeplex.com/Download?ProjectName=typescript&DownloadId=822190)), sign, scan, and email it back to . Be sure to include your github user name along with the agreement. Once we have received the signed CLA, we’ll review the request. Please note that we’re currently only accepting pull requests of bug fixes rather than new features. \ No newline at end of file +## Contributing + +## Contributing fixes to existing samples + +A bug must have an issue tracking it in the issue tracker that has been approved (labeled "help wanted") by the TypeScript team. +Your pull request should include a link to the bug that you are fixing. +If you've submitted a PR for a bug, please post a comment in the bug to avoid duplication of effort. + +## Contributing new samples + +New samples may be accepted, but will need to first be approved (labeled "help wanted" by a TypeScript coordinator) in the suggestion issue. + +For new samples, please provide a detailed explanation of the intended sample, list of technologies or tools used, and an explanation of why existing samples are not sufficient and a new sample is needed. + +A sample is meant to showcase a specific technology or toolchain integration with TypeScript; it is not meant to be a template that users would use to get a project going. +A sample should only include tools/technologies that serve the main technology it covers; for instance, a sample for a UI framework should not include a test framework integration. + +A sample should be well documented. +Please include comments in code as well as content in the a `README.md` explaining why steps are being taken. +Comments should also be included in build files if applicable. +A good sample `README.md` should read like a walkthrough, guiding the reader through different steps of setting up and building the sample. +See [TypeScript quick start samples](https://github.com/Microsoft/TypeScript-Handbook/tree/master/pages/quick-start) for guidance. + +A sample should be self-contained. +[npm](https://www.npmjs.com/) is the recommended way of acquiring dependencies. +[typings](https://github.com/typings/typings) is the recommended way of acquiring definition files. + +A sample should be IDE/editor-friendly. Please include a `tsconfig.json` file at the root. + +A sample should have no OS dependency. + +## Legal + +You will need to complete a Contributor License Agreement (CLA). +Briefly, this agreement testifies that you are granting us permission to use the submitted change according to the terms of the project's license, and that the work being submitted is under appropriate copyright. + +Please submit a Contributor License Agreement (CLA) before submitting a pull request. +You may visit https://cla.microsoft.com to sign digitally. +Alternatively, download the agreement ([Microsoft Contribution License Agreement.docx](https://www.codeplex.com/Download?ProjectName=typescript&DownloadId=822190) or [Microsoft Contribution License Agreement.pdf](https://www.codeplex.com/Download?ProjectName=typescript&DownloadId=921298)), sign, scan, and email it back to . +Be sure to include your GitHub user name along with the agreement. Once we have received the signed CLA, we'll review the request. diff --git a/README.md b/README.md index a907426..26d30d5 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,53 @@ -# TypeScript Samples - -Samples for TypeScript \ No newline at end of file +# TypeScript Samples + +Most of the samples here will assume that you have TypeScript installed. +You can get TypeScript with Visual Studio, NuGet, or with npm: + +```shell +npm install -g typescript +``` + +To compile each sample, `cd` into the directory and use the `tsc` command to compile. +`tsc` will use each directory's `tsconfig.json` to get specific compiler options. + +##### [AMD Modules](amd/README.md) + +##### [Angular Seed TypeScript](angular1/README.md) + +##### [Angular 2 TypeScript](angular2/README.md) + +##### [Async Functions](async/README.md) + +##### [Browserify](browserify/README.md) + +##### [D3](d3/README.md) + +##### [React + Flux + Babel + Karma: The Secret Recipe](react-flux-babel-karma/README.md) + +##### [Greeter](greeter/README.md) + +##### [Image Board](imageboard/README.md) + +##### [interfaces](interfaces/README.md) + +##### [JQuery Parallax Starfield](jquery/README.md) + +##### [JSPM](jspm/README.md) + +##### [jsx-demo](jsx/README.md) + +##### [Mankala](mankala/README.md) + +##### [Node.js](node/README.md) + +##### [Raytracer](raytracer/README.md) + +##### [Simple](simple/README.md) + +##### [SystemJS](systemjs/README.md) + +##### [Todo MVC](todomvc/README.md) + +##### [umd](umd/README.md) + +##### [Warship Combat](warship/README.md) diff --git a/amd/README.md b/amd/README.md index 4478f25..5170210 100644 --- a/amd/README.md +++ b/amd/README.md @@ -1,11 +1,14 @@ -# TypeScript Sample: AMD Module +# TypeScript Sample: AMD Modules ## Overview + This sample shows a simple Typescript application using an AMD module. +It uses [require.js](http://www.requirejs.org/) to load `app.js` once compiled from `app.ts` ## Running + ``` tsc --sourcemap --module amd app.ts -start default.htm +start default.html ``` diff --git a/amd/app.ts b/amd/app.ts index f6198ef..384d80f 100644 --- a/amd/app.ts +++ b/amd/app.ts @@ -1,5 +1,5 @@ -import model = require("greeter") - -var el = document.getElementById('content'); -var greeter = new model.Greeter(el); -greeter.start(); +import model = require("greeter") + +var el = document.getElementById('content'); +var greeter = new model.Greeter(el); +greeter.start(); diff --git a/amd/default.htm b/amd/default.html similarity index 72% rename from amd/default.htm rename to amd/default.html index 6742d5b..0cb9baf 100644 --- a/amd/default.htm +++ b/amd/default.html @@ -5,7 +5,13 @@ TypeScript HTML App + + +

TypeScript HTML App

diff --git a/amd/greeter.ts b/amd/greeter.ts index f36287a..02fba4e 100644 --- a/amd/greeter.ts +++ b/amd/greeter.ts @@ -1,25 +1,21 @@ -export class Greeter -{ - element: HTMLElement; - span: HTMLElement; - timerToken: number; - - constructor (element: HTMLElement) - { - this.element = element; - this.element.innerText += "The time is: "; - this.span = document.createElement('span'); - this.element.appendChild(this.span); - this.span.innerText = new Date().toUTCString(); - } - - start() - { - this.timerToken = setInterval(() => this.span.innerText = new Date().toUTCString(), 500); - } - - stop() - { - clearTimeout(this.timerToken); - } -} +export class Greeter { + element: HTMLElement; + span: HTMLElement; + timerToken: number; + + constructor (element: HTMLElement) { + this.element = element; + this.element.innerHTML += "The time is: "; + this.span = document.createElement('span'); + this.element.appendChild(this.span); + this.span.innerHTML = new Date().toUTCString(); + } + + start() { + this.timerToken = setInterval(() => this.span.innerHTML = new Date().toUTCString(), 500); + } + + stop() { + clearInterval(this.timerToken); + } +} diff --git a/amd/tsconfig.json b/amd/tsconfig.json new file mode 100644 index 0000000..08df685 --- /dev/null +++ b/amd/tsconfig.json @@ -0,0 +1,9 @@ +{ + "compilerOptions": { + "module": "amd", + "sourceMap": true + }, + "files": [ + "app.ts" + ] +} \ No newline at end of file diff --git a/angular1/.bowerrc b/angular1/.bowerrc new file mode 100644 index 0000000..8c58c8e --- /dev/null +++ b/angular1/.bowerrc @@ -0,0 +1,3 @@ +{ + "directory": "app/bower_components" +} \ No newline at end of file diff --git a/angular1/.gitignore b/angular1/.gitignore new file mode 100644 index 0000000..d4b61c3 --- /dev/null +++ b/angular1/.gitignore @@ -0,0 +1,9 @@ +logs/* +!.gitkeep +node_modules/ +bower_components/ +tmp +.DS_Store +.idea +app/**/*.js +e2e-tests/**/*.js \ No newline at end of file diff --git a/angular1/.jshintrc b/angular1/.jshintrc new file mode 100644 index 0000000..6f00218 --- /dev/null +++ b/angular1/.jshintrc @@ -0,0 +1,13 @@ +{ + "globalstrict": true, + "globals": { + "angular": false, + "describe": false, + "it": false, + "expect": false, + "beforeEach": false, + "afterEach": false, + "module": false, + "inject": false + } +} \ No newline at end of file diff --git a/angular1/.travis.yml b/angular1/.travis.yml new file mode 100644 index 0000000..cce5c68 --- /dev/null +++ b/angular1/.travis.yml @@ -0,0 +1,14 @@ +language: node_js +node_js: + - "0.10" + +before_script: + - export DISPLAY=:99.0 + - sh -e /etc/init.d/xvfb start + - npm start > /dev/null & + - npm run update-webdriver + - sleep 1 # give server time to start + +script: + - node_modules/.bin/karma start karma.conf.js --no-auto-watch --single-run --reporters=dots --browsers=Firefox + - node_modules/.bin/protractor e2e-tests/protractor.conf.js --browser=firefox diff --git a/angular1/CONVERSION.md b/angular1/CONVERSION.md new file mode 100644 index 0000000..1af6199 --- /dev/null +++ b/angular1/CONVERSION.md @@ -0,0 +1,11 @@ +The following is the list of modifications made to change the JS project to a TS Project: +* Moved original README.md to README-JS.md and added this README.md and CONVERSION.md +* Installed TypeScript typings for angular and related libs `tsd install angular jquery jasmine karma-jasmine angular-mocks angular-protractor selenium-webdriver --save` +* Added 2 `tsconfig.json` files, one for `app` and another for `e2e-tests`. Two files are needed because of different typings for each. +* Renamed the `.js` files to `.ts`. +* As a sample : Converted controller `View1` and `View2` *functions* to *classes* and added a type annotation to use these from tests in a type checked way. +* Minor modifications of typings needed because of conflict in `jquery` vs. `protractor` : https://github.com/borisyankov/DefinitelyTyped/issues/2734. + * Remove `$` from `jquery.d.ts` in `e2e-tests`. + * Remove `protractor` def from `app`. + +You will notice that stuff like `angular`, `mocks` etc will light up with IntelliSense and you will get errors if you try to misuse these. diff --git a/angular1/LICENSE b/angular1/LICENSE new file mode 100644 index 0000000..9ced331 --- /dev/null +++ b/angular1/LICENSE @@ -0,0 +1,22 @@ +The MIT License + +Copyright (c) 2010-2014 Google, Inc. http://angularjs.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/angular1/README-JS.md b/angular1/README-JS.md new file mode 100644 index 0000000..e7aece1 --- /dev/null +++ b/angular1/README-JS.md @@ -0,0 +1,297 @@ +# angular-seed — the seed for AngularJS apps + +This project is an application skeleton for a typical [AngularJS](http://angularjs.org/) web app. +You can use it to quickly bootstrap your angular webapp projects and dev environment for these +projects. + +The seed contains a sample AngularJS application and is preconfigured to install the Angular +framework and a bunch of development and testing tools for instant web development gratification. + +The seed app doesn't do much, just shows how to wire two controllers and views together. + + +## Getting Started + +To get you started you can simply clone the angular-seed repository and install the dependencies: + +### Prerequisites + +You need git to clone the angular-seed repository. You can get git from +[http://git-scm.com/](http://git-scm.com/). + +We also use a number of node.js tools to initialize and test angular-seed. You must have node.js and +its package manager (npm) installed. You can get them from [http://nodejs.org/](http://nodejs.org/). + +### Clone angular-seed + +Clone the angular-seed repository using [git][git]: + +``` +git clone https://github.com/angular/angular-seed.git +cd angular-seed +``` + +If you just want to start a new project without the angular-seed commit history then you can do: + +```bash +git clone --depth=1 https://github.com/angular/angular-seed.git +``` + +The `depth=1` tells git to only pull down one commit worth of historical data. + +### Install Dependencies + +We have two kinds of dependencies in this project: tools and angular framework code. The tools help +us manage and test the application. + +* We get the tools we depend upon via `npm`, the [node package manager][npm]. +* We get the angular code via `bower`, a [client-side code package manager][bower]. + +We have preconfigured `npm` to automatically run `bower` so we can simply do: + +``` +npm install +``` + +Behind the scenes this will also call `bower install`. You should find that you have two new +folders in your project. + +* `node_modules` - contains the npm packages for the tools we need +* `app/bower_components` - contains the angular framework files + +*Note that the `bower_components` folder would normally be installed in the root folder but +angular-seed changes this location through the `.bowerrc` file. Putting it in the app folder makes +it easier to serve the files by a webserver.* + +### Run the Application + +We have preconfigured the project with a simple development web server. The simplest way to start +this server is: + +``` +npm start +``` + +Now browse to the app at `http://localhost:8000/app/index.html`. + + + +## Directory Layout + +``` +app/ --> all of the source files for the application + app.css --> default stylesheet + components/ --> all app specific modules + version/ --> version related components + version.js --> version module declaration and basic "version" value service + version_test.js --> "version" value service tests + version-directive.js --> custom directive that returns the current app version + version-directive_test.js --> version directive tests + interpolate-filter.js --> custom interpolation filter + interpolate-filter_test.js --> interpolate filter tests + view1/ --> the view1 view template and logic + view1.html --> the partial template + view1.js --> the controller logic + view1_test.js --> tests of the controller + view2/ --> the view2 view template and logic + view2.html --> the partial template + view2.js --> the controller logic + view2_test.js --> tests of the controller + app.js --> main application module + index.html --> app layout file (the main html template file of the app) + index-async.html --> just like index.html, but loads js files asynchronously +karma.conf.js --> config file for running unit tests with Karma +e2e-tests/ --> end-to-end tests + protractor-conf.js --> Protractor config file + scenarios.js --> end-to-end scenarios to be run by Protractor +``` + +## Testing + +There are two kinds of tests in the angular-seed application: Unit tests and End to End tests. + +### Running Unit Tests + +The angular-seed app comes preconfigured with unit tests. These are written in +[Jasmine][jasmine], which we run with the [Karma Test Runner][karma]. We provide a Karma +configuration file to run them. + +* the configuration is found at `karma.conf.js` +* the unit tests are found next to the code they are testing and are named as `..._test.js`. + +The easiest way to run the unit tests is to use the supplied npm script: + +``` +npm test +``` + +This script will start the Karma test runner to execute the unit tests. Moreover, Karma will sit and +watch the source and test files for changes and then re-run the tests whenever any of them change. +This is the recommended strategy; if your unit tests are being run every time you save a file then +you receive instant feedback on any changes that break the expected code functionality. + +You can also ask Karma to do a single run of the tests and then exit. This is useful if you want to +check that a particular version of the code is operating as expected. The project contains a +predefined script to do this: + +``` +npm run test-single-run +``` + + +### End to end testing + +The angular-seed app comes with end-to-end tests, again written in [Jasmine][jasmine]. These tests +are run with the [Protractor][protractor] End-to-End test runner. It uses native events and has +special features for Angular applications. + +* the configuration is found at `e2e-tests/protractor-conf.js` +* the end-to-end tests are found in `e2e-tests/scenarios.js` + +Protractor simulates interaction with our web app and verifies that the application responds +correctly. Therefore, our web server needs to be serving up the application, so that Protractor +can interact with it. + +``` +npm start +``` + +In addition, since Protractor is built upon WebDriver we need to install this. The angular-seed +project comes with a predefined script to do this: + +``` +npm run update-webdriver +``` + +This will download and install the latest version of the stand-alone WebDriver tool. + +Once you have ensured that the development web server hosting our application is up and running +and WebDriver is updated, you can run the end-to-end tests using the supplied npm script: + +``` +npm run protractor +``` + +This script will execute the end-to-end tests against the application being hosted on the +development server. + + +## Updating Angular + +Previously we recommended that you merge in changes to angular-seed into your own fork of the project. +Now that the angular framework library code and tools are acquired through package managers (npm and +bower) you can use these tools instead to update the dependencies. + +You can update the tool dependencies by running: + +``` +npm update +``` + +This will find the latest versions that match the version ranges specified in the `package.json` file. + +You can update the Angular dependencies by running: + +``` +bower update +``` + +This will find the latest versions that match the version ranges specified in the `bower.json` file. + + +## Loading Angular Asynchronously + +The angular-seed project supports loading the framework and application scripts asynchronously. The +special `index-async.html` is designed to support this style of loading. For it to work you must +inject a piece of Angular JavaScript into the HTML page. The project has a predefined script to help +do this. + +``` +npm run update-index-async +``` + +This will copy the contents of the `angular-loader.js` library file into the `index-async.html` page. +You can run this every time you update the version of Angular that you are using. + + +## Serving the Application Files + +While angular is client-side-only technology and it's possible to create angular webapps that +don't require a backend server at all, we recommend serving the project files using a local +webserver during development to avoid issues with security restrictions (sandbox) in browsers. The +sandbox implementation varies between browsers, but quite often prevents things like cookies, xhr, +etc to function properly when an html page is opened via `file://` scheme instead of `http://`. + + +### Running the App during Development + +The angular-seed project comes preconfigured with a local development webserver. It is a node.js +tool called [http-server][http-server]. You can start this webserver with `npm start` but you may choose to +install the tool globally: + +``` +sudo npm install -g http-server +``` + +Then you can start your own development web server to serve static files from a folder by +running: + +``` +http-server -a localhost -p 8000 +``` + +Alternatively, you can choose to configure your own webserver, such as apache or nginx. Just +configure your server to serve the files under the `app/` directory. + + +### Running the App in Production + +This really depends on how complex your app is and the overall infrastructure of your system, but +the general rule is that all you need in production are all the files under the `app/` directory. +Everything else should be omitted. + +Angular apps are really just a bunch of static html, css and js files that just need to be hosted +somewhere they can be accessed by browsers. + +If your Angular app is talking to the backend server via xhr or other means, you need to figure +out what is the best way to host the static files to comply with the same origin policy if +applicable. Usually this is done by hosting the files by the backend server or through +reverse-proxying the backend server(s) and webserver(s). + + +## Continuous Integration + +### Travis CI + +[Travis CI][travis] is a continuous integration service, which can monitor GitHub for new commits +to your repository and execute scripts such as building the app or running tests. The angular-seed +project contains a Travis configuration file, `.travis.yml`, which will cause Travis to run your +tests when you push to GitHub. + +You will need to enable the integration between Travis and GitHub. See the Travis website for more +instruction on how to do this. + +### CloudBees + +CloudBees have provided a CI/deployment setup: + + + + +If you run this, you will get a cloned version of this repo to start working on in a private git repo, +along with a CI service (in Jenkins) hosted that will run unit and end to end tests in both Firefox and Chrome. + + +## Contact + +For more information on AngularJS please check out http://angularjs.org/ + +[git]: http://git-scm.com/ +[bower]: http://bower.io +[npm]: https://www.npmjs.org/ +[node]: http://nodejs.org +[protractor]: https://github.com/angular/protractor +[jasmine]: http://jasmine.github.io +[karma]: http://karma-runner.github.io +[travis]: https://travis-ci.org/ +[http-server]: https://github.com/nodeapps/http-server diff --git a/angular1/README.md b/angular1/README.md new file mode 100644 index 0000000..e658379 --- /dev/null +++ b/angular1/README.md @@ -0,0 +1,28 @@ +# Angular Seed TypeScript +This is based on https://github.com/angular/angular-seed. If you are curious about how the conversion of the JS project was done to the TS project checkout [CONVERSION.md](./CONVERSION.md). + +## Running +The following are specific to TypeScript + +Setup TypeScript: +```bash +npm install typescript -g +npm install tsd -g +``` +Start the TypeScript compiler in watch mode (either in the `app` folder or in the `e2e-tests` folder) and **leave it running**: + +```bash +# For app +tsc --watch --p app +# For e2e-tests +tsc --watch --p e2e-tests +``` + +That's it. You have typescript setup and ready to go. Now you can follow the standard steps of the original Angular-Seed JavaScript project in a new window using [README-JS](./README-JS.md) starting at the [install dependencies](./README-JS.md#install-dependencies) section. + +**TIP**: *Abriged the remaining JS steps for a quick start:* +```bash +npm install +npm start +``` +and visit : http://localhost:8000/app/ diff --git a/angular1/app/app.css b/angular1/app/app.css new file mode 100644 index 0000000..c925240 --- /dev/null +++ b/angular1/app/app.css @@ -0,0 +1,30 @@ +/* app css stylesheet */ + +.menu { + list-style: none; + border-bottom: 0.1em solid black; + margin-bottom: 2em; + padding: 0 0 0.5em; +} + +.menu:before { + content: "["; +} + +.menu:after { + content: "]"; +} + +.menu > li { + display: inline; +} + +.menu > li:before { + content: "|"; + padding-right: 0.3em; +} + +.menu > li:nth-child(1):before { + content: ""; + padding: 0; +} diff --git a/angular1/app/app.ts b/angular1/app/app.ts new file mode 100644 index 0000000..68fd66c --- /dev/null +++ b/angular1/app/app.ts @@ -0,0 +1,12 @@ +'use strict'; + +// Declare app level module which depends on views, and components +angular.module('myApp', [ + 'ngRoute', + 'myApp.view1', + 'myApp.view2', + 'myApp.version' +]) + .config(['$routeProvider', $routeProvider => { + $routeProvider.otherwise({ redirectTo: '/view1' }); + }]); diff --git a/angular1/app/components/version/interpolate-filter.ts b/angular1/app/components/version/interpolate-filter.ts new file mode 100644 index 0000000..91a4198 --- /dev/null +++ b/angular1/app/components/version/interpolate-filter.ts @@ -0,0 +1,6 @@ +'use strict'; + +angular.module('myApp.version.interpolate-filter', []) + .filter('interpolate', ['version', version => { + return text => String(text).replace(/\%VERSION\%/mg, version); + }]); diff --git a/angular1/app/components/version/interpolate-filter_test.ts b/angular1/app/components/version/interpolate-filter_test.ts new file mode 100644 index 0000000..c4b060f --- /dev/null +++ b/angular1/app/components/version/interpolate-filter_test.ts @@ -0,0 +1,15 @@ +'use strict'; + +describe('myApp.version module', () => { + beforeEach(module('myApp.version')); + + describe('interpolate filter', () => { + beforeEach(module($provide => { + $provide.value('version', 'TEST_VER'); + })); + + it('should replace VERSION', inject(interpolateFilter => { + expect(interpolateFilter('before %VERSION% after')).toEqual('before TEST_VER after'); + })); + }); +}); diff --git a/angular1/app/components/version/version-directive.ts b/angular1/app/components/version/version-directive.ts new file mode 100644 index 0000000..deb07d0 --- /dev/null +++ b/angular1/app/components/version/version-directive.ts @@ -0,0 +1,8 @@ +'use strict'; + +angular.module('myApp.version.version-directive', []) + .directive('appVersion', ['version', version => { + return (scope, element, attributes) => { + element.text(version); + }; + }]); diff --git a/angular1/app/components/version/version-directive_test.ts b/angular1/app/components/version/version-directive_test.ts new file mode 100644 index 0000000..2510e13 --- /dev/null +++ b/angular1/app/components/version/version-directive_test.ts @@ -0,0 +1,18 @@ +'use strict'; + +describe('myApp.version module', () => { + beforeEach(module('myApp.version')); + + describe('app-version directive', () => { + it('should print current version', () => { + module($provide => { + $provide.value('version', 'TEST_VER'); + }); + + inject(($compile, $rootScope) => { + let element = $compile('')($rootScope); + expect(element.text()).toEqual('TEST_VER'); + }); + }); + }); +}); diff --git a/angular1/app/components/version/version.ts b/angular1/app/components/version/version.ts new file mode 100644 index 0000000..0139bdb --- /dev/null +++ b/angular1/app/components/version/version.ts @@ -0,0 +1,7 @@ +'use strict'; + +angular.module('myApp.version', [ + 'myApp.version.interpolate-filter', + 'myApp.version.version-directive' +]) +.value('version', '0.1'); diff --git a/angular1/app/components/version/version_test.ts b/angular1/app/components/version/version_test.ts new file mode 100644 index 0000000..b911ef2 --- /dev/null +++ b/angular1/app/components/version/version_test.ts @@ -0,0 +1,11 @@ +'use strict'; + +describe('myApp.version module', () => { + beforeEach(module('myApp.version')); + + describe('version service', () => { + it('should return current version', inject(version => { + expect(version).toEqual('0.1'); + })); + }); +}); diff --git a/angular1/app/index-async.html b/angular1/app/index-async.html new file mode 100644 index 0000000..a559b71 --- /dev/null +++ b/angular1/app/index-async.html @@ -0,0 +1,58 @@ + + + + + + + + + + My AngularJS App + + + + + +
+ +
Angular seed app: v
+ + + diff --git a/angular1/app/index.html b/angular1/app/index.html new file mode 100644 index 0000000..3c4bb6b --- /dev/null +++ b/angular1/app/index.html @@ -0,0 +1,43 @@ + + + + + + + + + My AngularJS App + + + + + + + + + + + + +
+ +
Angular seed app: v
+ + + + + + + + + + + + diff --git a/angular1/app/tsconfig.json b/angular1/app/tsconfig.json new file mode 100644 index 0000000..744a66c --- /dev/null +++ b/angular1/app/tsconfig.json @@ -0,0 +1,5 @@ +{ + "compilerOptions": { + "module": "commonjs" + } +} diff --git a/angular1/app/typings/angularjs/angular-mocks.d.ts b/angular1/app/typings/angularjs/angular-mocks.d.ts new file mode 100644 index 0000000..1d7c80c --- /dev/null +++ b/angular1/app/typings/angularjs/angular-mocks.d.ts @@ -0,0 +1,239 @@ +// Type definitions for Angular JS 1.3 (ngMock, ngMockE2E module) +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "angular-mocks/ngMock" { + var _: string; + export = _; +} + +declare module "angular-mocks/ngAnimateMock" { + var _: string; + export = _; +} + +/////////////////////////////////////////////////////////////////////////////// +// functions attached to global object (window) +/////////////////////////////////////////////////////////////////////////////// +declare var module: (...modules: any[]) => any; +declare var inject: (...fns: Function[]) => any; + +/////////////////////////////////////////////////////////////////////////////// +// ngMock module (angular-mocks.js) +/////////////////////////////////////////////////////////////////////////////// +declare module angular { + + /////////////////////////////////////////////////////////////////////////// + // AngularStatic + // We reopen it to add the MockStatic definition + /////////////////////////////////////////////////////////////////////////// + interface IAngularStatic { + mock: IMockStatic; + } + + interface IMockStatic { + // see http://docs.angularjs.org/api/angular.mock.dump + dump(obj: any): string; + + // see http://docs.angularjs.org/api/angular.mock.inject + inject: { + (...fns: Function[]): any; + (...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works + strictDi(val?: boolean): void; + } + + // see http://docs.angularjs.org/api/angular.mock.module + module(...modules: any[]): any; + + // see http://docs.angularjs.org/api/angular.mock.TzDate + TzDate(offset: number, timestamp: number): Date; + TzDate(offset: number, timestamp: string): Date; + } + + /////////////////////////////////////////////////////////////////////////// + // ExceptionHandlerService + // see http://docs.angularjs.org/api/ngMock.$exceptionHandler + // see http://docs.angularjs.org/api/ngMock.$exceptionHandlerProvider + /////////////////////////////////////////////////////////////////////////// + interface IExceptionHandlerProvider extends IServiceProvider { + mode(mode: string): void; + } + + /////////////////////////////////////////////////////////////////////////// + // TimeoutService + // see http://docs.angularjs.org/api/ngMock.$timeout + // Augments the original service + /////////////////////////////////////////////////////////////////////////// + interface ITimeoutService { + flush(delay?: number): void; + flushNext(expectedDelay?: number): void; + verifyNoPendingTasks(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // IntervalService + // see http://docs.angularjs.org/api/ngMock.$interval + // Augments the original service + /////////////////////////////////////////////////////////////////////////// + interface IIntervalService { + flush(millis?: number): number; + } + + /////////////////////////////////////////////////////////////////////////// + // LogService + // see http://docs.angularjs.org/api/ngMock.$log + // Augments the original service + /////////////////////////////////////////////////////////////////////////// + interface ILogService { + assertEmpty(): void; + reset(): void; + } + + interface ILogCall { + logs: string[]; + } + + /////////////////////////////////////////////////////////////////////////// + // HttpBackendService + // see http://docs.angularjs.org/api/ngMock.$httpBackend + /////////////////////////////////////////////////////////////////////////// + interface IHttpBackendService { + flush(count?: number): void; + resetExpectations(): void; + verifyNoOutstandingExpectation(): void; + verifyNoOutstandingRequest(): void; + + expect(method: string, url: string, data?: string, headers?: Object): mock.IRequestHandler; + expect(method: string, url: string, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler; + expect(method: string, url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + expect(method: string, url: string, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + expect(method: string, url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expect(method: string, url: string, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler; + expect(method: string, url: string, data?: Object, headers?: Object): mock.IRequestHandler; + expect(method: string, url: string, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler; + + expectDELETE(url: string, headers?: Object): mock.IRequestHandler; + expectDELETE(url: RegExp, headers?: Object): mock.IRequestHandler; + expectGET(url: string, headers?: Object): mock.IRequestHandler; + expectGET(url: RegExp, headers?: Object): mock.IRequestHandler; + expectHEAD(url: string, headers?: Object): mock.IRequestHandler; + expectHEAD(url: RegExp, headers?: Object): mock.IRequestHandler; + expectJSONP(url: string): mock.IRequestHandler; + expectJSONP(url: RegExp): mock.IRequestHandler; + + expectPATCH(url: string, data?: string, headers?: Object): mock.IRequestHandler; + expectPATCH(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + expectPATCH(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expectPATCH(url: string, data?: Object, headers?: Object): mock.IRequestHandler; + expectPATCH(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + expectPATCH(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + expectPATCH(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expectPATCH(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + + expectPOST(url: string, data?: string, headers?: Object): mock.IRequestHandler; + expectPOST(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + expectPOST(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expectPOST(url: string, data?: Object, headers?: Object): mock.IRequestHandler; + expectPOST(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + expectPOST(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + expectPOST(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expectPOST(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + + expectPUT(url: string, data?: string, headers?: Object): mock.IRequestHandler; + expectPUT(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + expectPUT(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expectPUT(url: string, data?: Object, headers?: Object): mock.IRequestHandler; + expectPUT(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + expectPUT(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + expectPUT(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expectPUT(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + + when(method: string, url: string, data?: string, headers?: Object): mock.IRequestHandler; + when(method: string, url: string, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler; + when(method: string, url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + when(method: string, url: string, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + when(method: string, url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + when(method: string, url: string, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler; + when(method: string, url: string, data?: Object, headers?: Object): mock.IRequestHandler; + when(method: string, url: string, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler; + when(method: string, url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + when(method: string, url: RegExp, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler; + when(method: string, url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + when(method: string, url: RegExp, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + when(method: string, url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + when(method: string, url: RegExp, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler; + when(method: string, url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + when(method: string, url: RegExp, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler; + + whenDELETE(url: string, headers?: Object): mock.IRequestHandler; + whenDELETE(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler; + whenDELETE(url: RegExp, headers?: Object): mock.IRequestHandler; + whenDELETE(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + + whenGET(url: string, headers?: Object): mock.IRequestHandler; + whenGET(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler; + whenGET(url: RegExp, headers?: Object): mock.IRequestHandler; + whenGET(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + + whenHEAD(url: string, headers?: Object): mock.IRequestHandler; + whenHEAD(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler; + whenHEAD(url: RegExp, headers?: Object): mock.IRequestHandler; + whenHEAD(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + + whenJSONP(url: string): mock.IRequestHandler; + whenJSONP(url: RegExp): mock.IRequestHandler; + + whenPATCH(url: string, data?: string, headers?: Object): mock.IRequestHandler; + whenPATCH(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + whenPATCH(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + whenPATCH(url: string, data?: Object, headers?: Object): mock.IRequestHandler; + whenPATCH(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + whenPATCH(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + whenPATCH(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + whenPATCH(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + + whenPOST(url: string, data?: string, headers?: Object): mock.IRequestHandler; + whenPOST(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + whenPOST(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + whenPOST(url: string, data?: Object, headers?: Object): mock.IRequestHandler; + whenPOST(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + whenPOST(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + whenPOST(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + whenPOST(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + + whenPUT(url: string, data?: string, headers?: Object): mock.IRequestHandler; + whenPUT(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + whenPUT(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + whenPUT(url: string, data?: Object, headers?: Object): mock.IRequestHandler; + whenPUT(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + whenPUT(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + whenPUT(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + whenPUT(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + } + + export module mock { + + // returned interface by the the mocked HttpBackendService expect/when methods + interface IRequestHandler { + respond(func: Function): void; + respond(status: number, data?: any, headers?: any): void; + respond(data: any, headers?: any): void; + + // Available wehn ngMockE2E is loaded + passThrough(): void; + } + + } + +} diff --git a/angular1/app/typings/angularjs/angular.d.ts b/angular1/app/typings/angularjs/angular.d.ts new file mode 100644 index 0000000..eb826fa --- /dev/null +++ b/angular1/app/typings/angularjs/angular.d.ts @@ -0,0 +1,1714 @@ +// Type definitions for Angular JS 1.4+ +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +declare var angular: angular.IAngularStatic; + +// Support for painless dependency injection +interface Function { + $inject?: string[]; +} + +// Collapse angular into ng +import ng = angular; +// Support AMD require +declare module 'angular' { + export = angular; +} + +/////////////////////////////////////////////////////////////////////////////// +// ng module (angular.js) +/////////////////////////////////////////////////////////////////////////////// +declare module angular { + + // not directly implemented, but ensures that constructed class implements $get + interface IServiceProviderClass { + new (...args: any[]): IServiceProvider; + } + + interface IServiceProviderFactory { + (...args: any[]): IServiceProvider; + } + + // All service providers extend this interface + interface IServiceProvider { + $get: any; + } + + interface IAngularBootstrapConfig { + strictDi?: boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // AngularStatic + // see http://docs.angularjs.org/api + /////////////////////////////////////////////////////////////////////////// + interface IAngularStatic { + bind(context: any, fn: Function, ...args: any[]): Function; + + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: string, modules?: string, config?: IAngularBootstrapConfig): auto.IInjectorService; + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: string, modules?: Function, config?: IAngularBootstrapConfig): auto.IInjectorService; + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: string, modules?: string[], config?: IAngularBootstrapConfig): auto.IInjectorService; + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: JQuery, modules?: string, config?: IAngularBootstrapConfig): auto.IInjectorService; + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: JQuery, modules?: Function, config?: IAngularBootstrapConfig): auto.IInjectorService; + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: JQuery, modules?: string[], config?: IAngularBootstrapConfig): auto.IInjectorService; + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: Element, modules?: string, config?: IAngularBootstrapConfig): auto.IInjectorService; + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: Element, modules?: Function, config?: IAngularBootstrapConfig): auto.IInjectorService; + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: Element, modules?: string[], config?: IAngularBootstrapConfig): auto.IInjectorService; + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: Document, modules?: string, config?: IAngularBootstrapConfig): auto.IInjectorService; + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: Document, modules?: Function, config?: IAngularBootstrapConfig): auto.IInjectorService; + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: Document, modules?: string[], config?: IAngularBootstrapConfig): auto.IInjectorService; + + /** + * Creates a deep copy of source, which should be an object or an array. + * + * - If no destination is supplied, a copy of the object or array is created. + * - If a destination is provided, all of its elements (for array) or properties (for objects) are deleted and then all elements/properties from the source are copied to it. + * - If source is not an object or array (inc. null and undefined), source is returned. + * - If source is identical to 'destination' an exception will be thrown. + * + * @param source The source that will be used to make a copy. Can be any type, including primitives, null, and undefined. + * @param destination Destination into which the source is copied. If provided, must be of the same type as source. + */ + copy(source: T, destination?: T): T; + + /** + * Wraps a raw DOM element or HTML string as a jQuery element. + * + * If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite." + */ + element: IAugmentedJQueryStatic; + equals(value1: any, value2: any): boolean; + extend(destination: any, ...sources: any[]): any; + + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ + forEach(obj: T[], iterator: (value: T, key: number) => any, context?: any): any; + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ + forEach(obj: { [index: string]: T; }, iterator: (value: T, key: string) => any, context?: any): any; + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ + forEach(obj: any, iterator: (value: any, key: any) => any, context?: any): any; + + fromJson(json: string): any; + identity(arg?: any): any; + injector(modules?: any[]): auto.IInjectorService; + isArray(value: any): boolean; + isDate(value: any): boolean; + isDefined(value: any): boolean; + isElement(value: any): boolean; + isFunction(value: any): boolean; + isNumber(value: any): boolean; + isObject(value: any): boolean; + isString(value: any): boolean; + isUndefined(value: any): boolean; + lowercase(str: string): string; + + /** + * Deeply extends the destination object dst by copying own enumerable properties from the src object(s) to dst. You can specify multiple src objects. If you want to preserve original objects, you can do so by passing an empty object as the target: var object = angular.merge({}, object1, object2). + * + * Unlike extend(), merge() recursively descends into object properties of source objects, performing a deep copy. + * + * @param dst Destination object. + * @param src Source object(s). + */ + merge(dst: any, ...src: any[]): any; + + /** + * The angular.module is a global place for creating, registering and retrieving Angular modules. All modules (angular core or 3rd party) that should be available to an application must be registered using this mechanism. + * + * When passed two or more arguments, a new module is created. If passed only one argument, an existing module (the name passed as the first argument to module) is retrieved. + * + * @param name The name of the module to create or retrieve. + * @param requires The names of modules this module depends on. If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. + * @param configFn Optional configuration function for the module. + */ + module( + name: string, + requires?: string[], + configFn?: Function): IModule; + + noop(...args: any[]): void; + reloadWithDebugInfo(): void; + toJson(obj: any, pretty?: boolean): string; + uppercase(str: string): string; + version: { + full: string; + major: number; + minor: number; + dot: number; + codeName: string; + }; + } + + /////////////////////////////////////////////////////////////////////////// + // Module + // see http://docs.angularjs.org/api/angular.Module + /////////////////////////////////////////////////////////////////////////// + interface IModule { + animation(name: string, animationFactory: Function): IModule; + animation(name: string, inlineAnnotatedFunction: any[]): IModule; + animation(object: Object): IModule; + /** + * Use this method to register work which needs to be performed on module loading. + * + * @param configFn Execute this function on module load. Useful for service configuration. + */ + config(configFn: Function): IModule; + /** + * Use this method to register work which needs to be performed on module loading. + * + * @param inlineAnnotatedFunction Execute this function on module load. Useful for service configuration. + */ + config(inlineAnnotatedFunction: any[]): IModule; + /** + * Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator. + * + * @param name The name of the constant. + * @param value The constant value. + */ + constant(name: string, value: any): IModule; + constant(object: Object): IModule; + /** + * The $controller service is used by Angular to create new controllers. + * + * This provider allows controller registration via the register method. + * + * @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors. + * @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation). + */ + controller(name: string, controllerConstructor: Function): IModule; + /** + * The $controller service is used by Angular to create new controllers. + * + * This provider allows controller registration via the register method. + * + * @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors. + * @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation). + */ + controller(name: string, inlineAnnotatedConstructor: any[]): IModule; + controller(object: Object): IModule; + /** + * Register a new directive with the compiler. + * + * @param name Name of the directive in camel-case (i.e. ngBind which will match as ng-bind) + * @param directiveFactory An injectable directive factory function. + */ + directive(name: string, directiveFactory: IDirectiveFactory): IModule; + /** + * Register a new directive with the compiler. + * + * @param name Name of the directive in camel-case (i.e. ngBind which will match as ng-bind) + * @param directiveFactory An injectable directive factory function. + */ + directive(name: string, inlineAnnotatedFunction: any[]): IModule; + directive(object: Object): IModule; + /** + * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider. + * + * @param name The name of the instance. + * @param $getFn The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}). + */ + factory(name: string, $getFn: Function): IModule; + /** + * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider. + * + * @param name The name of the instance. + * @param inlineAnnotatedFunction The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}). + */ + factory(name: string, inlineAnnotatedFunction: any[]): IModule; + factory(object: Object): IModule; + filter(name: string, filterFactoryFunction: Function): IModule; + filter(name: string, inlineAnnotatedFunction: any[]): IModule; + filter(object: Object): IModule; + provider(name: string, serviceProviderFactory: IServiceProviderFactory): IModule; + provider(name: string, serviceProviderConstructor: IServiceProviderClass): IModule; + provider(name: string, inlineAnnotatedConstructor: any[]): IModule; + provider(name: string, providerObject: IServiceProvider): IModule; + provider(object: Object): IModule; + /** + * Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests. + */ + run(initializationFunction: Function): IModule; + /** + * Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests. + */ + run(inlineAnnotatedFunction: any[]): IModule; + service(name: string, serviceConstructor: Function): IModule; + service(name: string, inlineAnnotatedConstructor: any[]): IModule; + service(object: Object): IModule; + /** + * Register a value service with the $injector, such as a string, a number, an array, an object or a function. This is short for registering a service where its provider's $get property is a factory function that takes no arguments and returns the value service. + + Value services are similar to constant services, except that they cannot be injected into a module configuration function (see config) but they can be overridden by an Angular decorator. + * + * @param name The name of the instance. + * @param value The value. + */ + value(name: string, value: any): IModule; + value(object: Object): IModule; + + /** + * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. + * @param name The name of the service to decorate + * @param decorator This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. + */ + decorator(name:string, decoratorConstructor: Function): IModule; + decorator(name:string, inlineAnnotatedConstructor: any[]): IModule; + + // Properties + name: string; + requires: string[]; + } + + /////////////////////////////////////////////////////////////////////////// + // Attributes + // see http://docs.angularjs.org/api/ng.$compile.directive.Attributes + /////////////////////////////////////////////////////////////////////////// + interface IAttributes { + /** + * this is necessary to be able to access the scoped attributes. it's not very elegant + * because you have to use attrs['foo'] instead of attrs.foo but I don't know of a better way + * this should really be limited to return string but it creates this problem: http://stackoverflow.com/q/17201854/165656 + */ + [name: string]: any; + + /** + * Adds the CSS class value specified by the classVal parameter to the + * element. If animations are enabled then an animation will be triggered + * for the class addition. + */ + $addClass(classVal: string): void; + + /** + * Removes the CSS class value specified by the classVal parameter from the + * element. If animations are enabled then an animation will be triggered for + * the class removal. + */ + $removeClass(classVal: string): void; + + /** + * Set DOM element attribute value. + */ + $set(key: string, value: any): void; + + /** + * Observes an interpolated attribute. + * The observer function will be invoked once during the next $digest + * following compilation. The observer is then invoked whenever the + * interpolated value changes. + */ + $observe(name: string, fn: (value?: any) => any): Function; + + /** + * A map of DOM element attribute names to the normalized name. This is needed + * to do reverse lookup from normalized name back to actual name. + */ + $attr: Object; + } + + /** + * form.FormController - type in module ng + * see https://docs.angularjs.org/api/ng/type/form.FormController + */ + interface IFormController { + + /** + * Indexer which should return ng.INgModelController for most properties but cannot because of "All named properties must be assignable to string indexer type" constraint - see https://github.com/Microsoft/TypeScript/issues/272 + */ + [name: string]: any; + + $pristine: boolean; + $dirty: boolean; + $valid: boolean; + $invalid: boolean; + $submitted: boolean; + $error: any; + $addControl(control: INgModelController): void; + $removeControl(control: INgModelController): void; + $setValidity(validationErrorKey: string, isValid: boolean, control: INgModelController): void; + $setDirty(): void; + $setPristine(): void; + $commitViewValue(): void; + $rollbackViewValue(): void; + $setSubmitted(): void; + $setUntouched(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // NgModelController + // see http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController + /////////////////////////////////////////////////////////////////////////// + interface INgModelController { + $render(): void; + $setValidity(validationErrorKey: string, isValid: boolean): void; + // Documentation states viewValue and modelValue to be a string but other + // types do work and it's common to use them. + $setViewValue(value: any, trigger?: string): void; + $setPristine(): void; + $setDirty(): void; + $validate(): void; + $setTouched(): void; + $setUntouched(): void; + $rollbackViewValue(): void; + $commitViewValue(): void; + $isEmpty(value: any): boolean; + + $viewValue: any; + + $modelValue: any; + + $parsers: IModelParser[]; + $formatters: IModelFormatter[]; + $viewChangeListeners: IModelViewChangeListener[]; + $error: any; + $name: string; + + $touched: boolean; + $untouched: boolean; + + $validators: IModelValidators; + $asyncValidators: IAsyncModelValidators; + + $pending: any; + $pristine: boolean; + $dirty: boolean; + $valid: boolean; + $invalid: boolean; + } + + interface IModelValidators { + [index: string]: (modelValue: any, viewValue: string) => boolean; + } + + interface IAsyncModelValidators { + [index: string]: (modelValue: any, viewValue: string) => IPromise; + } + + interface IModelParser { + (value: any): any; + } + + interface IModelFormatter { + (value: any): any; + } + + interface IModelViewChangeListener { + (): void; + } + + /** + * $rootScope - $rootScopeProvider - service in module ng + * see https://docs.angularjs.org/api/ng/type/$rootScope.Scope and https://docs.angularjs.org/api/ng/service/$rootScope + */ + interface IRootScopeService { + [index: string]: any; + + $apply(): any; + $apply(exp: string): any; + $apply(exp: (scope: IScope) => any): any; + + $applyAsync(): any; + $applyAsync(exp: string): any; + $applyAsync(exp: (scope: IScope) => any): any; + + /** + * Dispatches an event name downwards to all child scopes (and their children) notifying the registered $rootScope.Scope listeners. + * + * The event life cycle starts at the scope on which $broadcast was called. All listeners listening for name event on this scope get notified. Afterwards, the event propagates to all direct and indirect scopes of the current scope and calls all registered listeners along the way. The event cannot be canceled. + * + * Any exception emitted from the listeners will be passed onto the $exceptionHandler service. + * + * @param name Event name to broadcast. + * @param args Optional one or more arguments which will be passed onto the event listeners. + */ + $broadcast(name: string, ...args: any[]): IAngularEvent; + $destroy(): void; + $digest(): void; + /** + * Dispatches an event name upwards through the scope hierarchy notifying the registered $rootScope.Scope listeners. + * + * The event life cycle starts at the scope on which $emit was called. All listeners listening for name event on this scope get notified. Afterwards, the event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it. + * + * Any exception emitted from the listeners will be passed onto the $exceptionHandler service. + * + * @param name Event name to emit. + * @param args Optional one or more arguments which will be passed onto the event listeners. + */ + $emit(name: string, ...args: any[]): IAngularEvent; + + $eval(): any; + $eval(expression: string, locals?: Object): any; + $eval(expression: (scope: IScope) => any, locals?: Object): any; + + $evalAsync(): void; + $evalAsync(expression: string): void; + $evalAsync(expression: (scope: IScope) => any): void; + + // Defaults to false by the implementation checking strategy + $new(isolate?: boolean, parent?: IScope): IScope; + + /** + * Listens on events of a given type. See $emit for discussion of event life cycle. + * + * The event listener function format is: function(event, args...). + * + * @param name Event name to listen on. + * @param listener Function to call when the event is emitted. + */ + $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; + + $watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function; + $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; + $watch(watchExpression: (scope: IScope) => any, listener?: string, objectEquality?: boolean): Function; + $watch(watchExpression: (scope: IScope) => any, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; + + $watchCollection(watchExpression: string, listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; + $watchCollection(watchExpression: (scope: IScope) => any, listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; + + $watchGroup(watchExpressions: any[], listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; + $watchGroup(watchExpressions: { (scope: IScope): any }[], listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; + + $parent: IScope; + $root: IRootScopeService; + $id: number; + + // Hidden members + $$isolateBindings: any; + $$phase: any; + } + + interface IScope extends IRootScopeService { } + + /** + * $scope for ngRepeat directive. + * see https://docs.angularjs.org/api/ng/directive/ngRepeat + */ + interface IRepeatScope extends IScope { + + /** + * iterator offset of the repeated element (0..length-1). + */ + $index: number; + + /** + * true if the repeated element is first in the iterator. + */ + $first: boolean; + + /** + * true if the repeated element is between the first and last in the iterator. + */ + $middle: boolean; + + /** + * true if the repeated element is last in the iterator. + */ + $last: boolean; + + /** + * true if the iterator position $index is even (otherwise false). + */ + $even: boolean; + + /** + * true if the iterator position $index is odd (otherwise false). + */ + $odd: boolean; + + } + + interface IAngularEvent { + /** + * the scope on which the event was $emit-ed or $broadcast-ed. + */ + targetScope: IScope; + /** + * the scope that is currently handling the event. Once the event propagates through the scope hierarchy, this property is set to null. + */ + currentScope: IScope; + /** + * name of the event. + */ + name: string; + /** + * calling stopPropagation function will cancel further event propagation (available only for events that were $emit-ed). + */ + stopPropagation?: Function; + /** + * calling preventDefault sets defaultPrevented flag to true. + */ + preventDefault: Function; + /** + * true if preventDefault was called. + */ + defaultPrevented: boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // WindowService + // see http://docs.angularjs.org/api/ng.$window + /////////////////////////////////////////////////////////////////////////// + interface IWindowService extends Window { + [key: string]: any; + } + + /////////////////////////////////////////////////////////////////////////// + // BrowserService + // TODO undocumented, so we need to get it from the source code + /////////////////////////////////////////////////////////////////////////// + interface IBrowserService { + defer: angular.ITimeoutService; + [key: string]: any; + } + + /////////////////////////////////////////////////////////////////////////// + // TimeoutService + // see http://docs.angularjs.org/api/ng.$timeout + /////////////////////////////////////////////////////////////////////////// + interface ITimeoutService { + (func: Function, delay?: number, invokeApply?: boolean): IPromise; + cancel(promise: IPromise): boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // IntervalService + // see http://docs.angularjs.org/api/ng.$interval + /////////////////////////////////////////////////////////////////////////// + interface IIntervalService { + (func: Function, delay: number, count?: number, invokeApply?: boolean): IPromise; + cancel(promise: IPromise): boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // AngularProvider + // see http://docs.angularjs.org/api/ng/provider/$animateProvider + /////////////////////////////////////////////////////////////////////////// + interface IAnimateProvider { + /** + * Registers a new injectable animation factory function. + * + * @param name The name of the animation. + * @param factory The factory function that will be executed to return the animation object. + */ + register(name: string, factory: () => IAnimateCallbackObject): void; + + /** + * Gets and/or sets the CSS class expression that is checked when performing an animation. + * + * @param expression The className expression which will be checked against all animations. + * @returns The current CSS className expression value. If null then there is no expression value. + */ + classNameFilter(expression?: RegExp): RegExp; + } + + /** + * The animation object which contains callback functions for each event that is expected to be animated. + */ + interface IAnimateCallbackObject { + eventFn(element: Node, doneFn: () => void): Function; + } + + /** + * $filter - $filterProvider - service in module ng + * + * Filters are used for formatting data displayed to the user. + * + * see https://docs.angularjs.org/api/ng/service/$filter + */ + interface IFilterService { + /** + * Usage: + * $filter(name); + * + * @param name Name of the filter function to retrieve + */ + (name: string): Function; + } + + /** + * $filterProvider - $filter - provider in module ng + * + * Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To achieve this a filter definition consists of a factory function which is annotated with dependencies and is responsible for creating a filter function. + * + * see https://docs.angularjs.org/api/ng/provider/$filterProvider + */ + interface IFilterProvider extends IServiceProvider { + /** + * register(name); + * + * @param name Name of the filter function, or an object map of filters where the keys are the filter names and the values are the filter factories. Note: Filter names must be valid angular Expressions identifiers, such as uppercase or orderBy. Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace your filters, then you can use capitalization (myappSubsectionFilterx) or underscores (myapp_subsection_filterx). + */ + register(name: string | {}): IServiceProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // LocaleService + // see http://docs.angularjs.org/api/ng.$locale + /////////////////////////////////////////////////////////////////////////// + interface ILocaleService { + id: string; + + // These are not documented + // Check angular's i18n files for exemples + NUMBER_FORMATS: ILocaleNumberFormatDescriptor; + DATETIME_FORMATS: ILocaleDateTimeFormatDescriptor; + pluralCat: (num: any) => string; + } + + interface ILocaleNumberFormatDescriptor { + DECIMAL_SEP: string; + GROUP_SEP: string; + PATTERNS: ILocaleNumberPatternDescriptor[]; + CURRENCY_SYM: string; + } + + interface ILocaleNumberPatternDescriptor { + minInt: number; + minFrac: number; + maxFrac: number; + posPre: string; + posSuf: string; + negPre: string; + negSuf: string; + gSize: number; + lgSize: number; + } + + interface ILocaleDateTimeFormatDescriptor { + MONTH: string[]; + SHORTMONTH: string[]; + DAY: string[]; + SHORTDAY: string[]; + AMPMS: string[]; + medium: string; + short: string; + fullDate: string; + longDate: string; + mediumDate: string; + shortDate: string; + mediumTime: string; + shortTime: string; + } + + /////////////////////////////////////////////////////////////////////////// + // LogService + // see http://docs.angularjs.org/api/ng.$log + // see http://docs.angularjs.org/api/ng.$logProvider + /////////////////////////////////////////////////////////////////////////// + interface ILogService { + debug: ILogCall; + error: ILogCall; + info: ILogCall; + log: ILogCall; + warn: ILogCall; + } + + interface ILogProvider { + debugEnabled(): boolean; + debugEnabled(enabled: boolean): ILogProvider; + } + + // We define this as separate interface so we can reopen it later for + // the ngMock module. + interface ILogCall { + (...args: any[]): void; + } + + /////////////////////////////////////////////////////////////////////////// + // ParseService + // see http://docs.angularjs.org/api/ng.$parse + // see http://docs.angularjs.org/api/ng.$parseProvider + /////////////////////////////////////////////////////////////////////////// + interface IParseService { + (expression: string): ICompiledExpression; + } + + interface IParseProvider { + logPromiseWarnings(): boolean; + logPromiseWarnings(value: boolean): IParseProvider; + + unwrapPromises(): boolean; + unwrapPromises(value: boolean): IParseProvider; + } + + interface ICompiledExpression { + (context: any, locals?: any): any; + + // If value is not provided, undefined is gonna be used since the implementation + // does not check the parameter. Let's force a value for consistency. If consumer + // whants to undefine it, pass the undefined value explicitly. + assign(context: any, value: any): any; + } + + /** + * $location - $locationProvider - service in module ng + * see https://docs.angularjs.org/api/ng/service/$location + */ + interface ILocationService { + absUrl(): string; + hash(): string; + hash(newHash: string): ILocationService; + host(): string; + + /** + * Return path of current url + */ + path(): string; + + /** + * Change path when called with parameter and return $location. + * Note: Path should always begin with forward slash (/), this method will add the forward slash if it is missing. + * + * @param path New path + */ + path(path: string): ILocationService; + + port(): number; + protocol(): string; + replace(): ILocationService; + + /** + * Return search part (as object) of current url + */ + search(): any; + + /** + * Change search part when called with parameter and return $location. + * + * @param search When called with a single argument the method acts as a setter, setting the search component of $location to the specified value. + * + * If the argument is a hash object containing an array of values, these values will be encoded as duplicate search parameters in the url. + */ + search(search: any): ILocationService; + + /** + * Change search part when called with parameter and return $location. + * + * @param search New search params + * @param paramValue If search is a string or a Number, then paramValue will override only a single search property. If paramValue is null, the property specified via the first argument will be deleted. If paramValue is an array, it will override the property of the search component of $location specified via the first argument. If paramValue is true, the property specified via the first argument will be added with no value nor trailing equal sign. + */ + search(search: string, paramValue: string|number|string[]|boolean): ILocationService; + + state(): any; + state(state: any): ILocationService; + url(): string; + url(url: string): ILocationService; + } + + interface ILocationProvider extends IServiceProvider { + hashPrefix(): string; + hashPrefix(prefix: string): ILocationProvider; + html5Mode(): boolean; + + // Documentation states that parameter is string, but + // implementation tests it as boolean, which makes more sense + // since this is a toggler + html5Mode(active: boolean): ILocationProvider; + html5Mode(mode: { enabled?: boolean; requireBase?: boolean; rewriteLinks?: boolean; }): ILocationProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // DocumentService + // see http://docs.angularjs.org/api/ng.$document + /////////////////////////////////////////////////////////////////////////// + interface IDocumentService extends IAugmentedJQuery {} + + /////////////////////////////////////////////////////////////////////////// + // ExceptionHandlerService + // see http://docs.angularjs.org/api/ng.$exceptionHandler + /////////////////////////////////////////////////////////////////////////// + interface IExceptionHandlerService { + (exception: Error, cause?: string): void; + } + + /////////////////////////////////////////////////////////////////////////// + // RootElementService + // see http://docs.angularjs.org/api/ng.$rootElement + /////////////////////////////////////////////////////////////////////////// + interface IRootElementService extends JQuery {} + + interface IQResolveReject { + (): void; + (value: T): void; + } + /** + * $q - service in module ng + * A promise/deferred implementation inspired by Kris Kowal's Q. + * See http://docs.angularjs.org/api/ng/service/$q + */ + interface IQService { + new (resolver: (resolve: IQResolveReject) => any): IPromise; + new (resolver: (resolve: IQResolveReject, reject: IQResolveReject) => any): IPromise; + new (resolver: (resolve: IQResolveReject, reject: IQResolveReject) => any): IPromise; + + /** + * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. + * + * Returns a single promise that will be resolved with an array of values, each value corresponding to the promise at the same index in the promises array. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. + * + * @param promises An array of promises. + */ + all(promises: IPromise[]): IPromise; + /** + * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. + * + * Returns a single promise that will be resolved with a hash of values, each value corresponding to the promise at the same key in the promises hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. + * + * @param promises A hash of promises. + */ + all(promises: { [id: string]: IPromise; }): IPromise<{ [id: string]: any; }>; + /** + * Creates a Deferred object which represents a task which will finish in the future. + */ + defer(): IDeferred; + /** + * Creates a promise that is resolved as rejected with the specified reason. This api should be used to forward rejection in a chain of promises. If you are dealing with the last promise in a promise chain, you don't need to worry about it. + * + * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of reject as the throw keyword in JavaScript. This also means that if you "catch" an error via a promise error callback and you want to forward the error to the promise derived from the current promise, you have to "rethrow" the error by returning a rejection constructed via reject. + * + * @param reason Constant, message, exception or an object representing the rejection reason. + */ + reject(reason?: any): IPromise; + /** + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. + * + * @param value Value or a promise + */ + when(value: IPromise|T): IPromise; + /** + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. + * + * @param value Value or a promise + */ + when(): IPromise; + } + + interface IPromise { + /** + * Regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected. + * + * This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method. + */ + then(successCallback: (promiseValue: T) => IHttpPromise|IPromise|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise; + + /** + * Shorthand for promise.then(null, errorCallback) + */ + catch(onRejected: (reason: any) => IHttpPromise|IPromise|TResult): IPromise; + + /** + * Allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information. + * + * Because finally is a reserved word in JavaScript and reserved keywords are not supported as property names by ES3, you'll need to invoke the method like promise['finally'](callback) to make your code IE8 and Android 2.x compatible. + */ + finally(finallyCallback: () => any): IPromise; + } + + interface IDeferred { + resolve(value?: T): void; + reject(reason?: any): void; + notify(state?: any): void; + promise: IPromise; + } + + /////////////////////////////////////////////////////////////////////////// + // AnchorScrollService + // see http://docs.angularjs.org/api/ng.$anchorScroll + /////////////////////////////////////////////////////////////////////////// + interface IAnchorScrollService { + (): void; + yOffset: any; + } + + interface IAnchorScrollProvider extends IServiceProvider { + disableAutoScrolling(): void; + } + + /** + * $cacheFactory - service in module ng + * + * Factory that constructs Cache objects and gives access to them. + * + * see https://docs.angularjs.org/api/ng/service/$cacheFactory + */ + interface ICacheFactoryService { + /** + * Factory that constructs Cache objects and gives access to them. + * + * @param cacheId Name or id of the newly created cache. + * @param optionsMap Options object that specifies the cache behavior. Properties: + * + * capacity — turns the cache into LRU cache. + */ + (cacheId: string, optionsMap?: { capacity?: number; }): ICacheObject; + + /** + * Get information about all the caches that have been created. + * @returns key-value map of cacheId to the result of calling cache#info + */ + info(): any; + + /** + * Get access to a cache object by the cacheId used when it was created. + * + * @param cacheId Name or id of a cache to access. + */ + get(cacheId: string): ICacheObject; + } + + /** + * $cacheFactory.Cache - type in module ng + * + * A cache object used to store and retrieve data, primarily used by $http and the script directive to cache templates and other data. + * + * see https://docs.angularjs.org/api/ng/type/$cacheFactory.Cache + */ + interface ICacheObject { + /** + * Retrieve information regarding a particular Cache. + */ + info(): { + /** + * the id of the cache instance + */ + id: string; + + /** + * the number of entries kept in the cache instance + */ + size: number; + + //...: any additional properties from the options object when creating the cache. + }; + + /** + * Inserts a named entry into the Cache object to be retrieved later, and incrementing the size of the cache if the key was not already present in the cache. If behaving like an LRU cache, it will also remove stale entries from the set. + * + * It will not insert undefined values into the cache. + * + * @param key the key under which the cached data is stored. + * @param value the value to store alongside the key. If it is undefined, the key will not be stored. + */ + put(key: string, value?: T): T; + + /** + * Retrieves named data stored in the Cache object. + * + * @param key the key of the data to be retrieved + */ + get(key: string): any; + + /** + * Removes an entry from the Cache object. + * + * @param key the key of the entry to be removed + */ + remove(key: string): void; + + /** + * Clears the cache object of any entries. + */ + removeAll(): void; + + /** + * Destroys the Cache object entirely, removing it from the $cacheFactory set. + */ + destroy(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // CompileService + // see http://docs.angularjs.org/api/ng.$compile + // see http://docs.angularjs.org/api/ng.$compileProvider + /////////////////////////////////////////////////////////////////////////// + interface ICompileService { + (element: string, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction; + (element: Element, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction; + (element: JQuery, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction; + } + + interface ICompileProvider extends IServiceProvider { + directive(name: string, directiveFactory: Function): ICompileProvider; + + // Undocumented, but it is there... + directive(directivesMap: any): ICompileProvider; + + aHrefSanitizationWhitelist(): RegExp; + aHrefSanitizationWhitelist(regexp: RegExp): ICompileProvider; + + imgSrcSanitizationWhitelist(): RegExp; + imgSrcSanitizationWhitelist(regexp: RegExp): ICompileProvider; + + debugInfoEnabled(enabled?: boolean): any; + } + + interface ICloneAttachFunction { + // Let's hint but not force cloneAttachFn's signature + (clonedElement?: JQuery, scope?: IScope): any; + } + + // This corresponds to the "publicLinkFn" returned by $compile. + interface ITemplateLinkingFunction { + (scope: IScope, cloneAttachFn?: ICloneAttachFunction): IAugmentedJQuery; + } + + // This corresponds to $transclude (and also the transclude function passed to link). + interface ITranscludeFunction { + // If the scope is provided, then the cloneAttachFn must be as well. + (scope: IScope, cloneAttachFn: ICloneAttachFunction): IAugmentedJQuery; + // If one argument is provided, then it's assumed to be the cloneAttachFn. + (cloneAttachFn?: ICloneAttachFunction): IAugmentedJQuery; + } + + /////////////////////////////////////////////////////////////////////////// + // ControllerService + // see http://docs.angularjs.org/api/ng.$controller + // see http://docs.angularjs.org/api/ng.$controllerProvider + /////////////////////////////////////////////////////////////////////////// + interface IControllerService { + // Although the documentation doesn't state this, locals are optional + (controllerConstructor: Function, locals?: any): any; + (controllerName: string, locals?: any): any; + } + + interface IControllerProvider extends IServiceProvider { + register(name: string, controllerConstructor: Function): void; + register(name: string, dependencyAnnotatedConstructor: any[]): void; + allowGlobals(): void; + } + + /** + * HttpService + * see http://docs.angularjs.org/api/ng/service/$http + */ + interface IHttpService { + /** + * Object describing the request to be made and how it should be processed. + */ + (config: IRequestConfig): IHttpPromise; + + /** + * Shortcut method to perform GET request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + get(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform DELETE request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + delete(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform HEAD request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + head(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform JSONP request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + jsonp(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform POST request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param data Request content + * @param config Optional configuration object + */ + post(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform PUT request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param data Request content + * @param config Optional configuration object + */ + put(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform PATCH request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param data Request content + * @param config Optional configuration object + */ + patch(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Runtime equivalent of the $httpProvider.defaults property. Allows configuration of default headers, withCredentials as well as request and response transformations. + */ + defaults: IRequestConfig; + + /** + * Array of config objects for currently pending requests. This is primarily meant to be used for debugging purposes. + */ + pendingRequests: any[]; + } + + /** + * Object describing the request to be made and how it should be processed. + * see http://docs.angularjs.org/api/ng/service/$http#usage + */ + interface IRequestShortcutConfig { + /** + * {Object.} + * Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified. + */ + params?: any; + + /** + * Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent. + */ + headers?: any; + + /** + * Name of HTTP header to populate with the XSRF token. + */ + xsrfHeaderName?: string; + + /** + * Name of cookie containing the XSRF token. + */ + xsrfCookieName?: string; + + /** + * {boolean|Cache} + * If true, a default $http cache will be used to cache the GET request, otherwise if a cache instance built with $cacheFactory, this cache will be used for caching. + */ + cache?: any; + + /** + * whether to to set the withCredentials flag on the XHR object. See [requests with credentials]https://developer.mozilla.org/en/http_access_control#section_5 for more information. + */ + withCredentials?: boolean; + + /** + * {string|Object} + * Data to be sent as the request message data. + */ + data?: any; + + /** + * {function(data, headersGetter)|Array.} + * Transform function or an array of such functions. The transform function takes the http request body and headers and returns its transformed (typically serialized) version. + */ + transformRequest?: any; + + /** + * {function(data, headersGetter)|Array.} + * Transform function or an array of such functions. The transform function takes the http response body and headers and returns its transformed (typically deserialized) version. + */ + transformResponse?: any; + + /** + * {number|Promise} + * Timeout in milliseconds, or promise that should abort the request when resolved. + */ + timeout?: any; + + /** + * See requestType. + */ + responseType?: string; + } + + /** + * Object describing the request to be made and how it should be processed. + * see http://docs.angularjs.org/api/ng/service/$http#usage + */ + interface IRequestConfig extends IRequestShortcutConfig { + /** + * HTTP method (e.g. 'GET', 'POST', etc) + */ + method: string; + /** + * Absolute or relative URL of the resource that is being requested. + */ + url: string; + } + + interface IHttpHeadersGetter { + (): { [name: string]: string; }; + (headerName: string): string; + } + + interface IHttpPromiseCallback { + (data: T, status: number, headers: IHttpHeadersGetter, config: IRequestConfig): void; + } + + interface IHttpPromiseCallbackArg { + data?: T; + status?: number; + headers?: IHttpHeadersGetter; + config?: IRequestConfig; + statusText?: string; + } + + interface IHttpPromise extends IPromise> { + success(callback: IHttpPromiseCallback): IHttpPromise; + error(callback: IHttpPromiseCallback): IHttpPromise; + then(successCallback: (response: IHttpPromiseCallbackArg) => IPromise|TResult, errorCallback?: (response: IHttpPromiseCallbackArg) => any): IPromise; + } + + /** + * Object that controls the defaults for $http provider + * https://docs.angularjs.org/api/ng/service/$http#defaults + */ + interface IHttpProviderDefaults { + xsrfCookieName?: string; + xsrfHeaderName?: string; + withCredentials?: boolean; + headers?: { + common?: any; + post?: any; + put?: any; + patch?: any; + } + } + + interface IHttpProvider extends IServiceProvider { + defaults: IHttpProviderDefaults; + interceptors: any[]; + useApplyAsync(): boolean; + useApplyAsync(value: boolean): IHttpProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // HttpBackendService + // see http://docs.angularjs.org/api/ng.$httpBackend + // You should never need to use this service directly. + /////////////////////////////////////////////////////////////////////////// + interface IHttpBackendService { + // XXX Perhaps define callback signature in the future + (method: string, url: string, post?: any, callback?: Function, headers?: any, timeout?: number, withCredentials?: boolean): void; + } + + /////////////////////////////////////////////////////////////////////////// + // InterpolateService + // see http://docs.angularjs.org/api/ng.$interpolate + // see http://docs.angularjs.org/api/ng.$interpolateProvider + /////////////////////////////////////////////////////////////////////////// + interface IInterpolateService { + (text: string, mustHaveExpression?: boolean, trustedContext?: string, allOrNothing?: boolean): IInterpolationFunction; + endSymbol(): string; + startSymbol(): string; + } + + interface IInterpolationFunction { + (context: any): string; + } + + interface IInterpolateProvider extends IServiceProvider { + startSymbol(): string; + startSymbol(value: string): IInterpolateProvider; + endSymbol(): string; + endSymbol(value: string): IInterpolateProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // TemplateCacheService + // see http://docs.angularjs.org/api/ng.$templateCache + /////////////////////////////////////////////////////////////////////////// + interface ITemplateCacheService extends ICacheObject {} + + /////////////////////////////////////////////////////////////////////////// + // SCEService + // see http://docs.angularjs.org/api/ng.$sce + /////////////////////////////////////////////////////////////////////////// + interface ISCEService { + getTrusted(type: string, mayBeTrusted: any): any; + getTrustedCss(value: any): any; + getTrustedHtml(value: any): any; + getTrustedJs(value: any): any; + getTrustedResourceUrl(value: any): any; + getTrustedUrl(value: any): any; + parse(type: string, expression: string): (context: any, locals: any) => any; + parseAsCss(expression: string): (context: any, locals: any) => any; + parseAsHtml(expression: string): (context: any, locals: any) => any; + parseAsJs(expression: string): (context: any, locals: any) => any; + parseAsResourceUrl(expression: string): (context: any, locals: any) => any; + parseAsUrl(expression: string): (context: any, locals: any) => any; + trustAs(type: string, value: any): any; + trustAsHtml(value: any): any; + trustAsJs(value: any): any; + trustAsResourceUrl(value: any): any; + trustAsUrl(value: any): any; + isEnabled(): boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // SCEProvider + // see http://docs.angularjs.org/api/ng.$sceProvider + /////////////////////////////////////////////////////////////////////////// + interface ISCEProvider extends IServiceProvider { + enabled(value: boolean): void; + } + + /////////////////////////////////////////////////////////////////////////// + // SCEDelegateService + // see http://docs.angularjs.org/api/ng.$sceDelegate + /////////////////////////////////////////////////////////////////////////// + interface ISCEDelegateService { + getTrusted(type: string, mayBeTrusted: any): any; + trustAs(type: string, value: any): any; + valueOf(value: any): any; + } + + + /////////////////////////////////////////////////////////////////////////// + // SCEDelegateProvider + // see http://docs.angularjs.org/api/ng.$sceDelegateProvider + /////////////////////////////////////////////////////////////////////////// + interface ISCEDelegateProvider extends IServiceProvider { + resourceUrlBlacklist(blacklist: any[]): void; + resourceUrlWhitelist(whitelist: any[]): void; + } + + /** + * $templateRequest service + * see http://docs.angularjs.org/api/ng/service/$templateRequest + */ + interface ITemplateRequestService { + /** + * Downloads a template using $http and, upon success, stores the + * contents inside of $templateCache. + * + * If the HTTP request fails or the response data of the HTTP request is + * empty then a $compile error will be thrown (unless + * {ignoreRequestError} is set to true). + * + * @param tpl The template URL. + * @param ignoreRequestError Whether or not to ignore the exception + * when the request fails or the template is + * empty. + * + * @return A promise whose value is the template content. + */ + (tpl: string, ignoreRequestError?: boolean): IPromise; + /** + * total amount of pending template requests being downloaded. + * @type {number} + */ + totalPendingRequests: number; + } + + /////////////////////////////////////////////////////////////////////////// + // Directive + // see http://docs.angularjs.org/api/ng.$compileProvider#directive + // and http://docs.angularjs.org/guide/directive + /////////////////////////////////////////////////////////////////////////// + + interface IDirectiveFactory { + (...args: any[]): IDirective; + } + + interface IDirectiveLinkFn { + ( + scope: IScope, + instanceElement: IAugmentedJQuery, + instanceAttributes: IAttributes, + controller: any, + transclude: ITranscludeFunction + ): void; + } + + interface IDirectivePrePost { + pre?: IDirectiveLinkFn; + post?: IDirectiveLinkFn; + } + + interface IDirectiveCompileFn { + ( + templateElement: IAugmentedJQuery, + templateAttributes: IAttributes, + transclude: ITranscludeFunction + ): IDirectivePrePost; + } + + interface IDirective { + compile?: IDirectiveCompileFn; + controller?: any; + controllerAs?: string; + bindToController?: boolean|Object; + link?: IDirectiveLinkFn | IDirectivePrePost; + name?: string; + priority?: number; + replace?: boolean; + require?: any; + restrict?: string; + scope?: any; + template?: any; + templateUrl?: any; + terminal?: boolean; + transclude?: any; + } + + /** + * angular.element + * when calling angular.element, angular returns a jQuery object, + * augmented with additional methods like e.g. scope. + * see: http://docs.angularjs.org/api/angular.element + */ + interface IAugmentedJQueryStatic extends JQueryStatic { + (selector: string, context?: any): IAugmentedJQuery; + (element: Element): IAugmentedJQuery; + (object: {}): IAugmentedJQuery; + (elementArray: Element[]): IAugmentedJQuery; + (object: JQuery): IAugmentedJQuery; + (func: Function): IAugmentedJQuery; + (array: any[]): IAugmentedJQuery; + (): IAugmentedJQuery; + } + + interface IAugmentedJQuery extends JQuery { + // TODO: events, how to define? + //$destroy + + find(selector: string): IAugmentedJQuery; + find(element: any): IAugmentedJQuery; + find(obj: JQuery): IAugmentedJQuery; + controller(): any; + controller(name: string): any; + injector(): any; + scope(): IScope; + isolateScope(): IScope; + + inheritedData(key: string, value: any): JQuery; + inheritedData(obj: { [key: string]: any; }): JQuery; + inheritedData(key?: string): any; + } + + /////////////////////////////////////////////////////////////////////// + // AnimateService + // see http://docs.angularjs.org/api/ng.$animate + /////////////////////////////////////////////////////////////////////// + interface IAnimateService { + addClass(element: JQuery, className: string, done?: Function): IPromise; + enter(element: JQuery, parent: JQuery, after: JQuery, done?: Function): void; + leave(element: JQuery, done?: Function): void; + move(element: JQuery, parent: JQuery, after: JQuery, done?: Function): void; + removeClass(element: JQuery, className: string, done?: Function): void; + } + + /////////////////////////////////////////////////////////////////////////// + // AUTO module (angular.js) + /////////////////////////////////////////////////////////////////////////// + export module auto { + + /////////////////////////////////////////////////////////////////////// + // InjectorService + // see http://docs.angularjs.org/api/AUTO.$injector + /////////////////////////////////////////////////////////////////////// + interface IInjectorService { + annotate(fn: Function): string[]; + annotate(inlineAnnotatedFunction: any[]): string[]; + get(name: string): any; + has(name: string): boolean; + instantiate(typeConstructor: Function, locals?: any): any; + invoke(inlineAnnotatedFunction: any[]): any; + invoke(func: Function, context?: any, locals?: any): any; + } + + /////////////////////////////////////////////////////////////////////// + // ProvideService + // see http://docs.angularjs.org/api/AUTO.$provide + /////////////////////////////////////////////////////////////////////// + interface IProvideService { + // Documentation says it returns the registered instance, but actual + // implementation does not return anything. + // constant(name: string, value: any): any; + /** + * Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator. + * + * @param name The name of the constant. + * @param value The constant value. + */ + constant(name: string, value: any): void; + + /** + * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. + * + * @param name The name of the service to decorate. + * @param decorator This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: + * + * $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. + */ + decorator(name: string, decorator: Function): void; + /** + * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. + * + * @param name The name of the service to decorate. + * @param inlineAnnotatedFunction This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: + * + * $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. + */ + decorator(name: string, inlineAnnotatedFunction: any[]): void; + factory(name: string, serviceFactoryFunction: Function): IServiceProvider; + factory(name: string, inlineAnnotatedFunction: any[]): IServiceProvider; + provider(name: string, provider: IServiceProvider): IServiceProvider; + provider(name: string, serviceProviderConstructor: Function): IServiceProvider; + service(name: string, constructor: Function): IServiceProvider; + value(name: string, value: any): IServiceProvider; + } + + } +} diff --git a/angular1/app/typings/jasmine/jasmine.d.ts b/angular1/app/typings/jasmine/jasmine.d.ts new file mode 100644 index 0000000..1eb8d5e --- /dev/null +++ b/angular1/app/typings/jasmine/jasmine.d.ts @@ -0,0 +1,478 @@ +// Type definitions for Jasmine 2.2 +// Project: http://jasmine.github.io/ +// Definitions by: Boris Yankov , Theodore Brown , David Pärsson +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +// For ddescribe / iit use : https://github.com/borisyankov/DefinitelyTyped/blob/master/karma-jasmine/karma-jasmine.d.ts + +declare function describe(description: string, specDefinitions: () => void): void; +declare function fdescribe(description: string, specDefinitions: () => void): void; +declare function xdescribe(description: string, specDefinitions: () => void): void; + +declare function it(expectation: string, assertion?: () => void, timeout?: number): void; +declare function it(expectation: string, assertion?: (done: () => void) => void, timeout?: number): void; +declare function fit(expectation: string, assertion?: () => void, timeout?: number): void; +declare function fit(expectation: string, assertion?: (done: () => void) => void, timeout?: number): void; +declare function xit(expectation: string, assertion?: () => void, timeout?: number): void; +declare function xit(expectation: string, assertion?: (done: () => void) => void, timeout?: number): void; + +/** If you call the function pending anywhere in the spec body, no matter the expectations, the spec will be marked pending. */ +declare function pending(reason?: string): void; + +declare function beforeEach(action: () => void, timeout?: number): void; +declare function beforeEach(action: (done: () => void) => void, timeout?: number): void; +declare function afterEach(action: () => void, timeout?: number): void; +declare function afterEach(action: (done: () => void) => void, timeout?: number): void; + +declare function beforeAll(action: () => void, timeout?: number): void; +declare function beforeAll(action: (done: () => void) => void, timeout?: number): void; +declare function afterAll(action: () => void, timeout?: number): void; +declare function afterAll(action: (done: () => void) => void, timeout?: number): void; + +declare function expect(spy: Function): jasmine.Matchers; +declare function expect(actual: any): jasmine.Matchers; + +declare function fail(e?: any): void; + +declare function spyOn(object: any, method: string): jasmine.Spy; + +declare function runs(asyncMethod: Function): void; +declare function waitsFor(latchMethod: () => boolean, failureMessage?: string, timeout?: number): void; +declare function waits(timeout?: number): void; + +declare module jasmine { + + var clock: () => Clock; + + function any(aclass: any): Any; + function anything(): Any; + function objectContaining(sample: any): ObjectContaining; + function createSpy(name: string, originalFn?: Function): Spy; + function createSpyObj(baseName: string, methodNames: any[]): any; + function createSpyObj(baseName: string, methodNames: any[]): T; + function pp(value: any): string; + function getEnv(): Env; + function addCustomEqualityTester(equalityTester: CustomEqualityTester): void; + function addMatchers(matchers: CustomMatcherFactories): void; + + interface Any { + + new (expectedClass: any): any; + + jasmineMatches(other: any): boolean; + jasmineToString(): string; + } + + // taken from TypeScript lib.core.es6.d.ts, applicable to CustomMatchers.contains() + interface ArrayLike { + length: number; + [n: number]: T; + } + + interface ObjectContaining { + new (sample: any): any; + + jasmineMatches(other: any, mismatchKeys: any[], mismatchValues: any[]): boolean; + jasmineToString(): string; + } + + interface Block { + + new (env: Env, func: SpecFunction, spec: Spec): any; + + execute(onComplete: () => void): void; + } + + interface WaitsBlock extends Block { + new (env: Env, timeout: number, spec: Spec): any; + } + + interface WaitsForBlock extends Block { + new (env: Env, timeout: number, latchFunction: SpecFunction, message: string, spec: Spec): any; + } + + interface Clock { + install(): void; + uninstall(): void; + /** Calls to any registered callback are triggered when the clock is ticked forward via the jasmine.clock().tick function, which takes a number of milliseconds. */ + tick(ms: number): void; + } + + interface CustomEqualityTester { + (first: any, second: any): boolean; + } + + interface CustomMatcher { + compare(actual: T, expected: T): CustomMatcherResult; + compare(actual: any, expected: any): CustomMatcherResult; + } + + interface CustomMatcherFactory { + (util: MatchersUtil, customEqualityTesters: Array): CustomMatcher; + } + + interface CustomMatcherFactories { + [index: string]: CustomMatcherFactory; + } + + interface CustomMatcherResult { + pass: boolean; + message: string; + } + + interface MatchersUtil { + equals(a: any, b: any, customTesters?: Array): boolean; + contains(haystack: ArrayLike | string, needle: any, customTesters?: Array): boolean; + buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: Array): string; + } + + interface Env { + setTimeout: any; + clearTimeout: void; + setInterval: any; + clearInterval: void; + updateInterval: number; + + currentSpec: Spec; + + matchersClass: Matchers; + + version(): any; + versionString(): string; + nextSpecId(): number; + addReporter(reporter: Reporter): void; + execute(): void; + describe(description: string, specDefinitions: () => void): Suite; + // ddescribe(description: string, specDefinitions: () => void): Suite; Not a part of jasmine. Angular team adds these + beforeEach(beforeEachFunction: () => void): void; + beforeAll(beforeAllFunction: () => void): void; + currentRunner(): Runner; + afterEach(afterEachFunction: () => void): void; + afterAll(afterAllFunction: () => void): void; + xdescribe(desc: string, specDefinitions: () => void): XSuite; + it(description: string, func: () => void): Spec; + // iit(description: string, func: () => void): Spec; Not a part of jasmine. Angular team adds these + xit(desc: string, func: () => void): XSpec; + compareRegExps_(a: RegExp, b: RegExp, mismatchKeys: string[], mismatchValues: string[]): boolean; + compareObjects_(a: any, b: any, mismatchKeys: string[], mismatchValues: string[]): boolean; + equals_(a: any, b: any, mismatchKeys: string[], mismatchValues: string[]): boolean; + contains_(haystack: any, needle: any): boolean; + addCustomEqualityTester(equalityTester: CustomEqualityTester): void; + addMatchers(matchers: CustomMatcherFactories): void; + specFilter(spec: Spec): boolean; + } + + interface FakeTimer { + + new (): any; + + reset(): void; + tick(millis: number): void; + runFunctionsWithinRange(oldMillis: number, nowMillis: number): void; + scheduleFunction(timeoutKey: any, funcToCall: () => void, millis: number, recurring: boolean): void; + } + + interface HtmlReporter { + new (): any; + } + + interface HtmlSpecFilter { + new (): any; + } + + interface Result { + type: string; + } + + interface NestedResults extends Result { + description: string; + + totalCount: number; + passedCount: number; + failedCount: number; + + skipped: boolean; + + rollupCounts(result: NestedResults): void; + log(values: any): void; + getItems(): Result[]; + addResult(result: Result): void; + passed(): boolean; + } + + interface MessageResult extends Result { + values: any; + trace: Trace; + } + + interface ExpectationResult extends Result { + matcherName: string; + passed(): boolean; + expected: any; + actual: any; + message: string; + trace: Trace; + } + + interface Trace { + name: string; + message: string; + stack: any; + } + + interface PrettyPrinter { + + new (): any; + + format(value: any): void; + iterateObject(obj: any, fn: (property: string, isGetter: boolean) => void): void; + emitScalar(value: any): void; + emitString(value: string): void; + emitArray(array: any[]): void; + emitObject(obj: any): void; + append(value: any): void; + } + + interface StringPrettyPrinter extends PrettyPrinter { + } + + interface Queue { + + new (env: any): any; + + env: Env; + ensured: boolean[]; + blocks: Block[]; + running: boolean; + index: number; + offset: number; + abort: boolean; + + addBefore(block: Block, ensure?: boolean): void; + add(block: any, ensure?: boolean): void; + insertNext(block: any, ensure?: boolean): void; + start(onComplete?: () => void): void; + isRunning(): boolean; + next_(): void; + results(): NestedResults; + } + + interface Matchers { + + new (env: Env, actual: any, spec: Env, isNot?: boolean): any; + + env: Env; + actual: any; + spec: Env; + isNot?: boolean; + message(): any; + + toBe(expected: any): boolean; + toEqual(expected: any): boolean; + toMatch(expected: any): boolean; + toBeDefined(): boolean; + toBeUndefined(): boolean; + toBeNull(): boolean; + toBeNaN(): boolean; + toBeTruthy(): boolean; + toBeFalsy(): boolean; + toHaveBeenCalled(): boolean; + toHaveBeenCalledWith(...params: any[]): boolean; + toContain(expected: any): boolean; + toBeLessThan(expected: any): boolean; + toBeGreaterThan(expected: any): boolean; + toBeCloseTo(expected: any, precision: any): boolean; + toContainHtml(expected: string): boolean; + toContainText(expected: string): boolean; + toThrow(expected?: any): boolean; + toThrowError(expected?: any): boolean; + not: Matchers; + + Any: Any; + } + + interface Reporter { + reportRunnerStarting(runner: Runner): void; + reportRunnerResults(runner: Runner): void; + reportSuiteResults(suite: Suite): void; + reportSpecStarting(spec: Spec): void; + reportSpecResults(spec: Spec): void; + log(str: string): void; + } + + interface MultiReporter extends Reporter { + addReporter(reporter: Reporter): void; + } + + interface Runner { + + new (env: Env): any; + + execute(): void; + beforeEach(beforeEachFunction: SpecFunction): void; + afterEach(afterEachFunction: SpecFunction): void; + beforeAll(beforeAllFunction: SpecFunction): void; + afterAll(afterAllFunction: SpecFunction): void; + finishCallback(): void; + addSuite(suite: Suite): void; + add(block: Block): void; + specs(): Spec[]; + suites(): Suite[]; + topLevelSuites(): Suite[]; + results(): NestedResults; + } + + interface SpecFunction { + (spec?: Spec): void; + } + + interface SuiteOrSpec { + id: number; + env: Env; + description: string; + queue: Queue; + } + + interface Spec extends SuiteOrSpec { + + new (env: Env, suite: Suite, description: string): any; + + suite: Suite; + + afterCallbacks: SpecFunction[]; + spies_: Spy[]; + + results_: NestedResults; + matchersClass: Matchers; + + getFullName(): string; + results(): NestedResults; + log(arguments: any): any; + runs(func: SpecFunction): Spec; + addToQueue(block: Block): void; + addMatcherResult(result: Result): void; + expect(actual: any): any; + waits(timeout: number): Spec; + waitsFor(latchFunction: SpecFunction, timeoutMessage?: string, timeout?: number): Spec; + fail(e?: any): void; + getMatchersClass_(): Matchers; + addMatchers(matchersPrototype: CustomMatcherFactories): void; + finishCallback(): void; + finish(onComplete?: () => void): void; + after(doAfter: SpecFunction): void; + execute(onComplete?: () => void): any; + addBeforesAndAftersToQueue(): void; + explodes(): void; + spyOn(obj: any, methodName: string, ignoreMethodDoesntExist: boolean): Spy; + removeAllSpies(): void; + } + + interface XSpec { + id: number; + runs(): void; + } + + interface Suite extends SuiteOrSpec { + + new (env: Env, description: string, specDefinitions: () => void, parentSuite: Suite): any; + + parentSuite: Suite; + + getFullName(): string; + finish(onComplete?: () => void): void; + beforeEach(beforeEachFunction: SpecFunction): void; + afterEach(afterEachFunction: SpecFunction): void; + beforeAll(beforeAllFunction: SpecFunction): void; + afterAll(afterAllFunction: SpecFunction): void; + results(): NestedResults; + add(suiteOrSpec: SuiteOrSpec): void; + specs(): Spec[]; + suites(): Suite[]; + children(): any[]; + execute(onComplete?: () => void): void; + } + + interface XSuite { + execute(): void; + } + + interface Spy { + (...params: any[]): any; + + identity: string; + and: SpyAnd; + calls: Calls; + mostRecentCall: { args: any[]; }; + argsForCall: any[]; + wasCalled: boolean; + } + + interface SpyAnd { + /** By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation. */ + callThrough(): Spy; + /** By chaining the spy with and.returnValue, all calls to the function will return a specific value. */ + returnValue(val: any): void; + /** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function. */ + callFake(fn: Function): Spy; + /** By chaining the spy with and.throwError, all calls to the spy will throw the specified value. */ + throwError(msg: string): void; + /** When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with and.stub. */ + stub(): Spy; + } + + interface Calls { + /** By chaining the spy with calls.any(), will return false if the spy has not been called at all, and then true once at least one call happens. **/ + any(): boolean; + /** By chaining the spy with calls.count(), will return the number of times the spy was called **/ + count(): number; + /** By chaining the spy with calls.argsFor(), will return the arguments passed to call number index **/ + argsFor(index: number): any[]; + /** By chaining the spy with calls.allArgs(), will return the arguments to all calls **/ + allArgs(): any[]; + /** By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls **/ + all(): any; + /** By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call **/ + mostRecent(): any; + /** By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call **/ + first(): any; + /** By chaining the spy with calls.reset(), will clears all tracking for a spy **/ + reset(): void; + } + + interface Util { + inherit(childClass: Function, parentClass: Function): any; + formatException(e: any): any; + htmlEscape(str: string): string; + argsToArray(args: any): any; + extend(destination: any, source: any): any; + } + + interface JsApiReporter extends Reporter { + + started: boolean; + finished: boolean; + result: any; + messages: any; + + new (): any; + + suites(): Suite[]; + summarize_(suiteOrSpec: SuiteOrSpec): any; + results(): any; + resultsForSpec(specId: any): any; + log(str: any): any; + resultsForSpecs(specIds: any): any; + summarizeResult_(result: any): any; + } + + interface Jasmine { + Spec: Spec; + clock: Clock; + util: Util; + } + + export var HtmlReporter: HtmlReporter; + export var HtmlSpecFilter: HtmlSpecFilter; + export var DEFAULT_TIMEOUT_INTERVAL: number; +} diff --git a/angular1/app/typings/jquery/jquery.d.ts b/angular1/app/typings/jquery/jquery.d.ts new file mode 100644 index 0000000..4653239 --- /dev/null +++ b/angular1/app/typings/jquery/jquery.d.ts @@ -0,0 +1,3170 @@ +// Type definitions for jQuery 1.10.x / 2.0.x +// Project: http://jquery.com/ +// Definitions by: Boris Yankov , Christian Hoffmeister , Steve Fenton , Diullei Gomes , Tass Iliopoulos , Jason Swearingen , Sean Hill , Guus Goossens , Kelly Summerlin , Basarat Ali Syed , Nicholas Wolverson , Derek Cicerone , Andrew Gaspar , James Harrison Fisher , Seikichi Kondo , Benjamin Jackman , Poul Sorensen , Josh Strobl , John Reilly , Dick van den Brink +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + +/** + * Interface for the AJAX setting that will configure the AJAX request + */ +interface JQueryAjaxSettings { + /** + * The content type sent in the request header that tells the server what kind of response it will accept in return. If the accepts setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. + */ + accepts?: any; + /** + * By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success(). + */ + async?: boolean; + /** + * A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request. + */ + beforeSend? (jqXHR: JQueryXHR, settings: JQueryAjaxSettings): any; + /** + * If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET. + */ + cache?: boolean; + /** + * A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. + */ + complete? (jqXHR: JQueryXHR, textStatus: string): any; + /** + * An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type. (version added: 1.5) + */ + contents?: { [key: string]: any; }; + //According to jQuery.ajax source code, ajax's option actually allows contentType to set to "false" + // https://github.com/borisyankov/DefinitelyTyped/issues/742 + /** + * When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. + */ + contentType?: any; + /** + * This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). + */ + context?: any; + /** + * An object containing dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response. (version added: 1.5) + */ + converters?: { [key: string]: any; }; + /** + * If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain. (version added: 1.5) + */ + crossDomain?: boolean; + /** + * Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). + */ + data?: any; + /** + * A function to be used to handle the raw response data of XMLHttpRequest.This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter. + */ + dataFilter? (data: any, ty: any): any; + /** + * The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). + */ + dataType?: string; + /** + * A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event. + */ + error? (jqXHR: JQueryXHR, textStatus: string, errorThrown: string): any; + /** + * Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events. + */ + global?: boolean; + /** + * An object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport. The header X-Requested-With: XMLHttpRequest is always added, but its default XMLHttpRequest value can be changed here. Values in the headers setting can also be overwritten from within the beforeSend function. (version added: 1.5) + */ + headers?: { [key: string]: any; }; + /** + * Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data. + */ + ifModified?: boolean; + /** + * Allow the current environment to be recognized as "local," (e.g. the filesystem), even if jQuery does not recognize it as such by default. The following protocols are currently recognized as local: file, *-extension, and widget. If the isLocal setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. (version added: 1.5.1) + */ + isLocal?: boolean; + /** + * Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" } + */ + jsonp?: any; + /** + * Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function. + */ + jsonpCallback?: any; + /** + * A mime type to override the XHR mime type. (version added: 1.5.1) + */ + mimeType?: string; + /** + * A password to be used with XMLHttpRequest in response to an HTTP access authentication request. + */ + password?: string; + /** + * By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false. + */ + processData?: boolean; + /** + * Only applies when the "script" transport is used (e.g., cross-domain requests with "jsonp" or "script" dataType and "GET" type). Sets the charset attribute on the script tag used in the request. Used when the character set on the local page is not the same as the one on the remote script. + */ + scriptCharset?: string; + /** + * An object of numeric HTTP codes and functions to be called when the response has the corresponding code. f the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback. (version added: 1.5) + */ + statusCode?: { [key: string]: any; }; + /** + * A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. + */ + success? (data: any, textStatus: string, jqXHR: JQueryXHR): any; + /** + * Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period. + */ + timeout?: number; + /** + * Set this to true if you wish to use the traditional style of param serialization. + */ + traditional?: boolean; + /** + * The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers. + */ + type?: string; + /** + * A string containing the URL to which the request is sent. + */ + url?: string; + /** + * A username to be used with XMLHttpRequest in response to an HTTP access authentication request. + */ + username?: string; + /** + * Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory. + */ + xhr?: any; + /** + * An object of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed. In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it. (version added: 1.5.1) + */ + xhrFields?: { [key: string]: any; }; +} + +/** + * Interface for the jqXHR object + */ +interface JQueryXHR extends XMLHttpRequest, JQueryPromise { + /** + * The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header. As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). + */ + overrideMimeType(mimeType: string): any; + /** + * Cancel the request. + * + * @param statusText A string passed as the textStatus parameter for the done callback. Default value: "canceled" + */ + abort(statusText?: string): void; + /** + * Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details. + */ + then(doneCallback: (data: any, textStatus: string, jqXHR: JQueryXHR) => void, failCallback?: (jqXHR: JQueryXHR, textStatus: string, errorThrown: any) => void): JQueryPromise; + /** + * Property containing the parsed response if the response Content-Type is json + */ + responseJSON?: any; +} + +/** + * Interface for the JQuery callback + */ +interface JQueryCallback { + /** + * Add a callback or a collection of callbacks to a callback list. + * + * @param callbacks A function, or array of functions, that are to be added to the callback list. + */ + add(callbacks: Function): JQueryCallback; + /** + * Add a callback or a collection of callbacks to a callback list. + * + * @param callbacks A function, or array of functions, that are to be added to the callback list. + */ + add(callbacks: Function[]): JQueryCallback; + + /** + * Disable a callback list from doing anything more. + */ + disable(): JQueryCallback; + + /** + * Determine if the callbacks list has been disabled. + */ + disabled(): boolean; + + /** + * Remove all of the callbacks from a list. + */ + empty(): JQueryCallback; + + /** + * Call all of the callbacks with the given arguments + * + * @param arguments The argument or list of arguments to pass back to the callback list. + */ + fire(...arguments: any[]): JQueryCallback; + + /** + * Determine if the callbacks have already been called at least once. + */ + fired(): boolean; + + /** + * Call all callbacks in a list with the given context and arguments. + * + * @param context A reference to the context in which the callbacks in the list should be fired. + * @param arguments An argument, or array of arguments, to pass to the callbacks in the list. + */ + fireWith(context?: any, ...args: any[]): JQueryCallback; + + /** + * Determine whether a supplied callback is in a list + * + * @param callback The callback to search for. + */ + has(callback: Function): boolean; + + /** + * Lock a callback list in its current state. + */ + lock(): JQueryCallback; + + /** + * Determine if the callbacks list has been locked. + */ + locked(): boolean; + + /** + * Remove a callback or a collection of callbacks from a callback list. + * + * @param callbacks A function, or array of functions, that are to be removed from the callback list. + */ + remove(callbacks: Function): JQueryCallback; + /** + * Remove a callback or a collection of callbacks from a callback list. + * + * @param callbacks A function, or array of functions, that are to be removed from the callback list. + */ + remove(callbacks: Function[]): JQueryCallback; +} + +/** + * Allows jQuery Promises to interop with non-jQuery promises + */ +interface JQueryGenericPromise { + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + */ + then(doneFilter: (value?: T, ...values: any[]) => U|JQueryPromise, failFilter?: (...reasons: any[]) => any, progressFilter?: (...progression: any[]) => any): JQueryPromise; + + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + */ + then(doneFilter: (value?: T, ...values: any[]) => void, failFilter?: (...reasons: any[]) => any, progressFilter?: (...progression: any[]) => any): JQueryPromise; +} + +/** + * Interface for the JQuery promise/deferred callbacks + */ +interface JQueryPromiseCallback { + (value?: T, ...args: any[]): void; +} + +interface JQueryPromiseOperator { + (callback1: JQueryPromiseCallback|JQueryPromiseCallback[], ...callbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; +} + +/** + * Interface for the JQuery promise, part of callbacks + */ +interface JQueryPromise extends JQueryGenericPromise { + /** + * Determine the current state of a Deferred object. + */ + state(): string; + /** + * Add handlers to be called when the Deferred object is either resolved or rejected. + * + * @param alwaysCallbacks1 A function, or array of functions, that is called when the Deferred is resolved or rejected. + * @param alwaysCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. + */ + always(alwaysCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...alwaysCallbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; + /** + * Add handlers to be called when the Deferred object is resolved. + * + * @param doneCallbacks1 A function, or array of functions, that are called when the Deferred is resolved. + * @param doneCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. + */ + done(doneCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...doneCallbackN: Array|JQueryPromiseCallback[]>): JQueryPromise; + /** + * Add handlers to be called when the Deferred object is rejected. + * + * @param failCallbacks1 A function, or array of functions, that are called when the Deferred is rejected. + * @param failCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. + */ + fail(failCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...failCallbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; + /** + * Add handlers to be called when the Deferred object generates progress notifications. + * + * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications. + */ + progress(progressCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...progressCallbackN: Array|JQueryPromiseCallback[]>): JQueryPromise; + + // Deprecated - given no typings + pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; +} + +/** + * Interface for the JQuery deferred, part of callbacks + */ +interface JQueryDeferred extends JQueryGenericPromise { + /** + * Determine the current state of a Deferred object. + */ + state(): string; + /** + * Add handlers to be called when the Deferred object is either resolved or rejected. + * + * @param alwaysCallbacks1 A function, or array of functions, that is called when the Deferred is resolved or rejected. + * @param alwaysCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. + */ + always(alwaysCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...alwaysCallbacksN: Array|JQueryPromiseCallback[]>): JQueryDeferred; + /** + * Add handlers to be called when the Deferred object is resolved. + * + * @param doneCallbacks1 A function, or array of functions, that are called when the Deferred is resolved. + * @param doneCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. + */ + done(doneCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...doneCallbackN: Array|JQueryPromiseCallback[]>): JQueryDeferred; + /** + * Add handlers to be called when the Deferred object is rejected. + * + * @param failCallbacks1 A function, or array of functions, that are called when the Deferred is rejected. + * @param failCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. + */ + fail(failCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...failCallbacksN: Array|JQueryPromiseCallback[]>): JQueryDeferred; + /** + * Add handlers to be called when the Deferred object generates progress notifications. + * + * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications. + */ + progress(progressCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...progressCallbackN: Array|JQueryPromiseCallback[]>): JQueryDeferred; + + /** + * Call the progressCallbacks on a Deferred object with the given args. + * + * @param args Optional arguments that are passed to the progressCallbacks. + */ + notify(value?: any, ...args: any[]): JQueryDeferred; + + /** + * Call the progressCallbacks on a Deferred object with the given context and args. + * + * @param context Context passed to the progressCallbacks as the this object. + * @param args Optional arguments that are passed to the progressCallbacks. + */ + notifyWith(context: any, value?: any, ...args: any[]): JQueryDeferred; + + /** + * Reject a Deferred object and call any failCallbacks with the given args. + * + * @param args Optional arguments that are passed to the failCallbacks. + */ + reject(value?: any, ...args: any[]): JQueryDeferred; + /** + * Reject a Deferred object and call any failCallbacks with the given context and args. + * + * @param context Context passed to the failCallbacks as the this object. + * @param args An optional array of arguments that are passed to the failCallbacks. + */ + rejectWith(context: any, value?: any, ...args: any[]): JQueryDeferred; + + /** + * Resolve a Deferred object and call any doneCallbacks with the given args. + * + * @param value First argument passed to doneCallbacks. + * @param args Optional subsequent arguments that are passed to the doneCallbacks. + */ + resolve(value?: T, ...args: any[]): JQueryDeferred; + + /** + * Resolve a Deferred object and call any doneCallbacks with the given context and args. + * + * @param context Context passed to the doneCallbacks as the this object. + * @param args An optional array of arguments that are passed to the doneCallbacks. + */ + resolveWith(context: any, value?: T, ...args: any[]): JQueryDeferred; + + /** + * Return a Deferred's Promise object. + * + * @param target Object onto which the promise methods have to be attached + */ + promise(target?: any): JQueryPromise; + + // Deprecated - given no typings + pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; +} + +/** + * Interface of the JQuery extension of the W3C event object + */ +interface BaseJQueryEventObject extends Event { + data: any; + delegateTarget: Element; + isDefaultPrevented(): boolean; + isImmediatePropagationStopped(): boolean; + isPropagationStopped(): boolean; + namespace: string; + originalEvent: Event; + preventDefault(): any; + relatedTarget: Element; + result: any; + stopImmediatePropagation(): void; + stopPropagation(): void; + target: Element; + pageX: number; + pageY: number; + which: number; + metaKey: boolean; +} + +interface JQueryInputEventObject extends BaseJQueryEventObject { + altKey: boolean; + ctrlKey: boolean; + metaKey: boolean; + shiftKey: boolean; +} + +interface JQueryMouseEventObject extends JQueryInputEventObject { + button: number; + clientX: number; + clientY: number; + offsetX: number; + offsetY: number; + pageX: number; + pageY: number; + screenX: number; + screenY: number; +} + +interface JQueryKeyEventObject extends JQueryInputEventObject { + char: any; + charCode: number; + key: any; + keyCode: number; +} + +interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject{ +} + +/* + Collection of properties of the current browser +*/ + +interface JQuerySupport { + ajax?: boolean; + boxModel?: boolean; + changeBubbles?: boolean; + checkClone?: boolean; + checkOn?: boolean; + cors?: boolean; + cssFloat?: boolean; + hrefNormalized?: boolean; + htmlSerialize?: boolean; + leadingWhitespace?: boolean; + noCloneChecked?: boolean; + noCloneEvent?: boolean; + opacity?: boolean; + optDisabled?: boolean; + optSelected?: boolean; + scriptEval? (): boolean; + style?: boolean; + submitBubbles?: boolean; + tbody?: boolean; +} + +interface JQueryParam { + /** + * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. + * + * @param obj An array or object to serialize. + */ + (obj: any): string; + + /** + * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. + * + * @param obj An array or object to serialize. + * @param traditional A Boolean indicating whether to perform a traditional "shallow" serialization. + */ + (obj: any, traditional: boolean): string; +} + +/** + * The interface used to construct jQuery events (with $.Event). It is + * defined separately instead of inline in JQueryStatic to allow + * overriding the construction function with specific strings + * returning specific event objects. + */ +interface JQueryEventConstructor { + (name: string, eventProperties?: any): JQueryEventObject; + new (name: string, eventProperties?: any): JQueryEventObject; +} + +/** + * The interface used to specify coordinates. + */ +interface JQueryCoordinates { + left: number; + top: number; +} + +/** + * Elements in the array returned by serializeArray() + */ +interface JQuerySerializeArrayElement { + name: string; + value: string; +} + +interface JQueryAnimationOptions { + /** + * A string or number determining how long the animation will run. + */ + duration?: any; + /** + * A string indicating which easing function to use for the transition. + */ + easing?: string; + /** + * A function to call once the animation is complete. + */ + complete?: Function; + /** + * A function to be called for each animated property of each animated element. This function provides an opportunity to modify the Tween object to change the value of the property before it is set. + */ + step?: (now: number, tween: any) => any; + /** + * A function to be called after each step of the animation, only once per animated element regardless of the number of animated properties. (version added: 1.8) + */ + progress?: (animation: JQueryPromise, progress: number, remainingMs: number) => any; + /** + * A function to call when the animation begins. (version added: 1.8) + */ + start?: (animation: JQueryPromise) => any; + /** + * A function to be called when the animation completes (its Promise object is resolved). (version added: 1.8) + */ + done?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; + /** + * A function to be called when the animation fails to complete (its Promise object is rejected). (version added: 1.8) + */ + fail?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; + /** + * A function to be called when the animation completes or stops without completing (its Promise object is either resolved or rejected). (version added: 1.8) + */ + always?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; + /** + * A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case the animation is added to the queue represented by that string. When a custom queue name is used the animation does not automatically start; you must call .dequeue("queuename") to start it. + */ + queue?: any; + /** + * A map of one or more of the CSS properties defined by the properties argument and their corresponding easing functions. (version added: 1.4) + */ + specialEasing?: Object; +} + +/** + * Static members of jQuery (those on $ and jQuery themselves) + */ +interface JQueryStatic { + + /** + * Perform an asynchronous HTTP (Ajax) request. + * + * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). + */ + ajax(settings: JQueryAjaxSettings): JQueryXHR; + /** + * Perform an asynchronous HTTP (Ajax) request. + * + * @param url A string containing the URL to which the request is sent. + * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). + */ + ajax(url: string, settings?: JQueryAjaxSettings): JQueryXHR; + + /** + * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). + * + * @param dataTypes An optional string containing one or more space-separated dataTypes + * @param handler A handler to set default values for future Ajax requests. + */ + ajaxPrefilter(dataTypes: string, handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; + /** + * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). + * + * @param handler A handler to set default values for future Ajax requests. + */ + ajaxPrefilter(handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; + + ajaxSettings: JQueryAjaxSettings; + + /** + * Set default values for future Ajax requests. Its use is not recommended. + * + * @param options A set of key/value pairs that configure the default Ajax request. All options are optional. + */ + ajaxSetup(options: JQueryAjaxSettings): void; + + /** + * Load data from the server using a HTTP GET request. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). + */ + get(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + /** + * Load data from the server using a HTTP GET request. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). + */ + get(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + /** + * Load JSON-encoded data from the server using a GET HTTP request. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. + */ + getJSON(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; + /** + * Load JSON-encoded data from the server using a GET HTTP request. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. + */ + getJSON(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; + /** + * Load a JavaScript file from the server using a GET HTTP request, then execute it. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. + */ + getScript(url: string, success?: (script: string, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; + + /** + * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. + */ + param: JQueryParam; + + /** + * Load data from the server using a HTTP POST request. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). + */ + post(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + /** + * Load data from the server using a HTTP POST request. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). + */ + post(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + + /** + * A multi-purpose callbacks list object that provides a powerful way to manage callback lists. + * + * @param flags An optional list of space-separated flags that change how the callback list behaves. + */ + Callbacks(flags?: string): JQueryCallback; + + /** + * Holds or releases the execution of jQuery's ready event. + * + * @param hold Indicates whether the ready hold is being requested or released + */ + holdReady(hold: boolean): void; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param selector A string containing a selector expression + * @param context A DOM Element, Document, or jQuery to use as context + */ + (selector: string, context?: Element|JQuery): JQuery; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param element A DOM element to wrap in a jQuery object. + */ + (element: Element): JQuery; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param elementArray An array containing a set of DOM elements to wrap in a jQuery object. + */ + (elementArray: Element[]): JQuery; + + /** + * Binds a function to be executed when the DOM has finished loading. + * + * @param callback A function to execute after the DOM is ready. + */ + (callback: (jQueryAlias?: JQueryStatic) => any): JQuery; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param object A plain object to wrap in a jQuery object. + */ + (object: {}): JQuery; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param object An existing jQuery object to clone. + */ + (object: JQuery): JQuery; + + /** + * Specify a function to execute when the DOM is fully loaded. + */ + (): JQuery; + + /** + * Creates DOM elements on the fly from the provided string of raw HTML. + * + * @param html A string of HTML to create on the fly. Note that this parses HTML, not XML. + * @param ownerDocument A document in which the new elements will be created. + */ + (html: string, ownerDocument?: Document): JQuery; + + /** + * Creates DOM elements on the fly from the provided string of raw HTML. + * + * @param html A string defining a single, standalone, HTML element (e.g.
or
). + * @param attributes An object of attributes, events, and methods to call on the newly-created element. + */ + (html: string, attributes: Object): JQuery; + + /** + * Relinquish jQuery's control of the $ variable. + * + * @param removeAll A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself). + */ + noConflict(removeAll?: boolean): Object; + + /** + * Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. + * + * @param deferreds One or more Deferred objects, or plain JavaScript objects. + */ + when(...deferreds: Array/* as JQueryDeferred */>): JQueryPromise; + + /** + * Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize CSS property naming, or create custom properties. + */ + cssHooks: { [key: string]: any; }; + cssNumber: any; + + /** + * Store arbitrary data associated with the specified element. Returns the value that was set. + * + * @param element The DOM element to associate with the data. + * @param key A string naming the piece of data to set. + * @param value The new data value. + */ + data(element: Element, key: string, value: T): T; + /** + * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. + * + * @param element The DOM element to associate with the data. + * @param key A string naming the piece of data to set. + */ + data(element: Element, key: string): any; + /** + * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. + * + * @param element The DOM element to associate with the data. + */ + data(element: Element): any; + + /** + * Execute the next function on the queue for the matched element. + * + * @param element A DOM element from which to remove and execute a queued function. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + dequeue(element: Element, queueName?: string): void; + + /** + * Determine whether an element has any jQuery data associated with it. + * + * @param element A DOM element to be checked for data. + */ + hasData(element: Element): boolean; + + /** + * Show the queue of functions to be executed on the matched element. + * + * @param element A DOM element to inspect for an attached queue. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + queue(element: Element, queueName?: string): any[]; + /** + * Manipulate the queue of functions to be executed on the matched element. + * + * @param element A DOM element where the array of queued functions is attached. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param newQueue An array of functions to replace the current queue contents. + */ + queue(element: Element, queueName: string, newQueue: Function[]): JQuery; + /** + * Manipulate the queue of functions to be executed on the matched element. + * + * @param element A DOM element on which to add a queued function. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param callback The new function to add to the queue. + */ + queue(element: Element, queueName: string, callback: Function): JQuery; + + /** + * Remove a previously-stored piece of data. + * + * @param element A DOM element from which to remove data. + * @param name A string naming the piece of data to remove. + */ + removeData(element: Element, name?: string): JQuery; + + /** + * A constructor function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function. + * + * @param beforeStart A function that is called just before the constructor returns. + */ + Deferred(beforeStart?: (deferred: JQueryDeferred) => any): JQueryDeferred; + + /** + * Effects + */ + fx: { + tick: () => void; + /** + * The rate (in milliseconds) at which animations fire. + */ + interval: number; + stop: () => void; + speeds: { slow: number; fast: number; }; + /** + * Globally disable all animations. + */ + off: boolean; + step: any; + }; + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fnction The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @param additionalArguments Any number of arguments to be passed to the function referenced in the function argument. + */ + proxy(fnction: (...args: any[]) => any, context: Object, ...additionalArguments: any[]): any; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param context The object to which the context (this) of the function should be set. + * @param name The name of the function whose context will be changed (should be a property of the context object). + * @param additionalArguments Any number of arguments to be passed to the function named in the name argument. + */ + proxy(context: Object, name: string, ...additionalArguments: any[]): any; + + Event: JQueryEventConstructor; + + /** + * Takes a string and throws an exception containing it. + * + * @param message The message to send out. + */ + error(message: any): JQuery; + + expr: any; + fn: any; //TODO: Decide how we want to type this + + isReady: boolean; + + // Properties + support: JQuerySupport; + + /** + * Check to see if a DOM element is a descendant of another DOM element. + * + * @param container The DOM element that may contain the other element. + * @param contained The DOM element that may be contained by (a descendant of) the other element. + */ + contains(container: Element, contained: Element): boolean; + + /** + * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. + * + * @param collection The object or array to iterate over. + * @param callback The function that will be executed on every object. + */ + each( + collection: T[], + callback: (indexInArray: number, valueOfElement: T) => any + ): any; + + /** + * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. + * + * @param collection The object or array to iterate over. + * @param callback The function that will be executed on every object. + */ + each( + collection: any, + callback: (indexInArray: any, valueOfElement: any) => any + ): any; + + /** + * Merge the contents of two or more objects together into the first object. + * + * @param target An object that will receive the new properties if additional objects are passed in or that will extend the jQuery namespace if it is the sole argument. + * @param object1 An object containing additional properties to merge in. + * @param objectN Additional objects containing properties to merge in. + */ + extend(target: any, object1?: any, ...objectN: any[]): any; + /** + * Merge the contents of two or more objects together into the first object. + * + * @param deep If true, the merge becomes recursive (aka. deep copy). + * @param target The object to extend. It will receive the new properties. + * @param object1 An object containing additional properties to merge in. + * @param objectN Additional objects containing properties to merge in. + */ + extend(deep: boolean, target: any, object1?: any, ...objectN: any[]): any; + + /** + * Execute some JavaScript code globally. + * + * @param code The JavaScript code to execute. + */ + globalEval(code: string): any; + + /** + * Finds the elements of an array which satisfy a filter function. The original array is not affected. + * + * @param array The array to search through. + * @param func The function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value. this will be the global window object. + * @param invert If "invert" is false, or not provided, then the function returns an array consisting of all elements for which "callback" returns true. If "invert" is true, then the function returns an array consisting of all elements for which "callback" returns false. + */ + grep(array: T[], func: (elementOfArray: T, indexInArray: number) => boolean, invert?: boolean): T[]; + + /** + * Search for a specified value within an array and return its index (or -1 if not found). + * + * @param value The value to search for. + * @param array An array through which to search. + * @param fromIndex he index of the array at which to begin the search. The default is 0, which will search the whole array. + */ + inArray(value: T, array: T[], fromIndex?: number): number; + + /** + * Determine whether the argument is an array. + * + * @param obj Object to test whether or not it is an array. + */ + isArray(obj: any): boolean; + /** + * Check to see if an object is empty (contains no enumerable properties). + * + * @param obj The object that will be checked to see if it's empty. + */ + isEmptyObject(obj: any): boolean; + /** + * Determine if the argument passed is a Javascript function object. + * + * @param obj Object to test whether or not it is a function. + */ + isFunction(obj: any): boolean; + /** + * Determines whether its argument is a number. + * + * @param obj The value to be tested. + */ + isNumeric(value: any): boolean; + /** + * Check to see if an object is a plain object (created using "{}" or "new Object"). + * + * @param obj The object that will be checked to see if it's a plain object. + */ + isPlainObject(obj: any): boolean; + /** + * Determine whether the argument is a window. + * + * @param obj Object to test whether or not it is a window. + */ + isWindow(obj: any): boolean; + /** + * Check to see if a DOM node is within an XML document (or is an XML document). + * + * @param node he DOM node that will be checked to see if it's in an XML document. + */ + isXMLDoc(node: Node): boolean; + + /** + * Convert an array-like object into a true JavaScript array. + * + * @param obj Any object to turn into a native Array. + */ + makeArray(obj: any): any[]; + + /** + * Translate all items in an array or object to new array of items. + * + * @param array The Array to translate. + * @param callback The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. Within the function, this refers to the global (window) object. + */ + map(array: T[], callback: (elementOfArray: T, indexInArray: number) => U): U[]; + /** + * Translate all items in an array or object to new array of items. + * + * @param arrayOrObject The Array or Object to translate. + * @param callback The function to process each item against. The first argument to the function is the value; the second argument is the index or key of the array or object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object. + */ + map(arrayOrObject: any, callback: (value: any, indexOrKey: any) => any): any; + + /** + * Merge the contents of two arrays together into the first array. + * + * @param first The first array to merge, the elements of second added. + * @param second The second array to merge into the first, unaltered. + */ + merge(first: T[], second: T[]): T[]; + + /** + * An empty function. + */ + noop(): any; + + /** + * Return a number representing the current time. + */ + now(): number; + + /** + * Takes a well-formed JSON string and returns the resulting JavaScript object. + * + * @param json The JSON string to parse. + */ + parseJSON(json: string): any; + + /** + * Parses a string into an XML document. + * + * @param data a well-formed XML string to be parsed + */ + parseXML(data: string): XMLDocument; + + /** + * Remove the whitespace from the beginning and end of a string. + * + * @param str Remove the whitespace from the beginning and end of a string. + */ + trim(str: string): string; + + /** + * Determine the internal JavaScript [[Class]] of an object. + * + * @param obj Object to get the internal JavaScript [[Class]] of. + */ + type(obj: any): string; + + /** + * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers. + * + * @param array The Array of DOM elements. + */ + unique(array: Element[]): Element[]; + + /** + * Parses a string into an array of DOM nodes. + * + * @param data HTML string to be parsed + * @param context DOM element to serve as the context in which the HTML fragment will be created + * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string + */ + parseHTML(data: string, context?: HTMLElement, keepScripts?: boolean): any[]; + + /** + * Parses a string into an array of DOM nodes. + * + * @param data HTML string to be parsed + * @param context DOM element to serve as the context in which the HTML fragment will be created + * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string + */ + parseHTML(data: string, context?: Document, keepScripts?: boolean): any[]; +} + +/** + * The jQuery instance members + */ +interface JQuery { + /** + * Register a handler to be called when Ajax requests complete. This is an AjaxEvent. + * + * @param handler The function to be invoked. + */ + ajaxComplete(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: any) => any): JQuery; + /** + * Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxError(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxSettings: JQueryAjaxSettings, thrownError: any) => any): JQuery; + /** + * Attach a function to be executed before an Ajax request is sent. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxSend(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxOptions: JQueryAjaxSettings) => any): JQuery; + /** + * Register a handler to be called when the first Ajax request begins. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxStart(handler: () => any): JQuery; + /** + * Register a handler to be called when all Ajax requests have completed. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxStop(handler: () => any): JQuery; + /** + * Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxSuccess(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: JQueryAjaxSettings) => any): JQuery; + + /** + * Load data from the server and place the returned HTML into the matched element. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param complete A callback function that is executed when the request completes. + */ + load(url: string, data?: string|Object, complete?: (responseText: string, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any): JQuery; + + /** + * Encode a set of form elements as a string for submission. + */ + serialize(): string; + /** + * Encode a set of form elements as an array of names and values. + */ + serializeArray(): JQuerySerializeArrayElement[]; + + /** + * Adds the specified class(es) to each of the set of matched elements. + * + * @param className One or more space-separated classes to be added to the class attribute of each matched element. + */ + addClass(className: string): JQuery; + /** + * Adds the specified class(es) to each of the set of matched elements. + * + * @param function A function returning one or more space-separated class names to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function, this refers to the current element in the set. + */ + addClass(func: (index: number, className: string) => string): JQuery; + + /** + * Add the previous set of elements on the stack to the current set, optionally filtered by a selector. + */ + addBack(selector?: string): JQuery; + + /** + * Get the value of an attribute for the first element in the set of matched elements. + * + * @param attributeName The name of the attribute to get. + */ + attr(attributeName: string): string; + /** + * Set one or more attributes for the set of matched elements. + * + * @param attributeName The name of the attribute to set. + * @param value A value to set for the attribute. + */ + attr(attributeName: string, value: string|number): JQuery; + /** + * Set one or more attributes for the set of matched elements. + * + * @param attributeName The name of the attribute to set. + * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments. + */ + attr(attributeName: string, func: (index: number, attr: string) => string|number): JQuery; + /** + * Set one or more attributes for the set of matched elements. + * + * @param attributes An object of attribute-value pairs to set. + */ + attr(attributes: Object): JQuery; + + /** + * Determine whether any of the matched elements are assigned the given class. + * + * @param className The class name to search for. + */ + hasClass(className: string): boolean; + + /** + * Get the HTML contents of the first element in the set of matched elements. + */ + html(): string; + /** + * Set the HTML contents of each element in the set of matched elements. + * + * @param htmlString A string of HTML to set as the content of each matched element. + */ + html(htmlString: string): JQuery; + /** + * Set the HTML contents of each element in the set of matched elements. + * + * @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. + */ + html(func: (index: number, oldhtml: string) => string): JQuery; + /** + * Set the HTML contents of each element in the set of matched elements. + * + * @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. + */ + + /** + * Get the value of a property for the first element in the set of matched elements. + * + * @param propertyName The name of the property to get. + */ + prop(propertyName: string): any; + /** + * Set one or more properties for the set of matched elements. + * + * @param propertyName The name of the property to set. + * @param value A value to set for the property. + */ + prop(propertyName: string, value: string|number|boolean): JQuery; + /** + * Set one or more properties for the set of matched elements. + * + * @param properties An object of property-value pairs to set. + */ + prop(properties: Object): JQuery; + /** + * Set one or more properties for the set of matched elements. + * + * @param propertyName The name of the property to set. + * @param func A function returning the value to set. Receives the index position of the element in the set and the old property value as arguments. Within the function, the keyword this refers to the current element. + */ + prop(propertyName: string, func: (index: number, oldPropertyValue: any) => any): JQuery; + + /** + * Remove an attribute from each element in the set of matched elements. + * + * @param attributeName An attribute to remove; as of version 1.7, it can be a space-separated list of attributes. + */ + removeAttr(attributeName: string): JQuery; + + /** + * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. + * + * @param className One or more space-separated classes to be removed from the class attribute of each matched element. + */ + removeClass(className?: string): JQuery; + /** + * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. + * + * @param function A function returning one or more space-separated class names to be removed. Receives the index position of the element in the set and the old class value as arguments. + */ + removeClass(func: (index: number, className: string) => string): JQuery; + + /** + * Remove a property for the set of matched elements. + * + * @param propertyName The name of the property to remove. + */ + removeProp(propertyName: string): JQuery; + + /** + * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. + * + * @param className One or more class names (separated by spaces) to be toggled for each element in the matched set. + * @param swtch A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed. + */ + toggleClass(className: string, swtch?: boolean): JQuery; + /** + * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. + * + * @param swtch A boolean value to determine whether the class should be added or removed. + */ + toggleClass(swtch?: boolean): JQuery; + /** + * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. + * + * @param func A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments. + * @param swtch A boolean value to determine whether the class should be added or removed. + */ + toggleClass(func: (index: number, className: string, swtch: boolean) => string, swtch?: boolean): JQuery; + + /** + * Get the current value of the first element in the set of matched elements. + */ + val(): any; + /** + * Set the value of each element in the set of matched elements. + * + * @param value A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked. + */ + val(value: string|string[]): JQuery; + /** + * Set the value of each element in the set of matched elements. + * + * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. + */ + val(func: (index: number, value: string) => string): JQuery; + + + /** + * Get the value of style properties for the first element in the set of matched elements. + * + * @param propertyName A CSS property. + */ + css(propertyName: string): string; + /** + * Set one or more CSS properties for the set of matched elements. + * + * @param propertyName A CSS property name. + * @param value A value to set for the property. + */ + css(propertyName: string, value: string|number): JQuery; + /** + * Set one or more CSS properties for the set of matched elements. + * + * @param propertyName A CSS property name. + * @param value A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. + */ + css(propertyName: string, value: (index: number, value: string) => string|number): JQuery; + /** + * Set one or more CSS properties for the set of matched elements. + * + * @param properties An object of property-value pairs to set. + */ + css(properties: Object): JQuery; + + /** + * Get the current computed height for the first element in the set of matched elements. + */ + height(): number; + /** + * Set the CSS height of every matched element. + * + * @param value An integer representing the number of pixels, or an integer with an optional unit of measure appended (as a string). + */ + height(value: number|string): JQuery; + /** + * Set the CSS height of every matched element. + * + * @param func A function returning the height to set. Receives the index position of the element in the set and the old height as arguments. Within the function, this refers to the current element in the set. + */ + height(func: (index: number, height: number) => number|string): JQuery; + + /** + * Get the current computed height for the first element in the set of matched elements, including padding but not border. + */ + innerHeight(): number; + + /** + * Sets the inner height on elements in the set of matched elements, including padding but not border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + innerHeight(height: number|string): JQuery; + + /** + * Get the current computed width for the first element in the set of matched elements, including padding but not border. + */ + innerWidth(): number; + + /** + * Sets the inner width on elements in the set of matched elements, including padding but not border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + innerWidth(width: number|string): JQuery; + + /** + * Get the current coordinates of the first element in the set of matched elements, relative to the document. + */ + offset(): JQueryCoordinates; + /** + * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. + * + * @param coordinates An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. + */ + offset(coordinates: JQueryCoordinates): JQuery; + /** + * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. + * + * @param func A function to return the coordinates to set. Receives the index of the element in the collection as the first argument and the current coordinates as the second argument. The function should return an object with the new top and left properties. + */ + offset(func: (index: number, coords: JQueryCoordinates) => JQueryCoordinates): JQuery; + + /** + * Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin. Returns an integer (without "px") representation of the value or null if called on an empty set of elements. + * + * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. + */ + outerHeight(includeMargin?: boolean): number; + + /** + * Sets the outer height on elements in the set of matched elements, including padding and border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + outerHeight(height: number|string): JQuery; + + /** + * Get the current computed width for the first element in the set of matched elements, including padding and border. + * + * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. + */ + outerWidth(includeMargin?: boolean): number; + + /** + * Sets the outer width on elements in the set of matched elements, including padding and border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + outerWidth(width: number|string): JQuery; + + /** + * Get the current coordinates of the first element in the set of matched elements, relative to the offset parent. + */ + position(): JQueryCoordinates; + + /** + * Get the current horizontal position of the scroll bar for the first element in the set of matched elements or set the horizontal position of the scroll bar for every matched element. + */ + scrollLeft(): number; + /** + * Set the current horizontal position of the scroll bar for each of the set of matched elements. + * + * @param value An integer indicating the new position to set the scroll bar to. + */ + scrollLeft(value: number): JQuery; + + /** + * Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element. + */ + scrollTop(): number; + /** + * Set the current vertical position of the scroll bar for each of the set of matched elements. + * + * @param value An integer indicating the new position to set the scroll bar to. + */ + scrollTop(value: number): JQuery; + + /** + * Get the current computed width for the first element in the set of matched elements. + */ + width(): number; + /** + * Set the CSS width of each element in the set of matched elements. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + width(value: number|string): JQuery; + /** + * Set the CSS width of each element in the set of matched elements. + * + * @param func A function returning the width to set. Receives the index position of the element in the set and the old width as arguments. Within the function, this refers to the current element in the set. + */ + width(func: (index: number, width: number) => number|string): JQuery; + + /** + * Remove from the queue all items that have not yet been run. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + clearQueue(queueName?: string): JQuery; + + /** + * Store arbitrary data associated with the matched elements. + * + * @param key A string naming the piece of data to set. + * @param value The new data value; it can be any Javascript type including Array or Object. + */ + data(key: string, value: any): JQuery; + /** + * Store arbitrary data associated with the matched elements. + * + * @param obj An object of key-value pairs of data to update. + */ + data(obj: { [key: string]: any; }): JQuery; + /** + * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. + * + * @param key Name of the data stored. + */ + data(key: string): any; + /** + * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. + */ + data(): any; + + /** + * Execute the next function on the queue for the matched elements. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + dequeue(queueName?: string): JQuery; + + /** + * Remove a previously-stored piece of data. + * + * @param name A string naming the piece of data to delete or space-separated string naming the pieces of data to delete. + */ + removeData(name: string): JQuery; + /** + * Remove a previously-stored piece of data. + * + * @param list An array of strings naming the pieces of data to delete. + */ + removeData(list: string[]): JQuery; + + /** + * Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished. + * + * @param type The type of queue that needs to be observed. (default: fx) + * @param target Object onto which the promise methods have to be attached + */ + promise(type?: string, target?: Object): JQueryPromise; + + /** + * Perform a custom animation of a set of CSS properties. + * + * @param properties An object of CSS properties and values that the animation will move toward. + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + animate(properties: Object, duration?: string|number, complete?: Function): JQuery; + /** + * Perform a custom animation of a set of CSS properties. + * + * @param properties An object of CSS properties and values that the animation will move toward. + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. (default: swing) + * @param complete A function to call once the animation is complete. + */ + animate(properties: Object, duration?: string|number, easing?: string, complete?: Function): JQuery; + /** + * Perform a custom animation of a set of CSS properties. + * + * @param properties An object of CSS properties and values that the animation will move toward. + * @param options A map of additional options to pass to the method. + */ + animate(properties: Object, options: JQueryAnimationOptions): JQuery; + + /** + * Set a timer to delay execution of subsequent items in the queue. + * + * @param duration An integer indicating the number of milliseconds to delay execution of the next item in the queue. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + delay(duration: number, queueName?: string): JQuery; + + /** + * Display the matched elements by fading them to opaque. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + fadeIn(duration?: number|string, complete?: Function): JQuery; + /** + * Display the matched elements by fading them to opaque. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeIn(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display the matched elements by fading them to opaque. + * + * @param options A map of additional options to pass to the method. + */ + fadeIn(options: JQueryAnimationOptions): JQuery; + + /** + * Hide the matched elements by fading them to transparent. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + fadeOut(duration?: number|string, complete?: Function): JQuery; + /** + * Hide the matched elements by fading them to transparent. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeOut(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Hide the matched elements by fading them to transparent. + * + * @param options A map of additional options to pass to the method. + */ + fadeOut(options: JQueryAnimationOptions): JQuery; + + /** + * Adjust the opacity of the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param opacity A number between 0 and 1 denoting the target opacity. + * @param complete A function to call once the animation is complete. + */ + fadeTo(duration: string|number, opacity: number, complete?: Function): JQuery; + /** + * Adjust the opacity of the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param opacity A number between 0 and 1 denoting the target opacity. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeTo(duration: string|number, opacity: number, easing?: string, complete?: Function): JQuery; + + /** + * Display or hide the matched elements by animating their opacity. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + fadeToggle(duration?: number|string, complete?: Function): JQuery; + /** + * Display or hide the matched elements by animating their opacity. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeToggle(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display or hide the matched elements by animating their opacity. + * + * @param options A map of additional options to pass to the method. + */ + fadeToggle(options: JQueryAnimationOptions): JQuery; + + /** + * Stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements. + * + * @param queue The name of the queue in which to stop animations. + */ + finish(queue?: string): JQuery; + + /** + * Hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + hide(duration?: number|string, complete?: Function): JQuery; + /** + * Hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + hide(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Hide the matched elements. + * + * @param options A map of additional options to pass to the method. + */ + hide(options: JQueryAnimationOptions): JQuery; + + /** + * Display the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + show(duration?: number|string, complete?: Function): JQuery; + /** + * Display the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + show(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display the matched elements. + * + * @param options A map of additional options to pass to the method. + */ + show(options: JQueryAnimationOptions): JQuery; + + /** + * Display the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + slideDown(duration?: number|string, complete?: Function): JQuery; + /** + * Display the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + slideDown(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display the matched elements with a sliding motion. + * + * @param options A map of additional options to pass to the method. + */ + slideDown(options: JQueryAnimationOptions): JQuery; + + /** + * Display or hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + slideToggle(duration?: number|string, complete?: Function): JQuery; + /** + * Display or hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + slideToggle(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display or hide the matched elements with a sliding motion. + * + * @param options A map of additional options to pass to the method. + */ + slideToggle(options: JQueryAnimationOptions): JQuery; + + /** + * Hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + slideUp(duration?: number|string, complete?: Function): JQuery; + /** + * Hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + slideUp(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Hide the matched elements with a sliding motion. + * + * @param options A map of additional options to pass to the method. + */ + slideUp(options: JQueryAnimationOptions): JQuery; + + /** + * Stop the currently-running animation on the matched elements. + * + * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. + * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. + */ + stop(clearQueue?: boolean, jumpToEnd?: boolean): JQuery; + /** + * Stop the currently-running animation on the matched elements. + * + * @param queue The name of the queue in which to stop animations. + * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. + * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. + */ + stop(queue?: string, clearQueue?: boolean, jumpToEnd?: boolean): JQuery; + + /** + * Display or hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + toggle(duration?: number|string, complete?: Function): JQuery; + /** + * Display or hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + toggle(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display or hide the matched elements. + * + * @param options A map of additional options to pass to the method. + */ + toggle(options: JQueryAnimationOptions): JQuery; + /** + * Display or hide the matched elements. + * + * @param showOrHide A Boolean indicating whether to show or hide the elements. + */ + toggle(showOrHide: boolean): JQuery; + + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + bind(eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param handler A function to execute each time the event is triggered. + */ + bind(eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param eventData An object containing data that will be passed to the event handler. + * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. + */ + bind(eventType: string, eventData: any, preventBubble: boolean): JQuery; + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. + */ + bind(eventType: string, preventBubble: boolean): JQuery; + /** + * Attach a handler to an event for the elements. + * + * @param events An object containing one or more DOM event types and functions to execute for them. + */ + bind(events: any): JQuery; + + /** + * Trigger the "blur" event on an element + */ + blur(): JQuery; + /** + * Bind an event handler to the "blur" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + blur(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "blur" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + blur(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "change" event on an element. + */ + change(): JQuery; + /** + * Bind an event handler to the "change" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + change(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "change" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + change(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "click" event on an element. + */ + click(): JQuery; + /** + * Bind an event handler to the "click" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + */ + click(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "click" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + click(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "dblclick" event on an element. + */ + dblclick(): JQuery; + /** + * Bind an event handler to the "dblclick" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + dblclick(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "dblclick" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + dblclick(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + delegate(selector: any, eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + delegate(selector: any, eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "focus" event on an element. + */ + focus(): JQuery; + /** + * Bind an event handler to the "focus" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + focus(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "focus" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + focus(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Bind an event handler to the "focusin" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + focusin(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "focusin" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + focusin(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Bind an event handler to the "focusout" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + focusout(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "focusout" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + focusout(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. + * + * @param handlerIn A function to execute when the mouse pointer enters the element. + * @param handlerOut A function to execute when the mouse pointer leaves the element. + */ + hover(handlerIn: (eventObject: JQueryEventObject) => any, handlerOut: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. + * + * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element. + */ + hover(handlerInOut: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "keydown" event on an element. + */ + keydown(): JQuery; + /** + * Bind an event handler to the "keydown" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + keydown(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; + /** + * Bind an event handler to the "keydown" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + keydown(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; + + /** + * Trigger the "keypress" event on an element. + */ + keypress(): JQuery; + /** + * Bind an event handler to the "keypress" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + keypress(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; + /** + * Bind an event handler to the "keypress" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + keypress(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; + + /** + * Trigger the "keyup" event on an element. + */ + keyup(): JQuery; + /** + * Bind an event handler to the "keyup" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + keyup(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; + /** + * Bind an event handler to the "keyup" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + keyup(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; + + /** + * Bind an event handler to the "load" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + load(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "load" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + load(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "mousedown" event on an element. + */ + mousedown(): JQuery; + /** + * Bind an event handler to the "mousedown" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mousedown(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "mousedown" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mousedown(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mouseenter" event on an element. + */ + mouseenter(): JQuery; + /** + * Bind an event handler to be fired when the mouse enters an element. + * + * @param handler A function to execute when the event is triggered. + */ + mouseenter(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to be fired when the mouse enters an element. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseenter(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mouseleave" event on an element. + */ + mouseleave(): JQuery; + /** + * Bind an event handler to be fired when the mouse leaves an element. + * + * @param handler A function to execute when the event is triggered. + */ + mouseleave(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to be fired when the mouse leaves an element. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseleave(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mousemove" event on an element. + */ + mousemove(): JQuery; + /** + * Bind an event handler to the "mousemove" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mousemove(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "mousemove" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mousemove(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mouseout" event on an element. + */ + mouseout(): JQuery; + /** + * Bind an event handler to the "mouseout" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mouseout(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "mouseout" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseout(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mouseover" event on an element. + */ + mouseover(): JQuery; + /** + * Bind an event handler to the "mouseover" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mouseover(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "mouseover" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseover(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mouseup" event on an element. + */ + mouseup(): JQuery; + /** + * Bind an event handler to the "mouseup" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mouseup(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "mouseup" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseup(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Remove an event handler. + */ + off(): JQuery; + /** + * Remove an event handler. + * + * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". + * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: string, selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Remove an event handler. + * + * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Remove an event handler. + * + * @param events An object where the string keys represent one or more space-separated event types and optional namespaces, and the values represent handler functions previously attached for the event(s). + * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. + */ + off(events: { [key: string]: any; }, selector?: string): JQuery; + + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: string, data : any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: string, selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + on(events: { [key: string]: any; }, selector?: string, data?: any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + on(events: { [key: string]: any; }, data?: any): JQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. + * @param handler A function to execute at the time the event is triggered. + */ + one(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. + * @param data An object containing data that will be passed to the event handler. + * @param handler A function to execute at the time the event is triggered. + */ + one(events: string, data: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + one(events: string, selector: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + one(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + one(events: { [key: string]: any; }, selector?: string, data?: any): JQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + one(events: { [key: string]: any; }, data?: any): JQuery; + + + /** + * Specify a function to execute when the DOM is fully loaded. + * + * @param handler A function to execute after the DOM is ready. + */ + ready(handler: (jQueryAlias?: JQueryStatic) => any): JQuery; + + /** + * Trigger the "resize" event on an element. + */ + resize(): JQuery; + /** + * Bind an event handler to the "resize" JavaScript event. + * + * @param handler A function to execute each time the event is triggered. + */ + resize(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "resize" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + resize(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "scroll" event on an element. + */ + scroll(): JQuery; + /** + * Bind an event handler to the "scroll" JavaScript event. + * + * @param handler A function to execute each time the event is triggered. + */ + scroll(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "scroll" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + scroll(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "select" event on an element. + */ + select(): JQuery; + /** + * Bind an event handler to the "select" JavaScript event. + * + * @param handler A function to execute each time the event is triggered. + */ + select(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "select" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + select(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "submit" event on an element. + */ + submit(): JQuery; + /** + * Bind an event handler to the "submit" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + submit(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "submit" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + submit(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Execute all handlers and behaviors attached to the matched elements for the given event type. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param extraParameters Additional parameters to pass along to the event handler. + */ + trigger(eventType: string, extraParameters?: any[]|Object): JQuery; + /** + * Execute all handlers and behaviors attached to the matched elements for the given event type. + * + * @param event A jQuery.Event object. + * @param extraParameters Additional parameters to pass along to the event handler. + */ + trigger(event: JQueryEventObject, extraParameters?: any[]|Object): JQuery; + + /** + * Execute all handlers attached to an element for an event. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param extraParameters An array of additional parameters to pass along to the event handler. + */ + triggerHandler(eventType: string, ...extraParameters: any[]): Object; + + /** + * Execute all handlers attached to an element for an event. + * + * @param event A jQuery.Event object. + * @param extraParameters An array of additional parameters to pass along to the event handler. + */ + triggerHandler(event: JQueryEventObject, ...extraParameters: any[]): Object; + + /** + * Remove a previously-attached event handler from the elements. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param handler The function that is to be no longer executed. + */ + unbind(eventType?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Remove a previously-attached event handler from the elements. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param fls Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ). + */ + unbind(eventType: string, fls: boolean): JQuery; + /** + * Remove a previously-attached event handler from the elements. + * + * @param evt A JavaScript event object as passed to an event handler. + */ + unbind(evt: any): JQuery; + + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + */ + undelegate(): JQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param selector A selector which will be used to filter the event results. + * @param eventType A string containing a JavaScript event type, such as "click" or "keydown" + * @param handler A function to execute at the time the event is triggered. + */ + undelegate(selector: string, eventType: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param selector A selector which will be used to filter the event results. + * @param events An object of one or more event types and previously bound functions to unbind from them. + */ + undelegate(selector: string, events: Object): JQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param namespace A string containing a namespace to unbind all events from. + */ + undelegate(namespace: string): JQuery; + + /** + * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) + * + * @param handler A function to execute when the event is triggered. + */ + unload(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) + * + * @param eventData A plain object of data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + unload(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document. (DEPRECATED from v1.10) + */ + context: Element; + + jquery: string; + + /** + * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) + * + * @param handler A function to execute when the event is triggered. + */ + error(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) + * + * @param eventData A plain object of data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + error(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Add a collection of DOM elements onto the jQuery stack. + * + * @param elements An array of elements to push onto the stack and make into a new jQuery object. + */ + pushStack(elements: any[]): JQuery; + /** + * Add a collection of DOM elements onto the jQuery stack. + * + * @param elements An array of elements to push onto the stack and make into a new jQuery object. + * @param name The name of a jQuery method that generated the array of elements. + * @param arguments The arguments that were passed in to the jQuery method (for serialization). + */ + pushStack(elements: any[], name: string, arguments: any[]): JQuery; + + /** + * Insert content, specified by the parameter, after each element in the set of matched elements. + * + * param content1 HTML string, DOM element, array of elements, or jQuery object to insert after each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements. + */ + after(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, after each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert after each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + after(func: (index: number, html: string) => string|Element|JQuery): JQuery; + + /** + * Insert content, specified by the parameter, to the end of each element in the set of matched elements. + * + * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements. + */ + append(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, to the end of each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. + */ + append(func: (index: number, html: string) => string|Element|JQuery): JQuery; + + /** + * Insert every element in the set of matched elements to the end of the target. + * + * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter. + */ + appendTo(target: JQuery|any[]|Element|string): JQuery; + + /** + * Insert content, specified by the parameter, before each element in the set of matched elements. + * + * param content1 HTML string, DOM element, array of elements, or jQuery object to insert before each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements. + */ + before(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, before each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert before each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + before(func: (index: number, html: string) => string|Element|JQuery): JQuery; + + /** + * Create a deep copy of the set of matched elements. + * + * param withDataAndEvents A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false. + * param deepWithDataAndEvents A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false). + */ + clone(withDataAndEvents?: boolean, deepWithDataAndEvents?: boolean): JQuery; + + /** + * Remove the set of matched elements from the DOM. + * + * param selector A selector expression that filters the set of matched elements to be removed. + */ + detach(selector?: string): JQuery; + + /** + * Remove all child nodes of the set of matched elements from the DOM. + */ + empty(): JQuery; + + /** + * Insert every element in the set of matched elements after the target. + * + * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter. + */ + insertAfter(target: JQuery|any[]|Element|Text|string): JQuery; + + /** + * Insert every element in the set of matched elements before the target. + * + * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter. + */ + insertBefore(target: JQuery|any[]|Element|Text|string): JQuery; + + /** + * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. + * + * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements. + */ + prepend(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the beginning of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. + */ + prepend(func: (index: number, html: string) => string|Element|JQuery): JQuery; + + /** + * Insert every element in the set of matched elements to the beginning of the target. + * + * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter. + */ + prependTo(target: JQuery|any[]|Element|string): JQuery; + + /** + * Remove the set of matched elements from the DOM. + * + * @param selector A selector expression that filters the set of matched elements to be removed. + */ + remove(selector?: string): JQuery; + + /** + * Replace each target element with the set of matched elements. + * + * @param target A selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace. + */ + replaceAll(target: JQuery|any[]|Element|string): JQuery; + + /** + * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. + * + * param newContent The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object. + */ + replaceWith(newContent: JQuery|any[]|Element|Text|string): JQuery; + /** + * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. + * + * param func A function that returns content with which to replace the set of matched elements. + */ + replaceWith(func: () => Element|JQuery): JQuery; + + /** + * Get the combined text contents of each element in the set of matched elements, including their descendants. + */ + text(): string; + /** + * Set the content of each element in the set of matched elements to the specified text. + * + * @param text The text to set as the content of each matched element. When Number or Boolean is supplied, it will be converted to a String representation. + */ + text(text: string|number|boolean): JQuery; + /** + * Set the content of each element in the set of matched elements to the specified text. + * + * @param func A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments. + */ + text(func: (index: number, text: string) => string): JQuery; + + /** + * Retrieve all the elements contained in the jQuery set, as an array. + */ + toArray(): any[]; + + /** + * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. + */ + unwrap(): JQuery; + + /** + * Wrap an HTML structure around each element in the set of matched elements. + * + * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. + */ + wrap(wrappingElement: JQuery|Element|string): JQuery; + /** + * Wrap an HTML structure around each element in the set of matched elements. + * + * @param func A callback function returning the HTML content or jQuery object to wrap around the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + wrap(func: (index: number) => string|JQuery): JQuery; + + /** + * Wrap an HTML structure around all elements in the set of matched elements. + * + * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. + */ + wrapAll(wrappingElement: JQuery|Element|string): JQuery; + wrapAll(func: (index: number) => string): JQuery; + + /** + * Wrap an HTML structure around the content of each element in the set of matched elements. + * + * @param wrappingElement An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements. + */ + wrapInner(wrappingElement: JQuery|Element|string): JQuery; + /** + * Wrap an HTML structure around the content of each element in the set of matched elements. + * + * @param func A callback function which generates a structure to wrap around the content of the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + wrapInner(func: (index: number) => string): JQuery; + + /** + * Iterate over a jQuery object, executing a function for each matched element. + * + * @param func A function to execute for each matched element. + */ + each(func: (index: number, elem: Element) => any): JQuery; + + /** + * Retrieve one of the elements matched by the jQuery object. + * + * @param index A zero-based integer indicating which element to retrieve. + */ + get(index: number): HTMLElement; + /** + * Retrieve the elements matched by the jQuery object. + */ + get(): any[]; + + /** + * Search for a given element from among the matched elements. + */ + index(): number; + /** + * Search for a given element from among the matched elements. + * + * @param selector A selector representing a jQuery collection in which to look for an element. + */ + index(selector: string|JQuery|Element): number; + + /** + * The number of elements in the jQuery object. + */ + length: number; + /** + * A selector representing selector passed to jQuery(), if any, when creating the original set. + * version deprecated: 1.7, removed: 1.9 + */ + selector: string; + [index: string]: any; + [index: number]: HTMLElement; + + /** + * Add elements to the set of matched elements. + * + * @param selector A string representing a selector expression to find additional elements to add to the set of matched elements. + * @param context The point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method. + */ + add(selector: string, context?: Element): JQuery; + /** + * Add elements to the set of matched elements. + * + * @param elements One or more elements to add to the set of matched elements. + */ + add(...elements: Element[]): JQuery; + /** + * Add elements to the set of matched elements. + * + * @param html An HTML fragment to add to the set of matched elements. + */ + add(html: string): JQuery; + /** + * Add elements to the set of matched elements. + * + * @param obj An existing jQuery object to add to the set of matched elements. + */ + add(obj: JQuery): JQuery; + + /** + * Get the children of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + children(selector?: string): JQuery; + + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param selector A string containing a selector expression to match elements against. + */ + closest(selector: string): JQuery; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param selector A string containing a selector expression to match elements against. + * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. + */ + closest(selector: string, context?: Element): JQuery; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param obj A jQuery object to match elements against. + */ + closest(obj: JQuery): JQuery; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param element An element to match elements against. + */ + closest(element: Element): JQuery; + + /** + * Get an array of all the elements and selectors matched against the current element up through the DOM tree. + * + * @param selectors An array or string containing a selector expression to match elements against (can also be a jQuery object). + * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. + */ + closest(selectors: any, context?: Element): any[]; + + /** + * Get the children of each element in the set of matched elements, including text and comment nodes. + */ + contents(): JQuery; + + /** + * End the most recent filtering operation in the current chain and return the set of matched elements to its previous state. + */ + end(): JQuery; + + /** + * Reduce the set of matched elements to the one at the specified index. + * + * @param index An integer indicating the 0-based position of the element. OR An integer indicating the position of the element, counting backwards from the last element in the set. + * + */ + eq(index: number): JQuery; + + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param selector A string containing a selector expression to match the current set of elements against. + */ + filter(selector: string): JQuery; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param func A function used as a test for each element in the set. this is the current DOM element. + */ + filter(func: (index: number, element: Element) => any): JQuery; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param element An element to match the current set of elements against. + */ + filter(element: Element): JQuery; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param obj An existing jQuery object to match the current set of elements against. + */ + filter(obj: JQuery): JQuery; + + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. + * + * @param selector A string containing a selector expression to match elements against. + */ + find(selector: string): JQuery; + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. + * + * @param element An element to match elements against. + */ + find(element: Element): JQuery; + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. + * + * @param obj A jQuery object to match elements against. + */ + find(obj: JQuery): JQuery; + + /** + * Reduce the set of matched elements to the first in the set. + */ + first(): JQuery; + + /** + * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. + * + * @param selector A string containing a selector expression to match elements against. + */ + has(selector: string): JQuery; + /** + * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. + * + * @param contained A DOM element to match elements against. + */ + has(contained: Element): JQuery; + + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param selector A string containing a selector expression to match elements against. + */ + is(selector: string): boolean; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param func A function used as a test for the set of elements. It accepts one argument, index, which is the element's index in the jQuery collection.Within the function, this refers to the current DOM element. + */ + is(func: (index: number, element: Element) => boolean): boolean; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param obj An existing jQuery object to match the current set of elements against. + */ + is(obj: JQuery): boolean; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param elements One or more elements to match the current set of elements against. + */ + is(elements: any): boolean; + + /** + * Reduce the set of matched elements to the final one in the set. + */ + last(): JQuery; + + /** + * Pass each element in the current matched set through a function, producing a new jQuery object containing the return values. + * + * @param callback A function object that will be invoked for each element in the current set. + */ + map(callback: (index: number, domElement: Element) => any): JQuery; + + /** + * Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + next(selector?: string): JQuery; + + /** + * Get all following siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + nextAll(selector?: string): JQuery; + + /** + * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. + * + * @param selector A string containing a selector expression to indicate where to stop matching following sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + nextUntil(selector?: string, filter?: string): JQuery; + /** + * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. + * + * @param element A DOM node or jQuery object indicating where to stop matching following sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + nextUntil(element?: Element, filter?: string): JQuery; + /** + * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. + * + * @param obj A DOM node or jQuery object indicating where to stop matching following sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + nextUntil(obj?: JQuery, filter?: string): JQuery; + + /** + * Remove elements from the set of matched elements. + * + * @param selector A string containing a selector expression to match elements against. + */ + not(selector: string): JQuery; + /** + * Remove elements from the set of matched elements. + * + * @param func A function used as a test for each element in the set. this is the current DOM element. + */ + not(func: (index: number, element: Element) => boolean): JQuery; + /** + * Remove elements from the set of matched elements. + * + * @param elements One or more DOM elements to remove from the matched set. + */ + not(...elements: Element[]): JQuery; + /** + * Remove elements from the set of matched elements. + * + * @param obj An existing jQuery object to match the current set of elements against. + */ + not(obj: JQuery): JQuery; + + /** + * Get the closest ancestor element that is positioned. + */ + offsetParent(): JQuery; + + /** + * Get the parent of each element in the current set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + parent(selector?: string): JQuery; + + /** + * Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + parents(selector?: string): JQuery; + + /** + * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param selector A string containing a selector expression to indicate where to stop matching ancestor elements. + * @param filter A string containing a selector expression to match elements against. + */ + parentsUntil(selector?: string, filter?: string): JQuery; + /** + * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param element A DOM node or jQuery object indicating where to stop matching ancestor elements. + * @param filter A string containing a selector expression to match elements against. + */ + parentsUntil(element?: Element, filter?: string): JQuery; + /** + * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param obj A DOM node or jQuery object indicating where to stop matching ancestor elements. + * @param filter A string containing a selector expression to match elements against. + */ + parentsUntil(obj?: JQuery, filter?: string): JQuery; + + /** + * Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + prev(selector?: string): JQuery; + + /** + * Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + prevAll(selector?: string): JQuery; + + /** + * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param selector A string containing a selector expression to indicate where to stop matching preceding sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + prevUntil(selector?: string, filter?: string): JQuery; + /** + * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param element A DOM node or jQuery object indicating where to stop matching preceding sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + prevUntil(element?: Element, filter?: string): JQuery; + /** + * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param obj A DOM node or jQuery object indicating where to stop matching preceding sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + prevUntil(obj?: JQuery, filter?: string): JQuery; + + /** + * Get the siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + siblings(selector?: string): JQuery; + + /** + * Reduce the set of matched elements to a subset specified by a range of indices. + * + * @param start An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set. + * @param end An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set. + */ + slice(start: number, end?: number): JQuery; + + /** + * Show the queue of functions to be executed on the matched elements. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + queue(queueName?: string): any[]; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param newQueue An array of functions to replace the current queue contents. + */ + queue(newQueue: Function[]): JQuery; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. + */ + queue(callback: Function): JQuery; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param newQueue An array of functions to replace the current queue contents. + */ + queue(queueName: string, newQueue: Function[]): JQuery; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. + */ + queue(queueName: string, callback: Function): JQuery; +} +declare module "jquery" { + export = $; +} +declare var jQuery: JQueryStatic; +declare var $: JQueryStatic; diff --git a/angular1/app/typings/karma-jasmine/karma-jasmine.d.ts b/angular1/app/typings/karma-jasmine/karma-jasmine.d.ts new file mode 100644 index 0000000..e4cdc5a --- /dev/null +++ b/angular1/app/typings/karma-jasmine/karma-jasmine.d.ts @@ -0,0 +1,9 @@ +// Type definitions for karma-jasmine plugin +// Project: https://github.com/karma-runner/karma-jasmine +// Definitions by: Michel Salib +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare function ddescribe(description: string, specDefinitions: () => void): void; +declare function iit(expectation: string, assertion: () => void): void; diff --git a/angular1/app/typings/selenium-webdriver/selenium-webdriver.d.ts b/angular1/app/typings/selenium-webdriver/selenium-webdriver.d.ts new file mode 100644 index 0000000..c4af933 --- /dev/null +++ b/angular1/app/typings/selenium-webdriver/selenium-webdriver.d.ts @@ -0,0 +1,4864 @@ +// Type definitions for Selenium WebDriverJS 2.44.0 +// Project: https://code.google.com/p/selenium/ +// Definitions by: Bill Armstrong +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module chrome { + /** + * Creates a new WebDriver client for Chrome. + * + * @extends {webdriver.WebDriver} + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(webdriver.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@link getDefaultService default service} by default. + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow to use, or + * {@code null} to use the currently active flow. + * @constructor + */ + constructor(opt_config?: webdriver.Capabilities, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: Options, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); + } + + interface IOptionsValues { + args: string[]; + binary?: string; + detach: boolean; + extensions: string[]; + localState?: any; + logFile?: string; + prefs?: any; + } + + /** + * Class for managing ChromeDriver specific options. + */ + class Options { + /** + * @constructor + */ + constructor(); + + /** + * Extracts the ChromeDriver specific options from the given capabilities + * object. + * @param {!webdriver.Capabilities} capabilities The capabilities object. + * @return {!Options} The ChromeDriver options. + */ + static fromCapabilities(capabilities: webdriver.Capabilities): Options; + + + /** + * Add additional command line arguments to use when launching the Chrome + * browser. Each argument may be specified with or without the "--" prefix + * (e.g. "--foo" and "foo"). Arguments with an associated value should be + * delimited by an "=": "foo=bar". + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: string[]): Options; + + + /** + * Add additional extensions to install when launching Chrome. Each extension + * should be specified as the path to the packed CRX file, or a Buffer for an + * extension. + * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The + * extensions to add. + * @return {!Options} A self reference. + */ + addExtensions(...var_args: any[]): Options; + + + /** + * Sets the path to the Chrome binary to use. On Mac OS X, this path should + * reference the actual Chrome executable, not just the application binary + * (e.g. "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"). + * + * The binary path be absolute or relative to the chromedriver server + * executable, but it must exist on the machine that will launch Chrome. + * + * @param {string} path The path to the Chrome binary to use. + * @return {!Options} A self reference. + */ + setChromeBinaryPath(path: string): Options; + + + /** + * Sets whether to leave the started Chrome browser running if the controlling + * ChromeDriver service is killed before {@link webdriver.WebDriver#quit()} is + * called. + * @param {boolean} detach Whether to leave the browser running if the + * chromedriver service is killed before the session. + * @return {!Options} A self reference. + */ + detachDriver(detach: boolean): Options; + + + /** + * Sets the user preferences for Chrome's user profile. See the "Preferences" + * file in Chrome's user data directory for examples. + * @param {!Object} prefs Dictionary of user preferences to use. + * @return {!Options} A self reference. + */ + setUserPreferences(prefs: any): Options; + + + /** + * Sets the logging preferences for the new session. + * @param {!webdriver.logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + + /** + * Sets preferences for the "Local State" file in Chrome's user data + * directory. + * @param {!Object} state Dictionary of local state preferences. + * @return {!Options} A self reference. + */ + setLocalState(state: any): Options; + + + /** + * Sets the path to Chrome's log file. This path should exist on the machine + * that will launch Chrome. + * @param {string} path Path to the log file to use. + * @return {!Options} A self reference. + */ + setChromeLogFile(path: string): Options; + + + /** + * Sets the proxy settings for the new session. + * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + + /** + * Converts this options instance to a {@link webdriver.Capabilities} object. + * @param {webdriver.Capabilities=} opt_capabilities The capabilities to merge + * these options into, if any. + * @return {!webdriver.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; + + + /** + * Converts this instance to its JSON wire protocol representation. Note this + * function is an implementation not intended for general use. + * @return {{args: !Array., + * binary: (string|undefined), + * detach: boolean, + * extensions: !Array., + * localState: (Object|undefined), + * logFile: (string|undefined), + * prefs: (Object|undefined)}} The JSON wire protocol representation + * of this instance. + */ + toJSON(): IOptionsValues; + } + + /** + * Creates {@link remote.DriverService} instances that manage a ChromeDriver + * server. + */ + class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the chromedriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the chromedriver + * cannot be found on the PATH. + * @constructor + */ + constructor(opt_exe?: string); + + /** + * Sets the port to start the ChromeDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; + + + /** + * Sets the path of the log file the driver should log to. If a log file is + * not specified, the driver will log to stderr. + * @param {string} path Path of the log file to use. + * @return {!ServiceBuilder} A self reference. + */ + loggingTo(path: string): ServiceBuilder; + + + /** + * Enables verbose logging. + * @return {!ServiceBuilder} A self reference. + */ + enableVerboseLogging(): ServiceBuilder; + + + /** + * Sets the number of threads the driver should use to manage HTTP requests. + * By default, the driver will use 4 threads. + * @param {number} n The number of threads to use. + * @return {!ServiceBuilder} A self reference. + */ + setNumHttpThreads(n: number): ServiceBuilder; + + + /** + * Sets the base path for WebDriver REST commands (e.g. "/wd/hub"). + * By default, the driver will accept commands relative to "/". + * @param {string} path The base path to use. + * @return {!ServiceBuilder} A self reference. + */ + setUrlBasePath(path: string): ServiceBuilder; + + + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array.)} config The + * configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string): ServiceBuilder; + setStdio(config: any[]): ServiceBuilder; + + + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: { [key: string]: string }): ServiceBuilder; + + + /** + * Creates a new DriverService using this instance's current configuration. + * @return {remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): any; + } + + /** + * Returns the default ChromeDriver service. If such a service has not been + * configured, one will be constructed using the default configuration for + * a ChromeDriver executable found on the system PATH. + * @return {!remote.DriverService} The default ChromeDriver service. + */ + function getDefaultService(): any; + + /** + * Sets the default service to use for new ChromeDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ + function setDefaultService(service: any): void; +} + +declare module firefox { + /** + * Manages a Firefox subprocess configured for use with WebDriver. + */ + class Binary { + /** + * @param {string=} opt_exe Path to the Firefox binary to use. If not + * specified, will attempt to locate Firefox on the current system. + * @constructor + */ + constructor(opt_exe?: string); + + /** + * Add arguments to the command line used to start Firefox. + * @param {...(string|!Array.)} var_args Either the arguments to add as + * varargs, or the arguments as an array. + */ + addArguments(...var_args: string[]): void; + + + /** + * Launches Firefox and eturns a promise that will be fulfilled when the process + * terminates. + * @param {string} profile Path to the profile directory to use. + * @return {!promise.Promise.} A promise for the process result. + * @throws {Error} If this instance has already been started. + */ + launch(profile: string): webdriver.promise.Promise; + + + /** + * Kills the managed Firefox process. + * @return {!promise.Promise} A promise for when the process has terminated. + */ + kill(): webdriver.promise.Promise; + } + + /** + * A WebDriver client for Firefox. + * + * @extends {webdriver.WebDriver} + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(Options|webdriver.Capabilities|Object)=} opt_config The + * configuration options for this driver, specified as either an + * {@link Options} or {@link webdriver.Capabilities}, or as a raw hash + * object. + * @param {webdriver.promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + * @constructor + */ + constructor(opt_config?: webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: any, opt_flow?: webdriver.promise.ControlFlow); + } + + /** + * Configuration options for the FirefoxDriver. + */ + class Options { + /** + * @constructor + */ + constructor(); + + /** + * Sets the profile to use. The profile may be specified as a + * {@link Profile} object or as the path to an existing Firefox profile to use + * as a template. + * + * @param {(string|!Profile)} profile The profile to use. + * @return {!Options} A self reference. + */ + setProfile(profile: string): Options; + setProfile(profile: Profile): Options; + + + /** + * Sets the binary to use. The binary may be specified as the path to a Firefox + * executable, or as a {@link Binary} object. + * + * @param {(string|!Binary)} binary The binary to use. + * @return {!Options} A self reference. + */ + setBinary(binary: string): Options; + setBinary(binary: Binary): Options; + + + /** + * Sets the logging preferences for the new session. + * @param {webdriver.logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; + + + /** + * Sets the proxy to use. + * + * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + + /** + * Converts these options to a {@link webdriver.Capabilities} instance. + * + * @return {!webdriver.Capabilities} A new capabilities object. + */ + toCapabilities(opt_remote?: any): webdriver.Capabilities; + } + + /** + * Models a Firefox proifle directory for use with the FirefoxDriver. The + * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} + * is called. + */ + class Profile { + /** + * @param {string=} opt_dir Path to an existing Firefox profile directory to + * use a template for this profile. If not specified, a blank profile will + * be used. + * @constructor + */ + constructor(opt_dir?: string); + + /** + * Registers an extension to be included with this profile. + * @param {string} extension Path to the extension to include, as either an + * unpacked extension directory or the path to a xpi file. + */ + addExtension(extension: string): void; + + + /** + * Sets a desired preference for this profile. + * @param {string} key The preference key. + * @param {(string|number|boolean)} value The preference value. + * @throws {Error} If attempting to set a frozen preference. + */ + setPreference(key: string, value: string): void; + setPreference(key: string, value: number): void; + setPreference(key: string, value: boolean): void; + + + /** + * Returns the currently configured value of a profile preference. This does + * not include any defaults defined in the profile's template directory user.js + * file (if a template were specified on construction). + * @param {string} key The desired preference. + * @return {(string|number|boolean|undefined)} The current value of the + * requested preference. + */ + getPreference(key: string): any; + + + /** + * @return {number} The port this profile is currently configured to use, or + * 0 if the port will be selected at random when the profile is written + * to disk. + */ + getPort(): number; + + + /** + * Sets the port to use for the WebDriver extension loaded by this profile. + * @param {number} port The desired port, or 0 to use any free port. + */ + setPort(port: number): void; + + + /** + * @return {boolean} Whether the FirefoxDriver is configured to automatically + * accept untrusted SSL certificates. + */ + acceptUntrustedCerts(): boolean; + + + /** + * Sets whether the FirefoxDriver should automatically accept untrusted SSL + * certificates. + * @param {boolean} value . + */ + setAcceptUntrustedCerts(value: boolean): void; + + + /** + * Sets whether to assume untrusted certificates come from untrusted issuers. + * @param {boolean} value . + */ + setAssumeUntrustedCertIssuer(value: boolean): void; + + + /** + * @return {boolean} Whether to assume untrusted certs come from untrusted + * issuers. + */ + assumeUntrustedCertIssuer(): boolean; + + + /** + * Sets whether to use native events with this profile. + * @param {boolean} enabled . + */ + setNativeEventsEnabled(enabled: boolean): void; + + + /** + * Returns whether native events are enabled in this profile. + * @return {boolean} . + */ + nativeEventsEnabled(): boolean; + + + /** + * Writes this profile to disk. + * @param {boolean=} opt_excludeWebDriverExt Whether to exclude the WebDriver + * extension from the generated profile. Used to reduce the size of an + * {@link #encode() encoded profile} since the server will always install + * the extension itself. + * @return {!promise.Promise.} A promise for the path to the new + * profile directory. + */ + writeToDisk(opt_excludeWebDriverExt?: boolean): webdriver.promise.Promise; + + + /** + * Encodes this profile as a zipped, base64 encoded directory. + * @return {!promise.Promise.} A promise for the encoded profile. + */ + encode(): webdriver.promise.Promise; + } +} + +declare module executors { + /** + * Creates a command executor that uses WebDriver's JSON wire protocol. + * @param url The server's URL, or a promise that will resolve to that URL. + * @returns {!webdriver.CommandExecutor} The new command executor. + */ + function createExecutor(url: string): webdriver.CommandExecutor; + function createExecutor(url: webdriver.promise.Promise): webdriver.CommandExecutor; +} + +declare module webdriver { + + module error { + interface IErrorCode { + SUCCESS: number; + + NO_SUCH_ELEMENT: number; + NO_SUCH_FRAME: number; + UNKNOWN_COMMAND: number; + UNSUPPORTED_OPERATION: number; // Alias for UNKNOWN_COMMAND. + STALE_ELEMENT_REFERENCE: number; + ELEMENT_NOT_VISIBLE: number; + INVALID_ELEMENT_STATE: number; + UNKNOWN_ERROR: number; + ELEMENT_NOT_SELECTABLE: number; + JAVASCRIPT_ERROR: number; + XPATH_LOOKUP_ERROR: number; + TIMEOUT: number; + NO_SUCH_WINDOW: number; + INVALID_COOKIE_DOMAIN: number; + UNABLE_TO_SET_COOKIE: number; + MODAL_DIALOG_OPENED: number; + UNEXPECTED_ALERT_OPEN: number; + NO_SUCH_ALERT: number; + NO_MODAL_DIALOG_OPEN: number; + SCRIPT_TIMEOUT: number; + INVALID_ELEMENT_COORDINATES: number; + IME_NOT_AVAILABLE: number; + IME_ENGINE_ACTIVATION_FAILED: number; + INVALID_SELECTOR_ERROR: number; + SESSION_NOT_CREATED: number; + MOVE_TARGET_OUT_OF_BOUNDS: number; + SQL_DATABASE_ERROR: number; + INVALID_XPATH_SELECTOR: number; + INVALID_XPATH_SELECTOR_RETURN_TYPE: number; + // The following error codes are derived straight from HTTP return codes. + METHOD_NOT_ALLOWED: number; + } + + var ErrorCode: IErrorCode; + + /** + * Error extension that includes error status codes from the WebDriver wire + * protocol: + * http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes + * + * @extends {Error} + */ + class Error { + + //region Constructors + + /** + * @param {!bot.ErrorCode} code The error's status code. + * @param {string=} opt_message Optional error message. + * @constructor + */ + constructor(code: number, opt_message?: string); + + //endregion + + //region Static Properties + + /** + * Status strings enumerated in the W3C WebDriver working draft. + * @enum {string} + * @see http://www.w3.org/TR/webdriver/#status-codes + */ + static State: { + ELEMENT_NOT_SELECTABLE: string; + ELEMENT_NOT_VISIBLE: string; + IME_ENGINE_ACTIVATION_FAILED: string; + IME_NOT_AVAILABLE: string; + INVALID_COOKIE_DOMAIN: string; + INVALID_ELEMENT_COORDINATES: string; + INVALID_ELEMENT_STATE: string; + INVALID_SELECTOR: string; + JAVASCRIPT_ERROR: string; + MOVE_TARGET_OUT_OF_BOUNDS: string; + NO_SUCH_ALERT: string; + NO_SUCH_DOM: string; + NO_SUCH_ELEMENT: string; + NO_SUCH_FRAME: string; + NO_SUCH_WINDOW: string; + SCRIPT_TIMEOUT: string; + SESSION_NOT_CREATED: string; + STALE_ELEMENT_REFERENCE: string; + SUCCESS: string; + TIMEOUT: string; + UNABLE_TO_SET_COOKIE: string; + UNEXPECTED_ALERT_OPEN: string; + UNKNOWN_COMMAND: string; + UNKNOWN_ERROR: string; + UNSUPPORTED_OPERATION: string; + } + + //endregion + + //region Properties + + /** + * This error's status code. + * @type {!bot.ErrorCode} + */ + code: number; + + /** @type {string} */ + state: string; + + /** @override */ + message: string; + + /** @override */ + name: string; + + /** @override */ + stack: string; + + /** + * Flag used for duck-typing when this code is embedded in a Firefox extension. + * This is required since an Error thrown in one component and then reported + * to another will fail instanceof checks in the second component. + * @type {boolean} + */ + isAutomationError: boolean; + + //endregion + + //region Methods + + /** @return {string} The string representation of this error. */ + toString(): string; + + //endregion + } + } + + module logging { + + /** + * A hash describing log preferences. + * @typedef {Object.} + */ + class Preferences { + setLevel(type: string, level: ILevel): void; + toJSON(): { [key: string]: string }; + } + + interface IType { + /** Logs originating from the browser. */ + BROWSER: string; + /** Logs from a WebDriver client. */ + CLIENT: string; + /** Logs from a WebDriver implementation. */ + DRIVER: string; + /** Logs related to performance. */ + PERFORMANCE: string; + /** Logs from the remote server. */ + SERVER: string; + } + + /** + * Common log types. + * @enum {string} + */ + var Type: IType; + + /** + * Logging levels. + * @enum {{value: number, name: webdriver.logging.LevelName}} + */ + interface ILevel { + value: number; + name: string; + } + + interface ILevelValues { + ALL: ILevel; + DEBUG: ILevel; + INFO: ILevel; + WARNING: ILevel; + SEVERE: ILevel; + OFF: ILevel; + } + + var Level: ILevelValues; + + /** + * Converts a level name or value to a {@link webdriver.logging.Level} value. + * If the name/value is not recognized, {@link webdriver.logging.Level.ALL} + * will be returned. + * @param {(number|string)} nameOrValue The log level name, or value, to + * convert . + * @return {!webdriver.logging.Level} The converted level. + */ + function getLevel(nameOrValue: string): ILevel; + function getLevel(nameOrValue: number): ILevel; + + interface IEntryJSON { + level: string; + message: string; + timestamp: number; + type: string; + } + + /** + * A single log entry. + */ + class Entry { + + //region Constructors + + /** + * @param {(!webdriver.logging.Level|string)} level The entry level. + * @param {string} message The log message. + * @param {number=} opt_timestamp The time this entry was generated, in + * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the + * current time will be used. + * @param {string=} opt_type The log type, if known. + * @constructor + */ + constructor(level: ILevel, message: string, opt_timestamp?:number, opt_type?:string); + constructor(level: string, message: string, opt_timestamp?:number, opt_type?:string); + + //endregion + + //region Public Properties + + /** @type {!webdriver.logging.Level} */ + level: ILevel; + + /** @type {string} */ + message: string; + + /** @type {number} */ + timestamp: number; + + /** @type {string} */ + type: string; + + //endregion + + //region Static Methods + + /** + * Converts a {@link goog.debug.LogRecord} into a + * {@link webdriver.logging.Entry}. + * @param {!goog.debug.LogRecord} logRecord The record to convert. + * @param {string=} opt_type The log type. + * @return {!webdriver.logging.Entry} The converted entry. + */ + static fromClosureLogRecord(logRecord: any, opt_type?:string): Entry; + + //endregion + + //region Methods + + /** + * @return {{level: string, message: string, timestamp: number, + * type: string}} The JSON representation of this entry. + */ + toJSON(): IEntryJSON; + + //endregion + } + } + + module promise { + //region Functions + + /** + * Given an array of promises, will return a promise that will be fulfilled + * with the fulfillment values of the input array's values. If any of the + * input array's promises are rejected, the returned promise will be rejected + * with the same reason. + * + * @param {!Array.<(T|!webdriver.promise.Promise.)>} arr An array of + * promises to wait on. + * @return {!webdriver.promise.Promise.>} A promise that is + * fulfilled with an array containing the fulfilled values of the + * input array, or rejected with the same reason as the first + * rejected value. + * @template T + */ + function all(arr: Promise[]): Promise; + + /** + * Invokes the appropriate callback function as soon as a promised + * {@code value} is resolved. This function is similar to + * {@link webdriver.promise.when}, except it does not return a new promise. + * @param {*} value The value to observe. + * @param {Function} callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + */ + function asap(value: any, callback: Function, opt_errback?: Function): void; + + /** + * @return {!webdriver.promise.ControlFlow} The currently active control flow. + */ + function controlFlow(): ControlFlow; + + /** + * Creates a new control flow. The provided callback will be invoked as the + * first task within the new flow, with the flow as its sole argument. Returns + * a promise that resolves to the callback result. + * @param {function(!webdriver.promise.ControlFlow)} callback The entry point + * to the newly created flow. + * @return {!webdriver.promise.Promise} A promise that resolves to the callback + * result. + */ + function createFlow(callback: (flow: ControlFlow) => R): Promise; + + /** + * Determines whether a {@code value} should be treated as a promise. + * Any object whose "then" property is a function will be considered a promise. + * + * @param {*} value The value to test. + * @return {boolean} Whether the value is a promise. + */ + function isPromise(value: any): boolean; + + /** + * Tests is a function is a generator. + * @param {!Function} fn The function to test. + * @return {boolean} Whether the function is a generator. + */ + function isGenerator(fn: Function): boolean; + + /** + * Creates a promise that will be resolved at a set time in the future. + * @param {number} ms The amount of time, in milliseconds, to wait before + * resolving the promise. + * @return {!webdriver.promise.Promise} The promise. + */ + function delayed(ms: number): Promise; + + /** + * Calls a function for each element in an array, and if the function returns + * true adds the element to a new array. + * + *

If the return value of the filter function is a promise, this function + * will wait for it to be fulfilled before determining whether to insert the + * element into the new array. + * + *

If the filter function throws or returns a rejected promise, the promise + * returned by this function will be rejected with the same reason. Only the + * first failure will be reported; all subsequent errors will be silently + * ignored. + * + * @param {!(Array.|webdriver.promise.Promise.>)} arr The + * array to iterator over, or a promise that will resolve to said array. + * @param {function(this: SELF, TYPE, number, !Array.): ( + * boolean|webdriver.promise.Promise.)} fn The function + * to call for each element in the array. + * @param {SELF=} opt_self The object to be used as the value of 'this' within + * {@code fn}. + * @template TYPE, SELF + */ + function filter(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise; + function filter(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + + /** + * Creates a new deferred object. + * @return {!webdriver.promise.Deferred} The new deferred object. + */ + function defer(): Deferred; + + /** + * Creates a promise that has been resolved with the given value. + * @param {*=} opt_value The resolved value. + * @return {!webdriver.promise.Promise} The resolved promise. + */ + function fulfilled(opt_value?: T): Promise; + + /** + * Calls a function for each element in an array and inserts the result into a + * new array, which is used as the fulfillment value of the promise returned + * by this function. + * + *

If the return value of the mapping function is a promise, this function + * will wait for it to be fulfilled before inserting it into the new array. + * + *

If the mapping function throws or returns a rejected promise, the + * promise returned by this function will be rejected with the same reason. + * Only the first failure will be reported; all subsequent errors will be + * silently ignored. + * + * @param {!(Array.|webdriver.promise.Promise.>)} arr The + * array to iterator over, or a promise that will resolve to said array. + * @param {function(this: SELF, TYPE, number, !Array.): ?} fn The + * function to call for each element in the array. This function should + * expect three arguments (the element, the index, and the array itself. + * @param {SELF=} opt_self The object to be used as the value of 'this' within + * {@code fn}. + * @template TYPE, SELF + */ + function map(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + function map(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + + /** + * Creates a promise that has been rejected with the given reason. + * @param {*=} opt_reason The rejection reason; may be any value, but is + * usually an Error or a string. + * @return {!webdriver.promise.Promise} The rejected promise. + */ + function rejected(opt_reason?: any): Promise; + + /** + * Wraps a function that is assumed to be a node-style callback as its final + * argument. This callback takes two arguments: an error value (which will be + * null if the call succeeded), and the success value as the second argument. + * If the call fails, the returned promise will be rejected, otherwise it will + * be resolved with the result. + * @param {!Function} fn The function to wrap. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * result of the provided function's callback. + */ + function checkedNodeCall(fn: Function, ...var_args: any[]): Promise; + + /** + * Consumes a {@code GeneratorFunction}. Each time the generator yields a + * promise, this function will wait for it to be fulfilled before feeding the + * fulfilled value back into {@code next}. Likewise, if a yielded promise is + * rejected, the rejection error will be passed to {@code throw}. + * + *

Example 1: the Fibonacci Sequence. + *


+         * webdriver.promise.consume(function* fibonacci() {
+         *   var n1 = 1, n2 = 1;
+         *   for (var i = 0; i < 4; ++i) {
+         *     var tmp = yield n1 + n2;
+         *     n1 = n2;
+         *     n2 = tmp;
+         *   }
+         *   return n1 + n2;
+         * }).then(function(result) {
+         *   console.log(result);  // 13
+         * });
+         * 
+ * + *

Example 2: a generator that throws. + *


+         * webdriver.promise.consume(function* () {
+         *   yield webdriver.promise.delayed(250).then(function() {
+         *     throw Error('boom');
+         *   });
+         * }).thenCatch(function(e) {
+         *   console.log(e.toString());  // Error: boom
+         * });
+         * 
+ * + * @param {!Function} generatorFn The generator function to execute. + * @param {Object=} opt_self The object to use as "this" when invoking the + * initial generator. + * @param {...*} var_args Any arguments to pass to the initial generator. + * @return {!webdriver.promise.Promise.} A promise that will resolve to the + * generator's final result. + * @throws {TypeError} If the given function is not a generator. + */ + function consume(generatorFn: Function, opt_self?: any, ...var_args: any[]): Promise; + + /** + * Registers an observer on a promised {@code value}, returning a new promise + * that will be resolved when the value is. If {@code value} is not a promise, + * then the return promise will be immediately resolved. + * @param {*} value The value to observe. + * @param {Function=} opt_callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + * @return {!webdriver.promise.Promise} A new promise. + */ + function when(value: T, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + function when(value: Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + + /** + * Returns a promise that will be resolved with the input value in a + * fully-resolved state. If the value is an array, each element will be fully + * resolved. Likewise, if the value is an object, all keys will be fully + * resolved. In both cases, all nested arrays and objects will also be + * fully resolved. All fields are resolved in place; the returned promise will + * resolve on {@code value} and not a copy. + * + * Warning: This function makes no checks against objects that contain + * cyclical references: + * + * var value = {}; + * value['self'] = value; + * webdriver.promise.fullyResolved(value); // Stack overflow. + * + * @param {*} value The value to fully resolve. + * @return {!webdriver.promise.Promise} A promise for a fully resolved version + * of the input value. + */ + function fullyResolved(value: any): Promise; + + /** + * Changes the default flow to use when no others are active. + * @param {!webdriver.promise.ControlFlow} flow The new default flow. + * @throws {Error} If the default flow is not currently active. + */ + function setDefaultFlow(flow: ControlFlow): void; + + //endregion + + /** + * Error used when the computation of a promise is cancelled. + * + * @extends {goog.debug.Error} + * @final + */ + class CancellationError { + /** + * @param {string=} opt_msg The cancellation message. + * @constructor + */ + constructor(opt_msg?: string); + + name: string; + message: string; + } + + interface IThenable { + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. This method is a no-op if the promise has alreayd been resolved. + * + * @param {string=} opt_reason The reason this promise is being cancelled. + */ + cancel(opt_reason?: string): void; + + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; + + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *

+             *   // Synchronous API:
+             *   try {
+             *     doSynchronousWork();
+             *   } catch (ex) {
+             *     console.error(ex);
+             *   }
+             *
+             *   // Asynchronous promise API:
+             *   doAsynchronousWork().thenCatch(function(ex) {
+             *     console.error(ex);
+             *   });
+             * 
+ * + * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!webdriver.promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *

+             *   // Synchronous API:
+             *   try {
+             *     doSynchronousWork();
+             *   } finally {
+             *     cleanUp();
+             *   }
+             *
+             *   // Asynchronous promise API:
+             *   doAsynchronousWork().thenFinally(cleanUp);
+             * 
+ * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *

+             *   try {
+             *     throw Error('one');
+             *   } finally {
+             *     throw Error('two');  // Hides Error: one
+             *   }
+             *
+             *   webdriver.promise.rejected(Error('one'))
+             *       .thenFinally(function() {
+             *         throw Error('two');  // Hides Error: one
+             *       });
+             * 
+ * + * + * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: () => any): Promise; + } + + /** + * Thenable is a promise-like object with a {@code then} method which may be + * used to schedule callbacks on a promised value. + * + * @interface + * @template T + */ + class Thenable implements IThenable { + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. This method is a no-op if the promise has alreayd been resolved. + * + * @param {string=} opt_reason The reason this promise is being cancelled. + */ + cancel(opt_reason?: string): void; + + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; + + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *

+             *   // Synchronous API:
+             *   try {
+             *     doSynchronousWork();
+             *   } catch (ex) {
+             *     console.error(ex);
+             *   }
+             *
+             *   // Asynchronous promise API:
+             *   doAsynchronousWork().thenCatch(function(ex) {
+             *     console.error(ex);
+             *   });
+             * 
+ * + * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!webdriver.promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *

+             *   // Synchronous API:
+             *   try {
+             *     doSynchronousWork();
+             *   } finally {
+             *     cleanUp();
+             *   }
+             *
+             *   // Asynchronous promise API:
+             *   doAsynchronousWork().thenFinally(cleanUp);
+             * 
+ * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *

+             *   try {
+             *     throw Error('one');
+             *   } finally {
+             *     throw Error('two');  // Hides Error: one
+             *   }
+             *
+             *   webdriver.promise.rejected(Error('one'))
+             *       .thenFinally(function() {
+             *         throw Error('two');  // Hides Error: one
+             *       });
+             * 
+ * + * + * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: () => any): Promise; + + /** + * Adds a property to a class prototype to allow runtime checks of whether + * instances of that class implement the Thenable interface. This function will + * also ensure the prototype's {@code then} function is exported from compiled + * code. + * @param {function(new: webdriver.promise.Thenable, ...[?])} ctor The + * constructor whose prototype to modify. + */ + static addImplementation(ctor: Function): void; + + + /** + * Checks if an object has been tagged for implementing the Thenable interface + * as defined by {@link webdriver.promise.Thenable.addImplementation}. + * @param {*} object The object to test. + * @return {boolean} Whether the object is an implementation of the Thenable + * interface. + */ + static isImplementation(object: any): boolean; + } + + /** + * Represents the eventual value of a completed operation. Each promise may be + * in one of three states: pending, resolved, or rejected. Each promise starts + * in the pending state and may make a single transition to either a + * fulfilled or failed state. + * + *

This class is based on the Promise/A proposal from CommonJS. Additional + * functions are provided for API compatibility with Dojo Deferred objects. + * + * @see http://wiki.commonjs.org/wiki/Promises/A + */ + class Promise implements IThenable { + + //region Constructors + + /** + * @constructor + * @see http://wiki.commonjs.org/wiki/Promises/A + */ + constructor(); + + //endregion + + //region Methods + + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. + * @param {*} reason The reason this promise is being cancelled. If not an + * {@code Error}, one will be created using the value's string + * representation. + */ + cancel(reason: any): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. This function most + * overridden by subtypes. + * + * @param opt_callback The function to call if this promise is + * successfully resolved. The function should expect a single argument: the + * promise's resolved value. + * @param opt_errback The function to call if this promise is + * rejected. The function should expect a single argument: the rejection + * reason. + * @return A new promise which will be resolved + * with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; + + /** + * Registers listeners for when this instance is resolved. This function most + * overridden by subtypes. + * + * @param opt_callback The function to call if this promise is + * successfully resolved. The function should expect a single argument: the + * promise's resolved value. + * @param opt_errback The function to call if this promise is + * rejected. The function should expect a single argument: the rejection + * reason. + * @return A new promise which will be resolved + * with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; + + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *


+             *   // Synchronous API:
+             *   try {
+             *     doSynchronousWork();
+             *   } catch (ex) {
+             *     console.error(ex);
+             *   }
+             *
+             *   // Asynchronous promise API:
+             *   doAsynchronousWork().thenCatch(function(ex) {
+             *     console.error(ex);
+             *   });
+             * 
+ * + * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!webdriver.promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *

+             *   // Synchronous API:
+             *   try {
+             *     doSynchronousWork();
+             *   } finally {
+             *     cleanUp();
+             *   }
+             *
+             *   // Asynchronous promise API:
+             *   doAsynchronousWork().thenFinally(cleanUp);
+             * 
+ * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *

+             *   try {
+             *     throw Error('one');
+             *   } finally {
+             *     throw Error('two');  // Hides Error: one
+             *   }
+             *
+             *   webdriver.promise.rejected(Error('one'))
+             *       .thenFinally(function() {
+             *         throw Error('two');  // Hides Error: one
+             *       });
+             * 
+ * + * + * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: () => any): Promise; + + //endregion + } + + /** + * Represents a value that will be resolved at some point in the future. This + * class represents the protected "producer" half of a Promise - each Deferred + * has a {@code promise} property that may be returned to consumers for + * registering callbacks, reserving the ability to resolve the deferred to the + * producer. + * + *

If this Deferred is rejected and there are no listeners registered before + * the next turn of the event loop, the rejection will be passed to the + * {@link webdriver.promise.ControlFlow} as an unhandled failure. + * + *

If this Deferred is cancelled, the cancellation reason will be forward to + * the Deferred's canceller function (if provided). The canceller may return a + * truth-y value to override the reason provided for rejection. + * + * @extends {webdriver.promise.Promise} + */ + class Deferred extends Promise { + //region Constructors + + /** + * + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow + * this instance was created under. This should only be provided during + * unit tests. + * @constructor + */ + constructor(opt_flow?: ControlFlow); + + //endregion + + static State_: { + BLOCKED: number; + PENDING: number; + REJECTED: number; + RESOLVED: number; + } + + //region Properties + + /** + * The consumer promise for this instance. Provides protected access to the + * callback registering functions. + * @type {!webdriver.promise.Promise} + */ + promise: Promise; + + //endregion + + //region Methods + + /** + * Rejects this promise. If the error is itself a promise, this instance will + * be chained to it and be rejected with the error's resolved value. + * @param {*=} opt_error The rejection reason, typically either a + * {@code Error} or a {@code string}. + */ + reject(opt_error?: any): void; + errback(opt_error?: any): void; + + /** + * Resolves this promise with the given value. If the value is itself a + * promise and not a reference to this deferred, this instance will wait for + * it before resolving. + * @param {*=} opt_value The resolved value. + */ + fulfill(opt_value?: T): void; + + /** + * Removes all of the listeners previously registered on this deferred. + * @throws {Error} If this deferred has already been resolved. + */ + removeAll(): void; + + //endregion + } + + interface IControlFlowTimer { + clearInterval: (ms: number) => void; + clearTimeout: (ms: number) => void; + setInterval: (fn: Function, ms: number) => number; + setTimeout: (fn: Function, ms: number) => number; + } + + /** + * Handles the execution of scheduled tasks, each of which may be an + * asynchronous operation. The control flow will ensure tasks are executed in + * the ordered scheduled, starting each task only once those before it have + * completed. + * + *

Each task scheduled within this flow may return a + * {@link webdriver.promise.Promise} to indicate it is an asynchronous + * operation. The ControlFlow will wait for such promises to be resolved before + * marking the task as completed. + * + *

Tasks and each callback registered on a {@link webdriver.promise.Deferred} + * will be run in their own ControlFlow frame. Any tasks scheduled within a + * frame will have priority over previously scheduled tasks. Furthermore, if + * any of the tasks in the frame fails, the remainder of the tasks in that frame + * will be discarded and the failure will be propagated to the user through the + * callback/task's promised result. + * + *

Each time a ControlFlow empties its task queue, it will fire an + * {@link webdriver.promise.ControlFlow.EventType.IDLE} event. Conversely, + * whenever the flow terminates due to an unhandled error, it will remove all + * remaining tasks in its queue and fire an + * {@link webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION} event. If + * there are no listeners registered with the flow, the error will be + * rethrown to the global error handler. + * + * @extends {webdriver.EventEmitter} + */ + class ControlFlow extends EventEmitter { + + //region Constructors + + /** + * @param {webdriver.promise.ControlFlow.Timer=} opt_timer The timer object + * to use. Should only be set for testing. + * @constructor + */ + constructor(opt_timer?: IControlFlowTimer); + + //endregion + + //region Properties + + /** + * The timer used by this instance. + * @type {webdriver.promise.ControlFlow.Timer} + */ + timer: IControlFlowTimer; + + //endregion + + //region Static Properties + + /** + * The default timer object, which uses the global timer functions. + * @type {webdriver.promise.ControlFlow.Timer} + */ + static defaultTimer: IControlFlowTimer; + + /** + * Events that may be emitted by an {@link webdriver.promise.ControlFlow}. + * @enum {string} + */ + static EventType: { + /** Emitted when all tasks have been successfully executed. */ + IDLE: string; + + /** Emitted when a ControlFlow has been reset. */ + RESET: string; + + /** Emitted whenever a new task has been scheduled. */ + SCHEDULE_TASK: string; + + /** + * Emitted whenever a control flow aborts due to an unhandled promise + * rejection. This event will be emitted along with the offending rejection + * reason. Upon emitting this event, the control flow will empty its task + * queue and revert to its initial state. + */ + UNCAUGHT_EXCEPTION: string; + }; + + /** + * How often, in milliseconds, the event loop should run. + * @type {number} + * @const + */ + static EVENT_LOOP_FREQUENCY: number; + + //endregion + + //region Methods + + /** + * Resets this instance, clearing its queue and removing all event listeners. + */ + reset(): void; + + /** + * Returns a summary of the recent task activity for this instance. This + * includes the most recently completed task, as well as any parent tasks. In + * the returned summary, the task at index N is considered a sub-task of the + * task at index N+1. + * @return {!Array.} A summary of this instance's recent task + * activity. + */ + getHistory(): string[]; + + /** Clears this instance's task history. */ + clearHistory(): void; + + /** + * Appends a summary of this instance's recent task history to the given + * error's stack trace. This function will also ensure the error's stack trace + * is in canonical form. + * @param {!(Error|goog.testing.JsUnitException)} e The error to annotate. + * @return {!(Error|goog.testing.JsUnitException)} The annotated error. + */ + annotateError(e: any): any; + + /** + * @return {string} The scheduled tasks still pending with this instance. + */ + getSchedule(): string; + + /** + * Schedules a task for execution. If there is nothing currently in the + * queue, the task will be executed in the next turn of the event loop. + * + * @param {!Function} fn The function to call to start the task. If the + * function returns a {@link webdriver.promise.Promise}, this instance + * will wait for it to be resolved before starting the next task. + * @param {string=} opt_description A description of the task. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the result of the action. + */ + execute(fn: Function, opt_description?: string): Promise; + + /** + * Inserts a {@code setTimeout} into the command queue. This is equivalent to + * a thread sleep in a synchronous programming language. + * + * @param {number} ms The timeout delay, in milliseconds. + * @param {string=} opt_description A description to accompany the timeout. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the result of the action. + */ + timeout(ms: number, opt_description?: string): Promise; + + /** + * Schedules a task that shall wait for a condition to hold. Each condition + * function may return any value, but it will always be evaluated as a boolean. + * + *

Condition functions may schedule sub-tasks with this instance, however, + * their execution time will be factored into whether a wait has timed out. + * + *

In the event a condition returns a Promise, the polling loop will wait for + * it to be resolved before evaluating whether the condition has been satisfied. + * The resolution time for a promise is factored into whether a wait has timed + * out. + * + *

If the condition function throws, or returns a rejected promise, the + * wait task will fail. + * + * @param {!Function} condition The condition function to poll. + * @param {number} timeout How long to wait, in milliseconds, for the condition + * to hold before timing out. + * @param {string=} opt_message An optional error message to include if the + * wait times out; defaults to the empty string. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * condition has been satisified. The promise shall be rejected if the wait + * times out waiting for the condition. + */ + wait(condition: Function, timeout: number, opt_message?: string): Promise; + + /** + * Schedules a task that will wait for another promise to resolve. The resolved + * promise's value will be returned as the task result. + * @param {!webdriver.promise.Promise} promise The promise to wait on. + * @return {!webdriver.promise.Promise} A promise that will resolve when the + * task has completed. + */ + await(promise: Promise): Promise; + + //endregion + } + } + + module stacktrace { + /** + * Class representing one stack frame. + */ + class Frame { + /** + * @param {(string|undefined)} context Context object, empty in case of global + * functions or if the browser doesn't provide this information. + * @param {(string|undefined)} name Function name, empty in case of anonymous + * functions. + * @param {(string|undefined)} alias Alias of the function if available. For + * example the function name will be 'c' and the alias will be 'b' if the + * function is defined as a.b = function c() {};. + * @param {(string|undefined)} path File path or URL including line number and + * optionally column number separated by colons. + * @constructor + */ + constructor(context?: string, name?: string, alias?: string, path?: string); + + /** + * @return {string} The function name or empty string if the function is + * anonymous and the object field which it's assigned to is unknown. + */ + getName(): string; + + + /** + * @return {string} The url or empty string if it is unknown. + */ + getUrl(): string; + + + /** + * @return {number} The line number if known or -1 if it is unknown. + */ + getLine(): number; + + + /** + * @return {number} The column number if known and -1 if it is unknown. + */ + getColumn(): number; + + + /** + * @return {boolean} Whether the stack frame contains an anonymous function. + */ + isAnonymous(): boolean; + + + /** + * Converts this frame to its string representation using V8's stack trace + * format: http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi + * @return {string} The string representation of this frame. + * @override + */ + toString(): string; + } + + /** + * Stores a snapshot of the stack trace at the time this instance was created. + * The stack trace will always be adjusted to exclude this function call. + */ + class Snapshot { + /** + * @param {number=} opt_slice The number of frames to remove from the top of + * the generated stack trace. + * @constructor + */ + constructor(opt_slice?: number); + + /** + * @return {!Array.} The parsed stack trace. + */ + getStacktrace(): Frame[]; + } + + /** + * Formats an error's stack trace. + * @param {!(Error|goog.testing.JsUnitException)} error The error to format. + * @return {!(Error|goog.testing.JsUnitException)} The formatted error. + */ + function format(error: any): any; + + /** + * Gets the native stack trace if available otherwise follows the call chain. + * The generated trace will exclude all frames up to and including the call to + * this function. + * @return {!Array.} The frames of the stack trace. + */ + function get(): Frame[]; + + /** + * Whether the current browser supports stack traces. + * + * @type {boolean} + * @const + */ + var BROWSER_SUPPORTED: boolean; + } + + module until { + /** + * Defines a condition to + */ + class Condition { + /** + * @param {string} message A descriptive error message. Should complete the + * sentence "Waiting [...]" + * @param {function(!webdriver.WebDriver): OUT} fn The condition function to + * evaluate on each iteration of the wait loop. + * @constructor + */ + constructor(message: string, fn: (webdriver: WebDriver) => any); + + /** @return {string} A description of this condition. */ + description(): string; + + /** @type {function(!webdriver.WebDriver): OUT} */ + fn(webdriver: WebDriver): any; + } + + /** + * Creates a condition that will wait until the input driver is able to switch + * to the designated frame. The target frame may be specified as: + *

    + *
  1. A numeric index into {@code window.frames} for the currently selected + * frame. + *
  2. A {@link webdriver.WebElement}, which must reference a FRAME or IFRAME + * element on the current page. + *
  3. A locator which may be used to first locate a FRAME or IFRAME on the + * current page before attempting to switch to it. + *
+ * + *

Upon successful resolution of this condition, the driver will be left + * focused on the new frame. + * + * @param {!(number|webdriver.WebElement| + * webdriver.Locator|webdriver.By.Hash| + * function(!webdriver.WebDriver): !webdriver.WebElement)} frame + * The frame identifier. + * @return {!until.Condition.} A new condition. + */ + function ableToSwitchToFrame(frame: number): Condition; + function ableToSwitchToFrame(frame: IWebElement): Condition; + function ableToSwitchToFrame(frame: Locator): Condition; + function ableToSwitchToFrame(frame: (webdriver: WebDriver) => IWebElement): Condition; + function ableToSwitchToFrame(frame: any): Condition; + + /** + * Creates a condition that waits for an alert to be opened. Upon success, the + * returned promise will be fulfilled with the handle for the opened alert. + * + * @return {!until.Condition.} The new condition. + */ + function alertIsPresent(): Condition; + + /** + * Creates a condition that will wait for the given element to be disabled. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isEnabled + */ + function elementIsDisabled(element: IWebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be enabled. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isEnabled + */ + function elementIsEnabled(element: IWebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be deselected. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isSelected + */ + function elementIsNotSelected(element: IWebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be in the DOM, + * yet not visible to the user. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isDisplayed + */ + function elementIsNotVisible(element: IWebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be selected. + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isSelected + */ + function elementIsSelected(element: IWebElement): Condition; + + /** + * Creates a condition that will wait for the given element to become visible. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isDisplayed + */ + function elementIsVisible(element: IWebElement): Condition; + + /** + * Creates a condition that will loop until an element is + * {@link webdriver.WebDriver#findElement found} with the given locator. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator + * to use. + * @return {!until.Condition.} The new condition. + */ + function elementLocated(locator: Locator): Condition; + function elementLocated(locator: any): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link webdriver.WebDriver#getText visible text} to contain the given + * substring. + * + * @param {!webdriver.WebElement} element The element to test. + * @param {string} substr The substring to search for. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#getText + */ + function elementTextContains(element: IWebElement, substr: string): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link webdriver.WebDriver#getText visible text} to match the given + * {@code text} exactly. + * + * @param {!webdriver.WebElement} element The element to test. + * @param {string} text The expected text. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#getText + */ + function elementTextIs(element: IWebElement, text: string): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link webdriver.WebDriver#getText visible text} to match a regular + * expression. + * + * @param {!webdriver.WebElement} element The element to test. + * @param {!RegExp} regex The regular expression to test against. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#getText + */ + function elementTextMatches(element: IWebElement, regex: RegExp): Condition; + + /** + * Creates a condition that will loop until at least one element is + * {@link webdriver.WebDriver#findElement found} with the given locator. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator + * to use. + * @return {!until.Condition.>} The new + * condition. + */ + function elementsLocated(locator: Locator): Condition; + function elementsLocated(locator: any): Condition; + + /** + * Creates a condition that will wait for the given element to become stale. An + * element is considered stale once it is removed from the DOM, or a new page + * has loaded. + * + * @param {!webdriver.WebElement} element The element that should become stale. + * @return {!until.Condition.} The new condition. + */ + function stalenessOf(element: IWebElement): Condition; + + /** + * Creates a condition that will wait for the current page's title to contain + * the given substring. + * + * @param {string} substr The substring that should be present in the page + * title. + * @return {!until.Condition.} The new condition. + */ + function titleContains(substr: string): Condition; + + /** + * Creates a condition that will wait for the current page's title to match the + * given value. + * + * @param {string} title The expected page title. + * @return {!until.Condition.} The new condition. + */ + function titleIs(title: string): Condition; + + /** + * Creates a condition that will wait for the current page's title to match the + * given regular expression. + * + * @param {!RegExp} regex The regular expression to test against. + * @return {!until.Condition.} The new condition. + */ + function titleMatches(regex: RegExp): Condition; + } + + interface ILocation { + x: number; + y: number; + } + + interface ISize { + width: number; + height: number; + } + + /** + * Enumeration of the buttons used in the advanced interactions API. + * NOTE: A TypeScript enum was not used so that this class could be extended in Protractor. + * @enum {number} + */ + interface IButton { + LEFT: number; + MIDDLE: number; + RIGHT: number; + } + + var Button: IButton + + /** + * Representations of pressable keys that aren't text. These are stored in + * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to + * http://www.google.com.au/search?&q=unicode+pua&btnG=Search + * + * @enum {string} + */ + interface IKey { + NULL: string; + CANCEL: string; // ^break + HELP: string; + BACK_SPACE: string; + TAB: string; + CLEAR: string; + RETURN: string; + ENTER: string; + SHIFT: string; + CONTROL: string; + ALT: string; + PAUSE: string; + ESCAPE: string; + SPACE: string; + PAGE_UP: string; + PAGE_DOWN: string; + END: string; + HOME: string; + ARROW_LEFT: string; + LEFT: string; + ARROW_UP: string; + UP: string; + ARROW_RIGHT: string; + RIGHT: string; + ARROW_DOWN: string; + DOWN: string; + INSERT: string; + DELETE: string; + SEMICOLON: string; + EQUALS: string; + + NUMPAD0: string; // number pad keys + NUMPAD1: string; + NUMPAD2: string; + NUMPAD3: string; + NUMPAD4: string; + NUMPAD5: string; + NUMPAD6: string; + NUMPAD7: string; + NUMPAD8: string; + NUMPAD9: string; + MULTIPLY: string; + ADD: string; + SEPARATOR: string; + SUBTRACT: string; + DECIMAL: string; + DIVIDE: string; + + F1: string; // function keys + F2: string; + F3: string; + F4: string; + F5: string; + F6: string; + F7: string; + F8: string; + F9: string; + F10: string; + F11: string; + F12: string; + + COMMAND: string; // Apple command key + META: string; // alias for Windows key + + /** + * Simulate pressing many keys at once in a "chord". Takes a sequence of + * {@link webdriver.Key}s or strings, appends each of the values to a string, + * and adds the chord termination key ({@link webdriver.Key.NULL}) and returns + * the resultant string. + * + * Note: when the low-level webdriver key handlers see Keys.NULL, active + * modifier keys (CTRL/ALT/SHIFT/etc) release via a keyup event. + * + * @param {...string} var_args The key sequence to concatenate. + * @return {string} The null-terminated key sequence. + * @see http://code.google.com/p/webdriver/issues/detail?id=79 + */ + chord: (...var_args: string[]) => string; + } + + var Key: IKey; + + /** + * Class for defining sequences of complex user interactions. Each sequence + * will not be executed until {@link #perform} is called. + * + *

Example:


+     *   new webdriver.ActionSequence(driver).
+     *       keyDown(webdriver.Key.SHIFT).
+     *       click(element1).
+     *       click(element2).
+     *       dragAndDrop(element3, element4).
+     *       keyUp(webdriver.Key.SHIFT).
+     *       perform();
+     * 
+ * + */ + class ActionSequence { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The driver instance to use. + * @constructor + */ + constructor(driver: WebDriver); + + //endregion + + //region Methods + + /** + * Executes this action sequence. + * @return {!webdriver.promise.Promise} A promise that will be resolved once + * this sequence has completed. + */ + perform(): webdriver.promise.Promise; + + /** + * Moves the mouse. The location to move to may be specified in terms of the + * mouse's current location, an offset relative to the top-left corner of an + * element, or an element (in which case the middle of the element is used). + * @param {(!webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, as either another WebElement or an offset in pixels. + * @param {{x: number, y: number}=} opt_offset An optional offset, in pixels. + * Defaults to (0, 0). + * @return {!webdriver.ActionSequence} A self reference. + */ + mouseMove(location: IWebElement, opt_offset?: ILocation): ActionSequence; + mouseMove(location: ILocation): ActionSequence; + + /** + * Presses a mouse button. The mouse button will not be released until + * {@link #mouseUp} is called, regardless of whether that call is made in this + * sequence or another. The behavior for out-of-order events (e.g. mouseDown, + * click) is undefined. + * + *

If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + *

sequence.mouseMove(element).mouseDown()
+ * + *

Warning: this method currently only supports the left mouse button. See + * http://code.google.com/p/selenium/issues/detail?id=4047 + * + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * button is specified. + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!webdriver.ActionSequence} A self reference. + */ + mouseDown(opt_elementOrButton?: IWebElement, opt_button?: number): ActionSequence; + mouseDown(opt_elementOrButton?: number): ActionSequence; + + /** + * Releases a mouse button. Behavior is undefined for calling this function + * without a previous call to {@link #mouseDown}. + * + *

If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + *

sequence.mouseMove(element).mouseUp()
+ * + *

Warning: this method currently only supports the left mouse button. See + * http://code.google.com/p/selenium/issues/detail?id=4047 + * + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * button is specified. + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!webdriver.ActionSequence} A self reference. + */ + mouseUp(opt_elementOrButton?: IWebElement, opt_button?: number): ActionSequence; + mouseUp(opt_elementOrButton?: number): ActionSequence; + + /** + * Convenience function for performing a "drag and drop" manuever. The target + * element may be moved to the location of another element, or by an offset (in + * pixels). + * @param {!webdriver.WebElement} element The element to drag. + * @param {(!webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, either as another WebElement or an offset in pixels. + * @return {!webdriver.ActionSequence} A self reference. + */ + dragAndDrop(element: IWebElement, location: IWebElement): ActionSequence; + dragAndDrop(element: IWebElement, location: ILocation): ActionSequence; + + /** + * Clicks a mouse button. + * + *

If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + *

sequence.mouseMove(element).click()
+ * + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * button is specified. + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!webdriver.ActionSequence} A self reference. + */ + click(opt_elementOrButton?: IWebElement, opt_button?: number): ActionSequence; + click(opt_elementOrButton?: number): ActionSequence; + + /** + * Double-clicks a mouse button. + * + *

If an element is provided, the mouse will first be moved to the center of + * that element. This is equivalent to: + *

sequence.mouseMove(element).doubleClick()
+ * + *

Warning: this method currently only supports the left mouse button. See + * http://code.google.com/p/selenium/issues/detail?id=4047 + * + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * button is specified. + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!webdriver.ActionSequence} A self reference. + */ + doubleClick(opt_elementOrButton?: IWebElement, opt_button?: number): ActionSequence; + doubleClick(opt_elementOrButton?: number): ActionSequence; + + /** + * Performs a modifier key press. The modifier key is not released + * until {@link #keyUp} or {@link #sendKeys} is called. The key press will be + * targetted at the currently focused element. + * @param {!webdriver.Key} key The modifier key to push. Must be one of + * {ALT, CONTROL, SHIFT, COMMAND, META}. + * @return {!webdriver.ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + keyDown(key: string): ActionSequence; + + /** + * Performs a modifier key release. The release is targetted at the currently + * focused element. + * @param {!webdriver.Key} key The modifier key to release. Must be one of + * {ALT, CONTROL, SHIFT, COMMAND, META}. + * @return {!webdriver.ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + keyUp(key: string): ActionSequence; + + /** + * Simulates typing multiple keys. Each modifier key encountered in the + * sequence will not be released until it is encountered again. All key events + * will be targetted at the currently focused element. + * @param {...(string|!webdriver.Key|!Array.<(string|!webdriver.Key)>)} var_args + * The keys to type. + * @return {!webdriver.ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + sendKeys(...var_args: any[]): ActionSequence; + + //endregion + } + + /** + * Represents a modal dialog such as {@code alert}, {@code confirm}, or + * {@code prompt}. Provides functions to retrieve the message displayed with + * the alert, accept or dismiss the alert, and set the response text (in the + * case of {@code prompt}). + */ + interface Alert { + + //region Methods + + /** + * Retrieves the message text displayed with this alert. For instance, if the + * alert were opened with alert("hello"), then this would return "hello". + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * text displayed with this alert. + */ + getText(): webdriver.promise.Promise; + + /** + * Accepts this alert. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * this command has completed. + */ + accept(): webdriver.promise.Promise; + + /** + * Dismisses this alert. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * this command has completed. + */ + dismiss(): webdriver.promise.Promise; + + /** + * Sets the response text on this alert. This command will return an error if + * the underlying alert does not support response text (e.g. window.alert and + * window.confirm). + * @param {string} text The text to set. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * this command has completed. + */ + sendKeys(text: string): webdriver.promise.Promise; + + //endregion + + } + + /** + * AlertPromise is a promise that will be fulfilled with an Alert. This promise + * serves as a forward proxy on an Alert, allowing calls to be scheduled + * directly on this instance before the underlying Alert has been fulfilled. In + * other words, the following two statements are equivalent: + *


+     *     driver.switchTo().alert().dismiss();
+     *     driver.switchTo().alert().then(function(alert) {
+     *       return alert.dismiss();
+     *     });
+     * 
+ * + * @param {!webdriver.WebDriver} driver The driver controlling the browser this + * alert is attached to. + * @param {!webdriver.promise.Thenable.} alert A thenable + * that will be fulfilled with the promised alert. + * @constructor + * @extends {webdriver.Alert} + * @implements {webdriver.promise.Thenable.} + * @final + */ + interface AlertPromise extends Alert, webdriver.promise.IThenable { + } + + /** + * An error returned to indicate that there is an unhandled modal dialog on the + * current page. + * @extends {bot.Error} + */ + interface UnhandledAlertError extends webdriver.error.Error { + //region Methods + + /** + * @return {string} The text displayed with the unhandled alert. + */ + getAlertText(): string; + + /** + * @return {!webdriver.Alert} The open alert. + * @deprecated Use {@link #getAlertText}. This method will be removed in + * 2.45.0. + */ + getAlert(): Alert; + + + //endregion + } + + /** + * Recognized browser names. + * @enum {string} + */ + interface IBrowser { + ANDROID: string; + CHROME: string; + FIREFOX: string; + INTERNET_EXPLORER: string; + IPAD: string; + IPHONE: string; + OPERA: string; + PHANTOM_JS: string; + SAFARI: string; + HTMLUNIT: string; + } + + var Browser: IBrowser + + interface ProxyConfig { + proxyType: string; + proxyAutoconfigUrl?: string; + ftpProxy?: string; + httpProxy?: string; + sslProxy?: string; + noProxy?: string; + } + + class Builder { + + //region Constructors + + /** + * @constructor + */ + constructor(); + + //endregion + + //region Methods + + /** + * Creates a new WebDriver client based on this builder's current + * configuration. + * + * @return {!webdriver.WebDriver} A new WebDriver instance. + * @throws {Error} If the current configuration is invalid. + */ + build(): WebDriver; + + /** + * Configures the target browser for clients created by this instance. + * Any calls to {@link #withCapabilities} after this function will + * overwrite these settings. + * + *

You may also define the target browser using the {@code SELENIUM_BROWSER} + * environment variable. If set, this environment variable should be of the + * form {@code browser[:[version][:platform]]}. + * + * @param {(string|webdriver.Browser)} name The name of the target browser; + * common defaults are available on the {@link webdriver.Browser} enum. + * @param {string=} opt_version A desired version; may be omitted if any + * version should be used. + * @param {string=} opt_platform The desired platform; may be omitted if any + * version may be used. + * @return {!Builder} A self reference. + */ + forBrowser(name: string, opt_version?: string, opt_platform?: string): Builder; + + /** + * Returns the base set of capabilities this instance is currently configured + * to use. + * @return {!webdriver.Capabilities} The current capabilities for this builder. + */ + getCapabilities(): Capabilities; + + /** + * @return {string} The URL of the WebDriver server this instance is configured + * to use. + */ + getServerUrl(): string; + + /** + * Sets the default action to take with an unexpected alert before returning + * an error. + * @param {string} beahvior The desired behavior; should be "accept", "dismiss", + * or "ignore". Defaults to "dismiss". + * @return {!Builder} A self reference. + */ + setAlertBehavior(behavior: string): Builder; + + /** + * Sets Chrome-specific options for drivers created by this builder. Any + * logging or proxy settings defined on the given options will take precedence + * over those set through {@link #setLoggingPrefs} and {@link #setProxy}, + * respectively. + * + * @param {!chrome.Options} options The ChromeDriver options to use. + * @return {!Builder} A self reference. + */ + setChromeOptions(options: chrome.Options): Builder; + + /** + * Sets the control flow that created drivers should execute actions in. If + * the flow is never set, or is set to {@code null}, it will use the active + * flow at the time {@link #build()} is called. + * @param {webdriver.promise.ControlFlow} flow The control flow to use, or + * {@code null} to + * @return {!Builder} A self reference. + */ + setControlFlow(flow: webdriver.promise.ControlFlow): Builder; + + /** + * Sets whether native events should be used. + * @param {boolean} enabled Whether to enable native events. + * @return {!Builder} A self reference. + */ + setEnableNativeEvents(enabled: boolean): Builder; + + /** + * Sets Firefox-specific options for drivers created by this builder. Any + * logging or proxy settings defined on the given options will take precedence + * over those set through {@link #setLoggingPrefs} and {@link #setProxy}, + * respectively. + * + * @param {!firefox.Options} options The FirefoxDriver options to use. + * @return {!Builder} A self reference. + */ + setFirefoxOptions(options: firefox.Options): Builder; + + /** + * Sets the logging preferences for the created session. Preferences may be + * changed by repeated calls, or by calling {@link #withCapabilities}. + * @param {!(webdriver.logging.Preferences|Object.)} prefs The + * desired logging preferences. + * @return {!Builder} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Builder; + setLoggingPrefs(prefs: { [key: string]: string }): Builder; + + /** + * Sets the proxy configuration to use for WebDriver clients created by this + * builder. Any calls to {@link #withCapabilities} after this function will + * overwrite these settings. + * @param {!webdriver.ProxyConfig} config The configuration to use. + * @return {!Builder} A self reference. + */ + setProxy(config: ProxyConfig): Builder; + + /** + * Sets how elements should be scrolled into view for interaction. + * @param {number} behavior The desired scroll behavior: either 0 to align with + * the top of the viewport or 1 to align with the bottom. + * @return {!Builder} A self reference. + */ + setScrollBehavior(behavior: number): Builder; + + /** + * Sets the URL of a remote WebDriver server to use. Once a remote URL has been + * specified, the builder direct all new clients to that server. If this method + * is never called, the Builder will attempt to create all clients locally. + * + *

As an alternative to this method, you may also set the + * {@code SELENIUM_REMOTE_URL} environment variable. + * + * @param {string} url The URL of a remote server to use. + * @return {!Builder} A self reference. + */ + usingServer(url: string): Builder; + + /** + * Sets the desired capabilities when requesting a new session. This will + * overwrite any previously set capabilities. + * @param {!(Object|webdriver.Capabilities)} capabilities The desired + * capabilities for a new session. + * @return {!Builder} A self reference. + */ + withCapabilities(capabilities: Capabilities): Builder; + withCapabilities(capabilities: any): Builder; + + //endregion + } + + /** + * Common webdriver capability keys. + * @enum {string} + */ + interface ICapability { + + /** + * Indicates whether a driver should accept all SSL certs by default. This + * capability only applies when requesting a new session. To query whether + * a driver can handle insecure SSL certs, see + * {@link webdriver.Capability.SECURE_SSL}. + */ + ACCEPT_SSL_CERTS: string; + + + /** + * The browser name. Common browser names are defined in the + * {@link webdriver.Browser} enum. + */ + BROWSER_NAME: string; + + /** + * Defines how elements should be scrolled into the viewport for interaction. + * This capability will be set to zero (0) if elements are aligned with the + * top of the viewport, or one (1) if aligned with the bottom. The default + * behavior is to align with the top of the viewport. + */ + ELEMENT_SCROLL_BEHAVIOR: string; + + /** + * Whether the driver is capable of handling modal alerts (e.g. alert, + * confirm, prompt). To define how a driver should handle alerts, + * use {@link webdriver.Capability.UNEXPECTED_ALERT_BEHAVIOR}. + */ + HANDLES_ALERTS: string; + + /** + * Key for the logging driver logging preferences. + */ + LOGGING_PREFS: string; + + /** + * Whether this session generates native events when simulating user input. + */ + NATIVE_EVENTS: string; + + /** + * Describes the platform the browser is running on. Will be one of + * ANDROID, IOS, LINUX, MAC, UNIX, or WINDOWS. When requesting a + * session, ANY may be used to indicate no platform preference (this is + * semantically equivalent to omitting the platform capability). + */ + PLATFORM: string; + + /** + * Describes the proxy configuration to use for a new WebDriver session. + */ + PROXY: string; + + /** Whether the driver supports changing the brower's orientation. */ + ROTATABLE: string; + + /** + * Whether a driver is only capable of handling secure SSL certs. To request + * that a driver accept insecure SSL certs by default, use + * {@link webdriver.Capability.ACCEPT_SSL_CERTS}. + */ + SECURE_SSL: string; + + /** Whether the driver supports manipulating the app cache. */ + SUPPORTS_APPLICATION_CACHE: string; + + /** Whether the driver supports locating elements with CSS selectors. */ + SUPPORTS_CSS_SELECTORS: string; + + /** Whether the browser supports JavaScript. */ + SUPPORTS_JAVASCRIPT: string; + + /** Whether the driver supports controlling the browser's location info. */ + SUPPORTS_LOCATION_CONTEXT: string; + + /** Whether the driver supports taking screenshots. */ + TAKES_SCREENSHOT: string; + + /** + * Defines how the driver should handle unexpected alerts. The value should + * be one of "accept", "dismiss", or "ignore. + */ + UNEXPECTED_ALERT_BEHAVIOR: string; + + /** Defines the browser version. */ + VERSION: string; + } + + var Capability: ICapability; + + class Capabilities { + //region Constructors + + /** + * @param {(webdriver.Capabilities|Object)=} opt_other Another set of + * capabilities to merge into this instance. + * @constructor + */ + constructor(opt_other?: Capabilities); + constructor(opt_other?: any); + + //endregion + + //region Methods + + /** @return {!Object} The JSON representation of this instance. */ + toJSON(): any; + + /** + * Merges another set of capabilities into this instance. Any duplicates in + * the provided set will override those already set on this instance. + * @param {!(webdriver.Capabilities|Object)} other The capabilities to + * merge into this instance. + * @return {!webdriver.Capabilities} A self reference. + */ + merge(other: Capabilities): Capabilities; + merge(other: any): Capabilities; + + /** + * @param {string} key The capability to set. + * @param {*} value The capability value. Capability values must be JSON + * serializable. Pass {@code null} to unset the capability. + * @return {!webdriver.Capabilities} A self reference. + */ + set(key: string, value: any): Capabilities; + + /** + * Sets the logging preferences. Preferences may be specified as a + * {@link webdriver.logging.Preferences} instance, or a as a map of log-type to + * log-level. + * @param {!(webdriver.logging.Preferences|Object.)} prefs The + * logging preferences. + * @return {!webdriver.Capabilities} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Capabilities; + setLoggingPrefs(prefs: { [key: string]: string }): Capabilities; + + + /** + * Sets the proxy configuration for this instance. + * @param {webdriver.ProxyConfig} proxy The desired proxy configuration. + * @return {!webdriver.Capabilities} A self reference. + */ + setProxy(proxy: ProxyConfig): Capabilities; + + + /** + * Sets whether native events should be used. + * @param {boolean} enabled Whether to enable native events. + * @return {!webdriver.Capabilities} A self reference. + */ + setEnableNativeEvents(enabled: boolean): Capabilities; + + + /** + * Sets how elements should be scrolled into view for interaction. + * @param {number} behavior The desired scroll behavior: either 0 to align with + * the top of the viewport or 1 to align with the bottom. + * @return {!webdriver.Capabilities} A self reference. + */ + setScrollBehavior(behavior: number): Capabilities; + + /** + * Sets the default action to take with an unexpected alert before returning + * an error. + * @param {string} behavior The desired behavior; should be "accept", "dismiss", + * or "ignore". Defaults to "dismiss". + * @return {!webdriver.Capabilities} A self reference. + */ + setAlertBehavior(behavior: string): Capabilities; + + /** + * @param {string} key The capability to return. + * @return {*} The capability with the given key, or {@code null} if it has + * not been set. + */ + get(key: string): any; + + /** + * @param {string} key The capability to check. + * @return {boolean} Whether the specified capability is set. + */ + has(key: string): boolean; + + //endregion + + //region Static Methods + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Android. + */ + static android(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Chrome. + */ + static chrome(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Firefox. + */ + static firefox(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for + * Internet Explorer. + */ + static ie(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for iPad. + */ + static ipad(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for iPhone. + */ + static iphone(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Opera. + */ + static opera(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for + * PhantomJS. + */ + static phantomjs(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Safari. + */ + static safari(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for HTMLUnit. + */ + static htmlunit(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for HTMLUnit + * with enabled Javascript. + */ + static htmlunitwithjs(): Capabilities; + + //endregion + } + + /** + * An enumeration of valid command string. + */ + interface ICommandName { + GET_SERVER_STATUS: string; + + NEW_SESSION: string; + GET_SESSIONS: string; + DESCRIBE_SESSION: string; + + CLOSE: string; + QUIT: string; + + GET_CURRENT_URL: string; + GET: string; + GO_BACK: string; + GO_FORWARD: string; + REFRESH: string; + + ADD_COOKIE: string; + GET_COOKIE: string; + GET_ALL_COOKIES: string; + DELETE_COOKIE: string; + DELETE_ALL_COOKIES: string; + + GET_ACTIVE_ELEMENT: string; + FIND_ELEMENT: string; + FIND_ELEMENTS: string; + FIND_CHILD_ELEMENT: string; + FIND_CHILD_ELEMENTS: string; + + CLEAR_ELEMENT: string; + CLICK_ELEMENT: string; + SEND_KEYS_TO_ELEMENT: string; + SUBMIT_ELEMENT: string; + + GET_CURRENT_WINDOW_HANDLE: string; + GET_WINDOW_HANDLES: string; + GET_WINDOW_POSITION: string; + SET_WINDOW_POSITION: string; + GET_WINDOW_SIZE: string; + SET_WINDOW_SIZE: string; + MAXIMIZE_WINDOW: string; + + SWITCH_TO_WINDOW: string; + SWITCH_TO_FRAME: string; + GET_PAGE_SOURCE: string; + GET_TITLE: string; + + EXECUTE_SCRIPT: string; + EXECUTE_ASYNC_SCRIPT: string; + + GET_ELEMENT_TEXT: string; + GET_ELEMENT_TAG_NAME: string; + IS_ELEMENT_SELECTED: string; + IS_ELEMENT_ENABLED: string; + IS_ELEMENT_DISPLAYED: string; + GET_ELEMENT_LOCATION: string; + GET_ELEMENT_LOCATION_IN_VIEW: string; + GET_ELEMENT_SIZE: string; + GET_ELEMENT_ATTRIBUTE: string; + GET_ELEMENT_VALUE_OF_CSS_PROPERTY: string; + ELEMENT_EQUALS: string; + + SCREENSHOT: string; + IMPLICITLY_WAIT: string; + SET_SCRIPT_TIMEOUT: string; + SET_TIMEOUT: string; + + ACCEPT_ALERT: string; + DISMISS_ALERT: string; + GET_ALERT_TEXT: string; + SET_ALERT_TEXT: string; + + EXECUTE_SQL: string; + GET_LOCATION: string; + SET_LOCATION: string; + GET_APP_CACHE: string; + GET_APP_CACHE_STATUS: string; + CLEAR_APP_CACHE: string; + IS_BROWSER_ONLINE: string; + SET_BROWSER_ONLINE: string; + + GET_LOCAL_STORAGE_ITEM: string; + GET_LOCAL_STORAGE_KEYS: string; + SET_LOCAL_STORAGE_ITEM: string; + REMOVE_LOCAL_STORAGE_ITEM: string; + CLEAR_LOCAL_STORAGE: string; + GET_LOCAL_STORAGE_SIZE: string; + + GET_SESSION_STORAGE_ITEM: string; + GET_SESSION_STORAGE_KEYS: string; + SET_SESSION_STORAGE_ITEM: string; + REMOVE_SESSION_STORAGE_ITEM: string; + CLEAR_SESSION_STORAGE: string; + GET_SESSION_STORAGE_SIZE: string; + + SET_SCREEN_ORIENTATION: string; + GET_SCREEN_ORIENTATION: string; + + // These belong to the Advanced user interactions - an element is + // optional for these commands. + CLICK: string; + DOUBLE_CLICK: string; + MOUSE_DOWN: string; + MOUSE_UP: string; + MOVE_TO: string; + SEND_KEYS_TO_ACTIVE_ELEMENT: string; + + // These belong to the Advanced Touch API + TOUCH_SINGLE_TAP: string; + TOUCH_DOWN: string; + TOUCH_UP: string; + TOUCH_MOVE: string; + TOUCH_SCROLL: string; + TOUCH_DOUBLE_TAP: string; + TOUCH_LONG_PRESS: string; + TOUCH_FLICK: string; + + GET_AVAILABLE_LOG_TYPES: string; + GET_LOG: string; + GET_SESSION_LOGS: string; + } + + var CommandName: ICommandName; + + /** + * Describes a command to be executed by the WebDriverJS framework. + * @param {!webdriver.CommandName} name The name of this command. + * @constructor + */ + class Command { + //region Constructors + + /** + * @param {!webdriver.CommandName} name The name of this command. + * @constructor + */ + constructor(name: string); + + //endregion + + //region Methods + + /** + * @return {!webdriver.CommandName} This command's name. + */ + getName(): string; + + /** + * Sets a parameter to send with this command. + * @param {string} name The parameter name. + * @param {*} value The parameter value. + * @return {!webdriver.Command} A self reference. + */ + setParameter(name: string, value: any): Command; + + /** + * Sets the parameters for this command. + * @param {!Object.<*>} parameters The command parameters. + * @return {!webdriver.Command} A self reference. + */ + setParameters(parameters: any): Command; + + /** + * Returns a named command parameter. + * @param {string} key The parameter key to look up. + * @return {*} The parameter value, or undefined if it has not been set. + */ + getParameter(key: string): any; + + /** + * @return {!Object.<*>} The parameters to send with this command. + */ + getParameters(): any; + + //endregion + } + + /** + * Handles the execution of {@code webdriver.Command} objects. + */ + interface CommandExecutor { + /** + * Executes the given {@code command}. If there is an error executing the + * command, the provided callback will be invoked with the offending error. + * Otherwise, the callback will be invoked with a null Error and non-null + * {@link bot.response.ResponseObject} object. + * @param {!webdriver.Command} command The command to execute. + * @param {function(Error, !bot.response.ResponseObject=)} callback the function + * to invoke when the command response is ready. + */ + execute(command: Command, callback: (error: Error, responseObject: any) => any ): void; + } + + /** + * Object that can emit events for others to listen for. This is used instead + * of Closure's event system because it is much more light weight. The API is + * based on Node's EventEmitters. + */ + class EventEmitter { + //region Constructors + + /** + * @constructor + */ + constructor(); + + //endregion + + //region Methods + + /** + * Fires an event and calls all listeners. + * @param {string} type The type of event to emit. + * @param {...*} var_args Any arguments to pass to each listener. + */ + emit(type: string, ...var_args: any[]): void; + + /** + * Returns a mutable list of listeners for a specific type of event. + * @param {string} type The type of event to retrieve the listeners for. + * @return {!Array.<{fn: !Function, oneshot: boolean, + * scope: (Object|undefined)}>} The registered listeners for + * the given event type. + */ + listeners(type: string): Array<{fn: Function; oneshot: boolean; scope: any;}>; + + /** + * Registers a listener. + * @param {string} type The type of event to listen for. + * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!webdriver.EventEmitter} A self reference. + */ + addListener(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; + + /** + * Registers a one-time listener which will be called only the first time an + * event is emitted, after which it will be removed. + * @param {string} type The type of event to listen for. + * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!webdriver.EventEmitter} A self reference. + */ + once(type: string, listenerFn: any, opt_scope?: any): EventEmitter; + + /** + * An alias for {@code #addListener()}. + * @param {string} type The type of event to listen for. + * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!webdriver.EventEmitter} A self reference. + */ + on(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; + + /** + * Removes a previously registered event listener. + * @param {string} type The type of event to unregister. + * @param {!Function} listenerFn The handler function to remove. + * @return {!webdriver.EventEmitter} A self reference. + */ + removeListener(type: string, listenerFn: Function): EventEmitter; + + /** + * Removes all listeners for a specific type of event. If no event is + * specified, all listeners across all types will be removed. + * @param {string=} opt_type The type of event to remove listeners from. + * @return {!webdriver.EventEmitter} A self reference. + */ + removeAllListeners(opt_type?: string): EventEmitter; + + //endregion + } + + /** + * Interface for navigating back and forth in the browser history. + */ + interface WebDriverNavigation { + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: WebDriver): WebDriverNavigation; + + //endregion + + //region Methods + + /** + * Schedules a command to navigate to a new URL. + * @param {string} url The URL to navigate to. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * URL has been loaded. + */ + to(url: string): webdriver.promise.Promise; + + /** + * Schedules a command to move backwards in the browser history. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * navigation event has completed. + */ + back(): webdriver.promise.Promise; + + /** + * Schedules a command to move forwards in the browser history. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * navigation event has completed. + */ + forward(): webdriver.promise.Promise; + + /** + * Schedules a command to refresh the current page. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * navigation event has completed. + */ + refresh(): webdriver.promise.Promise; + + //endregion + } + + interface IWebDriverOptionsCookie { + name: string; + value: string; + path?: string; + domain?: string; + secure?: boolean; + expiry?: number; + } + + /** + * Provides methods for managing browser and driver state. + */ + interface WebDriverOptions { + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: webdriver.WebDriver): WebDriverOptions; + + //endregion + + //region Methods + + /** + * Schedules a command to add a cookie. + * @param {string} name The cookie name. + * @param {string} value The cookie value. + * @param {string=} opt_path The cookie path. + * @param {string=} opt_domain The cookie domain. + * @param {boolean=} opt_isSecure Whether the cookie is secure. + * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified as + * a number, should be in milliseconds since midnight, January 1, 1970 UTC. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * cookie has been added to the page. + */ + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number): webdriver.promise.Promise; + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: Date): webdriver.promise.Promise; + + /** + * Schedules a command to delete all cookies visible to the current page. + * @return {!webdriver.promise.Promise} A promise that will be resolved when all + * cookies have been deleted. + */ + deleteAllCookies(): webdriver.promise.Promise; + + /** + * Schedules a command to delete the cookie with the given name. This command is + * a no-op if there is no cookie with the given name visible to the current + * page. + * @param {string} name The name of the cookie to delete. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * cookie has been deleted. + */ + deleteCookie(name: string): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve all cookies visible to the current page. + * Each cookie will be returned as a JSON object as described by the WebDriver + * wire protocol. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * cookies visible to the current page. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object + */ + getCookies(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the cookie with the given name. Returns null + * if there is no such cookie. The cookie will be returned as a JSON object as + * described by the WebDriver wire protocol. + * @param {string} name The name of the cookie to retrieve. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * named cookie, or {@code null} if there is no such cookie. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object + */ + getCookie(name: string): webdriver.promise.Promise; + + /** + * @return {!webdriver.WebDriver.Logs} The interface for managing driver + * logs. + */ + logs(): WebDriverLogs; + + /** + * @return {!webdriver.WebDriver.Timeouts} The interface for managing driver + * timeouts. + */ + timeouts(): WebDriverTimeouts; + + /** + * @return {!webdriver.WebDriver.Window} The interface for managing the + * current window. + */ + window(): WebDriverWindow; + + //endregion + } + + /** + * An interface for managing timeout behavior for WebDriver instances. + */ + interface WebDriverTimeouts { + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: WebDriver): WebDriverTimeouts; + + //endregion + + //region Methods + + /** + * Specifies the amount of time the driver should wait when searching for an + * element if it is not immediately present. + *

+ * When searching for a single element, the driver should poll the page + * until the element has been found, or this timeout expires before failing + * with a {@code bot.ErrorCode.NO_SUCH_ELEMENT} error. When searching + * for multiple elements, the driver should poll the page until at least one + * element has been found or this timeout has expired. + *

+ * Setting the wait timeout to 0 (its default value), disables implicit + * waiting. + *

+ * Increasing the implicit wait timeout should be used judiciously as it + * will have an adverse effect on test run time, especially when used with + * slower location strategies like XPath. + * + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * implicit wait timeout has been set. + */ + implicitlyWait(ms: number): webdriver.promise.Promise; + + /** + * Sets the amount of time to wait, in milliseconds, for an asynchronous script + * to finish execution before returning an error. If the timeout is less than or + * equal to 0, the script will be allowed to run indefinitely. + * + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * script timeout has been set. + */ + setScriptTimeout(ms: number): webdriver.promise.Promise; + + /** + * Sets the amount of time to wait for a page load to complete before returning + * an error. If the timeout is negative, page loads may be indefinite. + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the timeout has been set. + */ + pageLoadTimeout(ms: number): webdriver.promise.Promise; + + //endregion + } + + /** + * An interface for managing the current window. + */ + interface WebDriverWindow { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: WebDriver): WebDriverWindow; + + //endregion + + //region Methods + + /** + * Retrieves the window's current position, relative to the top left corner of + * the screen. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * window's position in the form of a {x:number, y:number} object literal. + */ + getPosition(): webdriver.promise.Promise; + + /** + * Repositions the current window. + * @param {number} x The desired horizontal position, relative to the left side + * of the screen. + * @param {number} y The desired vertical position, relative to the top of the + * of the screen. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * command has completed. + */ + setPosition(x: number, y: number): webdriver.promise.Promise; + + /** + * Retrieves the window's current size. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * window's size in the form of a {width:number, height:number} object + * literal. + */ + getSize(): webdriver.promise.Promise; + + /** + * Resizes the current window. + * @param {number} width The desired window width. + * @param {number} height The desired window height. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * command has completed. + */ + setSize(width: number, height: number): webdriver.promise.Promise; + + /** + * Maximizes the current window. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * command has completed. + */ + maximize(): webdriver.promise.Promise; + + //endregion + } + + /** + * Interface for managing WebDriver log records. + */ + interface WebDriverLogs { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: WebDriver): WebDriverLogs; + + //endregion + + //region + + /** + * Fetches available log entries for the given type. + * + *

Note that log buffers are reset after each call, meaning that + * available log entries correspond to those entries not yet returned for a + * given log type. In practice, this means that this call will return the + * available log entries since the last call, or from the start of the + * session. + * + * @param {!webdriver.logging.Type} type The desired log type. + * @return {!webdriver.promise.Promise.>} A + * promise that will resolve to a list of log entries for the specified + * type. + */ + get(type: string): webdriver.promise.Promise; + + /** + * Retrieves the log types available to this driver. + * @return {!webdriver.promise.Promise.>} A + * promise that will resolve to a list of available log types. + */ + getAvailableLogTypes(): webdriver.promise.Promise; + + //endregion + } + + /** + * An interface for changing the focus of the driver to another frame or window. + */ + interface WebDriverTargetLocator { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: WebDriver): WebDriverTargetLocator; + + //endregion + + //region Methods + + /** + * Schedules a command retrieve the {@code document.activeElement} element on + * the current document, or {@code document.body} if activeElement is not + * available. + * @return {!webdriver.WebElement} The active element. + */ + activeElement(): WebElementPromise; + + /** + * Schedules a command to switch focus of all future commands to the first frame + * on the page. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * driver has changed focus to the default content. + */ + defaultContent(): webdriver.promise.Promise; + + /** + * Schedules a command to switch the focus of all future commands to another + * frame on the page. + *

+ * If the frame is specified by a number, the command will switch to the frame + * by its (zero-based) index into the {@code window.frames} collection. + *

+ * If the frame is specified by a string, the command will select the frame by + * its name or ID. To select sub-frames, simply separate the frame names/IDs by + * dots. As an example, "main.child" will select the frame with the name "main" + * and then its child "child". + *

+ * If the specified frame can not be found, the deferred result will errback + * with a {@code bot.ErrorCode.NO_SUCH_FRAME} error. + * @param {string|number} nameOrIndex The frame locator. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * driver has changed focus to the specified frame. + */ + frame(nameOrIndex: string): webdriver.promise.Promise; + frame(nameOrIndex: number): webdriver.promise.Promise; + + /** + * Schedules a command to switch the focus of all future commands to another + * window. Windows may be specified by their {@code window.name} attribute or + * by its handle (as returned by {@code webdriver.WebDriver#getWindowHandles}). + *

+ * If the specificed window can not be found, the deferred result will errback + * with a {@code bot.ErrorCode.NO_SUCH_WINDOW} error. + * @param {string} nameOrHandle The name or window handle of the window to + * switch focus to. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * driver has changed focus to the specified window. + */ + window(nameOrHandle: string): webdriver.promise.Promise; + + /** + * Schedules a command to change focus to the active alert dialog. This command + * will return a {@link bot.ErrorCode.NO_MODAL_DIALOG_OPEN} error if a modal + * dialog is not currently open. + * @return {!webdriver.Alert} The open alert. + */ + alert(): AlertPromise; + + //endregion + } + + /** + * Creates a new WebDriver client, which provides control over a browser. + * + * Every WebDriver command returns a {@code webdriver.promise.Promise} that + * represents the result of that command. Callbacks may be registered on this + * object to manipulate the command result or catch an expected error. Any + * commands scheduled with a callback are considered sub-commands and will + * execute before the next command in the current frame. For example: + * + * var message = []; + * driver.call(message.push, message, 'a').then(function() { + * driver.call(message.push, message, 'b'); + * }); + * driver.call(message.push, message, 'c'); + * driver.call(function() { + * alert('message is abc? ' + (message.join('') == 'abc')); + * }); + * + */ + class WebDriver { + //region Constructors + + /** + * @param {!(webdriver.Session|webdriver.promise.Promise)} session Either a + * known session or a promise that will be resolved to a session. + * @param {!webdriver.CommandExecutor} executor The executor to use when + * sending commands to the browser. + * @param {webdriver.promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + * @constructor + */ + constructor(session: Session, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); + constructor(session: webdriver.promise.Promise, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); + + //endregion + + //region Static Properties + + static Navigation: WebDriverNavigation; + static Options: WebDriverOptions; + static Timeouts: WebDriverTimeouts; + static Window: WebDriverWindow; + static Logs: WebDriverLogs; + static TargetLocator: WebDriverTargetLocator; + + //endregion + + //region StaticMethods + + /** + * Creates a new WebDriver client for an existing session. + * @param {!webdriver.CommandExecutor} executor Command executor to use when + * querying for session details. + * @param {string} sessionId ID of the session to attach to. + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver + * commands should execute under. Defaults to the + * {@link webdriver.promise.controlFlow() currently active} control flow. + * @return {!webdriver.WebDriver} A new client for the specified session. + */ + static attachToSession(executor: CommandExecutor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + + /** + * Creates a new WebDriver session. + * @param {!webdriver.CommandExecutor} executor The executor to create the new + * session with. + * @param {!webdriver.Capabilities} desiredCapabilities The desired + * capabilities for the new session. + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver + * commands should execute under, including the initial session creation. + * Defaults to the {@link webdriver.promise.controlFlow() currently active} + * control flow. + * @return {!webdriver.WebDriver} The driver for the newly created session. + */ + static createSession(executor: CommandExecutor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + + //endregion + + //region Methods + + /** + * @return {!webdriver.promise.ControlFlow} The control flow used by this + * instance. + */ + controlFlow(): webdriver.promise.ControlFlow; + + /** + * Schedules a {@code webdriver.Command} to be executed by this driver's + * {@code webdriver.CommandExecutor}. + * @param {!webdriver.Command} command The command to schedule. + * @param {string} description A description of the command for debugging. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the command result. + */ + schedule(command: Command, description: string): webdriver.promise.Promise; + + /** + * @return {!webdriver.promise.Promise} A promise for this client's session. + */ + getSession(): webdriver.promise.Promise; + + /** + * @return {!webdriver.promise.Promise} A promise that will resolve with the + * this instance's capabilities. + */ + getCapabilities(): webdriver.promise.Promise; + + /** + * Schedules a command to quit the current session. After calling quit, this + * instance will be invalidated and may no longer be used to issue commands + * against the browser. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the command has completed. + */ + quit(): webdriver.promise.Promise; + + /** + * Creates a new action sequence using this driver. The sequence will not be + * scheduled for execution until {@link webdriver.ActionSequence#perform} is + * called. Example: + *


+         *   driver.actions().
+         *       mouseDown(element1).
+         *       mouseMove(element2).
+         *       mouseUp().
+         *       perform();
+         * 
+ * @return {!webdriver.ActionSequence} A new action sequence for this instance. + */ + actions(): ActionSequence; + + /** + * Schedules a command to execute JavaScript in the context of the currently + * selected frame or window. The script fragment will be executed as the body + * of an anonymous function. If the script is provided as a function object, + * that function will be converted to a string for injection into the target + * window. + * + * Any arguments provided in addition to the script will be included as script + * arguments and may be referenced using the {@code arguments} object. + * Arguments may be a boolean, number, string, or {@code webdriver.WebElement}. + * Arrays and objects may also be used as script arguments as long as each item + * adheres to the types previously mentioned. + * + * The script may refer to any variables accessible from the current window. + * Furthermore, the script will execute in the window's context, thus + * {@code document} may be used to refer to the current document. Any local + * variables will not be available once the script has finished executing, + * though global variables will persist. + * + * If the script has a return value (i.e. if the script contains a return + * statement), then the following steps will be taken for resolving this + * functions return value: + *
    + *
  • For a HTML element, the value will resolve to a + * {@code webdriver.WebElement}
  • + *
  • Null and undefined return values will resolve to null
  • + *
  • Booleans, numbers, and strings will resolve as is
  • + *
  • Functions will resolve to their string representation
  • + *
  • For arrays and objects, each member item will be converted according to + * the rules above
  • + *
+ * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * scripts return value. + */ + executeScript(script: string, ...var_args: any[]): webdriver.promise.Promise; + executeScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to execute asynchronous JavaScript in the context of the + * currently selected frame or window. The script fragment will be executed as + * the body of an anonymous function. If the script is provided as a function + * object, that function will be converted to a string for injection into the + * target window. + * + * Any arguments provided in addition to the script will be included as script + * arguments and may be referenced using the {@code arguments} object. + * Arguments may be a boolean, number, string, or {@code webdriver.WebElement}. + * Arrays and objects may also be used as script arguments as long as each item + * adheres to the types previously mentioned. + * + * Unlike executing synchronous JavaScript with + * {@code webdriver.WebDriver.prototype.executeScript}, scripts executed with + * this function must explicitly signal they are finished by invoking the + * provided callback. This callback will always be injected into the + * executed function as the last argument, and thus may be referenced with + * {@code arguments[arguments.length - 1]}. The following steps will be taken + * for resolving this functions return value against the first argument to the + * script's callback function: + *
    + *
  • For a HTML element, the value will resolve to a + * {@code webdriver.WebElement}
  • + *
  • Null and undefined return values will resolve to null
  • + *
  • Booleans, numbers, and strings will resolve as is
  • + *
  • Functions will resolve to their string representation
  • + *
  • For arrays and objects, each member item will be converted according to + * the rules above
  • + *
+ * + * Example #1: Performing a sleep that is synchronized with the currently + * selected window: + *
+         * var start = new Date().getTime();
+         * driver.executeAsyncScript(
+         *     'window.setTimeout(arguments[arguments.length - 1], 500);').
+         *     then(function() {
+         *       console.log('Elapsed time: ' + (new Date().getTime() - start) + ' ms');
+         *     });
+         * 
+ * + * Example #2: Synchronizing a test with an AJAX application: + *
+         * var button = driver.findElement(By.id('compose-button'));
+         * button.click();
+         * driver.executeAsyncScript(
+         *     'var callback = arguments[arguments.length - 1];' +
+         *     'mailClient.getComposeWindowWidget().onload(callback);');
+         * driver.switchTo().frame('composeWidget');
+         * driver.findElement(By.id('to')).sendKEys('dog@example.com');
+         * 
+ * + * Example #3: Injecting a XMLHttpRequest and waiting for the result. In this + * example, the inject script is specified with a function literal. When using + * this format, the function is converted to a string for injection, so it + * should not reference any symbols not defined in the scope of the page under + * test. + *
+         * driver.executeAsyncScript(function() {
+         *   var callback = arguments[arguments.length - 1];
+         *   var xhr = new XMLHttpRequest();
+         *   xhr.open("GET", "/resource/data.json", true);
+         *   xhr.onreadystatechange = function() {
+         *     if (xhr.readyState == 4) {
+         *       callback(xhr.resposneText);
+         *     }
+         *   }
+         *   xhr.send('');
+         * }).then(function(str) {
+         *   console.log(JSON.parse(str)['food']);
+         * });
+         * 
+ * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * scripts return value. + */ + executeAsyncScript(script: string, ...var_args: any[]): webdriver.promise.Promise; + executeAsyncScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to execute a custom function. + * @param {!Function} fn The function to execute. + * @param {Object=} opt_scope The object in whose scope to execute the function. + * @param {...*} var_args Any arguments to pass to the function. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * function's result. + */ + call(fn: Function, opt_scope?: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to wait for a condition to hold, as defined by some + * user supplied function. If any errors occur while evaluating the wait, they + * will be allowed to propagate. + * + *

In the event a condition returns a {@link webdriver.promise.Promise}, the + * polling loop will wait for it to be resolved and use the resolved value for + * evaluating whether the condition has been satisfied. The resolution time for + * a promise is factored into whether a wait has timed out. + * + * @param {!(webdriver.until.Condition.| + * function(!webdriver.WebDriver): T)} condition Either a condition + * object, or a function to evaluate as a condition. + * @param {number} timeout How long to wait for the condition to be true. + * @param {string=} opt_message An optional message to use if the wait times + * out. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the first truthy value returned by the condition function, or + * rejected if the condition times out. + * @template T + */ + wait(condition: webdriver.until.Condition, timeout: number, opt_message?: string): webdriver.promise.Promise; + wait(condition: (webdriver: WebDriver) => any, timeout: number, opt_message?: string): webdriver.promise.Promise; + + /** + * Schedules a command to make the driver sleep for the given amount of time. + * @param {number} ms The amount of time, in milliseconds, to sleep. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * sleep has finished. + */ + sleep(ms: number): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve they current window handle. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * current window handle. + */ + getWindowHandle(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the current list of available window handles. + * @return {!webdriver.promise.Promise} A promise that will be resolved with an + * array of window handles. + */ + getAllWindowHandles(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the current page's source. The page source + * returned is a representation of the underlying DOM: do not expect it to be + * formatted or escaped in the same way as the response sent from the web + * server. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * current page source. + */ + getPageSource(): webdriver.promise.Promise; + + /** + * Schedules a command to close the current window. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * this command has completed. + */ + close(): webdriver.promise.Promise; + + /** + * Schedules a command to navigate to the given URL. + * @param {string} url The fully qualified URL to open. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * document has finished loading. + */ + get(url: string): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the URL of the current page. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * current URL. + */ + getCurrentUrl(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the current page's title. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * current page's title. + */ + getTitle(): webdriver.promise.Promise; + + /** + * Schedule a command to find an element on the page. If the element cannot be + * found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned + * by the driver. Unlike other commands, this error cannot be suppressed. In + * other words, scheduling a command to find an element doubles as an assert + * that the element is present on the page. To test whether an element is + * present on the page, use {@code #isElementPresent} instead. + * + *

The search criteria for find an element may either be a + * {@code webdriver.Locator} object, or a simple JSON object whose sole key + * is one of the accepted locator strategies, as defined by + * {@code webdriver.Locator.Strategy}. For example, the following two statements + * are equivalent: + *

+         * var e1 = driver.findElement(By.id('foo'));
+         * var e2 = driver.findElement({id:'foo'});
+         * 
+ * + *

When running in the browser, a WebDriver cannot manipulate DOM elements + * directly; it may do so only through a {@link webdriver.WebElement} reference. + * This function may be used to generate a WebElement from a DOM element. A + * reference to the DOM element will be stored in a known location and this + * driver will attempt to retrieve it through {@link #executeScript}. If the + * element cannot be found (eg, it belongs to a different document than the + * one this instance is currently focused on), a + * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. + * + * @param {!(webdriver.Locator|Object.|Element)} locatorOrElement The + * locator strategy to use when searching for the element, or the actual + * DOM element to be located by the server. + * @param {...} var_args Arguments to pass to {@code #executeScript} if using a + * JavaScript locator. Otherwise ignored. + * @return {!webdriver.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locatorOrElement: Locator, ...var_args: any[]): WebElementPromise; + findElement(locatorOrElement: any, ...var_args: any[]): WebElementPromise; + + /** + * Schedules a command to test if an element is present on the page. + * + *

If given a DOM element, this function will check if it belongs to the + * document the driver is currently focused on. Otherwise, the function will + * test if at least one element can be found with the given search criteria. + * + * @param {!(webdriver.Locator|Object.|Element)} locatorOrElement The + * locator strategy to use when searching for the element, or the actual + * DOM element to be located by the server. + * @param {...} var_args Arguments to pass to {@code #executeScript} if using a + * JavaScript locator. Otherwise ignored. + * @return {!webdriver.promise.Promise} A promise that will resolve to whether + * the element is present on the page. + */ + isElementPresent(locatorOrElement: Locator, ...var_args: any[]): webdriver.promise.Promise; + isElementPresent(locatorOrElement: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedule a command to search for multiple elements on the page. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the element. + * @param {...} var_args Arguments to pass to {@code #executeScript} if using a + * JavaScript locator. Otherwise ignored. + * @return {!webdriver.promise.Promise} A promise that will be resolved to an + * array of the located {@link webdriver.WebElement}s. + */ + findElements(locator: Locator, ...var_args: any[]): webdriver.promise.Promise; + findElements(locator: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedule a command to take a screenshot. The driver makes a best effort to + * return a screenshot of the following, in order of preference: + *

    + *
  1. Entire page + *
  2. Current window + *
  3. Visible portion of the current frame + *
  4. The screenshot of the entire display containing the browser + *
+ * + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * screenshot as a base-64 encoded PNG. + */ + takeScreenshot(): webdriver.promise.Promise; + + /** + * @return {!webdriver.WebDriver.Options} The options interface for this + * instance. + */ + manage(): WebDriverOptions; + + /** + * @return {!webdriver.WebDriver.Navigation} The navigation interface for this + * instance. + */ + navigate(): WebDriverNavigation; + + /** + * @return {!webdriver.WebDriver.TargetLocator} The target locator interface for + * this instance. + */ + switchTo(): WebDriverTargetLocator; + + //endregion + } + + interface IWebElementId { + ELEMENT: string; + } + + /** + * Represents a DOM element. WebElements can be found by searching from the + * document root using a {@code webdriver.WebDriver} instance, or by searching + * under another {@code webdriver.WebElement}: + *

+     *   driver.get('http://www.google.com');
+     *   var searchForm = driver.findElement(By.tagName('form'));
+     *   var searchBox = searchForm.findElement(By.name('q'));
+     *   searchBox.sendKeys('webdriver');
+     * 
+ * + * The WebElement is implemented as a promise for compatibility with the promise + * API. It will always resolve itself when its internal state has been fully + * resolved and commands may be issued against the element. This can be used to + * catch errors when an element cannot be located on the page: + *

+     *   driver.findElement(By.id('not-there')).then(function(element) {
+     *     alert('Found an element that was not expected to be there!');
+     *   }, function(error) {
+     *     alert('The element was not found, as expected');
+     *   });
+     * 
+ */ + + interface IWebElement { + //region Methods + + /** + * Schedules a command to click on this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the click command has completed. + */ + click(): webdriver.promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by this + * instance. + *

+ * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the keysequence, that key state is toggled until one of the + * following occurs: + *

    + *
  • The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + *
  • + *
  • The {@code webdriver.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys("text was", + * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, + * "now text is"); + * // Alternatively: + * element.sendKeys("text was", + * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), + * "now text is"); + *
  • + *
  • The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + *
  • + *
+ * Note: On browsers where native keyboard events are not yet + * supported (e.g. Firefox on OS X), key events will be synthesized. Special + * punctionation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...string} var_args The sequence of keys to + * type. All arguments will be joined into a single sequence (var_args is + * permitted for convenience). + * @return {!webdriver.promise.Promise} A promise that will be resolved when all + * keys have been typed. + */ + sendKeys(...var_args: string[]): webdriver.promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's tag name. + */ + getTagName(): webdriver.promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + *

+ * Warning: the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * requested CSS value. + */ + getCssValue(cssStyleProperty: string): webdriver.promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value even if it has been modified after the + * page has been loaded. More exactly, this method will return the value of the + * given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned. The "style" attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be "boolean" attributes and will be returned as thus: + * + *

async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + *

Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + *

    + *
  • "class" + *
  • "readonly" + *
+ * @param {string} attributeName The name of the attribute to query. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * attribute's value. + */ + getAttribute(attributeName: string): webdriver.promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's visible text. + */ + getText(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's size as a {@code {width:number, height:number}} object. + */ + getSize(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * element's location as a {@code {x:number, y:number}} object. + */ + getLocation(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently enabled. + */ + isEnabled(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently selected. + */ + isSelected(): webdriver.promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the form has been submitted. + */ + submit(): webdriver.promise.Promise; + + /** + * Schedules a command to clear the {@code value} of this element. This command + * has no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the element has been cleared. + */ + clear(): webdriver.promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently visible on the page. + */ + isDisplayed(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the element's outer HTML. + */ + getOuterHtml(): webdriver.promise.Promise; + + /** + * @return {!webdriver.promise.Promise.} A promise + * that resolves to this element's JSON representation as defined by the + * WebDriver wire protocol. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol + */ + getId(): webdriver.promise.Promise + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): webdriver.promise.Promise; + + //endregion + } + + interface IWebElementFinders { + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + * + *

The search criteria for an element may be defined using one of the + * factories in the {@link webdriver.By} namespace, or as a short-hand + * {@link webdriver.By.Hash} object. For example, the following two statements + * are equivalent: + *

+         * var e1 = element.findElement(By.id('foo'));
+         * var e2 = element.findElement({id:'foo'});
+         * 
+ * + *

You may also provide a custom locator function, which takes as input + * this WebDriver instance and returns a {@link webdriver.WebElement}, or a + * promise that will resolve to a WebElement. For example, to find the first + * visible link on a page, you could write: + *

+         * var link = element.findElement(firstVisibleLink);
+         *
+         * function firstVisibleLink(element) {
+         *   var links = element.findElements(By.tagName('a'));
+         *   return webdriver.promise.filter(links, function(link) {
+         *     return links.isDisplayed();
+         *   }).then(function(visibleLinks) {
+         *     return visibleLinks[0];
+         *   });
+         * }
+         * 
+ * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!webdriver.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: Locator): WebElementPromise; + findElement(locator: any): WebElementPromise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether an element could be located on the page. + */ + isElementPresent(locator: Locator): webdriver.promise.Promise; + isElementPresent(locator: any): webdriver.promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that + * match the given search criteria. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the elements. + * @return {!webdriver.promise.Promise.>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: Locator): webdriver.promise.Promise; + findElements(locator: any): webdriver.promise.Promise; + } + + class WebElement implements IWebElement, IWebElementFinders { + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!(webdriver.promise.Promise.| + * webdriver.WebElement.Id)} id The server-assigned opaque ID for the + * underlying DOM element. + * @constructor + */ + constructor(driver: WebDriver, id: webdriver.promise.Promise); + constructor(driver: WebDriver, id: IWebElementId); + + //endregion + + //region Static Properties + + /** + * The property key used in the wire protocol to indicate that a JSON object + * contains the ID of a WebElement. + * @type {string} + * @const + */ + static ELEMENT_KEY: string; + + //endregion + + //region Methods + + /** + * @return {!webdriver.WebDriver} The parent driver for this instance. + */ + getDriver(): WebDriver; + + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + * + *

The search criteria for an element may be defined using one of the + * factories in the {@link webdriver.By} namespace, or as a short-hand + * {@link webdriver.By.Hash} object. For example, the following two statements + * are equivalent: + *

+         * var e1 = element.findElement(By.id('foo'));
+         * var e2 = element.findElement({id:'foo'});
+         * 
+ * + *

You may also provide a custom locator function, which takes as input + * this WebDriver instance and returns a {@link webdriver.WebElement}, or a + * promise that will resolve to a WebElement. For example, to find the first + * visible link on a page, you could write: + *

+         * var link = element.findElement(firstVisibleLink);
+         *
+         * function firstVisibleLink(element) {
+         *   var links = element.findElements(By.tagName('a'));
+         *   return webdriver.promise.filter(links, function(link) {
+         *     return links.isDisplayed();
+         *   }).then(function(visibleLinks) {
+         *     return visibleLinks[0];
+         *   });
+         * }
+         * 
+ * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!webdriver.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: Locator): WebElementPromise; + findElement(locator: any): WebElementPromise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether an element could be located on the page. + */ + isElementPresent(locator: Locator): webdriver.promise.Promise; + isElementPresent(locator: any): webdriver.promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that + * match the given search criteria. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the elements. + * @return {!webdriver.promise.Promise.>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: Locator): webdriver.promise.Promise; + findElements(locator: any): webdriver.promise.Promise; + + /** + * Schedules a command to click on this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the click command has completed. + */ + click(): webdriver.promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by this + * instance. + *

+ * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the keysequence, that key state is toggled until one of the + * following occurs: + *

    + *
  • The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + *
  • + *
  • The {@code webdriver.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys("text was", + * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, + * "now text is"); + * // Alternatively: + * element.sendKeys("text was", + * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), + * "now text is"); + *
  • + *
  • The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + *
  • + *
+ * Note: On browsers where native keyboard events are not yet + * supported (e.g. Firefox on OS X), key events will be synthesized. Special + * punctionation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...string} var_args The sequence of keys to + * type. All arguments will be joined into a single sequence (var_args is + * permitted for convenience). + * @return {!webdriver.promise.Promise} A promise that will be resolved when all + * keys have been typed. + */ + sendKeys(...var_args: string[]): webdriver.promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's tag name. + */ + getTagName(): webdriver.promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + *

+ * Warning: the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * requested CSS value. + */ + getCssValue(cssStyleProperty: string): webdriver.promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value even if it has been modified after the + * page has been loaded. More exactly, this method will return the value of the + * given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned. The "style" attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be "boolean" attributes and will be returned as thus: + * + *

async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + *

Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + *

    + *
  • "class" + *
  • "readonly" + *
+ * @param {string} attributeName The name of the attribute to query. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * attribute's value. + */ + getAttribute(attributeName: string): webdriver.promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's visible text. + */ + getText(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's size as a {@code {width:number, height:number}} object. + */ + getSize(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * element's location as a {@code {x:number, y:number}} object. + */ + getLocation(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently enabled. + */ + isEnabled(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently selected. + */ + isSelected(): webdriver.promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the form has been submitted. + */ + submit(): webdriver.promise.Promise; + + /** + * Schedules a command to clear the {@code value} of this element. This command + * has no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the element has been cleared. + */ + clear(): webdriver.promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently visible on the page. + */ + isDisplayed(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the element's outer HTML. + */ + getOuterHtml(): webdriver.promise.Promise; + + /** + * @return {!webdriver.promise.Promise.} A promise + * that resolves to this element's JSON representation as defined by the + * WebDriver wire protocol. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol + */ + getId(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): webdriver.promise.Promise; + + //endregion + + //region Static Methods + + /** + * Compares to WebElements for equality. + * @param {!webdriver.WebElement} a A WebElement. + * @param {!webdriver.WebElement} b A WebElement. + * @return {!webdriver.promise.Promise} A promise that will be resolved to + * whether the two WebElements are equal. + */ + static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; + + //endregion + } + + /** + * WebElementPromise is a promise that will be fulfilled with a WebElement. + * This serves as a forward proxy on WebElement, allowing calls to be + * scheduled without directly on this instance before the underlying + * WebElement has been fulfilled. In other words, the following two statements + * are equivalent: + *

+     *     driver.findElement({id: 'my-button'}).click();
+     *     driver.findElement({id: 'my-button'}).then(function(el) {
+     *       return el.click();
+     *     });
+     * 
+ * + * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!webdriver.promise.Promise.} el A promise + * that will resolve to the promised element. + * @constructor + * @extends {webdriver.WebElement} + * @implements {webdriver.promise.Thenable.} + * @final + */ + class WebElementPromise extends WebElement implements webdriver.promise.IThenable { + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. This method is a no-op if the promise has alreayd been resolved. + * + * @param {string=} opt_reason The reason this promise is being cancelled. + */ + cancel(opt_reason?: string): void; + + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: WebElement) => webdriver.promise.Promise, opt_errback?: (error: any) => any): webdriver.promise.Promise; + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: WebElement) => R, opt_errback?: (error: any) => any): webdriver.promise.Promise; + + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *

+         *   // Synchronous API:
+         *   try {
+         *     doSynchronousWork();
+         *   } catch (ex) {
+         *     console.error(ex);
+         *   }
+         *
+         *   // Asynchronous promise API:
+         *   doAsynchronousWork().thenCatch(function(ex) {
+         *     console.error(ex);
+         *   });
+         * 
+ * + * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!webdriver.promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): webdriver.promise.Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *

+         *   // Synchronous API:
+         *   try {
+         *     doSynchronousWork();
+         *   } finally {
+         *     cleanUp();
+         *   }
+         *
+         *   // Asynchronous promise API:
+         *   doAsynchronousWork().thenFinally(cleanUp);
+         * 
+ * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *

+         *   try {
+         *     throw Error('one');
+         *   } finally {
+         *     throw Error('two');  // Hides Error: one
+         *   }
+         *
+         *   webdriver.promise.rejected(Error('one'))
+         *       .thenFinally(function() {
+         *         throw Error('two');  // Hides Error: one
+         *       });
+         * 
+ * + * + * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: () => any): webdriver.promise.Promise; + } + + interface ILocatorStrategy { + className(value: string): Locator; + css(value: string): Locator; + id(value: string): Locator; + js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; + linkText(value: string): Locator; + name(value: string): Locator; + partialLinkText(value: string): Locator; + tagName(value: string): Locator; + xpath(value: string): Locator; + } + + var By: ILocatorStrategy; + + /** + * An element locator. + */ + interface Locator { + + //region Properties + + /** + * The search strategy to use when searching for an element. + * @type {string} + */ + using: string; + + /** + * The search target for this locator. + * @type {string} + */ + value: string; + + //endregion + + //region Methods + + /** @return {string} String representation of this locator. */ + toString(): string; + + //endregion + } + + /** + * Contains information about a WebDriver session. + */ + class Session { + + //region Constructors + + /** + * @param {string} id The session ID. + * @param {!(Object|webdriver.Capabilities)} capabilities The session + * capabilities. + * @constructor + */ + constructor(id: string, capabilities: Capabilities); + constructor(id: string, capabilities: any); + + //endregion + + //region Methods + + /** + * @return {string} This session's ID. + */ + getId(): string; + + /** + * @return {!webdriver.Capabilities} This session's capabilities. + */ + getCapabilities(): Capabilities; + + /** + * Retrieves the value of a specific capability. + * @param {string} key The capability to retrieve. + * @return {*} The capability value. + */ + getCapability(key: string): any; + + /** + * Returns the JSON representation of this object, which is just the string + * session ID. + * @return {string} The JSON representation of this Session. + */ + toJSON(): string; + + //endregion + } +} + +declare module testing { + /** + * Registers a new test suite. + * @param name The suite name. + * @param fn The suite function, or {@code undefined} to define a pending test suite. + */ + function describe(name: string, fn: Function): void; + + /** + * Defines a suppressed test suite. + * @param name The suite name. + * @param fn The suite function, or {@code undefined} to define a pending test suite. + */ + function xdescribe(name: string, fn: Function): void; + + /** + * Register a function to call after the current suite finishes. + * @param fn + */ + function after(fn: Function): void; + + /** + * Register a function to call after each test in a suite. + * @param fn + */ + function afterEach(fn: Function): void; + + /** + * Register a function to call before the current suite starts. + * @param fn + */ + function before(fn: Function): void; + + /** + * Register a function to call before each test in a suite. + * @param fn + */ + function beforeEach(fn: Function): void; + + /** + * Add a test to the current suite. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ + function it(name: string, fn: Function): void; + + /** + * An alias for {@link #it()} that flags the test as the only one that should + * be run within the current suite. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ + function iit(name: string, fn: Function): void; + + /** + * Adds a test to the current suite while suppressing it so it is not run. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ + function xit(name: string, fn: Function): void; +} + +declare module 'selenium-webdriver/chrome' { + export = chrome; +} + +declare module 'selenium-webdriver/firefox' { + export = firefox; +} + +declare module 'selenium-webdriver/executors' { + export = executors; +} + +declare module 'selenium-webdriver' { + export = webdriver; +} + +declare module 'selenium-webdriver/testing' { + export = testing; +} diff --git a/angular1/app/typings/tsd.d.ts b/angular1/app/typings/tsd.d.ts new file mode 100644 index 0000000..61fccdf --- /dev/null +++ b/angular1/app/typings/tsd.d.ts @@ -0,0 +1,6 @@ +/// +/// +/// +/// +/// +/// diff --git a/angular1/app/view1/view1.html b/angular1/app/view1/view1.html new file mode 100644 index 0000000..89459a6 --- /dev/null +++ b/angular1/app/view1/view1.html @@ -0,0 +1 @@ +

This is the partial for view 1.

diff --git a/angular1/app/view1/view1.ts b/angular1/app/view1/view1.ts new file mode 100644 index 0000000..8cf391b --- /dev/null +++ b/angular1/app/view1/view1.ts @@ -0,0 +1,14 @@ +'use strict'; + +class View1Controller { + static $inject = []; +} + +angular.module('myApp.view1', ['ngRoute']) + .config(['$routeProvider', $routeProvider => { + $routeProvider.when('/view1', { + templateUrl: 'view1/view1.html', + controller: 'View1Ctrl' + }); + }]) + .controller('View1Ctrl', View1Controller); diff --git a/angular1/app/view1/view1_test.ts b/angular1/app/view1/view1_test.ts new file mode 100644 index 0000000..95fa007 --- /dev/null +++ b/angular1/app/view1/view1_test.ts @@ -0,0 +1,12 @@ +'use strict'; + +describe('myApp.view1 module', () => { + beforeEach(module('myApp.view1')); + + describe('view1 controller', () => { + it('should be defined', inject($controller => { + let view1Ctrl: View1Controller = $controller('View1Ctrl'); + expect(view1Ctrl).toBeDefined(); + })); + }); +}); diff --git a/angular1/app/view2/view2.html b/angular1/app/view2/view2.html new file mode 100644 index 0000000..b6503ee --- /dev/null +++ b/angular1/app/view2/view2.html @@ -0,0 +1,5 @@ +

This is the partial for view 2.

+

+ Showing of 'interpolate' filter: + {{ 'Current version is v%VERSION%.' | interpolate }} +

diff --git a/angular1/app/view2/view2.ts b/angular1/app/view2/view2.ts new file mode 100644 index 0000000..264db98 --- /dev/null +++ b/angular1/app/view2/view2.ts @@ -0,0 +1,14 @@ +'use strict'; + +class View2Controller { + static $inject = []; +} + +angular.module('myApp.view2', ['ngRoute']) + .config(['$routeProvider', $routeProvider => { + $routeProvider.when('/view2', { + templateUrl: 'view2/view2.html', + controller: 'View2Ctrl' + }); + }]) + .controller('View2Ctrl', View2Controller); diff --git a/angular1/app/view2/view2_test.ts b/angular1/app/view2/view2_test.ts new file mode 100644 index 0000000..b3ee22b --- /dev/null +++ b/angular1/app/view2/view2_test.ts @@ -0,0 +1,12 @@ +'use strict'; + +describe('myApp.view2 module', () => { + beforeEach(module('myApp.view2')); + + describe('view2 controller', () => { + it('should be defined', inject($controller => { + let view2Ctrl: View2Controller = $controller('View2Ctrl'); + expect(view2Ctrl).toBeDefined(); + })); + }); +}); diff --git a/angular1/bower.json b/angular1/bower.json new file mode 100644 index 0000000..e468ad8 --- /dev/null +++ b/angular1/bower.json @@ -0,0 +1,15 @@ +{ + "name": "angular-seed", + "description": "A starter project for AngularJS using TypeScript", + "version": "0.0.0", + "homepage": "https://github.com/Microsoft/TypeScriptSamples/angular1", + "license": "MIT", + "private": true, + "dependencies": { + "angular": "~1.4.0", + "angular-route": "~1.4.0", + "angular-loader": "~1.4.0", + "angular-mocks": "~1.4.0", + "html5-boilerplate": "~5.2.0" + } +} diff --git a/angular1/e2e-tests/protractor.conf.ts b/angular1/e2e-tests/protractor.conf.ts new file mode 100644 index 0000000..bd5f3d0 --- /dev/null +++ b/angular1/e2e-tests/protractor.conf.ts @@ -0,0 +1,19 @@ +export var config = { + allScriptsTimeout: 11000, + + specs: [ + '*.js' + ], + + capabilities: { + 'browserName': 'chrome' + }, + + baseUrl: 'http://localhost:8000/app/', + + framework: 'jasmine', + + jasmineNodeOpts: { + defaultTimeoutInterval: 30000 + } +}; diff --git a/angular1/e2e-tests/scenarios.ts b/angular1/e2e-tests/scenarios.ts new file mode 100644 index 0000000..234906c --- /dev/null +++ b/angular1/e2e-tests/scenarios.ts @@ -0,0 +1,30 @@ +'use strict'; + +/* https://github.com/angular/protractor/blob/master/docs/toc.md */ + +describe('my app', () => { + it('should automatically redirect to /view1 when location hash/fragment is empty', () => { + browser.get('index.html'); + expect(browser.getLocationAbsUrl()).toMatch("/view1"); + }); + + describe('view1', () => { + beforeEach(() => { + browser.get('index.html#/view1'); + }); + + it('should render view1 when user navigates to /view1', () => { + expect(element.all(by.css('[ng-view] p')).first().getText()).toMatch(/partial for view 1/); + }); + }); + + describe('view2', () => { + beforeEach(() => { + browser.get('index.html#/view2'); + }); + + it('should render view2 when user navigates to /view2', () => { + expect(element.all(by.css('[ng-view] p')).first().getText()).toMatch(/partial for view 2/); + }); + }); +}); diff --git a/angular1/e2e-tests/tsconfig.json b/angular1/e2e-tests/tsconfig.json new file mode 100644 index 0000000..f974cb7 --- /dev/null +++ b/angular1/e2e-tests/tsconfig.json @@ -0,0 +1,34 @@ +{ + "filesGlob": [ + "../app/**/*.ts", + "!../app/typings/**/*.ts", + "./**/*.ts", + "./typings/**/*.ts" + ], + "compilerOptions": { + "module": "commonjs" + }, + "files": [ + "../app/app.ts", + "../app/components/version/interpolate-filter.ts", + "../app/components/version/interpolate-filter_test.ts", + "../app/components/version/version-directive.ts", + "../app/components/version/version-directive_test.ts", + "../app/components/version/version.ts", + "../app/components/version/version_test.ts", + "../app/view1/view1.ts", + "../app/view1/view1_test.ts", + "../app/view2/view2.ts", + "../app/view2/view2_test.ts", + "./protractor.conf.ts", + "./scenarios.ts", + "./typings/angular-protractor/angular-protractor.d.ts", + "./typings/angularjs/angular-mocks.d.ts", + "./typings/angularjs/angular.d.ts", + "./typings/jasmine/jasmine.d.ts", + "./typings/jquery/jquery.d.ts", + "./typings/karma-jasmine/karma-jasmine.d.ts", + "./typings/selenium-webdriver/selenium-webdriver.d.ts", + "./typings/tsd.d.ts" + ] +} diff --git a/angular1/e2e-tests/typings/angular-protractor/angular-protractor.d.ts b/angular1/e2e-tests/typings/angular-protractor/angular-protractor.d.ts new file mode 100644 index 0000000..76f0b5f --- /dev/null +++ b/angular1/e2e-tests/typings/angular-protractor/angular-protractor.d.ts @@ -0,0 +1,1685 @@ +// Type definitions for Angular Protractor 1.5.0 +// Project: https://github.com/angular/protractor +// Definitions by: Bill Armstrong +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module protractor { + //region Wrapped webdriver Items + + class ActionSequence extends webdriver.ActionSequence {} + class Builder extends webdriver.Builder {} + class Capabilities extends webdriver.Capabilities {} + class Command extends webdriver.Command {} + class EventEmitter extends webdriver.EventEmitter {} + class Session extends webdriver.Session {} + class WebDriver extends webdriver.WebDriver {} + class WebElement extends webdriver.WebElement {} + class WebElementPromise extends webdriver.WebElementPromise { } + + var Browser: webdriver.IBrowser; + var Button: webdriver.IButton; + var Capability: webdriver.ICapability; + var CommandName: webdriver.ICommandName; + var Key: webdriver.IKey; + + module error { + class Error extends webdriver.error.Error {} + var ErrorCode: webdriver.error.IErrorCode; + } + + module logging { + class Preferences extends webdriver.logging.Preferences { } + class Entry extends webdriver.logging.Entry { } + + var Type: webdriver.logging.IType; + var Level: webdriver.logging.ILevelValues; + + function getLevel(nameOrValue: string): webdriver.logging.ILevel; + function getLevel(nameOrValue: number): webdriver.logging.ILevel; + } + + module promise { + class Thenable extends webdriver.promise.Thenable { } + class Promise extends webdriver.promise.Promise { } + class Deferred extends webdriver.promise.Deferred { } + class ControlFlow extends webdriver.promise.ControlFlow { } + class CancellationError extends webdriver.promise.CancellationError { } + + /** + * Given an array of promises, will return a promise that will be fulfilled + * with the fulfillment values of the input array's values. If any of the + * input array's promises are rejected, the returned promise will be rejected + * with the same reason. + * + * @param {!Array.<(T|!webdriver.promise.Promise.)>} arr An array of + * promises to wait on. + * @return {!webdriver.promise.Promise.>} A promise that is + * fulfilled with an array containing the fulfilled values of the + * input array, or rejected with the same reason as the first + * rejected value. + * @template T + */ + function all(arr: webdriver.promise.Promise[]): webdriver.promise.Promise; + + /** + * Invokes the appropriate callback function as soon as a promised + * {@code value} is resolved. This function is similar to + * {@link webdriver.promise.when}, except it does not return a new promise. + * @param {*} value The value to observe. + * @param {Function} callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + */ + function asap(value: any, callback: Function, opt_errback?: Function): void; + + /** + * @return {!webdriver.promise.ControlFlow} The currently active control flow. + */ + function controlFlow(): webdriver.promise.ControlFlow; + + /** + * Creates a new control flow. The provided callback will be invoked as the + * first task within the new flow, with the flow as its sole argument. Returns + * a promise that resolves to the callback result. + * @param {function(!webdriver.promise.ControlFlow)} callback The entry point + * to the newly created flow. + * @return {!webdriver.promise.Promise} A promise that resolves to the callback + * result. + */ + function createFlow(callback: (flow: webdriver.promise.ControlFlow) => R): webdriver.promise.Promise; + + /** + * Determines whether a {@code value} should be treated as a promise. + * Any object whose "then" property is a function will be considered a promise. + * + * @param {*} value The value to test. + * @return {boolean} Whether the value is a promise. + */ + function isPromise(value: any): boolean; + + /** + * Tests is a function is a generator. + * @param {!Function} fn The function to test. + * @return {boolean} Whether the function is a generator. + */ + function isGenerator(fn: Function): boolean; + + /** + * Creates a promise that will be resolved at a set time in the future. + * @param {number} ms The amount of time, in milliseconds, to wait before + * resolving the promise. + * @return {!webdriver.promise.Promise} The promise. + */ + function delayed(ms: number): webdriver.promise.Promise; + + /** + * Calls a function for each element in an array, and if the function returns + * true adds the element to a new array. + * + *

If the return value of the filter function is a promise, this function + * will wait for it to be fulfilled before determining whether to insert the + * element into the new array. + * + *

If the filter function throws or returns a rejected promise, the promise + * returned by this function will be rejected with the same reason. Only the + * first failure will be reported; all subsequent errors will be silently + * ignored. + * + * @param {!(Array.|webdriver.promise.Promise.>)} arr The + * array to iterator over, or a promise that will resolve to said array. + * @param {function(this: SELF, TYPE, number, !Array.): ( + * boolean|webdriver.promise.Promise.)} fn The function + * to call for each element in the array. + * @param {SELF=} opt_self The object to be used as the value of 'this' within + * {@code fn}. + * @template TYPE, SELF + */ + function filter(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise; + function filter(arr: webdriver.promise.Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise + + /** + * Creates a new deferred object. + * @return {!webdriver.promise.Deferred} The new deferred object. + */ + function defer(): webdriver.promise.Deferred; + + /** + * Creates a promise that has been resolved with the given value. + * @param {*=} opt_value The resolved value. + * @return {!webdriver.promise.Promise} The resolved promise. + */ + function fulfilled(opt_value?: T): webdriver.promise.Promise; + + /** + * Calls a function for each element in an array and inserts the result into a + * new array, which is used as the fulfillment value of the promise returned + * by this function. + * + *

If the return value of the mapping function is a promise, this function + * will wait for it to be fulfilled before inserting it into the new array. + * + *

If the mapping function throws or returns a rejected promise, the + * promise returned by this function will be rejected with the same reason. + * Only the first failure will be reported; all subsequent errors will be + * silently ignored. + * + * @param {!(Array.|webdriver.promise.Promise.>)} arr The + * array to iterator over, or a promise that will resolve to said array. + * @param {function(this: SELF, TYPE, number, !Array.): ?} fn The + * function to call for each element in the array. This function should + * expect three arguments (the element, the index, and the array itself. + * @param {SELF=} opt_self The object to be used as the value of 'this' within + * {@code fn}. + * @template TYPE, SELF + */ + function map(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise + function map(arr: webdriver.promise.Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise + + /** + * Creates a promise that has been rejected with the given reason. + * @param {*=} opt_reason The rejection reason; may be any value, but is + * usually an Error or a string. + * @return {!webdriver.promise.Promise} The rejected promise. + */ + function rejected(opt_reason?: any): webdriver.promise.Promise; + + /** + * Wraps a function that is assumed to be a node-style callback as its final + * argument. This callback takes two arguments: an error value (which will be + * null if the call succeeded), and the success value as the second argument. + * If the call fails, the returned promise will be rejected, otherwise it will + * be resolved with the result. + * @param {!Function} fn The function to wrap. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * result of the provided function's callback. + */ + function checkedNodeCall(fn: Function, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Consumes a {@code GeneratorFunction}. Each time the generator yields a + * promise, this function will wait for it to be fulfilled before feeding the + * fulfilled value back into {@code next}. Likewise, if a yielded promise is + * rejected, the rejection error will be passed to {@code throw}. + * + *

Example 1: the Fibonacci Sequence. + *


+         * webdriver.promise.consume(function* fibonacci() {
+         *   var n1 = 1, n2 = 1;
+         *   for (var i = 0; i < 4; ++i) {
+         *     var tmp = yield n1 + n2;
+         *     n1 = n2;
+         *     n2 = tmp;
+         *   }
+         *   return n1 + n2;
+         * }).then(function(result) {
+         *   console.log(result);  // 13
+         * });
+         * 
+ * + *

Example 2: a generator that throws. + *


+         * webdriver.promise.consume(function* () {
+         *   yield webdriver.promise.delayed(250).then(function() {
+         *     throw Error('boom');
+         *   });
+         * }).thenCatch(function(e) {
+         *   console.log(e.toString());  // Error: boom
+         * });
+         * 
+ * + * @param {!Function} generatorFn The generator function to execute. + * @param {Object=} opt_self The object to use as "this" when invoking the + * initial generator. + * @param {...*} var_args Any arguments to pass to the initial generator. + * @return {!webdriver.promise.Promise.} A promise that will resolve to the + * generator's final result. + * @throws {TypeError} If the given function is not a generator. + */ + function consume(generatorFn: Function, opt_self?: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Registers an observer on a promised {@code value}, returning a new promise + * that will be resolved when the value is. If {@code value} is not a promise, + * then the return promise will be immediately resolved. + * @param {*} value The value to observe. + * @param {Function=} opt_callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + * @return {!webdriver.promise.Promise} A new promise. + */ + function when(value: T, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): webdriver.promise.Promise; + function when(value: webdriver.promise.Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): webdriver.promise.Promise; + + /** + * Returns a promise that will be resolved with the input value in a + * fully-resolved state. If the value is an array, each element will be fully + * resolved. Likewise, if the value is an object, all keys will be fully + * resolved. In both cases, all nested arrays and objects will also be + * fully resolved. All fields are resolved in place; the returned promise will + * resolve on {@code value} and not a copy. + * + * Warning: This function makes no checks against objects that contain + * cyclical references: + * + * var value = {}; + * value['self'] = value; + * webdriver.promise.fullyResolved(value); // Stack overflow. + * + * @param {*} value The value to fully resolve. + * @return {!webdriver.promise.Promise} A promise for a fully resolved version + * of the input value. + */ + function fullyResolved(value: any): webdriver.promise.Promise; + + /** + * Changes the default flow to use when no others are active. + * @param {!webdriver.promise.ControlFlow} flow The new default flow. + * @throws {Error} If the default flow is not currently active. + */ + function setDefaultFlow(flow: webdriver.promise.ControlFlow): void; + } + + module stacktrace { + class Frame extends webdriver.stacktrace.Frame { } + class Snapshot extends webdriver.stacktrace.Snapshot { } + + /** + * Formats an error's stack trace. + * @param {!(Error|goog.testing.JsUnitException)} error The error to format. + * @return {!(Error|goog.testing.JsUnitException)} The formatted error. + */ + function format(error: any): any; + + /** + * Gets the native stack trace if available otherwise follows the call chain. + * The generated trace will exclude all frames up to and including the call to + * this function. + * @return {!Array.} The frames of the stack trace. + */ + function get(): webdriver.stacktrace.Frame[]; + + /** + * Whether the current browser supports stack traces. + * + * @type {boolean} + * @const + */ + var BROWSER_SUPPORTED: boolean; + } + + module until { + class Condition extends webdriver.until.Condition { } + + /** + * Creates a condition that will wait until the input driver is able to switch + * to the designated frame. The target frame may be specified as: + *
    + *
  1. A numeric index into {@code window.frames} for the currently selected + * frame. + *
  2. A {@link webdriver.WebElement}, which must reference a FRAME or IFRAME + * element on the current page. + *
  3. A locator which may be used to first locate a FRAME or IFRAME on the + * current page before attempting to switch to it. + *
+ * + *

Upon successful resolution of this condition, the driver will be left + * focused on the new frame. + * + * @param {!(number|webdriver.WebElement| + * webdriver.Locator|webdriver.By.Hash| + * function(!webdriver.WebDriver): !webdriver.WebElement)} frame + * The frame identifier. + * @return {!until.Condition.} A new condition. + */ + function ableToSwitchToFrame(frame: number): webdriver.until.Condition; + function ableToSwitchToFrame(frame: webdriver.IWebElement): webdriver.until.Condition; + function ableToSwitchToFrame(frame: webdriver.Locator): webdriver.until.Condition; + function ableToSwitchToFrame(frame: (webdriver: webdriver.WebDriver) => webdriver.IWebElement): webdriver.until.Condition; + function ableToSwitchToFrame(frame: any): webdriver.until.Condition; + + /** + * Creates a condition that waits for an alert to be opened. Upon success, the + * returned promise will be fulfilled with the handle for the opened alert. + * + * @return {!until.Condition.} The new condition. + */ + function alertIsPresent(): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the given element to be disabled. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isEnabled + */ + function elementIsDisabled(element: webdriver.IWebElement): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the given element to be enabled. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isEnabled + */ + function elementIsEnabled(element: webdriver.IWebElement): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the given element to be deselected. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isSelected + */ + function elementIsNotSelected(element: webdriver.IWebElement): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the given element to be in the DOM, + * yet not visible to the user. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isDisplayed + */ + function elementIsNotVisible(element: webdriver.IWebElement): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the given element to be selected. + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isSelected + */ + function elementIsSelected(element: webdriver.IWebElement): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the given element to become visible. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isDisplayed + */ + function elementIsVisible(element: webdriver.IWebElement): webdriver.until.Condition; + + /** + * Creates a condition that will loop until an element is + * {@link webdriver.WebDriver#findElement found} with the given locator. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator + * to use. + * @return {!until.Condition.} The new condition. + */ + function elementLocated(locator: webdriver.Locator): webdriver.until.Condition; + function elementLocated(locator: any): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link webdriver.WebDriver#getText visible text} to contain the given + * substring. + * + * @param {!webdriver.WebElement} element The element to test. + * @param {string} substr The substring to search for. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#getText + */ + function elementTextContains(element: webdriver.IWebElement, substr: string): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link webdriver.WebDriver#getText visible text} to match the given + * {@code text} exactly. + * + * @param {!webdriver.WebElement} element The element to test. + * @param {string} text The expected text. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#getText + */ + function elementTextIs(element: webdriver.IWebElement, text: string): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link webdriver.WebDriver#getText visible text} to match a regular + * expression. + * + * @param {!webdriver.WebElement} element The element to test. + * @param {!RegExp} regex The regular expression to test against. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#getText + */ + function elementTextMatches(element: webdriver.IWebElement, regex: RegExp): webdriver.until.Condition; + + /** + * Creates a condition that will loop until at least one element is + * {@link webdriver.WebDriver#findElement found} with the given locator. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator + * to use. + * @return {!until.Condition.>} The new + * condition. + */ + function elementsLocated(locator: webdriver.Locator): webdriver.until.Condition; + function elementsLocated(locator: any): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the given element to become stale. An + * element is considered stale once it is removed from the DOM, or a new page + * has loaded. + * + * @param {!webdriver.WebElement} element The element that should become stale. + * @return {!until.Condition.} The new condition. + */ + function stalenessOf(element: webdriver.IWebElement): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the current page's title to contain + * the given substring. + * + * @param {string} substr The substring that should be present in the page + * title. + * @return {!until.Condition.} The new condition. + */ + function titleContains(substr: string): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the current page's title to match the + * given value. + * + * @param {string} title The expected page title. + * @return {!until.Condition.} The new condition. + */ + function titleIs(title: string): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the current page's title to match the + * given regular expression. + * + * @param {!RegExp} regex The regular expression to test against. + * @return {!until.Condition.} The new condition. + */ + function titleMatches(regex: RegExp): webdriver.until.Condition; + } + + //endregion + + /** + * Use as: element(locator) + * + * The ElementFinder can be treated as a WebElement for most purposes, in + * particular, you may perform actions (i.e. click, getText) on them as you + * would a WebElement. ElementFinders extend Promise, and once an action + * is performed on an ElementFinder, the latest result from the chain can be + * accessed using then. Unlike a WebElement, an ElementFinder will wait for + * angular to settle before performing finds or actions. + * + * ElementFinder can be used to build a chain of locators that is used to find + * an element. An ElementFinder does not actually attempt to find the element + * until an action is called, which means they can be set up in helper files + * before the page is available. + * + * @param {webdriver.Locator} locator An element locator. + * @return {ElementFinder} + */ + interface Element { + (locator: webdriver.Locator): ElementFinder; + + /** + * ElementArrayFinder is used for operations on an array of elements (as opposed + * to a single element). + * + * @param {webdriver.Locator} locator An element locator. + * @return {ElementArrayFinder} + */ + all(locator: webdriver.Locator): ElementArrayFinder; + } + + interface ElementFinder extends webdriver.IWebElement, webdriver.promise.IThenable { + /** + * Calls to element may be chained to find elements within a parent. + * + * @alias element(locator).element(locator) + * @view + *

+ *
+ * Child text + *
{{person.phone}}
+ *
+ *
+ * + * @example + * // Chain 2 element calls. + * var child = element(by.css('.parent')). + * element(by.css('.child')); + * expect(child.getText()).toBe('Child text\n555-123-4567'); + * + * // Chain 3 element calls. + * var triple = element(by.css('.parent')). + * element(by.css('.child')). + * element(by.binding('person.phone')); + * expect(triple.getText()).toBe('555-123-4567'); + * + * @param {webdriver.Locator} subLocator + * @return {ElementFinder} + */ + element(subLocator: webdriver.Locator): ElementFinder; + + /** + * Calls to element may be chained to find an array of elements within a parent. + * + * @alias element(locator).all(locator) + * @view + *
+ *
    + *
  • First
  • + *
  • Second
  • + *
  • Third
  • + *
+ *
+ * + * @example + * var items = element(by.css('.parent')).all(by.tagName('li')) + * + * @param {webdriver.Locator} subLocator + * @return {ElementArrayFinder} + */ + all(subLocator: webdriver.Locator): ElementArrayFinder; + + /** + * Shortcut for querying the document directly with css. + * + * @alias $(cssSelector) + * @view + *
+ * First + * Second + *
+ * + * @example + * var item = $('.count .two'); + * expect(item.getText()).toBe('Second'); + * + * @param {string} selector A css selector + * @return {ElementFinder} which identifies the located + * {@link webdriver.WebElement} + */ + $(selector: string): ElementFinder; + + /** + * Shortcut for querying the document directly with css. + * + * @alias $$(cssSelector) + * @view + *
+ * First + * Second + *
+ * + * @example + * // The following protractor expressions are equivalent. + * var list = element.all(by.css('.count span')); + * expect(list.count()).toBe(2); + * + * list = $$('.count span'); + * expect(list.count()).toBe(2); + * expect(list.get(0).getText()).toBe('First'); + * expect(list.get(1).getText()).toBe('Second'); + * + * @param {string} selector a css selector + * @return {ElementArrayFinder} which identifies the + * array of the located {@link webdriver.WebElement}s. + */ + $$(selector: string): ElementArrayFinder; + + /** + * Determine whether the element is present on the page. + * + * @view + * {{person.name}} + * + * @example + * // Element exists. + * expect(element(by.binding('person.name')).isPresent()).toBe(true); + * + * // Element not present. + * expect(element(by.binding('notPresent')).isPresent()).toBe(false); + * + * @return {ElementFinder} which resolves to whether + * the element is present on the page. + */ + isPresent(): webdriver.promise.Promise; + + /** + * Override for WebElement.prototype.isElementPresent so that protractor waits + * for Angular to settle before making the check. + * + * @see ElementFinder.isPresent + * + * @param {webdriver.Locator} subLocator Locator for element to look for. + * @return {ElementFinder} which resolves to whether + * the element is present on the page. + */ + isElementPresent(subLocator: webdriver.Locator): webdriver.promise.Promise; + + /** + * @see ElementArrayFinder.prototype.locator + * + * @return {webdriver.Locator} + */ + locator(): webdriver.Locator; + + /** + * Returns the WebElement represented by this ElementFinder. + * Throws the WebDriver error if the element doesn't exist. + * + * @example + * The following three expressions are equivalent. + * element(by.css('.parent')).getWebElement(); + * browser.waitForAngular(); browser.driver.findElement(by.css('.parent')); + * browser.findElement(by.css('.parent')); + * + * @alias element(locator).getWebElement() + * @return {webdriver.WebElement} + */ + getWebElement(): webdriver.WebElement; + + /** + * Evaluates the input as if it were on the scope of the current element. + * @see ElementArrayFinder.evaluate + * + * @param {string} expression + * + * @return {ElementFinder} which resolves to the evaluated expression. + */ + evaluate(expression: string): ElementFinder; + + /** + * @see ElementArrayFinder.prototype.allowAnimations. + * @param {string} value + * + * @return {ElementFinder} which resolves to whether animation is allowed. + */ + allowAnimations(value: string): ElementFinder; + + /** + * Create a shallow copy of ElementFinder. + * + * @return {!ElementFinder} A shallow copy of this. + */ + clone(): ElementFinder; + } + + interface ElementArrayFinder extends webdriver.promise.IThenable { + /** + * Returns the elements as an array of WebElements. + */ + getWebElements(): webdriver.WebElement[]; + + + /** + * Get an element within the ElementArrayFinder by index. The index starts at 0. + * Negative indices are wrapped (i.e. -i means ith element from last) + * This does not actually retrieve the underlying element. + * + * @alias element.all(locator).get(index) + * @view + *
    + *
  • First
  • + *
  • Second
  • + *
  • Third
  • + *
+ * + * @example + * var list = element.all(by.css('.items li')); + * expect(list.get(0).getText()).toBe('First'); + * expect(list.get(1).getText()).toBe('Second'); + * + * @param {number} index Element index. + * @return {ElementFinder} finder representing element at the given index. + */ + get(index: number): ElementFinder; + + /** + * Get the first matching element for the ElementArrayFinder. This does not + * actually retrieve the underlying element. + * + * @alias element.all(locator).first() + * @view + *
    + *
  • First
  • + *
  • Second
  • + *
  • Third
  • + *
+ * + * @example + * var first = element.all(by.css('.items li')).first(); + * expect(first.getText()).toBe('First'); + * + * @return {ElementFinder} finder representing the first matching element + */ + first(): ElementFinder; + + /** + * Get the last matching element for the ElementArrayFinder. This does not + * actually retrieve the underlying element. + * + * @alias element.all(locator).last() + * @view + *
    + *
  • First
  • + *
  • Second
  • + *
  • Third
  • + *
+ * + * @example + * var last = element.all(by.css('.items li')).last(); + * expect(last.getText()).toBe('Third'); + * + * @return {ElementFinder} finder representing the last matching element + */ + last(): ElementFinder; + + /** + * Count the number of elements represented by the ElementArrayFinder. + * + * @alias element.all(locator).count() + * @view + *
    + *
  • First
  • + *
  • Second
  • + *
  • Third
  • + *
+ * + * @example + * var list = element.all(by.css('.items li')); + * expect(list.count()).toBe(3); + * + * @return {!webdriver.promise.Promise} A promise which resolves to the + * number of elements matching the locator. + */ + count(): webdriver.promise.Promise; + + /** + * Calls the input function on each ElementFinder represented by the ElementArrayFinder. + * + * @alias element.all(locator).each(eachFunction) + * @view + *
    + *
  • First
  • + *
  • Second
  • + *
  • Third
  • + *
+ * + * @example + * element.all(by.css('.items li')).each(function(element) { + * // Will print First, Second, Third. + * element.getText().then(console.log); + * }); + * + * @param {function(ElementFinder)} fn Input function + */ + each(fn: (element: ElementFinder, index: number) => void): void; + + /** + * Apply a map function to each element within the ElementArrayFinder. The + * callback receives the ElementFinder as the first argument and the index as + * a second arg. + * + * @alias element.all(locator).map(mapFunction) + * @view + *
    + *
  • First
  • + *
  • Second
  • + *
  • Third
  • + *
+ * + * @example + * var items = element.all(by.css('.items li')).map(function(elm, index) { + * return { + * index: index, + * text: elm.getText(), + * class: elm.getAttribute('class') + * }; + * }); + * expect(items).toEqual([ + * {index: 0, text: 'First', class: 'one'}, + * {index: 1, text: 'Second', class: 'two'}, + * {index: 2, text: 'Third', class: 'three'} + * ]); + * + * @param {function(ElementFinder, number)} mapFn Map function that + * will be applied to each element. + * @return {!webdriver.promise.Promise} A promise that resolves to an array + * of values returned by the map function. + */ + map(mapFn: (element: ElementFinder, index: number) => T): webdriver.promise.Promise; + + /** + * Apply a filter function to each element within the ElementArrayFinder. Returns + * a new ElementArrayFinder with all elements that pass the filter function. The + * filter function receives the ElementFinder as the first argument + * and the index as a second arg. + * This does not actually retrieve the underlying list of elements, so it can + * be used in page objects. + * + * @alias element.all(locator).filter(filterFn) + * @view + *
    + *
  • First
  • + *
  • Second
  • + *
  • Third
  • + *
+ * + * @example + * element.all(by.css('.items li')).filter(function(elem, index) { + * return elem.getText().then(function(text) { + * return text === 'Third'; + * }); + * }).then(function(filteredElements) { + * filteredElements[0].click(); + * }); + * + * @param {function(ElementFinder, number): webdriver.WebElement.Promise} filterFn + * Filter function that will test if an element should be returned. + * filterFn can either return a boolean or a promise that resolves to a boolean. + * @return {!ElementArrayFinder} A ElementArrayFinder that represents an array + * of element that satisfy the filter function. + */ + filter(filterFn: (element: ElementFinder, index: number) => any): ElementArrayFinder; + + /** + * Apply a reduce function against an accumulator and every element found + * using the locator (from left-to-right). The reduce function has to reduce + * every element into a single value (the accumulator). Returns promise of + * the accumulator. The reduce function receives the accumulator, current + * ElementFinder, the index, and the entire array of ElementFinders, + * respectively. + * + * @alias element.all(locator).reduce(reduceFn) + * @view + *
    + *
  • First
  • + *
  • Second
  • + *
  • Third
  • + *
+ * + * @example + * var value = element.all(by.css('.items li')).reduce(function(acc, elem) { + * return elem.getText().then(function(text) { + * return acc + text + ' '; + * }); + * }); + * + * expect(value).toEqual('First Second Third '); + * + * @param {function(number, ElementFinder, number, Array.)} + * reduceFn Reduce function that reduces every element into a single value. + * @param {*} initialValue Initial value of the accumulator. + * @return {!webdriver.promise.Promise} A promise that resolves to the final + * value of the accumulator. + */ + reduce(reduceFn: (acc: T, element: ElementFinder, index: number, arr: ElementFinder[]) => webdriver.promise.Promise, initialValue: T): webdriver.promise.Promise; + reduce(reduceFn: (acc: T, element: ElementFinder, index: number, arr: ElementFinder[]) => T, initialValue: T): webdriver.promise.Promise; + + /** + * Represents the ElementArrayFinder as an array of ElementFinders. + * + * @return {Array.} Return a promise, which resolves to a list + * of ElementFinders specified by the locator. + */ + asElementFinders_(): ElementFinder[]; + + /** + * Create a shallow copy of ElementArrayFinder. + * + * @return {!ElementArrayFinder} A shallow copy of this. + */ + clone(): ElementArrayFinder; + + /** + * Calls to ElementArrayFinder may be chained to find an array of elements + * using the current elements in this ElementArrayFinder as the starting point. + * This function returns a new ElementArrayFinder which would contain the + * children elements found (and could also be empty). + * + * @alias element.all(locator).all(locator) + * @view + *
+ *
    + *
  • 1a
  • + *
  • 1b
  • + *
+ *
+ *
+ *
    + *
  • 2a
  • + *
  • 2b
  • + *
+ *
+ * + * @example + * var foo = element.all(by.css('.parent')).all(by.css('.foo')) + * expect(foo.getText()).toEqual(['1a', '2a']) + * var baz = element.all(by.css('.parent')).all(by.css('.baz')) + * expect(baz.getText()).toEqual(['1b']) + * var nonexistent = element.all(by.css('.parent')).all(by.css('.NONEXISTENT')) + * expect(nonexistent.getText()).toEqual(['']) + * + * @param {webdriver.Locator} subLocator + * @return {ElementArrayFinder} + */ + all(locator: webdriver.Locator): ElementArrayFinder; + + /** + * Shorthand function for finding arrays of elements by css. + * + * @type {function(string): ElementArrayFinder} + */ + $$(selector: string): ElementArrayFinder; + + /** + * Returns an ElementFinder representation of ElementArrayFinder. It ensures + * that the ElementArrayFinder resolves to one and only one underlying element. + * + * @return {ElementFinder} An ElementFinder representation + * @private + */ + toElementFinder_(): ElementFinder; + + /** + * Returns the most relevant locator. + * + * @example + * $('#ID1').locator() // returns by.css('#ID1') + * $('#ID1').$('#ID2').locator() // returns by.css('#ID2') + * $$('#ID1').filter(filterFn).get(0).click().locator() // returns by.css('#ID1') + * + * @return {webdriver.Locator} + */ + locator(): webdriver.Locator; + + /** + * Evaluates the input as if it were on the scope of the current underlying + * elements. + * + * @view + * {{variableInScope}} + * + * @example + * var value = element(by.id('foo')).evaluate('variableInScope'); + * + * @param {string} expression + * + * @return {ElementArrayFinder} which resolves to the + * evaluated expression for each underlying element. + * The result will be resolved as in + * {@link webdriver.WebDriver.executeScript}. In summary - primitives will + * be resolved as is, functions will be converted to string, and elements + * will be returned as a WebElement. + */ + evaluate(expression: string): ElementArrayFinder; + + /** + * Determine if animation is allowed on the current underlying elements. + * @param {string} value + * + * @example + * // Turns off ng-animate animations for all elements in the + * element(by.css('body')).allowAnimations(false); + * + * @return {ElementArrayFinder} which resolves to whether animation is allowed. + */ + allowAnimations(value: boolean): ElementArrayFinder; + + /** + * Schedules a command to click on this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the click command has completed. + */ + click(): webdriver.promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by this + * instance. + *

+ * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the keysequence, that key state is toggled until one of the + * following occurs: + *

    + *
  • The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + *
  • + *
  • The {@code webdriver.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys("text was", + * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, + * "now text is"); + * // Alternatively: + * element.sendKeys("text was", + * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), + * "now text is"); + *
  • + *
  • The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + *
  • + *
+ * Note: On browsers where native keyboard events are not yet + * supported (e.g. Firefox on OS X), key events will be synthesized. Special + * punctionation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...string} var_args The sequence of keys to + * type. All arguments will be joined into a single sequence (var_args is + * permitted for convenience). + * @return {!webdriver.promise.Promise} A promise that will be resolved when all + * keys have been typed. + */ + sendKeys(...var_args: string[]): webdriver.promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's tag name. + */ + getTagName(): webdriver.promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + *

+ * Warning: the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * requested CSS value. + */ + getCssValue(cssStyleProperty: string): webdriver.promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value even if it has been modified after the + * page has been loaded. More exactly, this method will return the value of the + * given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned. The "style" attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be "boolean" attributes and will be returned as thus: + * + *

async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + *

Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + *

    + *
  • "class" + *
  • "readonly" + *
+ * @param {string} attributeName The name of the attribute to query. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * attribute's value. + */ + getAttribute(attributeName: string): webdriver.promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's visible text. + */ + getText(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's size as a {@code {width:number, height:number}} object. + */ + getSize(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * element's location as a {@code {x:number, y:number}} object. + */ + getLocation(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently enabled. + */ + isEnabled(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently selected. + */ + isSelected(): webdriver.promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the form has been submitted. + */ + submit(): webdriver.promise.Promise; + + /** + * Schedules a command to clear the {@code value} of this element. This command + * has no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the element has been cleared. + */ + clear(): webdriver.promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently visible on the page. + */ + isDisplayed(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the element's outer HTML. + */ + getOuterHtml(): webdriver.promise.Promise; + + /** + * @return {!webdriver.promise.Promise.} A promise + * that resolves to this element's JSON representation as defined by the + * WebDriver wire protocol. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol + */ + getId(): webdriver.promise.Promise + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): webdriver.promise.Promise; + } + + interface LocatorWithColumn extends webdriver.Locator { + column(index: number): webdriver.Locator; + column(name: string): webdriver.Locator; + } + + interface RepeaterLocator extends LocatorWithColumn { + row(index: number): LocatorWithColumn; + } + + interface IProtractorLocatorStrategy extends webdriver.ILocatorStrategy { + /** + * Add a locator to this instance of ProtractorBy. This locator can then be + * used with element(by.locatorName(args)). + * + * @view + * + * + * @example + * // Add the custom locator. + * by.addLocator('buttonTextSimple', + * function(buttonText, opt_parentElement, opt_rootSelector) { + * // This function will be serialized as a string and will execute in the + * // browser. The first argument is the text for the button. The second + * // argument is the parent element, if any. + * var using = opt_parentElement, + * buttons = using.querySelectorAll('button'); + * + * // Return an array of buttons with the text. + * return Array.prototype.filter.call(buttons, function(button) { + * return button.textContent === buttonText; + * }); + * }); + * + * // Use the custom locator. + * element(by.buttonTextSimple('Go!')).click(); + * + * @alias by.addLocator(locatorName, functionOrScript) + * @param {string} name The name of the new locator. + * @param {Function|string} script A script to be run in the context of + * the browser. This script will be passed an array of arguments + * that contains any args passed into the locator followed by the + * element scoping the search and the css selector for the root angular + * element. It should return an array of elements. + */ + addLocator(name: string, script: string): void; + addLocator(name: string, script: Function): void; + + /** + * Find an element by binding. + * + * @view + * {{person.name}} + * + * + * @example + * var span1 = element(by.binding('person.name')); + * expect(span1.getText()).toBe('Foo'); + * + * var span2 = element(by.binding('person.email')); + * expect(span2.getText()).toBe('foo@bar.com'); + * + * @param {string} bindingDescriptor + * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} + */ + binding(bindingDescriptor: string): webdriver.Locator; + + /** + * Find an element by exact binding. + * + * @view + * {{ person.name }} + * + * {{person_phone|uppercase}} + * + * @example + * expect(element(by.exactBinding('person.name')).isPresent()).toBe(true); + * expect(element(by.exactBinding('person-email')).isPresent()).toBe(true); + * expect(element(by.exactBinding('person')).isPresent()).toBe(false); + * expect(element(by.exactBinding('person_phone')).isPresent()).toBe(true); + * expect(element(by.exactBinding('person_phone|uppercase')).isPresent()).toBe(true); + * expect(element(by.exactBinding('phone')).isPresent()).toBe(false); + * + * @param {string} bindingDescriptor + * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} + */ + exactBinding(bindingDescriptor: string): webdriver.Locator; + + /** + * Find an element by ng-model expression. + * + * @alias by.model(modelName) + * @view + * + * + * @example + * var input = element(by.model('person.name')); + * input.sendKeys('123'); + * expect(input.getAttribute('value')).toBe('Foo123'); + * + * @param {string} model ng-model expression. + */ + model(model: string): webdriver.Locator; + + /** + * Find a button by text. + * + * @view + * + * + * @example + * element(by.buttonText('Save')); + * + * @param {string} searchText + * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} + */ + buttonText(searchText: string): webdriver.Locator; + + /** + * Find a button by partial text. + * + * @view + * + * + * @example + * element(by.partialButtonText('Save')); + * + * @param {string} searchText + * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} + */ + partialButtonText(searchText: string): webdriver.Locator; + + + /** + * Find elements inside an ng-repeat. + * + * @view + *
+ * {{cat.name}} + * {{cat.age}} + *
+ * + *
+ * {{$index}} + *
+ *
+ *

{{book.name}}

+ *

{{book.blurb}}

+ *
+ * + * @example + * // Returns the DIV for the second cat. + * var secondCat = element(by.repeater('cat in pets').row(1)); + * + * // Returns the SPAN for the first cat's name. + * var firstCatName = element(by.repeater('cat in pets'). + * row(0).column('{{cat.name}}')); + * + * // Returns a promise that resolves to an array of WebElements from a column + * var ages = element.all( + * by.repeater('cat in pets').column('{{cat.age}}')); + * + * // Returns a promise that resolves to an array of WebElements containing + * // all top level elements repeated by the repeater. For 2 pets rows resolves + * // to an array of 2 elements. + * var rows = element.all(by.repeater('cat in pets')); + * + * // Returns a promise that resolves to an array of WebElements containing all + * // the elements with a binding to the book's name. + * var divs = element.all(by.repeater('book in library').column('book.name')); + * + * // Returns a promise that resolves to an array of WebElements containing + * // the DIVs for the second book. + * var bookInfo = element.all(by.repeater('book in library').row(1)); + * + * // Returns the H4 for the first book's name. + * var firstBookName = element(by.repeater('book in library'). + * row(0).column('{{book.name}}')); + * + * // Returns a promise that resolves to an array of WebElements containing + * // all top level elements repeated by the repeater. For 2 books divs + * // resolves to an array of 4 elements. + * var divs = element.all(by.repeater('book in library')); + */ + repeater(repeatDescriptor: string): RepeaterLocator; + + /** + * Find elements by CSS which contain a certain string. + * + * @view + *
    + *
  • Dog
  • + *
  • Cat
  • + *
+ * + * @example + * // Returns the DIV for the dog, but not cat. + * var dog = element(by.cssContainingText('.pet', 'Dog')); + */ + cssContainingText(cssSelector: string, searchText: string): webdriver.Locator; + + /** + * Find an element by ng-options expression. + * + * @alias by.options(optionsDescriptor) + * @view + * + * + * @example + * var allOptions = element.all(by.options('c for c in colors')); + * expect(allOptions.count()).toEqual(2); + * var firstOption = allOptions.first(); + * expect(firstOption.getText()).toEqual('red'); + * + * @param {string} optionsDescriptor ng-options expression. + */ + options(optionsDescriptor: string): webdriver.Locator; + } + + var By: IProtractorLocatorStrategy; + + interface Protractor extends webdriver.WebDriver { + + /** + * The wrapped webdriver instance. Use this to interact with pages that do + * not contain Angular (such as a log-in screen). + * + * @type {webdriver.WebDriver} + */ + driver: webdriver.WebDriver; + + /** + * Helper function for finding elements. + * + * @type {function(webdriver.Locator): ElementFinder} + */ + element(locator: webdriver.Locator): ElementFinder; + + /** + * Shorthand function for finding elements by css. + * + * @type {function(string): ElementFinder} + */ + $(selector: string): ElementFinder; + + /** + * Shorthand function for finding arrays of elements by css. + * + * @type {function(string): ElementArrayFinder} + */ + $$(selector: string): ElementArrayFinder; + + /** + * All get methods will be resolved against this base URL. Relative URLs are = + * resolved the way anchor tags resolve. + * + * @type {string} + */ + baseUrl: string; + + /** + * The css selector for an element on which to find Angular. This is usually + * 'body' but if your ng-app is on a subsection of the page it may be + * a subelement. + * + * @type {string} + */ + rootEl: string; + + /** + * If true, Protractor will not attempt to synchronize with the page before + * performing actions. This can be harmful because Protractor will not wait + * until $timeouts and $http calls have been processed, which can cause + * tests to become flaky. This should be used only when necessary, such as + * when a page continuously polls an API using $timeout. + * + * @type {boolean} + */ + ignoreSynchronization: boolean; + + /** + * Timeout in milliseconds to wait for pages to load when calling `get`. + * + * @type {number} + */ + getPageTimeout: number; + + /** + * An object that holds custom test parameters. + * + * @type {Object} + */ + params: any; + + /** + * The reset URL to use between page loads. + * + * @type {string} + */ + resetUrl: string; + + /** + * Instruct webdriver to wait until Angular has finished rendering and has + * no outstanding $http calls before continuing. + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * scripts return value. + */ + waitForAngular(): webdriver.promise.Promise; + + /** + * Add a module to load before Angular whenever Protractor.get is called. + * Modules will be registered after existing modules already on the page, + * so any module registered here will override preexisting modules with the same + * name. + * + * @example + * browser.addMockModule('modName', function() { + * angular.module('modName', []).value('foo', 'bar'); + * }); + * + * @param {!string} name The name of the module to load or override. + * @param {!string|Function} script The JavaScript to load the module. + * @param {...*} varArgs Any additional arguments will be provided to + * the script and may be referenced using the `arguments` object. + */ + addMockModule(name: string, script: string, ...varArgs: any[]): void; + addMockModule(name: string, script: Function, ...varArgs: any[]): void; + + /** + * Clear the list of registered mock modules. + */ + clearMockModules(): void; + + /** + * Remove a registered mock module. + * + * @example + * browser.removeMockModule('modName'); + * + * @param {!string} name The name of the module to remove. + */ + removeMockModule(name: string): void; + + /** + * @see webdriver.WebDriver.get + * + * Navigate to the given destination and loads mock modules before + * Angular. Assumes that the page being loaded uses Angular. + * If you need to access a page which does not have Angular on load, use + * the wrapped webdriver directly. + * + * @param {string} destination Destination URL. + * @param {number=} opt_timeout Number of milliseconds to wait for Angular to + * start. + */ + get(destination: string, opt_timeout?: number): webdriver.promise.Promise; + + /** + * See webdriver.WebDriver.refresh + * + * Makes a full reload of the current page and loads mock modules before + * Angular. Assumes that the page being loaded uses Angular. + * If you need to access a page which does not have Angular on load, use + * the wrapped webdriver directly. + * + * @param {number=} opt_timeout Number of seconds to wait for Angular to start. + */ + refresh(opt_timeout?: number): webdriver.promise.Promise; + + /** + * Browse to another page using in-page navigation. + * + * @param {string} url In page URL using the same syntax as $location.url() + * @returns {!webdriver.promise.Promise} A promise that will resolve once + * page has been changed. + */ + setLocation(url: string): webdriver.promise.Promise; + + /** + * Returns the current absolute url from AngularJS. + */ + getLocationAbsUrl(): webdriver.promise.Promise; + + /** + * Pauses the test and injects some helper functions into the browser, so that + * debugging may be done in the browser console. + * + * This should be used under node in debug mode, i.e. with + * protractor debug + * + * @example + * While in the debugger, commands can be scheduled through webdriver by + * entering the repl: + * debug> repl + * Press Ctrl + C to leave rdebug repl + * > ptor.findElement(protractor.By.input('user').sendKeys('Laura')); + * > ptor.debugger(); + * debug> c + * + * This will run the sendKeys command as the next task, then re-enter the + * debugger. + */ + debugger(): void; + + /** + * Beta (unstable) pause function for debugging webdriver tests. Use + * browser.pause() in your test to enter the protractor debugger from that + * point in the control flow. + * Does not require changes to the command line (no need to add 'debug'). + * + * @example + * element(by.id('foo')).click(); + * browser.pause(); + * // Execution will stop before the next click action. + * element(by.id('bar')).click(); + * + * @param {number=} opt_debugPort Optional port to use for the debugging process + */ + pause(opt_debugPort?: number): void; + } + + // Interface for the global browser object. + interface IBrowser extends Protractor { + /** + * Fork another instance of protractor for use in interactive tests. + * + * @param {boolean} opt_useSameUrl Whether to navigate to current url on creation + * @param {boolean} opt_copyMockModules Whether to apply same mock modules on creation + * @return {Protractor} a protractor instance. + */ + forkNewDriverInstance(opt_useSameUrl?: boolean, opt_copyMockModules?: boolean): Protractor; + } + + /** + * Create a new instance of Protractor by wrapping a webdriver instance. + * + * @param {webdriver.WebDriver} webdriver The configured webdriver instance. + * @param {string=} opt_baseUrl A URL to prepend to relative gets. + * @return {Protractor} + */ + function wrapDriver(webdriver: webdriver.WebDriver, opt_baseUrl?: string, opt_rootElement?: string): Protractor; +} + +interface cssSelectorHelper { + (cssLocator: string): protractor.ElementFinder; +} + +interface cssArraySelectorHelper { + (cssLocator: string): protractor.ElementArrayFinder; +} + +declare var browser: protractor.IBrowser; +declare var by: protractor.IProtractorLocatorStrategy; +declare var By: protractor.IProtractorLocatorStrategy; +declare var element: protractor.Element; +declare var $: cssSelectorHelper; +declare var $$: cssArraySelectorHelper; + +declare module 'protractor' { + export = protractor; +} diff --git a/angular1/e2e-tests/typings/angularjs/angular-mocks.d.ts b/angular1/e2e-tests/typings/angularjs/angular-mocks.d.ts new file mode 100644 index 0000000..1d7c80c --- /dev/null +++ b/angular1/e2e-tests/typings/angularjs/angular-mocks.d.ts @@ -0,0 +1,239 @@ +// Type definitions for Angular JS 1.3 (ngMock, ngMockE2E module) +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "angular-mocks/ngMock" { + var _: string; + export = _; +} + +declare module "angular-mocks/ngAnimateMock" { + var _: string; + export = _; +} + +/////////////////////////////////////////////////////////////////////////////// +// functions attached to global object (window) +/////////////////////////////////////////////////////////////////////////////// +declare var module: (...modules: any[]) => any; +declare var inject: (...fns: Function[]) => any; + +/////////////////////////////////////////////////////////////////////////////// +// ngMock module (angular-mocks.js) +/////////////////////////////////////////////////////////////////////////////// +declare module angular { + + /////////////////////////////////////////////////////////////////////////// + // AngularStatic + // We reopen it to add the MockStatic definition + /////////////////////////////////////////////////////////////////////////// + interface IAngularStatic { + mock: IMockStatic; + } + + interface IMockStatic { + // see http://docs.angularjs.org/api/angular.mock.dump + dump(obj: any): string; + + // see http://docs.angularjs.org/api/angular.mock.inject + inject: { + (...fns: Function[]): any; + (...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works + strictDi(val?: boolean): void; + } + + // see http://docs.angularjs.org/api/angular.mock.module + module(...modules: any[]): any; + + // see http://docs.angularjs.org/api/angular.mock.TzDate + TzDate(offset: number, timestamp: number): Date; + TzDate(offset: number, timestamp: string): Date; + } + + /////////////////////////////////////////////////////////////////////////// + // ExceptionHandlerService + // see http://docs.angularjs.org/api/ngMock.$exceptionHandler + // see http://docs.angularjs.org/api/ngMock.$exceptionHandlerProvider + /////////////////////////////////////////////////////////////////////////// + interface IExceptionHandlerProvider extends IServiceProvider { + mode(mode: string): void; + } + + /////////////////////////////////////////////////////////////////////////// + // TimeoutService + // see http://docs.angularjs.org/api/ngMock.$timeout + // Augments the original service + /////////////////////////////////////////////////////////////////////////// + interface ITimeoutService { + flush(delay?: number): void; + flushNext(expectedDelay?: number): void; + verifyNoPendingTasks(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // IntervalService + // see http://docs.angularjs.org/api/ngMock.$interval + // Augments the original service + /////////////////////////////////////////////////////////////////////////// + interface IIntervalService { + flush(millis?: number): number; + } + + /////////////////////////////////////////////////////////////////////////// + // LogService + // see http://docs.angularjs.org/api/ngMock.$log + // Augments the original service + /////////////////////////////////////////////////////////////////////////// + interface ILogService { + assertEmpty(): void; + reset(): void; + } + + interface ILogCall { + logs: string[]; + } + + /////////////////////////////////////////////////////////////////////////// + // HttpBackendService + // see http://docs.angularjs.org/api/ngMock.$httpBackend + /////////////////////////////////////////////////////////////////////////// + interface IHttpBackendService { + flush(count?: number): void; + resetExpectations(): void; + verifyNoOutstandingExpectation(): void; + verifyNoOutstandingRequest(): void; + + expect(method: string, url: string, data?: string, headers?: Object): mock.IRequestHandler; + expect(method: string, url: string, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler; + expect(method: string, url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + expect(method: string, url: string, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + expect(method: string, url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expect(method: string, url: string, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler; + expect(method: string, url: string, data?: Object, headers?: Object): mock.IRequestHandler; + expect(method: string, url: string, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler; + + expectDELETE(url: string, headers?: Object): mock.IRequestHandler; + expectDELETE(url: RegExp, headers?: Object): mock.IRequestHandler; + expectGET(url: string, headers?: Object): mock.IRequestHandler; + expectGET(url: RegExp, headers?: Object): mock.IRequestHandler; + expectHEAD(url: string, headers?: Object): mock.IRequestHandler; + expectHEAD(url: RegExp, headers?: Object): mock.IRequestHandler; + expectJSONP(url: string): mock.IRequestHandler; + expectJSONP(url: RegExp): mock.IRequestHandler; + + expectPATCH(url: string, data?: string, headers?: Object): mock.IRequestHandler; + expectPATCH(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + expectPATCH(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expectPATCH(url: string, data?: Object, headers?: Object): mock.IRequestHandler; + expectPATCH(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + expectPATCH(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + expectPATCH(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expectPATCH(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + + expectPOST(url: string, data?: string, headers?: Object): mock.IRequestHandler; + expectPOST(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + expectPOST(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expectPOST(url: string, data?: Object, headers?: Object): mock.IRequestHandler; + expectPOST(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + expectPOST(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + expectPOST(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expectPOST(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + + expectPUT(url: string, data?: string, headers?: Object): mock.IRequestHandler; + expectPUT(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + expectPUT(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expectPUT(url: string, data?: Object, headers?: Object): mock.IRequestHandler; + expectPUT(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + expectPUT(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + expectPUT(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expectPUT(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + + when(method: string, url: string, data?: string, headers?: Object): mock.IRequestHandler; + when(method: string, url: string, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler; + when(method: string, url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + when(method: string, url: string, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + when(method: string, url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + when(method: string, url: string, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler; + when(method: string, url: string, data?: Object, headers?: Object): mock.IRequestHandler; + when(method: string, url: string, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler; + when(method: string, url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + when(method: string, url: RegExp, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler; + when(method: string, url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + when(method: string, url: RegExp, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + when(method: string, url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + when(method: string, url: RegExp, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler; + when(method: string, url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + when(method: string, url: RegExp, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler; + + whenDELETE(url: string, headers?: Object): mock.IRequestHandler; + whenDELETE(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler; + whenDELETE(url: RegExp, headers?: Object): mock.IRequestHandler; + whenDELETE(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + + whenGET(url: string, headers?: Object): mock.IRequestHandler; + whenGET(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler; + whenGET(url: RegExp, headers?: Object): mock.IRequestHandler; + whenGET(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + + whenHEAD(url: string, headers?: Object): mock.IRequestHandler; + whenHEAD(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler; + whenHEAD(url: RegExp, headers?: Object): mock.IRequestHandler; + whenHEAD(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + + whenJSONP(url: string): mock.IRequestHandler; + whenJSONP(url: RegExp): mock.IRequestHandler; + + whenPATCH(url: string, data?: string, headers?: Object): mock.IRequestHandler; + whenPATCH(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + whenPATCH(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + whenPATCH(url: string, data?: Object, headers?: Object): mock.IRequestHandler; + whenPATCH(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + whenPATCH(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + whenPATCH(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + whenPATCH(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + + whenPOST(url: string, data?: string, headers?: Object): mock.IRequestHandler; + whenPOST(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + whenPOST(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + whenPOST(url: string, data?: Object, headers?: Object): mock.IRequestHandler; + whenPOST(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + whenPOST(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + whenPOST(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + whenPOST(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + + whenPUT(url: string, data?: string, headers?: Object): mock.IRequestHandler; + whenPUT(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + whenPUT(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + whenPUT(url: string, data?: Object, headers?: Object): mock.IRequestHandler; + whenPUT(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + whenPUT(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + whenPUT(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + whenPUT(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + } + + export module mock { + + // returned interface by the the mocked HttpBackendService expect/when methods + interface IRequestHandler { + respond(func: Function): void; + respond(status: number, data?: any, headers?: any): void; + respond(data: any, headers?: any): void; + + // Available wehn ngMockE2E is loaded + passThrough(): void; + } + + } + +} diff --git a/angular1/e2e-tests/typings/angularjs/angular.d.ts b/angular1/e2e-tests/typings/angularjs/angular.d.ts new file mode 100644 index 0000000..eb826fa --- /dev/null +++ b/angular1/e2e-tests/typings/angularjs/angular.d.ts @@ -0,0 +1,1714 @@ +// Type definitions for Angular JS 1.4+ +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +declare var angular: angular.IAngularStatic; + +// Support for painless dependency injection +interface Function { + $inject?: string[]; +} + +// Collapse angular into ng +import ng = angular; +// Support AMD require +declare module 'angular' { + export = angular; +} + +/////////////////////////////////////////////////////////////////////////////// +// ng module (angular.js) +/////////////////////////////////////////////////////////////////////////////// +declare module angular { + + // not directly implemented, but ensures that constructed class implements $get + interface IServiceProviderClass { + new (...args: any[]): IServiceProvider; + } + + interface IServiceProviderFactory { + (...args: any[]): IServiceProvider; + } + + // All service providers extend this interface + interface IServiceProvider { + $get: any; + } + + interface IAngularBootstrapConfig { + strictDi?: boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // AngularStatic + // see http://docs.angularjs.org/api + /////////////////////////////////////////////////////////////////////////// + interface IAngularStatic { + bind(context: any, fn: Function, ...args: any[]): Function; + + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: string, modules?: string, config?: IAngularBootstrapConfig): auto.IInjectorService; + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: string, modules?: Function, config?: IAngularBootstrapConfig): auto.IInjectorService; + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: string, modules?: string[], config?: IAngularBootstrapConfig): auto.IInjectorService; + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: JQuery, modules?: string, config?: IAngularBootstrapConfig): auto.IInjectorService; + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: JQuery, modules?: Function, config?: IAngularBootstrapConfig): auto.IInjectorService; + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: JQuery, modules?: string[], config?: IAngularBootstrapConfig): auto.IInjectorService; + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: Element, modules?: string, config?: IAngularBootstrapConfig): auto.IInjectorService; + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: Element, modules?: Function, config?: IAngularBootstrapConfig): auto.IInjectorService; + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: Element, modules?: string[], config?: IAngularBootstrapConfig): auto.IInjectorService; + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: Document, modules?: string, config?: IAngularBootstrapConfig): auto.IInjectorService; + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: Document, modules?: Function, config?: IAngularBootstrapConfig): auto.IInjectorService; + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: Document, modules?: string[], config?: IAngularBootstrapConfig): auto.IInjectorService; + + /** + * Creates a deep copy of source, which should be an object or an array. + * + * - If no destination is supplied, a copy of the object or array is created. + * - If a destination is provided, all of its elements (for array) or properties (for objects) are deleted and then all elements/properties from the source are copied to it. + * - If source is not an object or array (inc. null and undefined), source is returned. + * - If source is identical to 'destination' an exception will be thrown. + * + * @param source The source that will be used to make a copy. Can be any type, including primitives, null, and undefined. + * @param destination Destination into which the source is copied. If provided, must be of the same type as source. + */ + copy(source: T, destination?: T): T; + + /** + * Wraps a raw DOM element or HTML string as a jQuery element. + * + * If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite." + */ + element: IAugmentedJQueryStatic; + equals(value1: any, value2: any): boolean; + extend(destination: any, ...sources: any[]): any; + + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ + forEach(obj: T[], iterator: (value: T, key: number) => any, context?: any): any; + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ + forEach(obj: { [index: string]: T; }, iterator: (value: T, key: string) => any, context?: any): any; + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ + forEach(obj: any, iterator: (value: any, key: any) => any, context?: any): any; + + fromJson(json: string): any; + identity(arg?: any): any; + injector(modules?: any[]): auto.IInjectorService; + isArray(value: any): boolean; + isDate(value: any): boolean; + isDefined(value: any): boolean; + isElement(value: any): boolean; + isFunction(value: any): boolean; + isNumber(value: any): boolean; + isObject(value: any): boolean; + isString(value: any): boolean; + isUndefined(value: any): boolean; + lowercase(str: string): string; + + /** + * Deeply extends the destination object dst by copying own enumerable properties from the src object(s) to dst. You can specify multiple src objects. If you want to preserve original objects, you can do so by passing an empty object as the target: var object = angular.merge({}, object1, object2). + * + * Unlike extend(), merge() recursively descends into object properties of source objects, performing a deep copy. + * + * @param dst Destination object. + * @param src Source object(s). + */ + merge(dst: any, ...src: any[]): any; + + /** + * The angular.module is a global place for creating, registering and retrieving Angular modules. All modules (angular core or 3rd party) that should be available to an application must be registered using this mechanism. + * + * When passed two or more arguments, a new module is created. If passed only one argument, an existing module (the name passed as the first argument to module) is retrieved. + * + * @param name The name of the module to create or retrieve. + * @param requires The names of modules this module depends on. If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. + * @param configFn Optional configuration function for the module. + */ + module( + name: string, + requires?: string[], + configFn?: Function): IModule; + + noop(...args: any[]): void; + reloadWithDebugInfo(): void; + toJson(obj: any, pretty?: boolean): string; + uppercase(str: string): string; + version: { + full: string; + major: number; + minor: number; + dot: number; + codeName: string; + }; + } + + /////////////////////////////////////////////////////////////////////////// + // Module + // see http://docs.angularjs.org/api/angular.Module + /////////////////////////////////////////////////////////////////////////// + interface IModule { + animation(name: string, animationFactory: Function): IModule; + animation(name: string, inlineAnnotatedFunction: any[]): IModule; + animation(object: Object): IModule; + /** + * Use this method to register work which needs to be performed on module loading. + * + * @param configFn Execute this function on module load. Useful for service configuration. + */ + config(configFn: Function): IModule; + /** + * Use this method to register work which needs to be performed on module loading. + * + * @param inlineAnnotatedFunction Execute this function on module load. Useful for service configuration. + */ + config(inlineAnnotatedFunction: any[]): IModule; + /** + * Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator. + * + * @param name The name of the constant. + * @param value The constant value. + */ + constant(name: string, value: any): IModule; + constant(object: Object): IModule; + /** + * The $controller service is used by Angular to create new controllers. + * + * This provider allows controller registration via the register method. + * + * @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors. + * @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation). + */ + controller(name: string, controllerConstructor: Function): IModule; + /** + * The $controller service is used by Angular to create new controllers. + * + * This provider allows controller registration via the register method. + * + * @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors. + * @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation). + */ + controller(name: string, inlineAnnotatedConstructor: any[]): IModule; + controller(object: Object): IModule; + /** + * Register a new directive with the compiler. + * + * @param name Name of the directive in camel-case (i.e. ngBind which will match as ng-bind) + * @param directiveFactory An injectable directive factory function. + */ + directive(name: string, directiveFactory: IDirectiveFactory): IModule; + /** + * Register a new directive with the compiler. + * + * @param name Name of the directive in camel-case (i.e. ngBind which will match as ng-bind) + * @param directiveFactory An injectable directive factory function. + */ + directive(name: string, inlineAnnotatedFunction: any[]): IModule; + directive(object: Object): IModule; + /** + * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider. + * + * @param name The name of the instance. + * @param $getFn The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}). + */ + factory(name: string, $getFn: Function): IModule; + /** + * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider. + * + * @param name The name of the instance. + * @param inlineAnnotatedFunction The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}). + */ + factory(name: string, inlineAnnotatedFunction: any[]): IModule; + factory(object: Object): IModule; + filter(name: string, filterFactoryFunction: Function): IModule; + filter(name: string, inlineAnnotatedFunction: any[]): IModule; + filter(object: Object): IModule; + provider(name: string, serviceProviderFactory: IServiceProviderFactory): IModule; + provider(name: string, serviceProviderConstructor: IServiceProviderClass): IModule; + provider(name: string, inlineAnnotatedConstructor: any[]): IModule; + provider(name: string, providerObject: IServiceProvider): IModule; + provider(object: Object): IModule; + /** + * Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests. + */ + run(initializationFunction: Function): IModule; + /** + * Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests. + */ + run(inlineAnnotatedFunction: any[]): IModule; + service(name: string, serviceConstructor: Function): IModule; + service(name: string, inlineAnnotatedConstructor: any[]): IModule; + service(object: Object): IModule; + /** + * Register a value service with the $injector, such as a string, a number, an array, an object or a function. This is short for registering a service where its provider's $get property is a factory function that takes no arguments and returns the value service. + + Value services are similar to constant services, except that they cannot be injected into a module configuration function (see config) but they can be overridden by an Angular decorator. + * + * @param name The name of the instance. + * @param value The value. + */ + value(name: string, value: any): IModule; + value(object: Object): IModule; + + /** + * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. + * @param name The name of the service to decorate + * @param decorator This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. + */ + decorator(name:string, decoratorConstructor: Function): IModule; + decorator(name:string, inlineAnnotatedConstructor: any[]): IModule; + + // Properties + name: string; + requires: string[]; + } + + /////////////////////////////////////////////////////////////////////////// + // Attributes + // see http://docs.angularjs.org/api/ng.$compile.directive.Attributes + /////////////////////////////////////////////////////////////////////////// + interface IAttributes { + /** + * this is necessary to be able to access the scoped attributes. it's not very elegant + * because you have to use attrs['foo'] instead of attrs.foo but I don't know of a better way + * this should really be limited to return string but it creates this problem: http://stackoverflow.com/q/17201854/165656 + */ + [name: string]: any; + + /** + * Adds the CSS class value specified by the classVal parameter to the + * element. If animations are enabled then an animation will be triggered + * for the class addition. + */ + $addClass(classVal: string): void; + + /** + * Removes the CSS class value specified by the classVal parameter from the + * element. If animations are enabled then an animation will be triggered for + * the class removal. + */ + $removeClass(classVal: string): void; + + /** + * Set DOM element attribute value. + */ + $set(key: string, value: any): void; + + /** + * Observes an interpolated attribute. + * The observer function will be invoked once during the next $digest + * following compilation. The observer is then invoked whenever the + * interpolated value changes. + */ + $observe(name: string, fn: (value?: any) => any): Function; + + /** + * A map of DOM element attribute names to the normalized name. This is needed + * to do reverse lookup from normalized name back to actual name. + */ + $attr: Object; + } + + /** + * form.FormController - type in module ng + * see https://docs.angularjs.org/api/ng/type/form.FormController + */ + interface IFormController { + + /** + * Indexer which should return ng.INgModelController for most properties but cannot because of "All named properties must be assignable to string indexer type" constraint - see https://github.com/Microsoft/TypeScript/issues/272 + */ + [name: string]: any; + + $pristine: boolean; + $dirty: boolean; + $valid: boolean; + $invalid: boolean; + $submitted: boolean; + $error: any; + $addControl(control: INgModelController): void; + $removeControl(control: INgModelController): void; + $setValidity(validationErrorKey: string, isValid: boolean, control: INgModelController): void; + $setDirty(): void; + $setPristine(): void; + $commitViewValue(): void; + $rollbackViewValue(): void; + $setSubmitted(): void; + $setUntouched(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // NgModelController + // see http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController + /////////////////////////////////////////////////////////////////////////// + interface INgModelController { + $render(): void; + $setValidity(validationErrorKey: string, isValid: boolean): void; + // Documentation states viewValue and modelValue to be a string but other + // types do work and it's common to use them. + $setViewValue(value: any, trigger?: string): void; + $setPristine(): void; + $setDirty(): void; + $validate(): void; + $setTouched(): void; + $setUntouched(): void; + $rollbackViewValue(): void; + $commitViewValue(): void; + $isEmpty(value: any): boolean; + + $viewValue: any; + + $modelValue: any; + + $parsers: IModelParser[]; + $formatters: IModelFormatter[]; + $viewChangeListeners: IModelViewChangeListener[]; + $error: any; + $name: string; + + $touched: boolean; + $untouched: boolean; + + $validators: IModelValidators; + $asyncValidators: IAsyncModelValidators; + + $pending: any; + $pristine: boolean; + $dirty: boolean; + $valid: boolean; + $invalid: boolean; + } + + interface IModelValidators { + [index: string]: (modelValue: any, viewValue: string) => boolean; + } + + interface IAsyncModelValidators { + [index: string]: (modelValue: any, viewValue: string) => IPromise; + } + + interface IModelParser { + (value: any): any; + } + + interface IModelFormatter { + (value: any): any; + } + + interface IModelViewChangeListener { + (): void; + } + + /** + * $rootScope - $rootScopeProvider - service in module ng + * see https://docs.angularjs.org/api/ng/type/$rootScope.Scope and https://docs.angularjs.org/api/ng/service/$rootScope + */ + interface IRootScopeService { + [index: string]: any; + + $apply(): any; + $apply(exp: string): any; + $apply(exp: (scope: IScope) => any): any; + + $applyAsync(): any; + $applyAsync(exp: string): any; + $applyAsync(exp: (scope: IScope) => any): any; + + /** + * Dispatches an event name downwards to all child scopes (and their children) notifying the registered $rootScope.Scope listeners. + * + * The event life cycle starts at the scope on which $broadcast was called. All listeners listening for name event on this scope get notified. Afterwards, the event propagates to all direct and indirect scopes of the current scope and calls all registered listeners along the way. The event cannot be canceled. + * + * Any exception emitted from the listeners will be passed onto the $exceptionHandler service. + * + * @param name Event name to broadcast. + * @param args Optional one or more arguments which will be passed onto the event listeners. + */ + $broadcast(name: string, ...args: any[]): IAngularEvent; + $destroy(): void; + $digest(): void; + /** + * Dispatches an event name upwards through the scope hierarchy notifying the registered $rootScope.Scope listeners. + * + * The event life cycle starts at the scope on which $emit was called. All listeners listening for name event on this scope get notified. Afterwards, the event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it. + * + * Any exception emitted from the listeners will be passed onto the $exceptionHandler service. + * + * @param name Event name to emit. + * @param args Optional one or more arguments which will be passed onto the event listeners. + */ + $emit(name: string, ...args: any[]): IAngularEvent; + + $eval(): any; + $eval(expression: string, locals?: Object): any; + $eval(expression: (scope: IScope) => any, locals?: Object): any; + + $evalAsync(): void; + $evalAsync(expression: string): void; + $evalAsync(expression: (scope: IScope) => any): void; + + // Defaults to false by the implementation checking strategy + $new(isolate?: boolean, parent?: IScope): IScope; + + /** + * Listens on events of a given type. See $emit for discussion of event life cycle. + * + * The event listener function format is: function(event, args...). + * + * @param name Event name to listen on. + * @param listener Function to call when the event is emitted. + */ + $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; + + $watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function; + $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; + $watch(watchExpression: (scope: IScope) => any, listener?: string, objectEquality?: boolean): Function; + $watch(watchExpression: (scope: IScope) => any, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; + + $watchCollection(watchExpression: string, listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; + $watchCollection(watchExpression: (scope: IScope) => any, listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; + + $watchGroup(watchExpressions: any[], listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; + $watchGroup(watchExpressions: { (scope: IScope): any }[], listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; + + $parent: IScope; + $root: IRootScopeService; + $id: number; + + // Hidden members + $$isolateBindings: any; + $$phase: any; + } + + interface IScope extends IRootScopeService { } + + /** + * $scope for ngRepeat directive. + * see https://docs.angularjs.org/api/ng/directive/ngRepeat + */ + interface IRepeatScope extends IScope { + + /** + * iterator offset of the repeated element (0..length-1). + */ + $index: number; + + /** + * true if the repeated element is first in the iterator. + */ + $first: boolean; + + /** + * true if the repeated element is between the first and last in the iterator. + */ + $middle: boolean; + + /** + * true if the repeated element is last in the iterator. + */ + $last: boolean; + + /** + * true if the iterator position $index is even (otherwise false). + */ + $even: boolean; + + /** + * true if the iterator position $index is odd (otherwise false). + */ + $odd: boolean; + + } + + interface IAngularEvent { + /** + * the scope on which the event was $emit-ed or $broadcast-ed. + */ + targetScope: IScope; + /** + * the scope that is currently handling the event. Once the event propagates through the scope hierarchy, this property is set to null. + */ + currentScope: IScope; + /** + * name of the event. + */ + name: string; + /** + * calling stopPropagation function will cancel further event propagation (available only for events that were $emit-ed). + */ + stopPropagation?: Function; + /** + * calling preventDefault sets defaultPrevented flag to true. + */ + preventDefault: Function; + /** + * true if preventDefault was called. + */ + defaultPrevented: boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // WindowService + // see http://docs.angularjs.org/api/ng.$window + /////////////////////////////////////////////////////////////////////////// + interface IWindowService extends Window { + [key: string]: any; + } + + /////////////////////////////////////////////////////////////////////////// + // BrowserService + // TODO undocumented, so we need to get it from the source code + /////////////////////////////////////////////////////////////////////////// + interface IBrowserService { + defer: angular.ITimeoutService; + [key: string]: any; + } + + /////////////////////////////////////////////////////////////////////////// + // TimeoutService + // see http://docs.angularjs.org/api/ng.$timeout + /////////////////////////////////////////////////////////////////////////// + interface ITimeoutService { + (func: Function, delay?: number, invokeApply?: boolean): IPromise; + cancel(promise: IPromise): boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // IntervalService + // see http://docs.angularjs.org/api/ng.$interval + /////////////////////////////////////////////////////////////////////////// + interface IIntervalService { + (func: Function, delay: number, count?: number, invokeApply?: boolean): IPromise; + cancel(promise: IPromise): boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // AngularProvider + // see http://docs.angularjs.org/api/ng/provider/$animateProvider + /////////////////////////////////////////////////////////////////////////// + interface IAnimateProvider { + /** + * Registers a new injectable animation factory function. + * + * @param name The name of the animation. + * @param factory The factory function that will be executed to return the animation object. + */ + register(name: string, factory: () => IAnimateCallbackObject): void; + + /** + * Gets and/or sets the CSS class expression that is checked when performing an animation. + * + * @param expression The className expression which will be checked against all animations. + * @returns The current CSS className expression value. If null then there is no expression value. + */ + classNameFilter(expression?: RegExp): RegExp; + } + + /** + * The animation object which contains callback functions for each event that is expected to be animated. + */ + interface IAnimateCallbackObject { + eventFn(element: Node, doneFn: () => void): Function; + } + + /** + * $filter - $filterProvider - service in module ng + * + * Filters are used for formatting data displayed to the user. + * + * see https://docs.angularjs.org/api/ng/service/$filter + */ + interface IFilterService { + /** + * Usage: + * $filter(name); + * + * @param name Name of the filter function to retrieve + */ + (name: string): Function; + } + + /** + * $filterProvider - $filter - provider in module ng + * + * Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To achieve this a filter definition consists of a factory function which is annotated with dependencies and is responsible for creating a filter function. + * + * see https://docs.angularjs.org/api/ng/provider/$filterProvider + */ + interface IFilterProvider extends IServiceProvider { + /** + * register(name); + * + * @param name Name of the filter function, or an object map of filters where the keys are the filter names and the values are the filter factories. Note: Filter names must be valid angular Expressions identifiers, such as uppercase or orderBy. Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace your filters, then you can use capitalization (myappSubsectionFilterx) or underscores (myapp_subsection_filterx). + */ + register(name: string | {}): IServiceProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // LocaleService + // see http://docs.angularjs.org/api/ng.$locale + /////////////////////////////////////////////////////////////////////////// + interface ILocaleService { + id: string; + + // These are not documented + // Check angular's i18n files for exemples + NUMBER_FORMATS: ILocaleNumberFormatDescriptor; + DATETIME_FORMATS: ILocaleDateTimeFormatDescriptor; + pluralCat: (num: any) => string; + } + + interface ILocaleNumberFormatDescriptor { + DECIMAL_SEP: string; + GROUP_SEP: string; + PATTERNS: ILocaleNumberPatternDescriptor[]; + CURRENCY_SYM: string; + } + + interface ILocaleNumberPatternDescriptor { + minInt: number; + minFrac: number; + maxFrac: number; + posPre: string; + posSuf: string; + negPre: string; + negSuf: string; + gSize: number; + lgSize: number; + } + + interface ILocaleDateTimeFormatDescriptor { + MONTH: string[]; + SHORTMONTH: string[]; + DAY: string[]; + SHORTDAY: string[]; + AMPMS: string[]; + medium: string; + short: string; + fullDate: string; + longDate: string; + mediumDate: string; + shortDate: string; + mediumTime: string; + shortTime: string; + } + + /////////////////////////////////////////////////////////////////////////// + // LogService + // see http://docs.angularjs.org/api/ng.$log + // see http://docs.angularjs.org/api/ng.$logProvider + /////////////////////////////////////////////////////////////////////////// + interface ILogService { + debug: ILogCall; + error: ILogCall; + info: ILogCall; + log: ILogCall; + warn: ILogCall; + } + + interface ILogProvider { + debugEnabled(): boolean; + debugEnabled(enabled: boolean): ILogProvider; + } + + // We define this as separate interface so we can reopen it later for + // the ngMock module. + interface ILogCall { + (...args: any[]): void; + } + + /////////////////////////////////////////////////////////////////////////// + // ParseService + // see http://docs.angularjs.org/api/ng.$parse + // see http://docs.angularjs.org/api/ng.$parseProvider + /////////////////////////////////////////////////////////////////////////// + interface IParseService { + (expression: string): ICompiledExpression; + } + + interface IParseProvider { + logPromiseWarnings(): boolean; + logPromiseWarnings(value: boolean): IParseProvider; + + unwrapPromises(): boolean; + unwrapPromises(value: boolean): IParseProvider; + } + + interface ICompiledExpression { + (context: any, locals?: any): any; + + // If value is not provided, undefined is gonna be used since the implementation + // does not check the parameter. Let's force a value for consistency. If consumer + // whants to undefine it, pass the undefined value explicitly. + assign(context: any, value: any): any; + } + + /** + * $location - $locationProvider - service in module ng + * see https://docs.angularjs.org/api/ng/service/$location + */ + interface ILocationService { + absUrl(): string; + hash(): string; + hash(newHash: string): ILocationService; + host(): string; + + /** + * Return path of current url + */ + path(): string; + + /** + * Change path when called with parameter and return $location. + * Note: Path should always begin with forward slash (/), this method will add the forward slash if it is missing. + * + * @param path New path + */ + path(path: string): ILocationService; + + port(): number; + protocol(): string; + replace(): ILocationService; + + /** + * Return search part (as object) of current url + */ + search(): any; + + /** + * Change search part when called with parameter and return $location. + * + * @param search When called with a single argument the method acts as a setter, setting the search component of $location to the specified value. + * + * If the argument is a hash object containing an array of values, these values will be encoded as duplicate search parameters in the url. + */ + search(search: any): ILocationService; + + /** + * Change search part when called with parameter and return $location. + * + * @param search New search params + * @param paramValue If search is a string or a Number, then paramValue will override only a single search property. If paramValue is null, the property specified via the first argument will be deleted. If paramValue is an array, it will override the property of the search component of $location specified via the first argument. If paramValue is true, the property specified via the first argument will be added with no value nor trailing equal sign. + */ + search(search: string, paramValue: string|number|string[]|boolean): ILocationService; + + state(): any; + state(state: any): ILocationService; + url(): string; + url(url: string): ILocationService; + } + + interface ILocationProvider extends IServiceProvider { + hashPrefix(): string; + hashPrefix(prefix: string): ILocationProvider; + html5Mode(): boolean; + + // Documentation states that parameter is string, but + // implementation tests it as boolean, which makes more sense + // since this is a toggler + html5Mode(active: boolean): ILocationProvider; + html5Mode(mode: { enabled?: boolean; requireBase?: boolean; rewriteLinks?: boolean; }): ILocationProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // DocumentService + // see http://docs.angularjs.org/api/ng.$document + /////////////////////////////////////////////////////////////////////////// + interface IDocumentService extends IAugmentedJQuery {} + + /////////////////////////////////////////////////////////////////////////// + // ExceptionHandlerService + // see http://docs.angularjs.org/api/ng.$exceptionHandler + /////////////////////////////////////////////////////////////////////////// + interface IExceptionHandlerService { + (exception: Error, cause?: string): void; + } + + /////////////////////////////////////////////////////////////////////////// + // RootElementService + // see http://docs.angularjs.org/api/ng.$rootElement + /////////////////////////////////////////////////////////////////////////// + interface IRootElementService extends JQuery {} + + interface IQResolveReject { + (): void; + (value: T): void; + } + /** + * $q - service in module ng + * A promise/deferred implementation inspired by Kris Kowal's Q. + * See http://docs.angularjs.org/api/ng/service/$q + */ + interface IQService { + new (resolver: (resolve: IQResolveReject) => any): IPromise; + new (resolver: (resolve: IQResolveReject, reject: IQResolveReject) => any): IPromise; + new (resolver: (resolve: IQResolveReject, reject: IQResolveReject) => any): IPromise; + + /** + * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. + * + * Returns a single promise that will be resolved with an array of values, each value corresponding to the promise at the same index in the promises array. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. + * + * @param promises An array of promises. + */ + all(promises: IPromise[]): IPromise; + /** + * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. + * + * Returns a single promise that will be resolved with a hash of values, each value corresponding to the promise at the same key in the promises hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. + * + * @param promises A hash of promises. + */ + all(promises: { [id: string]: IPromise; }): IPromise<{ [id: string]: any; }>; + /** + * Creates a Deferred object which represents a task which will finish in the future. + */ + defer(): IDeferred; + /** + * Creates a promise that is resolved as rejected with the specified reason. This api should be used to forward rejection in a chain of promises. If you are dealing with the last promise in a promise chain, you don't need to worry about it. + * + * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of reject as the throw keyword in JavaScript. This also means that if you "catch" an error via a promise error callback and you want to forward the error to the promise derived from the current promise, you have to "rethrow" the error by returning a rejection constructed via reject. + * + * @param reason Constant, message, exception or an object representing the rejection reason. + */ + reject(reason?: any): IPromise; + /** + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. + * + * @param value Value or a promise + */ + when(value: IPromise|T): IPromise; + /** + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. + * + * @param value Value or a promise + */ + when(): IPromise; + } + + interface IPromise { + /** + * Regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected. + * + * This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method. + */ + then(successCallback: (promiseValue: T) => IHttpPromise|IPromise|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise; + + /** + * Shorthand for promise.then(null, errorCallback) + */ + catch(onRejected: (reason: any) => IHttpPromise|IPromise|TResult): IPromise; + + /** + * Allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information. + * + * Because finally is a reserved word in JavaScript and reserved keywords are not supported as property names by ES3, you'll need to invoke the method like promise['finally'](callback) to make your code IE8 and Android 2.x compatible. + */ + finally(finallyCallback: () => any): IPromise; + } + + interface IDeferred { + resolve(value?: T): void; + reject(reason?: any): void; + notify(state?: any): void; + promise: IPromise; + } + + /////////////////////////////////////////////////////////////////////////// + // AnchorScrollService + // see http://docs.angularjs.org/api/ng.$anchorScroll + /////////////////////////////////////////////////////////////////////////// + interface IAnchorScrollService { + (): void; + yOffset: any; + } + + interface IAnchorScrollProvider extends IServiceProvider { + disableAutoScrolling(): void; + } + + /** + * $cacheFactory - service in module ng + * + * Factory that constructs Cache objects and gives access to them. + * + * see https://docs.angularjs.org/api/ng/service/$cacheFactory + */ + interface ICacheFactoryService { + /** + * Factory that constructs Cache objects and gives access to them. + * + * @param cacheId Name or id of the newly created cache. + * @param optionsMap Options object that specifies the cache behavior. Properties: + * + * capacity — turns the cache into LRU cache. + */ + (cacheId: string, optionsMap?: { capacity?: number; }): ICacheObject; + + /** + * Get information about all the caches that have been created. + * @returns key-value map of cacheId to the result of calling cache#info + */ + info(): any; + + /** + * Get access to a cache object by the cacheId used when it was created. + * + * @param cacheId Name or id of a cache to access. + */ + get(cacheId: string): ICacheObject; + } + + /** + * $cacheFactory.Cache - type in module ng + * + * A cache object used to store and retrieve data, primarily used by $http and the script directive to cache templates and other data. + * + * see https://docs.angularjs.org/api/ng/type/$cacheFactory.Cache + */ + interface ICacheObject { + /** + * Retrieve information regarding a particular Cache. + */ + info(): { + /** + * the id of the cache instance + */ + id: string; + + /** + * the number of entries kept in the cache instance + */ + size: number; + + //...: any additional properties from the options object when creating the cache. + }; + + /** + * Inserts a named entry into the Cache object to be retrieved later, and incrementing the size of the cache if the key was not already present in the cache. If behaving like an LRU cache, it will also remove stale entries from the set. + * + * It will not insert undefined values into the cache. + * + * @param key the key under which the cached data is stored. + * @param value the value to store alongside the key. If it is undefined, the key will not be stored. + */ + put(key: string, value?: T): T; + + /** + * Retrieves named data stored in the Cache object. + * + * @param key the key of the data to be retrieved + */ + get(key: string): any; + + /** + * Removes an entry from the Cache object. + * + * @param key the key of the entry to be removed + */ + remove(key: string): void; + + /** + * Clears the cache object of any entries. + */ + removeAll(): void; + + /** + * Destroys the Cache object entirely, removing it from the $cacheFactory set. + */ + destroy(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // CompileService + // see http://docs.angularjs.org/api/ng.$compile + // see http://docs.angularjs.org/api/ng.$compileProvider + /////////////////////////////////////////////////////////////////////////// + interface ICompileService { + (element: string, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction; + (element: Element, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction; + (element: JQuery, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction; + } + + interface ICompileProvider extends IServiceProvider { + directive(name: string, directiveFactory: Function): ICompileProvider; + + // Undocumented, but it is there... + directive(directivesMap: any): ICompileProvider; + + aHrefSanitizationWhitelist(): RegExp; + aHrefSanitizationWhitelist(regexp: RegExp): ICompileProvider; + + imgSrcSanitizationWhitelist(): RegExp; + imgSrcSanitizationWhitelist(regexp: RegExp): ICompileProvider; + + debugInfoEnabled(enabled?: boolean): any; + } + + interface ICloneAttachFunction { + // Let's hint but not force cloneAttachFn's signature + (clonedElement?: JQuery, scope?: IScope): any; + } + + // This corresponds to the "publicLinkFn" returned by $compile. + interface ITemplateLinkingFunction { + (scope: IScope, cloneAttachFn?: ICloneAttachFunction): IAugmentedJQuery; + } + + // This corresponds to $transclude (and also the transclude function passed to link). + interface ITranscludeFunction { + // If the scope is provided, then the cloneAttachFn must be as well. + (scope: IScope, cloneAttachFn: ICloneAttachFunction): IAugmentedJQuery; + // If one argument is provided, then it's assumed to be the cloneAttachFn. + (cloneAttachFn?: ICloneAttachFunction): IAugmentedJQuery; + } + + /////////////////////////////////////////////////////////////////////////// + // ControllerService + // see http://docs.angularjs.org/api/ng.$controller + // see http://docs.angularjs.org/api/ng.$controllerProvider + /////////////////////////////////////////////////////////////////////////// + interface IControllerService { + // Although the documentation doesn't state this, locals are optional + (controllerConstructor: Function, locals?: any): any; + (controllerName: string, locals?: any): any; + } + + interface IControllerProvider extends IServiceProvider { + register(name: string, controllerConstructor: Function): void; + register(name: string, dependencyAnnotatedConstructor: any[]): void; + allowGlobals(): void; + } + + /** + * HttpService + * see http://docs.angularjs.org/api/ng/service/$http + */ + interface IHttpService { + /** + * Object describing the request to be made and how it should be processed. + */ + (config: IRequestConfig): IHttpPromise; + + /** + * Shortcut method to perform GET request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + get(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform DELETE request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + delete(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform HEAD request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + head(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform JSONP request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + jsonp(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform POST request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param data Request content + * @param config Optional configuration object + */ + post(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform PUT request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param data Request content + * @param config Optional configuration object + */ + put(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform PATCH request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param data Request content + * @param config Optional configuration object + */ + patch(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Runtime equivalent of the $httpProvider.defaults property. Allows configuration of default headers, withCredentials as well as request and response transformations. + */ + defaults: IRequestConfig; + + /** + * Array of config objects for currently pending requests. This is primarily meant to be used for debugging purposes. + */ + pendingRequests: any[]; + } + + /** + * Object describing the request to be made and how it should be processed. + * see http://docs.angularjs.org/api/ng/service/$http#usage + */ + interface IRequestShortcutConfig { + /** + * {Object.} + * Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified. + */ + params?: any; + + /** + * Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent. + */ + headers?: any; + + /** + * Name of HTTP header to populate with the XSRF token. + */ + xsrfHeaderName?: string; + + /** + * Name of cookie containing the XSRF token. + */ + xsrfCookieName?: string; + + /** + * {boolean|Cache} + * If true, a default $http cache will be used to cache the GET request, otherwise if a cache instance built with $cacheFactory, this cache will be used for caching. + */ + cache?: any; + + /** + * whether to to set the withCredentials flag on the XHR object. See [requests with credentials]https://developer.mozilla.org/en/http_access_control#section_5 for more information. + */ + withCredentials?: boolean; + + /** + * {string|Object} + * Data to be sent as the request message data. + */ + data?: any; + + /** + * {function(data, headersGetter)|Array.} + * Transform function or an array of such functions. The transform function takes the http request body and headers and returns its transformed (typically serialized) version. + */ + transformRequest?: any; + + /** + * {function(data, headersGetter)|Array.} + * Transform function or an array of such functions. The transform function takes the http response body and headers and returns its transformed (typically deserialized) version. + */ + transformResponse?: any; + + /** + * {number|Promise} + * Timeout in milliseconds, or promise that should abort the request when resolved. + */ + timeout?: any; + + /** + * See requestType. + */ + responseType?: string; + } + + /** + * Object describing the request to be made and how it should be processed. + * see http://docs.angularjs.org/api/ng/service/$http#usage + */ + interface IRequestConfig extends IRequestShortcutConfig { + /** + * HTTP method (e.g. 'GET', 'POST', etc) + */ + method: string; + /** + * Absolute or relative URL of the resource that is being requested. + */ + url: string; + } + + interface IHttpHeadersGetter { + (): { [name: string]: string; }; + (headerName: string): string; + } + + interface IHttpPromiseCallback { + (data: T, status: number, headers: IHttpHeadersGetter, config: IRequestConfig): void; + } + + interface IHttpPromiseCallbackArg { + data?: T; + status?: number; + headers?: IHttpHeadersGetter; + config?: IRequestConfig; + statusText?: string; + } + + interface IHttpPromise extends IPromise> { + success(callback: IHttpPromiseCallback): IHttpPromise; + error(callback: IHttpPromiseCallback): IHttpPromise; + then(successCallback: (response: IHttpPromiseCallbackArg) => IPromise|TResult, errorCallback?: (response: IHttpPromiseCallbackArg) => any): IPromise; + } + + /** + * Object that controls the defaults for $http provider + * https://docs.angularjs.org/api/ng/service/$http#defaults + */ + interface IHttpProviderDefaults { + xsrfCookieName?: string; + xsrfHeaderName?: string; + withCredentials?: boolean; + headers?: { + common?: any; + post?: any; + put?: any; + patch?: any; + } + } + + interface IHttpProvider extends IServiceProvider { + defaults: IHttpProviderDefaults; + interceptors: any[]; + useApplyAsync(): boolean; + useApplyAsync(value: boolean): IHttpProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // HttpBackendService + // see http://docs.angularjs.org/api/ng.$httpBackend + // You should never need to use this service directly. + /////////////////////////////////////////////////////////////////////////// + interface IHttpBackendService { + // XXX Perhaps define callback signature in the future + (method: string, url: string, post?: any, callback?: Function, headers?: any, timeout?: number, withCredentials?: boolean): void; + } + + /////////////////////////////////////////////////////////////////////////// + // InterpolateService + // see http://docs.angularjs.org/api/ng.$interpolate + // see http://docs.angularjs.org/api/ng.$interpolateProvider + /////////////////////////////////////////////////////////////////////////// + interface IInterpolateService { + (text: string, mustHaveExpression?: boolean, trustedContext?: string, allOrNothing?: boolean): IInterpolationFunction; + endSymbol(): string; + startSymbol(): string; + } + + interface IInterpolationFunction { + (context: any): string; + } + + interface IInterpolateProvider extends IServiceProvider { + startSymbol(): string; + startSymbol(value: string): IInterpolateProvider; + endSymbol(): string; + endSymbol(value: string): IInterpolateProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // TemplateCacheService + // see http://docs.angularjs.org/api/ng.$templateCache + /////////////////////////////////////////////////////////////////////////// + interface ITemplateCacheService extends ICacheObject {} + + /////////////////////////////////////////////////////////////////////////// + // SCEService + // see http://docs.angularjs.org/api/ng.$sce + /////////////////////////////////////////////////////////////////////////// + interface ISCEService { + getTrusted(type: string, mayBeTrusted: any): any; + getTrustedCss(value: any): any; + getTrustedHtml(value: any): any; + getTrustedJs(value: any): any; + getTrustedResourceUrl(value: any): any; + getTrustedUrl(value: any): any; + parse(type: string, expression: string): (context: any, locals: any) => any; + parseAsCss(expression: string): (context: any, locals: any) => any; + parseAsHtml(expression: string): (context: any, locals: any) => any; + parseAsJs(expression: string): (context: any, locals: any) => any; + parseAsResourceUrl(expression: string): (context: any, locals: any) => any; + parseAsUrl(expression: string): (context: any, locals: any) => any; + trustAs(type: string, value: any): any; + trustAsHtml(value: any): any; + trustAsJs(value: any): any; + trustAsResourceUrl(value: any): any; + trustAsUrl(value: any): any; + isEnabled(): boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // SCEProvider + // see http://docs.angularjs.org/api/ng.$sceProvider + /////////////////////////////////////////////////////////////////////////// + interface ISCEProvider extends IServiceProvider { + enabled(value: boolean): void; + } + + /////////////////////////////////////////////////////////////////////////// + // SCEDelegateService + // see http://docs.angularjs.org/api/ng.$sceDelegate + /////////////////////////////////////////////////////////////////////////// + interface ISCEDelegateService { + getTrusted(type: string, mayBeTrusted: any): any; + trustAs(type: string, value: any): any; + valueOf(value: any): any; + } + + + /////////////////////////////////////////////////////////////////////////// + // SCEDelegateProvider + // see http://docs.angularjs.org/api/ng.$sceDelegateProvider + /////////////////////////////////////////////////////////////////////////// + interface ISCEDelegateProvider extends IServiceProvider { + resourceUrlBlacklist(blacklist: any[]): void; + resourceUrlWhitelist(whitelist: any[]): void; + } + + /** + * $templateRequest service + * see http://docs.angularjs.org/api/ng/service/$templateRequest + */ + interface ITemplateRequestService { + /** + * Downloads a template using $http and, upon success, stores the + * contents inside of $templateCache. + * + * If the HTTP request fails or the response data of the HTTP request is + * empty then a $compile error will be thrown (unless + * {ignoreRequestError} is set to true). + * + * @param tpl The template URL. + * @param ignoreRequestError Whether or not to ignore the exception + * when the request fails or the template is + * empty. + * + * @return A promise whose value is the template content. + */ + (tpl: string, ignoreRequestError?: boolean): IPromise; + /** + * total amount of pending template requests being downloaded. + * @type {number} + */ + totalPendingRequests: number; + } + + /////////////////////////////////////////////////////////////////////////// + // Directive + // see http://docs.angularjs.org/api/ng.$compileProvider#directive + // and http://docs.angularjs.org/guide/directive + /////////////////////////////////////////////////////////////////////////// + + interface IDirectiveFactory { + (...args: any[]): IDirective; + } + + interface IDirectiveLinkFn { + ( + scope: IScope, + instanceElement: IAugmentedJQuery, + instanceAttributes: IAttributes, + controller: any, + transclude: ITranscludeFunction + ): void; + } + + interface IDirectivePrePost { + pre?: IDirectiveLinkFn; + post?: IDirectiveLinkFn; + } + + interface IDirectiveCompileFn { + ( + templateElement: IAugmentedJQuery, + templateAttributes: IAttributes, + transclude: ITranscludeFunction + ): IDirectivePrePost; + } + + interface IDirective { + compile?: IDirectiveCompileFn; + controller?: any; + controllerAs?: string; + bindToController?: boolean|Object; + link?: IDirectiveLinkFn | IDirectivePrePost; + name?: string; + priority?: number; + replace?: boolean; + require?: any; + restrict?: string; + scope?: any; + template?: any; + templateUrl?: any; + terminal?: boolean; + transclude?: any; + } + + /** + * angular.element + * when calling angular.element, angular returns a jQuery object, + * augmented with additional methods like e.g. scope. + * see: http://docs.angularjs.org/api/angular.element + */ + interface IAugmentedJQueryStatic extends JQueryStatic { + (selector: string, context?: any): IAugmentedJQuery; + (element: Element): IAugmentedJQuery; + (object: {}): IAugmentedJQuery; + (elementArray: Element[]): IAugmentedJQuery; + (object: JQuery): IAugmentedJQuery; + (func: Function): IAugmentedJQuery; + (array: any[]): IAugmentedJQuery; + (): IAugmentedJQuery; + } + + interface IAugmentedJQuery extends JQuery { + // TODO: events, how to define? + //$destroy + + find(selector: string): IAugmentedJQuery; + find(element: any): IAugmentedJQuery; + find(obj: JQuery): IAugmentedJQuery; + controller(): any; + controller(name: string): any; + injector(): any; + scope(): IScope; + isolateScope(): IScope; + + inheritedData(key: string, value: any): JQuery; + inheritedData(obj: { [key: string]: any; }): JQuery; + inheritedData(key?: string): any; + } + + /////////////////////////////////////////////////////////////////////// + // AnimateService + // see http://docs.angularjs.org/api/ng.$animate + /////////////////////////////////////////////////////////////////////// + interface IAnimateService { + addClass(element: JQuery, className: string, done?: Function): IPromise; + enter(element: JQuery, parent: JQuery, after: JQuery, done?: Function): void; + leave(element: JQuery, done?: Function): void; + move(element: JQuery, parent: JQuery, after: JQuery, done?: Function): void; + removeClass(element: JQuery, className: string, done?: Function): void; + } + + /////////////////////////////////////////////////////////////////////////// + // AUTO module (angular.js) + /////////////////////////////////////////////////////////////////////////// + export module auto { + + /////////////////////////////////////////////////////////////////////// + // InjectorService + // see http://docs.angularjs.org/api/AUTO.$injector + /////////////////////////////////////////////////////////////////////// + interface IInjectorService { + annotate(fn: Function): string[]; + annotate(inlineAnnotatedFunction: any[]): string[]; + get(name: string): any; + has(name: string): boolean; + instantiate(typeConstructor: Function, locals?: any): any; + invoke(inlineAnnotatedFunction: any[]): any; + invoke(func: Function, context?: any, locals?: any): any; + } + + /////////////////////////////////////////////////////////////////////// + // ProvideService + // see http://docs.angularjs.org/api/AUTO.$provide + /////////////////////////////////////////////////////////////////////// + interface IProvideService { + // Documentation says it returns the registered instance, but actual + // implementation does not return anything. + // constant(name: string, value: any): any; + /** + * Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator. + * + * @param name The name of the constant. + * @param value The constant value. + */ + constant(name: string, value: any): void; + + /** + * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. + * + * @param name The name of the service to decorate. + * @param decorator This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: + * + * $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. + */ + decorator(name: string, decorator: Function): void; + /** + * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. + * + * @param name The name of the service to decorate. + * @param inlineAnnotatedFunction This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: + * + * $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. + */ + decorator(name: string, inlineAnnotatedFunction: any[]): void; + factory(name: string, serviceFactoryFunction: Function): IServiceProvider; + factory(name: string, inlineAnnotatedFunction: any[]): IServiceProvider; + provider(name: string, provider: IServiceProvider): IServiceProvider; + provider(name: string, serviceProviderConstructor: Function): IServiceProvider; + service(name: string, constructor: Function): IServiceProvider; + value(name: string, value: any): IServiceProvider; + } + + } +} diff --git a/angular1/e2e-tests/typings/jasmine/jasmine.d.ts b/angular1/e2e-tests/typings/jasmine/jasmine.d.ts new file mode 100644 index 0000000..1eb8d5e --- /dev/null +++ b/angular1/e2e-tests/typings/jasmine/jasmine.d.ts @@ -0,0 +1,478 @@ +// Type definitions for Jasmine 2.2 +// Project: http://jasmine.github.io/ +// Definitions by: Boris Yankov , Theodore Brown , David Pärsson +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +// For ddescribe / iit use : https://github.com/borisyankov/DefinitelyTyped/blob/master/karma-jasmine/karma-jasmine.d.ts + +declare function describe(description: string, specDefinitions: () => void): void; +declare function fdescribe(description: string, specDefinitions: () => void): void; +declare function xdescribe(description: string, specDefinitions: () => void): void; + +declare function it(expectation: string, assertion?: () => void, timeout?: number): void; +declare function it(expectation: string, assertion?: (done: () => void) => void, timeout?: number): void; +declare function fit(expectation: string, assertion?: () => void, timeout?: number): void; +declare function fit(expectation: string, assertion?: (done: () => void) => void, timeout?: number): void; +declare function xit(expectation: string, assertion?: () => void, timeout?: number): void; +declare function xit(expectation: string, assertion?: (done: () => void) => void, timeout?: number): void; + +/** If you call the function pending anywhere in the spec body, no matter the expectations, the spec will be marked pending. */ +declare function pending(reason?: string): void; + +declare function beforeEach(action: () => void, timeout?: number): void; +declare function beforeEach(action: (done: () => void) => void, timeout?: number): void; +declare function afterEach(action: () => void, timeout?: number): void; +declare function afterEach(action: (done: () => void) => void, timeout?: number): void; + +declare function beforeAll(action: () => void, timeout?: number): void; +declare function beforeAll(action: (done: () => void) => void, timeout?: number): void; +declare function afterAll(action: () => void, timeout?: number): void; +declare function afterAll(action: (done: () => void) => void, timeout?: number): void; + +declare function expect(spy: Function): jasmine.Matchers; +declare function expect(actual: any): jasmine.Matchers; + +declare function fail(e?: any): void; + +declare function spyOn(object: any, method: string): jasmine.Spy; + +declare function runs(asyncMethod: Function): void; +declare function waitsFor(latchMethod: () => boolean, failureMessage?: string, timeout?: number): void; +declare function waits(timeout?: number): void; + +declare module jasmine { + + var clock: () => Clock; + + function any(aclass: any): Any; + function anything(): Any; + function objectContaining(sample: any): ObjectContaining; + function createSpy(name: string, originalFn?: Function): Spy; + function createSpyObj(baseName: string, methodNames: any[]): any; + function createSpyObj(baseName: string, methodNames: any[]): T; + function pp(value: any): string; + function getEnv(): Env; + function addCustomEqualityTester(equalityTester: CustomEqualityTester): void; + function addMatchers(matchers: CustomMatcherFactories): void; + + interface Any { + + new (expectedClass: any): any; + + jasmineMatches(other: any): boolean; + jasmineToString(): string; + } + + // taken from TypeScript lib.core.es6.d.ts, applicable to CustomMatchers.contains() + interface ArrayLike { + length: number; + [n: number]: T; + } + + interface ObjectContaining { + new (sample: any): any; + + jasmineMatches(other: any, mismatchKeys: any[], mismatchValues: any[]): boolean; + jasmineToString(): string; + } + + interface Block { + + new (env: Env, func: SpecFunction, spec: Spec): any; + + execute(onComplete: () => void): void; + } + + interface WaitsBlock extends Block { + new (env: Env, timeout: number, spec: Spec): any; + } + + interface WaitsForBlock extends Block { + new (env: Env, timeout: number, latchFunction: SpecFunction, message: string, spec: Spec): any; + } + + interface Clock { + install(): void; + uninstall(): void; + /** Calls to any registered callback are triggered when the clock is ticked forward via the jasmine.clock().tick function, which takes a number of milliseconds. */ + tick(ms: number): void; + } + + interface CustomEqualityTester { + (first: any, second: any): boolean; + } + + interface CustomMatcher { + compare(actual: T, expected: T): CustomMatcherResult; + compare(actual: any, expected: any): CustomMatcherResult; + } + + interface CustomMatcherFactory { + (util: MatchersUtil, customEqualityTesters: Array): CustomMatcher; + } + + interface CustomMatcherFactories { + [index: string]: CustomMatcherFactory; + } + + interface CustomMatcherResult { + pass: boolean; + message: string; + } + + interface MatchersUtil { + equals(a: any, b: any, customTesters?: Array): boolean; + contains(haystack: ArrayLike | string, needle: any, customTesters?: Array): boolean; + buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: Array): string; + } + + interface Env { + setTimeout: any; + clearTimeout: void; + setInterval: any; + clearInterval: void; + updateInterval: number; + + currentSpec: Spec; + + matchersClass: Matchers; + + version(): any; + versionString(): string; + nextSpecId(): number; + addReporter(reporter: Reporter): void; + execute(): void; + describe(description: string, specDefinitions: () => void): Suite; + // ddescribe(description: string, specDefinitions: () => void): Suite; Not a part of jasmine. Angular team adds these + beforeEach(beforeEachFunction: () => void): void; + beforeAll(beforeAllFunction: () => void): void; + currentRunner(): Runner; + afterEach(afterEachFunction: () => void): void; + afterAll(afterAllFunction: () => void): void; + xdescribe(desc: string, specDefinitions: () => void): XSuite; + it(description: string, func: () => void): Spec; + // iit(description: string, func: () => void): Spec; Not a part of jasmine. Angular team adds these + xit(desc: string, func: () => void): XSpec; + compareRegExps_(a: RegExp, b: RegExp, mismatchKeys: string[], mismatchValues: string[]): boolean; + compareObjects_(a: any, b: any, mismatchKeys: string[], mismatchValues: string[]): boolean; + equals_(a: any, b: any, mismatchKeys: string[], mismatchValues: string[]): boolean; + contains_(haystack: any, needle: any): boolean; + addCustomEqualityTester(equalityTester: CustomEqualityTester): void; + addMatchers(matchers: CustomMatcherFactories): void; + specFilter(spec: Spec): boolean; + } + + interface FakeTimer { + + new (): any; + + reset(): void; + tick(millis: number): void; + runFunctionsWithinRange(oldMillis: number, nowMillis: number): void; + scheduleFunction(timeoutKey: any, funcToCall: () => void, millis: number, recurring: boolean): void; + } + + interface HtmlReporter { + new (): any; + } + + interface HtmlSpecFilter { + new (): any; + } + + interface Result { + type: string; + } + + interface NestedResults extends Result { + description: string; + + totalCount: number; + passedCount: number; + failedCount: number; + + skipped: boolean; + + rollupCounts(result: NestedResults): void; + log(values: any): void; + getItems(): Result[]; + addResult(result: Result): void; + passed(): boolean; + } + + interface MessageResult extends Result { + values: any; + trace: Trace; + } + + interface ExpectationResult extends Result { + matcherName: string; + passed(): boolean; + expected: any; + actual: any; + message: string; + trace: Trace; + } + + interface Trace { + name: string; + message: string; + stack: any; + } + + interface PrettyPrinter { + + new (): any; + + format(value: any): void; + iterateObject(obj: any, fn: (property: string, isGetter: boolean) => void): void; + emitScalar(value: any): void; + emitString(value: string): void; + emitArray(array: any[]): void; + emitObject(obj: any): void; + append(value: any): void; + } + + interface StringPrettyPrinter extends PrettyPrinter { + } + + interface Queue { + + new (env: any): any; + + env: Env; + ensured: boolean[]; + blocks: Block[]; + running: boolean; + index: number; + offset: number; + abort: boolean; + + addBefore(block: Block, ensure?: boolean): void; + add(block: any, ensure?: boolean): void; + insertNext(block: any, ensure?: boolean): void; + start(onComplete?: () => void): void; + isRunning(): boolean; + next_(): void; + results(): NestedResults; + } + + interface Matchers { + + new (env: Env, actual: any, spec: Env, isNot?: boolean): any; + + env: Env; + actual: any; + spec: Env; + isNot?: boolean; + message(): any; + + toBe(expected: any): boolean; + toEqual(expected: any): boolean; + toMatch(expected: any): boolean; + toBeDefined(): boolean; + toBeUndefined(): boolean; + toBeNull(): boolean; + toBeNaN(): boolean; + toBeTruthy(): boolean; + toBeFalsy(): boolean; + toHaveBeenCalled(): boolean; + toHaveBeenCalledWith(...params: any[]): boolean; + toContain(expected: any): boolean; + toBeLessThan(expected: any): boolean; + toBeGreaterThan(expected: any): boolean; + toBeCloseTo(expected: any, precision: any): boolean; + toContainHtml(expected: string): boolean; + toContainText(expected: string): boolean; + toThrow(expected?: any): boolean; + toThrowError(expected?: any): boolean; + not: Matchers; + + Any: Any; + } + + interface Reporter { + reportRunnerStarting(runner: Runner): void; + reportRunnerResults(runner: Runner): void; + reportSuiteResults(suite: Suite): void; + reportSpecStarting(spec: Spec): void; + reportSpecResults(spec: Spec): void; + log(str: string): void; + } + + interface MultiReporter extends Reporter { + addReporter(reporter: Reporter): void; + } + + interface Runner { + + new (env: Env): any; + + execute(): void; + beforeEach(beforeEachFunction: SpecFunction): void; + afterEach(afterEachFunction: SpecFunction): void; + beforeAll(beforeAllFunction: SpecFunction): void; + afterAll(afterAllFunction: SpecFunction): void; + finishCallback(): void; + addSuite(suite: Suite): void; + add(block: Block): void; + specs(): Spec[]; + suites(): Suite[]; + topLevelSuites(): Suite[]; + results(): NestedResults; + } + + interface SpecFunction { + (spec?: Spec): void; + } + + interface SuiteOrSpec { + id: number; + env: Env; + description: string; + queue: Queue; + } + + interface Spec extends SuiteOrSpec { + + new (env: Env, suite: Suite, description: string): any; + + suite: Suite; + + afterCallbacks: SpecFunction[]; + spies_: Spy[]; + + results_: NestedResults; + matchersClass: Matchers; + + getFullName(): string; + results(): NestedResults; + log(arguments: any): any; + runs(func: SpecFunction): Spec; + addToQueue(block: Block): void; + addMatcherResult(result: Result): void; + expect(actual: any): any; + waits(timeout: number): Spec; + waitsFor(latchFunction: SpecFunction, timeoutMessage?: string, timeout?: number): Spec; + fail(e?: any): void; + getMatchersClass_(): Matchers; + addMatchers(matchersPrototype: CustomMatcherFactories): void; + finishCallback(): void; + finish(onComplete?: () => void): void; + after(doAfter: SpecFunction): void; + execute(onComplete?: () => void): any; + addBeforesAndAftersToQueue(): void; + explodes(): void; + spyOn(obj: any, methodName: string, ignoreMethodDoesntExist: boolean): Spy; + removeAllSpies(): void; + } + + interface XSpec { + id: number; + runs(): void; + } + + interface Suite extends SuiteOrSpec { + + new (env: Env, description: string, specDefinitions: () => void, parentSuite: Suite): any; + + parentSuite: Suite; + + getFullName(): string; + finish(onComplete?: () => void): void; + beforeEach(beforeEachFunction: SpecFunction): void; + afterEach(afterEachFunction: SpecFunction): void; + beforeAll(beforeAllFunction: SpecFunction): void; + afterAll(afterAllFunction: SpecFunction): void; + results(): NestedResults; + add(suiteOrSpec: SuiteOrSpec): void; + specs(): Spec[]; + suites(): Suite[]; + children(): any[]; + execute(onComplete?: () => void): void; + } + + interface XSuite { + execute(): void; + } + + interface Spy { + (...params: any[]): any; + + identity: string; + and: SpyAnd; + calls: Calls; + mostRecentCall: { args: any[]; }; + argsForCall: any[]; + wasCalled: boolean; + } + + interface SpyAnd { + /** By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation. */ + callThrough(): Spy; + /** By chaining the spy with and.returnValue, all calls to the function will return a specific value. */ + returnValue(val: any): void; + /** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function. */ + callFake(fn: Function): Spy; + /** By chaining the spy with and.throwError, all calls to the spy will throw the specified value. */ + throwError(msg: string): void; + /** When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with and.stub. */ + stub(): Spy; + } + + interface Calls { + /** By chaining the spy with calls.any(), will return false if the spy has not been called at all, and then true once at least one call happens. **/ + any(): boolean; + /** By chaining the spy with calls.count(), will return the number of times the spy was called **/ + count(): number; + /** By chaining the spy with calls.argsFor(), will return the arguments passed to call number index **/ + argsFor(index: number): any[]; + /** By chaining the spy with calls.allArgs(), will return the arguments to all calls **/ + allArgs(): any[]; + /** By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls **/ + all(): any; + /** By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call **/ + mostRecent(): any; + /** By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call **/ + first(): any; + /** By chaining the spy with calls.reset(), will clears all tracking for a spy **/ + reset(): void; + } + + interface Util { + inherit(childClass: Function, parentClass: Function): any; + formatException(e: any): any; + htmlEscape(str: string): string; + argsToArray(args: any): any; + extend(destination: any, source: any): any; + } + + interface JsApiReporter extends Reporter { + + started: boolean; + finished: boolean; + result: any; + messages: any; + + new (): any; + + suites(): Suite[]; + summarize_(suiteOrSpec: SuiteOrSpec): any; + results(): any; + resultsForSpec(specId: any): any; + log(str: any): any; + resultsForSpecs(specIds: any): any; + summarizeResult_(result: any): any; + } + + interface Jasmine { + Spec: Spec; + clock: Clock; + util: Util; + } + + export var HtmlReporter: HtmlReporter; + export var HtmlSpecFilter: HtmlSpecFilter; + export var DEFAULT_TIMEOUT_INTERVAL: number; +} diff --git a/angular1/e2e-tests/typings/jquery/jquery.d.ts b/angular1/e2e-tests/typings/jquery/jquery.d.ts new file mode 100644 index 0000000..7eaf613 --- /dev/null +++ b/angular1/e2e-tests/typings/jquery/jquery.d.ts @@ -0,0 +1,3170 @@ +// Type definitions for jQuery 1.10.x / 2.0.x +// Project: http://jquery.com/ +// Definitions by: Boris Yankov , Christian Hoffmeister , Steve Fenton , Diullei Gomes , Tass Iliopoulos , Jason Swearingen , Sean Hill , Guus Goossens , Kelly Summerlin , Basarat Ali Syed , Nicholas Wolverson , Derek Cicerone , Andrew Gaspar , James Harrison Fisher , Seikichi Kondo , Benjamin Jackman , Poul Sorensen , Josh Strobl , John Reilly , Dick van den Brink +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + +/** + * Interface for the AJAX setting that will configure the AJAX request + */ +interface JQueryAjaxSettings { + /** + * The content type sent in the request header that tells the server what kind of response it will accept in return. If the accepts setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. + */ + accepts?: any; + /** + * By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success(). + */ + async?: boolean; + /** + * A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request. + */ + beforeSend? (jqXHR: JQueryXHR, settings: JQueryAjaxSettings): any; + /** + * If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET. + */ + cache?: boolean; + /** + * A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. + */ + complete? (jqXHR: JQueryXHR, textStatus: string): any; + /** + * An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type. (version added: 1.5) + */ + contents?: { [key: string]: any; }; + //According to jQuery.ajax source code, ajax's option actually allows contentType to set to "false" + // https://github.com/borisyankov/DefinitelyTyped/issues/742 + /** + * When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. + */ + contentType?: any; + /** + * This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). + */ + context?: any; + /** + * An object containing dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response. (version added: 1.5) + */ + converters?: { [key: string]: any; }; + /** + * If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain. (version added: 1.5) + */ + crossDomain?: boolean; + /** + * Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). + */ + data?: any; + /** + * A function to be used to handle the raw response data of XMLHttpRequest.This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter. + */ + dataFilter? (data: any, ty: any): any; + /** + * The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). + */ + dataType?: string; + /** + * A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event. + */ + error? (jqXHR: JQueryXHR, textStatus: string, errorThrown: string): any; + /** + * Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events. + */ + global?: boolean; + /** + * An object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport. The header X-Requested-With: XMLHttpRequest is always added, but its default XMLHttpRequest value can be changed here. Values in the headers setting can also be overwritten from within the beforeSend function. (version added: 1.5) + */ + headers?: { [key: string]: any; }; + /** + * Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data. + */ + ifModified?: boolean; + /** + * Allow the current environment to be recognized as "local," (e.g. the filesystem), even if jQuery does not recognize it as such by default. The following protocols are currently recognized as local: file, *-extension, and widget. If the isLocal setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. (version added: 1.5.1) + */ + isLocal?: boolean; + /** + * Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" } + */ + jsonp?: any; + /** + * Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function. + */ + jsonpCallback?: any; + /** + * A mime type to override the XHR mime type. (version added: 1.5.1) + */ + mimeType?: string; + /** + * A password to be used with XMLHttpRequest in response to an HTTP access authentication request. + */ + password?: string; + /** + * By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false. + */ + processData?: boolean; + /** + * Only applies when the "script" transport is used (e.g., cross-domain requests with "jsonp" or "script" dataType and "GET" type). Sets the charset attribute on the script tag used in the request. Used when the character set on the local page is not the same as the one on the remote script. + */ + scriptCharset?: string; + /** + * An object of numeric HTTP codes and functions to be called when the response has the corresponding code. f the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback. (version added: 1.5) + */ + statusCode?: { [key: string]: any; }; + /** + * A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. + */ + success? (data: any, textStatus: string, jqXHR: JQueryXHR): any; + /** + * Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period. + */ + timeout?: number; + /** + * Set this to true if you wish to use the traditional style of param serialization. + */ + traditional?: boolean; + /** + * The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers. + */ + type?: string; + /** + * A string containing the URL to which the request is sent. + */ + url?: string; + /** + * A username to be used with XMLHttpRequest in response to an HTTP access authentication request. + */ + username?: string; + /** + * Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory. + */ + xhr?: any; + /** + * An object of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed. In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it. (version added: 1.5.1) + */ + xhrFields?: { [key: string]: any; }; +} + +/** + * Interface for the jqXHR object + */ +interface JQueryXHR extends XMLHttpRequest, JQueryPromise { + /** + * The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header. As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). + */ + overrideMimeType(mimeType: string): any; + /** + * Cancel the request. + * + * @param statusText A string passed as the textStatus parameter for the done callback. Default value: "canceled" + */ + abort(statusText?: string): void; + /** + * Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details. + */ + then(doneCallback: (data: any, textStatus: string, jqXHR: JQueryXHR) => void, failCallback?: (jqXHR: JQueryXHR, textStatus: string, errorThrown: any) => void): JQueryPromise; + /** + * Property containing the parsed response if the response Content-Type is json + */ + responseJSON?: any; +} + +/** + * Interface for the JQuery callback + */ +interface JQueryCallback { + /** + * Add a callback or a collection of callbacks to a callback list. + * + * @param callbacks A function, or array of functions, that are to be added to the callback list. + */ + add(callbacks: Function): JQueryCallback; + /** + * Add a callback or a collection of callbacks to a callback list. + * + * @param callbacks A function, or array of functions, that are to be added to the callback list. + */ + add(callbacks: Function[]): JQueryCallback; + + /** + * Disable a callback list from doing anything more. + */ + disable(): JQueryCallback; + + /** + * Determine if the callbacks list has been disabled. + */ + disabled(): boolean; + + /** + * Remove all of the callbacks from a list. + */ + empty(): JQueryCallback; + + /** + * Call all of the callbacks with the given arguments + * + * @param arguments The argument or list of arguments to pass back to the callback list. + */ + fire(...arguments: any[]): JQueryCallback; + + /** + * Determine if the callbacks have already been called at least once. + */ + fired(): boolean; + + /** + * Call all callbacks in a list with the given context and arguments. + * + * @param context A reference to the context in which the callbacks in the list should be fired. + * @param arguments An argument, or array of arguments, to pass to the callbacks in the list. + */ + fireWith(context?: any, ...args: any[]): JQueryCallback; + + /** + * Determine whether a supplied callback is in a list + * + * @param callback The callback to search for. + */ + has(callback: Function): boolean; + + /** + * Lock a callback list in its current state. + */ + lock(): JQueryCallback; + + /** + * Determine if the callbacks list has been locked. + */ + locked(): boolean; + + /** + * Remove a callback or a collection of callbacks from a callback list. + * + * @param callbacks A function, or array of functions, that are to be removed from the callback list. + */ + remove(callbacks: Function): JQueryCallback; + /** + * Remove a callback or a collection of callbacks from a callback list. + * + * @param callbacks A function, or array of functions, that are to be removed from the callback list. + */ + remove(callbacks: Function[]): JQueryCallback; +} + +/** + * Allows jQuery Promises to interop with non-jQuery promises + */ +interface JQueryGenericPromise { + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + */ + then(doneFilter: (value?: T, ...values: any[]) => U|JQueryPromise, failFilter?: (...reasons: any[]) => any, progressFilter?: (...progression: any[]) => any): JQueryPromise; + + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + */ + then(doneFilter: (value?: T, ...values: any[]) => void, failFilter?: (...reasons: any[]) => any, progressFilter?: (...progression: any[]) => any): JQueryPromise; +} + +/** + * Interface for the JQuery promise/deferred callbacks + */ +interface JQueryPromiseCallback { + (value?: T, ...args: any[]): void; +} + +interface JQueryPromiseOperator { + (callback1: JQueryPromiseCallback|JQueryPromiseCallback[], ...callbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; +} + +/** + * Interface for the JQuery promise, part of callbacks + */ +interface JQueryPromise extends JQueryGenericPromise { + /** + * Determine the current state of a Deferred object. + */ + state(): string; + /** + * Add handlers to be called when the Deferred object is either resolved or rejected. + * + * @param alwaysCallbacks1 A function, or array of functions, that is called when the Deferred is resolved or rejected. + * @param alwaysCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. + */ + always(alwaysCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...alwaysCallbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; + /** + * Add handlers to be called when the Deferred object is resolved. + * + * @param doneCallbacks1 A function, or array of functions, that are called when the Deferred is resolved. + * @param doneCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. + */ + done(doneCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...doneCallbackN: Array|JQueryPromiseCallback[]>): JQueryPromise; + /** + * Add handlers to be called when the Deferred object is rejected. + * + * @param failCallbacks1 A function, or array of functions, that are called when the Deferred is rejected. + * @param failCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. + */ + fail(failCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...failCallbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; + /** + * Add handlers to be called when the Deferred object generates progress notifications. + * + * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications. + */ + progress(progressCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...progressCallbackN: Array|JQueryPromiseCallback[]>): JQueryPromise; + + // Deprecated - given no typings + pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; +} + +/** + * Interface for the JQuery deferred, part of callbacks + */ +interface JQueryDeferred extends JQueryGenericPromise { + /** + * Determine the current state of a Deferred object. + */ + state(): string; + /** + * Add handlers to be called when the Deferred object is either resolved or rejected. + * + * @param alwaysCallbacks1 A function, or array of functions, that is called when the Deferred is resolved or rejected. + * @param alwaysCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. + */ + always(alwaysCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...alwaysCallbacksN: Array|JQueryPromiseCallback[]>): JQueryDeferred; + /** + * Add handlers to be called when the Deferred object is resolved. + * + * @param doneCallbacks1 A function, or array of functions, that are called when the Deferred is resolved. + * @param doneCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. + */ + done(doneCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...doneCallbackN: Array|JQueryPromiseCallback[]>): JQueryDeferred; + /** + * Add handlers to be called when the Deferred object is rejected. + * + * @param failCallbacks1 A function, or array of functions, that are called when the Deferred is rejected. + * @param failCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. + */ + fail(failCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...failCallbacksN: Array|JQueryPromiseCallback[]>): JQueryDeferred; + /** + * Add handlers to be called when the Deferred object generates progress notifications. + * + * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications. + */ + progress(progressCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...progressCallbackN: Array|JQueryPromiseCallback[]>): JQueryDeferred; + + /** + * Call the progressCallbacks on a Deferred object with the given args. + * + * @param args Optional arguments that are passed to the progressCallbacks. + */ + notify(value?: any, ...args: any[]): JQueryDeferred; + + /** + * Call the progressCallbacks on a Deferred object with the given context and args. + * + * @param context Context passed to the progressCallbacks as the this object. + * @param args Optional arguments that are passed to the progressCallbacks. + */ + notifyWith(context: any, value?: any, ...args: any[]): JQueryDeferred; + + /** + * Reject a Deferred object and call any failCallbacks with the given args. + * + * @param args Optional arguments that are passed to the failCallbacks. + */ + reject(value?: any, ...args: any[]): JQueryDeferred; + /** + * Reject a Deferred object and call any failCallbacks with the given context and args. + * + * @param context Context passed to the failCallbacks as the this object. + * @param args An optional array of arguments that are passed to the failCallbacks. + */ + rejectWith(context: any, value?: any, ...args: any[]): JQueryDeferred; + + /** + * Resolve a Deferred object and call any doneCallbacks with the given args. + * + * @param value First argument passed to doneCallbacks. + * @param args Optional subsequent arguments that are passed to the doneCallbacks. + */ + resolve(value?: T, ...args: any[]): JQueryDeferred; + + /** + * Resolve a Deferred object and call any doneCallbacks with the given context and args. + * + * @param context Context passed to the doneCallbacks as the this object. + * @param args An optional array of arguments that are passed to the doneCallbacks. + */ + resolveWith(context: any, value?: T, ...args: any[]): JQueryDeferred; + + /** + * Return a Deferred's Promise object. + * + * @param target Object onto which the promise methods have to be attached + */ + promise(target?: any): JQueryPromise; + + // Deprecated - given no typings + pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; +} + +/** + * Interface of the JQuery extension of the W3C event object + */ +interface BaseJQueryEventObject extends Event { + data: any; + delegateTarget: Element; + isDefaultPrevented(): boolean; + isImmediatePropagationStopped(): boolean; + isPropagationStopped(): boolean; + namespace: string; + originalEvent: Event; + preventDefault(): any; + relatedTarget: Element; + result: any; + stopImmediatePropagation(): void; + stopPropagation(): void; + target: Element; + pageX: number; + pageY: number; + which: number; + metaKey: boolean; +} + +interface JQueryInputEventObject extends BaseJQueryEventObject { + altKey: boolean; + ctrlKey: boolean; + metaKey: boolean; + shiftKey: boolean; +} + +interface JQueryMouseEventObject extends JQueryInputEventObject { + button: number; + clientX: number; + clientY: number; + offsetX: number; + offsetY: number; + pageX: number; + pageY: number; + screenX: number; + screenY: number; +} + +interface JQueryKeyEventObject extends JQueryInputEventObject { + char: any; + charCode: number; + key: any; + keyCode: number; +} + +interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject{ +} + +/* + Collection of properties of the current browser +*/ + +interface JQuerySupport { + ajax?: boolean; + boxModel?: boolean; + changeBubbles?: boolean; + checkClone?: boolean; + checkOn?: boolean; + cors?: boolean; + cssFloat?: boolean; + hrefNormalized?: boolean; + htmlSerialize?: boolean; + leadingWhitespace?: boolean; + noCloneChecked?: boolean; + noCloneEvent?: boolean; + opacity?: boolean; + optDisabled?: boolean; + optSelected?: boolean; + scriptEval? (): boolean; + style?: boolean; + submitBubbles?: boolean; + tbody?: boolean; +} + +interface JQueryParam { + /** + * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. + * + * @param obj An array or object to serialize. + */ + (obj: any): string; + + /** + * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. + * + * @param obj An array or object to serialize. + * @param traditional A Boolean indicating whether to perform a traditional "shallow" serialization. + */ + (obj: any, traditional: boolean): string; +} + +/** + * The interface used to construct jQuery events (with $.Event). It is + * defined separately instead of inline in JQueryStatic to allow + * overriding the construction function with specific strings + * returning specific event objects. + */ +interface JQueryEventConstructor { + (name: string, eventProperties?: any): JQueryEventObject; + new (name: string, eventProperties?: any): JQueryEventObject; +} + +/** + * The interface used to specify coordinates. + */ +interface JQueryCoordinates { + left: number; + top: number; +} + +/** + * Elements in the array returned by serializeArray() + */ +interface JQuerySerializeArrayElement { + name: string; + value: string; +} + +interface JQueryAnimationOptions { + /** + * A string or number determining how long the animation will run. + */ + duration?: any; + /** + * A string indicating which easing function to use for the transition. + */ + easing?: string; + /** + * A function to call once the animation is complete. + */ + complete?: Function; + /** + * A function to be called for each animated property of each animated element. This function provides an opportunity to modify the Tween object to change the value of the property before it is set. + */ + step?: (now: number, tween: any) => any; + /** + * A function to be called after each step of the animation, only once per animated element regardless of the number of animated properties. (version added: 1.8) + */ + progress?: (animation: JQueryPromise, progress: number, remainingMs: number) => any; + /** + * A function to call when the animation begins. (version added: 1.8) + */ + start?: (animation: JQueryPromise) => any; + /** + * A function to be called when the animation completes (its Promise object is resolved). (version added: 1.8) + */ + done?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; + /** + * A function to be called when the animation fails to complete (its Promise object is rejected). (version added: 1.8) + */ + fail?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; + /** + * A function to be called when the animation completes or stops without completing (its Promise object is either resolved or rejected). (version added: 1.8) + */ + always?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; + /** + * A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case the animation is added to the queue represented by that string. When a custom queue name is used the animation does not automatically start; you must call .dequeue("queuename") to start it. + */ + queue?: any; + /** + * A map of one or more of the CSS properties defined by the properties argument and their corresponding easing functions. (version added: 1.4) + */ + specialEasing?: Object; +} + +/** + * Static members of jQuery (those on $ and jQuery themselves) + */ +interface JQueryStatic { + + /** + * Perform an asynchronous HTTP (Ajax) request. + * + * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). + */ + ajax(settings: JQueryAjaxSettings): JQueryXHR; + /** + * Perform an asynchronous HTTP (Ajax) request. + * + * @param url A string containing the URL to which the request is sent. + * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). + */ + ajax(url: string, settings?: JQueryAjaxSettings): JQueryXHR; + + /** + * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). + * + * @param dataTypes An optional string containing one or more space-separated dataTypes + * @param handler A handler to set default values for future Ajax requests. + */ + ajaxPrefilter(dataTypes: string, handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; + /** + * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). + * + * @param handler A handler to set default values for future Ajax requests. + */ + ajaxPrefilter(handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; + + ajaxSettings: JQueryAjaxSettings; + + /** + * Set default values for future Ajax requests. Its use is not recommended. + * + * @param options A set of key/value pairs that configure the default Ajax request. All options are optional. + */ + ajaxSetup(options: JQueryAjaxSettings): void; + + /** + * Load data from the server using a HTTP GET request. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). + */ + get(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + /** + * Load data from the server using a HTTP GET request. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). + */ + get(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + /** + * Load JSON-encoded data from the server using a GET HTTP request. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. + */ + getJSON(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; + /** + * Load JSON-encoded data from the server using a GET HTTP request. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. + */ + getJSON(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; + /** + * Load a JavaScript file from the server using a GET HTTP request, then execute it. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. + */ + getScript(url: string, success?: (script: string, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; + + /** + * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. + */ + param: JQueryParam; + + /** + * Load data from the server using a HTTP POST request. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). + */ + post(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + /** + * Load data from the server using a HTTP POST request. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). + */ + post(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + + /** + * A multi-purpose callbacks list object that provides a powerful way to manage callback lists. + * + * @param flags An optional list of space-separated flags that change how the callback list behaves. + */ + Callbacks(flags?: string): JQueryCallback; + + /** + * Holds or releases the execution of jQuery's ready event. + * + * @param hold Indicates whether the ready hold is being requested or released + */ + holdReady(hold: boolean): void; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param selector A string containing a selector expression + * @param context A DOM Element, Document, or jQuery to use as context + */ + (selector: string, context?: Element|JQuery): JQuery; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param element A DOM element to wrap in a jQuery object. + */ + (element: Element): JQuery; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param elementArray An array containing a set of DOM elements to wrap in a jQuery object. + */ + (elementArray: Element[]): JQuery; + + /** + * Binds a function to be executed when the DOM has finished loading. + * + * @param callback A function to execute after the DOM is ready. + */ + (callback: (jQueryAlias?: JQueryStatic) => any): JQuery; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param object A plain object to wrap in a jQuery object. + */ + (object: {}): JQuery; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param object An existing jQuery object to clone. + */ + (object: JQuery): JQuery; + + /** + * Specify a function to execute when the DOM is fully loaded. + */ + (): JQuery; + + /** + * Creates DOM elements on the fly from the provided string of raw HTML. + * + * @param html A string of HTML to create on the fly. Note that this parses HTML, not XML. + * @param ownerDocument A document in which the new elements will be created. + */ + (html: string, ownerDocument?: Document): JQuery; + + /** + * Creates DOM elements on the fly from the provided string of raw HTML. + * + * @param html A string defining a single, standalone, HTML element (e.g.
or
). + * @param attributes An object of attributes, events, and methods to call on the newly-created element. + */ + (html: string, attributes: Object): JQuery; + + /** + * Relinquish jQuery's control of the $ variable. + * + * @param removeAll A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself). + */ + noConflict(removeAll?: boolean): Object; + + /** + * Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. + * + * @param deferreds One or more Deferred objects, or plain JavaScript objects. + */ + when(...deferreds: Array/* as JQueryDeferred */>): JQueryPromise; + + /** + * Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize CSS property naming, or create custom properties. + */ + cssHooks: { [key: string]: any; }; + cssNumber: any; + + /** + * Store arbitrary data associated with the specified element. Returns the value that was set. + * + * @param element The DOM element to associate with the data. + * @param key A string naming the piece of data to set. + * @param value The new data value. + */ + data(element: Element, key: string, value: T): T; + /** + * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. + * + * @param element The DOM element to associate with the data. + * @param key A string naming the piece of data to set. + */ + data(element: Element, key: string): any; + /** + * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. + * + * @param element The DOM element to associate with the data. + */ + data(element: Element): any; + + /** + * Execute the next function on the queue for the matched element. + * + * @param element A DOM element from which to remove and execute a queued function. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + dequeue(element: Element, queueName?: string): void; + + /** + * Determine whether an element has any jQuery data associated with it. + * + * @param element A DOM element to be checked for data. + */ + hasData(element: Element): boolean; + + /** + * Show the queue of functions to be executed on the matched element. + * + * @param element A DOM element to inspect for an attached queue. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + queue(element: Element, queueName?: string): any[]; + /** + * Manipulate the queue of functions to be executed on the matched element. + * + * @param element A DOM element where the array of queued functions is attached. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param newQueue An array of functions to replace the current queue contents. + */ + queue(element: Element, queueName: string, newQueue: Function[]): JQuery; + /** + * Manipulate the queue of functions to be executed on the matched element. + * + * @param element A DOM element on which to add a queued function. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param callback The new function to add to the queue. + */ + queue(element: Element, queueName: string, callback: Function): JQuery; + + /** + * Remove a previously-stored piece of data. + * + * @param element A DOM element from which to remove data. + * @param name A string naming the piece of data to remove. + */ + removeData(element: Element, name?: string): JQuery; + + /** + * A constructor function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function. + * + * @param beforeStart A function that is called just before the constructor returns. + */ + Deferred(beforeStart?: (deferred: JQueryDeferred) => any): JQueryDeferred; + + /** + * Effects + */ + fx: { + tick: () => void; + /** + * The rate (in milliseconds) at which animations fire. + */ + interval: number; + stop: () => void; + speeds: { slow: number; fast: number; }; + /** + * Globally disable all animations. + */ + off: boolean; + step: any; + }; + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fnction The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @param additionalArguments Any number of arguments to be passed to the function referenced in the function argument. + */ + proxy(fnction: (...args: any[]) => any, context: Object, ...additionalArguments: any[]): any; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param context The object to which the context (this) of the function should be set. + * @param name The name of the function whose context will be changed (should be a property of the context object). + * @param additionalArguments Any number of arguments to be passed to the function named in the name argument. + */ + proxy(context: Object, name: string, ...additionalArguments: any[]): any; + + Event: JQueryEventConstructor; + + /** + * Takes a string and throws an exception containing it. + * + * @param message The message to send out. + */ + error(message: any): JQuery; + + expr: any; + fn: any; //TODO: Decide how we want to type this + + isReady: boolean; + + // Properties + support: JQuerySupport; + + /** + * Check to see if a DOM element is a descendant of another DOM element. + * + * @param container The DOM element that may contain the other element. + * @param contained The DOM element that may be contained by (a descendant of) the other element. + */ + contains(container: Element, contained: Element): boolean; + + /** + * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. + * + * @param collection The object or array to iterate over. + * @param callback The function that will be executed on every object. + */ + each( + collection: T[], + callback: (indexInArray: number, valueOfElement: T) => any + ): any; + + /** + * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. + * + * @param collection The object or array to iterate over. + * @param callback The function that will be executed on every object. + */ + each( + collection: any, + callback: (indexInArray: any, valueOfElement: any) => any + ): any; + + /** + * Merge the contents of two or more objects together into the first object. + * + * @param target An object that will receive the new properties if additional objects are passed in or that will extend the jQuery namespace if it is the sole argument. + * @param object1 An object containing additional properties to merge in. + * @param objectN Additional objects containing properties to merge in. + */ + extend(target: any, object1?: any, ...objectN: any[]): any; + /** + * Merge the contents of two or more objects together into the first object. + * + * @param deep If true, the merge becomes recursive (aka. deep copy). + * @param target The object to extend. It will receive the new properties. + * @param object1 An object containing additional properties to merge in. + * @param objectN Additional objects containing properties to merge in. + */ + extend(deep: boolean, target: any, object1?: any, ...objectN: any[]): any; + + /** + * Execute some JavaScript code globally. + * + * @param code The JavaScript code to execute. + */ + globalEval(code: string): any; + + /** + * Finds the elements of an array which satisfy a filter function. The original array is not affected. + * + * @param array The array to search through. + * @param func The function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value. this will be the global window object. + * @param invert If "invert" is false, or not provided, then the function returns an array consisting of all elements for which "callback" returns true. If "invert" is true, then the function returns an array consisting of all elements for which "callback" returns false. + */ + grep(array: T[], func: (elementOfArray: T, indexInArray: number) => boolean, invert?: boolean): T[]; + + /** + * Search for a specified value within an array and return its index (or -1 if not found). + * + * @param value The value to search for. + * @param array An array through which to search. + * @param fromIndex he index of the array at which to begin the search. The default is 0, which will search the whole array. + */ + inArray(value: T, array: T[], fromIndex?: number): number; + + /** + * Determine whether the argument is an array. + * + * @param obj Object to test whether or not it is an array. + */ + isArray(obj: any): boolean; + /** + * Check to see if an object is empty (contains no enumerable properties). + * + * @param obj The object that will be checked to see if it's empty. + */ + isEmptyObject(obj: any): boolean; + /** + * Determine if the argument passed is a Javascript function object. + * + * @param obj Object to test whether or not it is a function. + */ + isFunction(obj: any): boolean; + /** + * Determines whether its argument is a number. + * + * @param obj The value to be tested. + */ + isNumeric(value: any): boolean; + /** + * Check to see if an object is a plain object (created using "{}" or "new Object"). + * + * @param obj The object that will be checked to see if it's a plain object. + */ + isPlainObject(obj: any): boolean; + /** + * Determine whether the argument is a window. + * + * @param obj Object to test whether or not it is a window. + */ + isWindow(obj: any): boolean; + /** + * Check to see if a DOM node is within an XML document (or is an XML document). + * + * @param node he DOM node that will be checked to see if it's in an XML document. + */ + isXMLDoc(node: Node): boolean; + + /** + * Convert an array-like object into a true JavaScript array. + * + * @param obj Any object to turn into a native Array. + */ + makeArray(obj: any): any[]; + + /** + * Translate all items in an array or object to new array of items. + * + * @param array The Array to translate. + * @param callback The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. Within the function, this refers to the global (window) object. + */ + map(array: T[], callback: (elementOfArray: T, indexInArray: number) => U): U[]; + /** + * Translate all items in an array or object to new array of items. + * + * @param arrayOrObject The Array or Object to translate. + * @param callback The function to process each item against. The first argument to the function is the value; the second argument is the index or key of the array or object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object. + */ + map(arrayOrObject: any, callback: (value: any, indexOrKey: any) => any): any; + + /** + * Merge the contents of two arrays together into the first array. + * + * @param first The first array to merge, the elements of second added. + * @param second The second array to merge into the first, unaltered. + */ + merge(first: T[], second: T[]): T[]; + + /** + * An empty function. + */ + noop(): any; + + /** + * Return a number representing the current time. + */ + now(): number; + + /** + * Takes a well-formed JSON string and returns the resulting JavaScript object. + * + * @param json The JSON string to parse. + */ + parseJSON(json: string): any; + + /** + * Parses a string into an XML document. + * + * @param data a well-formed XML string to be parsed + */ + parseXML(data: string): XMLDocument; + + /** + * Remove the whitespace from the beginning and end of a string. + * + * @param str Remove the whitespace from the beginning and end of a string. + */ + trim(str: string): string; + + /** + * Determine the internal JavaScript [[Class]] of an object. + * + * @param obj Object to get the internal JavaScript [[Class]] of. + */ + type(obj: any): string; + + /** + * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers. + * + * @param array The Array of DOM elements. + */ + unique(array: Element[]): Element[]; + + /** + * Parses a string into an array of DOM nodes. + * + * @param data HTML string to be parsed + * @param context DOM element to serve as the context in which the HTML fragment will be created + * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string + */ + parseHTML(data: string, context?: HTMLElement, keepScripts?: boolean): any[]; + + /** + * Parses a string into an array of DOM nodes. + * + * @param data HTML string to be parsed + * @param context DOM element to serve as the context in which the HTML fragment will be created + * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string + */ + parseHTML(data: string, context?: Document, keepScripts?: boolean): any[]; +} + +/** + * The jQuery instance members + */ +interface JQuery { + /** + * Register a handler to be called when Ajax requests complete. This is an AjaxEvent. + * + * @param handler The function to be invoked. + */ + ajaxComplete(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: any) => any): JQuery; + /** + * Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxError(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxSettings: JQueryAjaxSettings, thrownError: any) => any): JQuery; + /** + * Attach a function to be executed before an Ajax request is sent. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxSend(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxOptions: JQueryAjaxSettings) => any): JQuery; + /** + * Register a handler to be called when the first Ajax request begins. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxStart(handler: () => any): JQuery; + /** + * Register a handler to be called when all Ajax requests have completed. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxStop(handler: () => any): JQuery; + /** + * Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxSuccess(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: JQueryAjaxSettings) => any): JQuery; + + /** + * Load data from the server and place the returned HTML into the matched element. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param complete A callback function that is executed when the request completes. + */ + load(url: string, data?: string|Object, complete?: (responseText: string, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any): JQuery; + + /** + * Encode a set of form elements as a string for submission. + */ + serialize(): string; + /** + * Encode a set of form elements as an array of names and values. + */ + serializeArray(): JQuerySerializeArrayElement[]; + + /** + * Adds the specified class(es) to each of the set of matched elements. + * + * @param className One or more space-separated classes to be added to the class attribute of each matched element. + */ + addClass(className: string): JQuery; + /** + * Adds the specified class(es) to each of the set of matched elements. + * + * @param function A function returning one or more space-separated class names to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function, this refers to the current element in the set. + */ + addClass(func: (index: number, className: string) => string): JQuery; + + /** + * Add the previous set of elements on the stack to the current set, optionally filtered by a selector. + */ + addBack(selector?: string): JQuery; + + /** + * Get the value of an attribute for the first element in the set of matched elements. + * + * @param attributeName The name of the attribute to get. + */ + attr(attributeName: string): string; + /** + * Set one or more attributes for the set of matched elements. + * + * @param attributeName The name of the attribute to set. + * @param value A value to set for the attribute. + */ + attr(attributeName: string, value: string|number): JQuery; + /** + * Set one or more attributes for the set of matched elements. + * + * @param attributeName The name of the attribute to set. + * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments. + */ + attr(attributeName: string, func: (index: number, attr: string) => string|number): JQuery; + /** + * Set one or more attributes for the set of matched elements. + * + * @param attributes An object of attribute-value pairs to set. + */ + attr(attributes: Object): JQuery; + + /** + * Determine whether any of the matched elements are assigned the given class. + * + * @param className The class name to search for. + */ + hasClass(className: string): boolean; + + /** + * Get the HTML contents of the first element in the set of matched elements. + */ + html(): string; + /** + * Set the HTML contents of each element in the set of matched elements. + * + * @param htmlString A string of HTML to set as the content of each matched element. + */ + html(htmlString: string): JQuery; + /** + * Set the HTML contents of each element in the set of matched elements. + * + * @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. + */ + html(func: (index: number, oldhtml: string) => string): JQuery; + /** + * Set the HTML contents of each element in the set of matched elements. + * + * @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. + */ + + /** + * Get the value of a property for the first element in the set of matched elements. + * + * @param propertyName The name of the property to get. + */ + prop(propertyName: string): any; + /** + * Set one or more properties for the set of matched elements. + * + * @param propertyName The name of the property to set. + * @param value A value to set for the property. + */ + prop(propertyName: string, value: string|number|boolean): JQuery; + /** + * Set one or more properties for the set of matched elements. + * + * @param properties An object of property-value pairs to set. + */ + prop(properties: Object): JQuery; + /** + * Set one or more properties for the set of matched elements. + * + * @param propertyName The name of the property to set. + * @param func A function returning the value to set. Receives the index position of the element in the set and the old property value as arguments. Within the function, the keyword this refers to the current element. + */ + prop(propertyName: string, func: (index: number, oldPropertyValue: any) => any): JQuery; + + /** + * Remove an attribute from each element in the set of matched elements. + * + * @param attributeName An attribute to remove; as of version 1.7, it can be a space-separated list of attributes. + */ + removeAttr(attributeName: string): JQuery; + + /** + * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. + * + * @param className One or more space-separated classes to be removed from the class attribute of each matched element. + */ + removeClass(className?: string): JQuery; + /** + * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. + * + * @param function A function returning one or more space-separated class names to be removed. Receives the index position of the element in the set and the old class value as arguments. + */ + removeClass(func: (index: number, className: string) => string): JQuery; + + /** + * Remove a property for the set of matched elements. + * + * @param propertyName The name of the property to remove. + */ + removeProp(propertyName: string): JQuery; + + /** + * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. + * + * @param className One or more class names (separated by spaces) to be toggled for each element in the matched set. + * @param swtch A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed. + */ + toggleClass(className: string, swtch?: boolean): JQuery; + /** + * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. + * + * @param swtch A boolean value to determine whether the class should be added or removed. + */ + toggleClass(swtch?: boolean): JQuery; + /** + * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. + * + * @param func A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments. + * @param swtch A boolean value to determine whether the class should be added or removed. + */ + toggleClass(func: (index: number, className: string, swtch: boolean) => string, swtch?: boolean): JQuery; + + /** + * Get the current value of the first element in the set of matched elements. + */ + val(): any; + /** + * Set the value of each element in the set of matched elements. + * + * @param value A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked. + */ + val(value: string|string[]): JQuery; + /** + * Set the value of each element in the set of matched elements. + * + * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. + */ + val(func: (index: number, value: string) => string): JQuery; + + + /** + * Get the value of style properties for the first element in the set of matched elements. + * + * @param propertyName A CSS property. + */ + css(propertyName: string): string; + /** + * Set one or more CSS properties for the set of matched elements. + * + * @param propertyName A CSS property name. + * @param value A value to set for the property. + */ + css(propertyName: string, value: string|number): JQuery; + /** + * Set one or more CSS properties for the set of matched elements. + * + * @param propertyName A CSS property name. + * @param value A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. + */ + css(propertyName: string, value: (index: number, value: string) => string|number): JQuery; + /** + * Set one or more CSS properties for the set of matched elements. + * + * @param properties An object of property-value pairs to set. + */ + css(properties: Object): JQuery; + + /** + * Get the current computed height for the first element in the set of matched elements. + */ + height(): number; + /** + * Set the CSS height of every matched element. + * + * @param value An integer representing the number of pixels, or an integer with an optional unit of measure appended (as a string). + */ + height(value: number|string): JQuery; + /** + * Set the CSS height of every matched element. + * + * @param func A function returning the height to set. Receives the index position of the element in the set and the old height as arguments. Within the function, this refers to the current element in the set. + */ + height(func: (index: number, height: number) => number|string): JQuery; + + /** + * Get the current computed height for the first element in the set of matched elements, including padding but not border. + */ + innerHeight(): number; + + /** + * Sets the inner height on elements in the set of matched elements, including padding but not border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + innerHeight(height: number|string): JQuery; + + /** + * Get the current computed width for the first element in the set of matched elements, including padding but not border. + */ + innerWidth(): number; + + /** + * Sets the inner width on elements in the set of matched elements, including padding but not border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + innerWidth(width: number|string): JQuery; + + /** + * Get the current coordinates of the first element in the set of matched elements, relative to the document. + */ + offset(): JQueryCoordinates; + /** + * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. + * + * @param coordinates An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. + */ + offset(coordinates: JQueryCoordinates): JQuery; + /** + * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. + * + * @param func A function to return the coordinates to set. Receives the index of the element in the collection as the first argument and the current coordinates as the second argument. The function should return an object with the new top and left properties. + */ + offset(func: (index: number, coords: JQueryCoordinates) => JQueryCoordinates): JQuery; + + /** + * Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin. Returns an integer (without "px") representation of the value or null if called on an empty set of elements. + * + * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. + */ + outerHeight(includeMargin?: boolean): number; + + /** + * Sets the outer height on elements in the set of matched elements, including padding and border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + outerHeight(height: number|string): JQuery; + + /** + * Get the current computed width for the first element in the set of matched elements, including padding and border. + * + * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. + */ + outerWidth(includeMargin?: boolean): number; + + /** + * Sets the outer width on elements in the set of matched elements, including padding and border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + outerWidth(width: number|string): JQuery; + + /** + * Get the current coordinates of the first element in the set of matched elements, relative to the offset parent. + */ + position(): JQueryCoordinates; + + /** + * Get the current horizontal position of the scroll bar for the first element in the set of matched elements or set the horizontal position of the scroll bar for every matched element. + */ + scrollLeft(): number; + /** + * Set the current horizontal position of the scroll bar for each of the set of matched elements. + * + * @param value An integer indicating the new position to set the scroll bar to. + */ + scrollLeft(value: number): JQuery; + + /** + * Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element. + */ + scrollTop(): number; + /** + * Set the current vertical position of the scroll bar for each of the set of matched elements. + * + * @param value An integer indicating the new position to set the scroll bar to. + */ + scrollTop(value: number): JQuery; + + /** + * Get the current computed width for the first element in the set of matched elements. + */ + width(): number; + /** + * Set the CSS width of each element in the set of matched elements. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + width(value: number|string): JQuery; + /** + * Set the CSS width of each element in the set of matched elements. + * + * @param func A function returning the width to set. Receives the index position of the element in the set and the old width as arguments. Within the function, this refers to the current element in the set. + */ + width(func: (index: number, width: number) => number|string): JQuery; + + /** + * Remove from the queue all items that have not yet been run. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + clearQueue(queueName?: string): JQuery; + + /** + * Store arbitrary data associated with the matched elements. + * + * @param key A string naming the piece of data to set. + * @param value The new data value; it can be any Javascript type including Array or Object. + */ + data(key: string, value: any): JQuery; + /** + * Store arbitrary data associated with the matched elements. + * + * @param obj An object of key-value pairs of data to update. + */ + data(obj: { [key: string]: any; }): JQuery; + /** + * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. + * + * @param key Name of the data stored. + */ + data(key: string): any; + /** + * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. + */ + data(): any; + + /** + * Execute the next function on the queue for the matched elements. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + dequeue(queueName?: string): JQuery; + + /** + * Remove a previously-stored piece of data. + * + * @param name A string naming the piece of data to delete or space-separated string naming the pieces of data to delete. + */ + removeData(name: string): JQuery; + /** + * Remove a previously-stored piece of data. + * + * @param list An array of strings naming the pieces of data to delete. + */ + removeData(list: string[]): JQuery; + + /** + * Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished. + * + * @param type The type of queue that needs to be observed. (default: fx) + * @param target Object onto which the promise methods have to be attached + */ + promise(type?: string, target?: Object): JQueryPromise; + + /** + * Perform a custom animation of a set of CSS properties. + * + * @param properties An object of CSS properties and values that the animation will move toward. + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + animate(properties: Object, duration?: string|number, complete?: Function): JQuery; + /** + * Perform a custom animation of a set of CSS properties. + * + * @param properties An object of CSS properties and values that the animation will move toward. + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. (default: swing) + * @param complete A function to call once the animation is complete. + */ + animate(properties: Object, duration?: string|number, easing?: string, complete?: Function): JQuery; + /** + * Perform a custom animation of a set of CSS properties. + * + * @param properties An object of CSS properties and values that the animation will move toward. + * @param options A map of additional options to pass to the method. + */ + animate(properties: Object, options: JQueryAnimationOptions): JQuery; + + /** + * Set a timer to delay execution of subsequent items in the queue. + * + * @param duration An integer indicating the number of milliseconds to delay execution of the next item in the queue. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + delay(duration: number, queueName?: string): JQuery; + + /** + * Display the matched elements by fading them to opaque. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + fadeIn(duration?: number|string, complete?: Function): JQuery; + /** + * Display the matched elements by fading them to opaque. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeIn(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display the matched elements by fading them to opaque. + * + * @param options A map of additional options to pass to the method. + */ + fadeIn(options: JQueryAnimationOptions): JQuery; + + /** + * Hide the matched elements by fading them to transparent. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + fadeOut(duration?: number|string, complete?: Function): JQuery; + /** + * Hide the matched elements by fading them to transparent. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeOut(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Hide the matched elements by fading them to transparent. + * + * @param options A map of additional options to pass to the method. + */ + fadeOut(options: JQueryAnimationOptions): JQuery; + + /** + * Adjust the opacity of the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param opacity A number between 0 and 1 denoting the target opacity. + * @param complete A function to call once the animation is complete. + */ + fadeTo(duration: string|number, opacity: number, complete?: Function): JQuery; + /** + * Adjust the opacity of the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param opacity A number between 0 and 1 denoting the target opacity. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeTo(duration: string|number, opacity: number, easing?: string, complete?: Function): JQuery; + + /** + * Display or hide the matched elements by animating their opacity. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + fadeToggle(duration?: number|string, complete?: Function): JQuery; + /** + * Display or hide the matched elements by animating their opacity. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeToggle(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display or hide the matched elements by animating their opacity. + * + * @param options A map of additional options to pass to the method. + */ + fadeToggle(options: JQueryAnimationOptions): JQuery; + + /** + * Stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements. + * + * @param queue The name of the queue in which to stop animations. + */ + finish(queue?: string): JQuery; + + /** + * Hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + hide(duration?: number|string, complete?: Function): JQuery; + /** + * Hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + hide(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Hide the matched elements. + * + * @param options A map of additional options to pass to the method. + */ + hide(options: JQueryAnimationOptions): JQuery; + + /** + * Display the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + show(duration?: number|string, complete?: Function): JQuery; + /** + * Display the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + show(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display the matched elements. + * + * @param options A map of additional options to pass to the method. + */ + show(options: JQueryAnimationOptions): JQuery; + + /** + * Display the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + slideDown(duration?: number|string, complete?: Function): JQuery; + /** + * Display the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + slideDown(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display the matched elements with a sliding motion. + * + * @param options A map of additional options to pass to the method. + */ + slideDown(options: JQueryAnimationOptions): JQuery; + + /** + * Display or hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + slideToggle(duration?: number|string, complete?: Function): JQuery; + /** + * Display or hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + slideToggle(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display or hide the matched elements with a sliding motion. + * + * @param options A map of additional options to pass to the method. + */ + slideToggle(options: JQueryAnimationOptions): JQuery; + + /** + * Hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + slideUp(duration?: number|string, complete?: Function): JQuery; + /** + * Hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + slideUp(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Hide the matched elements with a sliding motion. + * + * @param options A map of additional options to pass to the method. + */ + slideUp(options: JQueryAnimationOptions): JQuery; + + /** + * Stop the currently-running animation on the matched elements. + * + * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. + * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. + */ + stop(clearQueue?: boolean, jumpToEnd?: boolean): JQuery; + /** + * Stop the currently-running animation on the matched elements. + * + * @param queue The name of the queue in which to stop animations. + * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. + * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. + */ + stop(queue?: string, clearQueue?: boolean, jumpToEnd?: boolean): JQuery; + + /** + * Display or hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + toggle(duration?: number|string, complete?: Function): JQuery; + /** + * Display or hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + toggle(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display or hide the matched elements. + * + * @param options A map of additional options to pass to the method. + */ + toggle(options: JQueryAnimationOptions): JQuery; + /** + * Display or hide the matched elements. + * + * @param showOrHide A Boolean indicating whether to show or hide the elements. + */ + toggle(showOrHide: boolean): JQuery; + + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + bind(eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param handler A function to execute each time the event is triggered. + */ + bind(eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param eventData An object containing data that will be passed to the event handler. + * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. + */ + bind(eventType: string, eventData: any, preventBubble: boolean): JQuery; + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. + */ + bind(eventType: string, preventBubble: boolean): JQuery; + /** + * Attach a handler to an event for the elements. + * + * @param events An object containing one or more DOM event types and functions to execute for them. + */ + bind(events: any): JQuery; + + /** + * Trigger the "blur" event on an element + */ + blur(): JQuery; + /** + * Bind an event handler to the "blur" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + blur(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "blur" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + blur(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "change" event on an element. + */ + change(): JQuery; + /** + * Bind an event handler to the "change" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + change(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "change" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + change(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "click" event on an element. + */ + click(): JQuery; + /** + * Bind an event handler to the "click" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + */ + click(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "click" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + click(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "dblclick" event on an element. + */ + dblclick(): JQuery; + /** + * Bind an event handler to the "dblclick" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + dblclick(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "dblclick" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + dblclick(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + delegate(selector: any, eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + delegate(selector: any, eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "focus" event on an element. + */ + focus(): JQuery; + /** + * Bind an event handler to the "focus" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + focus(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "focus" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + focus(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Bind an event handler to the "focusin" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + focusin(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "focusin" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + focusin(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Bind an event handler to the "focusout" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + focusout(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "focusout" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + focusout(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. + * + * @param handlerIn A function to execute when the mouse pointer enters the element. + * @param handlerOut A function to execute when the mouse pointer leaves the element. + */ + hover(handlerIn: (eventObject: JQueryEventObject) => any, handlerOut: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. + * + * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element. + */ + hover(handlerInOut: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "keydown" event on an element. + */ + keydown(): JQuery; + /** + * Bind an event handler to the "keydown" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + keydown(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; + /** + * Bind an event handler to the "keydown" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + keydown(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; + + /** + * Trigger the "keypress" event on an element. + */ + keypress(): JQuery; + /** + * Bind an event handler to the "keypress" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + keypress(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; + /** + * Bind an event handler to the "keypress" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + keypress(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; + + /** + * Trigger the "keyup" event on an element. + */ + keyup(): JQuery; + /** + * Bind an event handler to the "keyup" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + keyup(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; + /** + * Bind an event handler to the "keyup" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + keyup(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; + + /** + * Bind an event handler to the "load" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + load(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "load" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + load(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "mousedown" event on an element. + */ + mousedown(): JQuery; + /** + * Bind an event handler to the "mousedown" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mousedown(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "mousedown" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mousedown(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mouseenter" event on an element. + */ + mouseenter(): JQuery; + /** + * Bind an event handler to be fired when the mouse enters an element. + * + * @param handler A function to execute when the event is triggered. + */ + mouseenter(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to be fired when the mouse enters an element. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseenter(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mouseleave" event on an element. + */ + mouseleave(): JQuery; + /** + * Bind an event handler to be fired when the mouse leaves an element. + * + * @param handler A function to execute when the event is triggered. + */ + mouseleave(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to be fired when the mouse leaves an element. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseleave(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mousemove" event on an element. + */ + mousemove(): JQuery; + /** + * Bind an event handler to the "mousemove" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mousemove(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "mousemove" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mousemove(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mouseout" event on an element. + */ + mouseout(): JQuery; + /** + * Bind an event handler to the "mouseout" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mouseout(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "mouseout" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseout(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mouseover" event on an element. + */ + mouseover(): JQuery; + /** + * Bind an event handler to the "mouseover" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mouseover(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "mouseover" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseover(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mouseup" event on an element. + */ + mouseup(): JQuery; + /** + * Bind an event handler to the "mouseup" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mouseup(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "mouseup" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseup(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Remove an event handler. + */ + off(): JQuery; + /** + * Remove an event handler. + * + * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". + * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: string, selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Remove an event handler. + * + * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Remove an event handler. + * + * @param events An object where the string keys represent one or more space-separated event types and optional namespaces, and the values represent handler functions previously attached for the event(s). + * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. + */ + off(events: { [key: string]: any; }, selector?: string): JQuery; + + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: string, data : any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: string, selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + on(events: { [key: string]: any; }, selector?: string, data?: any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + on(events: { [key: string]: any; }, data?: any): JQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. + * @param handler A function to execute at the time the event is triggered. + */ + one(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. + * @param data An object containing data that will be passed to the event handler. + * @param handler A function to execute at the time the event is triggered. + */ + one(events: string, data: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + one(events: string, selector: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + one(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + one(events: { [key: string]: any; }, selector?: string, data?: any): JQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + one(events: { [key: string]: any; }, data?: any): JQuery; + + + /** + * Specify a function to execute when the DOM is fully loaded. + * + * @param handler A function to execute after the DOM is ready. + */ + ready(handler: (jQueryAlias?: JQueryStatic) => any): JQuery; + + /** + * Trigger the "resize" event on an element. + */ + resize(): JQuery; + /** + * Bind an event handler to the "resize" JavaScript event. + * + * @param handler A function to execute each time the event is triggered. + */ + resize(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "resize" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + resize(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "scroll" event on an element. + */ + scroll(): JQuery; + /** + * Bind an event handler to the "scroll" JavaScript event. + * + * @param handler A function to execute each time the event is triggered. + */ + scroll(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "scroll" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + scroll(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "select" event on an element. + */ + select(): JQuery; + /** + * Bind an event handler to the "select" JavaScript event. + * + * @param handler A function to execute each time the event is triggered. + */ + select(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "select" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + select(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "submit" event on an element. + */ + submit(): JQuery; + /** + * Bind an event handler to the "submit" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + submit(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "submit" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + submit(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Execute all handlers and behaviors attached to the matched elements for the given event type. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param extraParameters Additional parameters to pass along to the event handler. + */ + trigger(eventType: string, extraParameters?: any[]|Object): JQuery; + /** + * Execute all handlers and behaviors attached to the matched elements for the given event type. + * + * @param event A jQuery.Event object. + * @param extraParameters Additional parameters to pass along to the event handler. + */ + trigger(event: JQueryEventObject, extraParameters?: any[]|Object): JQuery; + + /** + * Execute all handlers attached to an element for an event. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param extraParameters An array of additional parameters to pass along to the event handler. + */ + triggerHandler(eventType: string, ...extraParameters: any[]): Object; + + /** + * Execute all handlers attached to an element for an event. + * + * @param event A jQuery.Event object. + * @param extraParameters An array of additional parameters to pass along to the event handler. + */ + triggerHandler(event: JQueryEventObject, ...extraParameters: any[]): Object; + + /** + * Remove a previously-attached event handler from the elements. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param handler The function that is to be no longer executed. + */ + unbind(eventType?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Remove a previously-attached event handler from the elements. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param fls Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ). + */ + unbind(eventType: string, fls: boolean): JQuery; + /** + * Remove a previously-attached event handler from the elements. + * + * @param evt A JavaScript event object as passed to an event handler. + */ + unbind(evt: any): JQuery; + + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + */ + undelegate(): JQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param selector A selector which will be used to filter the event results. + * @param eventType A string containing a JavaScript event type, such as "click" or "keydown" + * @param handler A function to execute at the time the event is triggered. + */ + undelegate(selector: string, eventType: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param selector A selector which will be used to filter the event results. + * @param events An object of one or more event types and previously bound functions to unbind from them. + */ + undelegate(selector: string, events: Object): JQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param namespace A string containing a namespace to unbind all events from. + */ + undelegate(namespace: string): JQuery; + + /** + * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) + * + * @param handler A function to execute when the event is triggered. + */ + unload(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) + * + * @param eventData A plain object of data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + unload(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document. (DEPRECATED from v1.10) + */ + context: Element; + + jquery: string; + + /** + * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) + * + * @param handler A function to execute when the event is triggered. + */ + error(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) + * + * @param eventData A plain object of data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + error(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Add a collection of DOM elements onto the jQuery stack. + * + * @param elements An array of elements to push onto the stack and make into a new jQuery object. + */ + pushStack(elements: any[]): JQuery; + /** + * Add a collection of DOM elements onto the jQuery stack. + * + * @param elements An array of elements to push onto the stack and make into a new jQuery object. + * @param name The name of a jQuery method that generated the array of elements. + * @param arguments The arguments that were passed in to the jQuery method (for serialization). + */ + pushStack(elements: any[], name: string, arguments: any[]): JQuery; + + /** + * Insert content, specified by the parameter, after each element in the set of matched elements. + * + * param content1 HTML string, DOM element, array of elements, or jQuery object to insert after each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements. + */ + after(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, after each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert after each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + after(func: (index: number, html: string) => string|Element|JQuery): JQuery; + + /** + * Insert content, specified by the parameter, to the end of each element in the set of matched elements. + * + * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements. + */ + append(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, to the end of each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. + */ + append(func: (index: number, html: string) => string|Element|JQuery): JQuery; + + /** + * Insert every element in the set of matched elements to the end of the target. + * + * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter. + */ + appendTo(target: JQuery|any[]|Element|string): JQuery; + + /** + * Insert content, specified by the parameter, before each element in the set of matched elements. + * + * param content1 HTML string, DOM element, array of elements, or jQuery object to insert before each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements. + */ + before(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, before each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert before each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + before(func: (index: number, html: string) => string|Element|JQuery): JQuery; + + /** + * Create a deep copy of the set of matched elements. + * + * param withDataAndEvents A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false. + * param deepWithDataAndEvents A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false). + */ + clone(withDataAndEvents?: boolean, deepWithDataAndEvents?: boolean): JQuery; + + /** + * Remove the set of matched elements from the DOM. + * + * param selector A selector expression that filters the set of matched elements to be removed. + */ + detach(selector?: string): JQuery; + + /** + * Remove all child nodes of the set of matched elements from the DOM. + */ + empty(): JQuery; + + /** + * Insert every element in the set of matched elements after the target. + * + * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter. + */ + insertAfter(target: JQuery|any[]|Element|Text|string): JQuery; + + /** + * Insert every element in the set of matched elements before the target. + * + * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter. + */ + insertBefore(target: JQuery|any[]|Element|Text|string): JQuery; + + /** + * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. + * + * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements. + */ + prepend(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the beginning of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. + */ + prepend(func: (index: number, html: string) => string|Element|JQuery): JQuery; + + /** + * Insert every element in the set of matched elements to the beginning of the target. + * + * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter. + */ + prependTo(target: JQuery|any[]|Element|string): JQuery; + + /** + * Remove the set of matched elements from the DOM. + * + * @param selector A selector expression that filters the set of matched elements to be removed. + */ + remove(selector?: string): JQuery; + + /** + * Replace each target element with the set of matched elements. + * + * @param target A selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace. + */ + replaceAll(target: JQuery|any[]|Element|string): JQuery; + + /** + * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. + * + * param newContent The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object. + */ + replaceWith(newContent: JQuery|any[]|Element|Text|string): JQuery; + /** + * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. + * + * param func A function that returns content with which to replace the set of matched elements. + */ + replaceWith(func: () => Element|JQuery): JQuery; + + /** + * Get the combined text contents of each element in the set of matched elements, including their descendants. + */ + text(): string; + /** + * Set the content of each element in the set of matched elements to the specified text. + * + * @param text The text to set as the content of each matched element. When Number or Boolean is supplied, it will be converted to a String representation. + */ + text(text: string|number|boolean): JQuery; + /** + * Set the content of each element in the set of matched elements to the specified text. + * + * @param func A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments. + */ + text(func: (index: number, text: string) => string): JQuery; + + /** + * Retrieve all the elements contained in the jQuery set, as an array. + */ + toArray(): any[]; + + /** + * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. + */ + unwrap(): JQuery; + + /** + * Wrap an HTML structure around each element in the set of matched elements. + * + * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. + */ + wrap(wrappingElement: JQuery|Element|string): JQuery; + /** + * Wrap an HTML structure around each element in the set of matched elements. + * + * @param func A callback function returning the HTML content or jQuery object to wrap around the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + wrap(func: (index: number) => string|JQuery): JQuery; + + /** + * Wrap an HTML structure around all elements in the set of matched elements. + * + * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. + */ + wrapAll(wrappingElement: JQuery|Element|string): JQuery; + wrapAll(func: (index: number) => string): JQuery; + + /** + * Wrap an HTML structure around the content of each element in the set of matched elements. + * + * @param wrappingElement An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements. + */ + wrapInner(wrappingElement: JQuery|Element|string): JQuery; + /** + * Wrap an HTML structure around the content of each element in the set of matched elements. + * + * @param func A callback function which generates a structure to wrap around the content of the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + wrapInner(func: (index: number) => string): JQuery; + + /** + * Iterate over a jQuery object, executing a function for each matched element. + * + * @param func A function to execute for each matched element. + */ + each(func: (index: number, elem: Element) => any): JQuery; + + /** + * Retrieve one of the elements matched by the jQuery object. + * + * @param index A zero-based integer indicating which element to retrieve. + */ + get(index: number): HTMLElement; + /** + * Retrieve the elements matched by the jQuery object. + */ + get(): any[]; + + /** + * Search for a given element from among the matched elements. + */ + index(): number; + /** + * Search for a given element from among the matched elements. + * + * @param selector A selector representing a jQuery collection in which to look for an element. + */ + index(selector: string|JQuery|Element): number; + + /** + * The number of elements in the jQuery object. + */ + length: number; + /** + * A selector representing selector passed to jQuery(), if any, when creating the original set. + * version deprecated: 1.7, removed: 1.9 + */ + selector: string; + [index: string]: any; + [index: number]: HTMLElement; + + /** + * Add elements to the set of matched elements. + * + * @param selector A string representing a selector expression to find additional elements to add to the set of matched elements. + * @param context The point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method. + */ + add(selector: string, context?: Element): JQuery; + /** + * Add elements to the set of matched elements. + * + * @param elements One or more elements to add to the set of matched elements. + */ + add(...elements: Element[]): JQuery; + /** + * Add elements to the set of matched elements. + * + * @param html An HTML fragment to add to the set of matched elements. + */ + add(html: string): JQuery; + /** + * Add elements to the set of matched elements. + * + * @param obj An existing jQuery object to add to the set of matched elements. + */ + add(obj: JQuery): JQuery; + + /** + * Get the children of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + children(selector?: string): JQuery; + + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param selector A string containing a selector expression to match elements against. + */ + closest(selector: string): JQuery; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param selector A string containing a selector expression to match elements against. + * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. + */ + closest(selector: string, context?: Element): JQuery; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param obj A jQuery object to match elements against. + */ + closest(obj: JQuery): JQuery; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param element An element to match elements against. + */ + closest(element: Element): JQuery; + + /** + * Get an array of all the elements and selectors matched against the current element up through the DOM tree. + * + * @param selectors An array or string containing a selector expression to match elements against (can also be a jQuery object). + * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. + */ + closest(selectors: any, context?: Element): any[]; + + /** + * Get the children of each element in the set of matched elements, including text and comment nodes. + */ + contents(): JQuery; + + /** + * End the most recent filtering operation in the current chain and return the set of matched elements to its previous state. + */ + end(): JQuery; + + /** + * Reduce the set of matched elements to the one at the specified index. + * + * @param index An integer indicating the 0-based position of the element. OR An integer indicating the position of the element, counting backwards from the last element in the set. + * + */ + eq(index: number): JQuery; + + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param selector A string containing a selector expression to match the current set of elements against. + */ + filter(selector: string): JQuery; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param func A function used as a test for each element in the set. this is the current DOM element. + */ + filter(func: (index: number, element: Element) => any): JQuery; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param element An element to match the current set of elements against. + */ + filter(element: Element): JQuery; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param obj An existing jQuery object to match the current set of elements against. + */ + filter(obj: JQuery): JQuery; + + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. + * + * @param selector A string containing a selector expression to match elements against. + */ + find(selector: string): JQuery; + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. + * + * @param element An element to match elements against. + */ + find(element: Element): JQuery; + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. + * + * @param obj A jQuery object to match elements against. + */ + find(obj: JQuery): JQuery; + + /** + * Reduce the set of matched elements to the first in the set. + */ + first(): JQuery; + + /** + * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. + * + * @param selector A string containing a selector expression to match elements against. + */ + has(selector: string): JQuery; + /** + * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. + * + * @param contained A DOM element to match elements against. + */ + has(contained: Element): JQuery; + + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param selector A string containing a selector expression to match elements against. + */ + is(selector: string): boolean; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param func A function used as a test for the set of elements. It accepts one argument, index, which is the element's index in the jQuery collection.Within the function, this refers to the current DOM element. + */ + is(func: (index: number, element: Element) => boolean): boolean; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param obj An existing jQuery object to match the current set of elements against. + */ + is(obj: JQuery): boolean; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param elements One or more elements to match the current set of elements against. + */ + is(elements: any): boolean; + + /** + * Reduce the set of matched elements to the final one in the set. + */ + last(): JQuery; + + /** + * Pass each element in the current matched set through a function, producing a new jQuery object containing the return values. + * + * @param callback A function object that will be invoked for each element in the current set. + */ + map(callback: (index: number, domElement: Element) => any): JQuery; + + /** + * Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + next(selector?: string): JQuery; + + /** + * Get all following siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + nextAll(selector?: string): JQuery; + + /** + * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. + * + * @param selector A string containing a selector expression to indicate where to stop matching following sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + nextUntil(selector?: string, filter?: string): JQuery; + /** + * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. + * + * @param element A DOM node or jQuery object indicating where to stop matching following sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + nextUntil(element?: Element, filter?: string): JQuery; + /** + * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. + * + * @param obj A DOM node or jQuery object indicating where to stop matching following sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + nextUntil(obj?: JQuery, filter?: string): JQuery; + + /** + * Remove elements from the set of matched elements. + * + * @param selector A string containing a selector expression to match elements against. + */ + not(selector: string): JQuery; + /** + * Remove elements from the set of matched elements. + * + * @param func A function used as a test for each element in the set. this is the current DOM element. + */ + not(func: (index: number, element: Element) => boolean): JQuery; + /** + * Remove elements from the set of matched elements. + * + * @param elements One or more DOM elements to remove from the matched set. + */ + not(...elements: Element[]): JQuery; + /** + * Remove elements from the set of matched elements. + * + * @param obj An existing jQuery object to match the current set of elements against. + */ + not(obj: JQuery): JQuery; + + /** + * Get the closest ancestor element that is positioned. + */ + offsetParent(): JQuery; + + /** + * Get the parent of each element in the current set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + parent(selector?: string): JQuery; + + /** + * Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + parents(selector?: string): JQuery; + + /** + * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param selector A string containing a selector expression to indicate where to stop matching ancestor elements. + * @param filter A string containing a selector expression to match elements against. + */ + parentsUntil(selector?: string, filter?: string): JQuery; + /** + * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param element A DOM node or jQuery object indicating where to stop matching ancestor elements. + * @param filter A string containing a selector expression to match elements against. + */ + parentsUntil(element?: Element, filter?: string): JQuery; + /** + * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param obj A DOM node or jQuery object indicating where to stop matching ancestor elements. + * @param filter A string containing a selector expression to match elements against. + */ + parentsUntil(obj?: JQuery, filter?: string): JQuery; + + /** + * Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + prev(selector?: string): JQuery; + + /** + * Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + prevAll(selector?: string): JQuery; + + /** + * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param selector A string containing a selector expression to indicate where to stop matching preceding sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + prevUntil(selector?: string, filter?: string): JQuery; + /** + * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param element A DOM node or jQuery object indicating where to stop matching preceding sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + prevUntil(element?: Element, filter?: string): JQuery; + /** + * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param obj A DOM node or jQuery object indicating where to stop matching preceding sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + prevUntil(obj?: JQuery, filter?: string): JQuery; + + /** + * Get the siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + siblings(selector?: string): JQuery; + + /** + * Reduce the set of matched elements to a subset specified by a range of indices. + * + * @param start An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set. + * @param end An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set. + */ + slice(start: number, end?: number): JQuery; + + /** + * Show the queue of functions to be executed on the matched elements. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + queue(queueName?: string): any[]; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param newQueue An array of functions to replace the current queue contents. + */ + queue(newQueue: Function[]): JQuery; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. + */ + queue(callback: Function): JQuery; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param newQueue An array of functions to replace the current queue contents. + */ + queue(queueName: string, newQueue: Function[]): JQuery; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. + */ + queue(queueName: string, callback: Function): JQuery; +} +declare module "jquery" { + var $: JQueryStatic; + export = $; +} +declare var jQuery: JQueryStatic; diff --git a/angular1/e2e-tests/typings/karma-jasmine/karma-jasmine.d.ts b/angular1/e2e-tests/typings/karma-jasmine/karma-jasmine.d.ts new file mode 100644 index 0000000..e4cdc5a --- /dev/null +++ b/angular1/e2e-tests/typings/karma-jasmine/karma-jasmine.d.ts @@ -0,0 +1,9 @@ +// Type definitions for karma-jasmine plugin +// Project: https://github.com/karma-runner/karma-jasmine +// Definitions by: Michel Salib +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare function ddescribe(description: string, specDefinitions: () => void): void; +declare function iit(expectation: string, assertion: () => void): void; diff --git a/angular1/e2e-tests/typings/selenium-webdriver/selenium-webdriver.d.ts b/angular1/e2e-tests/typings/selenium-webdriver/selenium-webdriver.d.ts new file mode 100644 index 0000000..c4af933 --- /dev/null +++ b/angular1/e2e-tests/typings/selenium-webdriver/selenium-webdriver.d.ts @@ -0,0 +1,4864 @@ +// Type definitions for Selenium WebDriverJS 2.44.0 +// Project: https://code.google.com/p/selenium/ +// Definitions by: Bill Armstrong +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module chrome { + /** + * Creates a new WebDriver client for Chrome. + * + * @extends {webdriver.WebDriver} + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(webdriver.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@link getDefaultService default service} by default. + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow to use, or + * {@code null} to use the currently active flow. + * @constructor + */ + constructor(opt_config?: webdriver.Capabilities, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: Options, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); + } + + interface IOptionsValues { + args: string[]; + binary?: string; + detach: boolean; + extensions: string[]; + localState?: any; + logFile?: string; + prefs?: any; + } + + /** + * Class for managing ChromeDriver specific options. + */ + class Options { + /** + * @constructor + */ + constructor(); + + /** + * Extracts the ChromeDriver specific options from the given capabilities + * object. + * @param {!webdriver.Capabilities} capabilities The capabilities object. + * @return {!Options} The ChromeDriver options. + */ + static fromCapabilities(capabilities: webdriver.Capabilities): Options; + + + /** + * Add additional command line arguments to use when launching the Chrome + * browser. Each argument may be specified with or without the "--" prefix + * (e.g. "--foo" and "foo"). Arguments with an associated value should be + * delimited by an "=": "foo=bar". + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: string[]): Options; + + + /** + * Add additional extensions to install when launching Chrome. Each extension + * should be specified as the path to the packed CRX file, or a Buffer for an + * extension. + * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The + * extensions to add. + * @return {!Options} A self reference. + */ + addExtensions(...var_args: any[]): Options; + + + /** + * Sets the path to the Chrome binary to use. On Mac OS X, this path should + * reference the actual Chrome executable, not just the application binary + * (e.g. "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"). + * + * The binary path be absolute or relative to the chromedriver server + * executable, but it must exist on the machine that will launch Chrome. + * + * @param {string} path The path to the Chrome binary to use. + * @return {!Options} A self reference. + */ + setChromeBinaryPath(path: string): Options; + + + /** + * Sets whether to leave the started Chrome browser running if the controlling + * ChromeDriver service is killed before {@link webdriver.WebDriver#quit()} is + * called. + * @param {boolean} detach Whether to leave the browser running if the + * chromedriver service is killed before the session. + * @return {!Options} A self reference. + */ + detachDriver(detach: boolean): Options; + + + /** + * Sets the user preferences for Chrome's user profile. See the "Preferences" + * file in Chrome's user data directory for examples. + * @param {!Object} prefs Dictionary of user preferences to use. + * @return {!Options} A self reference. + */ + setUserPreferences(prefs: any): Options; + + + /** + * Sets the logging preferences for the new session. + * @param {!webdriver.logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + + /** + * Sets preferences for the "Local State" file in Chrome's user data + * directory. + * @param {!Object} state Dictionary of local state preferences. + * @return {!Options} A self reference. + */ + setLocalState(state: any): Options; + + + /** + * Sets the path to Chrome's log file. This path should exist on the machine + * that will launch Chrome. + * @param {string} path Path to the log file to use. + * @return {!Options} A self reference. + */ + setChromeLogFile(path: string): Options; + + + /** + * Sets the proxy settings for the new session. + * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + + /** + * Converts this options instance to a {@link webdriver.Capabilities} object. + * @param {webdriver.Capabilities=} opt_capabilities The capabilities to merge + * these options into, if any. + * @return {!webdriver.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; + + + /** + * Converts this instance to its JSON wire protocol representation. Note this + * function is an implementation not intended for general use. + * @return {{args: !Array., + * binary: (string|undefined), + * detach: boolean, + * extensions: !Array., + * localState: (Object|undefined), + * logFile: (string|undefined), + * prefs: (Object|undefined)}} The JSON wire protocol representation + * of this instance. + */ + toJSON(): IOptionsValues; + } + + /** + * Creates {@link remote.DriverService} instances that manage a ChromeDriver + * server. + */ + class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the chromedriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the chromedriver + * cannot be found on the PATH. + * @constructor + */ + constructor(opt_exe?: string); + + /** + * Sets the port to start the ChromeDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; + + + /** + * Sets the path of the log file the driver should log to. If a log file is + * not specified, the driver will log to stderr. + * @param {string} path Path of the log file to use. + * @return {!ServiceBuilder} A self reference. + */ + loggingTo(path: string): ServiceBuilder; + + + /** + * Enables verbose logging. + * @return {!ServiceBuilder} A self reference. + */ + enableVerboseLogging(): ServiceBuilder; + + + /** + * Sets the number of threads the driver should use to manage HTTP requests. + * By default, the driver will use 4 threads. + * @param {number} n The number of threads to use. + * @return {!ServiceBuilder} A self reference. + */ + setNumHttpThreads(n: number): ServiceBuilder; + + + /** + * Sets the base path for WebDriver REST commands (e.g. "/wd/hub"). + * By default, the driver will accept commands relative to "/". + * @param {string} path The base path to use. + * @return {!ServiceBuilder} A self reference. + */ + setUrlBasePath(path: string): ServiceBuilder; + + + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array.)} config The + * configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string): ServiceBuilder; + setStdio(config: any[]): ServiceBuilder; + + + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: { [key: string]: string }): ServiceBuilder; + + + /** + * Creates a new DriverService using this instance's current configuration. + * @return {remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): any; + } + + /** + * Returns the default ChromeDriver service. If such a service has not been + * configured, one will be constructed using the default configuration for + * a ChromeDriver executable found on the system PATH. + * @return {!remote.DriverService} The default ChromeDriver service. + */ + function getDefaultService(): any; + + /** + * Sets the default service to use for new ChromeDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ + function setDefaultService(service: any): void; +} + +declare module firefox { + /** + * Manages a Firefox subprocess configured for use with WebDriver. + */ + class Binary { + /** + * @param {string=} opt_exe Path to the Firefox binary to use. If not + * specified, will attempt to locate Firefox on the current system. + * @constructor + */ + constructor(opt_exe?: string); + + /** + * Add arguments to the command line used to start Firefox. + * @param {...(string|!Array.)} var_args Either the arguments to add as + * varargs, or the arguments as an array. + */ + addArguments(...var_args: string[]): void; + + + /** + * Launches Firefox and eturns a promise that will be fulfilled when the process + * terminates. + * @param {string} profile Path to the profile directory to use. + * @return {!promise.Promise.} A promise for the process result. + * @throws {Error} If this instance has already been started. + */ + launch(profile: string): webdriver.promise.Promise; + + + /** + * Kills the managed Firefox process. + * @return {!promise.Promise} A promise for when the process has terminated. + */ + kill(): webdriver.promise.Promise; + } + + /** + * A WebDriver client for Firefox. + * + * @extends {webdriver.WebDriver} + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(Options|webdriver.Capabilities|Object)=} opt_config The + * configuration options for this driver, specified as either an + * {@link Options} or {@link webdriver.Capabilities}, or as a raw hash + * object. + * @param {webdriver.promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + * @constructor + */ + constructor(opt_config?: webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: any, opt_flow?: webdriver.promise.ControlFlow); + } + + /** + * Configuration options for the FirefoxDriver. + */ + class Options { + /** + * @constructor + */ + constructor(); + + /** + * Sets the profile to use. The profile may be specified as a + * {@link Profile} object or as the path to an existing Firefox profile to use + * as a template. + * + * @param {(string|!Profile)} profile The profile to use. + * @return {!Options} A self reference. + */ + setProfile(profile: string): Options; + setProfile(profile: Profile): Options; + + + /** + * Sets the binary to use. The binary may be specified as the path to a Firefox + * executable, or as a {@link Binary} object. + * + * @param {(string|!Binary)} binary The binary to use. + * @return {!Options} A self reference. + */ + setBinary(binary: string): Options; + setBinary(binary: Binary): Options; + + + /** + * Sets the logging preferences for the new session. + * @param {webdriver.logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; + + + /** + * Sets the proxy to use. + * + * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + + /** + * Converts these options to a {@link webdriver.Capabilities} instance. + * + * @return {!webdriver.Capabilities} A new capabilities object. + */ + toCapabilities(opt_remote?: any): webdriver.Capabilities; + } + + /** + * Models a Firefox proifle directory for use with the FirefoxDriver. The + * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} + * is called. + */ + class Profile { + /** + * @param {string=} opt_dir Path to an existing Firefox profile directory to + * use a template for this profile. If not specified, a blank profile will + * be used. + * @constructor + */ + constructor(opt_dir?: string); + + /** + * Registers an extension to be included with this profile. + * @param {string} extension Path to the extension to include, as either an + * unpacked extension directory or the path to a xpi file. + */ + addExtension(extension: string): void; + + + /** + * Sets a desired preference for this profile. + * @param {string} key The preference key. + * @param {(string|number|boolean)} value The preference value. + * @throws {Error} If attempting to set a frozen preference. + */ + setPreference(key: string, value: string): void; + setPreference(key: string, value: number): void; + setPreference(key: string, value: boolean): void; + + + /** + * Returns the currently configured value of a profile preference. This does + * not include any defaults defined in the profile's template directory user.js + * file (if a template were specified on construction). + * @param {string} key The desired preference. + * @return {(string|number|boolean|undefined)} The current value of the + * requested preference. + */ + getPreference(key: string): any; + + + /** + * @return {number} The port this profile is currently configured to use, or + * 0 if the port will be selected at random when the profile is written + * to disk. + */ + getPort(): number; + + + /** + * Sets the port to use for the WebDriver extension loaded by this profile. + * @param {number} port The desired port, or 0 to use any free port. + */ + setPort(port: number): void; + + + /** + * @return {boolean} Whether the FirefoxDriver is configured to automatically + * accept untrusted SSL certificates. + */ + acceptUntrustedCerts(): boolean; + + + /** + * Sets whether the FirefoxDriver should automatically accept untrusted SSL + * certificates. + * @param {boolean} value . + */ + setAcceptUntrustedCerts(value: boolean): void; + + + /** + * Sets whether to assume untrusted certificates come from untrusted issuers. + * @param {boolean} value . + */ + setAssumeUntrustedCertIssuer(value: boolean): void; + + + /** + * @return {boolean} Whether to assume untrusted certs come from untrusted + * issuers. + */ + assumeUntrustedCertIssuer(): boolean; + + + /** + * Sets whether to use native events with this profile. + * @param {boolean} enabled . + */ + setNativeEventsEnabled(enabled: boolean): void; + + + /** + * Returns whether native events are enabled in this profile. + * @return {boolean} . + */ + nativeEventsEnabled(): boolean; + + + /** + * Writes this profile to disk. + * @param {boolean=} opt_excludeWebDriverExt Whether to exclude the WebDriver + * extension from the generated profile. Used to reduce the size of an + * {@link #encode() encoded profile} since the server will always install + * the extension itself. + * @return {!promise.Promise.} A promise for the path to the new + * profile directory. + */ + writeToDisk(opt_excludeWebDriverExt?: boolean): webdriver.promise.Promise; + + + /** + * Encodes this profile as a zipped, base64 encoded directory. + * @return {!promise.Promise.} A promise for the encoded profile. + */ + encode(): webdriver.promise.Promise; + } +} + +declare module executors { + /** + * Creates a command executor that uses WebDriver's JSON wire protocol. + * @param url The server's URL, or a promise that will resolve to that URL. + * @returns {!webdriver.CommandExecutor} The new command executor. + */ + function createExecutor(url: string): webdriver.CommandExecutor; + function createExecutor(url: webdriver.promise.Promise): webdriver.CommandExecutor; +} + +declare module webdriver { + + module error { + interface IErrorCode { + SUCCESS: number; + + NO_SUCH_ELEMENT: number; + NO_SUCH_FRAME: number; + UNKNOWN_COMMAND: number; + UNSUPPORTED_OPERATION: number; // Alias for UNKNOWN_COMMAND. + STALE_ELEMENT_REFERENCE: number; + ELEMENT_NOT_VISIBLE: number; + INVALID_ELEMENT_STATE: number; + UNKNOWN_ERROR: number; + ELEMENT_NOT_SELECTABLE: number; + JAVASCRIPT_ERROR: number; + XPATH_LOOKUP_ERROR: number; + TIMEOUT: number; + NO_SUCH_WINDOW: number; + INVALID_COOKIE_DOMAIN: number; + UNABLE_TO_SET_COOKIE: number; + MODAL_DIALOG_OPENED: number; + UNEXPECTED_ALERT_OPEN: number; + NO_SUCH_ALERT: number; + NO_MODAL_DIALOG_OPEN: number; + SCRIPT_TIMEOUT: number; + INVALID_ELEMENT_COORDINATES: number; + IME_NOT_AVAILABLE: number; + IME_ENGINE_ACTIVATION_FAILED: number; + INVALID_SELECTOR_ERROR: number; + SESSION_NOT_CREATED: number; + MOVE_TARGET_OUT_OF_BOUNDS: number; + SQL_DATABASE_ERROR: number; + INVALID_XPATH_SELECTOR: number; + INVALID_XPATH_SELECTOR_RETURN_TYPE: number; + // The following error codes are derived straight from HTTP return codes. + METHOD_NOT_ALLOWED: number; + } + + var ErrorCode: IErrorCode; + + /** + * Error extension that includes error status codes from the WebDriver wire + * protocol: + * http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes + * + * @extends {Error} + */ + class Error { + + //region Constructors + + /** + * @param {!bot.ErrorCode} code The error's status code. + * @param {string=} opt_message Optional error message. + * @constructor + */ + constructor(code: number, opt_message?: string); + + //endregion + + //region Static Properties + + /** + * Status strings enumerated in the W3C WebDriver working draft. + * @enum {string} + * @see http://www.w3.org/TR/webdriver/#status-codes + */ + static State: { + ELEMENT_NOT_SELECTABLE: string; + ELEMENT_NOT_VISIBLE: string; + IME_ENGINE_ACTIVATION_FAILED: string; + IME_NOT_AVAILABLE: string; + INVALID_COOKIE_DOMAIN: string; + INVALID_ELEMENT_COORDINATES: string; + INVALID_ELEMENT_STATE: string; + INVALID_SELECTOR: string; + JAVASCRIPT_ERROR: string; + MOVE_TARGET_OUT_OF_BOUNDS: string; + NO_SUCH_ALERT: string; + NO_SUCH_DOM: string; + NO_SUCH_ELEMENT: string; + NO_SUCH_FRAME: string; + NO_SUCH_WINDOW: string; + SCRIPT_TIMEOUT: string; + SESSION_NOT_CREATED: string; + STALE_ELEMENT_REFERENCE: string; + SUCCESS: string; + TIMEOUT: string; + UNABLE_TO_SET_COOKIE: string; + UNEXPECTED_ALERT_OPEN: string; + UNKNOWN_COMMAND: string; + UNKNOWN_ERROR: string; + UNSUPPORTED_OPERATION: string; + } + + //endregion + + //region Properties + + /** + * This error's status code. + * @type {!bot.ErrorCode} + */ + code: number; + + /** @type {string} */ + state: string; + + /** @override */ + message: string; + + /** @override */ + name: string; + + /** @override */ + stack: string; + + /** + * Flag used for duck-typing when this code is embedded in a Firefox extension. + * This is required since an Error thrown in one component and then reported + * to another will fail instanceof checks in the second component. + * @type {boolean} + */ + isAutomationError: boolean; + + //endregion + + //region Methods + + /** @return {string} The string representation of this error. */ + toString(): string; + + //endregion + } + } + + module logging { + + /** + * A hash describing log preferences. + * @typedef {Object.} + */ + class Preferences { + setLevel(type: string, level: ILevel): void; + toJSON(): { [key: string]: string }; + } + + interface IType { + /** Logs originating from the browser. */ + BROWSER: string; + /** Logs from a WebDriver client. */ + CLIENT: string; + /** Logs from a WebDriver implementation. */ + DRIVER: string; + /** Logs related to performance. */ + PERFORMANCE: string; + /** Logs from the remote server. */ + SERVER: string; + } + + /** + * Common log types. + * @enum {string} + */ + var Type: IType; + + /** + * Logging levels. + * @enum {{value: number, name: webdriver.logging.LevelName}} + */ + interface ILevel { + value: number; + name: string; + } + + interface ILevelValues { + ALL: ILevel; + DEBUG: ILevel; + INFO: ILevel; + WARNING: ILevel; + SEVERE: ILevel; + OFF: ILevel; + } + + var Level: ILevelValues; + + /** + * Converts a level name or value to a {@link webdriver.logging.Level} value. + * If the name/value is not recognized, {@link webdriver.logging.Level.ALL} + * will be returned. + * @param {(number|string)} nameOrValue The log level name, or value, to + * convert . + * @return {!webdriver.logging.Level} The converted level. + */ + function getLevel(nameOrValue: string): ILevel; + function getLevel(nameOrValue: number): ILevel; + + interface IEntryJSON { + level: string; + message: string; + timestamp: number; + type: string; + } + + /** + * A single log entry. + */ + class Entry { + + //region Constructors + + /** + * @param {(!webdriver.logging.Level|string)} level The entry level. + * @param {string} message The log message. + * @param {number=} opt_timestamp The time this entry was generated, in + * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the + * current time will be used. + * @param {string=} opt_type The log type, if known. + * @constructor + */ + constructor(level: ILevel, message: string, opt_timestamp?:number, opt_type?:string); + constructor(level: string, message: string, opt_timestamp?:number, opt_type?:string); + + //endregion + + //region Public Properties + + /** @type {!webdriver.logging.Level} */ + level: ILevel; + + /** @type {string} */ + message: string; + + /** @type {number} */ + timestamp: number; + + /** @type {string} */ + type: string; + + //endregion + + //region Static Methods + + /** + * Converts a {@link goog.debug.LogRecord} into a + * {@link webdriver.logging.Entry}. + * @param {!goog.debug.LogRecord} logRecord The record to convert. + * @param {string=} opt_type The log type. + * @return {!webdriver.logging.Entry} The converted entry. + */ + static fromClosureLogRecord(logRecord: any, opt_type?:string): Entry; + + //endregion + + //region Methods + + /** + * @return {{level: string, message: string, timestamp: number, + * type: string}} The JSON representation of this entry. + */ + toJSON(): IEntryJSON; + + //endregion + } + } + + module promise { + //region Functions + + /** + * Given an array of promises, will return a promise that will be fulfilled + * with the fulfillment values of the input array's values. If any of the + * input array's promises are rejected, the returned promise will be rejected + * with the same reason. + * + * @param {!Array.<(T|!webdriver.promise.Promise.)>} arr An array of + * promises to wait on. + * @return {!webdriver.promise.Promise.>} A promise that is + * fulfilled with an array containing the fulfilled values of the + * input array, or rejected with the same reason as the first + * rejected value. + * @template T + */ + function all(arr: Promise[]): Promise; + + /** + * Invokes the appropriate callback function as soon as a promised + * {@code value} is resolved. This function is similar to + * {@link webdriver.promise.when}, except it does not return a new promise. + * @param {*} value The value to observe. + * @param {Function} callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + */ + function asap(value: any, callback: Function, opt_errback?: Function): void; + + /** + * @return {!webdriver.promise.ControlFlow} The currently active control flow. + */ + function controlFlow(): ControlFlow; + + /** + * Creates a new control flow. The provided callback will be invoked as the + * first task within the new flow, with the flow as its sole argument. Returns + * a promise that resolves to the callback result. + * @param {function(!webdriver.promise.ControlFlow)} callback The entry point + * to the newly created flow. + * @return {!webdriver.promise.Promise} A promise that resolves to the callback + * result. + */ + function createFlow(callback: (flow: ControlFlow) => R): Promise; + + /** + * Determines whether a {@code value} should be treated as a promise. + * Any object whose "then" property is a function will be considered a promise. + * + * @param {*} value The value to test. + * @return {boolean} Whether the value is a promise. + */ + function isPromise(value: any): boolean; + + /** + * Tests is a function is a generator. + * @param {!Function} fn The function to test. + * @return {boolean} Whether the function is a generator. + */ + function isGenerator(fn: Function): boolean; + + /** + * Creates a promise that will be resolved at a set time in the future. + * @param {number} ms The amount of time, in milliseconds, to wait before + * resolving the promise. + * @return {!webdriver.promise.Promise} The promise. + */ + function delayed(ms: number): Promise; + + /** + * Calls a function for each element in an array, and if the function returns + * true adds the element to a new array. + * + *

If the return value of the filter function is a promise, this function + * will wait for it to be fulfilled before determining whether to insert the + * element into the new array. + * + *

If the filter function throws or returns a rejected promise, the promise + * returned by this function will be rejected with the same reason. Only the + * first failure will be reported; all subsequent errors will be silently + * ignored. + * + * @param {!(Array.|webdriver.promise.Promise.>)} arr The + * array to iterator over, or a promise that will resolve to said array. + * @param {function(this: SELF, TYPE, number, !Array.): ( + * boolean|webdriver.promise.Promise.)} fn The function + * to call for each element in the array. + * @param {SELF=} opt_self The object to be used as the value of 'this' within + * {@code fn}. + * @template TYPE, SELF + */ + function filter(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise; + function filter(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + + /** + * Creates a new deferred object. + * @return {!webdriver.promise.Deferred} The new deferred object. + */ + function defer(): Deferred; + + /** + * Creates a promise that has been resolved with the given value. + * @param {*=} opt_value The resolved value. + * @return {!webdriver.promise.Promise} The resolved promise. + */ + function fulfilled(opt_value?: T): Promise; + + /** + * Calls a function for each element in an array and inserts the result into a + * new array, which is used as the fulfillment value of the promise returned + * by this function. + * + *

If the return value of the mapping function is a promise, this function + * will wait for it to be fulfilled before inserting it into the new array. + * + *

If the mapping function throws or returns a rejected promise, the + * promise returned by this function will be rejected with the same reason. + * Only the first failure will be reported; all subsequent errors will be + * silently ignored. + * + * @param {!(Array.|webdriver.promise.Promise.>)} arr The + * array to iterator over, or a promise that will resolve to said array. + * @param {function(this: SELF, TYPE, number, !Array.): ?} fn The + * function to call for each element in the array. This function should + * expect three arguments (the element, the index, and the array itself. + * @param {SELF=} opt_self The object to be used as the value of 'this' within + * {@code fn}. + * @template TYPE, SELF + */ + function map(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + function map(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + + /** + * Creates a promise that has been rejected with the given reason. + * @param {*=} opt_reason The rejection reason; may be any value, but is + * usually an Error or a string. + * @return {!webdriver.promise.Promise} The rejected promise. + */ + function rejected(opt_reason?: any): Promise; + + /** + * Wraps a function that is assumed to be a node-style callback as its final + * argument. This callback takes two arguments: an error value (which will be + * null if the call succeeded), and the success value as the second argument. + * If the call fails, the returned promise will be rejected, otherwise it will + * be resolved with the result. + * @param {!Function} fn The function to wrap. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * result of the provided function's callback. + */ + function checkedNodeCall(fn: Function, ...var_args: any[]): Promise; + + /** + * Consumes a {@code GeneratorFunction}. Each time the generator yields a + * promise, this function will wait for it to be fulfilled before feeding the + * fulfilled value back into {@code next}. Likewise, if a yielded promise is + * rejected, the rejection error will be passed to {@code throw}. + * + *

Example 1: the Fibonacci Sequence. + *


+         * webdriver.promise.consume(function* fibonacci() {
+         *   var n1 = 1, n2 = 1;
+         *   for (var i = 0; i < 4; ++i) {
+         *     var tmp = yield n1 + n2;
+         *     n1 = n2;
+         *     n2 = tmp;
+         *   }
+         *   return n1 + n2;
+         * }).then(function(result) {
+         *   console.log(result);  // 13
+         * });
+         * 
+ * + *

Example 2: a generator that throws. + *


+         * webdriver.promise.consume(function* () {
+         *   yield webdriver.promise.delayed(250).then(function() {
+         *     throw Error('boom');
+         *   });
+         * }).thenCatch(function(e) {
+         *   console.log(e.toString());  // Error: boom
+         * });
+         * 
+ * + * @param {!Function} generatorFn The generator function to execute. + * @param {Object=} opt_self The object to use as "this" when invoking the + * initial generator. + * @param {...*} var_args Any arguments to pass to the initial generator. + * @return {!webdriver.promise.Promise.} A promise that will resolve to the + * generator's final result. + * @throws {TypeError} If the given function is not a generator. + */ + function consume(generatorFn: Function, opt_self?: any, ...var_args: any[]): Promise; + + /** + * Registers an observer on a promised {@code value}, returning a new promise + * that will be resolved when the value is. If {@code value} is not a promise, + * then the return promise will be immediately resolved. + * @param {*} value The value to observe. + * @param {Function=} opt_callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + * @return {!webdriver.promise.Promise} A new promise. + */ + function when(value: T, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + function when(value: Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + + /** + * Returns a promise that will be resolved with the input value in a + * fully-resolved state. If the value is an array, each element will be fully + * resolved. Likewise, if the value is an object, all keys will be fully + * resolved. In both cases, all nested arrays and objects will also be + * fully resolved. All fields are resolved in place; the returned promise will + * resolve on {@code value} and not a copy. + * + * Warning: This function makes no checks against objects that contain + * cyclical references: + * + * var value = {}; + * value['self'] = value; + * webdriver.promise.fullyResolved(value); // Stack overflow. + * + * @param {*} value The value to fully resolve. + * @return {!webdriver.promise.Promise} A promise for a fully resolved version + * of the input value. + */ + function fullyResolved(value: any): Promise; + + /** + * Changes the default flow to use when no others are active. + * @param {!webdriver.promise.ControlFlow} flow The new default flow. + * @throws {Error} If the default flow is not currently active. + */ + function setDefaultFlow(flow: ControlFlow): void; + + //endregion + + /** + * Error used when the computation of a promise is cancelled. + * + * @extends {goog.debug.Error} + * @final + */ + class CancellationError { + /** + * @param {string=} opt_msg The cancellation message. + * @constructor + */ + constructor(opt_msg?: string); + + name: string; + message: string; + } + + interface IThenable { + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. This method is a no-op if the promise has alreayd been resolved. + * + * @param {string=} opt_reason The reason this promise is being cancelled. + */ + cancel(opt_reason?: string): void; + + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; + + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *

+             *   // Synchronous API:
+             *   try {
+             *     doSynchronousWork();
+             *   } catch (ex) {
+             *     console.error(ex);
+             *   }
+             *
+             *   // Asynchronous promise API:
+             *   doAsynchronousWork().thenCatch(function(ex) {
+             *     console.error(ex);
+             *   });
+             * 
+ * + * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!webdriver.promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *

+             *   // Synchronous API:
+             *   try {
+             *     doSynchronousWork();
+             *   } finally {
+             *     cleanUp();
+             *   }
+             *
+             *   // Asynchronous promise API:
+             *   doAsynchronousWork().thenFinally(cleanUp);
+             * 
+ * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *

+             *   try {
+             *     throw Error('one');
+             *   } finally {
+             *     throw Error('two');  // Hides Error: one
+             *   }
+             *
+             *   webdriver.promise.rejected(Error('one'))
+             *       .thenFinally(function() {
+             *         throw Error('two');  // Hides Error: one
+             *       });
+             * 
+ * + * + * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: () => any): Promise; + } + + /** + * Thenable is a promise-like object with a {@code then} method which may be + * used to schedule callbacks on a promised value. + * + * @interface + * @template T + */ + class Thenable implements IThenable { + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. This method is a no-op if the promise has alreayd been resolved. + * + * @param {string=} opt_reason The reason this promise is being cancelled. + */ + cancel(opt_reason?: string): void; + + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; + + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *

+             *   // Synchronous API:
+             *   try {
+             *     doSynchronousWork();
+             *   } catch (ex) {
+             *     console.error(ex);
+             *   }
+             *
+             *   // Asynchronous promise API:
+             *   doAsynchronousWork().thenCatch(function(ex) {
+             *     console.error(ex);
+             *   });
+             * 
+ * + * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!webdriver.promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *

+             *   // Synchronous API:
+             *   try {
+             *     doSynchronousWork();
+             *   } finally {
+             *     cleanUp();
+             *   }
+             *
+             *   // Asynchronous promise API:
+             *   doAsynchronousWork().thenFinally(cleanUp);
+             * 
+ * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *

+             *   try {
+             *     throw Error('one');
+             *   } finally {
+             *     throw Error('two');  // Hides Error: one
+             *   }
+             *
+             *   webdriver.promise.rejected(Error('one'))
+             *       .thenFinally(function() {
+             *         throw Error('two');  // Hides Error: one
+             *       });
+             * 
+ * + * + * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: () => any): Promise; + + /** + * Adds a property to a class prototype to allow runtime checks of whether + * instances of that class implement the Thenable interface. This function will + * also ensure the prototype's {@code then} function is exported from compiled + * code. + * @param {function(new: webdriver.promise.Thenable, ...[?])} ctor The + * constructor whose prototype to modify. + */ + static addImplementation(ctor: Function): void; + + + /** + * Checks if an object has been tagged for implementing the Thenable interface + * as defined by {@link webdriver.promise.Thenable.addImplementation}. + * @param {*} object The object to test. + * @return {boolean} Whether the object is an implementation of the Thenable + * interface. + */ + static isImplementation(object: any): boolean; + } + + /** + * Represents the eventual value of a completed operation. Each promise may be + * in one of three states: pending, resolved, or rejected. Each promise starts + * in the pending state and may make a single transition to either a + * fulfilled or failed state. + * + *

This class is based on the Promise/A proposal from CommonJS. Additional + * functions are provided for API compatibility with Dojo Deferred objects. + * + * @see http://wiki.commonjs.org/wiki/Promises/A + */ + class Promise implements IThenable { + + //region Constructors + + /** + * @constructor + * @see http://wiki.commonjs.org/wiki/Promises/A + */ + constructor(); + + //endregion + + //region Methods + + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. + * @param {*} reason The reason this promise is being cancelled. If not an + * {@code Error}, one will be created using the value's string + * representation. + */ + cancel(reason: any): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. This function most + * overridden by subtypes. + * + * @param opt_callback The function to call if this promise is + * successfully resolved. The function should expect a single argument: the + * promise's resolved value. + * @param opt_errback The function to call if this promise is + * rejected. The function should expect a single argument: the rejection + * reason. + * @return A new promise which will be resolved + * with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; + + /** + * Registers listeners for when this instance is resolved. This function most + * overridden by subtypes. + * + * @param opt_callback The function to call if this promise is + * successfully resolved. The function should expect a single argument: the + * promise's resolved value. + * @param opt_errback The function to call if this promise is + * rejected. The function should expect a single argument: the rejection + * reason. + * @return A new promise which will be resolved + * with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; + + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *


+             *   // Synchronous API:
+             *   try {
+             *     doSynchronousWork();
+             *   } catch (ex) {
+             *     console.error(ex);
+             *   }
+             *
+             *   // Asynchronous promise API:
+             *   doAsynchronousWork().thenCatch(function(ex) {
+             *     console.error(ex);
+             *   });
+             * 
+ * + * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!webdriver.promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *

+             *   // Synchronous API:
+             *   try {
+             *     doSynchronousWork();
+             *   } finally {
+             *     cleanUp();
+             *   }
+             *
+             *   // Asynchronous promise API:
+             *   doAsynchronousWork().thenFinally(cleanUp);
+             * 
+ * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *

+             *   try {
+             *     throw Error('one');
+             *   } finally {
+             *     throw Error('two');  // Hides Error: one
+             *   }
+             *
+             *   webdriver.promise.rejected(Error('one'))
+             *       .thenFinally(function() {
+             *         throw Error('two');  // Hides Error: one
+             *       });
+             * 
+ * + * + * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: () => any): Promise; + + //endregion + } + + /** + * Represents a value that will be resolved at some point in the future. This + * class represents the protected "producer" half of a Promise - each Deferred + * has a {@code promise} property that may be returned to consumers for + * registering callbacks, reserving the ability to resolve the deferred to the + * producer. + * + *

If this Deferred is rejected and there are no listeners registered before + * the next turn of the event loop, the rejection will be passed to the + * {@link webdriver.promise.ControlFlow} as an unhandled failure. + * + *

If this Deferred is cancelled, the cancellation reason will be forward to + * the Deferred's canceller function (if provided). The canceller may return a + * truth-y value to override the reason provided for rejection. + * + * @extends {webdriver.promise.Promise} + */ + class Deferred extends Promise { + //region Constructors + + /** + * + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow + * this instance was created under. This should only be provided during + * unit tests. + * @constructor + */ + constructor(opt_flow?: ControlFlow); + + //endregion + + static State_: { + BLOCKED: number; + PENDING: number; + REJECTED: number; + RESOLVED: number; + } + + //region Properties + + /** + * The consumer promise for this instance. Provides protected access to the + * callback registering functions. + * @type {!webdriver.promise.Promise} + */ + promise: Promise; + + //endregion + + //region Methods + + /** + * Rejects this promise. If the error is itself a promise, this instance will + * be chained to it and be rejected with the error's resolved value. + * @param {*=} opt_error The rejection reason, typically either a + * {@code Error} or a {@code string}. + */ + reject(opt_error?: any): void; + errback(opt_error?: any): void; + + /** + * Resolves this promise with the given value. If the value is itself a + * promise and not a reference to this deferred, this instance will wait for + * it before resolving. + * @param {*=} opt_value The resolved value. + */ + fulfill(opt_value?: T): void; + + /** + * Removes all of the listeners previously registered on this deferred. + * @throws {Error} If this deferred has already been resolved. + */ + removeAll(): void; + + //endregion + } + + interface IControlFlowTimer { + clearInterval: (ms: number) => void; + clearTimeout: (ms: number) => void; + setInterval: (fn: Function, ms: number) => number; + setTimeout: (fn: Function, ms: number) => number; + } + + /** + * Handles the execution of scheduled tasks, each of which may be an + * asynchronous operation. The control flow will ensure tasks are executed in + * the ordered scheduled, starting each task only once those before it have + * completed. + * + *

Each task scheduled within this flow may return a + * {@link webdriver.promise.Promise} to indicate it is an asynchronous + * operation. The ControlFlow will wait for such promises to be resolved before + * marking the task as completed. + * + *

Tasks and each callback registered on a {@link webdriver.promise.Deferred} + * will be run in their own ControlFlow frame. Any tasks scheduled within a + * frame will have priority over previously scheduled tasks. Furthermore, if + * any of the tasks in the frame fails, the remainder of the tasks in that frame + * will be discarded and the failure will be propagated to the user through the + * callback/task's promised result. + * + *

Each time a ControlFlow empties its task queue, it will fire an + * {@link webdriver.promise.ControlFlow.EventType.IDLE} event. Conversely, + * whenever the flow terminates due to an unhandled error, it will remove all + * remaining tasks in its queue and fire an + * {@link webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION} event. If + * there are no listeners registered with the flow, the error will be + * rethrown to the global error handler. + * + * @extends {webdriver.EventEmitter} + */ + class ControlFlow extends EventEmitter { + + //region Constructors + + /** + * @param {webdriver.promise.ControlFlow.Timer=} opt_timer The timer object + * to use. Should only be set for testing. + * @constructor + */ + constructor(opt_timer?: IControlFlowTimer); + + //endregion + + //region Properties + + /** + * The timer used by this instance. + * @type {webdriver.promise.ControlFlow.Timer} + */ + timer: IControlFlowTimer; + + //endregion + + //region Static Properties + + /** + * The default timer object, which uses the global timer functions. + * @type {webdriver.promise.ControlFlow.Timer} + */ + static defaultTimer: IControlFlowTimer; + + /** + * Events that may be emitted by an {@link webdriver.promise.ControlFlow}. + * @enum {string} + */ + static EventType: { + /** Emitted when all tasks have been successfully executed. */ + IDLE: string; + + /** Emitted when a ControlFlow has been reset. */ + RESET: string; + + /** Emitted whenever a new task has been scheduled. */ + SCHEDULE_TASK: string; + + /** + * Emitted whenever a control flow aborts due to an unhandled promise + * rejection. This event will be emitted along with the offending rejection + * reason. Upon emitting this event, the control flow will empty its task + * queue and revert to its initial state. + */ + UNCAUGHT_EXCEPTION: string; + }; + + /** + * How often, in milliseconds, the event loop should run. + * @type {number} + * @const + */ + static EVENT_LOOP_FREQUENCY: number; + + //endregion + + //region Methods + + /** + * Resets this instance, clearing its queue and removing all event listeners. + */ + reset(): void; + + /** + * Returns a summary of the recent task activity for this instance. This + * includes the most recently completed task, as well as any parent tasks. In + * the returned summary, the task at index N is considered a sub-task of the + * task at index N+1. + * @return {!Array.} A summary of this instance's recent task + * activity. + */ + getHistory(): string[]; + + /** Clears this instance's task history. */ + clearHistory(): void; + + /** + * Appends a summary of this instance's recent task history to the given + * error's stack trace. This function will also ensure the error's stack trace + * is in canonical form. + * @param {!(Error|goog.testing.JsUnitException)} e The error to annotate. + * @return {!(Error|goog.testing.JsUnitException)} The annotated error. + */ + annotateError(e: any): any; + + /** + * @return {string} The scheduled tasks still pending with this instance. + */ + getSchedule(): string; + + /** + * Schedules a task for execution. If there is nothing currently in the + * queue, the task will be executed in the next turn of the event loop. + * + * @param {!Function} fn The function to call to start the task. If the + * function returns a {@link webdriver.promise.Promise}, this instance + * will wait for it to be resolved before starting the next task. + * @param {string=} opt_description A description of the task. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the result of the action. + */ + execute(fn: Function, opt_description?: string): Promise; + + /** + * Inserts a {@code setTimeout} into the command queue. This is equivalent to + * a thread sleep in a synchronous programming language. + * + * @param {number} ms The timeout delay, in milliseconds. + * @param {string=} opt_description A description to accompany the timeout. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the result of the action. + */ + timeout(ms: number, opt_description?: string): Promise; + + /** + * Schedules a task that shall wait for a condition to hold. Each condition + * function may return any value, but it will always be evaluated as a boolean. + * + *

Condition functions may schedule sub-tasks with this instance, however, + * their execution time will be factored into whether a wait has timed out. + * + *

In the event a condition returns a Promise, the polling loop will wait for + * it to be resolved before evaluating whether the condition has been satisfied. + * The resolution time for a promise is factored into whether a wait has timed + * out. + * + *

If the condition function throws, or returns a rejected promise, the + * wait task will fail. + * + * @param {!Function} condition The condition function to poll. + * @param {number} timeout How long to wait, in milliseconds, for the condition + * to hold before timing out. + * @param {string=} opt_message An optional error message to include if the + * wait times out; defaults to the empty string. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * condition has been satisified. The promise shall be rejected if the wait + * times out waiting for the condition. + */ + wait(condition: Function, timeout: number, opt_message?: string): Promise; + + /** + * Schedules a task that will wait for another promise to resolve. The resolved + * promise's value will be returned as the task result. + * @param {!webdriver.promise.Promise} promise The promise to wait on. + * @return {!webdriver.promise.Promise} A promise that will resolve when the + * task has completed. + */ + await(promise: Promise): Promise; + + //endregion + } + } + + module stacktrace { + /** + * Class representing one stack frame. + */ + class Frame { + /** + * @param {(string|undefined)} context Context object, empty in case of global + * functions or if the browser doesn't provide this information. + * @param {(string|undefined)} name Function name, empty in case of anonymous + * functions. + * @param {(string|undefined)} alias Alias of the function if available. For + * example the function name will be 'c' and the alias will be 'b' if the + * function is defined as a.b = function c() {};. + * @param {(string|undefined)} path File path or URL including line number and + * optionally column number separated by colons. + * @constructor + */ + constructor(context?: string, name?: string, alias?: string, path?: string); + + /** + * @return {string} The function name or empty string if the function is + * anonymous and the object field which it's assigned to is unknown. + */ + getName(): string; + + + /** + * @return {string} The url or empty string if it is unknown. + */ + getUrl(): string; + + + /** + * @return {number} The line number if known or -1 if it is unknown. + */ + getLine(): number; + + + /** + * @return {number} The column number if known and -1 if it is unknown. + */ + getColumn(): number; + + + /** + * @return {boolean} Whether the stack frame contains an anonymous function. + */ + isAnonymous(): boolean; + + + /** + * Converts this frame to its string representation using V8's stack trace + * format: http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi + * @return {string} The string representation of this frame. + * @override + */ + toString(): string; + } + + /** + * Stores a snapshot of the stack trace at the time this instance was created. + * The stack trace will always be adjusted to exclude this function call. + */ + class Snapshot { + /** + * @param {number=} opt_slice The number of frames to remove from the top of + * the generated stack trace. + * @constructor + */ + constructor(opt_slice?: number); + + /** + * @return {!Array.} The parsed stack trace. + */ + getStacktrace(): Frame[]; + } + + /** + * Formats an error's stack trace. + * @param {!(Error|goog.testing.JsUnitException)} error The error to format. + * @return {!(Error|goog.testing.JsUnitException)} The formatted error. + */ + function format(error: any): any; + + /** + * Gets the native stack trace if available otherwise follows the call chain. + * The generated trace will exclude all frames up to and including the call to + * this function. + * @return {!Array.} The frames of the stack trace. + */ + function get(): Frame[]; + + /** + * Whether the current browser supports stack traces. + * + * @type {boolean} + * @const + */ + var BROWSER_SUPPORTED: boolean; + } + + module until { + /** + * Defines a condition to + */ + class Condition { + /** + * @param {string} message A descriptive error message. Should complete the + * sentence "Waiting [...]" + * @param {function(!webdriver.WebDriver): OUT} fn The condition function to + * evaluate on each iteration of the wait loop. + * @constructor + */ + constructor(message: string, fn: (webdriver: WebDriver) => any); + + /** @return {string} A description of this condition. */ + description(): string; + + /** @type {function(!webdriver.WebDriver): OUT} */ + fn(webdriver: WebDriver): any; + } + + /** + * Creates a condition that will wait until the input driver is able to switch + * to the designated frame. The target frame may be specified as: + *

    + *
  1. A numeric index into {@code window.frames} for the currently selected + * frame. + *
  2. A {@link webdriver.WebElement}, which must reference a FRAME or IFRAME + * element on the current page. + *
  3. A locator which may be used to first locate a FRAME or IFRAME on the + * current page before attempting to switch to it. + *
+ * + *

Upon successful resolution of this condition, the driver will be left + * focused on the new frame. + * + * @param {!(number|webdriver.WebElement| + * webdriver.Locator|webdriver.By.Hash| + * function(!webdriver.WebDriver): !webdriver.WebElement)} frame + * The frame identifier. + * @return {!until.Condition.} A new condition. + */ + function ableToSwitchToFrame(frame: number): Condition; + function ableToSwitchToFrame(frame: IWebElement): Condition; + function ableToSwitchToFrame(frame: Locator): Condition; + function ableToSwitchToFrame(frame: (webdriver: WebDriver) => IWebElement): Condition; + function ableToSwitchToFrame(frame: any): Condition; + + /** + * Creates a condition that waits for an alert to be opened. Upon success, the + * returned promise will be fulfilled with the handle for the opened alert. + * + * @return {!until.Condition.} The new condition. + */ + function alertIsPresent(): Condition; + + /** + * Creates a condition that will wait for the given element to be disabled. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isEnabled + */ + function elementIsDisabled(element: IWebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be enabled. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isEnabled + */ + function elementIsEnabled(element: IWebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be deselected. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isSelected + */ + function elementIsNotSelected(element: IWebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be in the DOM, + * yet not visible to the user. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isDisplayed + */ + function elementIsNotVisible(element: IWebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be selected. + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isSelected + */ + function elementIsSelected(element: IWebElement): Condition; + + /** + * Creates a condition that will wait for the given element to become visible. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isDisplayed + */ + function elementIsVisible(element: IWebElement): Condition; + + /** + * Creates a condition that will loop until an element is + * {@link webdriver.WebDriver#findElement found} with the given locator. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator + * to use. + * @return {!until.Condition.} The new condition. + */ + function elementLocated(locator: Locator): Condition; + function elementLocated(locator: any): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link webdriver.WebDriver#getText visible text} to contain the given + * substring. + * + * @param {!webdriver.WebElement} element The element to test. + * @param {string} substr The substring to search for. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#getText + */ + function elementTextContains(element: IWebElement, substr: string): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link webdriver.WebDriver#getText visible text} to match the given + * {@code text} exactly. + * + * @param {!webdriver.WebElement} element The element to test. + * @param {string} text The expected text. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#getText + */ + function elementTextIs(element: IWebElement, text: string): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link webdriver.WebDriver#getText visible text} to match a regular + * expression. + * + * @param {!webdriver.WebElement} element The element to test. + * @param {!RegExp} regex The regular expression to test against. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#getText + */ + function elementTextMatches(element: IWebElement, regex: RegExp): Condition; + + /** + * Creates a condition that will loop until at least one element is + * {@link webdriver.WebDriver#findElement found} with the given locator. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator + * to use. + * @return {!until.Condition.>} The new + * condition. + */ + function elementsLocated(locator: Locator): Condition; + function elementsLocated(locator: any): Condition; + + /** + * Creates a condition that will wait for the given element to become stale. An + * element is considered stale once it is removed from the DOM, or a new page + * has loaded. + * + * @param {!webdriver.WebElement} element The element that should become stale. + * @return {!until.Condition.} The new condition. + */ + function stalenessOf(element: IWebElement): Condition; + + /** + * Creates a condition that will wait for the current page's title to contain + * the given substring. + * + * @param {string} substr The substring that should be present in the page + * title. + * @return {!until.Condition.} The new condition. + */ + function titleContains(substr: string): Condition; + + /** + * Creates a condition that will wait for the current page's title to match the + * given value. + * + * @param {string} title The expected page title. + * @return {!until.Condition.} The new condition. + */ + function titleIs(title: string): Condition; + + /** + * Creates a condition that will wait for the current page's title to match the + * given regular expression. + * + * @param {!RegExp} regex The regular expression to test against. + * @return {!until.Condition.} The new condition. + */ + function titleMatches(regex: RegExp): Condition; + } + + interface ILocation { + x: number; + y: number; + } + + interface ISize { + width: number; + height: number; + } + + /** + * Enumeration of the buttons used in the advanced interactions API. + * NOTE: A TypeScript enum was not used so that this class could be extended in Protractor. + * @enum {number} + */ + interface IButton { + LEFT: number; + MIDDLE: number; + RIGHT: number; + } + + var Button: IButton + + /** + * Representations of pressable keys that aren't text. These are stored in + * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to + * http://www.google.com.au/search?&q=unicode+pua&btnG=Search + * + * @enum {string} + */ + interface IKey { + NULL: string; + CANCEL: string; // ^break + HELP: string; + BACK_SPACE: string; + TAB: string; + CLEAR: string; + RETURN: string; + ENTER: string; + SHIFT: string; + CONTROL: string; + ALT: string; + PAUSE: string; + ESCAPE: string; + SPACE: string; + PAGE_UP: string; + PAGE_DOWN: string; + END: string; + HOME: string; + ARROW_LEFT: string; + LEFT: string; + ARROW_UP: string; + UP: string; + ARROW_RIGHT: string; + RIGHT: string; + ARROW_DOWN: string; + DOWN: string; + INSERT: string; + DELETE: string; + SEMICOLON: string; + EQUALS: string; + + NUMPAD0: string; // number pad keys + NUMPAD1: string; + NUMPAD2: string; + NUMPAD3: string; + NUMPAD4: string; + NUMPAD5: string; + NUMPAD6: string; + NUMPAD7: string; + NUMPAD8: string; + NUMPAD9: string; + MULTIPLY: string; + ADD: string; + SEPARATOR: string; + SUBTRACT: string; + DECIMAL: string; + DIVIDE: string; + + F1: string; // function keys + F2: string; + F3: string; + F4: string; + F5: string; + F6: string; + F7: string; + F8: string; + F9: string; + F10: string; + F11: string; + F12: string; + + COMMAND: string; // Apple command key + META: string; // alias for Windows key + + /** + * Simulate pressing many keys at once in a "chord". Takes a sequence of + * {@link webdriver.Key}s or strings, appends each of the values to a string, + * and adds the chord termination key ({@link webdriver.Key.NULL}) and returns + * the resultant string. + * + * Note: when the low-level webdriver key handlers see Keys.NULL, active + * modifier keys (CTRL/ALT/SHIFT/etc) release via a keyup event. + * + * @param {...string} var_args The key sequence to concatenate. + * @return {string} The null-terminated key sequence. + * @see http://code.google.com/p/webdriver/issues/detail?id=79 + */ + chord: (...var_args: string[]) => string; + } + + var Key: IKey; + + /** + * Class for defining sequences of complex user interactions. Each sequence + * will not be executed until {@link #perform} is called. + * + *

Example:


+     *   new webdriver.ActionSequence(driver).
+     *       keyDown(webdriver.Key.SHIFT).
+     *       click(element1).
+     *       click(element2).
+     *       dragAndDrop(element3, element4).
+     *       keyUp(webdriver.Key.SHIFT).
+     *       perform();
+     * 
+ * + */ + class ActionSequence { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The driver instance to use. + * @constructor + */ + constructor(driver: WebDriver); + + //endregion + + //region Methods + + /** + * Executes this action sequence. + * @return {!webdriver.promise.Promise} A promise that will be resolved once + * this sequence has completed. + */ + perform(): webdriver.promise.Promise; + + /** + * Moves the mouse. The location to move to may be specified in terms of the + * mouse's current location, an offset relative to the top-left corner of an + * element, or an element (in which case the middle of the element is used). + * @param {(!webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, as either another WebElement or an offset in pixels. + * @param {{x: number, y: number}=} opt_offset An optional offset, in pixels. + * Defaults to (0, 0). + * @return {!webdriver.ActionSequence} A self reference. + */ + mouseMove(location: IWebElement, opt_offset?: ILocation): ActionSequence; + mouseMove(location: ILocation): ActionSequence; + + /** + * Presses a mouse button. The mouse button will not be released until + * {@link #mouseUp} is called, regardless of whether that call is made in this + * sequence or another. The behavior for out-of-order events (e.g. mouseDown, + * click) is undefined. + * + *

If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + *

sequence.mouseMove(element).mouseDown()
+ * + *

Warning: this method currently only supports the left mouse button. See + * http://code.google.com/p/selenium/issues/detail?id=4047 + * + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * button is specified. + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!webdriver.ActionSequence} A self reference. + */ + mouseDown(opt_elementOrButton?: IWebElement, opt_button?: number): ActionSequence; + mouseDown(opt_elementOrButton?: number): ActionSequence; + + /** + * Releases a mouse button. Behavior is undefined for calling this function + * without a previous call to {@link #mouseDown}. + * + *

If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + *

sequence.mouseMove(element).mouseUp()
+ * + *

Warning: this method currently only supports the left mouse button. See + * http://code.google.com/p/selenium/issues/detail?id=4047 + * + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * button is specified. + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!webdriver.ActionSequence} A self reference. + */ + mouseUp(opt_elementOrButton?: IWebElement, opt_button?: number): ActionSequence; + mouseUp(opt_elementOrButton?: number): ActionSequence; + + /** + * Convenience function for performing a "drag and drop" manuever. The target + * element may be moved to the location of another element, or by an offset (in + * pixels). + * @param {!webdriver.WebElement} element The element to drag. + * @param {(!webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, either as another WebElement or an offset in pixels. + * @return {!webdriver.ActionSequence} A self reference. + */ + dragAndDrop(element: IWebElement, location: IWebElement): ActionSequence; + dragAndDrop(element: IWebElement, location: ILocation): ActionSequence; + + /** + * Clicks a mouse button. + * + *

If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + *

sequence.mouseMove(element).click()
+ * + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * button is specified. + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!webdriver.ActionSequence} A self reference. + */ + click(opt_elementOrButton?: IWebElement, opt_button?: number): ActionSequence; + click(opt_elementOrButton?: number): ActionSequence; + + /** + * Double-clicks a mouse button. + * + *

If an element is provided, the mouse will first be moved to the center of + * that element. This is equivalent to: + *

sequence.mouseMove(element).doubleClick()
+ * + *

Warning: this method currently only supports the left mouse button. See + * http://code.google.com/p/selenium/issues/detail?id=4047 + * + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * button is specified. + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!webdriver.ActionSequence} A self reference. + */ + doubleClick(opt_elementOrButton?: IWebElement, opt_button?: number): ActionSequence; + doubleClick(opt_elementOrButton?: number): ActionSequence; + + /** + * Performs a modifier key press. The modifier key is not released + * until {@link #keyUp} or {@link #sendKeys} is called. The key press will be + * targetted at the currently focused element. + * @param {!webdriver.Key} key The modifier key to push. Must be one of + * {ALT, CONTROL, SHIFT, COMMAND, META}. + * @return {!webdriver.ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + keyDown(key: string): ActionSequence; + + /** + * Performs a modifier key release. The release is targetted at the currently + * focused element. + * @param {!webdriver.Key} key The modifier key to release. Must be one of + * {ALT, CONTROL, SHIFT, COMMAND, META}. + * @return {!webdriver.ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + keyUp(key: string): ActionSequence; + + /** + * Simulates typing multiple keys. Each modifier key encountered in the + * sequence will not be released until it is encountered again. All key events + * will be targetted at the currently focused element. + * @param {...(string|!webdriver.Key|!Array.<(string|!webdriver.Key)>)} var_args + * The keys to type. + * @return {!webdriver.ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + sendKeys(...var_args: any[]): ActionSequence; + + //endregion + } + + /** + * Represents a modal dialog such as {@code alert}, {@code confirm}, or + * {@code prompt}. Provides functions to retrieve the message displayed with + * the alert, accept or dismiss the alert, and set the response text (in the + * case of {@code prompt}). + */ + interface Alert { + + //region Methods + + /** + * Retrieves the message text displayed with this alert. For instance, if the + * alert were opened with alert("hello"), then this would return "hello". + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * text displayed with this alert. + */ + getText(): webdriver.promise.Promise; + + /** + * Accepts this alert. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * this command has completed. + */ + accept(): webdriver.promise.Promise; + + /** + * Dismisses this alert. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * this command has completed. + */ + dismiss(): webdriver.promise.Promise; + + /** + * Sets the response text on this alert. This command will return an error if + * the underlying alert does not support response text (e.g. window.alert and + * window.confirm). + * @param {string} text The text to set. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * this command has completed. + */ + sendKeys(text: string): webdriver.promise.Promise; + + //endregion + + } + + /** + * AlertPromise is a promise that will be fulfilled with an Alert. This promise + * serves as a forward proxy on an Alert, allowing calls to be scheduled + * directly on this instance before the underlying Alert has been fulfilled. In + * other words, the following two statements are equivalent: + *


+     *     driver.switchTo().alert().dismiss();
+     *     driver.switchTo().alert().then(function(alert) {
+     *       return alert.dismiss();
+     *     });
+     * 
+ * + * @param {!webdriver.WebDriver} driver The driver controlling the browser this + * alert is attached to. + * @param {!webdriver.promise.Thenable.} alert A thenable + * that will be fulfilled with the promised alert. + * @constructor + * @extends {webdriver.Alert} + * @implements {webdriver.promise.Thenable.} + * @final + */ + interface AlertPromise extends Alert, webdriver.promise.IThenable { + } + + /** + * An error returned to indicate that there is an unhandled modal dialog on the + * current page. + * @extends {bot.Error} + */ + interface UnhandledAlertError extends webdriver.error.Error { + //region Methods + + /** + * @return {string} The text displayed with the unhandled alert. + */ + getAlertText(): string; + + /** + * @return {!webdriver.Alert} The open alert. + * @deprecated Use {@link #getAlertText}. This method will be removed in + * 2.45.0. + */ + getAlert(): Alert; + + + //endregion + } + + /** + * Recognized browser names. + * @enum {string} + */ + interface IBrowser { + ANDROID: string; + CHROME: string; + FIREFOX: string; + INTERNET_EXPLORER: string; + IPAD: string; + IPHONE: string; + OPERA: string; + PHANTOM_JS: string; + SAFARI: string; + HTMLUNIT: string; + } + + var Browser: IBrowser + + interface ProxyConfig { + proxyType: string; + proxyAutoconfigUrl?: string; + ftpProxy?: string; + httpProxy?: string; + sslProxy?: string; + noProxy?: string; + } + + class Builder { + + //region Constructors + + /** + * @constructor + */ + constructor(); + + //endregion + + //region Methods + + /** + * Creates a new WebDriver client based on this builder's current + * configuration. + * + * @return {!webdriver.WebDriver} A new WebDriver instance. + * @throws {Error} If the current configuration is invalid. + */ + build(): WebDriver; + + /** + * Configures the target browser for clients created by this instance. + * Any calls to {@link #withCapabilities} after this function will + * overwrite these settings. + * + *

You may also define the target browser using the {@code SELENIUM_BROWSER} + * environment variable. If set, this environment variable should be of the + * form {@code browser[:[version][:platform]]}. + * + * @param {(string|webdriver.Browser)} name The name of the target browser; + * common defaults are available on the {@link webdriver.Browser} enum. + * @param {string=} opt_version A desired version; may be omitted if any + * version should be used. + * @param {string=} opt_platform The desired platform; may be omitted if any + * version may be used. + * @return {!Builder} A self reference. + */ + forBrowser(name: string, opt_version?: string, opt_platform?: string): Builder; + + /** + * Returns the base set of capabilities this instance is currently configured + * to use. + * @return {!webdriver.Capabilities} The current capabilities for this builder. + */ + getCapabilities(): Capabilities; + + /** + * @return {string} The URL of the WebDriver server this instance is configured + * to use. + */ + getServerUrl(): string; + + /** + * Sets the default action to take with an unexpected alert before returning + * an error. + * @param {string} beahvior The desired behavior; should be "accept", "dismiss", + * or "ignore". Defaults to "dismiss". + * @return {!Builder} A self reference. + */ + setAlertBehavior(behavior: string): Builder; + + /** + * Sets Chrome-specific options for drivers created by this builder. Any + * logging or proxy settings defined on the given options will take precedence + * over those set through {@link #setLoggingPrefs} and {@link #setProxy}, + * respectively. + * + * @param {!chrome.Options} options The ChromeDriver options to use. + * @return {!Builder} A self reference. + */ + setChromeOptions(options: chrome.Options): Builder; + + /** + * Sets the control flow that created drivers should execute actions in. If + * the flow is never set, or is set to {@code null}, it will use the active + * flow at the time {@link #build()} is called. + * @param {webdriver.promise.ControlFlow} flow The control flow to use, or + * {@code null} to + * @return {!Builder} A self reference. + */ + setControlFlow(flow: webdriver.promise.ControlFlow): Builder; + + /** + * Sets whether native events should be used. + * @param {boolean} enabled Whether to enable native events. + * @return {!Builder} A self reference. + */ + setEnableNativeEvents(enabled: boolean): Builder; + + /** + * Sets Firefox-specific options for drivers created by this builder. Any + * logging or proxy settings defined on the given options will take precedence + * over those set through {@link #setLoggingPrefs} and {@link #setProxy}, + * respectively. + * + * @param {!firefox.Options} options The FirefoxDriver options to use. + * @return {!Builder} A self reference. + */ + setFirefoxOptions(options: firefox.Options): Builder; + + /** + * Sets the logging preferences for the created session. Preferences may be + * changed by repeated calls, or by calling {@link #withCapabilities}. + * @param {!(webdriver.logging.Preferences|Object.)} prefs The + * desired logging preferences. + * @return {!Builder} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Builder; + setLoggingPrefs(prefs: { [key: string]: string }): Builder; + + /** + * Sets the proxy configuration to use for WebDriver clients created by this + * builder. Any calls to {@link #withCapabilities} after this function will + * overwrite these settings. + * @param {!webdriver.ProxyConfig} config The configuration to use. + * @return {!Builder} A self reference. + */ + setProxy(config: ProxyConfig): Builder; + + /** + * Sets how elements should be scrolled into view for interaction. + * @param {number} behavior The desired scroll behavior: either 0 to align with + * the top of the viewport or 1 to align with the bottom. + * @return {!Builder} A self reference. + */ + setScrollBehavior(behavior: number): Builder; + + /** + * Sets the URL of a remote WebDriver server to use. Once a remote URL has been + * specified, the builder direct all new clients to that server. If this method + * is never called, the Builder will attempt to create all clients locally. + * + *

As an alternative to this method, you may also set the + * {@code SELENIUM_REMOTE_URL} environment variable. + * + * @param {string} url The URL of a remote server to use. + * @return {!Builder} A self reference. + */ + usingServer(url: string): Builder; + + /** + * Sets the desired capabilities when requesting a new session. This will + * overwrite any previously set capabilities. + * @param {!(Object|webdriver.Capabilities)} capabilities The desired + * capabilities for a new session. + * @return {!Builder} A self reference. + */ + withCapabilities(capabilities: Capabilities): Builder; + withCapabilities(capabilities: any): Builder; + + //endregion + } + + /** + * Common webdriver capability keys. + * @enum {string} + */ + interface ICapability { + + /** + * Indicates whether a driver should accept all SSL certs by default. This + * capability only applies when requesting a new session. To query whether + * a driver can handle insecure SSL certs, see + * {@link webdriver.Capability.SECURE_SSL}. + */ + ACCEPT_SSL_CERTS: string; + + + /** + * The browser name. Common browser names are defined in the + * {@link webdriver.Browser} enum. + */ + BROWSER_NAME: string; + + /** + * Defines how elements should be scrolled into the viewport for interaction. + * This capability will be set to zero (0) if elements are aligned with the + * top of the viewport, or one (1) if aligned with the bottom. The default + * behavior is to align with the top of the viewport. + */ + ELEMENT_SCROLL_BEHAVIOR: string; + + /** + * Whether the driver is capable of handling modal alerts (e.g. alert, + * confirm, prompt). To define how a driver should handle alerts, + * use {@link webdriver.Capability.UNEXPECTED_ALERT_BEHAVIOR}. + */ + HANDLES_ALERTS: string; + + /** + * Key for the logging driver logging preferences. + */ + LOGGING_PREFS: string; + + /** + * Whether this session generates native events when simulating user input. + */ + NATIVE_EVENTS: string; + + /** + * Describes the platform the browser is running on. Will be one of + * ANDROID, IOS, LINUX, MAC, UNIX, or WINDOWS. When requesting a + * session, ANY may be used to indicate no platform preference (this is + * semantically equivalent to omitting the platform capability). + */ + PLATFORM: string; + + /** + * Describes the proxy configuration to use for a new WebDriver session. + */ + PROXY: string; + + /** Whether the driver supports changing the brower's orientation. */ + ROTATABLE: string; + + /** + * Whether a driver is only capable of handling secure SSL certs. To request + * that a driver accept insecure SSL certs by default, use + * {@link webdriver.Capability.ACCEPT_SSL_CERTS}. + */ + SECURE_SSL: string; + + /** Whether the driver supports manipulating the app cache. */ + SUPPORTS_APPLICATION_CACHE: string; + + /** Whether the driver supports locating elements with CSS selectors. */ + SUPPORTS_CSS_SELECTORS: string; + + /** Whether the browser supports JavaScript. */ + SUPPORTS_JAVASCRIPT: string; + + /** Whether the driver supports controlling the browser's location info. */ + SUPPORTS_LOCATION_CONTEXT: string; + + /** Whether the driver supports taking screenshots. */ + TAKES_SCREENSHOT: string; + + /** + * Defines how the driver should handle unexpected alerts. The value should + * be one of "accept", "dismiss", or "ignore. + */ + UNEXPECTED_ALERT_BEHAVIOR: string; + + /** Defines the browser version. */ + VERSION: string; + } + + var Capability: ICapability; + + class Capabilities { + //region Constructors + + /** + * @param {(webdriver.Capabilities|Object)=} opt_other Another set of + * capabilities to merge into this instance. + * @constructor + */ + constructor(opt_other?: Capabilities); + constructor(opt_other?: any); + + //endregion + + //region Methods + + /** @return {!Object} The JSON representation of this instance. */ + toJSON(): any; + + /** + * Merges another set of capabilities into this instance. Any duplicates in + * the provided set will override those already set on this instance. + * @param {!(webdriver.Capabilities|Object)} other The capabilities to + * merge into this instance. + * @return {!webdriver.Capabilities} A self reference. + */ + merge(other: Capabilities): Capabilities; + merge(other: any): Capabilities; + + /** + * @param {string} key The capability to set. + * @param {*} value The capability value. Capability values must be JSON + * serializable. Pass {@code null} to unset the capability. + * @return {!webdriver.Capabilities} A self reference. + */ + set(key: string, value: any): Capabilities; + + /** + * Sets the logging preferences. Preferences may be specified as a + * {@link webdriver.logging.Preferences} instance, or a as a map of log-type to + * log-level. + * @param {!(webdriver.logging.Preferences|Object.)} prefs The + * logging preferences. + * @return {!webdriver.Capabilities} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Capabilities; + setLoggingPrefs(prefs: { [key: string]: string }): Capabilities; + + + /** + * Sets the proxy configuration for this instance. + * @param {webdriver.ProxyConfig} proxy The desired proxy configuration. + * @return {!webdriver.Capabilities} A self reference. + */ + setProxy(proxy: ProxyConfig): Capabilities; + + + /** + * Sets whether native events should be used. + * @param {boolean} enabled Whether to enable native events. + * @return {!webdriver.Capabilities} A self reference. + */ + setEnableNativeEvents(enabled: boolean): Capabilities; + + + /** + * Sets how elements should be scrolled into view for interaction. + * @param {number} behavior The desired scroll behavior: either 0 to align with + * the top of the viewport or 1 to align with the bottom. + * @return {!webdriver.Capabilities} A self reference. + */ + setScrollBehavior(behavior: number): Capabilities; + + /** + * Sets the default action to take with an unexpected alert before returning + * an error. + * @param {string} behavior The desired behavior; should be "accept", "dismiss", + * or "ignore". Defaults to "dismiss". + * @return {!webdriver.Capabilities} A self reference. + */ + setAlertBehavior(behavior: string): Capabilities; + + /** + * @param {string} key The capability to return. + * @return {*} The capability with the given key, or {@code null} if it has + * not been set. + */ + get(key: string): any; + + /** + * @param {string} key The capability to check. + * @return {boolean} Whether the specified capability is set. + */ + has(key: string): boolean; + + //endregion + + //region Static Methods + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Android. + */ + static android(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Chrome. + */ + static chrome(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Firefox. + */ + static firefox(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for + * Internet Explorer. + */ + static ie(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for iPad. + */ + static ipad(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for iPhone. + */ + static iphone(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Opera. + */ + static opera(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for + * PhantomJS. + */ + static phantomjs(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Safari. + */ + static safari(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for HTMLUnit. + */ + static htmlunit(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for HTMLUnit + * with enabled Javascript. + */ + static htmlunitwithjs(): Capabilities; + + //endregion + } + + /** + * An enumeration of valid command string. + */ + interface ICommandName { + GET_SERVER_STATUS: string; + + NEW_SESSION: string; + GET_SESSIONS: string; + DESCRIBE_SESSION: string; + + CLOSE: string; + QUIT: string; + + GET_CURRENT_URL: string; + GET: string; + GO_BACK: string; + GO_FORWARD: string; + REFRESH: string; + + ADD_COOKIE: string; + GET_COOKIE: string; + GET_ALL_COOKIES: string; + DELETE_COOKIE: string; + DELETE_ALL_COOKIES: string; + + GET_ACTIVE_ELEMENT: string; + FIND_ELEMENT: string; + FIND_ELEMENTS: string; + FIND_CHILD_ELEMENT: string; + FIND_CHILD_ELEMENTS: string; + + CLEAR_ELEMENT: string; + CLICK_ELEMENT: string; + SEND_KEYS_TO_ELEMENT: string; + SUBMIT_ELEMENT: string; + + GET_CURRENT_WINDOW_HANDLE: string; + GET_WINDOW_HANDLES: string; + GET_WINDOW_POSITION: string; + SET_WINDOW_POSITION: string; + GET_WINDOW_SIZE: string; + SET_WINDOW_SIZE: string; + MAXIMIZE_WINDOW: string; + + SWITCH_TO_WINDOW: string; + SWITCH_TO_FRAME: string; + GET_PAGE_SOURCE: string; + GET_TITLE: string; + + EXECUTE_SCRIPT: string; + EXECUTE_ASYNC_SCRIPT: string; + + GET_ELEMENT_TEXT: string; + GET_ELEMENT_TAG_NAME: string; + IS_ELEMENT_SELECTED: string; + IS_ELEMENT_ENABLED: string; + IS_ELEMENT_DISPLAYED: string; + GET_ELEMENT_LOCATION: string; + GET_ELEMENT_LOCATION_IN_VIEW: string; + GET_ELEMENT_SIZE: string; + GET_ELEMENT_ATTRIBUTE: string; + GET_ELEMENT_VALUE_OF_CSS_PROPERTY: string; + ELEMENT_EQUALS: string; + + SCREENSHOT: string; + IMPLICITLY_WAIT: string; + SET_SCRIPT_TIMEOUT: string; + SET_TIMEOUT: string; + + ACCEPT_ALERT: string; + DISMISS_ALERT: string; + GET_ALERT_TEXT: string; + SET_ALERT_TEXT: string; + + EXECUTE_SQL: string; + GET_LOCATION: string; + SET_LOCATION: string; + GET_APP_CACHE: string; + GET_APP_CACHE_STATUS: string; + CLEAR_APP_CACHE: string; + IS_BROWSER_ONLINE: string; + SET_BROWSER_ONLINE: string; + + GET_LOCAL_STORAGE_ITEM: string; + GET_LOCAL_STORAGE_KEYS: string; + SET_LOCAL_STORAGE_ITEM: string; + REMOVE_LOCAL_STORAGE_ITEM: string; + CLEAR_LOCAL_STORAGE: string; + GET_LOCAL_STORAGE_SIZE: string; + + GET_SESSION_STORAGE_ITEM: string; + GET_SESSION_STORAGE_KEYS: string; + SET_SESSION_STORAGE_ITEM: string; + REMOVE_SESSION_STORAGE_ITEM: string; + CLEAR_SESSION_STORAGE: string; + GET_SESSION_STORAGE_SIZE: string; + + SET_SCREEN_ORIENTATION: string; + GET_SCREEN_ORIENTATION: string; + + // These belong to the Advanced user interactions - an element is + // optional for these commands. + CLICK: string; + DOUBLE_CLICK: string; + MOUSE_DOWN: string; + MOUSE_UP: string; + MOVE_TO: string; + SEND_KEYS_TO_ACTIVE_ELEMENT: string; + + // These belong to the Advanced Touch API + TOUCH_SINGLE_TAP: string; + TOUCH_DOWN: string; + TOUCH_UP: string; + TOUCH_MOVE: string; + TOUCH_SCROLL: string; + TOUCH_DOUBLE_TAP: string; + TOUCH_LONG_PRESS: string; + TOUCH_FLICK: string; + + GET_AVAILABLE_LOG_TYPES: string; + GET_LOG: string; + GET_SESSION_LOGS: string; + } + + var CommandName: ICommandName; + + /** + * Describes a command to be executed by the WebDriverJS framework. + * @param {!webdriver.CommandName} name The name of this command. + * @constructor + */ + class Command { + //region Constructors + + /** + * @param {!webdriver.CommandName} name The name of this command. + * @constructor + */ + constructor(name: string); + + //endregion + + //region Methods + + /** + * @return {!webdriver.CommandName} This command's name. + */ + getName(): string; + + /** + * Sets a parameter to send with this command. + * @param {string} name The parameter name. + * @param {*} value The parameter value. + * @return {!webdriver.Command} A self reference. + */ + setParameter(name: string, value: any): Command; + + /** + * Sets the parameters for this command. + * @param {!Object.<*>} parameters The command parameters. + * @return {!webdriver.Command} A self reference. + */ + setParameters(parameters: any): Command; + + /** + * Returns a named command parameter. + * @param {string} key The parameter key to look up. + * @return {*} The parameter value, or undefined if it has not been set. + */ + getParameter(key: string): any; + + /** + * @return {!Object.<*>} The parameters to send with this command. + */ + getParameters(): any; + + //endregion + } + + /** + * Handles the execution of {@code webdriver.Command} objects. + */ + interface CommandExecutor { + /** + * Executes the given {@code command}. If there is an error executing the + * command, the provided callback will be invoked with the offending error. + * Otherwise, the callback will be invoked with a null Error and non-null + * {@link bot.response.ResponseObject} object. + * @param {!webdriver.Command} command The command to execute. + * @param {function(Error, !bot.response.ResponseObject=)} callback the function + * to invoke when the command response is ready. + */ + execute(command: Command, callback: (error: Error, responseObject: any) => any ): void; + } + + /** + * Object that can emit events for others to listen for. This is used instead + * of Closure's event system because it is much more light weight. The API is + * based on Node's EventEmitters. + */ + class EventEmitter { + //region Constructors + + /** + * @constructor + */ + constructor(); + + //endregion + + //region Methods + + /** + * Fires an event and calls all listeners. + * @param {string} type The type of event to emit. + * @param {...*} var_args Any arguments to pass to each listener. + */ + emit(type: string, ...var_args: any[]): void; + + /** + * Returns a mutable list of listeners for a specific type of event. + * @param {string} type The type of event to retrieve the listeners for. + * @return {!Array.<{fn: !Function, oneshot: boolean, + * scope: (Object|undefined)}>} The registered listeners for + * the given event type. + */ + listeners(type: string): Array<{fn: Function; oneshot: boolean; scope: any;}>; + + /** + * Registers a listener. + * @param {string} type The type of event to listen for. + * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!webdriver.EventEmitter} A self reference. + */ + addListener(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; + + /** + * Registers a one-time listener which will be called only the first time an + * event is emitted, after which it will be removed. + * @param {string} type The type of event to listen for. + * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!webdriver.EventEmitter} A self reference. + */ + once(type: string, listenerFn: any, opt_scope?: any): EventEmitter; + + /** + * An alias for {@code #addListener()}. + * @param {string} type The type of event to listen for. + * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!webdriver.EventEmitter} A self reference. + */ + on(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; + + /** + * Removes a previously registered event listener. + * @param {string} type The type of event to unregister. + * @param {!Function} listenerFn The handler function to remove. + * @return {!webdriver.EventEmitter} A self reference. + */ + removeListener(type: string, listenerFn: Function): EventEmitter; + + /** + * Removes all listeners for a specific type of event. If no event is + * specified, all listeners across all types will be removed. + * @param {string=} opt_type The type of event to remove listeners from. + * @return {!webdriver.EventEmitter} A self reference. + */ + removeAllListeners(opt_type?: string): EventEmitter; + + //endregion + } + + /** + * Interface for navigating back and forth in the browser history. + */ + interface WebDriverNavigation { + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: WebDriver): WebDriverNavigation; + + //endregion + + //region Methods + + /** + * Schedules a command to navigate to a new URL. + * @param {string} url The URL to navigate to. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * URL has been loaded. + */ + to(url: string): webdriver.promise.Promise; + + /** + * Schedules a command to move backwards in the browser history. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * navigation event has completed. + */ + back(): webdriver.promise.Promise; + + /** + * Schedules a command to move forwards in the browser history. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * navigation event has completed. + */ + forward(): webdriver.promise.Promise; + + /** + * Schedules a command to refresh the current page. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * navigation event has completed. + */ + refresh(): webdriver.promise.Promise; + + //endregion + } + + interface IWebDriverOptionsCookie { + name: string; + value: string; + path?: string; + domain?: string; + secure?: boolean; + expiry?: number; + } + + /** + * Provides methods for managing browser and driver state. + */ + interface WebDriverOptions { + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: webdriver.WebDriver): WebDriverOptions; + + //endregion + + //region Methods + + /** + * Schedules a command to add a cookie. + * @param {string} name The cookie name. + * @param {string} value The cookie value. + * @param {string=} opt_path The cookie path. + * @param {string=} opt_domain The cookie domain. + * @param {boolean=} opt_isSecure Whether the cookie is secure. + * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified as + * a number, should be in milliseconds since midnight, January 1, 1970 UTC. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * cookie has been added to the page. + */ + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number): webdriver.promise.Promise; + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: Date): webdriver.promise.Promise; + + /** + * Schedules a command to delete all cookies visible to the current page. + * @return {!webdriver.promise.Promise} A promise that will be resolved when all + * cookies have been deleted. + */ + deleteAllCookies(): webdriver.promise.Promise; + + /** + * Schedules a command to delete the cookie with the given name. This command is + * a no-op if there is no cookie with the given name visible to the current + * page. + * @param {string} name The name of the cookie to delete. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * cookie has been deleted. + */ + deleteCookie(name: string): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve all cookies visible to the current page. + * Each cookie will be returned as a JSON object as described by the WebDriver + * wire protocol. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * cookies visible to the current page. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object + */ + getCookies(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the cookie with the given name. Returns null + * if there is no such cookie. The cookie will be returned as a JSON object as + * described by the WebDriver wire protocol. + * @param {string} name The name of the cookie to retrieve. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * named cookie, or {@code null} if there is no such cookie. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object + */ + getCookie(name: string): webdriver.promise.Promise; + + /** + * @return {!webdriver.WebDriver.Logs} The interface for managing driver + * logs. + */ + logs(): WebDriverLogs; + + /** + * @return {!webdriver.WebDriver.Timeouts} The interface for managing driver + * timeouts. + */ + timeouts(): WebDriverTimeouts; + + /** + * @return {!webdriver.WebDriver.Window} The interface for managing the + * current window. + */ + window(): WebDriverWindow; + + //endregion + } + + /** + * An interface for managing timeout behavior for WebDriver instances. + */ + interface WebDriverTimeouts { + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: WebDriver): WebDriverTimeouts; + + //endregion + + //region Methods + + /** + * Specifies the amount of time the driver should wait when searching for an + * element if it is not immediately present. + *

+ * When searching for a single element, the driver should poll the page + * until the element has been found, or this timeout expires before failing + * with a {@code bot.ErrorCode.NO_SUCH_ELEMENT} error. When searching + * for multiple elements, the driver should poll the page until at least one + * element has been found or this timeout has expired. + *

+ * Setting the wait timeout to 0 (its default value), disables implicit + * waiting. + *

+ * Increasing the implicit wait timeout should be used judiciously as it + * will have an adverse effect on test run time, especially when used with + * slower location strategies like XPath. + * + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * implicit wait timeout has been set. + */ + implicitlyWait(ms: number): webdriver.promise.Promise; + + /** + * Sets the amount of time to wait, in milliseconds, for an asynchronous script + * to finish execution before returning an error. If the timeout is less than or + * equal to 0, the script will be allowed to run indefinitely. + * + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * script timeout has been set. + */ + setScriptTimeout(ms: number): webdriver.promise.Promise; + + /** + * Sets the amount of time to wait for a page load to complete before returning + * an error. If the timeout is negative, page loads may be indefinite. + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the timeout has been set. + */ + pageLoadTimeout(ms: number): webdriver.promise.Promise; + + //endregion + } + + /** + * An interface for managing the current window. + */ + interface WebDriverWindow { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: WebDriver): WebDriverWindow; + + //endregion + + //region Methods + + /** + * Retrieves the window's current position, relative to the top left corner of + * the screen. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * window's position in the form of a {x:number, y:number} object literal. + */ + getPosition(): webdriver.promise.Promise; + + /** + * Repositions the current window. + * @param {number} x The desired horizontal position, relative to the left side + * of the screen. + * @param {number} y The desired vertical position, relative to the top of the + * of the screen. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * command has completed. + */ + setPosition(x: number, y: number): webdriver.promise.Promise; + + /** + * Retrieves the window's current size. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * window's size in the form of a {width:number, height:number} object + * literal. + */ + getSize(): webdriver.promise.Promise; + + /** + * Resizes the current window. + * @param {number} width The desired window width. + * @param {number} height The desired window height. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * command has completed. + */ + setSize(width: number, height: number): webdriver.promise.Promise; + + /** + * Maximizes the current window. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * command has completed. + */ + maximize(): webdriver.promise.Promise; + + //endregion + } + + /** + * Interface for managing WebDriver log records. + */ + interface WebDriverLogs { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: WebDriver): WebDriverLogs; + + //endregion + + //region + + /** + * Fetches available log entries for the given type. + * + *

Note that log buffers are reset after each call, meaning that + * available log entries correspond to those entries not yet returned for a + * given log type. In practice, this means that this call will return the + * available log entries since the last call, or from the start of the + * session. + * + * @param {!webdriver.logging.Type} type The desired log type. + * @return {!webdriver.promise.Promise.>} A + * promise that will resolve to a list of log entries for the specified + * type. + */ + get(type: string): webdriver.promise.Promise; + + /** + * Retrieves the log types available to this driver. + * @return {!webdriver.promise.Promise.>} A + * promise that will resolve to a list of available log types. + */ + getAvailableLogTypes(): webdriver.promise.Promise; + + //endregion + } + + /** + * An interface for changing the focus of the driver to another frame or window. + */ + interface WebDriverTargetLocator { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: WebDriver): WebDriverTargetLocator; + + //endregion + + //region Methods + + /** + * Schedules a command retrieve the {@code document.activeElement} element on + * the current document, or {@code document.body} if activeElement is not + * available. + * @return {!webdriver.WebElement} The active element. + */ + activeElement(): WebElementPromise; + + /** + * Schedules a command to switch focus of all future commands to the first frame + * on the page. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * driver has changed focus to the default content. + */ + defaultContent(): webdriver.promise.Promise; + + /** + * Schedules a command to switch the focus of all future commands to another + * frame on the page. + *

+ * If the frame is specified by a number, the command will switch to the frame + * by its (zero-based) index into the {@code window.frames} collection. + *

+ * If the frame is specified by a string, the command will select the frame by + * its name or ID. To select sub-frames, simply separate the frame names/IDs by + * dots. As an example, "main.child" will select the frame with the name "main" + * and then its child "child". + *

+ * If the specified frame can not be found, the deferred result will errback + * with a {@code bot.ErrorCode.NO_SUCH_FRAME} error. + * @param {string|number} nameOrIndex The frame locator. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * driver has changed focus to the specified frame. + */ + frame(nameOrIndex: string): webdriver.promise.Promise; + frame(nameOrIndex: number): webdriver.promise.Promise; + + /** + * Schedules a command to switch the focus of all future commands to another + * window. Windows may be specified by their {@code window.name} attribute or + * by its handle (as returned by {@code webdriver.WebDriver#getWindowHandles}). + *

+ * If the specificed window can not be found, the deferred result will errback + * with a {@code bot.ErrorCode.NO_SUCH_WINDOW} error. + * @param {string} nameOrHandle The name or window handle of the window to + * switch focus to. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * driver has changed focus to the specified window. + */ + window(nameOrHandle: string): webdriver.promise.Promise; + + /** + * Schedules a command to change focus to the active alert dialog. This command + * will return a {@link bot.ErrorCode.NO_MODAL_DIALOG_OPEN} error if a modal + * dialog is not currently open. + * @return {!webdriver.Alert} The open alert. + */ + alert(): AlertPromise; + + //endregion + } + + /** + * Creates a new WebDriver client, which provides control over a browser. + * + * Every WebDriver command returns a {@code webdriver.promise.Promise} that + * represents the result of that command. Callbacks may be registered on this + * object to manipulate the command result or catch an expected error. Any + * commands scheduled with a callback are considered sub-commands and will + * execute before the next command in the current frame. For example: + * + * var message = []; + * driver.call(message.push, message, 'a').then(function() { + * driver.call(message.push, message, 'b'); + * }); + * driver.call(message.push, message, 'c'); + * driver.call(function() { + * alert('message is abc? ' + (message.join('') == 'abc')); + * }); + * + */ + class WebDriver { + //region Constructors + + /** + * @param {!(webdriver.Session|webdriver.promise.Promise)} session Either a + * known session or a promise that will be resolved to a session. + * @param {!webdriver.CommandExecutor} executor The executor to use when + * sending commands to the browser. + * @param {webdriver.promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + * @constructor + */ + constructor(session: Session, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); + constructor(session: webdriver.promise.Promise, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); + + //endregion + + //region Static Properties + + static Navigation: WebDriverNavigation; + static Options: WebDriverOptions; + static Timeouts: WebDriverTimeouts; + static Window: WebDriverWindow; + static Logs: WebDriverLogs; + static TargetLocator: WebDriverTargetLocator; + + //endregion + + //region StaticMethods + + /** + * Creates a new WebDriver client for an existing session. + * @param {!webdriver.CommandExecutor} executor Command executor to use when + * querying for session details. + * @param {string} sessionId ID of the session to attach to. + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver + * commands should execute under. Defaults to the + * {@link webdriver.promise.controlFlow() currently active} control flow. + * @return {!webdriver.WebDriver} A new client for the specified session. + */ + static attachToSession(executor: CommandExecutor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + + /** + * Creates a new WebDriver session. + * @param {!webdriver.CommandExecutor} executor The executor to create the new + * session with. + * @param {!webdriver.Capabilities} desiredCapabilities The desired + * capabilities for the new session. + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver + * commands should execute under, including the initial session creation. + * Defaults to the {@link webdriver.promise.controlFlow() currently active} + * control flow. + * @return {!webdriver.WebDriver} The driver for the newly created session. + */ + static createSession(executor: CommandExecutor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + + //endregion + + //region Methods + + /** + * @return {!webdriver.promise.ControlFlow} The control flow used by this + * instance. + */ + controlFlow(): webdriver.promise.ControlFlow; + + /** + * Schedules a {@code webdriver.Command} to be executed by this driver's + * {@code webdriver.CommandExecutor}. + * @param {!webdriver.Command} command The command to schedule. + * @param {string} description A description of the command for debugging. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the command result. + */ + schedule(command: Command, description: string): webdriver.promise.Promise; + + /** + * @return {!webdriver.promise.Promise} A promise for this client's session. + */ + getSession(): webdriver.promise.Promise; + + /** + * @return {!webdriver.promise.Promise} A promise that will resolve with the + * this instance's capabilities. + */ + getCapabilities(): webdriver.promise.Promise; + + /** + * Schedules a command to quit the current session. After calling quit, this + * instance will be invalidated and may no longer be used to issue commands + * against the browser. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the command has completed. + */ + quit(): webdriver.promise.Promise; + + /** + * Creates a new action sequence using this driver. The sequence will not be + * scheduled for execution until {@link webdriver.ActionSequence#perform} is + * called. Example: + *


+         *   driver.actions().
+         *       mouseDown(element1).
+         *       mouseMove(element2).
+         *       mouseUp().
+         *       perform();
+         * 
+ * @return {!webdriver.ActionSequence} A new action sequence for this instance. + */ + actions(): ActionSequence; + + /** + * Schedules a command to execute JavaScript in the context of the currently + * selected frame or window. The script fragment will be executed as the body + * of an anonymous function. If the script is provided as a function object, + * that function will be converted to a string for injection into the target + * window. + * + * Any arguments provided in addition to the script will be included as script + * arguments and may be referenced using the {@code arguments} object. + * Arguments may be a boolean, number, string, or {@code webdriver.WebElement}. + * Arrays and objects may also be used as script arguments as long as each item + * adheres to the types previously mentioned. + * + * The script may refer to any variables accessible from the current window. + * Furthermore, the script will execute in the window's context, thus + * {@code document} may be used to refer to the current document. Any local + * variables will not be available once the script has finished executing, + * though global variables will persist. + * + * If the script has a return value (i.e. if the script contains a return + * statement), then the following steps will be taken for resolving this + * functions return value: + *
    + *
  • For a HTML element, the value will resolve to a + * {@code webdriver.WebElement}
  • + *
  • Null and undefined return values will resolve to null
  • + *
  • Booleans, numbers, and strings will resolve as is
  • + *
  • Functions will resolve to their string representation
  • + *
  • For arrays and objects, each member item will be converted according to + * the rules above
  • + *
+ * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * scripts return value. + */ + executeScript(script: string, ...var_args: any[]): webdriver.promise.Promise; + executeScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to execute asynchronous JavaScript in the context of the + * currently selected frame or window. The script fragment will be executed as + * the body of an anonymous function. If the script is provided as a function + * object, that function will be converted to a string for injection into the + * target window. + * + * Any arguments provided in addition to the script will be included as script + * arguments and may be referenced using the {@code arguments} object. + * Arguments may be a boolean, number, string, or {@code webdriver.WebElement}. + * Arrays and objects may also be used as script arguments as long as each item + * adheres to the types previously mentioned. + * + * Unlike executing synchronous JavaScript with + * {@code webdriver.WebDriver.prototype.executeScript}, scripts executed with + * this function must explicitly signal they are finished by invoking the + * provided callback. This callback will always be injected into the + * executed function as the last argument, and thus may be referenced with + * {@code arguments[arguments.length - 1]}. The following steps will be taken + * for resolving this functions return value against the first argument to the + * script's callback function: + *
    + *
  • For a HTML element, the value will resolve to a + * {@code webdriver.WebElement}
  • + *
  • Null and undefined return values will resolve to null
  • + *
  • Booleans, numbers, and strings will resolve as is
  • + *
  • Functions will resolve to their string representation
  • + *
  • For arrays and objects, each member item will be converted according to + * the rules above
  • + *
+ * + * Example #1: Performing a sleep that is synchronized with the currently + * selected window: + *
+         * var start = new Date().getTime();
+         * driver.executeAsyncScript(
+         *     'window.setTimeout(arguments[arguments.length - 1], 500);').
+         *     then(function() {
+         *       console.log('Elapsed time: ' + (new Date().getTime() - start) + ' ms');
+         *     });
+         * 
+ * + * Example #2: Synchronizing a test with an AJAX application: + *
+         * var button = driver.findElement(By.id('compose-button'));
+         * button.click();
+         * driver.executeAsyncScript(
+         *     'var callback = arguments[arguments.length - 1];' +
+         *     'mailClient.getComposeWindowWidget().onload(callback);');
+         * driver.switchTo().frame('composeWidget');
+         * driver.findElement(By.id('to')).sendKEys('dog@example.com');
+         * 
+ * + * Example #3: Injecting a XMLHttpRequest and waiting for the result. In this + * example, the inject script is specified with a function literal. When using + * this format, the function is converted to a string for injection, so it + * should not reference any symbols not defined in the scope of the page under + * test. + *
+         * driver.executeAsyncScript(function() {
+         *   var callback = arguments[arguments.length - 1];
+         *   var xhr = new XMLHttpRequest();
+         *   xhr.open("GET", "/resource/data.json", true);
+         *   xhr.onreadystatechange = function() {
+         *     if (xhr.readyState == 4) {
+         *       callback(xhr.resposneText);
+         *     }
+         *   }
+         *   xhr.send('');
+         * }).then(function(str) {
+         *   console.log(JSON.parse(str)['food']);
+         * });
+         * 
+ * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * scripts return value. + */ + executeAsyncScript(script: string, ...var_args: any[]): webdriver.promise.Promise; + executeAsyncScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to execute a custom function. + * @param {!Function} fn The function to execute. + * @param {Object=} opt_scope The object in whose scope to execute the function. + * @param {...*} var_args Any arguments to pass to the function. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * function's result. + */ + call(fn: Function, opt_scope?: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to wait for a condition to hold, as defined by some + * user supplied function. If any errors occur while evaluating the wait, they + * will be allowed to propagate. + * + *

In the event a condition returns a {@link webdriver.promise.Promise}, the + * polling loop will wait for it to be resolved and use the resolved value for + * evaluating whether the condition has been satisfied. The resolution time for + * a promise is factored into whether a wait has timed out. + * + * @param {!(webdriver.until.Condition.| + * function(!webdriver.WebDriver): T)} condition Either a condition + * object, or a function to evaluate as a condition. + * @param {number} timeout How long to wait for the condition to be true. + * @param {string=} opt_message An optional message to use if the wait times + * out. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the first truthy value returned by the condition function, or + * rejected if the condition times out. + * @template T + */ + wait(condition: webdriver.until.Condition, timeout: number, opt_message?: string): webdriver.promise.Promise; + wait(condition: (webdriver: WebDriver) => any, timeout: number, opt_message?: string): webdriver.promise.Promise; + + /** + * Schedules a command to make the driver sleep for the given amount of time. + * @param {number} ms The amount of time, in milliseconds, to sleep. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * sleep has finished. + */ + sleep(ms: number): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve they current window handle. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * current window handle. + */ + getWindowHandle(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the current list of available window handles. + * @return {!webdriver.promise.Promise} A promise that will be resolved with an + * array of window handles. + */ + getAllWindowHandles(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the current page's source. The page source + * returned is a representation of the underlying DOM: do not expect it to be + * formatted or escaped in the same way as the response sent from the web + * server. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * current page source. + */ + getPageSource(): webdriver.promise.Promise; + + /** + * Schedules a command to close the current window. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * this command has completed. + */ + close(): webdriver.promise.Promise; + + /** + * Schedules a command to navigate to the given URL. + * @param {string} url The fully qualified URL to open. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * document has finished loading. + */ + get(url: string): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the URL of the current page. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * current URL. + */ + getCurrentUrl(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the current page's title. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * current page's title. + */ + getTitle(): webdriver.promise.Promise; + + /** + * Schedule a command to find an element on the page. If the element cannot be + * found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned + * by the driver. Unlike other commands, this error cannot be suppressed. In + * other words, scheduling a command to find an element doubles as an assert + * that the element is present on the page. To test whether an element is + * present on the page, use {@code #isElementPresent} instead. + * + *

The search criteria for find an element may either be a + * {@code webdriver.Locator} object, or a simple JSON object whose sole key + * is one of the accepted locator strategies, as defined by + * {@code webdriver.Locator.Strategy}. For example, the following two statements + * are equivalent: + *

+         * var e1 = driver.findElement(By.id('foo'));
+         * var e2 = driver.findElement({id:'foo'});
+         * 
+ * + *

When running in the browser, a WebDriver cannot manipulate DOM elements + * directly; it may do so only through a {@link webdriver.WebElement} reference. + * This function may be used to generate a WebElement from a DOM element. A + * reference to the DOM element will be stored in a known location and this + * driver will attempt to retrieve it through {@link #executeScript}. If the + * element cannot be found (eg, it belongs to a different document than the + * one this instance is currently focused on), a + * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. + * + * @param {!(webdriver.Locator|Object.|Element)} locatorOrElement The + * locator strategy to use when searching for the element, or the actual + * DOM element to be located by the server. + * @param {...} var_args Arguments to pass to {@code #executeScript} if using a + * JavaScript locator. Otherwise ignored. + * @return {!webdriver.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locatorOrElement: Locator, ...var_args: any[]): WebElementPromise; + findElement(locatorOrElement: any, ...var_args: any[]): WebElementPromise; + + /** + * Schedules a command to test if an element is present on the page. + * + *

If given a DOM element, this function will check if it belongs to the + * document the driver is currently focused on. Otherwise, the function will + * test if at least one element can be found with the given search criteria. + * + * @param {!(webdriver.Locator|Object.|Element)} locatorOrElement The + * locator strategy to use when searching for the element, or the actual + * DOM element to be located by the server. + * @param {...} var_args Arguments to pass to {@code #executeScript} if using a + * JavaScript locator. Otherwise ignored. + * @return {!webdriver.promise.Promise} A promise that will resolve to whether + * the element is present on the page. + */ + isElementPresent(locatorOrElement: Locator, ...var_args: any[]): webdriver.promise.Promise; + isElementPresent(locatorOrElement: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedule a command to search for multiple elements on the page. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the element. + * @param {...} var_args Arguments to pass to {@code #executeScript} if using a + * JavaScript locator. Otherwise ignored. + * @return {!webdriver.promise.Promise} A promise that will be resolved to an + * array of the located {@link webdriver.WebElement}s. + */ + findElements(locator: Locator, ...var_args: any[]): webdriver.promise.Promise; + findElements(locator: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedule a command to take a screenshot. The driver makes a best effort to + * return a screenshot of the following, in order of preference: + *

    + *
  1. Entire page + *
  2. Current window + *
  3. Visible portion of the current frame + *
  4. The screenshot of the entire display containing the browser + *
+ * + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * screenshot as a base-64 encoded PNG. + */ + takeScreenshot(): webdriver.promise.Promise; + + /** + * @return {!webdriver.WebDriver.Options} The options interface for this + * instance. + */ + manage(): WebDriverOptions; + + /** + * @return {!webdriver.WebDriver.Navigation} The navigation interface for this + * instance. + */ + navigate(): WebDriverNavigation; + + /** + * @return {!webdriver.WebDriver.TargetLocator} The target locator interface for + * this instance. + */ + switchTo(): WebDriverTargetLocator; + + //endregion + } + + interface IWebElementId { + ELEMENT: string; + } + + /** + * Represents a DOM element. WebElements can be found by searching from the + * document root using a {@code webdriver.WebDriver} instance, or by searching + * under another {@code webdriver.WebElement}: + *

+     *   driver.get('http://www.google.com');
+     *   var searchForm = driver.findElement(By.tagName('form'));
+     *   var searchBox = searchForm.findElement(By.name('q'));
+     *   searchBox.sendKeys('webdriver');
+     * 
+ * + * The WebElement is implemented as a promise for compatibility with the promise + * API. It will always resolve itself when its internal state has been fully + * resolved and commands may be issued against the element. This can be used to + * catch errors when an element cannot be located on the page: + *

+     *   driver.findElement(By.id('not-there')).then(function(element) {
+     *     alert('Found an element that was not expected to be there!');
+     *   }, function(error) {
+     *     alert('The element was not found, as expected');
+     *   });
+     * 
+ */ + + interface IWebElement { + //region Methods + + /** + * Schedules a command to click on this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the click command has completed. + */ + click(): webdriver.promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by this + * instance. + *

+ * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the keysequence, that key state is toggled until one of the + * following occurs: + *

    + *
  • The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + *
  • + *
  • The {@code webdriver.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys("text was", + * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, + * "now text is"); + * // Alternatively: + * element.sendKeys("text was", + * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), + * "now text is"); + *
  • + *
  • The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + *
  • + *
+ * Note: On browsers where native keyboard events are not yet + * supported (e.g. Firefox on OS X), key events will be synthesized. Special + * punctionation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...string} var_args The sequence of keys to + * type. All arguments will be joined into a single sequence (var_args is + * permitted for convenience). + * @return {!webdriver.promise.Promise} A promise that will be resolved when all + * keys have been typed. + */ + sendKeys(...var_args: string[]): webdriver.promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's tag name. + */ + getTagName(): webdriver.promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + *

+ * Warning: the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * requested CSS value. + */ + getCssValue(cssStyleProperty: string): webdriver.promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value even if it has been modified after the + * page has been loaded. More exactly, this method will return the value of the + * given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned. The "style" attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be "boolean" attributes and will be returned as thus: + * + *

async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + *

Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + *

    + *
  • "class" + *
  • "readonly" + *
+ * @param {string} attributeName The name of the attribute to query. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * attribute's value. + */ + getAttribute(attributeName: string): webdriver.promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's visible text. + */ + getText(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's size as a {@code {width:number, height:number}} object. + */ + getSize(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * element's location as a {@code {x:number, y:number}} object. + */ + getLocation(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently enabled. + */ + isEnabled(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently selected. + */ + isSelected(): webdriver.promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the form has been submitted. + */ + submit(): webdriver.promise.Promise; + + /** + * Schedules a command to clear the {@code value} of this element. This command + * has no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the element has been cleared. + */ + clear(): webdriver.promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently visible on the page. + */ + isDisplayed(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the element's outer HTML. + */ + getOuterHtml(): webdriver.promise.Promise; + + /** + * @return {!webdriver.promise.Promise.} A promise + * that resolves to this element's JSON representation as defined by the + * WebDriver wire protocol. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol + */ + getId(): webdriver.promise.Promise + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): webdriver.promise.Promise; + + //endregion + } + + interface IWebElementFinders { + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + * + *

The search criteria for an element may be defined using one of the + * factories in the {@link webdriver.By} namespace, or as a short-hand + * {@link webdriver.By.Hash} object. For example, the following two statements + * are equivalent: + *

+         * var e1 = element.findElement(By.id('foo'));
+         * var e2 = element.findElement({id:'foo'});
+         * 
+ * + *

You may also provide a custom locator function, which takes as input + * this WebDriver instance and returns a {@link webdriver.WebElement}, or a + * promise that will resolve to a WebElement. For example, to find the first + * visible link on a page, you could write: + *

+         * var link = element.findElement(firstVisibleLink);
+         *
+         * function firstVisibleLink(element) {
+         *   var links = element.findElements(By.tagName('a'));
+         *   return webdriver.promise.filter(links, function(link) {
+         *     return links.isDisplayed();
+         *   }).then(function(visibleLinks) {
+         *     return visibleLinks[0];
+         *   });
+         * }
+         * 
+ * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!webdriver.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: Locator): WebElementPromise; + findElement(locator: any): WebElementPromise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether an element could be located on the page. + */ + isElementPresent(locator: Locator): webdriver.promise.Promise; + isElementPresent(locator: any): webdriver.promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that + * match the given search criteria. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the elements. + * @return {!webdriver.promise.Promise.>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: Locator): webdriver.promise.Promise; + findElements(locator: any): webdriver.promise.Promise; + } + + class WebElement implements IWebElement, IWebElementFinders { + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!(webdriver.promise.Promise.| + * webdriver.WebElement.Id)} id The server-assigned opaque ID for the + * underlying DOM element. + * @constructor + */ + constructor(driver: WebDriver, id: webdriver.promise.Promise); + constructor(driver: WebDriver, id: IWebElementId); + + //endregion + + //region Static Properties + + /** + * The property key used in the wire protocol to indicate that a JSON object + * contains the ID of a WebElement. + * @type {string} + * @const + */ + static ELEMENT_KEY: string; + + //endregion + + //region Methods + + /** + * @return {!webdriver.WebDriver} The parent driver for this instance. + */ + getDriver(): WebDriver; + + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + * + *

The search criteria for an element may be defined using one of the + * factories in the {@link webdriver.By} namespace, or as a short-hand + * {@link webdriver.By.Hash} object. For example, the following two statements + * are equivalent: + *

+         * var e1 = element.findElement(By.id('foo'));
+         * var e2 = element.findElement({id:'foo'});
+         * 
+ * + *

You may also provide a custom locator function, which takes as input + * this WebDriver instance and returns a {@link webdriver.WebElement}, or a + * promise that will resolve to a WebElement. For example, to find the first + * visible link on a page, you could write: + *

+         * var link = element.findElement(firstVisibleLink);
+         *
+         * function firstVisibleLink(element) {
+         *   var links = element.findElements(By.tagName('a'));
+         *   return webdriver.promise.filter(links, function(link) {
+         *     return links.isDisplayed();
+         *   }).then(function(visibleLinks) {
+         *     return visibleLinks[0];
+         *   });
+         * }
+         * 
+ * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!webdriver.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: Locator): WebElementPromise; + findElement(locator: any): WebElementPromise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether an element could be located on the page. + */ + isElementPresent(locator: Locator): webdriver.promise.Promise; + isElementPresent(locator: any): webdriver.promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that + * match the given search criteria. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the elements. + * @return {!webdriver.promise.Promise.>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: Locator): webdriver.promise.Promise; + findElements(locator: any): webdriver.promise.Promise; + + /** + * Schedules a command to click on this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the click command has completed. + */ + click(): webdriver.promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by this + * instance. + *

+ * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the keysequence, that key state is toggled until one of the + * following occurs: + *

    + *
  • The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + *
  • + *
  • The {@code webdriver.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys("text was", + * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, + * "now text is"); + * // Alternatively: + * element.sendKeys("text was", + * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), + * "now text is"); + *
  • + *
  • The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + *
  • + *
+ * Note: On browsers where native keyboard events are not yet + * supported (e.g. Firefox on OS X), key events will be synthesized. Special + * punctionation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...string} var_args The sequence of keys to + * type. All arguments will be joined into a single sequence (var_args is + * permitted for convenience). + * @return {!webdriver.promise.Promise} A promise that will be resolved when all + * keys have been typed. + */ + sendKeys(...var_args: string[]): webdriver.promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's tag name. + */ + getTagName(): webdriver.promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + *

+ * Warning: the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * requested CSS value. + */ + getCssValue(cssStyleProperty: string): webdriver.promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value even if it has been modified after the + * page has been loaded. More exactly, this method will return the value of the + * given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned. The "style" attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be "boolean" attributes and will be returned as thus: + * + *

async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + *

Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + *

    + *
  • "class" + *
  • "readonly" + *
+ * @param {string} attributeName The name of the attribute to query. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * attribute's value. + */ + getAttribute(attributeName: string): webdriver.promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's visible text. + */ + getText(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's size as a {@code {width:number, height:number}} object. + */ + getSize(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * element's location as a {@code {x:number, y:number}} object. + */ + getLocation(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently enabled. + */ + isEnabled(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently selected. + */ + isSelected(): webdriver.promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the form has been submitted. + */ + submit(): webdriver.promise.Promise; + + /** + * Schedules a command to clear the {@code value} of this element. This command + * has no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the element has been cleared. + */ + clear(): webdriver.promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently visible on the page. + */ + isDisplayed(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the element's outer HTML. + */ + getOuterHtml(): webdriver.promise.Promise; + + /** + * @return {!webdriver.promise.Promise.} A promise + * that resolves to this element's JSON representation as defined by the + * WebDriver wire protocol. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol + */ + getId(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): webdriver.promise.Promise; + + //endregion + + //region Static Methods + + /** + * Compares to WebElements for equality. + * @param {!webdriver.WebElement} a A WebElement. + * @param {!webdriver.WebElement} b A WebElement. + * @return {!webdriver.promise.Promise} A promise that will be resolved to + * whether the two WebElements are equal. + */ + static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; + + //endregion + } + + /** + * WebElementPromise is a promise that will be fulfilled with a WebElement. + * This serves as a forward proxy on WebElement, allowing calls to be + * scheduled without directly on this instance before the underlying + * WebElement has been fulfilled. In other words, the following two statements + * are equivalent: + *

+     *     driver.findElement({id: 'my-button'}).click();
+     *     driver.findElement({id: 'my-button'}).then(function(el) {
+     *       return el.click();
+     *     });
+     * 
+ * + * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!webdriver.promise.Promise.} el A promise + * that will resolve to the promised element. + * @constructor + * @extends {webdriver.WebElement} + * @implements {webdriver.promise.Thenable.} + * @final + */ + class WebElementPromise extends WebElement implements webdriver.promise.IThenable { + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. This method is a no-op if the promise has alreayd been resolved. + * + * @param {string=} opt_reason The reason this promise is being cancelled. + */ + cancel(opt_reason?: string): void; + + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: WebElement) => webdriver.promise.Promise, opt_errback?: (error: any) => any): webdriver.promise.Promise; + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: WebElement) => R, opt_errback?: (error: any) => any): webdriver.promise.Promise; + + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *

+         *   // Synchronous API:
+         *   try {
+         *     doSynchronousWork();
+         *   } catch (ex) {
+         *     console.error(ex);
+         *   }
+         *
+         *   // Asynchronous promise API:
+         *   doAsynchronousWork().thenCatch(function(ex) {
+         *     console.error(ex);
+         *   });
+         * 
+ * + * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!webdriver.promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): webdriver.promise.Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *

+         *   // Synchronous API:
+         *   try {
+         *     doSynchronousWork();
+         *   } finally {
+         *     cleanUp();
+         *   }
+         *
+         *   // Asynchronous promise API:
+         *   doAsynchronousWork().thenFinally(cleanUp);
+         * 
+ * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *

+         *   try {
+         *     throw Error('one');
+         *   } finally {
+         *     throw Error('two');  // Hides Error: one
+         *   }
+         *
+         *   webdriver.promise.rejected(Error('one'))
+         *       .thenFinally(function() {
+         *         throw Error('two');  // Hides Error: one
+         *       });
+         * 
+ * + * + * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: () => any): webdriver.promise.Promise; + } + + interface ILocatorStrategy { + className(value: string): Locator; + css(value: string): Locator; + id(value: string): Locator; + js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; + linkText(value: string): Locator; + name(value: string): Locator; + partialLinkText(value: string): Locator; + tagName(value: string): Locator; + xpath(value: string): Locator; + } + + var By: ILocatorStrategy; + + /** + * An element locator. + */ + interface Locator { + + //region Properties + + /** + * The search strategy to use when searching for an element. + * @type {string} + */ + using: string; + + /** + * The search target for this locator. + * @type {string} + */ + value: string; + + //endregion + + //region Methods + + /** @return {string} String representation of this locator. */ + toString(): string; + + //endregion + } + + /** + * Contains information about a WebDriver session. + */ + class Session { + + //region Constructors + + /** + * @param {string} id The session ID. + * @param {!(Object|webdriver.Capabilities)} capabilities The session + * capabilities. + * @constructor + */ + constructor(id: string, capabilities: Capabilities); + constructor(id: string, capabilities: any); + + //endregion + + //region Methods + + /** + * @return {string} This session's ID. + */ + getId(): string; + + /** + * @return {!webdriver.Capabilities} This session's capabilities. + */ + getCapabilities(): Capabilities; + + /** + * Retrieves the value of a specific capability. + * @param {string} key The capability to retrieve. + * @return {*} The capability value. + */ + getCapability(key: string): any; + + /** + * Returns the JSON representation of this object, which is just the string + * session ID. + * @return {string} The JSON representation of this Session. + */ + toJSON(): string; + + //endregion + } +} + +declare module testing { + /** + * Registers a new test suite. + * @param name The suite name. + * @param fn The suite function, or {@code undefined} to define a pending test suite. + */ + function describe(name: string, fn: Function): void; + + /** + * Defines a suppressed test suite. + * @param name The suite name. + * @param fn The suite function, or {@code undefined} to define a pending test suite. + */ + function xdescribe(name: string, fn: Function): void; + + /** + * Register a function to call after the current suite finishes. + * @param fn + */ + function after(fn: Function): void; + + /** + * Register a function to call after each test in a suite. + * @param fn + */ + function afterEach(fn: Function): void; + + /** + * Register a function to call before the current suite starts. + * @param fn + */ + function before(fn: Function): void; + + /** + * Register a function to call before each test in a suite. + * @param fn + */ + function beforeEach(fn: Function): void; + + /** + * Add a test to the current suite. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ + function it(name: string, fn: Function): void; + + /** + * An alias for {@link #it()} that flags the test as the only one that should + * be run within the current suite. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ + function iit(name: string, fn: Function): void; + + /** + * Adds a test to the current suite while suppressing it so it is not run. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ + function xit(name: string, fn: Function): void; +} + +declare module 'selenium-webdriver/chrome' { + export = chrome; +} + +declare module 'selenium-webdriver/firefox' { + export = firefox; +} + +declare module 'selenium-webdriver/executors' { + export = executors; +} + +declare module 'selenium-webdriver' { + export = webdriver; +} + +declare module 'selenium-webdriver/testing' { + export = testing; +} diff --git a/angular1/e2e-tests/typings/tsd.d.ts b/angular1/e2e-tests/typings/tsd.d.ts new file mode 100644 index 0000000..93e5d33 --- /dev/null +++ b/angular1/e2e-tests/typings/tsd.d.ts @@ -0,0 +1,7 @@ +/// +/// +/// +/// +/// +/// +/// diff --git a/angular1/karma.conf.js b/angular1/karma.conf.js new file mode 100644 index 0000000..44bb29f --- /dev/null +++ b/angular1/karma.conf.js @@ -0,0 +1,33 @@ +module.exports = function(config){ + config.set({ + + basePath : './', + + files : [ + 'app/bower_components/angular/angular.js', + 'app/bower_components/angular-route/angular-route.js', + 'app/bower_components/angular-mocks/angular-mocks.js', + 'app/components/**/*.js', + 'app/view*/**/*.js' + ], + + autoWatch : true, + + frameworks: ['jasmine'], + + browsers : ['Chrome'], + + plugins : [ + 'karma-chrome-launcher', + 'karma-firefox-launcher', + 'karma-jasmine', + 'karma-junit-reporter' + ], + + junitReporter : { + outputFile: 'test_out/unit.xml', + suite: 'unit' + } + + }); +}; diff --git a/angular1/package.json b/angular1/package.json new file mode 100644 index 0000000..6755f5f --- /dev/null +++ b/angular1/package.json @@ -0,0 +1,38 @@ +{ + "name": "angular-seed", + "private": true, + "version": "0.0.0", + "description": "A starter project for AngularJS using TypeScript", + "repository": "https://github.com/Microsoft/TypeScriptSamples/angular1", + "license": "MIT", + "devDependencies": { + "bower": "^1.3.1", + "http-server": "^0.6.1", + "jasmine-core": "^2.3.4", + "karma": "~0.12", + "karma-chrome-launcher": "^0.1.12", + "karma-firefox-launcher": "^0.1.6", + "karma-jasmine": "^0.3.5", + "karma-junit-reporter": "^0.2.2", + "protractor": "^2.1.0", + "shelljs": "^0.2.6" + }, + "scripts": { + "postinstall": "bower install", + + "prestart": "npm install", + "start": "http-server -a localhost -p 8000 -c-1", + + "pretest": "npm install", + "test": "karma start karma.conf.js", + "test-single-run": "karma start karma.conf.js --single-run", + + "preupdate-webdriver": "npm install", + "update-webdriver": "webdriver-manager update", + + "preprotractor": "npm run update-webdriver", + "protractor": "protractor e2e-tests/protractor.conf.js", + + "update-index-async": "node -e \"require('shelljs/global'); sed('-i', /\\/\\/@@NG_LOADER_START@@[\\s\\S]*\\/\\/@@NG_LOADER_END@@/, '//@@NG_LOADER_START@@\\n' + sed(/sourceMappingURL=angular-loader.min.js.map/,'sourceMappingURL=bower_components/angular-loader/angular-loader.min.js.map','app/bower_components/angular-loader/angular-loader.min.js') + '\\n//@@NG_LOADER_END@@', 'app/index-async.html');\"" + } +} diff --git a/angular2/.gitignore b/angular2/.gitignore new file mode 100644 index 0000000..ef430a6 --- /dev/null +++ b/angular2/.gitignore @@ -0,0 +1,2 @@ +todo.js +node_modules \ No newline at end of file diff --git a/angular2/README.md b/angular2/README.md new file mode 100644 index 0000000..6443133 --- /dev/null +++ b/angular2/README.md @@ -0,0 +1,22 @@ +**Fetch dependencies:** +``` +npm install +``` + +**Build and run (combines 'build' and 'run server' commands using the default port 8080)** +``` +npm start +``` + +**Build** +``` +node node_modules/typescript/lib/tsc.js +``` + +**Run server** +``` +node node_modules/http-server/bin/http-server -p 8080 +``` + +'-p' sets the port to use, default port is 8080. If it is taken pick any port that is free. +After server is started open 'localhost:8080' in a browser. \ No newline at end of file diff --git a/angular2/app/todo.ts b/angular2/app/todo.ts new file mode 100644 index 0000000..838b483 --- /dev/null +++ b/angular2/app/todo.ts @@ -0,0 +1,73 @@ +import {Component, bootstrap, NgFor, provide} from 'angular2/angular2'; +import {AngularFire, FirebaseArray} from '../firebase/angularfire'; + +@Component({ + selector: 'todo-app', + providers: [ + AngularFire, + provide(Firebase, { useValue: new Firebase('https://webapi.firebaseio-demo.com/test') }) + ], + directives: [NgFor], + templateUrl: 'todo.html' +}) +class TodoApp { + todoService: FirebaseArray; + todoEdit: any; + + constructor(sync: AngularFire) { + this.todoService = sync.asArray(); + this.todoEdit = null; + } + enterTodo($event, newTodo) { + if($event.which === 13) { // ENTER_KEY + this.addTodo(newTodo.value); + newTodo.value = ''; + } + } + editTodo($event, todo) { + this.todoEdit = todo; + } + doneEditing($event, todo) { + var which = $event.which; + var target = $event.target; + if(which === 13) { + todo.title = target.value; + this.todoService.save(todo); + this.todoEdit = null; + } else if (which === 27) { + this.todoEdit = null; + target.value = todo.title; + } + } + addTodo(newTitle) { + this.todoService.add({ + title: newTitle, + completed: false + }); + } + completeMe(todo) { + todo.completed = !todo.completed; + this.todoService.save(todo); + } + deleteMe(todo) { + this.todoService.remove(todo); + } + toggleAll($event) { + var isComplete = $event.target.checked; + this.todoService.list.forEach((todo)=> { + todo.completed = isComplete; + this.todoService.save(todo); + }); + } + clearCompleted() { + var toClear = {}; + this.todoService.list.forEach((todo) => { + if(todo.completed) { + toClear[todo._key] = null; + } + }); + this.todoService.bulkUpdate(toClear); + } + +} +bootstrap(TodoApp); diff --git a/angular2/css/base.css b/angular2/css/base.css new file mode 100644 index 0000000..502f06c --- /dev/null +++ b/angular2/css/base.css @@ -0,0 +1,379 @@ +@charset "utf-8"; + +button { + margin: 0; + padding: 0; + border: 0; + background: none; + font-size: 100%; + vertical-align: baseline; + font-family: inherit; + font-weight: inherit; + color: inherit; + -webkit-appearance: none; + -ms-appearance: none; + appearance: none; + -webkit-font-smoothing: antialiased; + -moz-font-smoothing: antialiased; + -ms-font-smoothing: antialiased; + font-smoothing: antialiased; +} + +button, +input[type="checkbox"] { + outline: none; +} + +.hidden { + display: none; +} + +.visible { + display: block !important; +} + +#todoapp { + background: #fff; + margin: 130px 0 40px 0; + position: relative; + box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), + 0 25px 50px 0 rgba(0, 0, 0, 0.1); +} + +#todoapp input::-webkit-input-placeholder { + font-style: italic; + font-weight: 300; + color: #e6e6e6; +} + +#todoapp input::-moz-placeholder { + font-style: italic; + font-weight: 300; + color: #e6e6e6; +} + +#todoapp input::input-placeholder { + font-style: italic; + font-weight: 300; + color: #e6e6e6; +} + +#todoapp h1 { + position: absolute; + top: -155px; + width: 100%; + font-size: 100px; + font-weight: 100; + text-align: center; + color: rgba(175, 47, 47, 0.15); + -webkit-text-rendering: optimizeLegibility; + -moz-text-rendering: optimizeLegibility; + -ms-text-rendering: optimizeLegibility; + text-rendering: optimizeLegibility; +} + +#new-todo, +.edit { + position: relative; + margin: 0; + width: 100%; + font-size: 24px; + font-family: inherit; + font-weight: inherit; + line-height: 1.4em; + border: 0; + outline: none; + color: inherit; + padding: 6px; + border: 1px solid #999; + box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2); + -ms-box-sizing: border-box; + box-sizing: border-box; + -webkit-font-smoothing: antialiased; + -moz-font-smoothing: antialiased; + -ms-font-smoothing: antialiased; + font-smoothing: antialiased; +} + +#new-todo { + padding: 16px 16px 16px 60px; + border: none; + background: rgba(0, 0, 0, 0.003); + box-shadow: inset 0 -2px 1px rgba(0,0,0,0.03); +} + +#main { + position: relative; + z-index: 2; + border-top: 1px solid #e6e6e6; +} + +label[for='toggle-all'] { + display: none; +} + +#toggle-all { + position: absolute; + top: -55px; + left: -12px; + width: 60px; + height: 34px; + text-align: center; + border: none; /* Mobile Safari */ +} + +#toggle-all:before { + content: 'â¯'; + font-size: 22px; + color: #e6e6e6; + padding: 10px 27px 10px 27px; +} + +#toggle-all:checked:before { + color: #737373; +} + +#todo-list { + margin: 0; + padding: 0; + list-style: none; +} + +#todo-list li { + position: relative; + font-size: 24px; + border-bottom: 1px solid #ededed; +} + +#todo-list li:last-child { + border-bottom: none; +} + +#todo-list li.editing { + border-bottom: none; + padding: 0; +} + +#todo-list li.editing .edit { + display: block; + width: 506px; + padding: 13px 17px 12px 17px; + margin: 0 0 0 43px; +} + +#todo-list li.editing .view { + display: none; +} + +#todo-list li .toggle { + text-align: center; + width: 40px; + /* auto, since non-WebKit browsers doesn't support input styling */ + height: auto; + position: absolute; + top: 0; + bottom: 0; + margin: auto 0; + border: none; /* Mobile Safari */ + -webkit-appearance: none; + -ms-appearance: none; + appearance: none; +} + +#todo-list li .toggle:after { + content: url('data:image/svg+xml;utf8,'); +} + +#todo-list li .toggle:checked:after { + content: url('data:image/svg+xml;utf8,'); +} + +#todo-list li label { + white-space: pre; + word-break: break-word; + padding: 15px 60px 15px 15px; + margin-left: 45px; + display: block; + line-height: 1.2; + transition: color 0.4s; +} + +#todo-list li.completed label { + color: #d9d9d9; + text-decoration: line-through; +} + +#todo-list li .destroy { + display: none; + position: absolute; + top: 0; + right: 10px; + bottom: 0; + width: 40px; + height: 40px; + margin: auto 0; + font-size: 30px; + color: #cc9a9a; + margin-bottom: 11px; + transition: color 0.2s ease-out; +} + +#todo-list li .destroy:hover { + color: #af5b5e; +} + +#todo-list li .destroy:after { + content: '×'; +} + +#todo-list li:hover .destroy { + display: block; +} + +#todo-list li .edit { + display: none; +} + +#todo-list li.editing:last-child { + margin-bottom: -1px; +} + +#footer { + color: #777; + padding: 10px 15px; + height: 20px; + text-align: center; + border-top: 1px solid #e6e6e6; +} + +#footer:before { + content: ''; + position: absolute; + right: 0; + bottom: 0; + left: 0; + height: 50px; + overflow: hidden; + box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2), + 0 8px 0 -3px #f6f6f6, + 0 9px 1px -3px rgba(0, 0, 0, 0.2), + 0 16px 0 -6px #f6f6f6, + 0 17px 2px -6px rgba(0, 0, 0, 0.2); +} + +#todo-count { + float: left; + text-align: left; +} + +#todo-count strong { + font-weight: 300; +} + +#filters { + margin: 0; + padding: 0; + list-style: none; + position: absolute; + right: 0; + left: 0; +} + +#filters li { + display: inline; +} + +#filters li a { + color: inherit; + margin: 3px; + padding: 3px 7px; + text-decoration: none; + border: 1px solid transparent; + border-radius: 3px; +} + +#filters li a.selected, +#filters li a:hover { + border-color: rgba(175, 47, 47, 0.1); +} + +#filters li a.selected { + border-color: rgba(175, 47, 47, 0.2); +} + +#clear-completed, +html #clear-completed:active { + float: right; + position: relative; + line-height: 20px; + text-decoration: none; + cursor: pointer; + visibility: hidden; + position: relative; +} + +#clear-completed::after { + visibility: visible; + content: 'Clear completed'; + position: absolute; + right: 0; + white-space: nowrap; +} + +#clear-completed:hover::after { + text-decoration: underline; +} + +#info { + margin: 65px auto 0; + color: #bfbfbf; + font-size: 10px; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); + text-align: center; +} + +#info p { + line-height: 1; +} + +#info a { + color: inherit; + text-decoration: none; + font-weight: 400; +} + +#info a:hover { + text-decoration: underline; +} + +/* +Hack to remove background from Mobile Safari. +Can't use it globally since it destroys checkboxes in Firefox +*/ +@media screen and (-webkit-min-device-pixel-ratio:0) { + #toggle-all, + #todo-list li .toggle { + background: none; + } + + #todo-list li .toggle { + height: 40px; + } + + #toggle-all { + -webkit-transform: rotate(90deg); + transform: rotate(90deg); + -webkit-appearance: none; + appearance: none; + } +} + +@media (max-width: 430px) { + #footer { + height: 50px; + } + + #filters { + bottom: 10px; + } +} diff --git a/angular2/css/bg.png b/angular2/css/bg.png new file mode 100644 index 0000000..b2a7600 Binary files /dev/null and b/angular2/css/bg.png differ diff --git a/angular2/firebase/angularfire.d.ts b/angular2/firebase/angularfire.d.ts new file mode 100644 index 0000000..409657b --- /dev/null +++ b/angular2/firebase/angularfire.d.ts @@ -0,0 +1,23 @@ +/// + +export declare class AngularFire { + asArray(): FirebaseArray; +} + +export interface FirebaseArray { + getItem(recOrIndex: any): any + getChild(recOrIndex: any): any; + add(newData: any): void; + remove(recOrIndex: any): void; + save(recOrIndex: any): void; + keyify(snap: any): any; + created(snap: any): void; + moved(snap: any): void; + updated(snap: any): void; + removed(snap: any): void; + bulkUpdate(items: Object): void; + spliceOut(key: any): void; + indexFor(key: any): number; + getRecord(key: any): any; + list: any[]; +} diff --git a/angular2/firebase/angularfire.js b/angular2/firebase/angularfire.js new file mode 100644 index 0000000..52deb96 --- /dev/null +++ b/angular2/firebase/angularfire.js @@ -0,0 +1,106 @@ +if (typeof __decorate !== "function") __decorate = function (decorators, target, key, desc) { + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); + switch (arguments.length) { + case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target); + case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0); + case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); + } +}; +if (typeof __metadata !== "function") __metadata = function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define(["require", "exports", 'angular2/angular2'], function (require, exports, angular2_1) { + var AngularFire = (function () { + function AngularFire(ref) { + this.ref = ref; + } + AngularFire.prototype.asArray = function () { + return new FirebaseArray(this.ref); + }; + AngularFire = __decorate([ + angular2_1.Component(), + __metadata('design:paramtypes', [(typeof Firebase !== 'undefined' && Firebase) || Object]) + ], AngularFire); + return AngularFire; + })(); + exports.AngularFire = AngularFire; + /* + FirebaseArray + + */ + var FirebaseArray = (function () { + function FirebaseArray(ref) { + this.ref = ref; + this.list = []; + // listen for changes at the Firebase instance + this.ref.on('child_added', this.created.bind(this), this.error); + this.ref.on('child_moved', this.moved.bind(this), this.error); + this.ref.on('child_changed', this.updated.bind(this), this.error); + this.ref.on('child_removed', this.removed.bind(this), this.error); + // determine when initial load is completed + // ref.once('value', function() { resolve(null); }, resolve); + } + FirebaseArray.prototype.getItem = function (recOrIndex) { + var item = recOrIndex; + if (typeof (recOrIndex) === "number") { + item = this.getRecord(recOrIndex); + } + return item; + }; + FirebaseArray.prototype.getChild = function (recOrIndex) { + var item = this.getItem(recOrIndex); + return this.ref.child(item._key); + }; + FirebaseArray.prototype.add = function (rec) { + this.ref.push(rec); + }; + FirebaseArray.prototype.remove = function (recOrIndex) { + this.getChild(recOrIndex).remove(); + }; + FirebaseArray.prototype.save = function (recOrIndex) { + var item = this.getItem(recOrIndex); + this.getChild(recOrIndex).update(item); + }; + FirebaseArray.prototype.keyify = function (snap) { + var item = snap.val(); + item._key = snap.key(); + return item; + }; + FirebaseArray.prototype.created = function (snap) { + var addedValue = this.keyify(snap); + this.list.push(addedValue); + }; + FirebaseArray.prototype.moved = function (snap) { + var key = snap.key(); + this.spliceOut(key); + }; + FirebaseArray.prototype.updated = function (snap) { + var key = snap.key(); + var indexToUpdate = this.indexFor(key); + this.list[indexToUpdate] = this.keyify(snap); + }; + FirebaseArray.prototype.removed = function (snap) { + var key = snap.key(); + this.spliceOut(key); + }; + FirebaseArray.prototype.bulkUpdate = function (items) { + this.ref.update(items); + }; + FirebaseArray.prototype.spliceOut = function (key) { + var i = this.indexFor(key); + if (i > -1) { + return this.list.splice(i, 1)[0]; + } + return null; + }; + FirebaseArray.prototype.indexFor = function (key) { + var record = this.getRecord(key); + return this.list.indexOf(record); + }; + FirebaseArray.prototype.getRecord = function (key) { + return this.list.find(function (item) { return key === item._key; }); + }; + return FirebaseArray; + })(); + exports.FirebaseArray = FirebaseArray; +}); diff --git a/angular2/firebase/firebase.d.ts b/angular2/firebase/firebase.d.ts new file mode 100644 index 0000000..5e58cca --- /dev/null +++ b/angular2/firebase/firebase.d.ts @@ -0,0 +1,308 @@ +// Type definitions for Firebase API 2.0.2 +// Project: https://www.firebase.com/docs/javascript/firebase +// Definitions by: Vincent Botone , Shin1 Kashimura +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface FirebaseAuthResult { + auth: any; + expires: number; +} + +interface FirebaseDataSnapshot { + /** + * Gets the JavaScript object representation of the DataSnapshot. + */ + val(): any; + /** + * Gets a DataSnapshot for the location at the specified relative path. + */ + child(childPath: string): FirebaseDataSnapshot; + /** + * Enumerates through the DataSnapshot’s children (in the default order). + */ + forEach(childAction: (childSnapshot: FirebaseDataSnapshot) => void): boolean; + forEach(childAction: (childSnapshot: FirebaseDataSnapshot) => boolean): boolean; + /** + * Returns true if the specified child exists. + */ + hasChild(childPath: string): boolean; + /** + * Returns true if the DataSnapshot has any children. + */ + hasChildren(): boolean; + /** + * Gets the key name of the location that generated this DataSnapshot. + */ + key(): string; + /** + * @deprecated Use key() instead. + * Gets the key name of the location that generated this DataSnapshot. + */ + name(): string; + /** + * Gets the number of children for this DataSnapshot. + */ + numChildren(): number; + /** + * Gets the Firebase reference for the location that generated this DataSnapshot. + */ + ref(): Firebase; + /** + * Gets the priority of the data in this DataSnapshot. + * @returns {string, number, null} The priority, or null if no priority was set. + */ + getPriority(): any; // string or number + /** + * Exports the entire contents of the DataSnapshot as a JavaScript object. + */ + exportVal(): Object; +} + +interface FirebaseOnDisconnect { + /** + * Ensures the data at this location is set to the specified value when the client is disconnected + * (due to closing the browser, navigating to a new page, or network issues). + */ + set(value: any, onComplete?: (error: any) => void): void; + /** + * Ensures the data at this location is set to the specified value and priority when the client is disconnected + * (due to closing the browser, navigating to a new page, or network issues). + */ + setWithPriority(value: any, priority: string, onComplete?: (error: any) => void): void; + setWithPriority(value: any, priority: number, onComplete?: (error: any) => void): void; + /** + * Writes the enumerated children at this Firebase location when the client is disconnected + * (due to closing the browser, navigating to a new page, or network issues). + */ + update(value: Object, onComplete?: (error: any) => void): void; + /** + * Ensures the data at this location is deleted when the client is disconnected + * (due to closing the browser, navigating to a new page, or network issues). + */ + remove(onComplete?: (error: any) => void): void; + /** + * Cancels all previously queued onDisconnect() set or update events for this location and all children. + */ + cancel(onComplete?: (error: any) => void): void; +} + +interface FirebaseQuery { + /** + * Listens for data changes at a particular location. + */ + on(eventType: string, callback: (dataSnapshot: FirebaseDataSnapshot, prevChildName?: string) => void, cancelCallback?: (error: any) => void, context?: Object): (dataSnapshot: FirebaseDataSnapshot, prevChildName?: string) => void; + /** + * Detaches a callback previously attached with on(). + */ + off(eventType?: string, callback?: (dataSnapshot: FirebaseDataSnapshot, prevChildName?: string) => void, context?: Object): void; + /** + * Listens for exactly one event of the specified event type, and then stops listening. + */ + once(eventType: string, successCallback: (dataSnapshot: FirebaseDataSnapshot) => void, context?: Object): void; + once(eventType: string, successCallback: (dataSnapshot: FirebaseDataSnapshot) => void, failureCallback?: (error: any) => void, context?: Object): void; + /** + * Generates a new Query object ordered by the specified child key. + */ + orderByChild(key: string): FirebaseQuery; + /** + * Generates a new Query object ordered by key name. + */ + orderByKey(): FirebaseQuery; + /** + * Generates a new Query object ordered by priority. + */ + orderByPriority(): FirebaseQuery; + /** + * @deprecated Use limitToFirst() and limitToLast() instead. + * Generates a new Query object limited to the specified number of children. + */ + limit(limit: number): FirebaseQuery; + /** + * Creates a Query with the specified starting point. + * The generated Query includes children which match the specified starting point. + */ + startAt(value: string, key?: string): FirebaseQuery; + startAt(value: number, key?: string): FirebaseQuery; + /** + * Creates a Query with the specified ending point. + * The generated Query includes children which match the specified ending point. + */ + endAt(value: string, key?: string): FirebaseQuery; + endAt(value: number, key?: string): FirebaseQuery; + /** + * Creates a Query which includes children which match the specified value. + */ + equalTo(value: string, key?: string): FirebaseQuery; + equalTo(value: number, key?: string): FirebaseQuery; + /** + * Generates a new Query object limited to the first certain number of children. + */ + limitToFirst(limit: number): FirebaseQuery; + /** + * Generates a new Query object limited to the last certain number of children. + */ + limitToLast(limit: number): FirebaseQuery; + /** + * Gets a Firebase reference to the Query's location. + */ + ref(): Firebase; +} + +interface Firebase extends FirebaseQuery { + /** + * @deprecated Use authWithCustomToken() instead. + * Authenticates a Firebase client using the provided authentication token or Firebase Secret. + */ + auth(authToken: string, onComplete?: (error: any, result: FirebaseAuthResult) => void, onCancel?:(error: any) => void): void; + /** + * Authenticates a Firebase client using an authentication token or Firebase Secret. + */ + authWithCustomToken(autoToken: string, onComplete: (error: any, authData: FirebaseAuthData) => void, options?:Object): void; + /** + * Authenticates a Firebase client using a new, temporary guest account. + */ + authAnonymously(onComplete: (error: any, authData: FirebaseAuthData) => void, options?: Object): void; + /** + * Authenticates a Firebase client using an email / password combination. + */ + authWithPassword(credentials: FirebaseCredentials, onComplete: (error: any, authData: FirebaseAuthData) => void, options?: Object): void; + /** + * Authenticates a Firebase client using a popup-based OAuth flow. + */ + authWithOAuthPopup(provider: string, onComplete:(error: any, authData: FirebaseAuthData) => void, options?: Object): void; + /** + * Authenticates a Firebase client using a redirect-based OAuth flow. + */ + authWithOAuthRedirect(provider: string, onComplete: (error: any) => void, options?: Object): void; + /** + * Authenticates a Firebase client using OAuth access tokens or credentials. + */ + authWithOAuthToken(provider: string, credentials: string, onComplete: (error: any, authData: FirebaseAuthData) => void, options?: Object): void; + authWithOAuthToken(provider: string, credentials: Object, onComplete: (error: any, authData: FirebaseAuthData) => void, options?: Object): void; + /** + * Synchronously access the current authentication state of the client. + */ + getAuth(): FirebaseAuthData; + /** + * Listen for changes to the client's authentication state. + */ + onAuth(onComplete: (authData: FirebaseAuthData) => void, context?: Object): void; + /** + * Detaches a callback previously attached with onAuth(). + */ + offAuth(onComplete: (authData: FirebaseAuthData) => void, context?: Object): void; + /** + * Unauthenticates a Firebase client. + */ + unauth(): void; + /** + * Gets a Firebase reference for the location at the specified relative path. + */ + child(childPath: string): Firebase; + /** + * Gets a Firebase reference to the parent location. + */ + parent(): Firebase; + /** + * Gets a Firebase reference to the root of the Firebase. + */ + root(): Firebase; + /** + * Returns the last token in a Firebase location. + */ + key(): string; + /** + * @deprecated Use key() instead. + * Returns the last token in a Firebase location. + */ + name(): string; + /** + * Gets the absolute URL corresponding to this Firebase reference's location. + */ + toString(): string; + /** + * Writes data to this Firebase location. + */ + set(value: any, onComplete?: (error: any) => void): void; + /** + * Writes the enumerated children to this Firebase location. + */ + update(value: Object, onComplete?: (error: any) => void): void; + /** + * Removes the data at this Firebase location. + */ + remove(onComplete?: (error: any) => void): void; + /** + * Generates a new child location using a unique name and returns a Firebase reference to it. + * @returns {Firebase} A Firebase reference for the generated location. + */ + push(value?: any, onComplete?: (error: any) => void): Firebase; + /** + * Writes data to this Firebase location. Like set() but also specifies the priority for that data. + */ + setWithPriority(value: any, priority: string, onComplete?: (error: any) => void): void; + setWithPriority(value: any, priority: number, onComplete?: (error: any) => void): void; + /** + * Sets a priority for the data at this Firebase location. + */ + setPriority(priority: string, onComplete?: (error: any) => void): void; + setPriority(priority: number, onComplete?: (error: any) => void): void; + /** + * Atomically modifies the data at this location. + */ + transaction(updateFunction: (currentData: any)=> any, onComplete?: (error: any, committed: boolean, snapshot: FirebaseDataSnapshot) => void, applyLocally?: boolean): void; + /** + * Creates a new user account using an email / password combination. + */ + createUser(credentials: FirebaseCredentials, onComplete: (error: any) => void): void; + /** + * Change the password of an existing user using an email / password combination. + */ + changePassword(credentials: { email: string; oldPassword: string; newPassword: string }, onComplete: (error: any) => void): void; + /** + * Removes an existing user account using an email / password combination. + */ + removeUser(credentials: FirebaseCredentials, onComplete: (error: any) => void): void; + /** + * Sends a password-reset email to the owner of the account, containing a token that may be used to authenticate and change the user password. + */ + resetPassword(credentials: { email: string }, onComplete: (error: any) => void): void; + onDisconnect(): FirebaseOnDisconnect; +} +interface FirebaseStatic { + /** + * Constructs a new Firebase reference from a full Firebase URL. + */ + new (firebaseURL: string): Firebase; + /** + * Manually disconnects the Firebase client from the server and disables automatic reconnection. + */ + goOffline(): void; + /** + * Manually reestablishes a connection to the Firebase server and enables automatic reconnection. + */ + goOnline(): void; + + ServerValue: { + /** + * A placeholder value for auto-populating the current timestamp + * (time since the Unix epoch, in milliseconds) by the Firebase servers. + */ + TIMESTAMP: any; + }; +} +declare var Firebase: FirebaseStatic; + +// Reference: https://www.firebase.com/docs/web/api/firebase/getauth.html +interface FirebaseAuthData { + uid: string; + provider: string; + token: string; + expires: number; + auth: Object; +} + +interface FirebaseCredentials { + email: string; + password: string; +} \ No newline at end of file diff --git a/angular2/firebase/firebase.js b/angular2/firebase/firebase.js new file mode 100644 index 0000000..ff5d7cc --- /dev/null +++ b/angular2/firebase/firebase.js @@ -0,0 +1,245 @@ +/*! @license Firebase v0.0.0 - License: https://www.firebase.com/terms/terms-of-service.html */ (function() {var h,aa=this;function m(a){return void 0!==a}function ba(){}function ca(a){a.Nb=function(){return a.kf?a.kf:a.kf=new a}} +function da(a){var b=typeof a;if("object"==b)if(a){if(a instanceof Array)return"array";if(a instanceof Object)return b;var c=Object.prototype.toString.call(a);if("[object Window]"==c)return"object";if("[object Array]"==c||"number"==typeof a.length&&"undefined"!=typeof a.splice&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("splice"))return"array";if("[object Function]"==c||"undefined"!=typeof a.call&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("call"))return"function"}else return"null"; +else if("function"==b&&"undefined"==typeof a.call)return"object";return b}function ea(a){return"array"==da(a)}function fa(a){var b=da(a);return"array"==b||"object"==b&&"number"==typeof a.length}function p(a){return"string"==typeof a}function ga(a){return"number"==typeof a}function ha(a){return"function"==da(a)}function ia(a){var b=typeof a;return"object"==b&&null!=a||"function"==b}function ja(a,b,c){return a.call.apply(a.bind,arguments)} +function ka(a,b,c){if(!a)throw Error();if(2b?e+="000":256>b?e+="00":4096>b&&(e+="0");return ra[a]=e+b.toString(16)}),'"')};function ta(a){return"undefined"!==typeof JSON&&m(JSON.parse)?JSON.parse(a):na(a)}function r(a){if("undefined"!==typeof JSON&&m(JSON.stringify))a=JSON.stringify(a);else{var b=[];pa(new oa,a,b);a=b.join("")}return a};function s(a,b){return Object.prototype.hasOwnProperty.call(a,b)}function t(a,b){if(Object.prototype.hasOwnProperty.call(a,b))return a[b]}function ua(a,b){for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&b(c,a[c])}function va(a){var b={};ua(a,function(a,d){b[a]=d});return b};function wa(a){this.tc=a;this.Ed="firebase:"}h=wa.prototype;h.set=function(a,b){null==b?this.tc.removeItem(this.Ed+a):this.tc.setItem(this.Ed+a,r(b))};h.get=function(a){a=this.tc.getItem(this.Ed+a);return null==a?null:ta(a)};h.remove=function(a){this.tc.removeItem(this.Ed+a)};h.lf=!1;h.toString=function(){return this.tc.toString()};function xa(){this.nc={}}xa.prototype.set=function(a,b){null==b?delete this.nc[a]:this.nc[a]=b};xa.prototype.get=function(a){return s(this.nc,a)?this.nc[a]:null};xa.prototype.remove=function(a){delete this.nc[a]};xa.prototype.lf=!0;function ya(a){try{if("undefined"!==typeof window&&"undefined"!==typeof window[a]){var b=window[a];b.setItem("firebase:sentinel","cache");b.removeItem("firebase:sentinel");return new wa(b)}}catch(c){}return new xa}var za=ya("localStorage"),Aa=ya("sessionStorage");function Ba(a,b,c,d,e){this.host=a.toLowerCase();this.domain=this.host.substr(this.host.indexOf(".")+1);this.Ab=b;this.tb=c;this.Dg=d;this.Dd=e||"";this.Ma=za.get("host:"+a)||this.host}function Ca(a,b){b!==a.Ma&&(a.Ma=b,"s-"===a.Ma.substr(0,2)&&za.set("host:"+a.host,a.Ma))}Ba.prototype.toString=function(){var a=(this.Ab?"https://":"http://")+this.host;this.Dd&&(a+="<"+this.Dd+">");return a};function Da(){this.Sa=-1};function Ea(){this.Sa=-1;this.Sa=64;this.R=[];this.be=[];this.Ef=[];this.Ad=[];this.Ad[0]=128;for(var a=1;ae;e++)d[e]=b.charCodeAt(c)<<24|b.charCodeAt(c+1)<<16|b.charCodeAt(c+2)<<8|b.charCodeAt(c+3),c+=4;else for(e=0;16>e;e++)d[e]=b[c]<<24|b[c+1]<<16|b[c+2]<<8|b[c+3],c+=4;for(e=16;80>e;e++){var f=d[e-3]^d[e-8]^d[e-14]^d[e-16];d[e]=(f<<1|f>>>31)&4294967295}b=a.R[0];c=a.R[1];for(var g=a.R[2],k=a.R[3],l=a.R[4],n,e=0;80>e;e++)40>e?20>e?(f=k^c&(g^k),n=1518500249):(f=c^g^k,n=1859775393):60>e?(f=c&g|k&(c|g),n=2400959708):(f=c^g^k,n=3395469782),f=(b<< +5|b>>>27)+f+l+n+d[e]&4294967295,l=k,k=g,g=(c<<30|c>>>2)&4294967295,c=b,b=f;a.R[0]=a.R[0]+b&4294967295;a.R[1]=a.R[1]+c&4294967295;a.R[2]=a.R[2]+g&4294967295;a.R[3]=a.R[3]+k&4294967295;a.R[4]=a.R[4]+l&4294967295} +Ea.prototype.update=function(a,b){m(b)||(b=a.length);for(var c=b-this.Sa,d=0,e=this.be,f=this.Sb;dc?Math.max(0,a.length+c):c;if(p(a))return p(b)&&1==b.length?a.indexOf(b,c):-1;for(;cc?null:p(a)?a.charAt(c):a[c]}function Oa(a,b,c){for(var d=a.length,e=p(a)?a.split(""):a,f=0;f=arguments.length?v.slice.call(a,b):v.slice.call(a,b,c)}function Ra(a,b){a.sort(b||Sa)}function Sa(a,b){return a>b?1:aparseFloat(a))?String(b):a})();var ab=null,bb=null,cb=null;function db(a,b){if(!fa(a))throw Error("encodeByteArray takes an array as a parameter");eb();for(var c=b?bb:ab,d=[],e=0;e>2,f=(f&3)<<4|k>>4,k=(k&15)<<2|n>>6,n=n&63;l||(n=64,g||(k=64));d.push(c[u],c[f],c[k],c[n])}return d.join("")} +function eb(){if(!ab){ab={};bb={};cb={};for(var a=0;65>a;a++)ab[a]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(a),bb[a]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.".charAt(a),cb[bb[a]]=a}};var fb=function(){var a=1;return function(){return a++}}();function w(a,b){if(!a)throw gb(b);}function gb(a){return Error("Firebase INTERNAL ASSERT FAILED:"+a)} +function hb(a){try{var b;if("undefined"!==typeof atob)b=atob(a);else{eb();for(var c=cb,d=[],e=0;e>4);64!=k&&(d.push(g<<4&240|k>>2),64!=l&&d.push(k<<6&192|l))}if(8192>d.length)b=String.fromCharCode.apply(null,d);else{a="";for(c=0;ca.Sb?a.update(a.Ad,56-a.Sb):a.update(a.Ad,a.Sa-(a.Sb-56));for(var d=a.Sa-1;56<=d;d--)a.be[d]=c&255,c/=256;Fa(a,a.be);for(d=c=0;5>d;d++)for(var e=24;0<=e;e-=8)b[c]=a.R[d]>>e&255,++c;return db(b)} +function lb(a){for(var b="",c=0;ca?c.push(a.substring(d,a.length)):c.push(a.substring(d,d+b));return c}function Ab(a,b){if(ea(a))for(var c=0;ca,a=Math.abs(a),a>=Math.pow(2,-1022)?(d=Math.min(Math.floor(Math.log(a)/Math.LN2),1023),c=d+1023,d=Math.round(a*Math.pow(2,52-d)-Math.pow(2,52))):(c=0,d=Math.round(a/Math.pow(2,-1074))));e=[];for(a=52;a;a-=1)e.push(d%2?1:0),d=Math.floor(d/2);for(a=11;a;a-=1)e.push(c%2?1:0),c=Math.floor(c/2);e.push(b?1:0);e.reverse();b=e.join("");c="";for(a=0;64>a;a+=8)d=parseInt(b.substr(a,8),2).toString(16),1===d.length&& +(d="0"+d),c+=d;return c.toLowerCase()}var Cb=/^-?\d{1,10}$/;function wb(a){return Cb.test(a)&&(a=Number(a),-2147483648<=a&&2147483647>=a)?a:null}function Db(a){try{a()}catch(b){setTimeout(function(){y("Exception was thrown by user callback.",b.stack||"");throw b;},Math.floor(0))}}function A(a,b){if(ha(a)){var c=Array.prototype.slice.call(arguments,1).slice();Db(function(){a.apply(null,c)})}};function Eb(a,b,c,d){this.le=b;this.Nd=c;this.Fd=d;this.jd=a}Eb.prototype.Qb=function(){var a=this.Nd.cc();return"value"===this.jd?a.path:a.parent().path};Eb.prototype.pe=function(){return this.jd};Eb.prototype.Lb=function(){return this.le.Lb(this)};Eb.prototype.toString=function(){return this.Qb().toString()+":"+this.jd+":"+r(this.Nd.bf())};function Fb(a,b,c){this.le=a;this.error=b;this.path=c}Fb.prototype.Qb=function(){return this.path};Fb.prototype.pe=function(){return"cancel"}; +Fb.prototype.Lb=function(){return this.le.Lb(this)};Fb.prototype.toString=function(){return this.path.toString()+":cancel"};function B(a,b,c,d){this.type=a;this.Ha=b;this.Ua=c;this.De=d;this.Fd=void 0}function Gb(a){return new B(Hb,a)}var Hb="value";function Ib(a,b,c){this.Hb=a;this.kb=b;this.mb=c||null}h=Ib.prototype;h.wf=function(a){return"value"===a};h.createEvent=function(a,b){var c=b.n.g;return new Eb("value",this,new C(a.Ha,b.cc(),c))};h.Lb=function(a){var b=this.mb;if("cancel"===a.pe()){w(this.kb,"Raising a cancel event on a listener with no cancel callback");var c=this.kb;return function(){c.call(b,a.error)}}var d=this.Hb;return function(){d.call(b,a.Nd)}};h.Ye=function(a,b){return this.kb?new Fb(this,a,b):null}; +h.matches=function(a){return a instanceof Ib?a.Hb&&this.Hb?a.Hb===this.Hb&&a.mb===this.mb:!0:!1};h.hf=function(){return null!==this.Hb};function Jb(a,b,c){this.da=a;this.kb=b;this.mb=c}h=Jb.prototype;h.wf=function(a){a="children_added"===a?"child_added":a;return("children_removed"===a?"child_removed":a)in this.da};h.Ye=function(a,b){return this.kb?new Fb(this,a,b):null}; +h.createEvent=function(a,b){w(null!=a.Ua,"Child events should have a childName.");var c=b.cc().o(a.Ua);return new Eb(a.type,this,new C(a.Ha,c,b.n.g),a.Fd)};h.Lb=function(a){var b=this.mb;if("cancel"===a.pe()){w(this.kb,"Raising a cancel event on a listener with no cancel callback");var c=this.kb;return function(){c.call(b,a.error)}}var d=this.da[a.jd];return function(){d.call(b,a.Nd,a.Fd)}}; +h.matches=function(a){if(a instanceof Jb){if(!this.da||!a.da)return!0;if(this.mb===a.mb){var b=Kb(a.da);if(b===Kb(this.da)){if(1===b){var b=Lb(a.da),c=Lb(this.da);return c===b&&(!a.da[b]||!this.da[c]||a.da[b]===this.da[c])}return Mb(this.da,function(b,c){return a.da[c]===b})}}}return!1};h.hf=function(){return null!==this.da};function kb(a){for(var b=[],c=0,d=0;d=e&&(e-=55296,d++,w(de?b[c++]=e:(2048>e?b[c++]=e>>6|192:(65536>e?b[c++]=e>>12|224:(b[c++]=e>>18|240,b[c++]=e>>12&63|128),b[c++]=e>>6&63|128),b[c++]=e&63|128)}return b};function D(a,b,c,d){var e;dc&&(e=0===c?"none":"no more than "+c);if(e)throw Error(a+" failed: Was called with "+d+(1===d?" argument.":" arguments.")+" Expects "+e+".");}function F(a,b,c){var d="";switch(b){case 1:d=c?"first":"First";break;case 2:d=c?"second":"Second";break;case 3:d=c?"third":"Third";break;case 4:d=c?"fourth":"Fourth";break;default:throw Error("errorPrefix called with argumentNumber > 4. Need to update it?");}return a=a+" failed: "+(d+" argument ")} +function G(a,b,c,d){if((!d||m(c))&&!ha(c))throw Error(F(a,b,d)+"must be a valid function.");}function Nb(a,b,c){if(m(c)&&(!ia(c)||null===c))throw Error(F(a,b,!0)+"must be a valid context object.");};var Ob=/[\[\].#$\/\u0000-\u001F\u007F]/,Pb=/[\[\].#$\u0000-\u001F\u007F]/;function Qb(a){return p(a)&&0!==a.length&&!Ob.test(a)}function Rb(a){return null===a||p(a)||ga(a)&&!tb(a)||ia(a)&&s(a,".sv")}function Sb(a,b,c){c&&!m(b)||Tb(F(a,1,c),b)} +function Tb(a,b,c,d){c||(c=0);var e=d||[];if(!m(b))throw Error(a+"contains undefined"+Ub(e));if(ha(b))throw Error(a+"contains a function"+Ub(e)+" with contents: "+b.toString());if(tb(b))throw Error(a+"contains "+b.toString()+Ub(e));if(1E310485760/3&&10485760=this.g.compare(this.Vc,a)&&0>=this.g.compare(a,this.vc)};h.C=function(a,b,c,d,e){this.matches(new M(b,c))||(c=L);return this.re.C(a,b,c,d,e)};h.oa=function(a,b,c){b.M()&&(b=L);var d=b.Fb(this.g),d=d.Z(L),e=this;b.U(K,function(a,b){e.matches(new M(a,b))||(d=d.P(a,L))});return this.re.oa(a,d,c)}; +h.Z=function(a){return a};h.ya=function(){return!0};h.Mb=function(){return this.re};function jc(a,b){return vb(a.name,b.name)}function kc(a,b){return vb(a,b)};function lc(){}var mc={};function nc(a){return q(a.compare,a)}lc.prototype.jf=function(a,b){return 0!==this.compare(new M("[MIN_NAME]",a),new M("[MIN_NAME]",b))};lc.prototype.Ce=function(){return oc};function pc(a){this.Ub=a}ma(pc,lc);h=pc.prototype;h.ue=function(a){return!a.K(this.Ub).e()};h.compare=function(a,b){var c=a.Y.K(this.Ub),d=b.Y.K(this.Ub),c=c.he(d);return 0===c?vb(a.name,b.name):c};h.Ae=function(a,b){var c=N(a),c=L.P(this.Ub,c);return new M(b,c)}; +h.Be=function(){var a=L.P(this.Ub,qc);return new M("[MAX_NAME]",a)};h.toString=function(){return this.Ub};var K=new pc(".priority");function rc(){}ma(rc,lc);h=rc.prototype;h.compare=function(a,b){return vb(a.name,b.name)};h.ue=function(){throw gb("KeyIndex.isDefinedOn not expected to be called.");};h.jf=function(){return!1};h.Ce=function(){return oc};h.Be=function(){return new M("[MAX_NAME]",L)};h.Ae=function(a){w(p(a),"KeyIndex indexValue must always be a string.");return new M(a,L)}; +h.toString=function(){return".key"};var sc=new rc;function tc(){}tc.prototype.ef=function(){return null};tc.prototype.oe=function(){return null};var uc=new tc;function vc(a,b,c){this.Bf=a;this.Ia=b;this.zd=c}vc.prototype.ef=function(a){var b=this.Ia.F;if(wc(b,a))return b.j().K(a);b=null!=this.zd?new xc(this.zd,!0,!1):this.Ia.u();return this.Bf.Ta(a,b)};vc.prototype.oe=function(a,b,c){var d=null!=this.zd?this.zd:yc(this.Ia);a=this.Bf.ce(d,b,1,c,a);return 0===a.length?null:a[0]};function zc(){this.Za={}} +function dc(a,b){var c=b.type,d=b.Ua;w("child_added"==c||"child_changed"==c||"child_removed"==c,"Only child changes supported for tracking");w(".priority"!==d,"Only non-priority child changes can be tracked.");var e=t(a.Za,d);if(e){var f=e.type;if("child_added"==c&&"child_removed"==f)a.Za[d]=new B("child_changed",b.Ha,d,e.Ha);else if("child_removed"==c&&"child_added"==f)delete a.Za[d];else if("child_removed"==c&&"child_changed"==f)a.Za[d]=new B("child_removed",e.De,d);else if("child_changed"==c&& +"child_added"==f)a.Za[d]=new B("child_added",b.Ha,d);else if("child_changed"==c&&"child_changed"==f)a.Za[d]=new B("child_changed",b.Ha,d,e.De);else throw gb("Illegal combination of changes: "+b+" occurred after "+e);}else a.Za[d]=b};function M(a,b){this.name=a;this.Y=b}function Ac(a,b){return new M(a,b)};function Bc(a){this.ma=new ec(a);this.g=a.g;w(a.ka,"Only valid if limit has been set");this.sa=a.sa;this.zb=!(""===a.Eb?a.ia:"l"===a.Eb)}h=Bc.prototype;h.C=function(a,b,c,d,e){this.ma.matches(new M(b,c))||(c=L);return a.K(b).ea(c)?a:a.ub()=this.g.compare(this.ma.Vc,f):0>=this.g.compare(f,this.ma.vc))d=d.P(f.name,f.Y),e++;else break}}else{d=b.Fb(this.g);d=d.Z(L);var k,l,n;if(this.zb){b=d.gf(this.g);k=this.ma.vc;l=this.ma.Vc;var u=nc(this.g);n=function(a,b){return u(b,a)}}else b=d.Ob(this.g),k=this.ma.Vc, +l=this.ma.vc,n=nc(this.g);for(var e=0,x=!1;0=n(k,f)&&(x=!0),(g=x&&e=n(f,l))?e++:d=d.P(f.name,L)}return this.ma.Mb().oa(a,d,c)};h.Z=function(a){return a};h.ya=function(){return!0};h.Mb=function(){return this.ma.Mb()}; +function Cc(a,b,c,d,e,f){var g;if(a.zb){var k=nc(a.g);g=function(a,b){return k(b,a)}}else g=nc(a.g);w(b.ub()==a.sa,"");var l=new M(c,d),n=a.zb?Dc(b,a.g):Ec(b,a.g),u=a.ma.matches(l);if(b.Da(c)){var x=b.K(c),n=e.oe(a.g,n,a.zb);null!=n&&n.name==c&&(n=e.oe(a.g,n,a.zb));e=null==n?1:g(n,l);if(u&&!d.e()&&0<=e)return null!=f&&dc(f,new B("child_changed",d,c,x)),b.P(c,d);null!=f&&dc(f,new B("child_removed",x,c));b=b.P(c,L);return null!=n&&a.ma.matches(n)?(null!=f&&dc(f,new B("child_added",n.Y,n.name)),b.P(n.name, +n.Y)):b}return d.e()?b:u&&0<=g(n,l)?(null!=f&&(dc(f,new B("child_removed",n.Y,n.name)),dc(f,new B("child_added",d,c))),b.P(c,d).P(n.name,L)):b};function Fc(){this.uc=this.qa=this.jc=this.ia=this.ka=!1;this.sa=0;this.Eb="";this.zc=null;this.Wb="";this.yc=null;this.Tb="";this.g=K}var Gc=new Fc;function gc(a){w(a.ia,"Only valid if start has been set");return a.zc}function fc(a){w(a.ia,"Only valid if start has been set");return a.jc?a.Wb:"[MIN_NAME]"}function ic(a){w(a.qa,"Only valid if end has been set");return a.yc}function hc(a){w(a.qa,"Only valid if end has been set");return a.uc?a.Tb:"[MAX_NAME]"} +function Hc(a){var b=new Fc;b.ka=a.ka;b.sa=a.sa;b.ia=a.ia;b.zc=a.zc;b.jc=a.jc;b.Wb=a.Wb;b.qa=a.qa;b.yc=a.yc;b.uc=a.uc;b.Tb=a.Tb;b.g=a.g;return b}h=Fc.prototype;h.xe=function(a){var b=Hc(this);b.ka=!0;b.sa=a;b.Eb="";return b};h.ye=function(a){var b=Hc(this);b.ka=!0;b.sa=a;b.Eb="l";return b};h.ze=function(a){var b=Hc(this);b.ka=!0;b.sa=a;b.Eb="r";return b};h.Od=function(a,b){var c=Hc(this);c.ia=!0;m(a)||(a=null);c.zc=a;null!=b?(c.jc=!0,c.Wb=b):(c.jc=!1,c.Wb="");return c}; +h.hd=function(a,b){var c=Hc(this);c.qa=!0;m(a)||(a=null);c.yc=a;m(b)?(c.uc=!0,c.Tb=b):(c.Ig=!1,c.Tb="");return c};function Ic(a,b){var c=Hc(a);c.g=b;return c}function Jc(a){var b={};a.ia&&(b.sp=a.zc,a.jc&&(b.sn=a.Wb));a.qa&&(b.ep=a.yc,a.uc&&(b.en=a.Tb));if(a.ka){b.l=a.sa;var c=a.Eb;""===c&&(c=a.ia?"l":"r");b.vf=c}a.g!==K&&(b.i=a.g.toString());return b}function Kc(a){return!(a.ia||a.qa||a.ka)}h.toString=function(){return r(Jc(this))};function P(a,b,c,d){this.k=a;this.path=b;this.n=c;this.ac=d} +function Lc(a){var b=null,c=null;a.ia&&(b=gc(a));a.qa&&(c=ic(a));if(a.g===sc){if(a.ia){if("[MIN_NAME]"!=fc(a))throw Error("Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().");if(null!=b&&"string"!==typeof b)throw Error("Query: When ordering by key, the argument passed to startAt(), endAt(),or equalTo() must be a string.");}if(a.qa){if("[MAX_NAME]"!=hc(a))throw Error("Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().");if(null!= +c&&"string"!==typeof c)throw Error("Query: When ordering by key, the argument passed to startAt(), endAt(),or equalTo() must be a string.");}}else if(a.g===K){if(null!=b&&!Rb(b)||null!=c&&!Rb(c))throw Error("Query: When ordering by priority, the first argument passed to startAt(), endAt(), or equalTo() must be a valid priority value (null, a number, or a string).");}else if(w(a.g instanceof pc,"unknown index type."),null!=b&&"object"===typeof b||null!=c&&"object"===typeof c)throw Error("Query: First argument passed to startAt(), endAt(), or equalTo() cannot be an object."); +}function Mc(a){if(a.ia&&a.qa&&a.ka&&(!a.ka||""===a.Eb))throw Error("Query: Can't combine startAt(), endAt(), and limit(). Use limitToFirst() or limitToLast() instead.");}function Nc(a,b){if(!0===a.ac)throw Error(b+": You can't combine multiple orderBy calls.");}P.prototype.cc=function(){D("Query.ref",0,0,arguments.length);return new Q(this.k,this.path)};P.prototype.ref=P.prototype.cc; +P.prototype.vb=function(a,b,c,d){D("Query.on",2,4,arguments.length);Xb("Query.on",a,!1);G("Query.on",2,b,!1);var e=Oc("Query.on",c,d);if("value"===a)Pc(this.k,this,new Ib(b,e.cancel||null,e.Ka||null));else{var f={};f[a]=b;Pc(this.k,this,new Jb(f,e.cancel,e.Ka))}return b};P.prototype.on=P.prototype.vb; +P.prototype.Zb=function(a,b,c){D("Query.off",0,3,arguments.length);Xb("Query.off",a,!0);G("Query.off",2,b,!0);Nb("Query.off",3,c);var d=null,e=null;"value"===a?d=new Ib(b||null,null,c||null):a&&(b&&(e={},e[a]=b),d=new Jb(e,null,c||null));e=this.k;d=".info"===H(this.path)?e.qd.gb(this,d):e.N.gb(this,d);Qc(e.$,this.path,d)};P.prototype.off=P.prototype.Zb; +P.prototype.lg=function(a,b){function c(g){f&&(f=!1,e.Zb(a,c),b.call(d.Ka,g))}D("Query.once",2,4,arguments.length);Xb("Query.once",a,!1);G("Query.once",2,b,!1);var d=Oc("Query.once",arguments[2],arguments[3]),e=this,f=!0;this.vb(a,c,function(b){e.Zb(a,c);d.cancel&&d.cancel.call(d.Ka,b)})};P.prototype.once=P.prototype.lg; +P.prototype.xe=function(a){y("Query.limit() being deprecated. Please use Query.limitToFirst() or Query.limitToLast() instead.");D("Query.limit",1,1,arguments.length);if(!ga(a)||Math.floor(a)!==a||0>=a)throw Error("Query.limit: First argument must be a positive integer.");if(this.n.ka)throw Error("Query.limit: Limit was already set (by another call to limit, limitToFirst, orlimitToLast.");var b=this.n.xe(a);Mc(b);return new P(this.k,this.path,b,this.ac)};P.prototype.limit=P.prototype.xe; +P.prototype.ye=function(a){D("Query.limitToFirst",1,1,arguments.length);if(!ga(a)||Math.floor(a)!==a||0>=a)throw Error("Query.limitToFirst: First argument must be a positive integer.");if(this.n.ka)throw Error("Query.limitToFirst: Limit was already set (by another call to limit, limitToFirst, or limitToLast).");return new P(this.k,this.path,this.n.ye(a),this.ac)};P.prototype.limitToFirst=P.prototype.ye; +P.prototype.ze=function(a){D("Query.limitToLast",1,1,arguments.length);if(!ga(a)||Math.floor(a)!==a||0>=a)throw Error("Query.limitToLast: First argument must be a positive integer.");if(this.n.ka)throw Error("Query.limitToLast: Limit was already set (by another call to limit, limitToFirst, or limitToLast).");return new P(this.k,this.path,this.n.ze(a),this.ac)};P.prototype.limitToLast=P.prototype.ze; +P.prototype.mg=function(a){D("Query.orderByChild",1,1,arguments.length);if("$key"===a)throw Error('Query.orderByChild: "$key" is invalid. Use Query.orderByKey() instead.');if("$priority"===a)throw Error('Query.orderByChild: "$priority" is invalid. Use Query.orderByPriority() instead.');Yb("Query.orderByChild",1,a,!1);Nc(this,"Query.orderByChild");var b=Ic(this.n,new pc(a));Lc(b);return new P(this.k,this.path,b,!0)};P.prototype.orderByChild=P.prototype.mg; +P.prototype.ng=function(){D("Query.orderByKey",0,0,arguments.length);Nc(this,"Query.orderByKey");var a=Ic(this.n,sc);Lc(a);return new P(this.k,this.path,a,!0)};P.prototype.orderByKey=P.prototype.ng;P.prototype.og=function(){D("Query.orderByPriority",0,0,arguments.length);Nc(this,"Query.orderByPriority");var a=Ic(this.n,K);Lc(a);return new P(this.k,this.path,a,!0)};P.prototype.orderByPriority=P.prototype.og; +P.prototype.Od=function(a,b){D("Query.startAt",0,2,arguments.length);Sb("Query.startAt",a,!0);Yb("Query.startAt",2,b,!0);var c=this.n.Od(a,b);Mc(c);Lc(c);if(this.n.ia)throw Error("Query.startAt: Starting point was already set (by another call to startAt or equalTo).");m(a)||(b=a=null);return new P(this.k,this.path,c,this.ac)};P.prototype.startAt=P.prototype.Od; +P.prototype.hd=function(a,b){D("Query.endAt",0,2,arguments.length);Sb("Query.endAt",a,!0);Yb("Query.endAt",2,b,!0);var c=this.n.hd(a,b);Mc(c);Lc(c);if(this.n.qa)throw Error("Query.endAt: Ending point was already set (by another call to endAt or equalTo).");return new P(this.k,this.path,c,this.ac)};P.prototype.endAt=P.prototype.hd; +P.prototype.Tf=function(a,b){D("Query.equalTo",1,2,arguments.length);Sb("Query.equalTo",a,!1);Yb("Query.equalTo",2,b,!0);if(this.n.ia)throw Error("Query.equalTo: Starting point was already set (by another call to endAt or equalTo).");if(this.n.qa)throw Error("Query.equalTo: Ending point was already set (by another call to endAt or equalTo).");return this.Od(a,b).hd(a,b)};P.prototype.equalTo=P.prototype.Tf;P.prototype.Fa=function(){var a=yb(Jc(this.n));return"{}"===a?"default":a}; +function Oc(a,b,c){var d={cancel:null,Ka:null};if(b&&c)d.cancel=b,G(a,3,d.cancel,!0),d.Ka=c,Nb(a,4,d.Ka);else if(b)if("object"===typeof b&&null!==b)d.Ka=b;else if("function"===typeof b)d.cancel=b;else throw Error(F(a,3,!0)+" must either be a cancel callback or a context object.");return d};function R(a,b){if(1==arguments.length){this.w=a.split("/");for(var c=0,d=0;d=a.w.length?null:a.w[a.ca]}function Rc(a){return a.w.length-a.ca}function S(a){var b=a.ca;b=this.w.length)return null;for(var a=[],b=this.ca;b=this.w.length};var T=new R("");function U(a,b){var c=H(a);if(null===c)return b;if(c===H(b))return U(S(a),S(b));throw Error("INTERNAL ERROR: innerPath ("+b+") is not within outerPath ("+a+")");} +R.prototype.ea=function(a){if(Rc(this)!==Rc(a))return!1;for(var b=this.ca,c=a.ca;b<=this.w.length;b++,c++)if(this.w[b]!==a.w[c])return!1;return!0};R.prototype.contains=function(a){var b=this.ca,c=a.ca;if(Rc(this)>Rc(a))return!1;for(;bb?c=c.left:0c?d=d.left:0e)a=this.ve?a.left:a.right;else if(0===e){this.Na.push(a);break}else this.Na.push(a),a=this.ve?a.right:a.left} +function O(a){if(0===a.Na.length)return null;var b=a.Na.pop(),c;c=a.Id?a.Id(b.key,b.value):{key:b.key,value:b.value};if(a.ve)for(b=b.left;!b.e();)a.Na.push(b),b=b.right;else for(b=b.right;!b.e();)a.Na.push(b),b=b.left;return c}function dd(a){if(0===a.Na.length)return null;var b;b=a.Na;b=b[b.length-1];return a.Id?a.Id(b.key,b.value):{key:b.key,value:b.value}}function ed(a,b,c,d,e){this.key=a;this.value=b;this.color=null!=c?c:!0;this.left=null!=d?d:ad;this.right=null!=e?e:ad}h=ed.prototype; +h.X=function(a,b,c,d,e){return new ed(null!=a?a:this.key,null!=b?b:this.value,null!=c?c:this.color,null!=d?d:this.left,null!=e?e:this.right)};h.count=function(){return this.left.count()+1+this.right.count()};h.e=function(){return!1};h.fa=function(a){return this.left.fa(a)||a(this.key,this.value)||this.right.fa(a)};function gd(a){return a.left.e()?a:gd(a.left)}h.Hc=function(){return gd(this).key};h.Xb=function(){return this.right.e()?this.key:this.right.Xb()}; +h.La=function(a,b,c){var d,e;e=this;d=c(a,e.key);e=0>d?e.X(null,null,null,e.left.La(a,b,c),null):0===d?e.X(null,b,null,null,null):e.X(null,null,null,null,e.right.La(a,b,c));return hd(e)};function id(a){if(a.left.e())return ad;a.left.ba()||a.left.left.ba()||(a=jd(a));a=a.X(null,null,null,id(a.left),null);return hd(a)} +h.remove=function(a,b){var c,d;c=this;if(0>b(a,c.key))c.left.e()||c.left.ba()||c.left.left.ba()||(c=jd(c)),c=c.X(null,null,null,c.left.remove(a,b),null);else{c.left.ba()&&(c=kd(c));c.right.e()||c.right.ba()||c.right.left.ba()||(c=ld(c),c.left.left.ba()&&(c=kd(c),c=ld(c)));if(0===b(a,c.key)){if(c.right.e())return ad;d=gd(c.right);c=c.X(d.key,d.value,null,null,id(c.right))}c=c.X(null,null,null,null,c.right.remove(a,b))}return hd(c)};h.ba=function(){return this.color}; +function hd(a){a.right.ba()&&!a.left.ba()&&(a=md(a));a.left.ba()&&a.left.left.ba()&&(a=kd(a));a.left.ba()&&a.right.ba()&&(a=ld(a));return a}function jd(a){a=ld(a);a.right.left.ba()&&(a=a.X(null,null,null,null,kd(a.right)),a=md(a),a=ld(a));return a}function md(a){return a.right.X(null,null,a.color,a.X(null,null,!0,null,a.right.left),null)}function kd(a){return a.left.X(null,null,a.color,null,a.X(null,null,!0,a.left.right,null))} +function ld(a){return a.X(null,null,!a.color,a.left.X(null,null,!a.left.color,null,null),a.right.X(null,null,!a.right.color,null,null))}function nd(){}h=nd.prototype;h.X=function(){return this};h.La=function(a,b){return new ed(a,b,null)};h.remove=function(){return this};h.count=function(){return 0};h.e=function(){return!0};h.fa=function(){return!1};h.Hc=function(){return null};h.Xb=function(){return null};h.ba=function(){return!1};var ad=new nd;function od(a,b){this.D=a;w(m(this.D)&&null!==this.D,"LeafNode shouldn't be created with null/undefined value.");this.ha=b||L;pd(this.ha);this.sb=null}h=od.prototype;h.M=function(){return!0};h.L=function(){return this.ha};h.Z=function(a){return new od(this.D,a)};h.K=function(a){return".priority"===a?this.ha:L};h.ra=function(a){return a.e()?this:".priority"===H(a)?this.ha:L};h.Da=function(){return!1};h.ff=function(){return null}; +h.P=function(a,b){return".priority"===a?this.Z(b):b.e()&&".priority"!==a?this:L.P(a,b).Z(this.ha)};h.C=function(a,b){var c=H(a);if(null===c)return b;if(b.e()&&".priority"!==c)return this;w(".priority"!==c||1===Rc(a),".priority must be the last token in a path");return this.P(c,L.C(S(a),b))};h.e=function(){return!1};h.ub=function(){return 0};h.I=function(a){return a&&!this.L().e()?{".value":this.za(),".priority":this.L().I()}:this.za()}; +h.hash=function(){if(null===this.sb){var a="";this.ha.e()||(a+="priority:"+qd(this.ha.I())+":");var b=typeof this.D,a=a+(b+":"),a="number"===b?a+Bb(this.D):a+this.D;this.sb=jb(a)}return this.sb};h.za=function(){return this.D};h.he=function(a){if(a===L)return 1;if(a instanceof V)return-1;w(a.M(),"Unknown node type");var b=typeof a.D,c=typeof this.D,d=Ha(rd,b),e=Ha(rd,c);w(0<=d,"Unknown leaf type: "+b);w(0<=e,"Unknown leaf type: "+c);return d===e?"object"===c?0:this.Db.compare(d,a);)O(c),d=dd(c);return c};h.gf=function(a){return this.Rb(a.Be(),a)};h.Rb=function(a,b){var c=zd(this,b);if(c)return c.Rb(a,function(a){return a});for(var c=this.m.Rb(a.name,Ac),d=dd(c);null!=d&&0=a.length){var b=Number(a);if(!isNaN(b)){e.Te=b;e.frames=[];a=null;break a}}e.Te=1;e.frames=[]}null!==a&&de(e,a)}};this.ta.onerror=function(a){e.f("WebSocket error. Closing connection.");(a=a.message||a.data)&&e.f(a);e.eb()}};ae.prototype.start=function(){}; +ae.isAvailable=function(){var a=!1;if("undefined"!==typeof navigator&&navigator.userAgent){var b=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/);b&&1parseFloat(b[1])&&(a=!0)}return!a&&null!==$d&&!be};ae.responsesRequiredToBeHealthy=2;ae.healthyTimeout=3E4;h=ae.prototype;h.sd=function(){za.remove("previous_websocket_failure")};function de(a,b){a.frames.push(b);if(a.frames.length==a.Te){var c=a.frames.join("");a.frames=null;c=ta(c);a.hg(c)}} +h.send=function(a){ce(this);a=r(a);this.jb+=a.length;Td(this.Ra,"bytes_sent",a.length);a=zb(a,16384);1document.domain="'+document.domain+'";\x3c/script>');a=""+a+"";try{this.Ba.ab.open(),this.Ba.ab.write(a),this.Ba.ab.close()}catch(f){ib("frame writing exception"),f.stack&&ib(f.stack),ib(f)}} +me.prototype.close=function(){this.ae=!1;if(this.Ba){this.Ba.ab.body.innerHTML="";var a=this;setTimeout(function(){null!==a.Ba&&(document.body.removeChild(a.Ba),a.Ba=null)},Math.floor(0))}var b=this.fb;b&&(this.fb=null,b())}; +function pe(a){if(a.ae&&a.Kd&&a.Ie.count()<(0=a.Pc[0].af.length+30+c.length){var e=a.Pc.shift(),c=c+"&seg"+d+"="+e.tg+"&ts"+d+"="+e.Bg+"&d"+d+"="+e.af;d++}else break;qe(a,b+c,a.ke);return!0}return!1}function qe(a,b,c){function d(){a.Ie.remove(c);pe(a)}a.Ie.add(c);var e=setTimeout(d,Math.floor(25E3));oe(a,b,function(){clearTimeout(e);d()})} +function oe(a,b,c){setTimeout(function(){try{if(a.Kd){var d=a.Ba.ab.createElement("script");d.type="text/javascript";d.async=!0;d.src=b;d.onload=d.onreadystatechange=function(){var a=d.readyState;a&&"loaded"!==a&&"complete"!==a||(d.onload=d.onreadystatechange=null,d.parentNode&&d.parentNode.removeChild(d),c())};d.onerror=function(){ib("Long-poll script failed to load: "+b);a.Kd=!1;a.close()};a.Ba.ab.body.appendChild(d)}}catch(e){}},Math.floor(1))};function re(a){se(this,a)}var te=[je,ae];function se(a,b){var c=ae&&ae.isAvailable(),d=c&&!(za.lf||!0===za.get("previous_websocket_failure"));b.Dg&&(c||y("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),d=!0);if(d)a.Xc=[ae];else{var e=a.Xc=[];Ab(te,function(a,b){b&&b.isAvailable()&&e.push(b)})}}function ue(a){if(0=a.yf?(a.f("Secondary connection is healthy."),a.rb=!0,a.B.sd(),a.B.start(),a.f("sending client ack on secondary"),a.B.send({t:"c",d:{t:"a",d:{}}}),a.f("Ending transmission on primary"),a.J.send({t:"c",d:{t:"n",d:{}}}),a.Yc=a.B,Be(a)):(a.f("sending ping on secondary."),a.B.send({t:"c",d:{t:"p",d:{}}}))}ve.prototype.xd=function(a){De(this);this.$b(a)};function De(a){a.rb||(a.Ke--,0>=a.Ke&&(a.f("Primary connection is healthy."),a.rb=!0,a.J.sd()))} +function Ae(a,b){a.B=new b("c:"+a.id+":"+a.Xe++,a.O,a.Md);a.yf=b.responsesRequiredToBeHealthy||0;a.B.open(xe(a,a.B),ye(a,a.B));setTimeout(function(){a.B&&(a.f("Timed out trying to upgrade."),a.B.close())},Math.floor(6E4))}function ze(a,b,c){a.f("Realtime connection established.");a.J=b;a.Qa=1;a.Jc&&(a.Jc(c),a.Jc=null);0===a.Ke?(a.f("Primary connection is healthy."),a.rb=!0):setTimeout(function(){Ee(a)},Math.floor(5E3))} +function Ee(a){a.rb||1!==a.Qa||(a.f("sending ping on primary."),Ge(a,{t:"c",d:{t:"p",d:{}}}))}function Ge(a,b){if(1!==a.Qa)throw"Connection is not connected";a.Yc.send(b)}ve.prototype.close=function(){2!==this.Qa&&(this.f("Closing realtime connection."),this.Qa=2,Ce(this),this.ga&&(this.ga(),this.ga=null))};function Ce(a){a.f("Shutting down all connections");a.J&&(a.J.close(),a.J=null);a.B&&(a.B.close(),a.B=null);a.nd&&(clearTimeout(a.nd),a.nd=null)};function He(a){var b={},c={},d={},e="";try{var f=a.split("."),b=ta(hb(f[0])||""),c=ta(hb(f[1])||""),e=f[2],d=c.d||{};delete c.d}catch(g){}return{Gg:b,fe:c,data:d,xg:e}}function Ie(a){a=He(a).fe;return"object"===typeof a&&a.hasOwnProperty("iat")?t(a,"iat"):null}function Je(a){a=He(a);var b=a.fe;return!!a.xg&&!!b&&"object"===typeof b&&b.hasOwnProperty("iat")};function Ke(a,b,c,d){this.id=Le++;this.f=pb("p:"+this.id+":");this.Cb=!0;this.Aa={};this.la=[];this.Mc=0;this.Ic=[];this.ja=!1;this.Wa=1E3;this.td=3E5;this.yd=b;this.wd=c;this.He=d;this.O=a;this.Oe=null;this.Rc={};this.sg=0;this.Cc=this.we=null;Me(this,0);Id.Nb().vb("visible",this.kg,this);-1===a.host.indexOf("fblocal")&&Jd.Nb().vb("online",this.ig,this)}var Le=0,Ne=0;h=Ke.prototype; +h.Ca=function(a,b,c){var d=++this.sg;a={r:d,a:a,b:b};this.f(r(a));w(this.ja,"sendRequest call when we're not connected not allowed.");this.Oa.Ca(a);c&&(this.Rc[d]=c)};function Oe(a,b,c,d,e){var f=b.Fa(),g=b.path.toString();a.f("Listen called for "+g+" "+f);a.Aa[g]=a.Aa[g]||{};w(!a.Aa[g][f],"listen() called twice for same path/queryId.");b={H:e,md:c,pg:Jc(b.n),tag:d};a.Aa[g][f]=b;a.ja&&Pe(a,g,f,b)} +function Pe(a,b,c,d){a.f("Listen on "+b+" for "+c);var e={p:b};d.tag&&(e.q=d.pg,e.t=d.tag);e.h=d.md();a.Ca("q",e,function(e){if((a.Aa[b]&&a.Aa[b][c])===d){a.f("listen response",e);var g=e.s;"ok"!==g&&Qe(a,b,c);e=e.d;d.H&&d.H(g,e)}})}h.Q=function(a,b,c){this.Ib={Rf:a,cf:!1,pc:b,ad:c};this.f("Authenticating using credential: "+a);Re(this);(b=40==a.length)||(a=He(a).fe,b="object"===typeof a&&!0===t(a,"admin"));b&&(this.f("Admin auth credential detected. Reducing max reconnect time."),this.td=3E4)}; +h.Ue=function(a){delete this.Ib;this.ja&&this.Ca("unauth",{},function(b){a(b.s,b.d)})};function Re(a){var b=a.Ib;a.ja&&b&&a.Ca("auth",{cred:b.Rf},function(c){var d=c.s;c=c.d||"error";"ok"!==d&&a.Ib===b&&delete a.Ib;b.cf?"ok"!==d&&b.ad&&b.ad(d,c):(b.cf=!0,b.pc&&b.pc(d,c))})}function Se(a,b,c,d){a.ja?Te(a,"o",b,c,d):a.Ic.push({Oc:b,action:"o",data:c,H:d})}function Ue(a,b,c,d){a.ja?Te(a,"om",b,c,d):a.Ic.push({Oc:b,action:"om",data:c,H:d})} +h.Fe=function(a,b){this.ja?Te(this,"oc",a,null,b):this.Ic.push({Oc:a,action:"oc",data:null,H:b})};function Te(a,b,c,d,e){c={p:c,d:d};a.f("onDisconnect "+b,c);a.Ca(b,c,function(a){e&&setTimeout(function(){e(a.s,a.d)},Math.floor(0))})}h.put=function(a,b,c,d){Ve(this,"p",a,b,c,d)};function We(a,b,c,d){Ve(a,"m",b,c,d,void 0)}function Ve(a,b,c,d,e,f){d={p:c,d:d};m(f)&&(d.h=f);a.la.push({action:b,uf:d,H:e});a.Mc++;b=a.la.length-1;a.ja?Xe(a,b):a.f("Buffering put: "+c)} +function Xe(a,b){var c=a.la[b].action,d=a.la[b].uf,e=a.la[b].H;a.la[b].qg=a.ja;a.Ca(c,d,function(d){a.f(c+" response",d);delete a.la[b];a.Mc--;0===a.Mc&&(a.la=[]);e&&e(d.s,d.d)})} +h.xd=function(a){if("r"in a){this.f("from server: "+r(a));var b=a.r,c=this.Rc[b];c&&(delete this.Rc[b],c(a.b))}else{if("error"in a)throw"A server-side error has occurred: "+a.error;"a"in a&&(b=a.a,c=a.b,this.f("handleServerMessage",b,c),"d"===b?this.yd(c.p,c.d,!1,c.t):"m"===b?this.yd(c.p,c.d,!0,c.t):"c"===b?Ye(this,c.p,c.q):"ac"===b?(a=c.s,b=c.d,c=this.Ib,delete this.Ib,c&&c.ad&&c.ad(a,b)):"sd"===b?this.Oe?this.Oe(c):"msg"in c&&"undefined"!==typeof console&&console.log("FIREBASE: "+c.msg.replace("\n", +"\nFIREBASE: ")):qb("Unrecognized action received from server: "+r(b)+"\nAre you using the latest client?"))}};h.Jc=function(a){this.f("connection ready");this.ja=!0;this.Cc=(new Date).getTime();this.He({serverTimeOffset:a-(new Date).getTime()});Ze(this);this.wd(!0)};function Me(a,b){w(!a.Oa,"Scheduling a connect when we're already connected/ing?");a.Kb&&clearTimeout(a.Kb);a.Kb=setTimeout(function(){a.Kb=null;$e(a)},Math.floor(b))} +h.kg=function(a){a&&!this.lc&&this.Wa===this.td&&(this.f("Window became visible. Reducing delay."),this.Wa=1E3,this.Oa||Me(this,0));this.lc=a};h.ig=function(a){a?(this.f("Browser went online. Reconnecting."),this.Wa=1E3,this.Cb=!0,this.Oa||Me(this,0)):(this.f("Browser went offline. Killing connection; don't reconnect."),this.Cb=!1,this.Oa&&this.Oa.close())}; +h.of=function(){this.f("data client disconnected");this.ja=!1;this.Oa=null;for(var a=0;ae.status){try{a=ta(e.responseText)}catch(b){}c(null,a)}else 500<=e.status&&600>e.status?c(W("SERVER_ERROR")):c(W("NETWORK_ERROR"));c=null;rf(window,"beforeunload",d)}};if("GET"===f)a+=(/\?/.test(a)?"":"?")+uf(b),g=null;else{var k=this.options.headers.content_type; +"application/json"===k&&(g=r(b));"application/x-www-form-urlencoded"===k&&(g=uf(b))}e.open(f,a,!0);a={"X-Requested-With":"XMLHttpRequest",Accept:"application/json;text/plain"};Rd(a,this.options.headers);for(var l in a)e.setRequestHeader(l,a[l]);e.send(g)};yf.isAvailable=function(){return!!window.XMLHttpRequest&&"string"===typeof(new XMLHttpRequest).responseType&&(!(navigator.userAgent.match(/MSIE/)||navigator.userAgent.match(/Trident/))||xf())};yf.prototype.rc=function(){return"json"};function zf(a){a=a||{};this.Sc=Ga()+Ga()+Ga();this.pf=a||{}} +zf.prototype.open=function(a,b,c){function d(){c&&(c(W("USER_CANCELLED")),c=null)}var e=this,f=sb(kf),g;b.requestId=this.Sc;b.redirectTo=f.scheme+"://"+f.host+"/blank/page.html";a+=/\?/.test(a)?"":"?";a+=uf(b);(g=window.open(a,"_blank","location=no"))&&ha(g.addEventListener)?(g.addEventListener("loadstart",function(a){var b;if(b=a&&a.url)a:{var n=a.url;try{var u=document.createElement("a");u.href=n;b=u.host===f.host&&"/blank/page.html"===u.pathname;break a}catch(x){}b=!1}b&&(a=tf(a.url),g.removeEventListener("exit", +d),g.close(),a=new lf(null,null,{requestId:e.Sc,requestKey:a}),e.pf.requestWithCredential("/auth/session",a,c),c=null)}),g.addEventListener("exit",d)):c(W("TRANSPORT_UNAVAILABLE"))};zf.isAvailable=function(){return wf()};zf.prototype.rc=function(){return"redirect"};function Af(a){a=a||{};if(!a.window_features||-1!==navigator.userAgent.indexOf("Fennec/")||-1!==navigator.userAgent.indexOf("Firefox/")&&-1!==navigator.userAgent.indexOf("Android"))a.window_features=void 0;a.window_name||(a.window_name="_blank");a.relay_url||(a.relay_url=vf()+"/auth/channel");this.options=a} +Af.prototype.open=function(a,b,c){function d(a){g&&(document.body.removeChild(g),g=void 0);u&&(u=clearInterval(u));rf(window,"message",e);rf(window,"unload",d);if(n&&!a)try{n.close()}catch(b){k.postMessage("die",l)}n=k=void 0}function e(a){if(a.origin===l)try{var b=ta(a.data);"ready"===b.a?k.postMessage(x,l):"error"===b.a?(d(!1),c&&(c(b.d),c=null)):"response"===b.a&&(d(b.forceKeepWindowOpen),c&&(c(null,b.d),c=null))}catch(e){}}var f=xf(),g,k,l=sf(a);if(l!==sf(this.options.relay_url))c&&setTimeout(function(){c(Error("invalid arguments: origin of url and relay_url must match"))}, +0);else{f&&(g=document.createElement("iframe"),g.setAttribute("src",this.options.relay_url),g.style.display="none",g.setAttribute("name","__winchan_relay_frame"),document.body.appendChild(g),k=g.contentWindow);a+=(/\?/.test(a)?"":"?")+uf(b);var n=window.open(a,this.options.window_name,this.options.window_features);k||(k=n);var u=setInterval(function(){n&&n.closed&&(d(!1),c&&(c(W("USER_CANCELLED")),c=null))},500),x=r({a:"request",d:b});qf(window,"unload",d);qf(window,"message",e)}}; +Af.isAvailable=function(){return"postMessage"in window&&!/^file:\//.test(location.href)&&!(wf()||navigator.userAgent.match(/Windows Phone/)||window.Windows&&/^ms-appx:/.test(location.href)||navigator.userAgent.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i)||navigator.userAgent.match(/CriOS/)||navigator.userAgent.match(/Twitter for iPhone/)||navigator.userAgent.match(/FBAN\/FBIOS/)||window.navigator.standalone)&&!navigator.userAgent.match(/PhantomJS/)};Af.prototype.rc=function(){return"popup"};function Bf(a){a=a||{};a.callback_parameter||(a.callback_parameter="callback");this.options=a;window.__firebase_auth_jsonp=window.__firebase_auth_jsonp||{}} +Bf.prototype.open=function(a,b,c){function d(){c&&(c(W("REQUEST_INTERRUPTED")),c=null)}function e(){setTimeout(function(){window.__firebase_auth_jsonp[f]=void 0;Od(window.__firebase_auth_jsonp)&&(window.__firebase_auth_jsonp=void 0);try{var a=document.getElementById(f);a&&a.parentNode.removeChild(a)}catch(b){}},1);rf(window,"beforeunload",d)}var f="fn"+(new Date).getTime()+Math.floor(99999*Math.random());b[this.options.callback_parameter]="__firebase_auth_jsonp."+f;a+=(/\?/.test(a)?"":"?")+uf(b); +qf(window,"beforeunload",d);window.__firebase_auth_jsonp[f]=function(a){c&&(c(null,a),c=null);e()};Cf(f,a,c)}; +function Cf(a,b,c){setTimeout(function(){try{var d=document.createElement("script");d.type="text/javascript";d.id=a;d.async=!0;d.src=b;d.onerror=function(){var b=document.getElementById(a);null!==b&&b.parentNode.removeChild(b);c&&c(W("NETWORK_ERROR"))};var e=document.getElementsByTagName("head");(e&&0!=e.length?e[0]:document.documentElement).appendChild(d)}catch(f){c&&c(W("NETWORK_ERROR"))}},0)}Bf.isAvailable=function(){return!wf()};Bf.prototype.rc=function(){return"json"};function Df(a,b){this.Je=["session",a.Dd,a.tb].join(":");this.Rd=b}Df.prototype.set=function(a,b){if(!b)if(this.Rd.length)b=this.Rd[0];else throw Error("fb.login.SessionManager : No storage options available!");b.set(this.Je,a)};Df.prototype.get=function(){var a=Ka(this.Rd,q(this.Zf,this)),a=Ja(a,function(a){return null!==a});Ra(a,function(a,c){return Ie(c.token)-Ie(a.token)});return 0=b&&Wg(g,c.path)?d=!1:c.path.contains(g.path)&&(e=!0));f--}if(d){if(e)this.T=Xg(this.wa,Yg,T),this.Dc=0f.Dc,"Stacking an older write on top of newer ones");m(g)||(g=!0);f.wa.push({path:b,Ga:c,Zd:d,visible:g});g&&(f.T=Pg(f.T,b,c));f.Dc=d;return e?ih(a,new $g(bh,b,c)):[]}function jh(a,b,c,d){var e=a.xb;w(d>e.Dc,"Stacking an older merge on top of newer ones");e.wa.push({path:b,children:c,Zd:d,visible:!0});e.T=Qg(e.T,b,c);e.Dc=d;c=yg(c);return ih(a,new dh(bh,b,c))} +function kh(a,b,c){c=c||!1;b=a.xb.Gd(b);return null==b?[]:ih(a,new ah(b,c))}function lh(a,b,c){c=yg(c);return ih(a,new dh(fh,b,c))}function mh(a,b,c,d){d=Pd(a.Wc,"_"+d);if(null!=d){var e=nh(d);d=e.path;e=e.yb;b=U(d,b);c=new $g(new eh(!1,!0,e,!0),b,c);return oh(a,d,c)}return[]}function ph(a,b,c,d){if(d=Pd(a.Wc,"_"+d)){var e=nh(d);d=e.path;e=e.yb;b=U(d,b);c=yg(c);c=new dh(new eh(!1,!0,e,!0),b,c);return oh(a,d,c)}return[]} +gh.prototype.Gb=function(a,b){var c=a.path,d=null,e=!1;Fg(this.na,c,function(a,b){var f=U(a,c);d=b.bb(f);e=e||null!=Kg(b);return!d});var f=this.na.get(c);f?(e=e||null!=Kg(f),d=d||f.bb(T)):(f=new Jg,this.na=this.na.set(c,f));var g;null!=d?g=!0:(g=!1,d=L,Ig(this.na.subtree(c),function(a,b){var c=b.bb(T);c&&(d=d.P(a,c))}));var k=null!=Mg(f,a);if(!k&&!Kc(a.n)){var l=qh(a);w(!(l in this.bc),"View does not exist, but we have a tag");var n=rh++;this.bc[l]=n;this.Wc["_"+n]=l}g=f.Gb(a,b,new Zg(c,this.xb), +d,g);k||e||(f=Mg(f,a),g=g.concat(sh(this,a,f)));return g}; +gh.prototype.gb=function(a,b,c){var d=a.path,e=this.na.get(d),f=[];if(e&&("default"===a.Fa()||null!=Mg(e,a))){f=e.gb(a,b,c);e.e()&&(this.na=this.na.remove(d));e=f.rg;f=f.Vf;b=-1!==Oa(e,function(a){return Kc(a.n)});var g=Dg(this.na,d,function(a,b){return null!=Kg(b)});if(b&&!g&&(d=this.na.subtree(d),!d.e()))for(var d=th(d),k=0;kf;f++)b[f]=Math.floor(64*Math.random());for(f=0;12>f;f++)c+="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz".charAt(b[f]);w(20===c.length,"NextPushId: Length should be 20."); +return c}}();function Q(a,b){var c,d,e;if(a instanceof zh)c=a,d=b;else{D("new Firebase",1,2,arguments.length);d=sb(arguments[0]);c=d.Ag;"firebase"===d.domain&&rb(d.host+" is no longer supported. Please use .firebaseio.com instead");c||rb("Cannot parse Firebase url. Please use https://.firebaseio.com");d.Ab||"undefined"!==typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&y("Insecure Firebase access from a secure page. Please use https in calls to new Firebase()."); +c=new Ba(d.host,d.Ab,c,"ws"===d.scheme||"wss"===d.scheme);d=new R(d.Oc);e=d.toString();var f;!(f=!p(c.host)||0===c.host.length||!Qb(c.tb))&&(f=0!==e.length)&&(e&&(e=e.replace(/^\/*\.info(\/|$)/,"/")),f=!(p(e)&&0!==e.length&&!Pb.test(e)));if(f)throw Error(F("new Firebase",1,!1)+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".');if(b)if(b instanceof X)e=b;else if(p(b))e=X.Nb(),c.Dd=b;else throw Error("Expected a valid Firebase.Context for second argument to new Firebase()"); +else e=X.Nb();f=c.toString();var g=t(e.ec,f);g||(g=new zh(c),e.ec[f]=g);c=g}P.call(this,c,d,Gc,!1)}ma(Q,P);"object"===typeof module&&module.exports?module.exports=Q:"function"==typeof aa.define&&aa.define.amd?aa.define(function(){return Q}):aa.Firebase=Q;Q.prototype.name=function(){y("Firebase.name() being deprecated. Please use Firebase.key() instead.");D("Firebase.name",0,0,arguments.length);return this.key()};Q.prototype.name=Q.prototype.name; +Q.prototype.key=function(){D("Firebase.key",0,0,arguments.length);return this.path.e()?null:Sc(this.path)};Q.prototype.key=Q.prototype.key;Q.prototype.o=function(a){D("Firebase.child",1,1,arguments.length);if(ga(a))a=String(a);else if(!(a instanceof R))if(null===H(this.path)){var b=a;b&&(b=b.replace(/^\/*\.info(\/|$)/,"/"));Zb("Firebase.child",b)}else Zb("Firebase.child",a);return new Q(this.k,this.path.o(a))};Q.prototype.child=Q.prototype.o; +Q.prototype.parent=function(){D("Firebase.parent",0,0,arguments.length);var a=this.path.parent();return null===a?null:new Q(this.k,a)};Q.prototype.parent=Q.prototype.parent;Q.prototype.root=function(){D("Firebase.ref",0,0,arguments.length);for(var a=this;null!==a.parent();)a=a.parent();return a};Q.prototype.root=Q.prototype.root; +Q.prototype.toString=function(){D("Firebase.toString",0,0,arguments.length);var a;if(null===this.parent())a=this.k.toString();else{a=this.parent().toString()+"/";var b=this.key();a+=encodeURIComponent(String(b))}return a};Q.prototype.toString=Q.prototype.toString;Q.prototype.set=function(a,b){D("Firebase.set",1,2,arguments.length);$b("Firebase.set",this.path);Sb("Firebase.set",a,!1);G("Firebase.set",2,b,!0);this.k.Bb(this.path,a,null,b||null)};Q.prototype.set=Q.prototype.set; +Q.prototype.update=function(a,b){D("Firebase.update",1,2,arguments.length);$b("Firebase.update",this.path);if(ea(a)){for(var c={},d=0;d + + + ng2do + + + + + + + Loading... + + + \ No newline at end of file diff --git a/angular2/package.json b/angular2/package.json new file mode 100644 index 0000000..5550dcc --- /dev/null +++ b/angular2/package.json @@ -0,0 +1,20 @@ +{ + "name": "typescript-angular2", + "version": "1.0.0", + "description": "Angular 2/TypeScript demo", + "repository": { + "type": "git", + "url": "https://github.com/Microsoft/TypeScriptSamples.git" + }, + "dependencies": { + "angular2": "2.0.0-alpha.44", + "systemjs": "0.19.5", + "http-server": "0.8.0" + }, + "devDependencies": { + "typescript": "^1.5.3" + }, + "scripts": { + "start": "node node_modules/typescript/lib/tsc.js && node node_modules/http-server/bin/http-server -o" + } +} \ No newline at end of file diff --git a/angular2/todo.html b/angular2/todo.html new file mode 100644 index 0000000..9aad309 --- /dev/null +++ b/angular2/todo.html @@ -0,0 +1,71 @@ + + +
+ + + +
+ + + +
    + +
  • + +
    + + + + + + +
    + +
    + + + +
    + +
  • +
+ +
+ + + +
+ +
+

Double-click to edit a todo

+

Created by David East

+
diff --git a/angular2/tsconfig.json b/angular2/tsconfig.json new file mode 100644 index 0000000..de30b3e --- /dev/null +++ b/angular2/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "module": "commonjs", + "target": "es5" + }, + "files": [ + "app/todo.ts" + ] +} \ No newline at end of file diff --git a/async/.gitignore b/async/.gitignore new file mode 100644 index 0000000..806b91f --- /dev/null +++ b/async/.gitignore @@ -0,0 +1,3 @@ +lib/ +!src/lib/ +.vscode/ \ No newline at end of file diff --git a/async/README.md b/async/README.md new file mode 100644 index 0000000..fd182c8 --- /dev/null +++ b/async/README.md @@ -0,0 +1,27 @@ +# Async Functions + +*Async Functions* are functions that can suspend their execution to wait for the completion of an +asynchronous operation. This allows complex algorithms that require asynchronous control flow to +be written sequentially. + +This sample uses *Async Functions* to query the GitHub API to view information about recent pull +requests. + +This sample requires a minimum of NodeJS v4.0.0. + +**Fetch dependencies** +``` +npm install +``` + +**Run** +``` +npm test +``` + +**Environment variables** + +| Name | Description | +|:------------------|:----------------------------------------------------------------------------| +| GITHUB_TOKEN | The Authentication token to use for GitHub API Requests. (Optional) | +| GITHUB_REPOSITORY | The GitHub repository to use for queries. (Default: "Microsoft/TypeScript") | \ No newline at end of file diff --git a/async/bin/ts-async-github-sample b/async/bin/ts-async-github-sample new file mode 100644 index 0000000..c1cabfa --- /dev/null +++ b/async/bin/ts-async-github-sample @@ -0,0 +1,2 @@ +#!/usr/bin/env node +require("../lib/index.js"); \ No newline at end of file diff --git a/async/gulpfile.js b/async/gulpfile.js new file mode 100644 index 0000000..06da741 --- /dev/null +++ b/async/gulpfile.js @@ -0,0 +1,71 @@ +var gulp = require('gulp') + , sourcemaps = require('gulp-sourcemaps') + , ts = require('gulp-typescript') + , typescript = require('typescript') + , del = require('del') + , merge = require('merge2') + , path = require('path') + , spawn = require('child_process').spawn; + +var lib = { + project: ts.createProject('./src/lib/tsconfig.json', { typescript: typescript }), + bin: "./bin/ts-async-github-sample", + main: "./lib/github", + base: "./src/lib/", + dest: "./lib/", + src: ["./src/lib/**/*.ts"], + out: ["./lib/**/*"] +}; + +gulp.task("clean:lib", clean(lib)); +gulp.task("clean", ["clean:lib"]); +gulp.task("build:lib", build(lib)); +gulp.task("build", ["build:lib"]); +gulp.task("test", ["build"], test(lib)); +gulp.task("watch:lib", ["build:lib"], watch(src(lib), ["build:lib"])); +gulp.task("watch", ["build", "test"], watch(src(lib), ["test"])); +gulp.task("default", ["build"]); + +function src() { + return Array.from(arguments).reduce(function (ar, opts) { + return ar.concat(opts.src); + }, []); +} + +function clean(opts) { + return function (done) { + del(opts.out, done); + }; +} + +function build(opts) { + return function () { + var tee = gulp + .src(opts.src, { base: opts.base }) + .pipe(sourcemaps.init()) + .pipe(ts(opts.project)); + return merge([ + tee.dts + .pipe(gulp.dest(opts.dest)), + tee.js + .pipe(sourcemaps.write('.', { includeContent: false, sourceRoot: path.relative(opts.dest, opts.base) })) + .pipe(gulp.dest(opts.dest)) + ]); + }; +} + +function test(opts) { + return function (done) { + var args = [opts.bin]; + console.log("Executing test..."); + spawn(process.argv[0], args, { stdio: "inherit" }).on("exit", function (code) { + done(code !== 0 ? "Error executing script." : undefined); + }); + }; +} + +function watch(src, tasks) { + return function () { + return gulp.watch(src, tasks); + } +} \ No newline at end of file diff --git a/async/jsconfig.json b/async/jsconfig.json new file mode 100644 index 0000000..5555a6e --- /dev/null +++ b/async/jsconfig.json @@ -0,0 +1,5 @@ +{ + "compilerOptions": { + "target": "ES6" + } +} \ No newline at end of file diff --git a/async/package.json b/async/package.json new file mode 100644 index 0000000..8d8486c --- /dev/null +++ b/async/package.json @@ -0,0 +1,27 @@ +{ + "name": "ts-node-github-async-sample", + "version": "1.0.0", + "description": "Sample for Async Functions in NodeJS v4.0.0", + "private": true, + "main": "lib/github.js", + "bin": { + "sample": "./bin/ts-async-github-sample" + }, + "dependencies": {}, + "devDependencies": { + "del": "^2.0.2", + "gulp": "^3.9.0", + "gulp-sourcemaps": "^1.5.2", + "gulp-typescript": "^2.9.0", + "merge2": "^0.3.6", + "typescript": "next" + }, + "scripts": { + "test": "./node_modules/.bin/gulp test" + }, + "author": "Microsoft Corp.", + "license": "Apache-2.0", + "engines": { + "node": ">=4.0.0" + } +} diff --git a/async/src/lib/github.ts b/async/src/lib/github.ts new file mode 100644 index 0000000..7eed090 --- /dev/null +++ b/async/src/lib/github.ts @@ -0,0 +1,528 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +"use strict"; + +import { LazyPromise } from "./utils"; +import * as querystring from "querystring"; +import * as url from "url"; +import * as http from "http"; +import * as https from "https"; + +const linkPattern = /(?:^|,\s*)<([^>]+)>; rel="([^"]+)"/g; +const noCachePattern = /(?:^|,)\s*no-cache\s*(?:=|,|$)/; +const noStorePattern = /(?:^|,)\s*no-store\s*(?:,|$)/; +const mustRevalidatePattern = /(?:^|,)\s*must-revalidate\s*(?:,|$)/; + +export class GitHubClient { + private cache = new Map(); + private token: string; + + constructor(options?: { token?: string; }) { + if (options) { + this.token = options.token; + } + } + + public async getRateLimit() { + return this.get(uri`/rate_limit`); + } + + public async listMyRepositories(options?: { visibility?: string; affiliation?: string; type?: string; } & SortOrder & Pagination) { + return this.list(uri`/user/repos`, options); + } + + public async listUserRepositories(username: string, options?: { type?: string; } & SortOrder & Pagination) { + return this.list(uri`/users/${username}/repos`, options); + } + + public async listOrganizationRepositories(org: string, options?: { type?: string; } & Pagination) { + return this.list(uri`/orgs/${org}/repos`, options); + } + + public async listPublicRepositories(options?: { since?: number; }) { + return this.list(uri`/repositories`, options); + } + + public async getRepository(owner: string, repo: string) { + return this.get(uri`/repos/${owner}/${repo}`); + } + + public async listContributors(owner: string, repo: string, options?: { anon?: boolean; } & Pagination) { + return this.list(uri`/repos/${owner}/${repo}/contributors`, options); + } + + public async getLanguages(owner: string, repo: string) { + return this.get(uri`/repos/${owner}/${repo}/languages`); + } + + public async listTeams(owner: string, repo: string, options?: Pagination) { + return this.list(uri`/repos/${owner}/${repo}/teams`, options); + } + + public async listTags(owner: string, repo: string, options?: Pagination) { + return this.list(uri`/repos/${owner}/${repo}/tags`, options); + } + + public async listBranches(owner: string, repo: string, options?: Pagination) { + return this.list(uri`/repos/${owner}/${repo}/branches`, options); + } + + public async getBranch(owner: string, repo: string, branch: string) { + return this.get(uri`/repos/${owner}/${repo}/branches/${branch}`); + } + + public async listComments(owner: string, repo: string, options?: Pagination) { + return this.list(uri`/repos/${owner}/${repo}/comments`, options); + } + + public async listCommitComments(owner: string, repo: string, ref: string, options?: Pagination) { + return this.list(uri`/repos/${owner}/${repo}/commits/${ref}/comments`, options); + } + + public async getComment(owner: string, repo: string, id: number) { + return this.get(uri`/repos/${owner}/${repo}/comments/${id}`); + } + + public async listCommits(owner: string, repo: string, options?: { sha?: string; path?: string; author?: string; since?: string; until?: string; } & Pagination) { + return this.list(uri`/repos/${owner}/${repo}/commits`, options); + } + + public async getCommit(owner: string, repo: string, sha: string) { + return this.get(uri`/repos/${owner}/${repo}/commits/${sha}`); + } + + public async compareCommits(owner: string, repo: string, base: string, head: string) { + let result = await this.get(uri`/repos/${owner}/${repo}/compare/${base}...${head}`); + return result; + } + + public async listPullRequests(owner: string, repo: string, options?: { state?: string; head?: string; base?: string; } & SortOrder & Pagination) { + return this.list(uri`/repos/${owner}/${repo}/pulls`, options); + } + + public async getPullRequest(owner: string, repo: string, number: number) { + return this.get(uri`/repos/${owner}/${repo}/pulls/${number}`); + } + + public async listPullRequestCommits(owner: string, repo: string, number: number, options?: { sha?: string; path?: string; author?: string; since?: string; until?: string; } & Pagination) { + return this.list(uri`/repos/${owner}/${repo}/pulls/${number}/commits`, options); + } + + public async listPullRequestFiles(owner: string, repo: string, number: number, options?: Pagination) { + return this.list(uri`/repos/${owner}/${repo}/pulls/${number}/files`, options); + } + + public async listPullRequestComments(owner: string, repo: string, number: number, options?: Pagination) { + return this.list(uri`/repos/${owner}/${repo}/pulls/${number}/comments`, options); + } + + public async getPullRequestComment(owner: string, repo: string, id: number) { + return this.get(uri`/repos/${owner}/${repo}/pulls/comments/${id}`); + } + + private async list(path: string, options: TOptions): Promise> { + let responseMessage = await this.sendAsync(this.prepareRequest("GET", path, options)); + let content = await responseMessage.content; + let result = >JSON.parse(content); + let link = responseMessage.headers.link; + for (let match = linkPattern.exec(link); match; match = linkPattern.exec(link)) { + let parsedUrl = url.parse(match[1], true); + if (match[2] === "next") { + result.next = Object.assign({ }, options, parsedUrl.query); + } + else if (match[2] === "last") { + result.last = Object.assign({ }, options, parsedUrl.query); + } + } + + return result; + } + + private async get(path: string, options?: any) { + let responseMessage = await this.sendAsync(this.prepareRequest("GET", path, options)); + let content = await responseMessage.content; + let result = JSON.parse(content); + return result; + } + + private prepareRequest(method: string, requestUrl: string, query: any) { + let parsedUrl = url.parse(url.resolve("https://api.github.com/", requestUrl), true); + let hostname = "api.github.com"; + let headers: any = { + "User-Agent": "github-api (NodeJS v4.0.0)", + "Accept": "application/vnd.github.v3+json" + }; + if (this.token) { + headers["Authorization"] = `token ${this.token}`; + } + + let pathname = parsedUrl.pathname; + let search = querystring.stringify(Object.assign({ }, parsedUrl.query, query)); + let path = search ? pathname + "?" + search : pathname; + return { method, hostname, path, headers }; + } + + private sendAsync(requestMessage: https.RequestOptions) { + return new Promise((resolve, reject) => { + let requestNoCache = noCachePattern.test(requestMessage.headers["Cache-Control"]); + let requestNoStore = noStorePattern.test(requestMessage.headers["Cache-Control"]); + let cachedResponse: ResponseMessage; + if (!requestNoCache && !requestNoStore) { + cachedResponse = this.cache.get(requestMessage.path); + if (cachedResponse) { + if (!mustRevalidatePattern.test(cachedResponse.headers["cache-control"]) && + Date.parse(cachedResponse.headers["expires"]) > Date.now()) { + resolve(cachedResponse); + return; + } + if (cachedResponse.headers["etag"]) { + requestMessage.headers["If-None-Modified"] = cachedResponse.headers["etag"]; + } + if (cachedResponse.headers["last-modified"]) { + requestMessage.headers["If-Modified-Since"] = cachedResponse.headers["last-modified"]; + } + } + } + + let nodeRequest = https.request(requestMessage, nodeResponse => { + if (nodeResponse.statusCode === 304 && cachedResponse) { + resolve(cachedResponse); + return; + } + + let responseMessage = Object.freeze({ + httpVersion: nodeResponse.httpVersion, + statusCode: nodeResponse.statusCode, + statusMessage: nodeResponse.statusMessage, + headers: nodeResponse.headers, + content: new LazyPromise((resolve, reject) => { + if (nodeResponse.statusCode < 200 || nodeResponse.statusCode >= 300) { + throw new Error(`${nodeResponse.statusCode} ${nodeResponse.statusMessage}`); + } + + let data = ""; + nodeResponse.setEncoding("utf8"); + nodeResponse.on("data", chunk => { data += chunk; }); + nodeResponse.on("error", reject); + nodeResponse.on("end", () => { resolve(data); }); + }) + }); + + let responseNoCache = noCachePattern.test(nodeResponse.headers["cache-control"]); + let responseNoStore = noStorePattern.test(nodeResponse.headers["cache-control"]); + if (!requestNoCache && !requestNoStore && !responseNoCache && !responseNoStore && + (responseMessage.headers["etag"] || responseMessage.headers["last-modified"] || responseMessage.headers["expires"])) { + this.cache.set(requestMessage.path, responseMessage); + } + else if (cachedResponse) { + this.cache.delete(requestMessage.path); + } + + resolve(responseMessage); + }); + + nodeRequest.once("error", reject); + nodeRequest.end(); + }); + } +} + +function uri(template: TemplateStringsArray, ...args: any[]): string; +function uri(template: TemplateStringsArray) { + let text = template[0]; + for (let i = 1; i < template.length; i++) { + text += encodeURIComponent(String(arguments[i])); + text += template[i]; + } + return text; +} + +interface ResponseMessage { + httpVersion: string; + statusCode: number; + statusMessage: string; + headers: any; + content: Promise; +} + +export interface Page extends Array { + next: TOptions; + last: TOptions; +} + +export interface Repository { + id: number; + name: string; + full_name: string; + owner: Person; + private: boolean; + html_url: string; + description: string; + fork: boolean; + url: string; + created_at: string; + updated_at: string; + pushed_at: string; + git_url: string; + ssh_url: string; + clone_url: string; + svn_url: string; + homepage: string; + size: number; + stargazers_count: number; + watchers_count: number; + language: string; + has_issues: boolean; + has_downloads: boolean; + has_wiki: boolean; + has_pages: boolean; + forks_count: number; + mirror_url: string; + open_issues_count: number; + default_branch: string; + permissions: { + admin: boolean; + push: boolean; + pull: boolean; + }; + organization: Person; + network_count: number; + subscribers_count: number; +} + +export interface CommitRef { + url: string; + sha: string; +} + +export interface GitPerson { + name: string; + email: string; + date: string; +} + +export interface GitCommit extends CommitRef { + author: GitPerson; + url: string; + message: string; + tree: CommitRef; + committer: GitPerson; + comment_count: number; +} + +export interface SortOrder { + sort?: string; + direction?: string; +} + +export interface Pagination { + page?: number; + per_page?: number; +} + +export interface Person { + login: string; + id: number; + avatar_url: string; + gravatar_id: string; + url: string; + html_url: string; + type: string; + site_admin: boolean; +} + +export interface Comment { + html_url: string; + url: string; + id: number; + body: string; + path: string; + position: number; + line: number; + commit_id: string; + user: Person; + created_at: string; + updated_at: string; +} + +export interface CommitSummary extends CommitRef { + commit: GitCommit; + html_url: string; + author: Person; + committer: Person; + parents: CommitRef[]; +} + +export interface Commit extends CommitSummary { + stats: { + additions: number; + deletions: number; + total: number; + }; + files: File[]; +} + +export interface File { + sha: string; + filename: string; + status: string; + additions: number; + deletions: number; + changes: number; + blob_url: string; + raw_url: string; + contents_url: string; + patch: string; +} + +export interface CommitDiff { + url: string; + html_url: string; + permalink_url: string; + diff_url: string; + path_url: string; + base_commit: Commit; + merge_base_commit: Commit; + status: string; + ahead_by: number; + behind_by: number; + total_commits: number; + commits: CommitSummary[]; + files: File[]; +} + +export interface Label { + label: string; + ref: string; + sha: string; + user: Person; + repo: Repository; +} + +export interface Languages { + [language: string]: number; + C?: number; + Python?: number; + Java?: number; + TypeScript?: number; + HTML?: number; + PowerShell?: number; + Batchfile?: number; + JavaScript?: number; + Shell?: number; +} + +export interface Team { + id: number; + url: string; + name: string; + slug: string; + description: string; + privacy: string; + permission: string; +} + +export interface Tag { + name: string; + commit: CommitRef; + zipball_url: string; + tarball_url: string; +} + +export interface BranchSummary { + name: string; + commit: CommitRef; +} + +export interface Branch { + name: string; + commit: CommitSummary; +} + +export interface PullRequestSummary { + url: string; + id: number; + html_url: string; + diff_url: string; + patch_url: string; + issue_url: string; + statuses_url: string; + number: number; + state: string; + locked: boolean; + title: string; + body: string; + created_at: string; + updated_at: string; + closed_at: string; + merged_at: string; + merge_commit_sha: string; + assignee: Person; + milestone: Milestone; + head: Label; + base: Label; + user: Person; +} + +export interface PullRequest extends PullRequestSummary { + merged: boolean; + mergeable: boolean; + mergeable_state: string; + merged_by: Person; + comments: number; + review_comments: number; + commits: number; + additions: number; + deletions: number; + changed_files: number; +} + +export interface Milestone { + url: string; + html_url: string; + id: number; + number: number; + state: string; + title: string; + description: string; + creator: Person; + open_issues: number; + closed_issues: number; + created_at: string; + updated_at: string; + closed_at: string; + due_on: string; +} + +export interface RateLimit { + resources: { + core: { + limit: number; + remaining: number; + reset: number; + }, + search: { + limit: number, + remaining: number, + reset: number + } + }, + rate: { + limit: number; + remaining: number; + reset: number; + } +} \ No newline at end of file diff --git a/async/src/lib/index.ts b/async/src/lib/index.ts new file mode 100644 index 0000000..b792f67 --- /dev/null +++ b/async/src/lib/index.ts @@ -0,0 +1,155 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +"use strict"; + +import { GitHubClient } from "./github"; +import { formatMessage, sleep } from "./utils"; + +// A GitHub authentication token. This may be undefined to make API requests anonymously. +const githubToken: string = process.env.GITHUB_TOKEN; + +// A GitHub repository to access. +const githubRepository: string = process.env.GITHUB_REPOSITORY || "Microsoft/TypeScript"; + +/** + * This is the main entry point for the program, and is invoked + * at the bottom of this file. + */ +async function main() { + // The `async` keyword indicates to TypeScript that it must + // modify the emit of the function. As a result, this function + // will return a Promise at run-time, and will pause execution + // at any point where it encounters an `await` expression + // until the awaited value has either been resolved with a value, + // or rejected with an error. + try { + let parts = githubRepository.split("/"); + let owner = parts[0]; + let repo = parts[1]; + + // Create a GitHubClient. This client is designed to wrap the + // GitHub v3 REST API. It also supports conditional requests [1] to + // better interact with GitHub API Rate Limiting [2]. + // + // [1] https://developer.github.com/v3/#conditional-requests + // [2] https://developer.github.com/v3/#rate-limiting + let github = new GitHubClient({ token: githubToken }); + + // Print the recent pull requests for a repository. + // + // We `await` the result of the function call. This allows us to + // observe any exceptions raised by the function call, + // even if we do not use the asynchronous return value. + await printRecentPullRequests(github, owner, repo); + } + catch (e) { + // We catch exceptions here at the entry point so that we can report them. + // + // If we do not catch the exception here, it will not be reported to the + // host. + // + // Alternatively, we could subscribe to the Promise that is returned from + // the call to `main()` below via the `catch` method of the Promise. + console.error(e.stack); + process.exit(-1); + } +} + +/** + * Prints information about the 5 most recent pull requests for a repository. + * @param github The GitHubClient to use to make requests + * @param owner The repository owner. + * @param repo The repository name. + * @returns A Promise that is resolved with the asynchronous function completes. + */ +async function printRecentPullRequests(github: GitHubClient, owner: string, repo: string) { + // Fetch the last 5 pull requests. + // + // Here we `await` the result of the asynchronous function call. In this case, + // the function call returns a Promise instance. As a result, execution of this function + // will pause until the Promise is resolved with a value, or rejected + // with an exception. + // + // We could also have written this line in the following fashion: + // + // let pullRequestsPromise = github.listPullRequests(owner, repo, { per_page: 5 }); + // let pullRequests = await pullRequestsPromise; + // + // The above works because the `await` keyword operates on a value, not a call. + let pullRequests = await github.listPullRequests(owner, repo, { per_page: 5 }); + + // Print the details of each pull request. + console.log(`Last ${pullRequests.length} pull request(s):`); + for (let pullRequest of pullRequests) { + console.log(` #${pullRequest.number} ${pullRequest.title.trim()} - @${pullRequest.user.login}`); + console.log(` [${pullRequest.html_url}]`); + console.log(); + + // Fetch the last 5 commits. + // + // Here we `await` a value inside of a for..of loop. Without `await` it is much more difficult to + // emulate the same run-time behavior when only using Promise#then or Promise.all. + let commits = await github.listPullRequestCommits(owner, repo, pullRequest.number, { per_page: 5 }); + + // Print the details of each commit. + console.log(` Last ${commits.length} commit(s):`); + for (let commit of commits) { + // Get the author of the commit + let author = commit.author ? commit.author.login + : commit.committer ? commit.committer.login + : commit.commit.author ? commit.commit.author.name + : commit.commit.committer ? commit.commit.committer.name + : "unknown"; + + // Format the commit message + let message = formatMessage(commit.commit.message, 60, 100); + + // Print the commit message. + let firstLine = message.shift(); + console.log(` ${commit.sha.substr(0, 8)} ${firstLine}${message.length > 0 ? "..." : ""} - @${author} on ${commit.commit.author.date}`); + + // If the commit message spans multiple lines, print them out following the commit details. + if (message.length > 0) { + for (let line of message) { + console.log(` | ${line}`); + } + console.log(); + } + } + + console.log(); + + // Fetch the last 5 comments. + let comments = await github.listPullRequestComments(owner, repo, pullRequest.number, { per_page: 5 }); + if (comments.length) { + // Print the details of each comment. + console.log(` Last ${comments.length} comment(s):`); + for (let comment of comments) { + console.log(` @${comment.user.login} commented on ${comment.commit_id.substr(0, 8)} at ${comment.created_at}:`); + for (let line of formatMessage(comment.body, 100)) { + console.log(` | ${line}`); + } + + console.log(); + } + + console.log(); + } + } +} + +// Kick off the main async function. +main(); \ No newline at end of file diff --git a/async/src/lib/tsconfig.json b/async/src/lib/tsconfig.json new file mode 100644 index 0000000..0438b79 --- /dev/null +++ b/async/src/lib/tsconfig.json @@ -0,0 +1,6 @@ +{ + "compilerOptions": { + "target": "ES6", + "module": "commonjs" + } +} \ No newline at end of file diff --git a/async/src/lib/tsd.json b/async/src/lib/tsd.json new file mode 100644 index 0000000..cd99291 --- /dev/null +++ b/async/src/lib/tsd.json @@ -0,0 +1,12 @@ +{ + "version": "v4", + "repo": "borisyankov/DefinitelyTyped", + "ref": "master", + "path": "typings", + "bundle": "typings/tsd.d.ts", + "installed": { + "node/node.d.ts": { + "commit": "32029fcb4e1a3ef8968711b545d77b584435729d" + } + } +} diff --git a/imageboard/typings/node/node.d.ts b/async/src/lib/typings/node/node.d.ts similarity index 61% rename from imageboard/typings/node/node.d.ts rename to async/src/lib/typings/node/node.d.ts index 99ab5ec..7498e40 100644 --- a/imageboard/typings/node/node.d.ts +++ b/async/src/lib/typings/node/node.d.ts @@ -1,1334 +1,2077 @@ -// Type definitions for Node.js v0.10.1 -// Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript , DefinitelyTyped -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/************************************************ -* * -* Node.js v0.10.1 API * -* * -************************************************/ - -/************************************************ -* * -* GLOBAL * -* * -************************************************/ -declare var process: NodeJS.Process; -declare var global: any; - -declare var __filename: string; -declare var __dirname: string; - -declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; -declare function clearTimeout(timeoutId: NodeJS.Timer): void; -declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; -declare function clearInterval(intervalId: NodeJS.Timer): void; -declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; -declare function clearImmediate(immediateId: any): void; - -declare var require: { - (id: string): any; - resolve(id:string): string; - cache: any; - extensions: any; - main: any; -}; - -declare var module: { - exports: any; - require(id: string): any; - id: string; - filename: string; - loaded: boolean; - parent: any; - children: any[]; -}; - -// Same as module.exports -declare var exports: any; -declare var SlowBuffer: { - new (str: string, encoding?: string): Buffer; - new (size: number): Buffer; - new (size: Uint8Array): Buffer; - new (array: any[]): Buffer; - prototype: Buffer; - isBuffer(obj: any): boolean; - byteLength(string: string, encoding?: string): number; - concat(list: Buffer[], totalLength?: number): Buffer; -}; - - -// Buffer class -interface Buffer extends NodeBuffer {} -declare var Buffer: { - new (str: string, encoding?: string): Buffer; - new (size: number): Buffer; - new (size: Uint8Array): Buffer; - new (array: any[]): Buffer; - prototype: Buffer; - isBuffer(obj: any): boolean; - byteLength(string: string, encoding?: string): number; - concat(list: Buffer[], totalLength?: number): Buffer; -}; - -/************************************************ -* * -* GLOBAL INTERFACES * -* * -************************************************/ -declare module NodeJS { - export interface ErrnoException extends Error { - errno?: any; - code?: string; - path?: string; - syscall?: string; - } - - export interface EventEmitter { - addListener(event: string, listener: Function): EventEmitter; - on(event: string, listener: Function): EventEmitter; - once(event: string, listener: Function): EventEmitter; - removeListener(event: string, listener: Function): EventEmitter; - removeAllListeners(event?: string): EventEmitter; - setMaxListeners(n: number): void; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - } - - export interface ReadableStream extends EventEmitter { - readable: boolean; - read(size?: number): any; - setEncoding(encoding: string): void; - pause(): void; - resume(): void; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: string): void; - unshift(chunk: Buffer): void; - wrap(oldStream: ReadableStream): ReadableStream; - } - - export interface WritableStream extends EventEmitter { - writable: boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - } - - export interface ReadWriteStream extends ReadableStream, WritableStream {} - - export interface Process extends EventEmitter { - stdout: WritableStream; - stderr: WritableStream; - stdin: ReadableStream; - argv: string[]; - execPath: string; - abort(): void; - chdir(directory: string): void; - cwd(): string; - env: any; - exit(code?: number): void; - getgid(): number; - setgid(id: number): void; - setgid(id: string): void; - getuid(): number; - setuid(id: number): void; - setuid(id: string): void; - version: string; - versions: { - http_parser: string; - node: string; - v8: string; - ares: string; - uv: string; - zlib: string; - openssl: string; - }; - config: { - target_defaults: { - cflags: any[]; - default_configuration: string; - defines: string[]; - include_dirs: string[]; - libraries: string[]; - }; - variables: { - clang: number; - host_arch: string; - node_install_npm: boolean; - node_install_waf: boolean; - node_prefix: string; - node_shared_openssl: boolean; - node_shared_v8: boolean; - node_shared_zlib: boolean; - node_use_dtrace: boolean; - node_use_etw: boolean; - node_use_openssl: boolean; - target_arch: string; - v8_no_strict_aliasing: number; - v8_use_snapshot: boolean; - visibility: string; - }; - }; - kill(pid: number, signal?: string): void; - pid: number; - title: string; - arch: string; - platform: string; - memoryUsage(): { rss: number; heapTotal: number; heapUsed: number; }; - nextTick(callback: Function): void; - umask(mask?: number): number; - uptime(): number; - hrtime(time?:number[]): number[]; - - // Worker - send?(message: any, sendHandle?: any): void; - } - - export interface Timer { - ref() : void; - unref() : void; - } -} - -/** - * @deprecated - */ -interface NodeBuffer { - [index: number]: number; - write(string: string, offset?: number, length?: number, encoding?: string): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): any; - length: number; - copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): Buffer; - readUInt8(offset: number, noAsset?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; - writeUInt8(value: number, offset: number, noAssert?: boolean): void; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): void; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): void; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): void; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): void; - writeInt8(value: number, offset: number, noAssert?: boolean): void; - writeInt16LE(value: number, offset: number, noAssert?: boolean): void; - writeInt16BE(value: number, offset: number, noAssert?: boolean): void; - writeInt32LE(value: number, offset: number, noAssert?: boolean): void; - writeInt32BE(value: number, offset: number, noAssert?: boolean): void; - writeFloatLE(value: number, offset: number, noAssert?: boolean): void; - writeFloatBE(value: number, offset: number, noAssert?: boolean): void; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): void; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): void; - fill(value: any, offset?: number, end?: number): void; -} - -/************************************************ -* * -* MODULES * -* * -************************************************/ -declare module "buffer" { - export var INSPECT_MAX_BYTES: number; -} - -declare module "querystring" { - export function stringify(obj: any, sep?: string, eq?: string): string; - export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; - export function escape(): any; - export function unescape(): any; -} - -declare module "events" { - export class EventEmitter implements NodeJS.EventEmitter { - static listenerCount(emitter: EventEmitter, event: string): number; - - addListener(event: string, listener: Function): EventEmitter; - on(event: string, listener: Function): EventEmitter; - once(event: string, listener: Function): EventEmitter; - removeListener(event: string, listener: Function): EventEmitter; - removeAllListeners(event?: string): EventEmitter; - setMaxListeners(n: number): void; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - } -} - -declare module "http" { - import events = require("events"); - import net = require("net"); - import stream = require("stream"); - - export interface Server extends events.EventEmitter { - listen(port: number, hostname?: string, backlog?: number, callback?: Function): Server; - listen(path: string, callback?: Function): Server; - listen(handle: any, listeningListener?: Function): Server; - close(cb?: any): Server; - address(): { port: number; family: string; address: string; }; - maxHeadersCount: number; - } - export interface ServerRequest extends events.EventEmitter, stream.Readable { - method: string; - url: string; - headers: any; - trailers: string; - httpVersion: string; - setEncoding(encoding?: string): void; - pause(): void; - resume(): void; - connection: net.Socket; - } - export interface ServerResponse extends events.EventEmitter, stream.Writable { - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - - writeContinue(): void; - writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; - writeHead(statusCode: number, headers?: any): void; - statusCode: number; - setHeader(name: string, value: string): void; - sendDate: boolean; - getHeader(name: string): string; - removeHeader(name: string): void; - write(chunk: any, encoding?: string): any; - addTrailers(headers: any): void; - - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; - } - export interface ClientRequest extends events.EventEmitter, stream.Writable { - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - - write(chunk: any, encoding?: string): void; - abort(): void; - setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: boolean): void; - setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; - - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; - } - export interface ClientResponse extends events.EventEmitter, stream.Readable { - statusCode: number; - httpVersion: string; - headers: any; - trailers: any; - setEncoding(encoding?: string): void; - pause(): void; - resume(): void; - } - export interface Agent { maxSockets: number; sockets: any; requests: any; } - - export var STATUS_CODES: { - [errorCode: number]: string; - [errorCode: string]: string; - }; - export function createServer(requestListener?: (request: ServerRequest, response: ServerResponse) =>void ): Server; - export function createClient(port?: number, host?: string): any; - export function request(options: any, callback?: Function): ClientRequest; - export function get(options: any, callback?: Function): ClientRequest; - export var globalAgent: Agent; -} - -declare module "cluster" { - import child = require("child_process"); - import events = require("events"); - - export interface ClusterSettings { - exec?: string; - args?: string[]; - silent?: boolean; - } - - export class Worker extends events.EventEmitter { - id: string; - process: child.ChildProcess; - suicide: boolean; - send(message: any, sendHandle?: any): void; - kill(signal?: string): void; - destroy(signal?: string): void; - disconnect(): void; - } - - export var settings: ClusterSettings; - export var isMaster: boolean; - export var isWorker: boolean; - export function setupMaster(settings?: ClusterSettings): void; - export function fork(env?: any): Worker; - export function disconnect(callback?: Function): void; - export var worker: Worker; - export var workers: Worker[]; - - // Event emitter - export function addListener(event: string, listener: Function): void; - export function on(event: string, listener: Function): any; - export function once(event: string, listener: Function): void; - export function removeListener(event: string, listener: Function): void; - export function removeAllListeners(event?: string): void; - export function setMaxListeners(n: number): void; - export function listeners(event: string): Function[]; - export function emit(event: string, ...args: any[]): boolean; -} - -declare module "zlib" { - import stream = require("stream"); - export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } - - export interface Gzip extends stream.Transform { } - export interface Gunzip extends stream.Transform { } - export interface Deflate extends stream.Transform { } - export interface Inflate extends stream.Transform { } - export interface DeflateRaw extends stream.Transform { } - export interface InflateRaw extends stream.Transform { } - export interface Unzip extends stream.Transform { } - - export function createGzip(options?: ZlibOptions): Gzip; - export function createGunzip(options?: ZlibOptions): Gunzip; - export function createDeflate(options?: ZlibOptions): Deflate; - export function createInflate(options?: ZlibOptions): Inflate; - export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; - export function createInflateRaw(options?: ZlibOptions): InflateRaw; - export function createUnzip(options?: ZlibOptions): Unzip; - - export function deflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function gzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function gunzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function inflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function unzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - - // Constants - export var Z_NO_FLUSH: number; - export var Z_PARTIAL_FLUSH: number; - export var Z_SYNC_FLUSH: number; - export var Z_FULL_FLUSH: number; - export var Z_FINISH: number; - export var Z_BLOCK: number; - export var Z_TREES: number; - export var Z_OK: number; - export var Z_STREAM_END: number; - export var Z_NEED_DICT: number; - export var Z_ERRNO: number; - export var Z_STREAM_ERROR: number; - export var Z_DATA_ERROR: number; - export var Z_MEM_ERROR: number; - export var Z_BUF_ERROR: number; - export var Z_VERSION_ERROR: number; - export var Z_NO_COMPRESSION: number; - export var Z_BEST_SPEED: number; - export var Z_BEST_COMPRESSION: number; - export var Z_DEFAULT_COMPRESSION: number; - export var Z_FILTERED: number; - export var Z_HUFFMAN_ONLY: number; - export var Z_RLE: number; - export var Z_FIXED: number; - export var Z_DEFAULT_STRATEGY: number; - export var Z_BINARY: number; - export var Z_TEXT: number; - export var Z_ASCII: number; - export var Z_UNKNOWN: number; - export var Z_DEFLATED: number; - export var Z_NULL: number; -} - -declare module "os" { - export function tmpdir(): string; - export function hostname(): string; - export function type(): string; - export function platform(): string; - export function arch(): string; - export function release(): string; - export function uptime(): number; - export function loadavg(): number[]; - export function totalmem(): number; - export function freemem(): number; - export function cpus(): { model: string; speed: number; times: { user: number; nice: number; sys: number; idle: number; irq: number; }; }[]; - export function networkInterfaces(): any; - export var EOL: string; -} - -declare module "https" { - import tls = require("tls"); - import events = require("events"); - import http = require("http"); - - export interface ServerOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - crl?: any; - ciphers?: string; - honorCipherOrder?: boolean; - requestCert?: boolean; - rejectUnauthorized?: boolean; - NPNProtocols?: any; - SNICallback?: (servername: string) => any; - } - - export interface RequestOptions { - host?: string; - hostname?: string; - port?: number; - path?: string; - method?: string; - headers?: any; - auth?: string; - agent?: any; - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - ciphers?: string; - rejectUnauthorized?: boolean; - } - - export interface Agent { - maxSockets: number; - sockets: any; - requests: any; - } - export var Agent: { - new (options?: RequestOptions): Agent; - }; - export interface Server extends tls.Server { } - export function createServer(options: ServerOptions, requestListener?: Function): Server; - export function request(options: RequestOptions, callback?: (res: http.ClientResponse) =>void ): http.ClientRequest; - export function get(options: RequestOptions, callback?: (res: http.ClientResponse) =>void ): http.ClientRequest; - export var globalAgent: Agent; -} - -declare module "punycode" { - export function decode(string: string): string; - export function encode(string: string): string; - export function toUnicode(domain: string): string; - export function toASCII(domain: string): string; - export var ucs2: ucs2; - interface ucs2 { - decode(string: string): string; - encode(codePoints: number[]): string; - } - export var version: any; -} - -declare module "repl" { - import stream = require("stream"); - import events = require("events"); - - export interface ReplOptions { - prompt?: string; - input?: NodeJS.ReadableStream; - output?: NodeJS.WritableStream; - terminal?: boolean; - eval?: Function; - useColors?: boolean; - useGlobal?: boolean; - ignoreUndefined?: boolean; - writer?: Function; - } - export function start(options: ReplOptions): events.EventEmitter; -} - -declare module "readline" { - import events = require("events"); - import stream = require("stream"); - - export interface ReadLine extends events.EventEmitter { - setPrompt(prompt: string, length: number): void; - prompt(preserveCursor?: boolean): void; - question(query: string, callback: Function): void; - pause(): void; - resume(): void; - close(): void; - write(data: any, key?: any): void; - } - export interface ReadLineOptions { - input: NodeJS.ReadableStream; - output: NodeJS.WritableStream; - completer?: Function; - terminal?: boolean; - } - export function createInterface(options: ReadLineOptions): ReadLine; -} - -declare module "vm" { - export interface Context { } - export interface Script { - runInThisContext(): void; - runInNewContext(sandbox?: Context): void; - } - export function runInThisContext(code: string, filename?: string): void; - export function runInNewContext(code: string, sandbox?: Context, filename?: string): void; - export function runInContext(code: string, context: Context, filename?: string): void; - export function createContext(initSandbox?: Context): Context; - export function createScript(code: string, filename?: string): Script; -} - -declare module "child_process" { - import events = require("events"); - import stream = require("stream"); - - export interface ChildProcess extends events.EventEmitter { - stdin: stream.Writable; - stdout: stream.Readable; - stderr: stream.Readable; - pid: number; - kill(signal?: string): void; - send(message: any, sendHandle: any): void; - disconnect(): void; - } - - export function spawn(command: string, args?: string[], options?: { - cwd?: string; - stdio?: any; - custom?: any; - env?: any; - detached?: boolean; - }): ChildProcess; - export function exec(command: string, options: { - cwd?: string; - stdio?: any; - customFds?: any; - env?: any; - encoding?: string; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - }, callback: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function exec(command: string, callback: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function execFile(file: string, - callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function execFile(file: string, args?: string[], - callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function execFile(file: string, args?: string[], options?: { - cwd?: string; - stdio?: any; - customFds?: any; - env?: any; - encoding?: string; - timeout?: number; - maxBuffer?: string; - killSignal?: string; - }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function fork(modulePath: string, args?: string[], options?: { - cwd?: string; - env?: any; - encoding?: string; - }): ChildProcess; -} - -declare module "url" { - export interface Url { - href: string; - protocol: string; - auth: string; - hostname: string; - port: string; - host: string; - pathname: string; - search: string; - query: any; // string | Object - slashes: boolean; - hash?: string; - path?: string; - } - - export interface UrlOptions { - protocol?: string; - auth?: string; - hostname?: string; - port?: string; - host?: string; - pathname?: string; - search?: string; - query?: any; - hash?: string; - path?: string; - } - - export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url; - export function format(url: UrlOptions): string; - export function resolve(from: string, to: string): string; -} - -declare module "dns" { - export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string; - export function lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string; - export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve6(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; -} - -declare module "net" { - import stream = require("stream"); - - export interface Socket extends stream.Duplex { - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - - connect(port: number, host?: string, connectionListener?: Function): void; - connect(path: string, connectionListener?: Function): void; - bufferSize: number; - setEncoding(encoding?: string): void; - write(data: any, encoding?: string, callback?: Function): void; - destroy(): void; - pause(): void; - resume(): void; - setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: boolean): void; - setKeepAlive(enable?: boolean, initialDelay?: number): void; - address(): { port: number; family: string; address: string; }; - unref(): void; - ref(): void; - - remoteAddress: string; - remotePort: number; - bytesRead: number; - bytesWritten: number; - - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; - } - - export var Socket: { - new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; - }; - - export interface Server extends Socket { - listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server; - listen(path: string, listeningListener?: Function): Server; - listen(handle: any, listeningListener?: Function): Server; - close(callback?: Function): Server; - address(): { port: number; family: string; address: string; }; - maxConnections: number; - connections: number; - } - export function createServer(connectionListener?: (socket: Socket) =>void ): Server; - export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) =>void ): Server; - export function connect(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; - export function connect(port: number, host?: string, connectionListener?: Function): Socket; - export function connect(path: string, connectionListener?: Function): Socket; - export function createConnection(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; - export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; - export function createConnection(path: string, connectionListener?: Function): Socket; - export function isIP(input: string): number; - export function isIPv4(input: string): boolean; - export function isIPv6(input: string): boolean; -} - -declare module "dgram" { - import events = require("events"); - - interface RemoteInfo { - address: string; - port: number; - size: number; - } - - interface AddressInfo { - address: string; - family: string; - port: number; - } - - export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; - - interface Socket extends events.EventEmitter { - send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; - bind(port: number, address?: string, callback?: () => void): void; - close(): void; - address(): AddressInfo; - setBroadcast(flag: boolean): void; - setMulticastTTL(ttl: number): void; - setMulticastLoopback(flag: boolean): void; - addMembership(multicastAddress: string, multicastInterface?: string): void; - dropMembership(multicastAddress: string, multicastInterface?: string): void; - } -} - -declare module "fs" { - import stream = require("stream"); - import events = require("events"); - - interface Stats { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - dev: number; - ino: number; - mode: number; - nlink: number; - uid: number; - gid: number; - rdev: number; - size: number; - blksize: number; - blocks: number; - atime: Date; - mtime: Date; - ctime: Date; - } - - interface FSWatcher extends events.EventEmitter { - close(): void; - } - - export interface ReadStream extends stream.Readable { - close(): void; - } - export interface WriteStream extends stream.Writable { - close(): void; - } - - export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function renameSync(oldPath: string, newPath: string): void; - export function truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function truncate(path: string, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function truncateSync(path: string, len?: number): void; - export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function ftruncateSync(fd: number, len?: number): void; - export function chown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chownSync(path: string, uid: number, gid: number): void; - export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fchownSync(fd: number, uid: number, gid: number): void; - export function lchown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchownSync(path: string, uid: number, gid: number): void; - export function chmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chmodSync(path: string, mode: number): void; - export function chmodSync(path: string, mode: string): void; - export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fchmodSync(fd: number, mode: number): void; - export function fchmodSync(fd: number, mode: string): void; - export function lchmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchmodSync(path: string, mode: number): void; - export function lchmodSync(path: string, mode: string): void; - export function stat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function lstat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function statSync(path: string): Stats; - export function lstatSync(path: string): Stats; - export function fstatSync(fd: number): Stats; - export function link(srcpath: string, dstpath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function linkSync(srcpath: string, dstpath: string): void; - export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function symlinkSync(srcpath: string, dstpath: string, type?: string): void; - export function readlink(path: string, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; - export function readlinkSync(path: string): string; - export function realpath(path: string, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; - export function realpath(path: string, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) =>any): void; - export function realpathSync(path: string, cache?: {[path: string]: string}): string; - export function unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function unlinkSync(path: string): void; - export function rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function rmdirSync(path: string): void; - export function mkdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function mkdir(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function mkdir(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function mkdirSync(path: string, mode?: number): void; - export function mkdirSync(path: string, mode?: string): void; - export function readdir(path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; - export function readdirSync(path: string): string[]; - export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function closeSync(fd: number): void; - export function open(path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; - export function open(path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; - export function open(path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; - export function openSync(path: string, flags: string, mode?: number): number; - export function openSync(path: string, flags: string, mode?: string): number; - export function utimes(path: string, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function utimes(path: string, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function utimesSync(path: string, atime: number, mtime: number): void; - export function utimesSync(path: string, atime: Date, mtime: Date): void; - export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function futimesSync(fd: number, atime: number, mtime: number): void; - export function futimesSync(fd: number, atime: Date, mtime: Date): void; - export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fsyncSync(fd: number): void; - export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; - export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; - export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; - export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; - export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; - export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void; - export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; - export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void ): void; - export function readFileSync(filename: string, encoding: string): string; - export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; - export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; - export function writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; - export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; - export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; - export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; - export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; - export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; - export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void; - export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; - export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; - export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; - export function watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; - export function exists(path: string, callback?: (exists: boolean) => void): void; - export function existsSync(path: string): boolean; - export function createReadStream(path: string, options?: { - flags?: string; - encoding?: string; - fd?: string; - mode?: number; - bufferSize?: number; - }): ReadStream; - export function createReadStream(path: string, options?: { - flags?: string; - encoding?: string; - fd?: string; - mode?: string; - bufferSize?: number; - }): ReadStream; - export function createWriteStream(path: string, options?: { - flags?: string; - encoding?: string; - string?: string; - }): WriteStream; -} - -declare module "path" { - export function normalize(p: string): string; - export function join(...paths: any[]): string; - export function resolve(...pathSegments: any[]): string; - export function relative(from: string, to: string): string; - export function dirname(p: string): string; - export function basename(p: string, ext?: string): string; - export function extname(p: string): string; - export var sep: string; -} - -declare module "string_decoder" { - export interface NodeStringDecoder { - write(buffer: Buffer): string; - detectIncompleteChar(buffer: Buffer): number; - } - export var StringDecoder: { - new (encoding: string): NodeStringDecoder; - }; -} - -declare module "tls" { - import crypto = require("crypto"); - import net = require("net"); - import stream = require("stream"); - - var CLIENT_RENEG_LIMIT: number; - var CLIENT_RENEG_WINDOW: number; - - export interface TlsOptions { - pfx?: any; //string or buffer - key?: any; //string or buffer - passphrase?: string; - cert?: any; - ca?: any; //string or buffer - crl?: any; //string or string array - ciphers?: string; - honorCipherOrder?: any; - requestCert?: boolean; - rejectUnauthorized?: boolean; - NPNProtocols?: any; //array or Buffer; - SNICallback?: (servername: string) => any; - } - - export interface ConnectionOptions { - host?: string; - port?: number; - socket?: net.Socket; - pfx?: any; //string | Buffer - key?: any; //string | Buffer - passphrase?: string; - cert?: any; //string | Buffer - ca?: any; //Array of string | Buffer - rejectUnauthorized?: boolean; - NPNProtocols?: any; //Array of string | Buffer - servername?: string; - } - - export interface Server extends net.Server { - // Extended base methods - listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server; - listen(path: string, listeningListener?: Function): Server; - listen(handle: any, listeningListener?: Function): Server; - - listen(port: number, host?: string, callback?: Function): Server; - close(): Server; - address(): { port: number; family: string; address: string; }; - addContext(hostName: string, credentials: { - key: string; - cert: string; - ca: string; - }): void; - maxConnections: number; - connections: number; - } - - export interface ClearTextStream extends stream.Duplex { - authorized: boolean; - authorizationError: Error; - getPeerCertificate(): any; - getCipher: { - name: string; - version: string; - }; - address: { - port: number; - family: string; - address: string; - }; - remoteAddress: string; - remotePort: number; - } - - export interface SecurePair { - encrypted: any; - cleartext: any; - } - - export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) =>void ): Server; - export function connect(options: TlsOptions, secureConnectionListener?: () =>void ): ClearTextStream; - export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; - export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; - export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; -} - -declare module "crypto" { - export interface CredentialDetails { - pfx: string; - key: string; - passphrase: string; - cert: string; - ca: any; //string | string array - crl: any; //string | string array - ciphers: string; - } - export interface Credentials { context?: any; } - export function createCredentials(details: CredentialDetails): Credentials; - export function createHash(algorithm: string): Hash; - export function createHmac(algorithm: string, key: string): Hmac; - export function createHmac(algorithm: string, key: Buffer): Hmac; - interface Hash { - update(data: any, input_encoding?: string): Hash; - digest(encoding: 'buffer'): Buffer; - digest(encoding: string): any; - digest(): Buffer; - } - interface Hmac { - update(data: any, input_encoding?: string): Hmac; - digest(encoding: 'buffer'): Buffer; - digest(encoding: string): any; - digest(): Buffer; - } - export function createCipher(algorithm: string, password: any): Cipher; - export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; - interface Cipher { - update(data: Buffer): Buffer; - update(data: string, input_encoding?: string, output_encoding?: string): string; - final(): Buffer; - final(output_encoding: string): string; - setAutoPadding(auto_padding: boolean): void; - } - export function createDecipher(algorithm: string, password: any): Decipher; - export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; - interface Decipher { - update(data: Buffer): Buffer; - update(data: string, input_encoding?: string, output_encoding?: string): string; - final(): Buffer; - final(output_encoding: string): string; - setAutoPadding(auto_padding: boolean): void; - } - export function createSign(algorithm: string): Signer; - interface Signer { - update(data: any): void; - sign(private_key: string, output_format: string): string; - } - export function createVerify(algorith: string): Verify; - interface Verify { - update(data: any): void; - verify(object: string, signature: string, signature_format?: string): boolean; - } - export function createDiffieHellman(prime_length: number): DiffieHellman; - export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman; - interface DiffieHellman { - generateKeys(encoding?: string): string; - computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; - getPrime(encoding?: string): string; - getGenerator(encoding: string): string; - getPublicKey(encoding?: string): string; - getPrivateKey(encoding?: string): string; - setPublicKey(public_key: string, encoding?: string): void; - setPrivateKey(public_key: string, encoding?: string): void; - } - export function getDiffieHellman(group_name: string): DiffieHellman; - export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; - export function pbkdf2Sync(password: string, salt: string, iterations: number, keylen: number) : Buffer; - export function randomBytes(size: number): Buffer; - export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; - export function pseudoRandomBytes(size: number): Buffer; - export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; -} - -declare module "stream" { - import events = require("events"); - - export interface Stream extends events.EventEmitter { - pipe(destination: T, options?: { end?: boolean; }): T; - } - - export interface ReadableOptions { - highWaterMark?: number; - encoding?: string; - objectMode?: boolean; - } - - export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { - readable: boolean; - constructor(opts?: ReadableOptions); - _read(size: number): void; - read(size?: number): any; - setEncoding(encoding: string): void; - pause(): void; - resume(): void; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: string): void; - unshift(chunk: Buffer): void; - wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; - push(chunk: any, encoding?: string): boolean; - } - - export interface WritableOptions { - highWaterMark?: number; - decodeStrings?: boolean; - } - - export class Writable extends events.EventEmitter implements NodeJS.WritableStream { - writable: boolean; - constructor(opts?: WritableOptions); - _write(data: Buffer, encoding: string, callback: Function): void; - _write(data: string, encoding: string, callback: Function): void; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - } - - export interface DuplexOptions extends ReadableOptions, WritableOptions { - allowHalfOpen?: boolean; - } - - // Note: Duplex extends both Readable and Writable. - export class Duplex extends Readable implements NodeJS.ReadWriteStream { - writable: boolean; - constructor(opts?: DuplexOptions); - _write(data: Buffer, encoding: string, callback: Function): void; - _write(data: string, encoding: string, callback: Function): void; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - } - - export interface TransformOptions extends ReadableOptions, WritableOptions {} - - // Note: Transform lacks the _read and _write methods of Readable/Writable. - export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { - readable: boolean; - writable: boolean; - constructor(opts?: TransformOptions); - _transform(chunk: Buffer, encoding: string, callback: Function): void; - _transform(chunk: string, encoding: string, callback: Function): void; - _flush(callback: Function): void; - read(size?: number): any; - setEncoding(encoding: string): void; - pause(): void; - resume(): void; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: string): void; - unshift(chunk: Buffer): void; - wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; - push(chunk: any, encoding?: string): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - } - - export class PassThrough extends Transform {} -} - -declare module "util" { - export interface InspectOptions { - showHidden?: boolean; - depth?: number; - colors?: boolean; - customInspect?: boolean; - } - - export function format(format: any, ...param: any[]): string; - export function debug(string: string): void; - export function error(...param: any[]): void; - export function puts(...param: any[]): void; - export function print(...param: any[]): void; - export function log(string: string): void; - export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string; - export function inspect(object: any, options: InspectOptions): string; - export function isArray(object: any): boolean; - export function isRegExp(object: any): boolean; - export function isDate(object: any): boolean; - export function isError(object: any): boolean; - export function inherits(constructor: any, superConstructor: any): void; -} - -declare module "assert" { - function internal (value: any, message?: string): void; - module internal { - export class AssertionError implements Error { - name: string; - message: string; - actual: any; - expected: any; - operator: string; - generatedMessage: boolean; - - constructor(options?: {message?: string; actual?: any; expected?: any; - operator?: string; stackStartFunction?: Function}); - } - - export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; - export function ok(value: any, message?: string): void; - export function equal(actual: any, expected: any, message?: string): void; - export function notEqual(actual: any, expected: any, message?: string): void; - export function deepEqual(actual: any, expected: any, message?: string): void; - export function notDeepEqual(acutal: any, expected: any, message?: string): void; - export function strictEqual(actual: any, expected: any, message?: string): void; - export function notStrictEqual(actual: any, expected: any, message?: string): void; - export var throws: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; - - export var doesNotThrow: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; - - export function ifError(value: any): void; - } - - export = internal; -} - -declare module "tty" { - import net = require("net"); - - export function isatty(fd: number): boolean; - export interface ReadStream extends net.Socket { - isRaw: boolean; - setRawMode(mode: boolean): void; - } - export interface WriteStream extends net.Socket { - columns: number; - rows: number; - } -} - -declare module "domain" { - import events = require("events"); - - export class Domain extends events.EventEmitter { - run(fn: Function): void; - add(emitter: events.EventEmitter): void; - remove(emitter: events.EventEmitter): void; - bind(cb: (err: Error, data: any) => any): any; - intercept(cb: (data: any) => any): any; - dispose(): void; - - addListener(event: string, listener: Function): Domain; - on(event: string, listener: Function): Domain; - once(event: string, listener: Function): Domain; - removeListener(event: string, listener: Function): Domain; - removeAllListeners(event?: string): Domain; - } - - export function create(): Domain; -} +// Type definitions for Node.js v0.12.0 +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript , DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/************************************************ +* * +* Node.js v0.12.0 API * +* * +************************************************/ + +interface Error { + stack?: string; +} + + +// compat for TypeScript 1.5.3 +// if you use with --target es3 or --target es5 and use below definitions, +// use the lib.es6.d.ts that is bundled with TypeScript 1.5.3. +interface MapConstructor {} +interface WeakMapConstructor {} +interface SetConstructor {} +interface WeakSetConstructor {} + +/************************************************ +* * +* GLOBAL * +* * +************************************************/ +declare var process: NodeJS.Process; +declare var global: NodeJS.Global; + +declare var __filename: string; +declare var __dirname: string; + +declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; +declare function clearTimeout(timeoutId: NodeJS.Timer): void; +declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; +declare function clearInterval(intervalId: NodeJS.Timer): void; +declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; +declare function clearImmediate(immediateId: any): void; + +interface NodeRequireFunction { + (id: string): any; +} + +interface NodeRequire extends NodeRequireFunction { + resolve(id:string): string; + cache: any; + extensions: any; + main: any; +} + +declare var require: NodeRequire; + +interface NodeModule { + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: any; + children: any[]; +} + +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; +declare var SlowBuffer: { + new (str: string, encoding?: string): Buffer; + new (size: number): Buffer; + new (size: Uint8Array): Buffer; + new (array: any[]): Buffer; + prototype: Buffer; + isBuffer(obj: any): boolean; + byteLength(string: string, encoding?: string): number; + concat(list: Buffer[], totalLength?: number): Buffer; +}; + + +// Buffer class +interface Buffer extends NodeBuffer {} + +/** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + */ +declare var Buffer: { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + new (str: string, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + new (size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + new (array: Uint8Array): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + new (array: any[]): Buffer; + prototype: Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + isBuffer(obj: any): boolean; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + compare(buf1: Buffer, buf2: Buffer): number; +}; + +/************************************************ +* * +* GLOBAL INTERFACES * +* * +************************************************/ +declare module NodeJS { + export interface ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; + } + + export interface EventEmitter { + addListener(event: string, listener: Function): EventEmitter; + on(event: string, listener: Function): EventEmitter; + once(event: string, listener: Function): EventEmitter; + removeListener(event: string, listener: Function): EventEmitter; + removeAllListeners(event?: string): EventEmitter; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + } + + export interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string|Buffer; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: string): void; + unshift(chunk: Buffer): void; + wrap(oldStream: ReadableStream): ReadableStream; + } + + export interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + export interface ReadWriteStream extends ReadableStream, WritableStream {} + + export interface Process extends EventEmitter { + stdout: WritableStream; + stderr: WritableStream; + stdin: ReadableStream; + argv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + env: any; + exit(code?: number): void; + getgid(): number; + setgid(id: number): void; + setgid(id: string): void; + getuid(): number; + setuid(id: number): void; + setuid(id: string): void; + version: string; + versions: { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + openssl: string; + }; + config: { + target_defaults: { + cflags: any[]; + default_configuration: string; + defines: string[]; + include_dirs: string[]; + libraries: string[]; + }; + variables: { + clang: number; + host_arch: string; + node_install_npm: boolean; + node_install_waf: boolean; + node_prefix: string; + node_shared_openssl: boolean; + node_shared_v8: boolean; + node_shared_zlib: boolean; + node_use_dtrace: boolean; + node_use_etw: boolean; + node_use_openssl: boolean; + target_arch: string; + v8_no_strict_aliasing: number; + v8_use_snapshot: boolean; + visibility: string; + }; + }; + kill(pid: number, signal?: string): void; + pid: number; + title: string; + arch: string; + platform: string; + memoryUsage(): { rss: number; heapTotal: number; heapUsed: number; }; + nextTick(callback: Function): void; + umask(mask?: number): number; + uptime(): number; + hrtime(time?:number[]): number[]; + + // Worker + send?(message: any, sendHandle?: any): void; + } + + export interface Global { + Array: typeof Array; + ArrayBuffer: typeof ArrayBuffer; + Boolean: typeof Boolean; + Buffer: typeof Buffer; + DataView: typeof DataView; + Date: typeof Date; + Error: typeof Error; + EvalError: typeof EvalError; + Float32Array: typeof Float32Array; + Float64Array: typeof Float64Array; + Function: typeof Function; + GLOBAL: Global; + Infinity: typeof Infinity; + Int16Array: typeof Int16Array; + Int32Array: typeof Int32Array; + Int8Array: typeof Int8Array; + Intl: typeof Intl; + JSON: typeof JSON; + Map: MapConstructor; + Math: typeof Math; + NaN: typeof NaN; + Number: typeof Number; + Object: typeof Object; + Promise: Function; + RangeError: typeof RangeError; + ReferenceError: typeof ReferenceError; + RegExp: typeof RegExp; + Set: SetConstructor; + String: typeof String; + Symbol: Function; + SyntaxError: typeof SyntaxError; + TypeError: typeof TypeError; + URIError: typeof URIError; + Uint16Array: typeof Uint16Array; + Uint32Array: typeof Uint32Array; + Uint8Array: typeof Uint8Array; + Uint8ClampedArray: Function; + WeakMap: WeakMapConstructor; + WeakSet: WeakSetConstructor; + clearImmediate: (immediateId: any) => void; + clearInterval: (intervalId: NodeJS.Timer) => void; + clearTimeout: (timeoutId: NodeJS.Timer) => void; + console: typeof console; + decodeURI: typeof decodeURI; + decodeURIComponent: typeof decodeURIComponent; + encodeURI: typeof encodeURI; + encodeURIComponent: typeof encodeURIComponent; + escape: (str: string) => string; + eval: typeof eval; + global: Global; + isFinite: typeof isFinite; + isNaN: typeof isNaN; + parseFloat: typeof parseFloat; + parseInt: typeof parseInt; + process: Process; + root: Global; + setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any; + setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; + setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; + undefined: typeof undefined; + unescape: (str: string) => string; + gc: () => void; + } + + export interface Timer { + ref() : void; + unref() : void; + } +} + +/** + * @deprecated + */ +interface NodeBuffer { + [index: number]: number; + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): any; + length: number; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAsset?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + writeUInt8(value: number, offset: number, noAssert?: boolean): void; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): void; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): void; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): void; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): void; + writeInt8(value: number, offset: number, noAssert?: boolean): void; + writeInt16LE(value: number, offset: number, noAssert?: boolean): void; + writeInt16BE(value: number, offset: number, noAssert?: boolean): void; + writeInt32LE(value: number, offset: number, noAssert?: boolean): void; + writeInt32BE(value: number, offset: number, noAssert?: boolean): void; + writeFloatLE(value: number, offset: number, noAssert?: boolean): void; + writeFloatBE(value: number, offset: number, noAssert?: boolean): void; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): void; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): void; + fill(value: any, offset?: number, end?: number): void; +} + +/************************************************ +* * +* MODULES * +* * +************************************************/ +declare module "buffer" { + export var INSPECT_MAX_BYTES: number; +} + +declare module "querystring" { + export function stringify(obj: any, sep?: string, eq?: string): string; + export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; + export function escape(str: string): string; + export function unescape(str: string): string; +} + +declare module "events" { + export class EventEmitter implements NodeJS.EventEmitter { + static listenerCount(emitter: EventEmitter, event: string): number; + + addListener(event: string, listener: Function): EventEmitter; + on(event: string, listener: Function): EventEmitter; + once(event: string, listener: Function): EventEmitter; + removeListener(event: string, listener: Function): EventEmitter; + removeAllListeners(event?: string): EventEmitter; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + } +} + +declare module "http" { + import * as events from "events"; + import * as net from "net"; + import * as stream from "stream"; + + export interface Server extends events.EventEmitter { + listen(port: number, hostname?: string, backlog?: number, callback?: Function): Server; + listen(port: number, hostname?: string, callback?: Function): Server; + listen(path: string, callback?: Function): Server; + listen(handle: any, listeningListener?: Function): Server; + close(cb?: any): Server; + address(): { port: number; family: string; address: string; }; + maxHeadersCount: number; + } + /** + * @deprecated Use IncomingMessage + */ + export interface ServerRequest extends IncomingMessage { + connection: net.Socket; + } + export interface ServerResponse extends events.EventEmitter, stream.Writable { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + writeContinue(): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; + writeHead(statusCode: number, headers?: any): void; + statusCode: number; + statusMessage: string; + setHeader(name: string, value: string): void; + sendDate: boolean; + getHeader(name: string): string; + removeHeader(name: string): void; + write(chunk: any, encoding?: string): any; + addTrailers(headers: any): void; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + export interface ClientRequest extends events.EventEmitter, stream.Writable { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + write(chunk: any, encoding?: string): void; + abort(): void; + setTimeout(timeout: number, callback?: Function): void; + setNoDelay(noDelay?: boolean): void; + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + export interface IncomingMessage extends events.EventEmitter, stream.Readable { + httpVersion: string; + headers: any; + rawHeaders: string[]; + trailers: any; + rawTrailers: any; + setTimeout(msecs: number, callback: Function): NodeJS.Timer; + /** + * Only valid for request obtained from http.Server. + */ + method?: string; + /** + * Only valid for request obtained from http.Server. + */ + url?: string; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusCode?: number; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusMessage?: string; + socket: net.Socket; + } + /** + * @deprecated Use IncomingMessage + */ + export interface ClientResponse extends IncomingMessage { } + + export interface AgentOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number; + } + + export class Agent { + maxSockets: number; + sockets: any; + requests: any; + + constructor(opts?: AgentOptions); + + /** + * Destroy any sockets that are currently in use by the agent. + * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, + * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, + * sockets may hang open for quite a long time before the server terminates them. + */ + destroy(): void; + } + + export var METHODS: string[]; + + export var STATUS_CODES: { + [errorCode: number]: string; + [errorCode: string]: string; + }; + export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) =>void ): Server; + export function createClient(port?: number, host?: string): any; + export function request(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; + export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; + export var globalAgent: Agent; +} + +declare module "cluster" { + import * as child from "child_process"; + import * as events from "events"; + + export interface ClusterSettings { + exec?: string; + args?: string[]; + silent?: boolean; + } + + export class Worker extends events.EventEmitter { + id: string; + process: child.ChildProcess; + suicide: boolean; + send(message: any, sendHandle?: any): void; + kill(signal?: string): void; + destroy(signal?: string): void; + disconnect(): void; + } + + export var settings: ClusterSettings; + export var isMaster: boolean; + export var isWorker: boolean; + export function setupMaster(settings?: ClusterSettings): void; + export function fork(env?: any): Worker; + export function disconnect(callback?: Function): void; + export var worker: Worker; + export var workers: Worker[]; + + // Event emitter + export function addListener(event: string, listener: Function): void; + export function on(event: string, listener: Function): any; + export function once(event: string, listener: Function): void; + export function removeListener(event: string, listener: Function): void; + export function removeAllListeners(event?: string): void; + export function setMaxListeners(n: number): void; + export function listeners(event: string): Function[]; + export function emit(event: string, ...args: any[]): boolean; +} + +declare module "zlib" { + import * as stream from "stream"; + export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } + + export interface Gzip extends stream.Transform { } + export interface Gunzip extends stream.Transform { } + export interface Deflate extends stream.Transform { } + export interface Inflate extends stream.Transform { } + export interface DeflateRaw extends stream.Transform { } + export interface InflateRaw extends stream.Transform { } + export interface Unzip extends stream.Transform { } + + export function createGzip(options?: ZlibOptions): Gzip; + export function createGunzip(options?: ZlibOptions): Gunzip; + export function createDeflate(options?: ZlibOptions): Deflate; + export function createInflate(options?: ZlibOptions): Inflate; + export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; + export function createInflateRaw(options?: ZlibOptions): InflateRaw; + export function createUnzip(options?: ZlibOptions): Unzip; + + export function deflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function deflateSync(buf: Buffer, options?: ZlibOptions): any; + export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function deflateRawSync(buf: Buffer, options?: ZlibOptions): any; + export function gzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function gzipSync(buf: Buffer, options?: ZlibOptions): any; + export function gunzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function gunzipSync(buf: Buffer, options?: ZlibOptions): any; + export function inflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function inflateSync(buf: Buffer, options?: ZlibOptions): any; + export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function inflateRawSync(buf: Buffer, options?: ZlibOptions): any; + export function unzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function unzipSync(buf: Buffer, options?: ZlibOptions): any; + + // Constants + export var Z_NO_FLUSH: number; + export var Z_PARTIAL_FLUSH: number; + export var Z_SYNC_FLUSH: number; + export var Z_FULL_FLUSH: number; + export var Z_FINISH: number; + export var Z_BLOCK: number; + export var Z_TREES: number; + export var Z_OK: number; + export var Z_STREAM_END: number; + export var Z_NEED_DICT: number; + export var Z_ERRNO: number; + export var Z_STREAM_ERROR: number; + export var Z_DATA_ERROR: number; + export var Z_MEM_ERROR: number; + export var Z_BUF_ERROR: number; + export var Z_VERSION_ERROR: number; + export var Z_NO_COMPRESSION: number; + export var Z_BEST_SPEED: number; + export var Z_BEST_COMPRESSION: number; + export var Z_DEFAULT_COMPRESSION: number; + export var Z_FILTERED: number; + export var Z_HUFFMAN_ONLY: number; + export var Z_RLE: number; + export var Z_FIXED: number; + export var Z_DEFAULT_STRATEGY: number; + export var Z_BINARY: number; + export var Z_TEXT: number; + export var Z_ASCII: number; + export var Z_UNKNOWN: number; + export var Z_DEFLATED: number; + export var Z_NULL: number; +} + +declare module "os" { + export function tmpdir(): string; + export function hostname(): string; + export function type(): string; + export function platform(): string; + export function arch(): string; + export function release(): string; + export function uptime(): number; + export function loadavg(): number[]; + export function totalmem(): number; + export function freemem(): number; + export function cpus(): { model: string; speed: number; times: { user: number; nice: number; sys: number; idle: number; irq: number; }; }[]; + export function networkInterfaces(): any; + export var EOL: string; +} + +declare module "https" { + import * as tls from "tls"; + import * as events from "events"; + import * as http from "http"; + + export interface ServerOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + crl?: any; + ciphers?: string; + honorCipherOrder?: boolean; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: any; + SNICallback?: (servername: string) => any; + } + + export interface RequestOptions { + host?: string; + hostname?: string; + port?: number; + path?: string; + method?: string; + headers?: any; + auth?: string; + agent?: any; + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + ciphers?: string; + rejectUnauthorized?: boolean; + } + + export interface Agent { + maxSockets: number; + sockets: any; + requests: any; + } + export var Agent: { + new (options?: RequestOptions): Agent; + }; + export interface Server extends tls.Server { } + export function createServer(options: ServerOptions, requestListener?: Function): Server; + export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest; + export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest; + export var globalAgent: Agent; +} + +declare module "punycode" { + export function decode(string: string): string; + export function encode(string: string): string; + export function toUnicode(domain: string): string; + export function toASCII(domain: string): string; + export var ucs2: ucs2; + interface ucs2 { + decode(string: string): string; + encode(codePoints: number[]): string; + } + export var version: any; +} + +declare module "repl" { + import * as stream from "stream"; + import * as events from "events"; + + export interface ReplOptions { + prompt?: string; + input?: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + terminal?: boolean; + eval?: Function; + useColors?: boolean; + useGlobal?: boolean; + ignoreUndefined?: boolean; + writer?: Function; + } + export function start(options: ReplOptions): events.EventEmitter; +} + +declare module "readline" { + import * as events from "events"; + import * as stream from "stream"; + + export interface ReadLine extends events.EventEmitter { + setPrompt(prompt: string): void; + prompt(preserveCursor?: boolean): void; + question(query: string, callback: Function): void; + pause(): void; + resume(): void; + close(): void; + write(data: any, key?: any): void; + } + export interface ReadLineOptions { + input: NodeJS.ReadableStream; + output: NodeJS.WritableStream; + completer?: Function; + terminal?: boolean; + } + export function createInterface(options: ReadLineOptions): ReadLine; +} + +declare module "vm" { + export interface Context { } + export interface Script { + runInThisContext(): void; + runInNewContext(sandbox?: Context): void; + } + export function runInThisContext(code: string, filename?: string): void; + export function runInNewContext(code: string, sandbox?: Context, filename?: string): void; + export function runInContext(code: string, context: Context, filename?: string): void; + export function createContext(initSandbox?: Context): Context; + export function createScript(code: string, filename?: string): Script; +} + +declare module "child_process" { + import * as events from "events"; + import * as stream from "stream"; + + export interface ChildProcess extends events.EventEmitter { + stdin: stream.Writable; + stdout: stream.Readable; + stderr: stream.Readable; + pid: number; + kill(signal?: string): void; + send(message: any, sendHandle?: any): void; + disconnect(): void; + unref(): void; + } + + export function spawn(command: string, args?: string[], options?: { + cwd?: string; + stdio?: any; + custom?: any; + env?: any; + detached?: boolean; + }): ChildProcess; + export function exec(command: string, options: { + cwd?: string; + stdio?: any; + customFds?: any; + env?: any; + encoding?: string; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function exec(command: string, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function execFile(file: string, + callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function execFile(file: string, args?: string[], + callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function execFile(file: string, args?: string[], options?: { + cwd?: string; + stdio?: any; + customFds?: any; + env?: any; + encoding?: string; + timeout?: number; + maxBuffer?: string; + killSignal?: string; + }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function fork(modulePath: string, args?: string[], options?: { + cwd?: string; + env?: any; + encoding?: string; + }): ChildProcess; + export function execSync(command: string, options?: { + cwd?: string; + input?: string|Buffer; + stdio?: any; + env?: any; + uid?: number; + gid?: number; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + encoding?: string; + }): ChildProcess; + export function execFileSync(command: string, args?: string[], options?: { + cwd?: string; + input?: string|Buffer; + stdio?: any; + env?: any; + uid?: number; + gid?: number; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + encoding?: string; + }): ChildProcess; +} + +declare module "url" { + export interface Url { + href: string; + protocol: string; + auth: string; + hostname: string; + port: string; + host: string; + pathname: string; + search: string; + query: any; // string | Object + slashes: boolean; + hash?: string; + path?: string; + } + + export interface UrlOptions { + protocol?: string; + auth?: string; + hostname?: string; + port?: string; + host?: string; + pathname?: string; + search?: string; + query?: any; + hash?: string; + path?: string; + } + + export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url; + export function format(url: UrlOptions): string; + export function resolve(from: string, to: string): string; +} + +declare module "dns" { + export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string; + export function lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string; + export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolve6(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; +} + +declare module "net" { + import * as stream from "stream"; + + export interface Socket extends stream.Duplex { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + connect(port: number, host?: string, connectionListener?: Function): void; + connect(path: string, connectionListener?: Function): void; + bufferSize: number; + setEncoding(encoding?: string): void; + write(data: any, encoding?: string, callback?: Function): void; + destroy(): void; + pause(): void; + resume(): void; + setTimeout(timeout: number, callback?: Function): void; + setNoDelay(noDelay?: boolean): void; + setKeepAlive(enable?: boolean, initialDelay?: number): void; + address(): { port: number; family: string; address: string; }; + unref(): void; + ref(): void; + + remoteAddress: string; + remoteFamily: string; + remotePort: number; + localAddress: string; + localPort: number; + bytesRead: number; + bytesWritten: number; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + + export var Socket: { + new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; + }; + + export interface Server extends Socket { + listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server; + listen(path: string, listeningListener?: Function): Server; + listen(handle: any, listeningListener?: Function): Server; + close(callback?: Function): Server; + address(): { port: number; family: string; address: string; }; + maxConnections: number; + connections: number; + } + export function createServer(connectionListener?: (socket: Socket) =>void ): Server; + export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) =>void ): Server; + export function connect(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function connect(port: number, host?: string, connectionListener?: Function): Socket; + export function connect(path: string, connectionListener?: Function): Socket; + export function createConnection(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; + export function createConnection(path: string, connectionListener?: Function): Socket; + export function isIP(input: string): number; + export function isIPv4(input: string): boolean; + export function isIPv6(input: string): boolean; +} + +declare module "dgram" { + import * as events from "events"; + + interface RemoteInfo { + address: string; + port: number; + size: number; + } + + interface AddressInfo { + address: string; + family: string; + port: number; + } + + export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + + interface Socket extends events.EventEmitter { + send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + bind(port: number, address?: string, callback?: () => void): void; + close(): void; + address(): AddressInfo; + setBroadcast(flag: boolean): void; + setMulticastTTL(ttl: number): void; + setMulticastLoopback(flag: boolean): void; + addMembership(multicastAddress: string, multicastInterface?: string): void; + dropMembership(multicastAddress: string, multicastInterface?: string): void; + } +} + +declare module "fs" { + import * as stream from "stream"; + import * as events from "events"; + + interface Stats { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: number; + ino: number; + mode: number; + nlink: number; + uid: number; + gid: number; + rdev: number; + size: number; + blksize: number; + blocks: number; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + + interface FSWatcher extends events.EventEmitter { + close(): void; + } + + export interface ReadStream extends stream.Readable { + close(): void; + } + export interface WriteStream extends stream.Writable { + close(): void; + bytesWritten: number; + } + + /** + * Asynchronous rename. + * @param oldPath + * @param newPath + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /** + * Synchronous rename + * @param oldPath + * @param newPath + */ + export function renameSync(oldPath: string, newPath: string): void; + export function truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncate(path: string, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncateSync(path: string, len?: number): void; + export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function ftruncateSync(fd: number, len?: number): void; + export function chown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chownSync(path: string, uid: number, gid: number): void; + export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchownSync(fd: number, uid: number, gid: number): void; + export function lchown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchownSync(path: string, uid: number, gid: number): void; + export function chmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmodSync(path: string, mode: number): void; + export function chmodSync(path: string, mode: string): void; + export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchmodSync(fd: number, mode: number): void; + export function fchmodSync(fd: number, mode: string): void; + export function lchmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmodSync(path: string, mode: number): void; + export function lchmodSync(path: string, mode: string): void; + export function stat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function lstat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function statSync(path: string): Stats; + export function lstatSync(path: string): Stats; + export function fstatSync(fd: number): Stats; + export function link(srcpath: string, dstpath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function linkSync(srcpath: string, dstpath: string): void; + export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function symlinkSync(srcpath: string, dstpath: string, type?: string): void; + export function readlink(path: string, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; + export function readlinkSync(path: string): string; + export function realpath(path: string, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; + export function realpath(path: string, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) =>any): void; + export function realpathSync(path: string, cache?: { [path: string]: string }): string; + /* + * Asynchronous unlink - deletes the file specified in {path} + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Synchronous unlink - deletes the file specified in {path} + * + * @param path + */ + export function unlinkSync(path: string): void; + /* + * Asynchronous rmdir - removes the directory specified in {path} + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Synchronous rmdir - removes the directory specified in {path} + * + * @param path + */ + export function rmdirSync(path: string): void; + /* + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdir(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdir(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdirSync(path: string, mode?: number): void; + /* + * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdirSync(path: string, mode?: string): void; + export function readdir(path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; + export function readdirSync(path: string): string[]; + export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function closeSync(fd: number): void; + export function open(path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function open(path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function open(path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function openSync(path: string, flags: string, mode?: number): number; + export function openSync(path: string, flags: string, mode?: string): number; + export function utimes(path: string, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimes(path: string, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimesSync(path: string, atime: number, mtime: number): void; + export function utimesSync(path: string, atime: Date, mtime: Date): void; + export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function futimesSync(fd: number, atime: number, mtime: number): void; + export function futimesSync(fd: number, atime: Date, mtime: Date): void; + export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fsyncSync(fd: number): void; + export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; + export function write(fd: number, buffer: Buffer, offset: number, length: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; + export function write(fd: number, data: any, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function write(fd: number, data: any, offset: number, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function write(fd: number, data: any, offset: number, encoding: string, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; + export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; + export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param encoding + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + /* + * Synchronous readFile - Synchronously reads the entire contents of a file. + * + * @param fileName + * @param encoding + */ + export function readFileSync(filename: string, encoding: string): string; + /* + * Synchronous readFile - Synchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. + */ + export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; + /* + * Synchronous readFile - Synchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. + */ + export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; + export function writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; + export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; + export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; + export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; + export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void; + export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; + export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; + export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; + export function watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; + export function exists(path: string, callback?: (exists: boolean) => void): void; + export function existsSync(path: string): boolean; + /** Constant for fs.access(). File is visible to the calling process. */ + export var F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + export var R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + export var W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + export var X_OK: number; + /** Tests a user's permissions for the file specified by path. */ + export function access(path: string, callback: (err: NodeJS.ErrnoException) => void): void; + export function access(path: string, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; + /** Synchronous version of fs.access. This throws if any accessibility checks fail, and does nothing otherwise. */ + export function accessSync(path: string, mode ?: number): void; + export function createReadStream(path: string, options?: { + flags?: string; + encoding?: string; + fd?: string; + mode?: number; + bufferSize?: number; + }): ReadStream; + export function createReadStream(path: string, options?: { + flags?: string; + encoding?: string; + fd?: string; + mode?: string; + bufferSize?: number; + }): ReadStream; + export function createWriteStream(path: string, options?: { + flags?: string; + encoding?: string; + string?: string; + }): WriteStream; +} + +declare module "path" { + + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + export interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param p string path to normalize. + */ + export function normalize(p: string): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths string paths to join. + */ + export function join(...paths: any[]): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths string paths to join. + */ + export function join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param pathSegments string paths to join. Non-string arguments are ignored. + */ + export function resolve(...pathSegments: any[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * @param path path to test. + */ + export function isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to}. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + * + * @param from + * @param to + */ + export function relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param p the path to evaluate. + */ + export function dirname(p: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param p the path to evaluate. + * @param ext optionally, an extension to remove from the result. + */ + export function basename(p: string, ext?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string + * + * @param p the path to evaluate. + */ + export function extname(p: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + export var sep: string; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + export var delimiter: string; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param pathString path to evaluate. + */ + export function parse(pathString: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathString path to evaluate. + */ + export function format(pathObject: ParsedPath): string; + + export module posix { + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; + } + + export module win32 { + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; + } +} + +declare module "string_decoder" { + export interface NodeStringDecoder { + write(buffer: Buffer): string; + detectIncompleteChar(buffer: Buffer): number; + } + export var StringDecoder: { + new (encoding: string): NodeStringDecoder; + }; +} + +declare module "tls" { + import * as crypto from "crypto"; + import * as net from "net"; + import * as stream from "stream"; + + var CLIENT_RENEG_LIMIT: number; + var CLIENT_RENEG_WINDOW: number; + + export interface TlsOptions { + pfx?: any; //string or buffer + key?: any; //string or buffer + passphrase?: string; + cert?: any; + ca?: any; //string or buffer + crl?: any; //string or string array + ciphers?: string; + honorCipherOrder?: any; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: any; //array or Buffer; + SNICallback?: (servername: string) => any; + } + + export interface ConnectionOptions { + host?: string; + port?: number; + socket?: net.Socket; + pfx?: any; //string | Buffer + key?: any; //string | Buffer + passphrase?: string; + cert?: any; //string | Buffer + ca?: any; //Array of string | Buffer + rejectUnauthorized?: boolean; + NPNProtocols?: any; //Array of string | Buffer + servername?: string; + } + + export interface Server extends net.Server { + // Extended base methods + listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server; + listen(path: string, listeningListener?: Function): Server; + listen(handle: any, listeningListener?: Function): Server; + + listen(port: number, host?: string, callback?: Function): Server; + close(): Server; + address(): { port: number; family: string; address: string; }; + addContext(hostName: string, credentials: { + key: string; + cert: string; + ca: string; + }): void; + maxConnections: number; + connections: number; + } + + export interface ClearTextStream extends stream.Duplex { + authorized: boolean; + authorizationError: Error; + getPeerCertificate(): any; + getCipher: { + name: string; + version: string; + }; + address: { + port: number; + family: string; + address: string; + }; + remoteAddress: string; + remotePort: number; + } + + export interface SecurePair { + encrypted: any; + cleartext: any; + } + + export interface SecureContextOptions { + pfx?: any; //string | buffer + key?: any; //string | buffer + passphrase?: string; + cert?: any; // string | buffer + ca?: any; // string | buffer + crl?: any; // string | string[] + ciphers?: string; + honorCipherOrder?: boolean; + } + + export interface SecureContext { + context: any; + } + + export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) =>void ): Server; + export function connect(options: TlsOptions, secureConnectionListener?: () =>void ): ClearTextStream; + export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; + export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; + export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; + export function createSecureContext(details: SecureContextOptions): SecureContext; +} + +declare module "crypto" { + export interface CredentialDetails { + pfx: string; + key: string; + passphrase: string; + cert: string; + ca: any; //string | string array + crl: any; //string | string array + ciphers: string; + } + export interface Credentials { context?: any; } + export function createCredentials(details: CredentialDetails): Credentials; + export function createHash(algorithm: string): Hash; + export function createHmac(algorithm: string, key: string): Hmac; + export function createHmac(algorithm: string, key: Buffer): Hmac; + interface Hash { + update(data: any, input_encoding?: string): Hash; + digest(encoding: 'buffer'): Buffer; + digest(encoding: string): any; + digest(): Buffer; + } + interface Hmac { + update(data: any, input_encoding?: string): Hmac; + digest(encoding: 'buffer'): Buffer; + digest(encoding: string): any; + digest(): Buffer; + } + export function createCipher(algorithm: string, password: any): Cipher; + export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; + interface Cipher { + update(data: Buffer): Buffer; + update(data: string, input_encoding?: string, output_encoding?: string): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding: boolean): void; + } + export function createDecipher(algorithm: string, password: any): Decipher; + export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; + interface Decipher { + update(data: Buffer): Buffer; + update(data: string, input_encoding?: string, output_encoding?: string): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding: boolean): void; + } + export function createSign(algorithm: string): Signer; + interface Signer extends NodeJS.WritableStream { + update(data: any): void; + sign(private_key: string, output_format: string): string; + } + export function createVerify(algorith: string): Verify; + interface Verify extends NodeJS.WritableStream { + update(data: any): void; + verify(object: string, signature: string, signature_format?: string): boolean; + } + export function createDiffieHellman(prime_length: number): DiffieHellman; + export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman; + interface DiffieHellman { + generateKeys(encoding?: string): string; + computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; + getPrime(encoding?: string): string; + getGenerator(encoding: string): string; + getPublicKey(encoding?: string): string; + getPrivateKey(encoding?: string): string; + setPublicKey(public_key: string, encoding?: string): void; + setPrivateKey(public_key: string, encoding?: string): void; + } + export function getDiffieHellman(group_name: string): DiffieHellman; + export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2Sync(password: string, salt: string, iterations: number, keylen: number) : Buffer; + export function pbkdf2Sync(password: string, salt: string, iterations: number, keylen: number, digest: string) : Buffer; + export function randomBytes(size: number): Buffer; + export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; + export function pseudoRandomBytes(size: number): Buffer; + export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; +} + +declare module "stream" { + import * as events from "events"; + + export interface Stream extends events.EventEmitter { + pipe(destination: T, options?: { end?: boolean; }): T; + } + + export interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + } + + export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { + readable: boolean; + constructor(opts?: ReadableOptions); + _read(size: number): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + } + + export interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + } + + export class Writable extends events.EventEmitter implements NodeJS.WritableStream { + writable: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + } + + // Note: Duplex extends both Readable and Writable. + export class Duplex extends Readable implements NodeJS.ReadWriteStream { + writable: boolean; + constructor(opts?: DuplexOptions); + _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export interface TransformOptions extends ReadableOptions, WritableOptions {} + + // Note: Transform lacks the _read and _write methods of Readable/Writable. + export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { + readable: boolean; + writable: boolean; + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: string, callback: Function): void; + _flush(callback: Function): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export class PassThrough extends Transform {} +} + +declare module "util" { + export interface InspectOptions { + showHidden?: boolean; + depth?: number; + colors?: boolean; + customInspect?: boolean; + } + + export function format(format: any, ...param: any[]): string; + export function debug(string: string): void; + export function error(...param: any[]): void; + export function puts(...param: any[]): void; + export function print(...param: any[]): void; + export function log(string: string): void; + export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string; + export function inspect(object: any, options: InspectOptions): string; + export function isArray(object: any): boolean; + export function isRegExp(object: any): boolean; + export function isDate(object: any): boolean; + export function isError(object: any): boolean; + export function inherits(constructor: any, superConstructor: any): void; +} + +declare module "assert" { + function internal (value: any, message?: string): void; + module internal { + export class AssertionError implements Error { + name: string; + message: string; + actual: any; + expected: any; + operator: string; + generatedMessage: boolean; + + constructor(options?: {message?: string; actual?: any; expected?: any; + operator?: string; stackStartFunction?: Function}); + } + + export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; + export function ok(value: any, message?: string): void; + export function equal(actual: any, expected: any, message?: string): void; + export function notEqual(actual: any, expected: any, message?: string): void; + export function deepEqual(actual: any, expected: any, message?: string): void; + export function notDeepEqual(acutal: any, expected: any, message?: string): void; + export function strictEqual(actual: any, expected: any, message?: string): void; + export function notStrictEqual(actual: any, expected: any, message?: string): void; + export var throws: { + (block: Function, message?: string): void; + (block: Function, error: Function, message?: string): void; + (block: Function, error: RegExp, message?: string): void; + (block: Function, error: (err: any) => boolean, message?: string): void; + }; + + export var doesNotThrow: { + (block: Function, message?: string): void; + (block: Function, error: Function, message?: string): void; + (block: Function, error: RegExp, message?: string): void; + (block: Function, error: (err: any) => boolean, message?: string): void; + }; + + export function ifError(value: any): void; + } + + export = internal; +} + +declare module "tty" { + import * as net from "net"; + + export function isatty(fd: number): boolean; + export interface ReadStream extends net.Socket { + isRaw: boolean; + setRawMode(mode: boolean): void; + } + export interface WriteStream extends net.Socket { + columns: number; + rows: number; + } +} + +declare module "domain" { + import * as events from "events"; + + export class Domain extends events.EventEmitter { + run(fn: Function): void; + add(emitter: events.EventEmitter): void; + remove(emitter: events.EventEmitter): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + dispose(): void; + + addListener(event: string, listener: Function): Domain; + on(event: string, listener: Function): Domain; + once(event: string, listener: Function): Domain; + removeListener(event: string, listener: Function): Domain; + removeAllListeners(event?: string): Domain; + } + + export function create(): Domain; +} + +declare module "constants" { + export var E2BIG: number; + export var EACCES: number; + export var EADDRINUSE: number; + export var EADDRNOTAVAIL: number; + export var EAFNOSUPPORT: number; + export var EAGAIN: number; + export var EALREADY: number; + export var EBADF: number; + export var EBADMSG: number; + export var EBUSY: number; + export var ECANCELED: number; + export var ECHILD: number; + export var ECONNABORTED: number; + export var ECONNREFUSED: number; + export var ECONNRESET: number; + export var EDEADLK: number; + export var EDESTADDRREQ: number; + export var EDOM: number; + export var EEXIST: number; + export var EFAULT: number; + export var EFBIG: number; + export var EHOSTUNREACH: number; + export var EIDRM: number; + export var EILSEQ: number; + export var EINPROGRESS: number; + export var EINTR: number; + export var EINVAL: number; + export var EIO: number; + export var EISCONN: number; + export var EISDIR: number; + export var ELOOP: number; + export var EMFILE: number; + export var EMLINK: number; + export var EMSGSIZE: number; + export var ENAMETOOLONG: number; + export var ENETDOWN: number; + export var ENETRESET: number; + export var ENETUNREACH: number; + export var ENFILE: number; + export var ENOBUFS: number; + export var ENODATA: number; + export var ENODEV: number; + export var ENOENT: number; + export var ENOEXEC: number; + export var ENOLCK: number; + export var ENOLINK: number; + export var ENOMEM: number; + export var ENOMSG: number; + export var ENOPROTOOPT: number; + export var ENOSPC: number; + export var ENOSR: number; + export var ENOSTR: number; + export var ENOSYS: number; + export var ENOTCONN: number; + export var ENOTDIR: number; + export var ENOTEMPTY: number; + export var ENOTSOCK: number; + export var ENOTSUP: number; + export var ENOTTY: number; + export var ENXIO: number; + export var EOPNOTSUPP: number; + export var EOVERFLOW: number; + export var EPERM: number; + export var EPIPE: number; + export var EPROTO: number; + export var EPROTONOSUPPORT: number; + export var EPROTOTYPE: number; + export var ERANGE: number; + export var EROFS: number; + export var ESPIPE: number; + export var ESRCH: number; + export var ETIME: number; + export var ETIMEDOUT: number; + export var ETXTBSY: number; + export var EWOULDBLOCK: number; + export var EXDEV: number; + export var WSAEINTR: number; + export var WSAEBADF: number; + export var WSAEACCES: number; + export var WSAEFAULT: number; + export var WSAEINVAL: number; + export var WSAEMFILE: number; + export var WSAEWOULDBLOCK: number; + export var WSAEINPROGRESS: number; + export var WSAEALREADY: number; + export var WSAENOTSOCK: number; + export var WSAEDESTADDRREQ: number; + export var WSAEMSGSIZE: number; + export var WSAEPROTOTYPE: number; + export var WSAENOPROTOOPT: number; + export var WSAEPROTONOSUPPORT: number; + export var WSAESOCKTNOSUPPORT: number; + export var WSAEOPNOTSUPP: number; + export var WSAEPFNOSUPPORT: number; + export var WSAEAFNOSUPPORT: number; + export var WSAEADDRINUSE: number; + export var WSAEADDRNOTAVAIL: number; + export var WSAENETDOWN: number; + export var WSAENETUNREACH: number; + export var WSAENETRESET: number; + export var WSAECONNABORTED: number; + export var WSAECONNRESET: number; + export var WSAENOBUFS: number; + export var WSAEISCONN: number; + export var WSAENOTCONN: number; + export var WSAESHUTDOWN: number; + export var WSAETOOMANYREFS: number; + export var WSAETIMEDOUT: number; + export var WSAECONNREFUSED: number; + export var WSAELOOP: number; + export var WSAENAMETOOLONG: number; + export var WSAEHOSTDOWN: number; + export var WSAEHOSTUNREACH: number; + export var WSAENOTEMPTY: number; + export var WSAEPROCLIM: number; + export var WSAEUSERS: number; + export var WSAEDQUOT: number; + export var WSAESTALE: number; + export var WSAEREMOTE: number; + export var WSASYSNOTREADY: number; + export var WSAVERNOTSUPPORTED: number; + export var WSANOTINITIALISED: number; + export var WSAEDISCON: number; + export var WSAENOMORE: number; + export var WSAECANCELLED: number; + export var WSAEINVALIDPROCTABLE: number; + export var WSAEINVALIDPROVIDER: number; + export var WSAEPROVIDERFAILEDINIT: number; + export var WSASYSCALLFAILURE: number; + export var WSASERVICE_NOT_FOUND: number; + export var WSATYPE_NOT_FOUND: number; + export var WSA_E_NO_MORE: number; + export var WSA_E_CANCELLED: number; + export var WSAEREFUSED: number; + export var SIGHUP: number; + export var SIGINT: number; + export var SIGILL: number; + export var SIGABRT: number; + export var SIGFPE: number; + export var SIGKILL: number; + export var SIGSEGV: number; + export var SIGTERM: number; + export var SIGBREAK: number; + export var SIGWINCH: number; + export var SSL_OP_ALL: number; + export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + export var SSL_OP_CIPHER_SERVER_PREFERENCE: number; + export var SSL_OP_CISCO_ANYCONNECT: number; + export var SSL_OP_COOKIE_EXCHANGE: number; + export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + export var SSL_OP_EPHEMERAL_RSA: number; + export var SSL_OP_LEGACY_SERVER_CONNECT: number; + export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + export var SSL_OP_MICROSOFT_SESS_ID_BUG: number; + export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + export var SSL_OP_NETSCAPE_CA_DN_BUG: number; + export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + export var SSL_OP_NO_COMPRESSION: number; + export var SSL_OP_NO_QUERY_MTU: number; + export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + export var SSL_OP_NO_SSLv2: number; + export var SSL_OP_NO_SSLv3: number; + export var SSL_OP_NO_TICKET: number; + export var SSL_OP_NO_TLSv1: number; + export var SSL_OP_NO_TLSv1_1: number; + export var SSL_OP_NO_TLSv1_2: number; + export var SSL_OP_PKCS1_CHECK_1: number; + export var SSL_OP_PKCS1_CHECK_2: number; + export var SSL_OP_SINGLE_DH_USE: number; + export var SSL_OP_SINGLE_ECDH_USE: number; + export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + export var SSL_OP_TLS_BLOCK_PADDING_BUG: number; + export var SSL_OP_TLS_D5_BUG: number; + export var SSL_OP_TLS_ROLLBACK_BUG: number; + export var ENGINE_METHOD_DSA: number; + export var ENGINE_METHOD_DH: number; + export var ENGINE_METHOD_RAND: number; + export var ENGINE_METHOD_ECDH: number; + export var ENGINE_METHOD_ECDSA: number; + export var ENGINE_METHOD_CIPHERS: number; + export var ENGINE_METHOD_DIGESTS: number; + export var ENGINE_METHOD_STORE: number; + export var ENGINE_METHOD_PKEY_METHS: number; + export var ENGINE_METHOD_PKEY_ASN1_METHS: number; + export var ENGINE_METHOD_ALL: number; + export var ENGINE_METHOD_NONE: number; + export var DH_CHECK_P_NOT_SAFE_PRIME: number; + export var DH_CHECK_P_NOT_PRIME: number; + export var DH_UNABLE_TO_CHECK_GENERATOR: number; + export var DH_NOT_SUITABLE_GENERATOR: number; + export var NPN_ENABLED: number; + export var RSA_PKCS1_PADDING: number; + export var RSA_SSLV23_PADDING: number; + export var RSA_NO_PADDING: number; + export var RSA_PKCS1_OAEP_PADDING: number; + export var RSA_X931_PADDING: number; + export var RSA_PKCS1_PSS_PADDING: number; + export var POINT_CONVERSION_COMPRESSED: number; + export var POINT_CONVERSION_UNCOMPRESSED: number; + export var POINT_CONVERSION_HYBRID: number; + export var O_RDONLY: number; + export var O_WRONLY: number; + export var O_RDWR: number; + export var S_IFMT: number; + export var S_IFREG: number; + export var S_IFDIR: number; + export var S_IFCHR: number; + export var S_IFLNK: number; + export var O_CREAT: number; + export var O_EXCL: number; + export var O_TRUNC: number; + export var O_APPEND: number; + export var F_OK: number; + export var R_OK: number; + export var W_OK: number; + export var X_OK: number; + export var UV_UDP_REUSEADDR: number; +} diff --git a/async/src/lib/typings/tsd.d.ts b/async/src/lib/typings/tsd.d.ts new file mode 100644 index 0000000..a8b1fe5 --- /dev/null +++ b/async/src/lib/typings/tsd.d.ts @@ -0,0 +1,2 @@ + +/// diff --git a/async/src/lib/utils.ts b/async/src/lib/utils.ts new file mode 100644 index 0000000..f56107e --- /dev/null +++ b/async/src/lib/utils.ts @@ -0,0 +1,133 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +"use strict"; + +export class LazyPromise extends Promise { + public static [Symbol.species] = Promise; + + private _resolve: (value: T | PromiseLike) => void; + private _reject: (reason: any) => void; + private _executor: (resolve: (value: T | PromiseLike) => void, reject: (reason: any) => void) => void; + + public constructor(executor: (resolve: (value: T | PromiseLike) => void, reject: (reason: any) => void) => void) { + let resolver: (value: T | PromiseLike) => void; + let rejecter: (reason: any) => void; + super((resolve, reject) => { resolver = resolve; rejecter = reject; }); + this._resolve = resolver; + this._reject = rejecter; + this._executor = executor; + } + + public then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise { + this._lazyExecute(); + return super.then(onfulfilled, onrejected); + } + + private _lazyExecute() { + if (this._executor) { + let executor = this._executor, resolve = this._resolve, reject = this._reject; + delete this._executor; + delete this._resolve; + delete this._reject; + try { + executor(resolve, reject); + } + catch (e) { + reject(e); + } + } + } +} + +export function sleep(msec: number) { + return new Promise(resolve => setTimeout(resolve, msec)); +} + +export function formatMessage(text: string, firstLineWidth: number, remainingLinesWidth?: number) { + if (remainingLinesWidth === undefined) remainingLinesWidth = firstLineWidth; + let pattern = /(\r\n?|\n)|(\s)|(\S+)/g; + let match: RegExpMatchArray; + let lines: string[] = []; + let line: string = ""; + let leadingWhiteSpace: string = ""; + let width = firstLineWidth; + while (match = pattern.exec(text)) { + if (match[1]) { + lines.push(line); + width = remainingLinesWidth; + line = ""; + leadingWhiteSpace = ""; + } + else if (match[2]) { + leadingWhiteSpace += match[2]; + } + else if (match[3]) { + let token = match[3]; + let lineLengthWithWhitespace = line.length + leadingWhiteSpace.length; + let lineLengthWithText = lineLengthWithWhitespace + token.length; + if (token.length > width) { + // If there is room, append the first chunk of the long line to the + // current line. + let offset = 0; + if (lineLengthWithWhitespace < width) { + let chunk = token.substr(offset, width - lineLengthWithWhitespace); + line += leadingWhiteSpace + chunk; + offset += chunk.length; + } + + // Push the current line. + if (line) { + lines.push(line); + width = remainingLinesWidth; + line = ""; + } + + leadingWhiteSpace = ""; + + // Append lines for each chunk longer than one line. + while (token.length - offset > width) { + lines.push(token.substr(offset, width)); + width = remainingLinesWidth; + offset += width; + } + + // Append the remaining text to the current line. + if (token.length - offset > 0) { + line = token.substr(offset); + } + else { + line = ""; + } + } + else if (lineLengthWithText > width) { + lines.push(line); + width = remainingLinesWidth; + line = token; + leadingWhiteSpace = ""; + } + else { + line += leadingWhiteSpace + token; + leadingWhiteSpace = ""; + } + } + } + + if (line) { + lines.push(line); + } + + return lines; +} \ No newline at end of file diff --git a/browserify/.gitignore b/browserify/.gitignore new file mode 100644 index 0000000..4c43fe6 --- /dev/null +++ b/browserify/.gitignore @@ -0,0 +1 @@ +*.js \ No newline at end of file diff --git a/browserify/README.md b/browserify/README.md new file mode 100644 index 0000000..ea600ee --- /dev/null +++ b/browserify/README.md @@ -0,0 +1,63 @@ +**Install Browserify** + +```shell +npm install -g browserify +``` + +**Fetch dependencies** + +```shell +npm install +``` + +**Compile .ts files** + +Either enter the following command + +```shell +node node_modules/typescript/bin/tsc.js +``` + +or use the `tsc` script from our `package.json` with + +```shell +npm run tsc +``` + +**Run Browserify** + +Either enter the following command + +```shell +browserify src/app.js -o bundle.js -s app +``` + +or use the `browserify` script from our `package.json` with + +```shell +npm run browserify + +``` + +**Start http-server** + +Either enter the following command + +```shell +node node_modules/http-server/bin/http-server -o +``` + +or use the `listen` script from our `package.json` with + +``` +npm run listen +``` + +By default http-server listens on port `8080`. +If this port is taken, use '-p ####' to specify a free port, where `####` is the available port. + +**Shortcut for running all steps in a batch** + +``` +npm run all +``` \ No newline at end of file diff --git a/browserify/app.css b/browserify/app.css new file mode 100644 index 0000000..eb24fc6 --- /dev/null +++ b/browserify/app.css @@ -0,0 +1,8 @@ +body +{ + font-family: 'Segoe UI', sans-serif +} + +span { + font-style: italic +} \ No newline at end of file diff --git a/browserify/index.html b/browserify/index.html new file mode 100644 index 0000000..bacd21a --- /dev/null +++ b/browserify/index.html @@ -0,0 +1,22 @@ + + + + + + TypeScript HTML App + + + + +

Browserify/TypeScript sample

+
+ + + + + \ No newline at end of file diff --git a/browserify/package.json b/browserify/package.json new file mode 100644 index 0000000..d6b3f94 --- /dev/null +++ b/browserify/package.json @@ -0,0 +1,21 @@ +{ + "name": "typescript-browserify", + "version": "1.0.0", + "description": "Browserify/TypeScript demo", + "repository": { + "type": "git", + "url": "https://github.com/Microsoft/TypeScriptSamples.git" + }, + "dependencies": { + "http-server": "0.8.0" + }, + "devDependencies": { + "typescript": "^1.8.9" + }, + "scripts": { + "tsc": "node node_modules/typescript/lib/tsc.js", + "browserify": "browserify src/app.js -o bundle.js -s app", + "listen": "node node_modules/http-server/bin/http-server", + "all": "npm run tsc && npm run browserify && npm run listen" + } +} diff --git a/browserify/src/app.ts b/browserify/src/app.ts new file mode 100644 index 0000000..76779fb --- /dev/null +++ b/browserify/src/app.ts @@ -0,0 +1,8 @@ +import { TimeReporter, Printer } from './timeReporter' +import { EOL } from 'os'; + + +export function start(printer: Printer) { + let timeReporter = new TimeReporter(printer); + timeReporter.start(); +} \ No newline at end of file diff --git a/browserify/src/node.d.ts b/browserify/src/node.d.ts new file mode 100644 index 0000000..eee9af5 --- /dev/null +++ b/browserify/src/node.d.ts @@ -0,0 +1,7 @@ +declare module "os" { + export var EOL: string; +} + +declare module "util" { + export function format(format: string, ...args: any[]): string; +} diff --git a/browserify/src/timeReporter.ts b/browserify/src/timeReporter.ts new file mode 100644 index 0000000..afe930f --- /dev/null +++ b/browserify/src/timeReporter.ts @@ -0,0 +1,27 @@ +import {format} from "util"; + +export type Printer = (s: string) => void; + +export class TimeReporter +{ + timerToken: number; + + constructor (private printer: Printer) + { + this.reportDate(); + } + + start() + { + this.timerToken = setInterval(() => this.reportDate(), 500); + } + + stop() + { + clearTimeout(this.timerToken); + } + + reportDate() { + this.printer(format("Date is %s", new Date().toUTCString())); + } +} diff --git a/browserify/tsconfig.json b/browserify/tsconfig.json new file mode 100644 index 0000000..6a22f00 --- /dev/null +++ b/browserify/tsconfig.json @@ -0,0 +1,6 @@ +{ + "compilerOptions": { + "module": "CommonJS", + "target": "es5" + } +} \ No newline at end of file diff --git a/buildall.cmd b/buildall.cmd index 31d6ba3..bfdd49e 100644 --- a/buildall.cmd +++ b/buildall.cmd @@ -1,71 +1,71 @@ -@echo off & setlocal EnableDelayedExpansion - -if "%1"=="" ( - goto :Help -) - -goto :Start - - -:Help -Echo ********************************************************** -Echo Usage: -Echo buildall.cmd tscPath -Echo Example: -Echo buildall c:\typescript\built\local\tsc.js -Echo ********************************************************** -goto :Done - - -:Start -set tscPath=%1 -set CURRENTDIR=%~dp0 - -call :buildProject "amd" "--sourcemap --module amd %CURRENTDIR%amd\app.ts" -call :buildProject "d3" "--sourcemap %CURRENTDIR%d3\data.ts" -call :buildProject "greeter" "--sourcemap %CURRENTDIR%greeter\greeter.ts" -call :buildProject "imageboard" "--sourcemap --module commonjs %CURRENTDIR%imageboard\app.ts" -call :buildProject "interfaces" "--sourcemap %CURRENTDIR%interfaces\interfaces.ts" -call :buildProject "jquery" "--sourcemap --target ES5 %CURRENTDIR%jquery\parallax.ts" -call :buildProject "mankala" "Driver.ts --sourcemap -out %CURRENTDIR%mankalagame.js" -call :buildProject "node" "--sourcemap --module commonjs %CURRENTDIR%node\HttpServer.ts" -call :buildProject "node" "--sourcemap --module commonjs %CURRENTDIR%node\TcpServer.ts" -call :buildProject "raytracer" "--sourcemap %CURRENTDIR%raytracer\raytracer.ts" -call :buildProject "simple" "--sourcemap %CURRENTDIR%simple\animals.ts" -call :buildProject "todomvc" "--sourcemap %CURRENTDIR%todomvc\js\todos.ts" -call :buildProject "warship" "--sourcemap --target ES5 %CURRENTDIR%warship\warship.ts" - -goto :Done - -:buildProject -pushd %CURRENTDIR%%~1 -echo Running %~1 using node... - -echo on -call node "%tscPath%" %~2 -echo off - -if not %errorlevel%==0 ( - echo Failed! -) else ( - echo Done. -) - -echo Running %~1 using cscript... - -echo on -call cscript /nologo "%tscPath%" %~2 -echo off - -if not %errorlevel%==0 ( - echo Failed! -) else ( - echo Done. -) - -popd -goto :eof - - -:Done +@echo off & setlocal EnableDelayedExpansion + +if "%1"=="" ( + goto :Help +) + +goto :Start + + +:Help +Echo ********************************************************** +Echo Usage: +Echo buildall.cmd tscPath +Echo Example: +Echo buildall c:\typescript\built\local\tsc.js +Echo ********************************************************** +goto :Done + + +:Start +set tscPath=%1 +set CURRENTDIR=%~dp0 + +call :buildProject "amd" "--sourcemap --module amd %CURRENTDIR%amd\app.ts" +call :buildProject "d3" "--sourcemap %CURRENTDIR%d3\data.ts" +call :buildProject "greeter" "--sourcemap %CURRENTDIR%greeter\greeter.ts" +call :buildProject "imageboard" "--sourcemap --module commonjs %CURRENTDIR%imageboard\app.ts" +call :buildProject "interfaces" "--sourcemap %CURRENTDIR%interfaces\interfaces.ts" +call :buildProject "jquery" "--sourcemap --target ES5 %CURRENTDIR%jquery\parallax.ts" +call :buildProject "mankala" "Driver.ts --sourcemap -out %CURRENTDIR%mankalagame.js" +call :buildProject "node" "--sourcemap --module commonjs %CURRENTDIR%node\HttpServer.ts" +call :buildProject "node" "--sourcemap --module commonjs %CURRENTDIR%node\TcpServer.ts" +call :buildProject "raytracer" "--sourcemap %CURRENTDIR%raytracer\raytracer.ts" +call :buildProject "simple" "--sourcemap %CURRENTDIR%simple\animals.ts" +call :buildProject "todomvc" "--sourcemap %CURRENTDIR%todomvc\js\todos.ts" +call :buildProject "warship" "--sourcemap --target ES5 %CURRENTDIR%warship\warship.ts" + +goto :Done + +:buildProject +pushd %CURRENTDIR%%~1 +echo Running %~1 using node... + +echo on +call node "%tscPath%" %~2 +echo off + +if not %errorlevel%==0 ( + echo Failed! +) else ( + echo Done. +) + +echo Running %~1 using cscript... + +echo on +call cscript /nologo "%tscPath%" %~2 +echo off + +if not %errorlevel%==0 ( + echo Failed! +) else ( + echo Done. +) + +popd +goto :eof + + +:Done ENDLOCAL \ No newline at end of file diff --git a/d3/d3.d.ts b/d3/d3.d.ts index c5f51bf..7d0a6a0 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -1,277 +1,277 @@ -interface ID3Selectors { - select: (selector: string) => ID3Selection; - selectAll: (selector: string) => ID3Selection; -} - -interface ID3Base extends ID3Selectors { - // Array Helpers - ascending: (a: number, b: number) => number; - descending: (a: number, b: number) => number; - min(arr: T[], map: (v: T) => U ): U; - min(arr: T[]): T; - max(arr: T[], map: (v: T) => U ): U; - max(arr: T[]): T; - extent(arr: T[], map: (v: T) => U): U[]; - extent(arr: T[]): T[]; - quantile: (arr: number[], p: number) => number; - bisectLeft(arr: T[], x: T, low?: number, high?: number): number; - bisect(arr: T[], x: T, low?: number, high?: number): number; - bisectRight(arr: T[], x: T, low?: number, high?: number): number; - - // Loading resources - xhr: { - (url: string, callback: (xhr: XMLHttpRequest) => void): void; - (url: string, mime: string, callback: (xhr: XMLHttpRequest) => void): void; - }; - text: { - (url: string, callback: (response: string) => void): void; - (url: string, mime: string, callback: (response: string) => void): void; - }; - json: (url: string, callback: (response: any) => void) => void; - xml: { - (url: string, callback: (response: Document) => void): void; - (url: string, mime: string, callback: (response: Document) => void): void; - }; - html: (url: string, callback: (response: DocumentFragment) => void) => void; - csv: { - (url: string, callback: (response: any[]) => void); - parse(string: string): any[]; - parseRows(string: string, accessor: (row: any[], index: number) => any): any; - format(rows: any[]): string; - }; - - time: ID3Time; - scale: { - linear(): ID3LinearScale; - }; - interpolate: ID3BaseInterpolate; - interpolateNumber: ID3BaseInterpolate; - interpolateRound: ID3BaseInterpolate; - interpolateString: ID3BaseInterpolate; - interpolateRgb: ID3BaseInterpolate; - interpolateHsl: ID3BaseInterpolate; - interpolateArray: ID3BaseInterpolate; - interpolateObject: ID3BaseInterpolate; - interpolateTransform: ID3BaseInterpolate; - layout: ID3Layout; - svg: ID3Svg; - random: ID3Random; -} - -interface ID3Selection extends ID3Selectors { - attr: { - (name: string): string; - (name: string, value: any): ID3Selection; - (name: string, valueFunction: (data: any, index: number) => any): ID3Selection; - }; - - classed: { - (name: string): string; - (name: string, value: any): ID3Selection; - (name: string, valueFunction: (data: any, index: number) => any): ID3Selection; - }; - - style: { - (name: string): string; - (name: string, value: any, priority?: string): ID3Selection; - (name: string, valueFunction: (data: any, index: number) => any, priority?: string): ID3Selection; - }; - - property: { - (name: string): void; - (name: string, value: any): ID3Selection; - (name: string, valueFunction: (data: any, index: number) => any): ID3Selection; - }; - - text: { - (): string; - (value: any): ID3Selection; - (valueFunction: (data: any, index: number) => any): ID3Selection; - }; - - html: { - (): string; - (value: any): ID3Selection; - (valueFunction: (data: any, index: number) => any): ID3Selection; - }; - - append: (name: string) => ID3Selection; - insert: (name: string, before: string) => ID3Selection; - remove: () => ID3Selection; - - data: { - (values: (data: any, index: number) => any) : any; - (values: any[], key?: (data: any, index: number) => any): ID3UpdateSelection; - }; - - call(callback: (selection: ID3Selection) => void): ID3Selection; -} - -interface ID3EnterSelection { - append: (name: string) => ID3Selection; - insert: (name: string, before: string) => ID3Selection; - select: (selector: string) => ID3Selection; - empty: () => boolean; - node: () => Node; -} - -interface ID3UpdateSelection extends ID3Selection { - enter: () => ID3EnterSelection; - update: () => ID3Selection; - exit: () => ID3Selection; -} - -interface ID3Time { - second: ID3Interval; - minute: ID3Interval; - hour: ID3Interval; - day: ID3Interval; - week: ID3Interval; - sunday: ID3Interval; - monday: ID3Interval; - tuesday: ID3Interval; - wednesday: ID3Interval; - thursday: ID3Interval; - friday: ID3Interval; - saturday: ID3Interval; - month: ID3Interval; - year: ID3Interval; - - seconds: ID3Range; - minutes: ID3Range; - hours: ID3Range; - days: ID3Range; - weeks: ID3Range; - months: ID3Range; - years: ID3Range; - - sundays: ID3Range; - mondays: ID3Range; - tuesdays: ID3Range; - wednesdays: ID3Range; - thursdays: ID3Range; - fridays: ID3Range; - saturdays: ID3Range; - format: { - - (specifier: string): ID3TimeFormat; - utc: (specifier: string) => ID3TimeFormat; - iso: ID3TimeFormat; - }; - - scale(): ID3TimeScale; -} - -interface ID3Range { - (start: Date, end: Date, step?: number): Date[]; -} - -interface ID3Interval { - (date: Date): Date; - floor: (date: Date) => Date; - round: (date: Date) => Date; - ceil: (date: Date) => Date; - range: ID3Range; - offset: (date: Date, step: number) => Date; - utc: ID3Interval; -} - -interface ID3TimeFormat { - (date: Date): string; - parse: (string: string) => Date; -} - -interface ID3LinearScale { - (value: number): number; - invert(value: number): number; - domain(numbers: any[]): ID3LinearScale; - range: { - (values: any[]): ID3LinearScale; - (): any[]; - }; - rangeRound: (values: any[]) => ID3LinearScale; - interpolate: { - (): ID3Interpolate; - (factory: ID3Interpolate): ID3LinearScale; - }; - clamp(clamp: boolean): ID3LinearScale; - nice(): ID3LinearScale; - ticks(count: number): any[]; - tickFormat(count: number): (n: number) => string; - copy: ID3LinearScale; -} - -interface ID3TimeScale { - (value: Date): number; - invert(value: number): Date; - domain(numbers: any[]): ID3TimeScale; - range: { - (values: any[]): ID3TimeScale; - (): any[]; - }; - rangeRound: (values: any[]) => ID3TimeScale; - interpolate: { - (): ID3Interpolate; - (factory: ID3InterpolateFactory): ID3TimeScale; - }; - clamp(clamp: boolean): ID3TimeScale; - ticks: { - (count: number): any[]; - (range: ID3Range, count: number): any[]; - }; - tickFormat(count: number): (n: number) => string; - copy(): ID3TimeScale; -} - -interface ID3InterpolateFactory { - (a: any, b: any): ID3BaseInterpolate; -} -interface ID3BaseInterpolate { - (a: any, b: any): ID3Interpolate; -} - -interface ID3Interpolate { - (t: number): number; -} - -interface ID3Layout { - stack(): ID3StackLayout; -} - -interface ID3StackLayout { - (layers: any[], index?: number): any[]; - values(accessor?: (d: any) => any): ID3StackLayout; - offset(offset: string): ID3StackLayout; -} - -interface ID3Svg { - axis(): ID3SvgAxis; -} - -interface ID3SvgAxis { - (selection: ID3Selection): void; - scale: { - (): any; - (scale: any): ID3SvgAxis; - }; - - orient: { - (): string; - (orientation: string): ID3SvgAxis; - }; - - ticks: { - (count: number): ID3SvgAxis; - (range: ID3Range, count?: number): ID3SvgAxis; - }; - - tickSubdivide(count: number): ID3SvgAxis; - tickSize(major?: number, minor?: number, end?: number): ID3SvgAxis; - tickFormat(formatter: (value: any) => string): ID3SvgAxis; -} - -interface ID3Random { - normal(mean?: number, deviation?: number): () => number; -} - -declare var d3: ID3Base; +interface ID3Selectors { + select: (selector: string) => ID3Selection; + selectAll: (selector: string) => ID3Selection; +} + +interface ID3Base extends ID3Selectors { + // Array Helpers + ascending: (a: number, b: number) => number; + descending: (a: number, b: number) => number; + min(arr: T[], map: (v: T) => U ): U; + min(arr: T[]): T; + max(arr: T[], map: (v: T) => U ): U; + max(arr: T[]): T; + extent(arr: T[], map: (v: T) => U): U[]; + extent(arr: T[]): T[]; + quantile: (arr: number[], p: number) => number; + bisectLeft(arr: T[], x: T, low?: number, high?: number): number; + bisect(arr: T[], x: T, low?: number, high?: number): number; + bisectRight(arr: T[], x: T, low?: number, high?: number): number; + + // Loading resources + xhr: { + (url: string, callback: (xhr: XMLHttpRequest) => void): void; + (url: string, mime: string, callback: (xhr: XMLHttpRequest) => void): void; + }; + text: { + (url: string, callback: (response: string) => void): void; + (url: string, mime: string, callback: (response: string) => void): void; + }; + json: (url: string, callback: (response: any) => void) => void; + xml: { + (url: string, callback: (response: Document) => void): void; + (url: string, mime: string, callback: (response: Document) => void): void; + }; + html: (url: string, callback: (response: DocumentFragment) => void) => void; + csv: { + (url: string, callback: (response: any[]) => void); + parse(string: string): any[]; + parseRows(string: string, accessor: (row: any[], index: number) => any): any; + format(rows: any[]): string; + }; + + time: ID3Time; + scale: { + linear(): ID3LinearScale; + }; + interpolate: ID3BaseInterpolate; + interpolateNumber: ID3BaseInterpolate; + interpolateRound: ID3BaseInterpolate; + interpolateString: ID3BaseInterpolate; + interpolateRgb: ID3BaseInterpolate; + interpolateHsl: ID3BaseInterpolate; + interpolateArray: ID3BaseInterpolate; + interpolateObject: ID3BaseInterpolate; + interpolateTransform: ID3BaseInterpolate; + layout: ID3Layout; + svg: ID3Svg; + random: ID3Random; +} + +interface ID3Selection extends ID3Selectors { + attr: { + (name: string): string; + (name: string, value: any): ID3Selection; + (name: string, valueFunction: (data: any, index: number) => any): ID3Selection; + }; + + classed: { + (name: string): string; + (name: string, value: any): ID3Selection; + (name: string, valueFunction: (data: any, index: number) => any): ID3Selection; + }; + + style: { + (name: string): string; + (name: string, value: any, priority?: string): ID3Selection; + (name: string, valueFunction: (data: any, index: number) => any, priority?: string): ID3Selection; + }; + + property: { + (name: string): void; + (name: string, value: any): ID3Selection; + (name: string, valueFunction: (data: any, index: number) => any): ID3Selection; + }; + + text: { + (): string; + (value: any): ID3Selection; + (valueFunction: (data: any, index: number) => any): ID3Selection; + }; + + html: { + (): string; + (value: any): ID3Selection; + (valueFunction: (data: any, index: number) => any): ID3Selection; + }; + + append: (name: string) => ID3Selection; + insert: (name: string, before: string) => ID3Selection; + remove: () => ID3Selection; + + data: { + (values: (data: any, index: number) => any) : any; + (values: any[], key?: (data: any, index: number) => any): ID3UpdateSelection; + }; + + call(callback: (selection: ID3Selection) => void): ID3Selection; +} + +interface ID3EnterSelection { + append: (name: string) => ID3Selection; + insert: (name: string, before: string) => ID3Selection; + select: (selector: string) => ID3Selection; + empty: () => boolean; + node: () => Node; +} + +interface ID3UpdateSelection extends ID3Selection { + enter: () => ID3EnterSelection; + update: () => ID3Selection; + exit: () => ID3Selection; +} + +interface ID3Time { + second: ID3Interval; + minute: ID3Interval; + hour: ID3Interval; + day: ID3Interval; + week: ID3Interval; + sunday: ID3Interval; + monday: ID3Interval; + tuesday: ID3Interval; + wednesday: ID3Interval; + thursday: ID3Interval; + friday: ID3Interval; + saturday: ID3Interval; + month: ID3Interval; + year: ID3Interval; + + seconds: ID3Range; + minutes: ID3Range; + hours: ID3Range; + days: ID3Range; + weeks: ID3Range; + months: ID3Range; + years: ID3Range; + + sundays: ID3Range; + mondays: ID3Range; + tuesdays: ID3Range; + wednesdays: ID3Range; + thursdays: ID3Range; + fridays: ID3Range; + saturdays: ID3Range; + format: { + + (specifier: string): ID3TimeFormat; + utc: (specifier: string) => ID3TimeFormat; + iso: ID3TimeFormat; + }; + + scale(): ID3TimeScale; +} + +interface ID3Range { + (start: Date, end: Date, step?: number): Date[]; +} + +interface ID3Interval { + (date: Date): Date; + floor: (date: Date) => Date; + round: (date: Date) => Date; + ceil: (date: Date) => Date; + range: ID3Range; + offset: (date: Date, step: number) => Date; + utc: ID3Interval; +} + +interface ID3TimeFormat { + (date: Date): string; + parse: (string: string) => Date; +} + +interface ID3LinearScale { + (value: number): number; + invert(value: number): number; + domain(numbers: any[]): ID3LinearScale; + range: { + (values: any[]): ID3LinearScale; + (): any[]; + }; + rangeRound: (values: any[]) => ID3LinearScale; + interpolate: { + (): ID3Interpolate; + (factory: ID3Interpolate): ID3LinearScale; + }; + clamp(clamp: boolean): ID3LinearScale; + nice(): ID3LinearScale; + ticks(count: number): any[]; + tickFormat(count: number): (n: number) => string; + copy: ID3LinearScale; +} + +interface ID3TimeScale { + (value: Date): number; + invert(value: number): Date; + domain(numbers: any[]): ID3TimeScale; + range: { + (values: any[]): ID3TimeScale; + (): any[]; + }; + rangeRound: (values: any[]) => ID3TimeScale; + interpolate: { + (): ID3Interpolate; + (factory: ID3InterpolateFactory): ID3TimeScale; + }; + clamp(clamp: boolean): ID3TimeScale; + ticks: { + (count: number): any[]; + (range: ID3Range, count: number): any[]; + }; + tickFormat(count: number): (n: number) => string; + copy(): ID3TimeScale; +} + +interface ID3InterpolateFactory { + (a: any, b: any): ID3BaseInterpolate; +} +interface ID3BaseInterpolate { + (a: any, b: any): ID3Interpolate; +} + +interface ID3Interpolate { + (t: number): number; +} + +interface ID3Layout { + stack(): ID3StackLayout; +} + +interface ID3StackLayout { + (layers: any[], index?: number): any[]; + values(accessor?: (d: any) => any): ID3StackLayout; + offset(offset: string): ID3StackLayout; +} + +interface ID3Svg { + axis(): ID3SvgAxis; +} + +interface ID3SvgAxis { + (selection: ID3Selection): void; + scale: { + (): any; + (scale: any): ID3SvgAxis; + }; + + orient: { + (): string; + (orientation: string): ID3SvgAxis; + }; + + ticks: { + (count: number): ID3SvgAxis; + (range: ID3Range, count?: number): ID3SvgAxis; + }; + + tickSubdivide(count: number): ID3SvgAxis; + tickSize(major?: number, minor?: number, end?: number): ID3SvgAxis; + tickFormat(formatter: (value: any) => string): ID3SvgAxis; +} + +interface ID3Random { + normal(mean?: number, deviation?: number): () => number; +} + +declare var d3: ID3Base; diff --git a/d3/data.ts b/d3/data.ts index ed5209a..9812f57 100644 --- a/d3/data.ts +++ b/d3/data.ts @@ -1,282 +1,282 @@ -/// -"use strict"; - -interface IDataSeries { - desc: string; - data: IRun[]; -} - -interface IRun { - date: Date; - pass: boolean; -} - -interface IPerfDataSeries { - desc: string; - data: IPerfRun[]; -} - -interface IPerfRun { - x: Date; - y: number; -} - -module Chart { - - export class Base { - public iso8601 = d3.time.format('%Y-%m-%d'); - public chartWidth = 800; - - constructor (public element) { } - } - - export class Bar extends Base { - public element: ID3Selection; - constructor(element: ID3Selection) { - super(element); - this.element = element; - } - - public chartHeight = 400; - public chartWidth = 800; - public legendItemHeight = 30; - public legendWidth = 150; - public colors = ['rgb(0, 113, 188)', 'rgb(0, 174, 239)', 'rgb(145, 0, 145)']; - public xAxisHashHeight = 10; - public layout = 'wiggle'; - - - public render(data: IPerfDataSeries[]) { - - // Create stack layout - var stackLayout = d3.layout.stack() - .values(function(d) { return d.data }) - .offset(this.layout); - - var stackData = stackLayout(data); - - // Maximum measurement in the dataset - var maxY = d3.max(stackData, (d) => d3.max(d.data, (d) => d.y0 + d.y)); - - // Earliest day in the dataset - var minX = d3.min(data, (d) => d3.min(d.data, (d) => d.x)); - - // All days in the dataset (from earliest day until now) - var days = d3.time.days(minX, new Date()); - - // Area of the region containing the bars - var areaWidth = this.chartWidth - this.legendWidth; - - var barWidth = areaWidth / days.length; - - // Create scales for X and Y axis (X based on dates, Y based on performance data) - var x = d3.time.scale() - .domain([minX, d3.time.day(d3.time.day.offset(new Date(), 1))]) - .range([0, this.chartWidth - this.legendWidth]); - var y = d3.scale.linear() - .domain([0, maxY]) - .range([0, this.chartHeight]); - var ticks = x.ticks(d3.time.mondays, 1); - - // SVG element - var svg = this.element.append('svg') - .attr('height', this.chartHeight + 25) - .attr('width', this.chartWidth); - - // Groups that contain bar segments for each dataset - var barGroups = svg.selectAll('g.bars') - .data(stackData) - .enter().append('g') - .attr('class', 'bars') - .style('fill', (d, i) => this.colors[i]) - .attr('transform', 'translate(' + this.legendWidth + ', 0)'); - - // Legend - var legendGroup = svg.append('g') - .attr('class', 'legend') - - // Legend items - var legendItem = legendGroup.selectAll('g.legendItem') - .data(stackData) - .enter().append('g') - .attr('class', 'legendItem') - .style('fill', (d, i) => this.colors[i]) - .attr('transform', (d, i) => 'translate(0, ' + (this.legendItemHeight * (2 - i)) + ')'); - - legendItem.append('rect') - .attr('width', 25) - .attr('height', 25); - - legendItem.append('text') - .text((d) => d.desc) - .attr('x', 30) - .attr('dy', '1em'); - - - // Bars - var rects = barGroups.selectAll('rect') - .data((d) => d.data) - .enter() - .append('rect') - .attr('x', (d, i) => x(d.x)) - .attr('y', (d, i) => this.chartHeight - y(d.y + d.y0)) - .attr('width', barWidth) - .attr('height', (d, i) => y(d.y)); - - // Add title (mouseover popup) to bars - rects.append('title') - .text((d) => this.iso8601(d.x) + ' - ' + d.y + 'ms'); - - - // Add an axis marker to the bottom - var axis = d3.svg.axis(); - axis.scale(x) - .ticks(d3.time.mondays, 1) - .tickSubdivide(6) - .tickFormat(this.iso8601) - .tickSize(10, 5, 0); - - var axisGroup = svg.append('g') - .attr('class', 'axis') - .attr('transform', 'translate(' + this.legendWidth + ',' + this.chartHeight + ')') - .call(axis); - - } - } - - export class DailyBuild extends Base { - public element: ID3Selection; - constructor (element: ID3Selection) { - super(element); - this.element = element; - } - - public labelWidth = 140; - public labelGutter = 10; - public chartWidth = 800; - - private getTextDataString(data) { - return data.pass ? 'pass' : 'fail'; - } - - public render(data: IDataSeries[]) { - // Minimum date in the dataset - var minDate = d3.min(data.map(function(d) { return d3.time.day(d.data[0].date) })); - - // All the days in the dataset, from min until now. - var days = d3.time.days(minDate, new Date()); - - var boxSize = (this.chartWidth - this.labelWidth - this.labelGutter) / days.length; - - // Create our scales for x and y axis - var x = d3.time.scale() - .domain([minDate, d3.time.day(new Date())]) - .range([0, boxSize * (days.length - 1)]); - - var y = d3.scale.linear() - .domain([0, 1]) - .range([0, boxSize]); - - - // SVG element - var svg = this.element.append('svg') - .attr('height', y(data.length + 1)) - .attr('width', this.chartWidth); - - svg.selectAll('text') - .data(data) - .enter().append('text') - .attr('x', this.labelWidth) - .attr('transform', function(d, i) { return 'translate(0,' + y(i) + ')' }) - .attr('dy', '1em') - .attr('text-anchor', 'end') - .text(function(d) { return d.desc }); - - // Groups of boxes for updated builds - var g = svg.selectAll('g.boxes') - .data(data) - .enter().append('g') - .attr('class', 'boxes') - .attr('transform', function(d, i) { return 'translate(0,' + y(i) + ')' }); - - // Boxes of build info - var rects = g.selectAll('rect') - .data(function(d, i) { return d.data; }) - .enter().append('rect') - .attr('class', (d) => 'day ' + this.getTextDataString(d)) - .attr('x', (d, i) => this.labelWidth + this.labelGutter + x(d.date)) - .attr('width', boxSize) - .attr('height', boxSize); - - rects.append('title') - .text( (d) => this.iso8601(d.date) + ' - ' + this.getTextDataString(d) ); - - var ticks = x.ticks(d3.time.mondays, 1); - - // Date text boxes - svg.append('g').attr('class', 'dates').selectAll('text') - .data(ticks) - .enter().append('text') - .text((d) => this.iso8601(d) ) - .attr('transform', (d, i) => 'translate(' + (this.labelWidth + this.labelGutter + x(d) + 5) + ', ' + y(data.length + 1) + ')') - .attr('text-anchor', 'start') - - // Vertical hashes at week boundaries - svg.append('g').attr('class', 'hashes').selectAll('line') - .data(ticks) - .enter().append('line') - .attr('x1', (d) => this.labelWidth + this.labelGutter + x(d) ) - .attr('x2', (d) => this.labelWidth + this.labelGutter + x(d) ) - .attr('y1', 0) - .attr('y2', y(data.length + 1)); - - return svg; - } - } -} - -var start = d3.time.day.offset(new Date(), -30); -var end = new Date() -var days = d3.time.days(start, end); - -var buildData: IRun[] = days.map(day => ({ date: day, pass: Math.random() > 0.1 })); -var compilerTestData: IRun[] = days.map(day => ({ date: day, pass: Math.random() > 0.1 })); -var servicesTestData: IRun[] = days.map(day => ({ date: day, pass: Math.random() > 0.1 })); - -function decreasingRandom(start: number, deviation: number, factor: number) { - var factorRandom = d3.random.normal(factor, 0.05); - - return function () { - var random = d3.random.normal(start, deviation)(); - start = start * factorRandom(); - - return parseFloat(random.toFixed()) - } -} - -var parseRandom = decreasingRandom(400, 20, 0.97); -var typecheckRandom = decreasingRandom(500, 20, 0.97); -var emitRandom = decreasingRandom(100, 10, 0.97); - -var parseData: IPerfRun[] = days.map(day => ({ x: day, y: parseRandom() })); -var typecheckData: IPerfRun[] = days.map(day => ({ x: day, y: typecheckRandom() })); -var emitData: IPerfRun[] = days.map(day => ({ x: day, y: emitRandom() })); - -document.addEventListener('DOMContentLoaded', function () { - var chart = new Chart.DailyBuild(d3.select('#passchart')); - - chart.render([ - { desc: "Build Status", data: buildData }, - { desc: "Compiler Tests", data: compilerTestData }, - { desc: "Services Tests", data: servicesTestData }, - ]); - - var normalizedData = [ - { desc: 'Emit', data: emitData }, - { desc: 'Typecheck', data: typecheckData }, - { desc: 'Parse', data: parseData } - ] - - var perfchart = new Chart.Bar(d3.select('#performanceChart')); - perfchart.render(normalizedData); -}); +/// +"use strict"; + +interface IDataSeries { + desc: string; + data: IRun[]; +} + +interface IRun { + date: Date; + pass: boolean; +} + +interface IPerfDataSeries { + desc: string; + data: IPerfRun[]; +} + +interface IPerfRun { + x: Date; + y: number; +} + +module Chart { + + export class Base { + public iso8601 = d3.time.format('%Y-%m-%d'); + public chartWidth = 800; + + constructor (public element) { } + } + + export class Bar extends Base { + public element: ID3Selection; + constructor(element: ID3Selection) { + super(element); + this.element = element; + } + + public chartHeight = 400; + public chartWidth = 800; + public legendItemHeight = 30; + public legendWidth = 150; + public colors = ['rgb(0, 113, 188)', 'rgb(0, 174, 239)', 'rgb(145, 0, 145)']; + public xAxisHashHeight = 10; + public layout = 'wiggle'; + + + public render(data: IPerfDataSeries[]) { + + // Create stack layout + var stackLayout = d3.layout.stack() + .values(function(d) { return d.data }) + .offset(this.layout); + + var stackData = stackLayout(data); + + // Maximum measurement in the dataset + var maxY = d3.max(stackData, (d) => d3.max(d.data, (d) => d.y0 + d.y)); + + // Earliest day in the dataset + var minX = d3.min(data, (d) => d3.min(d.data, (d) => d.x)); + + // All days in the dataset (from earliest day until now) + var days = d3.time.days(minX, new Date()); + + // Area of the region containing the bars + var areaWidth = this.chartWidth - this.legendWidth; + + var barWidth = areaWidth / days.length; + + // Create scales for X and Y axis (X based on dates, Y based on performance data) + var x = d3.time.scale() + .domain([minX, d3.time.day(d3.time.day.offset(new Date(), 1))]) + .range([0, this.chartWidth - this.legendWidth]); + var y = d3.scale.linear() + .domain([0, maxY]) + .range([0, this.chartHeight]); + var ticks = x.ticks(d3.time.mondays, 1); + + // SVG element + var svg = this.element.append('svg') + .attr('height', this.chartHeight + 25) + .attr('width', this.chartWidth); + + // Groups that contain bar segments for each dataset + var barGroups = svg.selectAll('g.bars') + .data(stackData) + .enter().append('g') + .attr('class', 'bars') + .style('fill', (d, i) => this.colors[i]) + .attr('transform', 'translate(' + this.legendWidth + ', 0)'); + + // Legend + var legendGroup = svg.append('g') + .attr('class', 'legend') + + // Legend items + var legendItem = legendGroup.selectAll('g.legendItem') + .data(stackData) + .enter().append('g') + .attr('class', 'legendItem') + .style('fill', (d, i) => this.colors[i]) + .attr('transform', (d, i) => 'translate(0, ' + (this.legendItemHeight * (2 - i)) + ')'); + + legendItem.append('rect') + .attr('width', 25) + .attr('height', 25); + + legendItem.append('text') + .text((d) => d.desc) + .attr('x', 30) + .attr('dy', '1em'); + + + // Bars + var rects = barGroups.selectAll('rect') + .data((d) => d.data) + .enter() + .append('rect') + .attr('x', (d, i) => x(d.x)) + .attr('y', (d, i) => this.chartHeight - y(d.y + d.y0)) + .attr('width', barWidth) + .attr('height', (d, i) => y(d.y)); + + // Add title (mouseover popup) to bars + rects.append('title') + .text((d) => this.iso8601(d.x) + ' - ' + d.y + 'ms'); + + + // Add an axis marker to the bottom + var axis = d3.svg.axis(); + axis.scale(x) + .ticks(d3.time.mondays, 1) + .tickSubdivide(6) + .tickFormat(this.iso8601) + .tickSize(10, 5, 0); + + var axisGroup = svg.append('g') + .attr('class', 'axis') + .attr('transform', 'translate(' + this.legendWidth + ',' + this.chartHeight + ')') + .call(axis); + + } + } + + export class DailyBuild extends Base { + public element: ID3Selection; + constructor (element: ID3Selection) { + super(element); + this.element = element; + } + + public labelWidth = 140; + public labelGutter = 10; + public chartWidth = 800; + + private getTextDataString(data) { + return data.pass ? 'pass' : 'fail'; + } + + public render(data: IDataSeries[]) { + // Minimum date in the dataset + var minDate = d3.min(data.map(function(d) { return d3.time.day(d.data[0].date) })); + + // All the days in the dataset, from min until now. + var days = d3.time.days(minDate, new Date()); + + var boxSize = (this.chartWidth - this.labelWidth - this.labelGutter) / days.length; + + // Create our scales for x and y axis + var x = d3.time.scale() + .domain([minDate, d3.time.day(new Date())]) + .range([0, boxSize * (days.length - 1)]); + + var y = d3.scale.linear() + .domain([0, 1]) + .range([0, boxSize]); + + + // SVG element + var svg = this.element.append('svg') + .attr('height', y(data.length + 1)) + .attr('width', this.chartWidth); + + svg.selectAll('text') + .data(data) + .enter().append('text') + .attr('x', this.labelWidth) + .attr('transform', function(d, i) { return 'translate(0,' + y(i) + ')' }) + .attr('dy', '1em') + .attr('text-anchor', 'end') + .text(function(d) { return d.desc }); + + // Groups of boxes for updated builds + var g = svg.selectAll('g.boxes') + .data(data) + .enter().append('g') + .attr('class', 'boxes') + .attr('transform', function(d, i) { return 'translate(0,' + y(i) + ')' }); + + // Boxes of build info + var rects = g.selectAll('rect') + .data(function(d, i) { return d.data; }) + .enter().append('rect') + .attr('class', (d) => 'day ' + this.getTextDataString(d)) + .attr('x', (d, i) => this.labelWidth + this.labelGutter + x(d.date)) + .attr('width', boxSize) + .attr('height', boxSize); + + rects.append('title') + .text( (d) => this.iso8601(d.date) + ' - ' + this.getTextDataString(d) ); + + var ticks = x.ticks(d3.time.mondays, 1); + + // Date text boxes + svg.append('g').attr('class', 'dates').selectAll('text') + .data(ticks) + .enter().append('text') + .text((d) => this.iso8601(d) ) + .attr('transform', (d, i) => 'translate(' + (this.labelWidth + this.labelGutter + x(d) + 5) + ', ' + y(data.length + 1) + ')') + .attr('text-anchor', 'start') + + // Vertical hashes at week boundaries + svg.append('g').attr('class', 'hashes').selectAll('line') + .data(ticks) + .enter().append('line') + .attr('x1', (d) => this.labelWidth + this.labelGutter + x(d) ) + .attr('x2', (d) => this.labelWidth + this.labelGutter + x(d) ) + .attr('y1', 0) + .attr('y2', y(data.length + 1)); + + return svg; + } + } +} + +var start = d3.time.day.offset(new Date(), -30); +var end = new Date() +var days = d3.time.days(start, end); + +var buildData: IRun[] = days.map(day => ({ date: day, pass: Math.random() > 0.1 })); +var compilerTestData: IRun[] = days.map(day => ({ date: day, pass: Math.random() > 0.1 })); +var servicesTestData: IRun[] = days.map(day => ({ date: day, pass: Math.random() > 0.1 })); + +function decreasingRandom(start: number, deviation: number, factor: number) { + var factorRandom = d3.random.normal(factor, 0.05); + + return function () { + var random = d3.random.normal(start, deviation)(); + start = start * factorRandom(); + + return parseFloat(random.toFixed()) + } +} + +var parseRandom = decreasingRandom(400, 20, 0.97); +var typecheckRandom = decreasingRandom(500, 20, 0.97); +var emitRandom = decreasingRandom(100, 10, 0.97); + +var parseData: IPerfRun[] = days.map(day => ({ x: day, y: parseRandom() })); +var typecheckData: IPerfRun[] = days.map(day => ({ x: day, y: typecheckRandom() })); +var emitData: IPerfRun[] = days.map(day => ({ x: day, y: emitRandom() })); + +document.addEventListener('DOMContentLoaded', function () { + var chart = new Chart.DailyBuild(d3.select('#passchart')); + + chart.render([ + { desc: "Build Status", data: buildData }, + { desc: "Compiler Tests", data: compilerTestData }, + { desc: "Services Tests", data: servicesTestData }, + ]); + + var normalizedData = [ + { desc: 'Emit', data: emitData }, + { desc: 'Typecheck', data: typecheckData }, + { desc: 'Parse', data: parseData } + ] + + var perfchart = new Chart.Bar(d3.select('#performanceChart')); + perfchart.render(normalizedData); +}); diff --git a/d3/perf.html b/d3/perf.html index 4dda67e..16dabe1 100644 --- a/d3/perf.html +++ b/d3/perf.html @@ -1,45 +1,45 @@ - - - - - - - - -

Status

-
- -

Compiler Performance

-
- + + + + + + + + +

Status

+
+ +

Compiler Performance

+
+ \ No newline at end of file diff --git a/d3/tsconfig.json b/d3/tsconfig.json new file mode 100644 index 0000000..8036243 --- /dev/null +++ b/d3/tsconfig.json @@ -0,0 +1,5 @@ +{ + "compilerOptions": { + "sourceMap": true + } +} \ No newline at end of file diff --git a/greeter/greeter.html b/greeter/greeter.html index 965d776..b241eac 100644 --- a/greeter/greeter.html +++ b/greeter/greeter.html @@ -1,7 +1,7 @@ - - - TypeScript Greeter - - - + + + TypeScript Greeter + + + \ No newline at end of file diff --git a/greeter/greeter.ts b/greeter/greeter.ts index 41915ca..845fdff 100644 --- a/greeter/greeter.ts +++ b/greeter/greeter.ts @@ -1,9 +1,10 @@ -class Greeter { - constructor(public greeting: string) { } - greet() { - return "

" + this.greeting + "

"; - } -}; -var greeter = new Greeter("Hello, world!"); -var str = greeter.greet(); -document.body.innerHTML = str; +class Greeter { + constructor(public greeting: string) { } + greet() { + return "

" + this.greeting + "

"; + } +}; + +var greeter = new Greeter("Hello, world!"); + +document.body.innerHTML = greeter.greet(); diff --git a/greeter/tsconfig.json b/greeter/tsconfig.json new file mode 100644 index 0000000..8036243 --- /dev/null +++ b/greeter/tsconfig.json @@ -0,0 +1,5 @@ +{ + "compilerOptions": { + "sourceMap": true + } +} \ No newline at end of file diff --git a/imageboard/ImageBoard.csproj b/imageboard/ImageBoard.csproj index 4ab7a37..caeba4e 100644 --- a/imageboard/ImageBoard.csproj +++ b/imageboard/ImageBoard.csproj @@ -1,85 +1,85 @@ - - - - - 12.0 - 1.4 - - - Debug - AnyCPU - {BE268EA8-89D1-44DB-839D-FB007556CC97} - Library - false - ClassLibrary - v4.0 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - false - true - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - false - true - - - ImageBoard - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - commonjs - - + + + + + 12.0 + 1.4 + + + Debug + AnyCPU + {BE268EA8-89D1-44DB-839D-FB007556CC97} + Library + false + ClassLibrary + v4.0 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + false + true + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + false + true + + + ImageBoard + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + commonjs + + \ No newline at end of file diff --git a/imageboard/ImageBoardNodeProj.njsproj b/imageboard/ImageBoardNodeProj.njsproj new file mode 100644 index 0000000..df4f667 --- /dev/null +++ b/imageboard/ImageBoardNodeProj.njsproj @@ -0,0 +1,107 @@ + + + + Debug + 2.0 + {abeae01d-ced1-4453-9533-6f0ebb26b1a3} + + ShowAllFiles + app.ts + . + . + {3AF33F2E-1136-4D97-BBB7-1795711AC8B8};{349c5851-65df-11da-9384-00065b846f21};{9092AA53-FB77-4645-B42D-1CCCA6BD08BD} + true + CommonJS + true + 11.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + True + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + False + True + 0 + / + http://localhost:48022/ + False + True + http://localhost:1337 + False + + + + + + + CurrentPage + True + False + False + False + + + + + + + + + False + False + + + + + \ No newline at end of file diff --git a/imageboard/ImageBoardNodeProj.sln b/imageboard/ImageBoardNodeProj.sln new file mode 100644 index 0000000..1ef49a3 --- /dev/null +++ b/imageboard/ImageBoardNodeProj.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.22803.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9092AA53-FB77-4645-B42D-1CCCA6BD08BD}") = "ImageBoardNodeProj", "ImageBoardNodeProj.njsproj", "{ABEAE01D-CED1-4453-9533-6F0EBB26B1A3}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {ABEAE01D-CED1-4453-9533-6F0EBB26B1A3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {ABEAE01D-CED1-4453-9533-6F0EBB26B1A3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {ABEAE01D-CED1-4453-9533-6F0EBB26B1A3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {ABEAE01D-CED1-4453-9533-6F0EBB26B1A3}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/imageboard/README.md b/imageboard/README.md index e6ad55f..807bc0f 100644 --- a/imageboard/README.md +++ b/imageboard/README.md @@ -4,32 +4,51 @@ This sample implements a complete Node.js application. Notable features: -- Typed usage of express for server side MVC -- Typed usage of mongodb for server side database -- Typed usage of Node.js -- Use of TypeScript module syntax -- Visual Studio project file for working with the project + +* Typed usage of express for server side MVC +* Typed usage of mongodb for server side database +* Typed usage of Node.js +* Use of external typings from DefinitelyTyped +* Visual Studio project file for working with the project ## Running -Note: Perform steps 3 - 6 with your working directory set to the folder containing this README: +Note: All commands entered need to be performed from within *this directory*. 1. Install MongoDB if necessary (see http://docs.mongodb.org/manual/installation/ ) -2. Run the following command to launch the MongoDB process: -`\bin\mongod` - -3. Restore the sample app data to MongoDB in another command prompt with the following command: -`\bin\mongorestore dump` - -4. Install the app's node dependencies with the following command: -`npm install` - -5. Compile the app with the following command: -`tsc --sourcemap --module commonjs app.ts` - -6. Launch the Node process to serve the app using the following command: -`node app.js` - -7. Open your favorite browser and going to the following URL to access the app: -`http://localhost:3000/` +2. Ensure you have a clean directory to dedicate as to a database (e.g. `C:\imageboard` or `~/imageboard/`). + +3. From *this repository's imageboard directory*, run the following command to launch the MongoDB process. + ```shell + /bin/mongod --dbpath + ``` + +4. From *this repository's imageboard directory*, restore the sample app data to MongoDB in another command prompt with the following command: + ```shell + /bin/mongorestore dump + ``` + +5. From this imageboard directory, install the app's node dependencies, tsd, and typings with the following commands: + ```shell + npm install + npm install -g tsd + tsd install + ``` + Some things to note: + + * `npm install` will install this project's node dependencies from `package.json`. + * `tsd install` will retrieve `.d.ts` files from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped). + +6. Compile the app with the following command: + ```shell + tsc + ``` + The above command will use `tsconfig.json` to compile all necessary files. + +7. Launch the Node process to serve the app using the following command: + ```shell + node app.js + ``` + +7. Open your favorite browser and navigating to `http://localhost:3000/` to access the app. diff --git a/imageboard/app.ts b/imageboard/app.ts index cb15c80..5cc3ce1 100644 --- a/imageboard/app.ts +++ b/imageboard/app.ts @@ -1,136 +1,135 @@ -/// -/// -/// -/// - - -import http = require("http") -import url = require("url") -import routes = require("./routes/index") -import db = require("./db") -import express = require("express") -import bodyParser = require("body-parser"); -import methodOverride = require("method-override"); -import errorHandler = require("errorhandler"); - -var app = express(); - -// Configuration - -app.set('views', __dirname + '/views'); -app.set('view engine', 'jade'); -app.set('view options', { layout: false }); -app.use(bodyParser.urlencoded({ extended: true })); -app.use(bodyParser.json()); -app.use(methodOverride()); -app.use(express.static(__dirname + '/public')); - -var env = process.env.NODE_ENV || 'development'; -if (env === 'development') { - app.use(errorHandler({ dumpExceptions: true, showStack: true })); -} -else if (env === 'production') { - app.use(errorHandler()); -} - - -// Routes - -app.get('/', routes.index); - -app.get('/findImages', function(req, res) { - console.log('getting images from' + req.query['url']); - - var req2 = http.get(url.parse(req.query['url']), function(urlres) { - console.log("Got response: " + urlres.statusCode); - var text = ""; - urlres.on('data', function(chunk: string) { - text += chunk; - }); - urlres.on('end', function() { - console.log(text); - var re = /]+src=[\"\']([^\'\"]+)[\"\']/g; - var match, matches = []; - while(match = re.exec(text)) { - matches.push(match[1]); - } - res.write(JSON.stringify(matches)); - res.end(); - }); - }).on('error', function(a,e) { - console.log("Got error: " + e.message); - }); -}); - -app.get('/user/:userid', function(req, res) { - console.log('getting user ' + req.params.userid); - db.getUser(req.params.userid, function(user) { - res.render('user', { - title: user._id, - username: user._id, - boards: user.boards - }); - }); -}); - -app.get('/user/:userid/newboard', function(req, res) { - res.render('newboard', { - username: req.params.userid - }); -}); - -app.post('/user/:userid/newboard', function(req, res) { - db.addBoard(req.params.userid, req.param('title'), req.param('description'), function(user) { - res.redirect('/user/'+req.params.userid) - }); -}); - -app.get('/user/:userid/:boardid', function(req, res) { - console.log('getting ' + req.params.userid + ", " + req.params.boardid); - db.getUser(req.params.userid, function(user) { - var board = user.boards.filter(function(board) { - return decodeURIComponent(req.params.boardid) === board.title; - })[0]; - if(board) { - db.getImages(board.images, function(images) { - res.render('board', { - title: user._id, - username: user._id, - board: board, - images: images - }); - }); - } else { - res.send(404, 'not found'); - } - }); -}); - -app.get('/user/:userid/:boardid/newpin', function(req, res) { - res.render('newpin', { - username: req.params.userid, - boardid: req.params.boardid - }); -}); - -app.post('/user/:userid/:boardid/newpin', function(req, res) { - db.addPin(req.params.userid, req.params.boardid, req.param('imageUri'), req.param('link'), req.param('caption'), function(user) { - res.redirect('/user/'+req.params.userid +"/" + req.params.boardid) - }); -}); - -app.get('/image/:imageid', function(req, res) { - console.log('getting image ' + req.params.imageid); - db.getImage(req.params.imageid, function(image) { - res.render('image', { - title: "image", - image: image - }); - }); -}); - -app.listen(3000, function(){ - console.log("Demo Express server listening on port %d in %s mode", 3000, app.settings.env); -}); - +import * as http from "http"; +import * as url from "url"; +import * as express from "express"; +import * as bodyParser from "body-parser"; +import errorHandler = require("errorhandler"); +import methodOverride = require("method-override"); + +import * as routes from "./routes/index"; +import * as db from "./db"; + +var app = express(); + +// Configuration + +app.set('views', __dirname + '/views'); +app.set('view engine', 'jade'); +app.set('view options', { layout: false }); +app.use(bodyParser.urlencoded({ extended: true })); +app.use(bodyParser.json()); +app.use(methodOverride()); +app.use(express.static(__dirname + '/public')); + +var env = process.env.NODE_ENV || 'development'; +if (env === 'development') { + app.use(errorHandler()); +} + + +// Routes + +app.get('/', routes.index); + +app.get('/findImages', (req, res) => { + console.log('getting images from' + req.query['url']); + + let req2 = http.get(url.parse(req.query['url']), urlMessage => { + console.log("Got response: " + urlMessage.statusCode); + + let text = ""; + + urlMessage.on('data', (chunk: string) => { + text += chunk; + }); + + urlMessage.on('end', () => { + console.log(text); + const imageTagRegEx = /]+src=[\"\']([^\'\"]+)[\"\']/g; + + let match: RegExpMatchArray; + let matches: string[] = []; + while (match = imageTagRegEx.exec(text)) { + matches.push(match[1]); + } + + res.write(JSON.stringify(matches)); + res.end(); + }); + + }).on('error', function(a,e) { + console.log("Got error: " + e.message); + }); +}); + +app.get('/user/:userid', (req, res) => { + console.log('getting user ' + req.params.userid); + db.getUser(req.params.userid, user => { + res.render('user', { + title: user._id, + username: user._id, + boards: user.boards + }); + }); +}); + +app.get('/user/:userid/newboard', (req, res) => { + res.render('newboard', { + username: req.params.userid + }); +}); + +app.post('/user/:userid/newboard', (req, res) => { + db.addBoard(req.params.userid, req.param('title'), req.param('description'), user => { + res.redirect('/user/'+req.params.userid); + }); +}); + +app.get('/user/:userid/:boardid', (req, res) => { + console.log('getting ' + req.params.userid + ", " + req.params.boardid); + db.getUser(req.params.userid, user => { + let board = user.boards.filter(board => decodeURIComponent(req.params.boardid) === board.title)[0]; + + if (board) { + db.getImages(board.images, images => { + res.render('board', { + title: user._id, + username: user._id, + board: board, + images: images + }); + }); + } + else { + res.send(404, 'not found'); + } + }); +}); + +app.get('/user/:userid/:boardid/newpin', (req, res) => { + res.render('newpin', { + username: req.params.userid, + boardid: req.params.boardid + }); +}); + +app.post('/user/:userid/:boardid/newpin', (req, res) => { + db.addPin(req.params.userid, req.params.boardid, req.param('imageUri'), req.param('link'), req.param('caption'), user => { + res.redirect('/user/'+req.params.userid +"/" + req.params.boardid) + }); +}); + +app.get('/image/:imageid', (req, res) => { + console.log('getting image ' + req.params.imageid); + db.getImage(req.params.imageid, image => { + res.render('image', { + title: "image", + image: image + }); + }); +}); + +app.listen(3000, function(){ + console.log("Demo Express server listening on port %d in %s mode", 3000, app.settings.env); +}); + export var App = app; \ No newline at end of file diff --git a/imageboard/db.ts b/imageboard/db.ts index 950ec10..ad85c69 100644 --- a/imageboard/db.ts +++ b/imageboard/db.ts @@ -1,110 +1,110 @@ -// Mongo -import mongodb = require('mongodb'); - -var server = new mongodb.Server('localhost', 27017, {auto_reconnect: true}) -var db = new mongodb.Db('mydb', server, { w: 1 }); -db.open(function() {}); - -export interface User { - _id: string; - email: string; - first_name: string; - last_name: string; - fbId: number; - boards: Board[]; -} - -export interface Board { - title: string; - description: string; - images: mongodb.ObjectID[]; -} - -export interface Image { - _id: mongodb.ObjectID; - user: string; - caption: string; - imageUri: string; - link: string; - board: string; - comments: {text: string; user: string;}[]; -} - -export function getUser(id: string, callback: (user: User) => void) { - db.collection('users', function(error, users) { - if(error) { console.error(error); return; } - users.findOne({_id: id}, function(error, user) { - if(error) { console.error(error); return; } - callback(user); - }); - }); -} - -export function getUsers(callback: (users: User[]) => void) { - db.collection('users', function(error, users_collection) { - if(error) { console.error(error); return; } - users_collection.find({}, { '_id': 1 }).toArray(function(error, userobjs) { - if(error) { console.error(error); return; } - callback(userobjs); - }); - }); -} - -export function getImage(imageId: string, callback: (image: Image) => void) { - db.collection('images', function(error, images_collection) { - if(error) { console.error(error); return; } - images_collection.findOne({_id: new mongodb.ObjectID(imageId)}, function(error, image) { - if(error) { console.error(error); return; } - callback(image); - }); - }); -} - -export function getImages(imageIds: mongodb.ObjectID[], callback: (images: Image[]) => void) { - db.collection('images', function(error, images_collection) { - if(error) { console.error(error); return; } - images_collection.find({_id: {$in: imageIds}}).toArray(function(error, images) { - callback(images); - }); - }); -} - -export function addBoard(userid: any, title: string, description: string, callback: (user: User) => void) { - db.collection('users', function(error, users) { - if(error) { console.error(error); return; } - users.update( - {_id: userid}, - {"$push": {boards: { title: title, description: description, images: []}}}, - function(error, user) { - if(error) { console.error(error); return; } - callback(user); - } - ); - }); -} - -export function addPin(userid: string, boardid: string, imageUri: string, link: string, caption: string, callback: (user: User) => void) { - db.collection('images', function(error, images_collection) { - if(error) { console.error(error); return; } - images_collection.insert({ - user: userid, - caption: caption, - imageUri: imageUri, - link: link, - board: boardid, - comments: [] - }, function(error, image) { - console.log(image); - db.collection('users', function(error, users) { - if(error) { console.error(error); return; } - users.update( - {_id: userid, "boards.title": boardid}, - {"$push": {"boards.$.images": image[0]._id}}, - function(error, user) { - callback(user); - } - ); - }) - }) - }) -} +// Mongo +import mongodb = require('mongodb'); + +var server = new mongodb.Server('localhost', 27017, {auto_reconnect: true}); +var db = new mongodb.Db('mydb', server, { w: 1 }); +db.open(function() {}); + +export interface User { + _id: string; + email: string; + first_name: string; + last_name: string; + fbId: number; + boards: Board[]; +} + +export interface Board { + title: string; + description: string; + images: mongodb.ObjectID[]; +} + +export interface Image { + _id: mongodb.ObjectID; + user: string; + caption: string; + imageUri: string; + link: string; + board: string; + comments: {text: string; user: string;}[]; +} + +export function getUser(id: string, callback: (user: User) => void) { + db.collection('users', function(error, users) { + if(error) { console.error(error); return; } + users.find({_id: id}).batchSize(10).nextObject(function(error, user) { + if(error) { console.error(error); return; } + callback(user); + }); + }); +} + +export function getUsers(callback: (users: User[]) => void) { + db.collection('users', function(error, users_collection) { + if(error) { console.error(error); return; } + users_collection.find({}, { '_id': 1 }).toArray(function(error, userobjs) { + if(error) { console.error(error); return; } + callback(userobjs); + }); + }); +} + +export function getImage(imageId: string, callback: (image: Image) => void) { + db.collection('images', function(error, images_collection) { + if(error) { console.error(error); return; } + images_collection.find({_id: new mongodb.ObjectID(imageId)}).batchSize(10).nextObject(function(error, image) { + if(error) { console.error(error); return; } + callback(image); + }); + }); +} + +export function getImages(imageIds: mongodb.ObjectID[], callback: (images: Image[]) => void) { + db.collection('images', function(error, images_collection) { + if(error) { console.error(error); return; } + images_collection.find({_id: {$in: imageIds}}).toArray(function(error, images) { + callback(images); + }); + }); +} + +export function addBoard(userid: any, title: string, description: string, callback: (user: User) => void) { + db.collection('users', function(error, users) { + if(error) { console.error(error); return; } + users.update( + {_id: userid}, + {"$push": {boards: { title: title, description: description, images: []}}}, + function(error, user) { + if(error) { console.error(error); return; } + callback(user); + } + ); + }); +} + +export function addPin(userid: string, boardid: string, imageUri: string, link: string, caption: string, callback: (user: User) => void) { + db.collection('images', function(error, images_collection) { + if(error) { console.error(error); return; } + images_collection.insert({ + user: userid, + caption: caption, + imageUri: imageUri, + link: link, + board: boardid, + comments: [] + }, function(error, image) { + console.log(image); + db.collection('users', function(error, users) { + if(error) { console.error(error); return; } + users.update( + {_id: userid, "boards.title": boardid}, + {"$push": {"boards.$.images": image[0]._id}}, + function(error, user) { + callback(user); + } + ); + }) + }) + }) +} diff --git a/imageboard/package.json b/imageboard/package.json index 2666410..723204e 100644 --- a/imageboard/package.json +++ b/imageboard/package.json @@ -1,14 +1,14 @@ -{ - "name": "imageboard-sample", - "version": "0.0.1", - "private": true, - "dependencies": { - "express": "4.11.1", - "body-parser": "1.10.2", - "errorhandler": "1.3.2", - "method-override": "2.3.1", - "ejs": ">= 0.5.0", - "jade": ">= 0.0.1", - "mongodb": ">= 1.4.29" - } +{ + "name": "imageboard-sample", + "version": "0.0.1", + "private": true, + "dependencies": { + "express": "^4.13.3", + "body-parser": "^1.14.1", + "errorhandler": "^1.4.2", + "method-override": "^2.3.5", + "ejs": ">= 0.5.0", + "jade": ">= 1.11.0", + "mongodb": ">= 1.4.29" + } } \ No newline at end of file diff --git a/imageboard/public/javascripts/fb.js b/imageboard/public/javascripts/fb.js index 273693e..801bd04 100644 --- a/imageboard/public/javascripts/fb.js +++ b/imageboard/public/javascripts/fb.js @@ -1,31 +1,31 @@ -/// -/// - -// initialize the library with the API key -FB.init({ appId: '349900301735115' }); - -// fetch the status on load -FB.getLoginStatus(handleSessionResponse2); - -$('#login').bind('click', function () { - FB.login(handleSessionResponse); -}); - -$('#logout').bind('click', function () { - FB.logout(handleSessionResponse); -}); - -function handleSessionResponse2() { } -// handle a session response from any of the auth related calls -function handleSessionResponse() { - FB.api('/me', function (response) { - console.dir(response); - //$('#user-info').html(response.id + ' - ' + response.name); - }); - FB.api('/me/picture', function (response) { - console.dir(response); - var img = document.createElement('img'); - img.src = response; - document.body.appendChild(img); - }); -} +/// +/// + +// initialize the library with the API key +FB.init({ appId: '349900301735115' }); + +// fetch the status on load +FB.getLoginStatus(handleSessionResponse2); + +$('#login').bind('click', function () { + FB.login(handleSessionResponse); +}); + +$('#logout').bind('click', function () { + FB.logout(handleSessionResponse); +}); + +function handleSessionResponse2() { } +// handle a session response from any of the auth related calls +function handleSessionResponse() { + FB.api('/me', function (response) { + console.dir(response); + //$('#user-info').html(response.id + ' - ' + response.name); + }); + FB.api('/me/picture', function (response) { + console.dir(response); + var img = document.createElement('img'); + img.src = response; + document.body.appendChild(img); + }); +} diff --git a/imageboard/public/stylesheets/style.css b/imageboard/public/stylesheets/style.css index d2b07ad..b2722c2 100644 --- a/imageboard/public/stylesheets/style.css +++ b/imageboard/public/stylesheets/style.css @@ -1,102 +1,102 @@ -html { background-color: #f9f9f9; margin: 0; padding: 0; } -body { margin: 0 auto; padding: 0; font-family:"Segoe UI","HelveticaNeue-Light", sans-serif; font-weight:200;} -h1, h2, p, summary, footer, li { line-height: 170%; } -h1, h2 { border-bottom: 1px solid #aaa; font-family:"Segoe UI Light","HelveticaNeue-UltraLight", sans-serif; font-weight:100; } -h2 { font-size: 16pt; } -p { margin: 1em 20px 0 20px; } -ul { margin-top: 1em; } -#footer { font-style: italic; color: #999; text-align: center; padding: 1em 0 2em 0; margin-top: 1em; font-size: 80%; } -em { letter-spacing: 1px; } -li { margin-left: 1em; } - -#container -{ - padding: 50px; -} - -a -{ - font-weight: bold; - text-decoration: none; - color: #777777; -} - -.imglink -{ - text: none; -} - -img.small -{ - border:0; - width: 200px; -} - -img.large -{ - border:0; - display: block; - margin-left: auto; - margin-right: auto -} - - -.image -{ - margin: 10px; - padding: 5px; - word-wrap: break-word; - border-style: solid; - border-width: 1px; - border-color: #bbbbbb; - background-color: #ffffff; - -} - -.imagebox -{ - margin: 10px; -} - -.commentbox -{ - margin: 5px -5px -5px -5px; - padding: 5px; - background-color: #eeeeee; -} - -.primarysource -{ - font-size: 80%; -} - -form -{ - font-size: 18px; -} - -.inputtitle -{ - display:block; - float: left; - width: 100px; -} - -input[type="text"], textarea -{ - padding: 6px 12px; - line-height: 1.4; - border: 1px solid #A4A2A2; - border-radius: 6px; -} - - -input.button -{ - padding: 6px 12px; - line-height: 1.4; - border: 1px solid #A4A2A2; - border-radius: 6px; - background-color: #ab2222; - color: #ffffff; +html { background-color: #f9f9f9; margin: 0; padding: 0; } +body { margin: 0 auto; padding: 0; font-family:"Segoe UI","HelveticaNeue-Light", sans-serif; font-weight:200;} +h1, h2, p, summary, footer, li { line-height: 170%; } +h1, h2 { border-bottom: 1px solid #aaa; font-family:"Segoe UI Light","HelveticaNeue-UltraLight", sans-serif; font-weight:100; } +h2 { font-size: 16pt; } +p { margin: 1em 20px 0 20px; } +ul { margin-top: 1em; } +#footer { font-style: italic; color: #999; text-align: center; padding: 1em 0 2em 0; margin-top: 1em; font-size: 80%; } +em { letter-spacing: 1px; } +li { margin-left: 1em; } + +#container +{ + padding: 50px; +} + +a +{ + font-weight: bold; + text-decoration: none; + color: #777777; +} + +img.small +{ + border:0; + width: 200px; +} + +img.large +{ + border:0; + display: block; + margin-left: auto; + margin-right: auto +} + + +.image +{ + margin: 10px; + padding: 5px; + word-wrap: break-word; + border-style: solid; + border-width: 1px; + border-color: #bbbbbb; + background-color: #ffffff; + +} + +.imagebox +{ + margin: 10px; +} + +.commentbox +{ + margin: 5px -5px -5px -5px; + padding: 5px; + background-color: #eeeeee; +} + +.primarysource +{ + font-size: 80%; +} + +.title +{ + font-size: 2.5rem; +} + +form +{ + font-size: 18px; +} + +.inputtitle +{ + display:block; + float: left; + width: 100px; +} + +input[type="text"], textarea +{ + padding: 6px 12px; + line-height: 1.4; + border: 1px solid #A4A2A2; + border-radius: 6px; +} + + +input.button +{ + padding: 6px 12px; + line-height: 1.4; + border: 1px solid #A4A2A2; + border-radius: 6px; + background-color: #ab2222; + color: #ffffff; } \ No newline at end of file diff --git a/imageboard/routes/index.ts b/imageboard/routes/index.ts index 2b087bd..6c06431 100644 --- a/imageboard/routes/index.ts +++ b/imageboard/routes/index.ts @@ -1,9 +1,9 @@ -import express = require("express") -import db = require("../db") - -export function index(req: express.Request, res: express.Response) { - db.getUsers(function(users) { - console.dir(users); - res.render('index', { title: 'ImageBoard', users: users }) - }); +import express = require("express") +import db = require("../db") + +export function index(req: express.Request, res: express.Response) { + db.getUsers(function(users) { + console.dir(users); + res.render('index', { title: 'ImageBoard', users: users }) + }); }; \ No newline at end of file diff --git a/imageboard/tsconfig.json b/imageboard/tsconfig.json new file mode 100644 index 0000000..74fff99 --- /dev/null +++ b/imageboard/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "module": "commonjs", + "sourceMap": true + }, + "files": [ + "./typings/tsd.d.ts", + "./routes/index.ts", + "./db.ts", + "./app.ts" + ] +} \ No newline at end of file diff --git a/imageboard/tsd.json b/imageboard/tsd.json new file mode 100644 index 0000000..cca55c2 --- /dev/null +++ b/imageboard/tsd.json @@ -0,0 +1,33 @@ +{ + "version": "v4", + "repo": "borisyankov/DefinitelyTyped", + "ref": "master", + "path": "typings", + "bundle": "typings/tsd.d.ts", + "installed": { + "mime/mime.d.ts": { + "commit": "fc341765ebbb04b7109981a25dced01f488f4d94" + }, + "serve-static/serve-static.d.ts": { + "commit": "fc341765ebbb04b7109981a25dced01f488f4d94" + }, + "express/express.d.ts": { + "commit": "fc341765ebbb04b7109981a25dced01f488f4d94" + }, + "mongodb/mongodb.d.ts": { + "commit": "fc341765ebbb04b7109981a25dced01f488f4d94" + }, + "node/node.d.ts": { + "commit": "fc341765ebbb04b7109981a25dced01f488f4d94" + }, + "method-override/method-override.d.ts": { + "commit": "fc341765ebbb04b7109981a25dced01f488f4d94" + }, + "errorhandler/errorhandler.d.ts": { + "commit": "fc341765ebbb04b7109981a25dced01f488f4d94" + }, + "body-parser/body-parser.d.ts": { + "commit": "fc341765ebbb04b7109981a25dced01f488f4d94" + } + } +} diff --git a/imageboard/typings/express/express-middleware.d.ts b/imageboard/typings/express/express-middleware.d.ts deleted file mode 100644 index 9d1c09f..0000000 --- a/imageboard/typings/express/express-middleware.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -/// - -declare module "body-parser" { - import express = require("express"); - function bodyParser(): express.RequestHandler; - module bodyParser { - function urlencoded(opts?: any): express.RequestHandler; - function json(): express.RequestHandler; - } - export = bodyParser; -} - -declare module "method-override" { - import express = require("express"); - function methodOverride(): express.RequestHandler; - export = methodOverride; -} - -declare module "errorhandler" { - import express = require("express"); - function errorHandler(opts?: any): express.ErrorRequestHandler; - export = errorHandler; -} \ No newline at end of file diff --git a/imageboard/typings/express/express.d.ts b/imageboard/typings/express/express.d.ts deleted file mode 100644 index 043c1e4..0000000 --- a/imageboard/typings/express/express.d.ts +++ /dev/null @@ -1,1093 +0,0 @@ -// Type definitions for Express 4.x -// Project: http://expressjs.com -// Definitions by: Boris Yankov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/* =================== USAGE =================== - - import express = require('express'); - var app = express(); - - =============================================== */ - -/// - -declare module Express { - - // These open interfaces may be extended in an application-specific manner via declaration merging. - // See for example method-override.d.ts (https://github.com/borisyankov/DefinitelyTyped/blob/master/method-override/method-override.d.ts) - export interface Request { } - export interface Response { } - export interface Application { } -} - - -declare module "express" { - import http = require('http'); - - function e(): e.Express; - - module e { - interface IRoute { - path: string; - stack: any; - all(...handler: RequestHandler[]): IRoute; - get(...handler: RequestHandler[]): IRoute; - post(...handler: RequestHandler[]): IRoute; - put(...handler: RequestHandler[]): IRoute; - delete(...handler: RequestHandler[]): IRoute; - patch(...handler: RequestHandler[]): IRoute; - options(...handler: RequestHandler[]): IRoute; - } - - interface IRouterMatcher { - (name: string, ...handlers: RequestHandler[]): T; - (name: RegExp, ...handlers: RequestHandler[]): T; - } - - interface IRouter extends RequestHandler { - /** - * Map the given param placeholder `name`(s) to the given callback(s). - * - * Parameter mapping is used to provide pre-conditions to routes - * which use normalized placeholders. For example a _:user_id_ parameter - * could automatically load a user's information from the database without - * any additional code, - * - * The callback uses the samesignature as middleware, the only differencing - * being that the value of the placeholder is passed, in this case the _id_ - * of the user. Once the `next()` function is invoked, just like middleware - * it will continue on to execute the route, or subsequent parameter functions. - * - * app.param('user_id', function(req, res, next, id){ - * User.find(id, function(err, user){ - * if (err) { - * next(err); - * } else if (user) { - * req.user = user; - * next(); - * } else { - * next(new Error('failed to load user')); - * } - * }); - * }); - * - * @param name - * @param fn - */ - param(name: string, handler: RequestParamHandler): T; - param(name: string, matcher: RegExp): T; - param(name: string, mapper: (param: any) => any): T; - // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API - param(callback: (name: string, matcher: RegExp) => RequestParamHandler): T; - - /** - * Special-cased "all" method, applying the given route `path`, - * middleware, and callback to _every_ HTTP method. - * - * @param path - * @param fn - */ - all: IRouterMatcher; - get: IRouterMatcher; - post: IRouterMatcher; - put: IRouterMatcher; - delete: IRouterMatcher; - patch: IRouterMatcher; - options: IRouterMatcher; - - route(path: string): IRoute; - - use(...handler: RequestHandler[]): T; - use(handler: ErrorRequestHandler): T; - use(path: string, ...handler: RequestHandler[]): T; - use(path: string, handler: ErrorRequestHandler): T; - } - - export function Router(options?: any): Router; - - export interface Router extends IRouter {} - - interface CookieOptions { - maxAge?: number; - signed?: boolean; - expires?: Date; - httpOnly?: boolean; - path?: string; - domain?: string; - secure?: boolean; - } - - interface Errback { (err: Error): void; } - - interface Request extends http.ServerRequest, Express.Request { - - /** - * Return request header. - * - * The `Referrer` header field is special-cased, - * both `Referrer` and `Referer` are interchangeable. - * - * Examples: - * - * req.get('Content-Type'); - * // => "text/plain" - * - * req.get('content-type'); - * // => "text/plain" - * - * req.get('Something'); - * // => undefined - * - * Aliased as `req.header()`. - * - * @param name - */ - get (name: string): string; - - header(name: string): string; - - headers: { [key: string]: string; }; - - /** - * Check if the given `type(s)` is acceptable, returning - * the best match when true, otherwise `undefined`, in which - * case you should respond with 406 "Not Acceptable". - * - * The `type` value may be a single mime type string - * such as "application/json", the extension name - * such as "json", a comma-delimted list such as "json, html, text/plain", - * or an array `["json", "html", "text/plain"]`. When a list - * or array is given the _best_ match, if any is returned. - * - * Examples: - * - * // Accept: text/html - * req.accepts('html'); - * // => "html" - * - * // Accept: text/*, application/json - * req.accepts('html'); - * // => "html" - * req.accepts('text/html'); - * // => "text/html" - * req.accepts('json, text'); - * // => "json" - * req.accepts('application/json'); - * // => "application/json" - * - * // Accept: text/*, application/json - * req.accepts('image/png'); - * req.accepts('png'); - * // => undefined - * - * // Accept: text/*;q=.5, application/json - * req.accepts(['html', 'json']); - * req.accepts('html, json'); - * // => "json" - */ - accepts(type: string): string; - - accepts(type: string[]): string; - - /** - * Check if the given `charset` is acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param charset - */ - acceptsCharset(charset: string): boolean; - - /** - * Check if the given `lang` is acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param lang - */ - acceptsLanguage(lang: string): boolean; - - /** - * Parse Range header field, - * capping to the given `size`. - * - * Unspecified ranges such as "0-" require - * knowledge of your resource length. In - * the case of a byte range this is of course - * the total number of bytes. If the Range - * header field is not given `null` is returned, - * `-1` when unsatisfiable, `-2` when syntactically invalid. - * - * NOTE: remember that ranges are inclusive, so - * for example "Range: users=0-3" should respond - * with 4 users when available, not 3. - * - * @param size - */ - range(size: number): any[]; - - /** - * Return an array of Accepted media types - * ordered from highest quality to lowest. - */ - accepted: MediaType[]; - - /** - * Return an array of Accepted languages - * ordered from highest quality to lowest. - * - * Examples: - * - * Accept-Language: en;q=.5, en-us - * ['en-us', 'en'] - */ - acceptedLanguages: any[]; - - /** - * Return an array of Accepted charsets - * ordered from highest quality to lowest. - * - * Examples: - * - * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8 - * ['unicode-1-1', 'iso-8859-5'] - */ - acceptedCharsets: any[]; - - /** - * Return the value of param `name` when present or `defaultValue`. - * - * - Checks route placeholders, ex: _/user/:id_ - * - Checks body params, ex: id=12, {"id":12} - * - Checks query string params, ex: ?id=12 - * - * To utilize request bodies, `req.body` - * should be an object. This can be done by using - * the `connect.bodyParser()` middleware. - * - * @param name - * @param defaultValue - */ - param(name: string, defaultValue?: any): string; - - /** - * Check if the incoming request contains the "Content-Type" - * header field, and it contains the give mime `type`. - * - * Examples: - * - * // With Content-Type: text/html; charset=utf-8 - * req.is('html'); - * req.is('text/html'); - * req.is('text/*'); - * // => true - * - * // When Content-Type is application/json - * req.is('json'); - * req.is('application/json'); - * req.is('application/*'); - * // => true - * - * req.is('html'); - * // => false - * - * @param type - */ - is(type: string): boolean; - - /** - * Return the protocol string "http" or "https" - * when requested with TLS. When the "trust proxy" - * setting is enabled the "X-Forwarded-Proto" header - * field will be trusted. If you're running behind - * a reverse proxy that supplies https for you this - * may be enabled. - */ - protocol: string; - - /** - * Short-hand for: - * - * req.protocol == 'https' - */ - secure: boolean; - - /** - * Return the remote address, or when - * "trust proxy" is `true` return - * the upstream addr. - */ - ip: string; - - /** - * When "trust proxy" is `true`, parse - * the "X-Forwarded-For" ip address list. - * - * For example if the value were "client, proxy1, proxy2" - * you would receive the array `["client", "proxy1", "proxy2"]` - * where "proxy2" is the furthest down-stream. - */ - ips: string[]; - - /** - * Return subdomains as an array. - * - * Subdomains are the dot-separated parts of the host before the main domain of - * the app. By default, the domain of the app is assumed to be the last two - * parts of the host. This can be changed by setting "subdomain offset". - * - * For example, if the domain is "tobi.ferrets.example.com": - * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. - * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. - */ - subdomains: string[]; - - /** - * Short-hand for `url.parse(req.url).pathname`. - */ - path: string; - - /** - * Parse the "Host" header field hostname. - */ - host: string; - - /** - * Check if the request is fresh, aka - * Last-Modified and/or the ETag - * still match. - */ - fresh: boolean; - - /** - * Check if the request is stale, aka - * "Last-Modified" and / or the "ETag" for the - * resource has changed. - */ - stale: boolean; - - /** - * Check if the request was an _XMLHttpRequest_. - */ - xhr: boolean; - - //body: { username: string; password: string; remember: boolean; title: string; }; - body: any; - - //cookies: { string; remember: boolean; }; - cookies: any; - - method: string; - - params: any; - - user: any; - - authenticatedUser: any; - - files: any; - - /** - * Clear cookie `name`. - * - * @param name - * @param options - */ - clearCookie(name: string, options?: any): Response; - - query: any; - - route: any; - - signedCookies: any; - - originalUrl: string; - - url: string; - } - - interface MediaType { - value: string; - quality: number; - type: string; - subtype: string; - } - - interface Send { - (status: number, body?: any): Response; - (body: any): Response; - } - - interface Response extends http.ServerResponse, Express.Response { - /** - * Set status `code`. - * - * @param code - */ - status(code: number): Response; - - /** - * Set the response HTTP status code to `statusCode` and send its string representation as the response body. - * @link http://expressjs.com/4x/api.html#res.sendStatus - * - * Examples: - * - * res.sendStatus(200); // equivalent to res.status(200).send('OK') - * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden') - * res.sendStatus(404); // equivalent to res.status(404).send('Not Found') - * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error') - * - * @param code - */ - sendStatus(code: number): Response; - - /** - * Set Link header field with the given `links`. - * - * Examples: - * - * res.links({ - * next: 'http://api.example.com/users?page=2', - * last: 'http://api.example.com/users?page=5' - * }); - * - * @param links - */ - links(links: any): Response; - - /** - * Send a response. - * - * Examples: - * - * res.send(new Buffer('wahoo')); - * res.send({ some: 'json' }); - * res.send('

some html

'); - * res.send(404, 'Sorry, cant find that'); - * res.send(404); - */ - send: Send; - - /** - * Send JSON response. - * - * Examples: - * - * res.json(null); - * res.json({ user: 'tj' }); - * res.json(500, 'oh noes!'); - * res.json(404, 'I dont have that'); - */ - json: Send; - - /** - * Send JSON response with JSONP callback support. - * - * Examples: - * - * res.jsonp(null); - * res.jsonp({ user: 'tj' }); - * res.jsonp(500, 'oh noes!'); - * res.jsonp(404, 'I dont have that'); - */ - jsonp: Send; - - /** - * Transfer the file at the given `path`. - * - * Automatically sets the _Content-Type_ response header field. - * The callback `fn(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.sentHeader` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: - * - * - `maxAge` defaulting to 0 (can be string converted by `ms`) - * - `root` root directory for relative filenames - * - `headers` object of headers to serve with file - * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them - * - * Other options are passed along to `send`. - * - * Examples: - * - * The following example illustrates how `res.sendFile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendFile()` is actually - * the same code, so HTTP cache support etc is identical. - * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; - * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendFile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); - * - * @api public - */ - sendFile(path: string): void; - sendFile(path: string, options: any): void; - sendFile(path: string, fn: Errback): void; - sendFile(path: string, options: any, fn: Errback): void; - - /** - * deprecated, use sendFile instead. - */ - sendfile(path: string): void; - /** - * deprecated, use sendFile instead. - */ - sendfile(path: string, options: any): void; - /** - * deprecated, use sendFile instead. - */ - sendfile(path: string, fn: Errback): void; - /** - * deprecated, use sendFile instead. - */ - sendfile(path: string, options: any, fn: Errback): void; - - /** - * Transfer the file at the given `path` as an attachment. - * - * Optionally providing an alternate attachment `filename`, - * and optional callback `fn(err)`. The callback is invoked - * when the data transfer is complete, or when an error has - * ocurred. Be sure to check `res.headerSent` if you plan to respond. - * - * This method uses `res.sendfile()`. - */ - download(path: string): void; - download(path: string, filename: string): void; - download(path: string, fn: Errback): void; - download(path: string, filename: string, fn: Errback): void; - - /** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); - * - * @param type - */ - contentType(type: string): Response; - - /** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); - * - * @param type - */ - type(type: string): Response; - - /** - * Respond to the Acceptable formats using an `obj` - * of mime-type callbacks. - * - * This method uses `req.accepted`, an array of - * acceptable types ordered by their quality values. - * When "Accept" is not present the _first_ callback - * is invoked, otherwise the first match is used. When - * no match is performed the server responds with - * 406 "Not Acceptable". - * - * Content-Type is set for you, however if you choose - * you may alter this within the callback using `res.type()` - * or `res.set('Content-Type', ...)`. - * - * res.format({ - * 'text/plain': function(){ - * res.send('hey'); - * }, - * - * 'text/html': function(){ - * res.send('

hey

'); - * }, - * - * 'appliation/json': function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * In addition to canonicalized MIME types you may - * also use extnames mapped to these types: - * - * res.format({ - * text: function(){ - * res.send('hey'); - * }, - * - * html: function(){ - * res.send('

hey

'); - * }, - * - * json: function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * By default Express passes an `Error` - * with a `.status` of 406 to `next(err)` - * if a match is not made. If you provide - * a `.default` callback it will be invoked - * instead. - * - * @param obj - */ - format(obj: any): Response; - - /** - * Set _Content-Disposition_ header to _attachment_ with optional `filename`. - * - * @param filename - */ - attachment(filename?: string): Response; - - /** - * Set header `field` to `val`, or pass - * an object of header fields. - * - * Examples: - * - * res.set('Foo', ['bar', 'baz']); - * res.set('Accept', 'application/json'); - * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); - * - * Aliased as `res.header()`. - */ - set(field: any): Response; - set(field: string, value?: string): Response; - - header(field: any): Response; - header(field: string, value?: string): Response; - - // Property indicating if HTTP headers has been sent for the response. - headersSent: boolean; - - /** - * Get value for header `field`. - * - * @param field - */ - get (field: string): string; - - /** - * Clear cookie `name`. - * - * @param name - * @param options - */ - clearCookie(name: string, options?: any): Response; - - /** - * Set cookie `name` to `val`, with the given `options`. - * - * Options: - * - * - `maxAge` max-age in milliseconds, converted to `expires` - * - `signed` sign the cookie - * - `path` defaults to "/" - * - * Examples: - * - * // "Remember Me" for 15 minutes - * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); - * - * // save as above - * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) - */ - cookie(name: string, val: string, options: CookieOptions): Response; - cookie(name: string, val: any, options: CookieOptions): Response; - cookie(name: string, val: any): Response; - - /** - * Set the location header to `url`. - * - * The given `url` can also be the name of a mapped url, for - * example by default express supports "back" which redirects - * to the _Referrer_ or _Referer_ headers or "/". - * - * Examples: - * - * res.location('/foo/bar').; - * res.location('http://example.com'); - * res.location('../login'); // /blog/post/1 -> /blog/login - * - * Mounting: - * - * When an application is mounted and `res.location()` - * is given a path that does _not_ lead with "/" it becomes - * relative to the mount-point. For example if the application - * is mounted at "/blog", the following would become "/blog/login". - * - * res.location('login'); - * - * While the leading slash would result in a location of "/login": - * - * res.location('/login'); - * - * @param url - */ - location(url: string): Response; - - /** - * Redirect to the given `url` with optional response `status` - * defaulting to 302. - * - * The resulting `url` is determined by `res.location()`, so - * it will play nicely with mounted apps, relative paths, - * `"back"` etc. - * - * Examples: - * - * res.redirect('/foo/bar'); - * res.redirect('http://example.com'); - * res.redirect(301, 'http://example.com'); - * res.redirect('http://example.com', 301); - * res.redirect('../login'); // /blog/post/1 -> /blog/login - */ - redirect(url: string): void; - redirect(status: number, url: string): void; - redirect(url: string, status: number): void; - - /** - * Render `view` with the given `options` and optional callback `fn`. - * When a callback function is given a response will _not_ be made - * automatically, otherwise a response of _200_ and _text/html_ is given. - * - * Options: - * - * - `cache` boolean hinting to the engine it should cache - * - `filename` filename of the view being rendered - */ - render(view: string, options?: Object, callback?: (err: Error, html: string) => void ): void; - render(view: string, callback?: (err: Error, html: string) => void ): void; - - locals: any; - - charset: string; - } - - interface ErrorRequestHandler { - (err: any, req: Request, res: Response, next: Function): any; - } - - interface RequestHandler { - (req: Request, res: Response, next: Function): any; - } - - interface Handler extends RequestHandler {} - - interface RequestParamHandler { - (req: Request, res: Response, next: Function, param: any): any; - } - - interface Application extends IRouter, Express.Application { - /** - * Initialize the server. - * - * - setup default configuration - * - setup default middleware - * - setup route reflection methods - */ - init(): void; - - /** - * Initialize application configuration. - */ - defaultConfiguration(): void; - - /** - * Register the given template engine callback `fn` - * as `ext`. - * - * By default will `require()` the engine based on the - * file extension. For example if you try to render - * a "foo.jade" file Express will invoke the following internally: - * - * app.engine('jade', require('jade').__express); - * - * For engines that do not provide `.__express` out of the box, - * or if you wish to "map" a different extension to the template engine - * you may use this method. For example mapping the EJS template engine to - * ".html" files: - * - * app.engine('html', require('ejs').renderFile); - * - * In this case EJS provides a `.renderFile()` method with - * the same signature that Express expects: `(path, options, callback)`, - * though note that it aliases this method as `ejs.__express` internally - * so if you're using ".ejs" extensions you dont need to do anything. - * - * Some template engines do not follow this convention, the - * [Consolidate.js](https://github.com/visionmedia/consolidate.js) - * library was created to map all of node's popular template - * engines to follow this convention, thus allowing them to - * work seamlessly within Express. - */ - engine(ext: string, fn: Function): Application; - - /** - * Assign `setting` to `val`, or return `setting`'s value. - * - * app.set('foo', 'bar'); - * app.get('foo'); - * // => "bar" - * app.set('foo', ['bar', 'baz']); - * app.get('foo'); - * // => ["bar", "baz"] - * - * Mounted servers inherit their parent server's settings. - * - * @param setting - * @param val - */ - set(setting: string, val: any): Application; - get: { - (name: string): any; // Getter - (name: string, ...handlers: RequestHandler[]): Application; - (name: RegExp, ...handlers: RequestHandler[]): Application; - }; - - /** - * Return the app's absolute pathname - * based on the parent(s) that have - * mounted it. - * - * For example if the application was - * mounted as "/admin", which itself - * was mounted as "/blog" then the - * return value would be "/blog/admin". - */ - path(): string; - - /** - * Check if `setting` is enabled (truthy). - * - * app.enabled('foo') - * // => false - * - * app.enable('foo') - * app.enabled('foo') - * // => true - */ - enabled(setting: string): boolean; - - /** - * Check if `setting` is disabled. - * - * app.disabled('foo') - * // => true - * - * app.enable('foo') - * app.disabled('foo') - * // => false - * - * @param setting - */ - disabled(setting: string): boolean; - - /** - * Enable `setting`. - * - * @param setting - */ - enable(setting: string): Application; - - /** - * Disable `setting`. - * - * @param setting - */ - disable(setting: string): Application; - - /** - * Configure callback for zero or more envs, - * when no `env` is specified that callback will - * be invoked for all environments. Any combination - * can be used multiple times, in any order desired. - * - * Examples: - * - * app.configure(function(){ - * // executed for all envs - * }); - * - * app.configure('stage', function(){ - * // executed staging env - * }); - * - * app.configure('stage', 'production', function(){ - * // executed for stage and production - * }); - * - * Note: - * - * These callbacks are invoked immediately, and - * are effectively sugar for the following: - * - * var env = process.env.NODE_ENV || 'development'; - * - * switch (env) { - * case 'development': - * ... - * break; - * case 'stage': - * ... - * break; - * case 'production': - * ... - * break; - * } - * - * @param env - * @param fn - */ - configure(fn: Function): Application; - configure(env0: string, fn: Function): Application; - configure(env0: string, env1: string, fn: Function): Application; - configure(env0: string, env1: string, env2: string, fn: Function): Application; - configure(env0: string, env1: string, env2: string, env3: string, fn: Function): Application; - configure(env0: string, env1: string, env2: string, env3: string, env4: string, fn: Function): Application; - - /** - * Render the given view `name` name with `options` - * and a callback accepting an error and the - * rendered template string. - * - * Example: - * - * app.render('email', { name: 'Tobi' }, function(err, html){ - * // ... - * }) - * - * @param name - * @param options or fn - * @param fn - */ - render(name: string, options?: Object, callback?: (err: Error, html: string) => void): void; - render(name: string, callback: (err: Error, html: string) => void): void; - - - /** - * Listen for connections. - * - * A node `http.Server` is returned, with this - * application (which is a `Function`) as its - * callback. If you wish to create both an HTTP - * and HTTPS server you may do so with the "http" - * and "https" modules as shown here: - * - * var http = require('http') - * , https = require('https') - * , express = require('express') - * , app = express(); - * - * http.createServer(app).listen(80); - * https.createServer({ ... }, app).listen(443); - */ - listen(port: number, hostname: string, backlog: number, callback?: Function): http.Server; - listen(port: number, hostname: string, callback?: Function): http.Server; - listen(port: number, callback?: Function): http.Server; - listen(path: string, callback?: Function): http.Server; - listen(handle: any, listeningListener?: Function): http.Server; - - route(path: string): IRoute; - - router: string; - - settings: any; - - resource: any; - - map: any; - - locals: any; - - /** - * The app.routes object houses all of the routes defined mapped by the - * associated HTTP verb. This object may be used for introspection - * capabilities, for example Express uses this internally not only for - * routing but to provide default OPTIONS behaviour unless app.options() - * is used. Your application or framework may also remove routes by - * simply by removing them from this object. - */ - routes: any; - } - - interface Express extends Application { - /** - * Framework version. - */ - version: string; - - /** - * Expose mime. - */ - mime: string; - - (): Application; - - /** - * Create an express application. - */ - createApplication(): Application; - - createServer(): Application; - - application: any; - - request: Request; - - response: Response; - } - - /** - * Static: - * - * Static file server with the given `root` path. - * - * Examples: - * - * var oneDay = 86400000; - * - * connect() - * .use(connect.static(__dirname + '/public')) - * - * connect() - * .use(connect.static(__dirname + '/public', { maxAge: oneDay })) - * - * Options: - * - * - `maxAge` Browser cache maxAge in milliseconds. defaults to 0 - * - `hidden` Allow transfer of hidden files. defaults to false - * - `redirect` Redirect to trailing "/" when the pathname is a dir. defaults to true - * - * @param root - * @param options - */ - function static(root: string, options?: any): RequestHandler; - } - - export = e; -} diff --git a/imageboard/typings/mongodb/mongodb.d.ts b/imageboard/typings/mongodb/mongodb.d.ts deleted file mode 100644 index a28f484..0000000 --- a/imageboard/typings/mongodb/mongodb.d.ts +++ /dev/null @@ -1,443 +0,0 @@ -// Type definitions for MongoDB -// Project: https://github.com/mongodb/node-mongodb-native -// Definitions by: Boris Yankov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -// Documentation : http://mongodb.github.io/node-mongodb-native/ - -/// - -declare module "mongodb" { - - // Class documentation : http://mongodb.github.io/node-mongodb-native/api-generated/mongoclient.html - export class MongoClient{ - constructor(serverConfig: any, options: any); - - static connect(uri: string, options: any, callback: (err: Error, db: Db) => void): void; - static connect(uri: string, callback: (err: Error, db: Db) => void): void; - } - - // Class documentation : http://mongodb.github.io/node-mongodb-native/api-generated/server.html - export class Server { - constructor (host: string, port: number, opts?: ServerOptions); - - public connect(): any; - } - - // Class documentation : http://mongodb.github.io/node-mongodb-native/api-generated/db.html - export class Db { - constructor (databaseName: string, serverConfig: Server, dbOptions?: DbCreateOptions); - - public db(dbName: string): Db; - - public open(callback: (err : Error, db : Db) => void ): void; - public close(forceClose?: boolean, callback?: (err: Error, result: any) => void ): void; - public admin(callback: (err: Error, result: any) => void ): any; - public collectionsInfo(collectionName: string, callback?: (err: Error, result: any) => void ): void; - public collectionNames(collectionName: string, options: any, callback?: (err: Error, result: any) => void ): void; - - public collection(collectionName: string): Collection; - public collection(collectionName: string, callback: (err: Error, collection: Collection) => void ): Collection; - public collection(collectionName: string, options: MongoCollectionOptions, callback: (err: Error, collection: Collection) => void ): Collection; - - public collections(callback: (err: Error, collections: Collection[]) => void ): void; - public eval(code: any, parameters: any[], options?: any, callback?: (err: Error, result: any) => void ): void; - //public dereference(dbRef: DbRef, callback: (err: Error, result: any) => void): void; - - public logout(options: any, callback?: (err: Error, result: any) => void ): void; - public logout(callback: (err: Error, result: any) => void ): void; - - public authenticate(userName: string, password: string, callback?: (err: Error, result: any) => void ): void; - public authenticate(userName: string, password: string, options: any, callback?: (err: Error, result: any) => void ): void; - - public addUser(username: string, password: string, callback?: (err: Error, result: any) => void ): void; - public addUser(username: string, password: string, options: any, callback?: (err: Error, result: any) => void ): void; - - public removeUser(username: string, callback?: (err: Error, result: any) => void ): void; - public removeUser(username: string, options: any, callback?: (err: Error, result: any) => void ): void; - - public createCollection(collectionName: string, callback?: (err: Error, result: Collection) => void ): void; - public createCollection(collectionName: string, options: CollectionCreateOptions, callback?: (err: Error, result: any) => void ): void; - - public command(selector: Object, callback?: (err: Error, result: any) => void ): void; - public command(selector: Object, options: any, callback?: (err: Error, result: any) => void ): void; - - public dropCollection(collectionName: string, callback?: (err: Error, result: any) => void ): void; - public renameCollection(fromCollection: string, toCollection: string, callback?: (err: Error, result: any) => void ): void; - - public lastError(options: Object, connectionOptions: any, callback: (err: Error, result: any) => void ): void; - public previousError(options: Object, callback: (err: Error, result: any) => void ): void; - - // error = lastError - // lastStatus = lastError - - public executeDbCommand(command_hash: any, callback?: (err: Error, result: any) => void ): void; - public executeDbCommand(command_hash: any, options: any, callback?: (err: Error, result: any) => void ): void; - - public executeDbAdminCommand(command_hash: any, callback?: (err: Error, result: any) => void ): void; - public executeDbAdminCommand(command_hash: any, options: any, callback?: (err: Error, result: any) => void ): void; - - public resetErrorHistory(callback?: (err: Error, result: any) => void ): void; - public resetErrorHistory(options: any, callback?: (err: Error, result: any) => void ): void; - - public createIndex(collectionName: any, fieldOrSpec: any, options: IndexOptions, callback: Function): void; - public ensureIndex(collectionName: any, fieldOrSpec: any, options: IndexOptions, callback: Function): void; - - public cursorInfo(options: any, callback: Function): void; - - public dropIndex(collectionName: string, indexName: string, callback: Function): void; - public reIndex(collectionName: string, callback: Function): void; - public indexInformation(collectionName: string, options: any, callback: Function): void; - public dropDatabase(callback: (err: Error, result: any) => void ): void; - - public stats(options: any, callback: Function): void; - public _registerHandler(db_command: any, raw: any, connection: any, exhaust: any, callback: Function): void; - public _reRegisterHandler(newId: any, object: any, callback: Function): void; - public _callHandler(id: any, document: any, err: any): any; - public _hasHandler(id: any): any; - public _removeHandler(id: any): any; - public _findHandler(id: any): { id: string; callback: Function; }; - public __executeQueryCommand(self: any, db_command: any, options: any, callback: any): void; - - public DEFAULT_URL: string; - - public connect(url: string, options: { uri_decode_auth?: boolean; }, callback: (err: Error, result: any) => void ): void; - - public addListener(event: string, handler:(param: any) => any): any; - } - - // Class documentation : http://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html - // Last update: doc. version 1.3.13 (28.08.2013) - export class ObjectID { - constructor (s?: string); - - // Returns the ObjectID id as a 24 byte hex string representation - public toHexString() : string; - - // Compares the equality of this ObjectID with otherID. - public equals(otherID: ObjectID) : boolean; - - // Returns the generation date (accurate up to the second) that this ID was generated. - public getTimestamp(): Date; - - // Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. - // time – an integer number representing a number of seconds. - public static createFromTime(time: number): ObjectID; - - // Creates an ObjectID from a hex string representation of an ObjectID. - // hexString – create a ObjectID from a passed in 24 byte hexstring. - public static createFromHexString(hexString: string): ObjectID; - } - - // Class documentation : http://mongodb.github.io/node-mongodb-native/api-bson-generated/binary.html - export class Binary { - constructor (buffer: Buffer, subType?: number); - - // Updates this binary with byte_value - put(byte_value: any): void; - - // Writes a buffer or string to the binary - write(buffer: any, offset: number): void; - - // Reads length bytes starting at position. - read(position: number, length: number): Buffer; - - // Returns the value of this binary as a string. - value(): string; - - // The length of the binary. - length(): number; - } - - export interface SocketOptions { - //= set seconds before connection times out default:0 - timeout?: number; - //= Disables the Nagle algorithm default:true - noDelay?: boolean; - //= Set if keepAlive is used default:0 , which means no keepAlive, set higher than 0 for keepAlive - keepAlive?: number; - //= ‘ascii’|’utf8’|’base64’ default:null - encoding?: string; - } - - export interface ServerOptions { - // - to reconnect automatically, default:false - auto_reconnect?: boolean; - // - specify the number of connections in the pool default:1 - poolSize?: number; - // - a collection of pr socket settings - socketOptions?: any; - } - - export interface PKFactory { - counter: number; - createPk: () => number; - } - - // See : http://mongodb.github.io/node-mongodb-native/api-generated/db.html - // Current definition by documentation version 1.3.13 (28.08.2013) - export interface DbCreateOptions { - // the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = ‘majority’ or tag acknowledges the write. - w?: any; - - // set the timeout for waiting for write concern to finish (combines with w option). - wtimeout?: number; - - // write waits for fsync before returning. default:false. - fsync?: boolean; - - // write waits for journal sync before returning. default:false. - journal?: boolean; - - // the prefered read preference. use 'ReadPreference' class. - readPreference?: string; - - // use c++ bson parser. default:false. - native_parser?: boolean; - - // force server to create _id fields instead of client. default:false. - forceServerObjectId?: boolean; - - // custom primary key factory to generate _id values (see Custom primary keys). - pkFactory?: PKFactory; - - // serialize functions. default:false. - serializeFunctions?: boolean; - - // peform operations using raw bson buffers. default:false. - raw?: boolean; - - // record query statistics during execution. default:false. - recordQueryStats?: boolean; - - // number of miliseconds between retries. default:5000. - retryMiliSeconds?: number; - - // number of retries off connection. default:5. - numberOfRetries?: number; - - // an object representing a logger that you want to use, needs to support functions debug, log, error. default:null. - logger?: Object - - // force setting of SlaveOk flag on queries (only use when explicitly connecting to a secondary server). default:null. - slaveOk?: number; - - // when deserializing a Long will fit it into a Number if it’s smaller than 53 bits. default:true. - promoteLongs?: boolean; - } - - export class ReadPreference { - public static PRIMARY: string; - public static PRIMARY_PREFERRED: string; - public static SECONDARY: string; - public static SECONDARY_PREFERRED: string; - public static NEAREST: string; - } - - // See : http://mongodb.github.io/node-mongodb-native/api-generated/collection.html - // Current definition by documentation version 1.3.13 (28.08.2013) - export interface CollectionCreateOptions { - // the prefered read preference. use 'ReadPreference' class. - readPreference?: string; - - // Allow reads from secondaries. default:false. - slaveOk?: boolean; - - // serialize functions on the document. default:false. - serializeFunctions?: boolean; - - // perform all operations using raw bson objects. default:false. - raw?: boolean; - - // object overriding the basic ObjectID primary key generation. - pkFactory?: PKFactory; - } - - // Documentation : http://mongodb.github.io/node-mongodb-native/api-generated/collection.html - export interface Collection { - new (db: Db, collectionName: string, pkFactory?: Object, options?: CollectionCreateOptions): Collection; // is this right? - - insert(query: any, callback: (err: Error, result: any) => void): void; - insert(query: any, options: { safe?: any; continueOnError?: boolean; keepGoing?: boolean; serializeFunctions?: boolean; }, callback: (err: Error, result: any) => void): void; - - remove(selector: Object, callback?: (err: Error, result: any) => void): void; - remove(selector: Object, options: { safe?: any; single?: boolean; }, callback?: (err: Error, result: any) => void): void; - - rename(newName: String, callback?: (err: Error, result: any) => void): void; - - save(doc: any, callback : (err: Error, result: any) => void): void; - save(doc: any, options: { safe: any; }, callback : (err: Error, result: any) => void): void; - - update(selector: Object, document: any, callback?: (err: Error, result: any) => void): void; - update(selector: Object, document: any, options: { safe?: boolean; upsert?: any; multi?: boolean; serializeFunctions?: boolean; }, callback: (err: Error, result: any) => void): void; - - distinct(key: string, query: Object, callback: (err: Error, result: any) => void): void; - distinct(key: string, query: Object, options: { readPreference: string; }, callback: (err: Error, result: any) => void): void; - - count(callback: (err: Error, result: any) => void): void; - count(query: Object, callback: (err: Error, result: any) => void): void; - count(query: Object, options: { readPreference: string; }, callback: (err: Error, result: any) => void): void; - - drop(callback?: (err: Error, result: any) => void): void; - - findAndModify(query: Object, sort: any[], doc: Object, callback: (err: Error, result: any) => void): void; - findAndModify(query: Object, sort: any[], doc: Object, options: { safe?: any; remove?: boolean; upsert?: boolean; new?: boolean; }, callback: (err: Error, result: any) => void): void; - - findAndRemove(query : Object, sort? : any[], callback?: (err: Error, result: any) => void): void; - findAndRemove(query : Object, sort? : any[], options?: { safe: any; }, callback?: (err: Error, result: any) => void): void; - - find(callback?: (err: Error, result: Cursor) => void): Cursor; - find(selector: Object, callback?: (err: Error, result: Cursor) => void): Cursor; - find(selector: Object, fields: any, callback?: (err: Error, result: Cursor) => void): Cursor; - find(selector: Object, options: CollectionFindOptions, callback?: (err: Error, result: Cursor) => void): Cursor; - find(selector: Object, fields: any, options: CollectionFindOptions, callback?: (err: Error, result: Cursor) => void): Cursor; - find(selector: Object, fields: any, skip: number, limit: number, callback?: (err: Error, result: Cursor) => void): Cursor; - find(selector: Object, fields: any, skip: number, limit: number, timeout: number, callback?: (err: Error, result: Cursor) => void): Cursor; - - findOne(callback?: (err: Error, result: any) => void): Cursor; - findOne(selector: Object, callback?: (err: Error, result: any) => void): Cursor; - findOne(selector: Object, fields: any, callback?: (err: Error, result: any) => void): Cursor; - findOne(selector: Object, options: CollectionFindOptions, callback?: (err: Error, result: any) => void): Cursor; - findOne(selector: Object, fields: any, options: CollectionFindOptions, callback?: (err: Error, result: any) => void): Cursor; - findOne(selector: Object, fields: any, skip: number, limit: number, callback?: (err: Error, result: any) => void): Cursor; - findOne(selector: Object, fields: any, skip: number, limit: number, timeout: number, callback?: (err: Error, result: any) => void): Cursor; - - createIndex(fieldOrSpec: any, callback: (err: Error, indexName: string) => void): void; - createIndex(fieldOrSpec: any, options: IndexOptions, callback: (err: Error, indexName: string) => void): void; - - ensureIndex(fieldOrSpec: any, callback: (err: Error, indexName: string) => void): void; - ensureIndex(fieldOrSpec: any, options: IndexOptions, callback: (err: Error, indexName: string) => void): void; - - indexInformation(options: any, callback: Function): void; - dropIndex(name: string, callback: Function): void; - dropAllIndexes(callback: Function): void; - // dropIndexes = dropAllIndexes - - reIndex(callback: Function): void; - mapReduce(map: Function, reduce: Function, options: MapReduceOptions, callback: Function): void; - group(keys: Object, condition: Object, initial: Object, reduce: Function, finalize: Function, command: boolean, options: {readPreference: string}, callback: Function): void; - options(callback: Function): void; - isCapped(callback: Function): void; - indexExists(indexes: string, callback: Function): void; - geoNear(x: number, y: number, callback: Function): void; - geoNear(x: number, y: number, options: Object, callback: Function): void; - geoHaystackSearch(x: number, y: number, callback: Function): void; - geoHaystackSearch(x: number, y: number, options: Object, callback: Function): void; - indexes(callback: Function): void; - aggregate(pipeline: any[], callback: (err: Error, results: any) => void): void; - aggregate(pipeline: any[], options: {readPreference: string}, callback: (err: Error, results: any) => void): void; - stats(options: {readPreference: string; scale: number}, callback: Function): void; - stats(callback: (err: Error, results: any) => void): void; - - hint: any; - } - - export interface MapReduceOptions { - out?: Object; - query?: Object; - sort?: Object; - limit?: number; - keeptemp?: boolean; - finalize?: any; - scope?: Object; - jsMode?: boolean; - verbose?: boolean; - readPreference?: string; - } - - export interface IndexOptions { - w?: any; - wtimeout?: number; - fsync?: boolean; - journal?: boolean; - unique?: boolean; - sparse?: boolean; - background?: boolean; - dropDups?: boolean; - min?: number; - max?: number; - v?: number; - expireAfterSeconds?: number; - name?: string; - } - - // Class documentation : http://mongodb.github.io/node-mongodb-native/api-generated/cursor.html - // Last update: doc. version 1.3.13 (29.08.2013) - export class Cursor { - // INTERNAL TYPE - // constructor (db: Db, collection: Collection, selector, fields, skip, limit, sort, hint, explain, snapshot, timeout, tailable, batchSize, slaveOk, raw, read, returnKey, maxScan, min, max, showDiskLoc, comment, awaitdata, numberOfRetries, dbName, tailableRetryInterval, exhaust, partial); - // constructor(db: Db, collection: Collection, selector, fields, options); - - rewind() : Cursor; - toArray(callback: (err: Error, results: any[]) => any) : void; - each(callback: (err: Error, item: any) => void) : void; - count(applySkipLimit: boolean, callback: (err: Error, count: number) => void) : void; - - sort(keyOrList: any, callback? : (err: Error, result: any) => void): Cursor; - - // this determines how the results are sorted. "asc", "ascending" or 1 for asceding order while "desc", "desceding or -1 for descending order. Note that the strings are case insensitive. - sort(keyOrList: String, direction : string, callback : (err: Error, result: any) => void): Cursor; - limit(limit: number, callback?: (err: Error, result: any) => void): Cursor; - setReadPreference(preference: string, callback?: Function): Cursor; - skip(skip: number, callback?: (err: Error, result: any) => void): Cursor; - batchSize(batchSize: number, callback?: (err: Error, result: any) => void): Cursor; - - nextObject(callback: (err: Error, doc: any) => void) : void; - explain(callback: (err: Error, result: any) => void) : void; - - stream(): CursorStream; - - close(callback: (err: Error, result: any) => void) : void; - isClosed(): boolean; - - public static INIT: number; - public static OPEN: number; - public static CLOSED: number; - public static GET_MORE: number; - } - - // Class documentation : http://mongodb.github.io/node-mongodb-native/api-generated/cursorstream.html - // Last update: doc. version 1.3.13 (29.08.2013) - export class CursorStream { - constructor(cursor: Cursor); - - public pause(): any; - public resume(): any; - public destroy(): any; - } - - export interface CollectionFindOptions { - limit?: number; - sort?: any; - fields?: Object; - skip?: number; - hint?: Object; - explain?: boolean; - snapshot?: boolean; - timeout?: boolean; - tailtable?: boolean; - tailableRetryInterval?: number; - numberOfRetries?: number; - awaitdata?: boolean; - oplogReplay?: boolean; - exhaust?: boolean; - batchSize?: number; - returnKey?: boolean; - maxScan?: number; - min?: number; - max?: number; - showDiskLoc?: boolean; - comment?: String; - raw?: boolean; - readPreference?: String; - partial?: boolean; - } - - export interface MongoCollectionOptions { - safe?: any; - serializeFunctions?: any; - raw?: boolean; - pkFactory?: any; - readPreference?: string; - } -} diff --git a/imageboard/views/board.jade b/imageboard/views/board.jade index 7f87dc8..75e406d 100644 --- a/imageboard/views/board.jade +++ b/imageboard/views/board.jade @@ -1,26 +1,26 @@ -extends layout - -block mainContent - h1 #{board.title} by - a(href= "/user/"+username)!= username - div.board - h4.description= board.description - #board.images - - each image in images - div.image.grid_3 - div.imagebox - div - a(href= "/image/"+image._id.toString()) - img.small(src= image.imageUri) - =image.caption - div.primarysource - a(href= image.link)!= /http:\/\/([^\/]*)\//.exec(image.link)[1] - div.commentbox - - each comment in image.comments - div.comment - a(href= "/user/"+comment.user) - b= comment.user -   #{comment.text} - .grid_12 - br +extends layout + +block mainContent + h1 #{board.title} by + a(href= "/user/"+username)!= username + div.board + h4.description= board.description + #board.images + - each image in images + div.image.grid_3 + div.imagebox + div + a(href= "/image/"+image._id.toString()) + img.small(src= image.imageUri) + =image.caption + div.primarysource + a(href= image.link)!= /http:\/\/([^\/]*)\//.exec(image.link)[1] + div.commentbox + - each comment in image.comments + div.comment + a(href= "/user/"+comment.user) + b= comment.user +   #{comment.text} + .grid_12 + br a(href= "/user/"+username+"/"+board.title+"/newpin") Add a new pin... \ No newline at end of file diff --git a/imageboard/views/image.jade b/imageboard/views/image.jade index a723327..5d80ec0 100644 --- a/imageboard/views/image.jade +++ b/imageboard/views/image.jade @@ -1,15 +1,15 @@ -extends layout - -block mainContent - h1 Posted by #{image.user} - div.image.grid_9 - div.imagebox - div - img.large(src= image.imageUri) - =image.caption - div.commentbox - - each comment in image.comments - div.comment - a(href= "/user/"+comment.user) - b= comment.user +extends layout + +block mainContent + h1 Posted by #{image.user} + div.image.grid_9 + div.imagebox + div + img.large(src= image.imageUri) + =image.caption + div.commentbox + - each comment in image.comments + div.comment + a(href= "/user/"+comment.user) + b= comment.user   #{comment.text} \ No newline at end of file diff --git a/imageboard/views/index.jade b/imageboard/views/index.jade index c35ef0a..2831781 100644 --- a/imageboard/views/index.jade +++ b/imageboard/views/index.jade @@ -1,11 +1,11 @@ -extends layout - -block mainContent - h1= title - p Welcome to #{title} - - ul - - each user in users - li - a(href= "/user/"+user._id) +extends layout + +block mainContent + h1= title + p Welcome to #{title} + + ul + - each user in users + li + a(href= "/user/"+user._id) b= user._id \ No newline at end of file diff --git a/imageboard/views/layout.jade b/imageboard/views/layout.jade index e29305d..c2224eb 100644 --- a/imageboard/views/layout.jade +++ b/imageboard/views/layout.jade @@ -1,14 +1,13 @@ -doctype html -html - head - title ImageBoard - link(rel='stylesheet', href='http://cachedcommons.org/cache/960/0.0.0/stylesheets/960.css') - link(rel='stylesheet', href='/stylesheets/style.css') - body - #header.container_12 - #fb-root - script(src='http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.min.js') - script(src='http://connect.facebook.net/en_US/all.js') - script(src='/javascripts/fb.js') - #container.container_12!= body - block mainContent +doctype html +html + head + title ImageBoard + link(rel='stylesheet', href='/stylesheets/style.css') + body + #header.container_12 + #fb-root + script(src='http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.min.js') + script(src='http://connect.facebook.net/en_US/all.js') + script(src='/javascripts/fb.js') + #container.container_12!= body + block mainContent diff --git a/imageboard/views/newboard.jade b/imageboard/views/newboard.jade index 505b3df..12865e8 100644 --- a/imageboard/views/newboard.jade +++ b/imageboard/views/newboard.jade @@ -1,18 +1,18 @@ -extends layout - -block mainContent - h1 Create a new board for - a(href= "/user/"+username)!= username - form( method="post") - div - br - div - span.inputtitle Title : - input(type="text", name="title", id="editArticleTitle") - br - div - span.inputtitle Description : - textarea( name="description", rows=10, cols=16, id="editArticleBody") - br - #editArticleSubmit +extends layout + +block mainContent + h1 Create a new board for + a(href= "/user/"+username)!= username + form( method="post") + div + br + div + span.inputtitle Title : + input(type="text", name="title", id="editArticleTitle") + br + div + span.inputtitle Description : + textarea( name="description", rows=10, cols=16, id="editArticleBody") + br + #editArticleSubmit input.button(type="submit", value="Save board") \ No newline at end of file diff --git a/imageboard/views/newpin.jade b/imageboard/views/newpin.jade index 607d062..5577345 100644 --- a/imageboard/views/newpin.jade +++ b/imageboard/views/newpin.jade @@ -1,24 +1,24 @@ -extends layout - -block mainContent - h1 Pin new image to - a(href= "/user/"+username)!= username - 's board - a(href= "/user/"+username+"/"+boardid)!= boardid - form( method="post") - div - br - div - span.inputtitle Image url: - input(type="text", name="imageUri") - br - div - span.inputtitle Link : - input(type="text", name="link") - br - div - span.inputtitle Caption : - textarea( name="caption", rows=10, cols=16) - br - #editArticleSubmit +extends layout + +block mainContent + h1 Pin new image to + a(href= "/user/"+username)!= username + 's board + a(href= "/user/"+username+"/"+boardid)!= boardid + form( method="post") + div + br + div + span.inputtitle Image url: + input(type="text", name="imageUri") + br + div + span.inputtitle Link : + input(type="text", name="link") + br + div + span.inputtitle Caption : + textarea( name="caption", rows=10, cols=16) + br + #editArticleSubmit input.button(type="submit", value="Save pin") \ No newline at end of file diff --git a/imageboard/views/user.jade b/imageboard/views/user.jade index 5cecafb..a3b67cf 100644 --- a/imageboard/views/user.jade +++ b/imageboard/views/user.jade @@ -1,13 +1,13 @@ -extends layout - -block mainContent - h1 #{username}'s ImageBoard - #boards - - each board in boards - div.board - br - div.title - a(href= "/user/"+username+"/"+board.title)!= board.title - div.description= board.description - br +extends layout + +block mainContent + h1 #{username}'s ImageBoard + #boards + - each board in boards + div.board + br + div.title + a(href= "/user/"+username+"/"+board.title)!= board.title + div.description= board.description + br a(href= "/user/"+username+"/newboard") Add a new board... \ No newline at end of file diff --git a/interfaces/interfaces.ts b/interfaces/interfaces.ts index f18e601..6d73684 100644 --- a/interfaces/interfaces.ts +++ b/interfaces/interfaces.ts @@ -1,52 +1,52 @@ -interface Drivable { - - // Starts the car's ignition so that it can drive. - start(): void; - // Attempt to drive a distance. Returns true or false based on whether or not the drive was successful. - drive(distance: number): boolean; - // Give the distance from the start. - getPosition(): number; -} - -class Car implements Drivable { - private _isRunning: boolean; - private _distanceFromStart: number; - - constructor() { - this._isRunning = false; - this._distanceFromStart = 0; - } - - /** - * Starts the car's ignition so that it can drive. - */ - public start() { - this._isRunning = true; - } - - /** - * Attempt to drive a distance. Returns true or false based on whether or not the drive was successful. - * - * @param {number} distance The distance attempting to cover - * - * @returns {boolean} Whether or not the drive was successful - */ - public drive(distance: number): boolean { - if (this._isRunning) { - this._distanceFromStart += distance; - return true; - } - return false; - } - - /** - * Gives the distance from starting position - * - * @returns {number} Distance from starting position; - */ - public getPosition(): number { - return this._distanceFromStart; - } -} - +interface Drivable { + + // Starts the car's ignition so that it can drive. + start(): void; + // Attempt to drive a distance. Returns true or false based on whether or not the drive was successful. + drive(distance: number): boolean; + // Give the distance from the start. + getPosition(): number; +} + +class Car implements Drivable { + private _isRunning: boolean; + private _distanceFromStart: number; + + constructor() { + this._isRunning = false; + this._distanceFromStart = 0; + } + + /** + * Starts the car's ignition so that it can drive. + */ + public start() { + this._isRunning = true; + } + + /** + * Attempt to drive a distance. Returns true or false based on whether or not the drive was successful. + * + * @param {number} distance The distance attempting to cover + * + * @returns {boolean} Whether or not the drive was successful + */ + public drive(distance: number): boolean { + if (this._isRunning) { + this._distanceFromStart += distance; + return true; + } + return false; + } + + /** + * Gives the distance from starting position + * + * @returns {number} Distance from starting position; + */ + public getPosition(): number { + return this._distanceFromStart; + } +} + // Want to experiment? Try adding a second interface: Flyable. Implement it in a Helicopter class, then write a FlyingCar class that implements both Drivable and Flyable! \ No newline at end of file diff --git a/interfaces/tsconfig.json b/interfaces/tsconfig.json new file mode 100644 index 0000000..8036243 --- /dev/null +++ b/interfaces/tsconfig.json @@ -0,0 +1,5 @@ +{ + "compilerOptions": { + "sourceMap": true + } +} \ No newline at end of file diff --git a/jquery/README.md b/jquery/README.md index 6739dba..2ffaefc 100644 --- a/jquery/README.md +++ b/jquery/README.md @@ -10,6 +10,7 @@ For best results, scroll the window using the scrollbar. ## Running ``` -tsc --sourcemap --target ES5 parallax.ts -start parallax.html +npm install +tsc +open parallax.html ``` diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts deleted file mode 100644 index f9e09f4..0000000 --- a/jquery/jquery.d.ts +++ /dev/null @@ -1,703 +0,0 @@ -/* ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -// Typing for the jQuery library, version 1.10 - -/* - Interface for the AJAX setting that will configure the AJAX request -*/ -interface JQueryAjaxSettings { - accepts?: any; - async?: boolean; - beforeSend? (jqXHR: JQueryXHR, settings: JQueryAjaxSettings): any; - cache?: boolean; - complete? (jqXHR: JQueryXHR, textStatus: string): any; - contents?: { [key: string]: any; }; - contentType?: any; - context?: any; - converters?: { [key: string]: any; }; - crossDomain?: boolean; - data?: any; - dataFilter? (data: any, ty: any): any; - dataType?: string; - error? (jqXHR: JQueryXHR, textStatus: string, errorThrow: string): any; - global?: boolean; - headers?: { [key: string]: any; }; - ifModified?: boolean; - isLocal?: boolean; - jsonp?: string; - jsonpCallback?: any; - mimeType?: string; - password?: string; - processData?: boolean; - scriptCharset?: string; - statusCode?: { [key: string]: any; }; - success? (data: any, textStatus: string, jqXHR: JQueryXHR): any; - timeout?: number; - traditional?: boolean; - type?: string; - url?: string; - username?: string; - xhr?: any; - xhrFields?: { [key: string]: any; }; -} - -/* - Interface for the jqXHR object -*/ -interface JQueryXHR extends XMLHttpRequest { - overrideMimeType(): any; -} - -/* - Interface for the JQuery callback -*/ -interface JQueryCallback { - add(...callbacks: any[]): any; - disable(): any; - empty(): any; - fire(...arguments: any[]): any; - fired(): boolean; - fireWith(context: any, ...args: any[]): any; - has(callback: any): boolean; - lock(): any; - locked(): boolean; - removed(...callbacks: any[]): any; -} - -/* - Interface for the JQuery promise, part of callbacks -*/ -interface JQueryPromise { - always(...alwaysCallbacks: any[]): JQueryDeferred; - done(...doneCallbacks: any[]): JQueryDeferred; - fail(...failCallbacks: any[]): JQueryDeferred; - pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; - then(doneCallbacks: any, failCallbacks: any, progressCallbacks?: any): JQueryDeferred; -} - -/* - Interface for the JQuery deferred, part of callbacks -*/ -interface JQueryDeferred extends JQueryPromise { - notify(...args: any[]): JQueryDeferred; - notifyWith(context: any, ...args: any[]): JQueryDeferred; - - progress(...progressCallbacks: any[]): JQueryDeferred; - reject(...args: any[]): JQueryDeferred; - rejectWith(context: any, ...args: any[]): JQueryDeferred; - resolve(...args: any[]): JQueryDeferred; - resolveWith(context: any, ...args: any[]): JQueryDeferred; - state(): string; - then(doneCallbacks: any, failCallbacks?: any, progressCallbacks?: any): JQueryDeferred; -} - -/* - Interface of the JQuery extension of the W3C event object -*/ -interface JQueryEventObject extends Event { - data: any; - delegateTarget: Element; - isDefaultPrevented(): boolean; - isImmediatePropogationStopped(): boolean; - isPropogationStopped(): boolean; - namespace: string; - preventDefault(): any; - relatedTarget: Element; - result: any; - stopImmediatePropagation(): void; - stopPropagation(): void; - pageX: number; - pageY: number; - which: number; - metaKey: any; -} - -/* - Collection of properties of the current browser -*/ -interface JQueryBrowserInfo { - safari: boolean; - opera: boolean; - msie: boolean; - mozilla: boolean; - version: string; -} - -interface JQuerySupport { - ajax?: boolean; - boxModel?: boolean; - changeBubbles?: boolean; - checkClone?: boolean; - checkOn?: boolean; - cors?: boolean; - cssFloat?: boolean; - hrefNormalized?: boolean; - htmlSerialize?: boolean; - leadingWhitespace?: boolean; - noCloneChecked?: boolean; - noCloneEvent?: boolean; - opacity?: boolean; - optDisabled?: boolean; - optSelected?: boolean; - scriptEval? (): boolean; - style?: boolean; - submitBubbles?: boolean; - tbody?: boolean; -} - -interface JQueryTransport { - send(headers: { [index: string]: string; }, completeCallback: (status: number, statusText: string, responses: { [dataType: string]: any; }, headers: string) => void): void; - abort(): void; -} - -/* - Static members of jQuery (those on $ and jQuery themselves) -*/ -interface JQueryStatic { - - // AJAX - ajax(settings: JQueryAjaxSettings): JQueryXHR; - ajax(url: string, settings: JQueryAjaxSettings): JQueryXHR; - - ajaxPrefilter(handler: (opts: any, originalOpts: any, jqXHR: JQueryXHR) => any): any; - ajaxPrefilter(dataTypes: string, handler: (opts: any, originalOpts: any, jqXHR: JQueryXHR) => any): any; - - ajaxSetup(options: any): void; - ajaxTransport(dataType: string, handler: (options: JQueryAjaxSettings, originalOptions: JQueryAjaxSettings, jqXHR: JQueryXHR) => JQueryTransport): void; - - get(url: string, data?: any, success?: any, dataType?: any): JQueryXHR; - getJSON(url: string, data?: any, success?: any): JQueryXHR; - getScript(url: string, success?: any): JQueryXHR; - - param(obj: any): string; - param(obj: any, traditional: boolean): string; - - post(url: string, data?: any, success?: any, dataType?: any): JQueryXHR; - - // Callbacks - Callbacks(flags: any): JQueryCallback; - - // Core - holdReady(hold: boolean): any; - - (): JQuery; - (selector: string, context?: any): JQuery; - (element: Element): JQuery; - (elementArray: Element[]): JQuery; - (object: JQuery): JQuery; - (func: Function): JQuery; - (object: {}): JQuery; - - noConflict(removeAll?: boolean): Object; - - when(...deferreds: any[]): JQueryPromise; - - // CSS - css(e: any, propertyName: string, value?: any): any; - css(e: any, propertyName: any, value?: any): any; - cssHooks: { [key: string]: any; }; - - // Data - data(element: Element, key: string, value: any): Object; - - dequeue(element: Element, queueName?: string): any; - - hasData(element: Element): boolean; - - queue(element: Element, queueName?: string): any[]; - queue(element: Element, queueName: string, newQueueOrCallback: any): JQuery; - - removeData(element: Element, name?: string): JQuery; - - // Deferred - Deferred(beforeStart?: (deferred: JQueryDeferred) => any): JQueryDeferred; - - // Effects - fx: { tick: () => void; interval: number; stop: () => void; speeds: { slow: number; fast: number; }; off: boolean; step: any; }; - - // Events - proxy(func: Function, context: any): any; - proxy(context: any, name: string): any; - - // Internals - error(message: any): void; - - // Miscellaneous - expr: any; - fn: any; //TODO: Decide how we want to type this - isReady: boolean; - - // Properties - browser: JQueryBrowserInfo; - support: JQuerySupport; - - // Utilities - contains(container: Element, contained: Element): boolean; - - each(collection: any, callback: (indexInArray: any, valueOfElement: any) => any): any; - - extend(deep: boolean, target: any, ...objs: any[]): Object; - extend(target: any, ...objs: any[]): Object; - - globalEval(code: string): any; - - grep(array: any[], func: any, invert: boolean): any[]; - - inArray(value: any, array: any[], fromIndex?: number): number; - - isArray(obj: any): boolean; - isEmptyObject(obj: any): boolean; - isFunction(obj: any): boolean; - isNumeric(value: any): boolean; - isPlainObject(obj: any): boolean; - isWindow(obj: any): boolean; - isXMLDoc(node: Node): boolean; - - makeArray(obj: any): any[]; - - map(array: any[], callback: (elementOfArray: any, indexInArray: any) => any): any[]; - - merge(first: any[], second: any[]): any[]; - - noop(): any; - - now(): number; - - parseHTML(data: string, context?: Element, keepScripts?: boolean): any[]; - parseJSON(json: string): any; - - //FIXME: This should return an XMLDocument - parseXML(data: string): any; - - queue(element: Element, queueName: string, newQueue: any[]): JQuery; - - trim(str: string): string; - - type(obj: any): string; - - unique(arr: any[]): any[]; -} - -/* - The jQuery instance members -*/ -interface JQuery { - // AJAX - ajaxComplete(handler: any): JQuery; - ajaxError(handler: (evt: any, xhr: any, opts: any) => any): JQuery; - ajaxSend(handler: (evt: any, xhr: any, opts: any) => any): JQuery; - ajaxStart(handler: () => any): JQuery; - ajaxStop(handler: () => any): JQuery; - ajaxSuccess(handler: (evt: any, xml: any, opts: any) => any): JQuery; - - serialize(): string; - serializeArray(): any[]; - - // Attributes - addClass(classNames: string): JQuery; - addClass(func: (index: any, currentClass: any) => JQuery): JQuery; - - attr(attributeName: string): string; - attr(attributeName: string, func: (index: any, attr: any) => any): JQuery; - attr(attributeName: string, value: any): JQuery; - attr(map: { [key: string]: any; }): JQuery; - - hasClass(className: string): boolean; - - html(): string; - html(htmlString: string): JQuery; - - prop(propertyName: string): any; - prop(propertyName: string, func: (index: any, oldPropertyValue: any) => any): JQuery; - prop(propertyName: string, value: any): JQuery; - prop(map: any): JQuery; - - removeAttr(attributeName: any): JQuery; - - removeClass(func: (index: any, cls: any) => any): JQuery; - removeClass(className?: string): JQuery; - - removeProp(propertyName: any): JQuery; - - toggleClass(func: (index: any, cls: any, swtch: any) => any): JQuery; - toggleClass(swtch?: boolean): JQuery; - toggleClass(className: any, swtch?: boolean): JQuery; - - val(): any; - val(value: string[]): JQuery; - val(value: string): JQuery; - val(func: (index: any, value: any) => any): JQuery; - - // CSS - css(propertyNames: any[]): string; - css(propertyName: string): string; - css(propertyName: string, value: any): JQuery; - css(propertyName: any, value?: any): JQuery; - - height(): number; - height(value: number): JQuery; - height(func: (index: any, height: any) => any): JQuery; - - innerHeight(): number; - innerWidth(): number; - - offset(): { top: number; left: number; }; - offset(func: (index: any, coords: any) => any): JQuery; - offset(coordinates: any): JQuery; - - outerHeight(includeMargin?: boolean): number; - outerWidth(includeMargin?: boolean): number; - - position(): { top: number; left: number; }; - - scrollLeft(): number; - scrollLeft(value: number): JQuery; - - scrollTop(): number; - scrollTop(value: number): JQuery; - - width(): number; - width(value: number): JQuery; - width(func: (index: any, height: any) => any): JQuery; - - // Data - clearQueue(queueName?: string): JQuery; - - data(key: string, value: any): JQuery; - data(obj: { [key: string]: any; }): JQuery; - data(key?: string): any; - - dequeue(queueName?: string): JQuery; - - queue(queueName?: string): any[]; - queue(queueName: string, newQueueOrCallback: any): JQuery; - queue(newQueueOrCallback: any): JQuery; - - removeData(nameOrList?: any): JQuery; - - // Deferred - promise(type?: any, target?: any): JQueryPromise; - - // Effects - animate(properties: any, options: { duration?: any; easing?: string; complete?: Function; step?: Function; queue?: boolean; specialEasing?: any; }): JQuery; - animate(properties: any, duration?: any, easing?: "linear", complete?: Function): JQuery; - animate(properties: any, duration?: any, easing?: "swing", complete?: Function): JQuery; - animate(properties: any, duration?: any, easing?: string, complete?: Function): JQuery; - - delay(duration: number, queueName?: string): JQuery; - - fadeIn(duration?: any, easing?: "linear", complete?: Function): JQuery; - fadeIn(duration?: any, easing?: "swing", complete?: Function): JQuery; - fadeIn(duration?: any, easing?: string, complete?: Function): JQuery; - fadeIn(duration?: any, complete?: Function): JQuery; - - - fadeOut(duration?: any, easing?: "linear", complete?: Function): JQuery; - fadeOut(duration?: any, easing?: "swing", complete?: Function): JQuery; - fadeOut(duration?: any, easing?: string, complete?: Function): JQuery; - fadeOut(duration?: any, complete?: any): JQuery; - - fadeTo(duration: any, opacity: number, easing?: "linear", complete?: Function): JQuery; - fadeTo(duration: any, opacity: number, easing?: "swing", complete?: Function): JQuery; - fadeTo(duration: any, opacity: number, easing?: string, complete?: Function): JQuery; - fadeTo(duration: any, opacity: number, complete?: Function): JQuery; - - fadeToggle(duration?: any, easing?: "linear", complete?: Function): JQuery; - fadeToggle(duration?: any, easing?: "swing", complete?: Function): JQuery; - fadeToggle(duration?: any, easing?: string, complete?: Function): JQuery; - - finish(queue?: string): JQuery; - - hide(duration?: any, easing?: "linear", callback?: Function): JQuery; - hide(duration?: any, easing?: "swing", callback?: Function): JQuery; - hide(duration?: any, easing?: string, callback?: Function): JQuery; - hide(duration?: any, callback?: Function): JQuery; - - show(duration?: any, easing?: "linear", complete?: Function): JQuery; - show(duration?: any, easing?: "swing", complete?: Function): JQuery; - show(duration?: any, easing?: string, complete?: Function): JQuery; - show(duration?: any, complete?: Function): JQuery; - - slideDown(duration?: any, easing?: "linear", complete?: Function): JQuery; - slideDown(duration?: any, easing?: "swing", complete?: Function): JQuery; - slideDown(duration?: any, easing?: string, complete?: Function): JQuery; - slideDown(duration?: any, complete?: Function): JQuery; - - slideToggle(duration?: any, easing?: "linear", complete?: Function): JQuery; - slideToggle(duration?: any, easing?: "swing", complete?: Function): JQuery; - slideToggle(duration?: any, easing?: string, complete?: Function): JQuery; - slideToggle(duration?: any, complete?: Function): JQuery; - - slideUp(duration?: any, easing?: "linear", complete?: Function): JQuery; - slideUp(duration?: any, easing?: "swing", complete?: Function): JQuery; - slideUp(duration?: any, easing?: string, complete?: Function): JQuery; - slideUp(duration?: any, complete?: Function): JQuery; - - stop(clearQueue?: boolean, jumpToEnd?: boolean): JQuery; - stop(queue?: any, clearQueue?: boolean, jumpToEnd?: boolean): JQuery; - - toggle(showOrHide: boolean): JQuery; - toggle(duration?: any, easing?: "linear", complete?: Function): JQuery; - toggle(duration?: any, easing?: "swing", complete?: Function): JQuery; - toggle(duration?: any, easing?: string, complete?: Function): JQuery; - toggle(duration?: any, complete?: Function): JQuery; - - // Events - bind(eventType: string, preventBubble: boolean): JQuery; - bind(eventType: string, eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - bind(eventType: string, eventData: any, preventBubble: boolean): JQuery; - bind(...events: any[]): JQuery; - - blur(handler: (eventObject: JQueryEventObject) => any): JQuery; - blur(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - change(handler: (eventObject: JQueryEventObject) => any): JQuery; - change(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - click(handler: (eventObject: JQueryEventObject) => any): JQuery; - click(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - dblclick(handler: (eventObject: JQueryEventObject) => any): JQuery; - dblclick(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - delegate(selector: any, eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; - - focus(handler: (eventObject: JQueryEventObject) => any): JQuery; - focus(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - focusin(handler: (eventObject: JQueryEventObject) => any): JQuery; - focusin(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - focusout(handler: (eventObject: JQueryEventObject) => any): JQuery; - focusout(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - hover(handlerIn: (eventObject: JQueryEventObject) => any, handlerOut: (eventObject: JQueryEventObject) => any): JQuery; - hover(handlerInOut: (eventObject: JQueryEventObject) => any): JQuery; - - keydown(handler: (eventObject: JQueryEventObject) => any): JQuery; - keydown(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - keypress(handler: (eventObject: JQueryEventObject) => any): JQuery; - keypress(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - keyup(handler: (eventObject: JQueryEventObject) => any): JQuery; - keyup(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - mousedown(handler: (eventObject: JQueryEventObject) => any): JQuery; - mousedown(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - mouseevent(handler: (eventObject: JQueryEventObject) => any): JQuery; - mouseevent(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - mouseenter(handler: (eventObject: JQueryEventObject) => any): JQuery; - mouseenter(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - mouseleave(handler: (eventObject: JQueryEventObject) => any): JQuery; - mouseleave(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - mousemove(handler: (eventObject: JQueryEventObject) => any): JQuery; - mousemove(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - mouseout(handler: (eventObject: JQueryEventObject) => any): JQuery; - mouseout(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - mouseover(handler: (eventObject: JQueryEventObject) => any): JQuery; - mouseover(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - mouseup(handler: (eventObject: JQueryEventObject) => any): JQuery; - mouseup(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - off(events?: string, selector?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - off(eventsMap: { [key: string]: any; }, selector?: any): JQuery; - - on(events: string, selector?: any, data?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - on(eventsMap: { [key: string]: any; }, selector?: any, data?: any): JQuery; - - one(events: string, selector?: any, data?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - one(eventsMap: { [key: string]: any; }, selector?: any, data?: any): JQuery; - - ready(handler: any): JQuery; - - resize(handler: (eventObject: JQueryEventObject) => any): JQuery; - resize(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - scroll(handler: (eventObject: JQueryEventObject) => any): JQuery; - scroll(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - select(handler: (eventObject: JQueryEventObject) => any): JQuery; - select(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - submit(handler: (eventObject: JQueryEventObject) => any): JQuery; - submit(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - trigger(eventType: string, ...extraParameters: any[]): JQuery; - trigger(event: JQueryEventObject): JQuery; - - triggerHandler(eventType: string, ...extraParameters: any[]): Object; - - unbind(eventType?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - unbind(eventType: string, fls: boolean): JQuery; - unbind(evt: any): JQuery; - - undelegate(): JQuery; - undelegate(selector: any, eventType: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - undelegate(selector: any, events: any): JQuery; - undelegate(namespace: string): JQuery; - - // Internals - context: Element; - jquery: string; - pushStack(elements: any[]): JQuery; - pushStack(elements: any[], name: any, arguments: any): JQuery; - - // Manipulation - after(func: (index: any) => any): JQuery; - after(...content: any[]): JQuery; - - append(func: (index: any, html: any) => any): JQuery; - append(...content: any[]): JQuery; - - appendTo(target: any): JQuery; - - before(func: (index: any) => any): JQuery; - before(...content: any[]): JQuery; - - clone(withDataAndEvents?: boolean, deepWithDataAndEvents?: boolean): JQuery; - - detach(selector?: any): JQuery; - - empty(): JQuery; - - insertAfter(target: any): JQuery; - insertBefore(target: any): JQuery; - - prepend(func: (index: any, html: any) => any): JQuery; - prepend(...content: any[]): JQuery; - - prependTo(target: any): JQuery; - - remove(selector?: any): JQuery; - - replaceAll(target: any): JQuery; - - replaceWith(func: any): JQuery; - - text(textString: string): JQuery; - text(): string; - - toArray(): any[]; - - unwrap(): JQuery; - - wrap(func: (index: any) => any): JQuery; - wrap(wrappingElement: any): JQuery; - - wrapAll(wrappingElement: any): JQuery; - - wrapInner(func: (index: any) => any): JQuery; - wrapInner(wrappingElement: any): JQuery; - - // Miscellaneous - each(func: (index: any, elem: Element) => any): JQuery; - - get(index?: number): any; - - index(selectorOrElement?: any): number; - - // Properties - length: number; - [x: number]: HTMLElement; - - // Traversing - add(selector: string, context?: any): JQuery; - add(html: string): JQuery; - add(obj: JQuery): JQuery; - add(...elements: any[]): JQuery; - - addBack(selector?: any): JQuery; - - children(selector?: any): JQuery; - - closest(selector: string): JQuery; - closest(selector: string, context?: Element): JQuery; - closest(obj: JQuery): JQuery; - closest(element: any): JQuery; - closest(selectors: any, context?: Element): any[]; - - contents(): JQuery; - - end(): JQuery; - - eq(index: number): JQuery; - - filter(selector: string): JQuery; - filter(func: (index: any) => any): JQuery; - filter(obj: JQuery): JQuery; - filter(element: any): JQuery; - - find(selector: string): JQuery; - find(element: any): JQuery; - find(obj: JQuery): JQuery; - - first(): JQuery; - - has(selector: string): JQuery; - has(contained: Element): JQuery; - - is(selector: string): boolean; - is(func: (index: any) => any): boolean; - is(obj: JQuery): boolean; - is(element: any): boolean; - - last(): JQuery; - - map(callback: (index: any, domElement: Element) => any): JQuery; - - next(selector?: string): JQuery; - - nextAll(selector?: string): JQuery; - - nextUntil(selector?: string, filter?: string): JQuery; - nextUntil(element?: Element, filter?: string): JQuery; - - not(selector: string): JQuery; - not(func: (index: any) => any): JQuery; - not(obj: JQuery): JQuery; - not(element: any): JQuery; - - offsetParent(): JQuery; - - parent(selector?: string): JQuery; - - parents(selector?: string): JQuery; - - parentsUntil(selector?: string, filter?: string): JQuery; - parentsUntil(element?: Element, filter?: string): JQuery; - - prev(selector?: string): JQuery; - - prevAll(selector?: string): JQuery; - - prevUntil(selector?: string, filter?: string): JQuery; - prevUntil(element?: Element, filter?: string): JQuery; - - siblings(selector?: string): JQuery; - - slice(start: number, end?: number): JQuery; -} - -declare var jQuery: JQueryStatic; -declare var $: JQueryStatic; diff --git a/jquery/package.json b/jquery/package.json new file mode 100644 index 0000000..8fe52aa --- /dev/null +++ b/jquery/package.json @@ -0,0 +1,18 @@ +{ + "name": "jquery", + "version": "1.0.0", + "description": "jQuery Typescript Demo", + "scripts":{ + "tsc": "tsc" + }, + "dependencies": { + "jquery": "^3.1.1" + }, + "devDependencies": { + "@types/jquery": "^2.0.40", + "typescript": "^2.1.6" + }, + "type": "git", + "url": "https://github.com/Microsoft/TypeScriptSamples.git", + "license": "MIT" +} \ No newline at end of file diff --git a/jquery/parallax.html b/jquery/parallax.html index 917c150..4f2c4c7 100644 --- a/jquery/parallax.html +++ b/jquery/parallax.html @@ -1,98 +1,91 @@ - - - - - - - -
-
-   -
-
-   -
-
-   -
-
-   -
-
-   -
-
- - - - - - + + + + + + + +
+
+   +
+
+   +
+
+   +
+
+   +
+
+   +
+
+ + + + + + \ No newline at end of file diff --git a/jquery/parallax.ts b/jquery/parallax.ts index 0ef3ac5..8d44af9 100644 --- a/jquery/parallax.ts +++ b/jquery/parallax.ts @@ -1,58 +1,56 @@ -/// - -module Parallax { - export class ParallaxContainer { - private content: HTMLElement; - private perspective: number; - private surface: ParallaxSurface[]; - - /** - * Creates a Container for a Parallax - * - * @param {HTMLElement} scrollableContent The container that will be parallaxed - * @param {perspective} perspective The ratio of how much back content should be scroleld relative to forward content. For example, if this value is 0.5, and there are 2 surfaces, - * the front-most surface would be scrolled normally, and the surface behind it would be scrolled half as much. - */ - constructor(scrollableContent: HTMLElement, - perspective: number) { - this.perspective = perspective; - this.surface = []; - this.content = scrollableContent; - - $(scrollableContent).scroll((event: JQueryEventObject) => { - this.onContainerScroll(event); - }); - } - - private onContainerScroll(e: JQueryEventObject): void { - var currentScrollPos = $(this.content).scrollTop(); - var currentParallax = 1; - for (var i = 0; i < this.surface.length; i++) { - var surface = this.surface[i]; - var offset = -(currentScrollPos * currentParallax); - surface.currentY = offset; - currentParallax *= this.perspective; - } - } - - addSurface(surface: ParallaxSurface): void { - this.surface.push(surface); - } - } - - export class ParallaxSurface { - private content: HTMLElement; - - constructor(surfaceContents: HTMLElement) { - this.content = surfaceContents; - } - - get currentY(): number { - return -$(this.content).css('margin-top'); - } - - set currentY(value: number) { - $(this.content).css({ marginTop: value }); - } - } -} +module Parallax { + export class ParallaxContainer { + private content: HTMLElement; + private perspective: number; + private surface: ParallaxSurface[]; + + /** + * Creates a Container for a Parallax + * + * @param {HTMLElement} scrollableContent The container that will be parallaxed + * @param {perspective} perspective The ratio of how much back content should be scrolled relative to forward content. For example, if this value is 0.5, and there are 2 surfaces, + * the front-most surface would be scrolled normally, and the surface behind it would be scrolled half as much. + */ + constructor(scrollableContent: HTMLElement, + perspective: number) { + this.perspective = perspective; + this.surface = []; + this.content = scrollableContent; + + $(scrollableContent).scroll((event: JQueryEventObject) => { + this.onContainerScroll(event); + }); + } + + private onContainerScroll(e: JQueryEventObject): void { + var currentScrollPos = $(this.content).scrollTop(); + var currentParallax = 1; + for (var i = 0; i < this.surface.length; i++) { + var surface = this.surface[i]; + var offset = -(currentScrollPos * currentParallax); + surface.currentY = offset; + currentParallax *= this.perspective; + } + } + + addSurface(surface: ParallaxSurface): void { + this.surface.push(surface); + } + } + + export class ParallaxSurface { + private content: HTMLElement; + + constructor(surfaceContents: HTMLElement) { + this.content = surfaceContents; + } + + get currentY(): number { + return -$(this.content).css('margin-top'); + } + + set currentY(value: number) { + $(this.content).css({ marginTop: value }); + } + } +} \ No newline at end of file diff --git a/jquery/tsconfig.json b/jquery/tsconfig.json new file mode 100644 index 0000000..7b0924e --- /dev/null +++ b/jquery/tsconfig.json @@ -0,0 +1,6 @@ +{ + "compilerOptions": { + "target": "es5", + "sourceMap": true + } +} \ No newline at end of file diff --git a/js-and-ts/README.md b/js-and-ts/README.md new file mode 100644 index 0000000..2b3ecfb --- /dev/null +++ b/js-and-ts/README.md @@ -0,0 +1,17 @@ +# TypeScript Sample: Mixing TypeScript and JavaScript + +## Overview + +A sample of how to use the `allowJS` option to use both JavaScript and TypeScript together. +A simple text formatter is provided, written in JavaScript. This formatter is then used +within a TypeScript class to format a computation. + +To run this sample, you must have `node` installed. You can also use `ts-node` to run this directly +without a compilation from TypeScript to JavaScript. + +## Running + +```bash +$ tsc robot.ts` +$ node robot.js` +``` \ No newline at end of file diff --git a/js-and-ts/format.js b/js-and-ts/format.js new file mode 100644 index 0000000..9b6ebd7 --- /dev/null +++ b/js-and-ts/format.js @@ -0,0 +1,13 @@ +const surroundWithStars = (value) => { + const valueLength = value.toString().length; + const topBottomBorder = '*'.repeat(valueLength + 2); + + return topBottomBorder + + "\n" + + '*' + value.toString() + '*' + + "\n" + + topBottomBorder; +} + +module.exports.Formatter = { surroundWithStars }; + diff --git a/js-and-ts/robot.ts b/js-and-ts/robot.ts new file mode 100644 index 0000000..0542c12 --- /dev/null +++ b/js-and-ts/robot.ts @@ -0,0 +1,46 @@ +// This import wouldn't be possible without the allowJS option in tsconfig +import { Formatter } from './format.js'; + +interface Robot { + name: String; + currentComputation: Number; +} + +class Robot { + constructor(public name: String) { + this.name = name; + this.currentComputation = 0; + } + + // Given a mathematical operation, return a value based on the value passed, + // the operation and the number 10 + compute(operation, value) { + let computedValue = 0; + switch(operation) { + case '+': + computedValue = value + 10; + break; + case '-': + computedValue = value - 10; + break; + case '/': + computedValue = value / 10; + break; + case '*': + computedValue = value * 10; + break; + default: + console.log("Does not compute!!") + } + this.currentComputation = computedValue; + } + + // Using an external JS module, format the computed value from our robot + displayCurrentComputation() { + console.log(Formatter.surroundWithStars(this.currentComputation)); + } +} + +const hal = new Robot('Hal'); +hal.compute('+', 32); +hal.displayCurrentComputation(); \ No newline at end of file diff --git a/js-and-ts/tsconfig.json b/js-and-ts/tsconfig.json new file mode 100644 index 0000000..2a9bebf --- /dev/null +++ b/js-and-ts/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "outDir": "./built", + "sourceMap": true, + "allowJs": true, + "target": "es6" + }, + "include": [ + "./**/*" + ] +} \ No newline at end of file diff --git a/jspm/.gitignore b/jspm/.gitignore new file mode 100644 index 0000000..494c0b5 --- /dev/null +++ b/jspm/.gitignore @@ -0,0 +1 @@ +jspm_packages \ No newline at end of file diff --git a/jspm/README.md b/jspm/README.md new file mode 100644 index 0000000..6f64daf --- /dev/null +++ b/jspm/README.md @@ -0,0 +1,16 @@ +**Setup jspm and install jspm dependencies** +``` +npm install -g jspm@beta +jspm install +jspm dl-loader --edge +``` + +**run:** +- install http-server package via + ``` + npm install -g http-server + ``` +- run server (if port 8080 it taken, pick any port that is free) + ``` + http-server -p 8080 + ``` diff --git a/jspm/index.html b/jspm/index.html new file mode 100644 index 0000000..83851d5 --- /dev/null +++ b/jspm/index.html @@ -0,0 +1,16 @@ + + + Jspm sample + + + + +
+ + + \ No newline at end of file diff --git a/jspm/jspm.config.js b/jspm/jspm.config.js new file mode 100644 index 0000000..3ceb73b --- /dev/null +++ b/jspm/jspm.config.js @@ -0,0 +1,271 @@ +SystemJS.config({ + transpiler: "plugin-typescript", + typescriptOptions: { + "tsconfig": true, + "typeCheck": true + }, + packages: { + "app": { + "main": "app.ts", + "defaultExtension": "ts" + } + }, + browserConfig: { + "baseURL": "/", + "paths": { + "app/": "src/", + "github:": "jspm_packages/github/", + "npm:": "jspm_packages/npm/" + } + }, + devConfig: { + "map": { + "plugin-typescript": "github:frankwallis/plugin-typescript@5.3.3", + "os": "npm:jspm-nodelibs-os@0.2.0", + "child_process": "npm:jspm-nodelibs-child_process@0.2.0", + "assert": "npm:jspm-nodelibs-assert@0.2.0", + "module": "npm:jspm-nodelibs-module@0.2.0", + "buffer": "npm:jspm-nodelibs-buffer@0.2.1", + "util": "npm:jspm-nodelibs-util@0.2.1", + "crypto": "npm:jspm-nodelibs-crypto@0.2.0", + "stream": "npm:jspm-nodelibs-stream@0.2.0", + "constants": "npm:jspm-nodelibs-constants@0.2.0", + "string_decoder": "npm:jspm-nodelibs-string_decoder@0.2.0", + "vm": "npm:jspm-nodelibs-vm@0.2.0", + "events": "npm:jspm-nodelibs-events@0.2.0", + "net": "npm:jspm-nodelibs-net@0.2.0" + }, + "packages": { + "npm:jspm-nodelibs-os@0.2.0": { + "map": { + "os-browserify": "npm:os-browserify@0.2.1" + } + }, + "github:frankwallis/plugin-typescript@5.3.3": { + "map": { + "typescript": "npm:typescript@2.1.4" + } + }, + "npm:typescript@2.1.4": { + "map": { + "source-map-support": "npm:source-map-support@0.4.8" + } + }, + "npm:source-map-support@0.4.8": { + "map": { + "source-map": "npm:source-map@0.5.6" + } + }, + "npm:jspm-nodelibs-buffer@0.2.1": { + "map": { + "buffer": "npm:buffer@4.9.1" + } + }, + "npm:buffer@4.9.1": { + "map": { + "base64-js": "npm:base64-js@1.2.0", + "ieee754": "npm:ieee754@1.1.8", + "isarray": "npm:isarray@1.0.0" + } + }, + "npm:jspm-nodelibs-crypto@0.2.0": { + "map": { + "crypto-browserify": "npm:crypto-browserify@3.11.0" + } + }, + "npm:crypto-browserify@3.11.0": { + "map": { + "diffie-hellman": "npm:diffie-hellman@5.0.2", + "pbkdf2": "npm:pbkdf2@3.0.9", + "create-ecdh": "npm:create-ecdh@4.0.0", + "browserify-sign": "npm:browserify-sign@4.0.0", + "create-hmac": "npm:create-hmac@1.1.4", + "browserify-cipher": "npm:browserify-cipher@1.0.0", + "create-hash": "npm:create-hash@1.1.2", + "inherits": "npm:inherits@2.0.3", + "public-encrypt": "npm:public-encrypt@4.0.0", + "randombytes": "npm:randombytes@2.0.3" + } + }, + "npm:pbkdf2@3.0.9": { + "map": { + "create-hmac": "npm:create-hmac@1.1.4" + } + }, + "npm:browserify-sign@4.0.0": { + "map": { + "create-hmac": "npm:create-hmac@1.1.4", + "create-hash": "npm:create-hash@1.1.2", + "inherits": "npm:inherits@2.0.3", + "bn.js": "npm:bn.js@4.11.6", + "parse-asn1": "npm:parse-asn1@5.0.0", + "elliptic": "npm:elliptic@6.3.2", + "browserify-rsa": "npm:browserify-rsa@4.0.1" + } + }, + "npm:diffie-hellman@5.0.2": { + "map": { + "randombytes": "npm:randombytes@2.0.3", + "bn.js": "npm:bn.js@4.11.6", + "miller-rabin": "npm:miller-rabin@4.0.0" + } + }, + "npm:create-hmac@1.1.4": { + "map": { + "create-hash": "npm:create-hash@1.1.2", + "inherits": "npm:inherits@2.0.3" + } + }, + "npm:create-hash@1.1.2": { + "map": { + "inherits": "npm:inherits@2.0.3", + "cipher-base": "npm:cipher-base@1.0.3", + "ripemd160": "npm:ripemd160@1.0.1", + "sha.js": "npm:sha.js@2.4.8" + } + }, + "npm:public-encrypt@4.0.0": { + "map": { + "create-hash": "npm:create-hash@1.1.2", + "randombytes": "npm:randombytes@2.0.3", + "bn.js": "npm:bn.js@4.11.6", + "parse-asn1": "npm:parse-asn1@5.0.0", + "browserify-rsa": "npm:browserify-rsa@4.0.1" + } + }, + "npm:create-ecdh@4.0.0": { + "map": { + "bn.js": "npm:bn.js@4.11.6", + "elliptic": "npm:elliptic@6.3.2" + } + }, + "npm:miller-rabin@4.0.0": { + "map": { + "bn.js": "npm:bn.js@4.11.6", + "brorand": "npm:brorand@1.0.6" + } + }, + "npm:parse-asn1@5.0.0": { + "map": { + "create-hash": "npm:create-hash@1.1.2", + "pbkdf2": "npm:pbkdf2@3.0.9", + "asn1.js": "npm:asn1.js@4.9.0", + "evp_bytestokey": "npm:evp_bytestokey@1.0.0", + "browserify-aes": "npm:browserify-aes@1.0.6" + } + }, + "npm:asn1.js@4.9.0": { + "map": { + "bn.js": "npm:bn.js@4.11.6", + "inherits": "npm:inherits@2.0.3", + "minimalistic-assert": "npm:minimalistic-assert@1.0.0" + } + }, + "npm:browserify-cipher@1.0.0": { + "map": { + "evp_bytestokey": "npm:evp_bytestokey@1.0.0", + "browserify-des": "npm:browserify-des@1.0.0", + "browserify-aes": "npm:browserify-aes@1.0.6" + } + }, + "npm:cipher-base@1.0.3": { + "map": { + "inherits": "npm:inherits@2.0.3" + } + }, + "npm:sha.js@2.4.8": { + "map": { + "inherits": "npm:inherits@2.0.3" + } + }, + "npm:evp_bytestokey@1.0.0": { + "map": { + "create-hash": "npm:create-hash@1.1.2" + } + }, + "npm:browserify-aes@1.0.6": { + "map": { + "cipher-base": "npm:cipher-base@1.0.3", + "create-hash": "npm:create-hash@1.1.2", + "evp_bytestokey": "npm:evp_bytestokey@1.0.0", + "inherits": "npm:inherits@2.0.3", + "buffer-xor": "npm:buffer-xor@1.0.3" + } + }, + "npm:browserify-des@1.0.0": { + "map": { + "cipher-base": "npm:cipher-base@1.0.3", + "inherits": "npm:inherits@2.0.3", + "des.js": "npm:des.js@1.0.0" + } + }, + "npm:elliptic@6.3.2": { + "map": { + "bn.js": "npm:bn.js@4.11.6", + "brorand": "npm:brorand@1.0.6", + "inherits": "npm:inherits@2.0.3", + "hash.js": "npm:hash.js@1.0.3" + } + }, + "npm:browserify-rsa@4.0.1": { + "map": { + "bn.js": "npm:bn.js@4.11.6", + "randombytes": "npm:randombytes@2.0.3" + } + }, + "npm:jspm-nodelibs-stream@0.2.0": { + "map": { + "stream-browserify": "npm:stream-browserify@2.0.1" + } + }, + "npm:des.js@1.0.0": { + "map": { + "inherits": "npm:inherits@2.0.3", + "minimalistic-assert": "npm:minimalistic-assert@1.0.0" + } + }, + "npm:stream-browserify@2.0.1": { + "map": { + "inherits": "npm:inherits@2.0.3", + "readable-stream": "npm:readable-stream@2.2.2" + } + }, + "npm:hash.js@1.0.3": { + "map": { + "inherits": "npm:inherits@2.0.3" + } + }, + "npm:readable-stream@2.2.2": { + "map": { + "isarray": "npm:isarray@1.0.0", + "inherits": "npm:inherits@2.0.3", + "string_decoder": "npm:string_decoder@0.10.31", + "process-nextick-args": "npm:process-nextick-args@1.0.7", + "buffer-shims": "npm:buffer-shims@1.0.0", + "core-util-is": "npm:core-util-is@1.0.2", + "util-deprecate": "npm:util-deprecate@1.0.2" + } + }, + "npm:jspm-nodelibs-string_decoder@0.2.0": { + "map": { + "string_decoder-browserify": "npm:string_decoder@0.10.31" + } + } + } + } +}); + +SystemJS.config({ + packageConfigPaths: [ + "npm:@*/*.json", + "npm:*.json", + "github:*/*.json" + ], + map: { + "core-js": "npm:core-js@2.4.0", + "fs": "npm:jspm-nodelibs-fs@0.2.0", + "path": "npm:jspm-nodelibs-path@0.2.0", + "process": "npm:jspm-nodelibs-process@0.2.0" + }, + packages: {} +}); diff --git a/jspm/package.json b/jspm/package.json new file mode 100644 index 0000000..a9604fb --- /dev/null +++ b/jspm/package.json @@ -0,0 +1,49 @@ +{ + "jspm": { + "dependencies": { + "core-js": "npm:core-js@^2.4.0" + }, + "devDependencies": { + "assert": "npm:jspm-nodelibs-assert@^0.2.0", + "buffer": "npm:jspm-nodelibs-buffer@^0.2.0", + "child_process": "npm:jspm-nodelibs-child_process@^0.2.0", + "constants": "npm:jspm-nodelibs-constants@^0.2.0", + "crypto": "npm:jspm-nodelibs-crypto@^0.2.0", + "events": "npm:jspm-nodelibs-events@^0.2.0", + "module": "npm:jspm-nodelibs-module@^0.2.0", + "net": "npm:jspm-nodelibs-net@^0.2.0", + "os": "npm:jspm-nodelibs-os@^0.2.0", + "plugin-typescript": "github:frankwallis/plugin-typescript@^5.3.3", + "stream": "npm:jspm-nodelibs-stream@^0.2.0", + "string_decoder": "npm:jspm-nodelibs-string_decoder@^0.2.0", + "util": "npm:jspm-nodelibs-util@^0.2.0", + "vm": "npm:jspm-nodelibs-vm@^0.2.0" + }, + "peerDependencies": { + "fs": "npm:jspm-nodelibs-fs@^0.2.0", + "path": "npm:jspm-nodelibs-path@^0.2.0", + "process": "npm:jspm-nodelibs-process@^0.2.0" + }, + "overrides": { + "npm:inherits@2.0.3": { + "ignore": [ + "test.js" + ] + }, + "npm:typescript@2.1.4": { + "browser": {}, + "map": { + "buffer": "@empty", + "child_process": "@empty", + "fs": "@empty", + "path": "@empty", + "process": "@empty", + "readline": "@empty" + }, + "dependencies": { + "source-map-support": "*" + } + } + } + } +} diff --git a/jspm/src/app.ts b/jspm/src/app.ts new file mode 100644 index 0000000..b4897f1 --- /dev/null +++ b/jspm/src/app.ts @@ -0,0 +1,6 @@ +import { Greeter } from "./greeter"; + +export function main(el: HTMLElement): void { + let greeter = new Greeter(el); + greeter.start(); +} \ No newline at end of file diff --git a/jspm/src/core-js.d.ts b/jspm/src/core-js.d.ts new file mode 100644 index 0000000..bb2a7c5 --- /dev/null +++ b/jspm/src/core-js.d.ts @@ -0,0 +1,3032 @@ +// Type definitions for core-js v0.9.7 +// Project: https://github.com/zloirock/core-js/ +// Definitions by: Ron Buckton +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +declare type PropertyKey = string | number | symbol; + +// ############################################################################################# +// ECMAScript 6: Object & Function +// Modules: es6.object.assign, es6.object.is, es6.object.set-prototype-of, +// es6.object.to-string, es6.function.name and es6.function.has-instance. +// ############################################################################################# + +interface ObjectConstructor { + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param sources One or more source objects to copy properties from. + */ + assign(target: any, ...sources: any[]): any; + + /** + * Returns true if the values are the same value, false otherwise. + * @param value1 The first value. + * @param value2 The second value. + */ + is(value1: any, value2: any): boolean; + + /** + * Sets the prototype of a specified object o to object proto or null. Returns the object o. + * @param o The object to change its prototype. + * @param proto The value of the new prototype or null. + * @remarks Requires `__proto__` support. + */ + setPrototypeOf(o: any, proto: any): any; +} + +interface Function { + /** + * Returns the name of the function. Function names are read-only and can not be changed. + */ + name: string; + + /** + * Determines if a constructor object recognizes an object as one of the + * constructor’s instances. + * @param value The object to test. + */ + [Symbol.hasInstance](value: any): boolean; +} + +// ############################################################################################# +// ECMAScript 6: Array +// Modules: es6.array.from, es6.array.of, es6.array.copy-within, es6.array.fill, es6.array.find, +// and es6.array.find-index +// ############################################################################################# + +interface Array { + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): T; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: T) => boolean, thisArg?: any): number; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: T, start?: number, end?: number): T[]; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): T[]; + + [Symbol.unscopables]: any; +} + +interface ArrayConstructor { + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): Array; + + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(iterable: Iterable, mapfn: (v: T, k: number) => U, thisArg?: any): Array; + + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + */ + from(arrayLike: ArrayLike): Array; + + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + */ + from(iterable: Iterable): Array; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: T[]): Array; +} + +// ############################################################################################# +// ECMAScript 6: String & RegExp +// Modules: es6.string.from-code-point, es6.string.raw, es6.string.code-point-at, +// es6.string.ends-with, es6.string.includes, es6.string.repeat, +// es6.string.starts-with, and es6.regexp +// ############################################################################################# + +interface String { + /** + * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point + * value of the UTF-16 encoded code point starting at the string element at position pos in + * the String resulting from converting this object to a String. + * If there is no element at that position, the result is undefined. + * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. + */ + codePointAt(pos: number): number; + + /** + * Returns true if searchString appears as a substring of the result of converting this + * object to a String, at one or more positions that are + * greater than or equal to position; otherwise, returns false. + * @param searchString search string + * @param position If position is undefined, 0 is assumed, so as to search all of the String. + */ + includes(searchString: string, position?: number): boolean; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * endPosition – length(this). Otherwise returns false. + */ + endsWith(searchString: string, endPosition?: number): boolean; + + /** + * Returns a String value that is made from count copies appended together. If count is 0, + * T is the empty String is returned. + * @param count number of copies to append + */ + repeat(count: number): string; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * position. Otherwise returns false. + */ + startsWith(searchString: string, position?: number): boolean; +} + +interface StringConstructor { + /** + * Return the String value whose elements are, in order, the elements in the List elements. + * If length is 0, the empty string is returned. + */ + fromCodePoint(...codePoints: number[]): string; + + /** + * String.raw is intended for use as a tag function of a Tagged Template String. When called + * as such the first argument will be a well formed template call site object and the rest + * parameter will contain the substitution values. + * @param template A well-formed template string call site representation. + * @param substitutions A set of substitution values. + */ + raw(template: TemplateStringsArray, ...substitutions: any[]): string; +} + +interface RegExp { + /** + * Returns a string indicating the flags of the regular expression in question. This field is read-only. + * The characters in this string are sequenced and concatenated in the following order: + * + * - "g" for global + * - "i" for ignoreCase + * - "m" for multiline + * - "u" for unicode + * - "y" for sticky + * + * If no flags are set, the value is the empty string. + */ + flags: string; +} + +// ############################################################################################# +// ECMAScript 6: Number & Math +// Modules: es6.number.constructor, es6.number.statics, and es6.math +// ############################################################################################# + +interface NumberConstructor { + /** + * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 + * that is representable as a Number value, which is approximately: + * 2.2204460492503130808472633361816 x 10â€âˆ’â€16. + */ + EPSILON: number; + + /** + * Returns true if passed value is finite. + * Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a + * number. Only finite values of the type number, result in true. + * @param number A numeric value. + */ + isFinite(number: number): boolean; + + /** + * Returns true if the value passed is an integer, false otherwise. + * @param number A numeric value. + */ + isInteger(number: number): boolean; + + /** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a + * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter + * to a number. Only values of the type number, that are also NaN, result in true. + * @param number A numeric value. + */ + isNaN(number: number): boolean; + + /** + * Returns true if the value passed is a safe integer. + * @param number A numeric value. + */ + isSafeInteger(number: number): boolean; + + /** + * The value of the largest integer n such that n and n + 1 are both exactly representable as + * a Number value. + * The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 − 1. + */ + MAX_SAFE_INTEGER: number; + + /** + * The value of the smallest integer n such that n and n − 1 are both exactly representable as + * a Number value. + * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)). + */ + MIN_SAFE_INTEGER: number; + + /** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ + parseFloat(string: string): number; + + /** + * Converts A string to an integer. + * @param s A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ + parseInt(string: string, radix?: number): number; +} + +interface Math { + /** + * Returns the number of leading zero bits in the 32-bit binary representation of a number. + * @param x A numeric expression. + */ + clz32(x: number): number; + + /** + * Returns the result of 32-bit multiplication of two numbers. + * @param x First number + * @param y Second number + */ + imul(x: number, y: number): number; + + /** + * Returns the sign of the x, indicating whether x is positive, negative or zero. + * @param x The numeric expression to test + */ + sign(x: number): number; + + /** + * Returns the base 10 logarithm of a number. + * @param x A numeric expression. + */ + log10(x: number): number; + + /** + * Returns the base 2 logarithm of a number. + * @param x A numeric expression. + */ + log2(x: number): number; + + /** + * Returns the natural logarithm of 1 + x. + * @param x A numeric expression. + */ + log1p(x: number): number; + + /** + * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of + * the natural logarithms). + * @param x A numeric expression. + */ + expm1(x: number): number; + + /** + * Returns the hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cosh(x: number): number; + + /** + * Returns the hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sinh(x: number): number; + + /** + * Returns the hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tanh(x: number): number; + + /** + * Returns the inverse hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + acosh(x: number): number; + + /** + * Returns the inverse hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + asinh(x: number): number; + + /** + * Returns the inverse hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + atanh(x: number): number; + + /** + * Returns the square root of the sum of squares of its arguments. + * @param values Values to compute the square root for. + * If no arguments are passed, the result is +0. + * If there is only one argument, the result is the absolute value. + * If any argument is +Infinity or -Infinity, the result is +Infinity. + * If any argument is NaN, the result is NaN. + * If all arguments are either +0 or −0, the result is +0. + */ + hypot(...values: number[]): number; + + /** + * Returns the integral part of the a numeric expression, x, removing any fractional digits. + * If x is already an integer, the result is x. + * @param x A numeric expression. + */ + trunc(x: number): number; + + /** + * Returns the nearest single precision float representation of a number. + * @param x A numeric expression. + */ + fround(x: number): number; + + /** + * Returns an implementation-dependent approximation to the cube root of number. + * @param x A numeric expression. + */ + cbrt(x: number): number; +} + +// ############################################################################################# +// ECMAScript 6: Symbols +// Modules: es6.symbol +// ############################################################################################# + +interface Symbol { + /** Returns a string representation of an object. */ + toString(): string; + + [Symbol.toStringTag]: string; +} + +interface SymbolConstructor { + /** + * A reference to the prototype. + */ + prototype: Symbol; + + /** + * Returns a new unique Symbol value. + * @param description Description of the new Symbol object. + */ + (description?: string|number): symbol; + + /** + * Returns a Symbol object from the global symbol registry matching the given key if found. + * Otherwise, returns a new symbol with this key. + * @param key key to search for. + */ + for(key: string): symbol; + + /** + * Returns a key from the global symbol registry matching the given Symbol if found. + * Otherwise, returns a undefined. + * @param sym Symbol to find the key for. + */ + keyFor(sym: symbol): string; + + // Well-known Symbols + + /** + * A method that determines if a constructor object recognizes an object as one of the + * constructor’s instances. Called by the semantics of the instanceof operator. + */ + hasInstance: symbol; + + /** + * A Boolean value that if true indicates that an object should flatten to its array elements + * by Array.prototype.concat. + */ + isConcatSpreadable: symbol; + + /** + * A method that returns the default iterator for an object. Called by the semantics of the + * for-of statement. + */ + iterator: symbol; + + /** + * A regular expression method that matches the regular expression against a string. Called + * by the String.prototype.match method. + */ + match: symbol; + + /** + * A regular expression method that replaces matched substrings of a string. Called by the + * String.prototype.replace method. + */ + replace: symbol; + + /** + * A regular expression method that returns the index within a string that matches the + * regular expression. Called by the String.prototype.search method. + */ + search: symbol; + + /** + * A function valued property that is the constructor function that is used to create + * derived objects. + */ + species: symbol; + + /** + * A regular expression method that splits a string at the indices that match the regular + * expression. Called by the String.prototype.split method. + */ + split: symbol; + + /** + * A method that converts an object to a corresponding primitive value.Called by the ToPrimitive + * abstract operation. + */ + toPrimitive: symbol; + + /** + * A String value that is used in the creation of the default string description of an object. + * Called by the built-in method Object.prototype.toString. + */ + toStringTag: symbol; + + /** + * An Object whose own property names are property names that are excluded from the with + * environment bindings of the associated objects. + */ + unscopables: symbol; + + /** + * Non-standard. Use simple mode for core-js symbols. See https://github.com/zloirock/core-js/#caveats-when-using-symbol-polyfill + */ + useSimple(): void; + + /** + * Non-standard. Use setter mode for core-js symbols. See https://github.com/zloirock/core-js/#caveats-when-using-symbol-polyfill + */ + userSetter(): void; +} + +declare var Symbol: SymbolConstructor; + +interface Object { + /** + * Determines whether an object has a property with the specified name. + * @param v A property name. + */ + hasOwnProperty(v: PropertyKey): boolean; + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: PropertyKey): boolean; +} + +interface ObjectConstructor { + /** + * Returns an array of all symbol properties found directly on object o. + * @param o Object to retrieve the symbols from. + */ + getOwnPropertySymbols(o: any): symbol[]; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not + * inherited from the object's prototype. + * @param o Object that contains the property. + * @param p Name of the property. + */ + getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param o Object on which to add or modify the property. This can be a native JavaScript + * object (that is, a user-defined object or a built in object) or a DOM object. + * @param p The property name. + * @param attributes Descriptor for the property. It can be for a data property or an accessor + * property. + */ + defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; +} + +interface Math { + [Symbol.toStringTag]: string; +} + +interface JSON { + [Symbol.toStringTag]: string; +} + +// ############################################################################################# +// ECMAScript 6: Collections +// Modules: es6.map, es6.set, es6.weak-map, and es6.weak-set +// ############################################################################################# + +interface Map { + clear(): void; + delete(key: K): boolean; + forEach(callbackfn: (value: V, index: K, map: Map) => void, thisArg?: any): void; + get(key: K): V; + has(key: K): boolean; + set(key: K, value?: V): Map; + size: number; +} + +interface MapConstructor { + new (): Map; + new (iterable: Iterable<[K, V]>): Map; + prototype: Map; +} + +declare var Map: MapConstructor; + +interface Set { + add(value: T): Set; + clear(): void; + delete(value: T): boolean; + forEach(callbackfn: (value: T, index: T, set: Set) => void, thisArg?: any): void; + has(value: T): boolean; + size: number; +} + +interface SetConstructor { + new (): Set; + new (iterable: Iterable): Set; + prototype: Set; +} + +declare var Set: SetConstructor; + +interface WeakMap { + delete(key: K): boolean; + get(key: K): V; + has(key: K): boolean; + set(key: K, value?: V): WeakMap; +} + +interface WeakMapConstructor { + new (): WeakMap; + new (iterable: Iterable<[K, V]>): WeakMap; + prototype: WeakMap; +} + +declare var WeakMap: WeakMapConstructor; + +interface WeakSet { + add(value: T): WeakSet; + delete(value: T): boolean; + has(value: T): boolean; +} + +interface WeakSetConstructor { + new (): WeakSet; + new (iterable: Iterable): WeakSet; + prototype: WeakSet; +} + +declare var WeakSet: WeakSetConstructor; + +// ############################################################################################# +// ECMAScript 6: Iterators +// Modules: es6.string.iterator, es6.array.iterator, es6.map, es6.set, web.dom.iterable +// ############################################################################################# + +interface IteratorResult { + done: boolean; + value?: T; +} + +interface Iterator { + next(value?: any): IteratorResult; + return?(value?: any): IteratorResult; + throw?(e?: any): IteratorResult; +} + +interface Iterable { + [Symbol.iterator](): Iterator; +} + +interface IterableIterator extends Iterator { + [Symbol.iterator](): IterableIterator; +} + +interface String { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + +interface Array { + /** Iterator */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; +} + +interface Map { + entries(): IterableIterator<[K, V]>; + keys(): IterableIterator; + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[K, V]>; +} + +interface Set { + entries(): IterableIterator<[T, T]>; + keys(): IterableIterator; + values(): IterableIterator; + [Symbol.iterator](): IterableIterator; +} + +interface NodeList { + [Symbol.iterator](): IterableIterator; +} + +interface $for extends IterableIterator { + of(callbackfn: (value: T, key: any) => void, thisArg?: any): void; + array(): T[]; + array(callbackfn: (value: T, key: any) => U, thisArg?: any): U[]; + filter(callbackfn: (value: T, key: any) => boolean, thisArg?: any): $for; + map(callbackfn: (value: T, key: any) => U, thisArg?: any): $for; +} + +declare function $for(iterable: Iterable): $for; + +// ############################################################################################# +// ECMAScript 6: Promises +// Modules: es6.promise +// ############################################################################################# + +interface PromiseLike { + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): PromiseLike; + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): PromiseLike; +} + +/** + * Represents the completion of an asynchronous operation + */ +interface Promise { + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; + + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onrejected?: (reason: any) => T | PromiseLike): Promise; + catch(onrejected?: (reason: any) => void): Promise; +} + +interface PromiseConstructor { + /** + * A reference to the prototype. + */ + prototype: Promise; + + /** + * Creates a new Promise. + * @param executor A callback used to initialize the promise. This callback is passed two arguments: + * a resolve callback used resolve the promise with a value or the result of another promise, + * and a reject callback used to reject the promise with a provided reason or error. + */ + new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: Iterable>): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: Iterable>): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new resolved promise for the provided value. + * @param value A promise. + * @returns A promise whose internal state matches the provided promise. + */ + resolve(value: T | PromiseLike): Promise; + + /** + * Creates a new resolved promise . + * @returns A resolved promise. + */ + resolve(): Promise; +} + +declare var Promise: PromiseConstructor; + +// ############################################################################################# +// ECMAScript 6: Reflect +// Modules: es6.reflect +// ############################################################################################# + +declare module Reflect { + function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; + function construct(target: Function, argumentsList: ArrayLike, newTarget?: any): any; + function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: any, propertyKey: PropertyKey): boolean; + function enumerate(target: any): IterableIterator; + function get(target: any, propertyKey: PropertyKey, receiver?: any): any; + function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; + function getPrototypeOf(target: any): any; + function has(target: any, propertyKey: PropertyKey): boolean; + function isExtensible(target: any): boolean; + function ownKeys(target: any): Array; + function preventExtensions(target: any): boolean; + function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function setPrototypeOf(target: any, proto: any): boolean; +} + +// ############################################################################################# +// ECMAScript 7 +// Modules: es7.array.includes, es7.string.at, es7.string.lpad, es7.string.rpad, +// es7.object.to-array, es7.object.get-own-property-descriptors, es7.regexp.escape, +// es7.map.to-json, and es7.set.to-json +// ############################################################################################# + +interface Array { + includes(value: T, fromIndex?: number): boolean; +} + +interface String { + at(index: number): string; + lpad(length: number, fillStr?: string): string; + rpad(length: number, fillStr?: string): string; +} + +interface ObjectConstructor { + values(object: any): any[]; + entries(object: any): [string, any][]; + getOwnPropertyDescriptors(object: any): PropertyDescriptorMap; +} + +interface RegExpConstructor { + escape(str: string): string; +} + +interface Map { + toJSON(): any; +} + +interface Set { + toJSON(): any; +} + +// ############################################################################################# +// Mozilla JavaScript: Array generics +// Modules: js.array.statics +// ############################################################################################# + +interface ArrayConstructor { + /** + * Appends new elements to an array, and returns the new length of the array. + * @param items New elements of the Array. + */ + push(array: ArrayLike, ...items: T[]): number; + /** + * Removes the last element from an array and returns it. + */ + pop(array: ArrayLike): T; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(array: ArrayLike, ...items: (T[]| T)[]): T[]; + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ + join(array: ArrayLike, separator?: string): string; + /** + * Reverses the elements in an Array. + */ + reverse(array: ArrayLike): T[]; + /** + * Removes the first element from an array and returns it. + */ + shift(array: ArrayLike): T; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(array: ArrayLike, start?: number, end?: number): T[]; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(array: ArrayLike, compareFn?: (a: T, b: T) => number): T[]; + + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + */ + splice(array: ArrayLike, start: number): T[]; + + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + * @param deleteCount The number of elements to remove. + * @param items Elements to insert into the array in place of the deleted elements. + */ + splice(array: ArrayLike, start: number, deleteCount: number, ...items: T[]): T[]; + + /** + * Inserts new elements at the start of an array. + * @param items Elements to insert at the start of the Array. + */ + unshift(array: ArrayLike, ...items: T[]): number; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(array: ArrayLike, searchElement: T, fromIndex?: number): number; + + /** + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(array: ArrayLike, earchElement: T, fromIndex?: number): number; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + every(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + some(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[]; + + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(array: ArrayLike, callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(array: ArrayLike, callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(array: ArrayLike, callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(array: ArrayLike, callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(array: ArrayLike): IterableIterator<[number, T]>; + + /** + * Returns an list of keys in the array + */ + keys(array: ArrayLike): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(array: ArrayLike): IterableIterator; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(array: ArrayLike, predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): T; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(array: ArrayLike, predicate: (value: T) => boolean, thisArg?: any): number; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(array: ArrayLike, value: T, start?: number, end?: number): T[]; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(array: ArrayLike, target: number, start: number, end?: number): T[]; + + includes(array: ArrayLike, value: T, fromIndex?: number): boolean; + turn(array: ArrayLike, callbackfn: (memo: U, value: T, index: number, array: Array) => void, memo?: U): U; + turn(array: ArrayLike, callbackfn: (memo: Array, value: T, index: number, array: Array) => void, memo?: Array): Array; +} + +// ############################################################################################# +// Object - https://github.com/zloirock/core-js/#object +// Modules: core.object +// ############################################################################################# + +interface ObjectConstructor { + /** + * Non-standard. + */ + isObject(value: any): boolean; + + /** + * Non-standard. + */ + classof(value: any): string; + + /** + * Non-standard. + */ + define(target: T, mixin: any): T; + + /** + * Non-standard. + */ + make(proto: T, mixin?: any): T; +} + +// ############################################################################################# +// Console - https://github.com/zloirock/core-js/#console +// Modules: core.log +// ############################################################################################# + +interface Log extends Console { + (message?: any, ...optionalParams: any[]): void; + enable(): void; + disable(): void; +} + +/** + * Non-standard. + */ +declare var log: Log; + +// ############################################################################################# +// Dict - https://github.com/zloirock/core-js/#dict +// Modules: core.dict +// ############################################################################################# + +interface Dict { + [key: string]: T; + [key: number]: T; + //[key: symbol]: T; +} + +interface DictConstructor { + prototype: Dict; + + new (value?: Dict): Dict; + new (value?: any): Dict; + (value?: Dict): Dict; + (value?: any): Dict; + + isDict(value: any): boolean; + values(object: Dict): IterableIterator; + keys(object: Dict): IterableIterator; + entries(object: Dict): IterableIterator<[PropertyKey, T]>; + has(object: Dict, key: PropertyKey): boolean; + get(object: Dict, key: PropertyKey): T; + set(object: Dict, key: PropertyKey, value: T): Dict; + forEach(object: Dict, callbackfn: (value: T, key: PropertyKey, dict: Dict) => void, thisArg?: any): void; + map(object: Dict, callbackfn: (value: T, key: PropertyKey, dict: Dict) => U, thisArg?: any): Dict; + mapPairs(object: Dict, callbackfn: (value: T, key: PropertyKey, dict: Dict) => [PropertyKey, U], thisArg?: any): Dict; + filter(object: Dict, callbackfn: (value: T, key: PropertyKey, dict: Dict) => boolean, thisArg?: any): Dict; + some(object: Dict, callbackfn: (value: T, key: PropertyKey, dict: Dict) => boolean, thisArg?: any): boolean; + every(object: Dict, callbackfn: (value: T, key: PropertyKey, dict: Dict) => boolean, thisArg?: any): boolean; + find(object: Dict, callbackfn: (value: T, key: PropertyKey, dict: Dict) => boolean, thisArg?: any): T; + findKey(object: Dict, callbackfn: (value: T, key: PropertyKey, dict: Dict) => boolean, thisArg?: any): PropertyKey; + keyOf(object: Dict, value: T): PropertyKey; + includes(object: Dict, value: T): boolean; + reduce(object: Dict, callbackfn: (previousValue: U, value: T, key: PropertyKey, dict: Dict) => U, initialValue: U): U; + reduce(object: Dict, callbackfn: (previousValue: T, value: T, key: PropertyKey, dict: Dict) => T, initialValue?: T): T; + turn(object: Dict, callbackfn: (memo: Dict, value: T, key: PropertyKey, dict: Dict) => void, memo: Dict): Dict; + turn(object: Dict, callbackfn: (memo: Dict, value: T, key: PropertyKey, dict: Dict) => void, memo?: Dict): Dict; +} + +/** + * Non-standard. + */ +declare var Dict: DictConstructor; + +// ############################################################################################# +// Partial application - https://github.com/zloirock/core-js/#partial-application +// Modules: core.function.part +// ############################################################################################# + +interface Function { + /** + * Non-standard. + */ + part(...args: any[]): any; +} + +// ############################################################################################# +// Date formatting - https://github.com/zloirock/core-js/#date-formatting +// Modules: core.date +// ############################################################################################# + +interface Date { + /** + * Non-standard. + */ + format(template: string, locale?: string): string; + + /** + * Non-standard. + */ + formatUTC(template: string, locale?: string): string; +} + +// ############################################################################################# +// Array - https://github.com/zloirock/core-js/#array +// Modules: core.array.turn +// ############################################################################################# + +interface Array { + /** + * Non-standard. + */ + turn(callbackfn: (memo: U, value: T, index: number, array: Array) => void, memo?: U): U; + + /** + * Non-standard. + */ + turn(callbackfn: (memo: Array, value: T, index: number, array: Array) => void, memo?: Array): Array; +} + +// ############################################################################################# +// Number - https://github.com/zloirock/core-js/#number +// Modules: core.number.iterator +// ############################################################################################# + +interface Number { + /** + * Non-standard. + */ + [Symbol.iterator](): IterableIterator; +} + +// ############################################################################################# +// Escaping characters - https://github.com/zloirock/core-js/#escaping-characters +// Modules: core.string.escape-html +// ############################################################################################# + +interface String { + /** + * Non-standard. + */ + escapeHTML(): string; + + /** + * Non-standard. + */ + unescapeHTML(): string; +} + +// ############################################################################################# +// delay - https://github.com/zloirock/core-js/#delay +// Modules: core.delay +// ############################################################################################# + +declare function delay(msec: number): Promise; + +declare module core { + module Reflect { + function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; + function construct(target: Function, argumentsList: ArrayLike): any; + function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: any, propertyKey: PropertyKey): boolean; + function enumerate(target: any): IterableIterator; + function get(target: any, propertyKey: PropertyKey, receiver?: any): any; + function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; + function getPrototypeOf(target: any): any; + function has(target: any, propertyKey: string): boolean; + function has(target: any, propertyKey: symbol): boolean; + function isExtensible(target: any): boolean; + function ownKeys(target: any): Array; + function preventExtensions(target: any): boolean; + function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function setPrototypeOf(target: any, proto: any): boolean; + } + + var Object: { + getPrototypeOf(o: any): any; + getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor; + getOwnPropertyNames(o: any): string[]; + create(o: any, properties?: PropertyDescriptorMap): any; + defineProperty(o: any, p: string, attributes: PropertyDescriptor): any; + defineProperties(o: any, properties: PropertyDescriptorMap): any; + seal(o: T): T; + freeze(o: T): T; + preventExtensions(o: T): T; + isSealed(o: any): boolean; + isFrozen(o: any): boolean; + isExtensible(o: any): boolean; + keys(o: any): string[]; + assign(target: any, ...sources: any[]): any; + is(value1: any, value2: any): boolean; + setPrototypeOf(o: any, proto: any): any; + getOwnPropertySymbols(o: any): symbol[]; + getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; + defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; + values(object: any): any[]; + entries(object: any): any[]; + getOwnPropertyDescriptors(object: any): PropertyDescriptorMap; + isObject(value: any): boolean; + classof(value: any): string; + define(target: T, mixin: any): T; + make(proto: T, mixin?: any): T; + }; + + var Function: { + bind(target: Function, thisArg: any, ...argArray: any[]): any; + part(target: Function, ...args: any[]): any; + }; + + var Array: { + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): Array; + from(iterable: Iterable, mapfn: (v: T, k: number) => U, thisArg?: any): Array; + from(arrayLike: ArrayLike): Array; + from(iterable: Iterable): Array; + of(...items: T[]): Array; + push(array: ArrayLike, ...items: T[]): number; + pop(array: ArrayLike): T; + concat(array: ArrayLike, ...items: (T[]| T)[]): T[]; + join(array: ArrayLike, separator?: string): string; + reverse(array: ArrayLike): T[]; + shift(array: ArrayLike): T; + slice(array: ArrayLike, start?: number, end?: number): T[]; + sort(array: ArrayLike, compareFn?: (a: T, b: T) => number): T[]; + splice(array: ArrayLike, start: number): T[]; + splice(array: ArrayLike, start: number, deleteCount: number, ...items: T[]): T[]; + unshift(array: ArrayLike, ...items: T[]): number; + indexOf(array: ArrayLike, searchElement: T, fromIndex?: number): number; + lastIndexOf(array: ArrayLike, earchElement: T, fromIndex?: number): number; + every(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + some(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + forEach(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + map(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; + filter(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[]; + reduce(array: ArrayLike, callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + reduce(array: ArrayLike, callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + reduceRight(array: ArrayLike, callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + reduceRight(array: ArrayLike, callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + entries(array: ArrayLike): IterableIterator<[number, T]>; + keys(array: ArrayLike): IterableIterator; + values(array: ArrayLike): IterableIterator; + find(array: ArrayLike, predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): T; + findIndex(array: ArrayLike, predicate: (value: T) => boolean, thisArg?: any): number; + fill(array: ArrayLike, value: T, start?: number, end?: number): T[]; + copyWithin(array: ArrayLike, target: number, start: number, end?: number): T[]; + includes(array: ArrayLike, value: T, fromIndex?: number): boolean; + turn(array: ArrayLike, callbackfn: (memo: Array, value: T, index: number, array: Array) => void, memo?: Array): Array; + turn(array: ArrayLike, callbackfn: (memo: U, value: T, index: number, array: Array) => void, memo?: U): U; + }; + + var String: { + codePointAt(text: string, pos: number): number; + includes(text: string, searchString: string, position?: number): boolean; + endsWith(text: string, searchString: string, endPosition?: number): boolean; + repeat(text: string, count: number): string; + fromCodePoint(...codePoints: number[]): string; + raw(template: TemplateStringsArray, ...substitutions: any[]): string; + startsWith(text: string, searchString: string, position?: number): boolean; + at(text: string, index: number): string; + lpad(text: string, length: number, fillStr?: string): string; + rpad(text: string, length: number, fillStr?: string): string; + escapeHTML(text: string): string; + unescapeHTML(text: string): string; + }; + + var Date: { + now(): number; + toISOString(date: Date): string; + format(date: Date, template: string, locale?: string): string; + formatUTC(date: Date, template: string, locale?: string): string; + }; + + var Number: { + EPSILON: number; + isFinite(number: number): boolean; + isInteger(number: number): boolean; + isNaN(number: number): boolean; + isSafeInteger(number: number): boolean; + MAX_SAFE_INTEGER: number; + MIN_SAFE_INTEGER: number; + parseFloat(string: string): number; + parseInt(string: string, radix?: number): number; + clz32(x: number): number; + imul(x: number, y: number): number; + sign(x: number): number; + log10(x: number): number; + log2(x: number): number; + log1p(x: number): number; + expm1(x: number): number; + cosh(x: number): number; + sinh(x: number): number; + tanh(x: number): number; + acosh(x: number): number; + asinh(x: number): number; + atanh(x: number): number; + hypot(...values: number[]): number; + trunc(x: number): number; + fround(x: number): number; + cbrt(x: number): number; + random(lim?: number): number; + }; + + var Math: { + clz32(x: number): number; + imul(x: number, y: number): number; + sign(x: number): number; + log10(x: number): number; + log2(x: number): number; + log1p(x: number): number; + expm1(x: number): number; + cosh(x: number): number; + sinh(x: number): number; + tanh(x: number): number; + acosh(x: number): number; + asinh(x: number): number; + atanh(x: number): number; + hypot(...values: number[]): number; + trunc(x: number): number; + fround(x: number): number; + cbrt(x: number): number; + }; + + var RegExp: { + escape(str: string): string; + }; + + var Map: MapConstructor; + var Set: SetConstructor; + var WeakMap: WeakMapConstructor; + var WeakSet: WeakSetConstructor; + var Promise: PromiseConstructor; + var Symbol: SymbolConstructor; + var Dict: DictConstructor; + var global: any; + var log: Log; + var _: boolean; + + function setTimeout(handler: any, timeout?: any, ...args: any[]): number; + + function setInterval(handler: any, timeout?: any, ...args: any[]): number; + + function setImmediate(expression: any, ...args: any[]): number; + + function clearImmediate(handle: number): void; + + function $for(iterable: Iterable): $for; + + function isIterable(value: any): boolean; + + function getIterator(iterable: Iterable): Iterator; + + interface Locale { + weekdays: string; + months: string; + } + + function addLocale(lang: string, locale: Locale): typeof core; + + function locale(lang?: string): string; + + function delay(msec: number): Promise; +} + +declare module "core-js" { + export = core; +} +declare module "core-js/shim" { + export = core; +} +declare module "core-js/core" { + export = core; +} +declare module "core-js/core/$for" { + import $for = core.$for; + export = $for; +} +declare module "core-js/core/_" { + var _: typeof core._; + export = _; +} +declare module "core-js/core/array" { + var Array: typeof core.Array; + export = Array; +} +declare module "core-js/core/date" { + var Date: typeof core.Date; + export = Date; +} +declare module "core-js/core/delay" { + var delay: typeof core.delay; + export = delay; +} +declare module "core-js/core/dict" { + var Dict: typeof core.Dict; + export = Dict; +} +declare module "core-js/core/function" { + var Function: typeof core.Function; + export = Function; +} +declare module "core-js/core/global" { + var global: typeof core.global; + export = global; +} +declare module "core-js/core/log" { + var log: typeof core.log; + export = log; +} +declare module "core-js/core/number" { + var Number: typeof core.Number; + export = Number; +} +declare module "core-js/core/object" { + var Object: typeof core.Object; + export = Object; +} +declare module "core-js/core/string" { + var String: typeof core.String; + export = String; +} +declare module "core-js/fn/$for" { + import $for = core.$for; + export = $for; +} +declare module "core-js/fn/_" { + var _: typeof core._; + export = _; +} +declare module "core-js/fn/clear-immediate" { + var clearImmediate: typeof core.clearImmediate; + export = clearImmediate; +} +declare module "core-js/fn/delay" { + var delay: typeof core.delay; + export = delay; +} +declare module "core-js/fn/dict" { + var Dict: typeof core.Dict; + export = Dict; +} +declare module "core-js/fn/get-iterator" { + var getIterator: typeof core.getIterator; + export = getIterator; +} +declare module "core-js/fn/global" { + var global: typeof core.global; + export = global; +} +declare module "core-js/fn/is-iterable" { + var isIterable: typeof core.isIterable; + export = isIterable; +} +declare module "core-js/fn/log" { + var log: typeof core.log; + export = log; +} +declare module "core-js/fn/map" { + var Map: typeof core.Map; + export = Map; +} +declare module "core-js/fn/promise" { + var Promise: typeof core.Promise; + export = Promise; +} +declare module "core-js/fn/set" { + var Set: typeof core.Set; + export = Set; +} +declare module "core-js/fn/set-immediate" { + var setImmediate: typeof core.setImmediate; + export = setImmediate; +} +declare module "core-js/fn/set-interval" { + var setInterval: typeof core.setInterval; + export = setInterval; +} +declare module "core-js/fn/set-timeout" { + var setTimeout: typeof core.setTimeout; + export = setTimeout; +} +declare module "core-js/fn/weak-map" { + var WeakMap: typeof core.WeakMap; + export = WeakMap; +} +declare module "core-js/fn/weak-set" { + var WeakSet: typeof core.WeakSet; + export = WeakSet; +} +declare module "core-js/fn/array" { + var Array: typeof core.Array; + export = Array; +} +declare module "core-js/fn/array/concat" { + var concat: typeof core.Array.concat; + export = concat; +} +declare module "core-js/fn/array/copy-within" { + var copyWithin: typeof core.Array.copyWithin; + export = copyWithin; +} +declare module "core-js/fn/array/entries" { + var entries: typeof core.Array.entries; + export = entries; +} +declare module "core-js/fn/array/every" { + var every: typeof core.Array.every; + export = every; +} +declare module "core-js/fn/array/fill" { + var fill: typeof core.Array.fill; + export = fill; +} +declare module "core-js/fn/array/filter" { + var filter: typeof core.Array.filter; + export = filter; +} +declare module "core-js/fn/array/find" { + var find: typeof core.Array.find; + export = find; +} +declare module "core-js/fn/array/find-index" { + var findIndex: typeof core.Array.findIndex; + export = findIndex; +} +declare module "core-js/fn/array/for-each" { + var forEach: typeof core.Array.forEach; + export = forEach; +} +declare module "core-js/fn/array/from" { + var from: typeof core.Array.from; + export = from; +} +declare module "core-js/fn/array/includes" { + var includes: typeof core.Array.includes; + export = includes; +} +declare module "core-js/fn/array/index-of" { + var indexOf: typeof core.Array.indexOf; + export = indexOf; +} +declare module "core-js/fn/array/join" { + var join: typeof core.Array.join; + export = join; +} +declare module "core-js/fn/array/keys" { + var keys: typeof core.Array.keys; + export = keys; +} +declare module "core-js/fn/array/last-index-of" { + var lastIndexOf: typeof core.Array.lastIndexOf; + export = lastIndexOf; +} +declare module "core-js/fn/array/map" { + var map: typeof core.Array.map; + export = map; +} +declare module "core-js/fn/array/of" { + var of: typeof core.Array.of; + export = of; +} +declare module "core-js/fn/array/pop" { + var pop: typeof core.Array.pop; + export = pop; +} +declare module "core-js/fn/array/push" { + var push: typeof core.Array.push; + export = push; +} +declare module "core-js/fn/array/reduce" { + var reduce: typeof core.Array.reduce; + export = reduce; +} +declare module "core-js/fn/array/reduce-right" { + var reduceRight: typeof core.Array.reduceRight; + export = reduceRight; +} +declare module "core-js/fn/array/reverse" { + var reverse: typeof core.Array.reverse; + export = reverse; +} +declare module "core-js/fn/array/shift" { + var shift: typeof core.Array.shift; + export = shift; +} +declare module "core-js/fn/array/slice" { + var slice: typeof core.Array.slice; + export = slice; +} +declare module "core-js/fn/array/some" { + var some: typeof core.Array.some; + export = some; +} +declare module "core-js/fn/array/sort" { + var sort: typeof core.Array.sort; + export = sort; +} +declare module "core-js/fn/array/splice" { + var splice: typeof core.Array.splice; + export = splice; +} +declare module "core-js/fn/array/turn" { + var turn: typeof core.Array.turn; + export = turn; +} +declare module "core-js/fn/array/unshift" { + var unshift: typeof core.Array.unshift; + export = unshift; +} +declare module "core-js/fn/array/values" { + var values: typeof core.Array.values; + export = values; +} +declare module "core-js/fn/date" { + var Date: typeof core.Date; + export = Date; +} +declare module "core-js/fn/date/add-locale" { + var addLocale: typeof core.addLocale; + export = addLocale; +} +declare module "core-js/fn/date/format" { + var format: typeof core.Date.format; + export = format; +} +declare module "core-js/fn/date/formatUTC" { + var formatUTC: typeof core.Date.formatUTC; + export = formatUTC; +} +declare module "core-js/fn/function" { + var Function: typeof core.Function; + export = Function; +} +declare module "core-js/fn/function/has-instance" { + var hasInstance: (value: any) => boolean; + export = hasInstance; +} +declare module "core-js/fn/function/name" +{ +} +declare module "core-js/fn/function/part" { + var part: typeof core.Function.part; + export = part; +} +declare module "core-js/fn/math" { + var Math: typeof core.Math; + export = Math; +} +declare module "core-js/fn/math/acosh" { + var acosh: typeof core.Math.acosh; + export = acosh; +} +declare module "core-js/fn/math/asinh" { + var asinh: typeof core.Math.asinh; + export = asinh; +} +declare module "core-js/fn/math/atanh" { + var atanh: typeof core.Math.atanh; + export = atanh; +} +declare module "core-js/fn/math/cbrt" { + var cbrt: typeof core.Math.cbrt; + export = cbrt; +} +declare module "core-js/fn/math/clz32" { + var clz32: typeof core.Math.clz32; + export = clz32; +} +declare module "core-js/fn/math/cosh" { + var cosh: typeof core.Math.cosh; + export = cosh; +} +declare module "core-js/fn/math/expm1" { + var expm1: typeof core.Math.expm1; + export = expm1; +} +declare module "core-js/fn/math/fround" { + var fround: typeof core.Math.fround; + export = fround; +} +declare module "core-js/fn/math/hypot" { + var hypot: typeof core.Math.hypot; + export = hypot; +} +declare module "core-js/fn/math/imul" { + var imul: typeof core.Math.imul; + export = imul; +} +declare module "core-js/fn/math/log10" { + var log10: typeof core.Math.log10; + export = log10; +} +declare module "core-js/fn/math/log1p" { + var log1p: typeof core.Math.log1p; + export = log1p; +} +declare module "core-js/fn/math/log2" { + var log2: typeof core.Math.log2; + export = log2; +} +declare module "core-js/fn/math/sign" { + var sign: typeof core.Math.sign; + export = sign; +} +declare module "core-js/fn/math/sinh" { + var sinh: typeof core.Math.sinh; + export = sinh; +} +declare module "core-js/fn/math/tanh" { + var tanh: typeof core.Math.tanh; + export = tanh; +} +declare module "core-js/fn/math/trunc" { + var trunc: typeof core.Math.trunc; + export = trunc; +} +declare module "core-js/fn/number" { + var Number: typeof core.Number; + export = Number; +} +declare module "core-js/fn/number/epsilon" { + var EPSILON: typeof core.Number.EPSILON; + export = EPSILON; +} +declare module "core-js/fn/number/is-finite" { + var isFinite: typeof core.Number.isFinite; + export = isFinite; +} +declare module "core-js/fn/number/is-integer" { + var isInteger: typeof core.Number.isInteger; + export = isInteger; +} +declare module "core-js/fn/number/is-nan" { + var isNaN: typeof core.Number.isNaN; + export = isNaN; +} +declare module "core-js/fn/number/is-safe-integer" { + var isSafeInteger: typeof core.Number.isSafeInteger; + export = isSafeInteger; +} +declare module "core-js/fn/number/max-safe-integer" { + var MAX_SAFE_INTEGER: typeof core.Number.MAX_SAFE_INTEGER; + export = MAX_SAFE_INTEGER; +} +declare module "core-js/fn/number/min-safe-interger" { + var MIN_SAFE_INTEGER: typeof core.Number.MIN_SAFE_INTEGER; + export = MIN_SAFE_INTEGER; +} +declare module "core-js/fn/number/parse-float" { + var parseFloat: typeof core.Number.parseFloat; + export = parseFloat; +} +declare module "core-js/fn/number/parse-int" { + var parseInt: typeof core.Number.parseInt; + export = parseInt; +} +declare module "core-js/fn/number/random" { + var random: typeof core.Number.random; + export = random; +} +declare module "core-js/fn/object" { + var Object: typeof core.Object; + export = Object; +} +declare module "core-js/fn/object/assign" { + var assign: typeof core.Object.assign; + export = assign; +} +declare module "core-js/fn/object/classof" { + var classof: typeof core.Object.classof; + export = classof; +} +declare module "core-js/fn/object/create" { + var create: typeof core.Object.create; + export = create; +} +declare module "core-js/fn/object/define" { + var define: typeof core.Object.define; + export = define; +} +declare module "core-js/fn/object/define-properties" { + var defineProperties: typeof core.Object.defineProperties; + export = defineProperties; +} +declare module "core-js/fn/object/define-property" { + var defineProperty: typeof core.Object.defineProperty; + export = defineProperty; +} +declare module "core-js/fn/object/entries" { + var entries: typeof core.Object.entries; + export = entries; +} +declare module "core-js/fn/object/freeze" { + var freeze: typeof core.Object.freeze; + export = freeze; +} +declare module "core-js/fn/object/get-own-property-descriptor" { + var getOwnPropertyDescriptor: typeof core.Object.getOwnPropertyDescriptor; + export = getOwnPropertyDescriptor; +} +declare module "core-js/fn/object/get-own-property-descriptors" { + var getOwnPropertyDescriptors: typeof core.Object.getOwnPropertyDescriptors; + export = getOwnPropertyDescriptors; +} +declare module "core-js/fn/object/get-own-property-names" { + var getOwnPropertyNames: typeof core.Object.getOwnPropertyNames; + export = getOwnPropertyNames; +} +declare module "core-js/fn/object/get-own-property-symbols" { + var getOwnPropertySymbols: typeof core.Object.getOwnPropertySymbols; + export = getOwnPropertySymbols; +} +declare module "core-js/fn/object/get-prototype-of" { + var getPrototypeOf: typeof core.Object.getPrototypeOf; + export = getPrototypeOf; +} +declare module "core-js/fn/object/is" { + var is: typeof core.Object.is; + export = is; +} +declare module "core-js/fn/object/is-extensible" { + var isExtensible: typeof core.Object.isExtensible; + export = isExtensible; +} +declare module "core-js/fn/object/is-frozen" { + var isFrozen: typeof core.Object.isFrozen; + export = isFrozen; +} +declare module "core-js/fn/object/is-object" { + var isObject: typeof core.Object.isObject; + export = isObject; +} +declare module "core-js/fn/object/is-sealed" { + var isSealed: typeof core.Object.isSealed; + export = isSealed; +} +declare module "core-js/fn/object/keys" { + var keys: typeof core.Object.keys; + export = keys; +} +declare module "core-js/fn/object/make" { + var make: typeof core.Object.make; + export = make; +} +declare module "core-js/fn/object/prevent-extensions" { + var preventExtensions: typeof core.Object.preventExtensions; + export = preventExtensions; +} +declare module "core-js/fn/object/seal" { + var seal: typeof core.Object.seal; + export = seal; +} +declare module "core-js/fn/object/set-prototype-of" { + var setPrototypeOf: typeof core.Object.setPrototypeOf; + export = setPrototypeOf; +} +declare module "core-js/fn/object/values" { + var values: typeof core.Object.values; + export = values; +} +declare module "core-js/fn/reflect" { + var Reflect: typeof core.Reflect; + export = Reflect; +} +declare module "core-js/fn/reflect/apply" { + var apply: typeof core.Reflect.apply; + export = apply; +} +declare module "core-js/fn/reflect/construct" { + var construct: typeof core.Reflect.construct; + export = construct; +} +declare module "core-js/fn/reflect/define-property" { + var defineProperty: typeof core.Reflect.defineProperty; + export = defineProperty; +} +declare module "core-js/fn/reflect/delete-property" { + var deleteProperty: typeof core.Reflect.deleteProperty; + export = deleteProperty; +} +declare module "core-js/fn/reflect/enumerate" { + var enumerate: typeof core.Reflect.enumerate; + export = enumerate; +} +declare module "core-js/fn/reflect/get" { + var get: typeof core.Reflect.get; + export = get; +} +declare module "core-js/fn/reflect/get-own-property-descriptor" { + var getOwnPropertyDescriptor: typeof core.Reflect.getOwnPropertyDescriptor; + export = getOwnPropertyDescriptor; +} +declare module "core-js/fn/reflect/get-prototype-of" { + var getPrototypeOf: typeof core.Reflect.getPrototypeOf; + export = getPrototypeOf; +} +declare module "core-js/fn/reflect/has" { + var has: typeof core.Reflect.has; + export = has; +} +declare module "core-js/fn/reflect/is-extensible" { + var isExtensible: typeof core.Reflect.isExtensible; + export = isExtensible; +} +declare module "core-js/fn/reflect/own-keys" { + var ownKeys: typeof core.Reflect.ownKeys; + export = ownKeys; +} +declare module "core-js/fn/reflect/prevent-extensions" { + var preventExtensions: typeof core.Reflect.preventExtensions; + export = preventExtensions; +} +declare module "core-js/fn/reflect/set" { + var set: typeof core.Reflect.set; + export = set; +} +declare module "core-js/fn/reflect/set-prototype-of" { + var setPrototypeOf: typeof core.Reflect.setPrototypeOf; + export = setPrototypeOf; +} +declare module "core-js/fn/regexp" { + var RegExp: typeof core.RegExp; + export = RegExp; +} +declare module "core-js/fn/regexp/escape" { + var escape: typeof core.RegExp.escape; + export = escape; +} +declare module "core-js/fn/string" { + var String: typeof core.String; + export = String; +} +declare module "core-js/fn/string/at" { + var at: typeof core.String.at; + export = at; +} +declare module "core-js/fn/string/code-point-at" { + var codePointAt: typeof core.String.codePointAt; + export = codePointAt; +} +declare module "core-js/fn/string/ends-with" { + var endsWith: typeof core.String.endsWith; + export = endsWith; +} +declare module "core-js/fn/string/escape-html" { + var escapeHTML: typeof core.String.escapeHTML; + export = escapeHTML; +} +declare module "core-js/fn/string/from-code-point" { + var fromCodePoint: typeof core.String.fromCodePoint; + export = fromCodePoint; +} +declare module "core-js/fn/string/includes" { + var includes: typeof core.String.includes; + export = includes; +} +declare module "core-js/fn/string/lpad" { + var lpad: typeof core.String.lpad; + export = lpad; +} +declare module "core-js/fn/string/raw" { + var raw: typeof core.String.raw; + export = raw; +} +declare module "core-js/fn/string/repeat" { + var repeat: typeof core.String.repeat; + export default repeat; +} +declare module "core-js/fn/string/rpad" { + var rpad: typeof core.String.rpad; + export = rpad; +} +declare module "core-js/fn/string/starts-with" { + var startsWith: typeof core.String.startsWith; + export = startsWith; +} +declare module "core-js/fn/string/unescape-html" { + var unescapeHTML: typeof core.String.unescapeHTML; + export = unescapeHTML; +} +declare module "core-js/fn/symbol" { + var Symbol: typeof core.Symbol; + export = Symbol; +} +declare module "core-js/fn/symbol/for" { + var _for: typeof core.Symbol.for; + export = _for; +} +declare module "core-js/fn/symbol/has-instance" { + var hasInstance: typeof core.Symbol.hasInstance; + export = hasInstance; +} +declare module "core-js/fn/symbol/is-concat-spreadable" { + var isConcatSpreadable: typeof core.Symbol.isConcatSpreadable; + export = isConcatSpreadable; +} +declare module "core-js/fn/symbol/iterator" { + var iterator: typeof core.Symbol.iterator; + export = iterator; +} +declare module "core-js/fn/symbol/key-for" { + var keyFor: typeof core.Symbol.keyFor; + export = keyFor; +} +declare module "core-js/fn/symbol/match" { + var match: typeof core.Symbol.match; + export = match; +} +declare module "core-js/fn/symbol/replace" { + var replace: typeof core.Symbol.replace; + export = replace; +} +declare module "core-js/fn/symbol/search" { + var search: typeof core.Symbol.search; + export = search; +} +declare module "core-js/fn/symbol/species" { + var species: typeof core.Symbol.species; + export = species; +} +declare module "core-js/fn/symbol/split" { + var split: typeof core.Symbol.split; + export = split; +} +declare module "core-js/fn/symbol/to-primitive" { + var toPrimitive: typeof core.Symbol.toPrimitive; + export = toPrimitive; +} +declare module "core-js/fn/symbol/to-string-tag" { + var toStringTag: typeof core.Symbol.toStringTag; + export = toStringTag; +} +declare module "core-js/fn/symbol/unscopables" { + var unscopables: typeof core.Symbol.unscopables; + export = unscopables; +} +declare module "core-js/es5" { + export = core; +} +declare module "core-js/es6" { + export = core; +} +declare module "core-js/es6/array" { + var Array: typeof core.Array; + export = Array; +} +declare module "core-js/es6/function" { + var Function: typeof core.Function; + export = Function; +} +declare module "core-js/es6/map" { + var Map: typeof core.Map; + export = Map; +} +declare module "core-js/es6/math" { + var Math: typeof core.Math; + export = Math; +} +declare module "core-js/es6/number" { + var Number: typeof core.Number; + export = Number; +} +declare module "core-js/es6/object" { + var Object: typeof core.Object; + export = Object; +} +declare module "core-js/es6/promise" { + var Promise: typeof core.Promise; + export = Promise; +} +declare module "core-js/es6/reflect" { + var Reflect: typeof core.Reflect; + export = Reflect; +} +declare module "core-js/es6/regexp" { + var RegExp: typeof core.RegExp; + export = RegExp; +} +declare module "core-js/es6/set" { + var Set: typeof core.Set; + export = Set; +} +declare module "core-js/es6/string" { + var String: typeof core.String; + export = String; +} +declare module "core-js/es6/symbol" { + var Symbol: typeof core.Symbol; + export = Symbol; +} +declare module "core-js/es6/weak-map" { + var WeakMap: typeof core.WeakMap; + export = WeakMap; +} +declare module "core-js/es6/weak-set" { + var WeakSet: typeof core.WeakSet; + export = WeakSet; +} +declare module "core-js/es7" { + export = core; +} +declare module "core-js/es7/array" { + var Array: typeof core.Array; + export = Array; +} +declare module "core-js/es7/map" { + var Map: typeof core.Map; + export = Map; +} +declare module "core-js/es7/object" { + var Object: typeof core.Object; + export = Object; +} +declare module "core-js/es7/regexp" { + var RegExp: typeof core.RegExp; + export = RegExp; +} +declare module "core-js/es7/set" { + var Set: typeof core.Set; + export = Set; +} +declare module "core-js/es7/string" { + var String: typeof core.String; + export = String; +} +declare module "core-js/js" { + export = core; +} +declare module "core-js/js/array" { + var Array: typeof core.Array; + export = Array; +} +declare module "core-js/web" { + export = core; +} +declare module "core-js/web/dom" { + export = core; +} +declare module "core-js/web/immediate" { + export = core; +} +declare module "core-js/web/timers" { + export = core; +} +declare module "core-js/libary" { + export = core; +} +declare module "core-js/libary/shim" { + export = core; +} +declare module "core-js/libary/core" { + export = core; +} +declare module "core-js/libary/core/$for" { + import $for = core.$for; + export = $for; +} +declare module "core-js/libary/core/_" { + var _: typeof core._; + export = _; +} +declare module "core-js/libary/core/array" { + var Array: typeof core.Array; + export = Array; +} +declare module "core-js/libary/core/date" { + var Date: typeof core.Date; + export = Date; +} +declare module "core-js/libary/core/delay" { + var delay: typeof core.delay; + export = delay; +} +declare module "core-js/libary/core/dict" { + var Dict: typeof core.Dict; + export = Dict; +} +declare module "core-js/libary/core/function" { + var Function: typeof core.Function; + export = Function; +} +declare module "core-js/libary/core/global" { + var global: typeof core.global; + export = global; +} +declare module "core-js/libary/core/log" { + var log: typeof core.log; + export = log; +} +declare module "core-js/libary/core/number" { + var Number: typeof core.Number; + export = Number; +} +declare module "core-js/libary/core/object" { + var Object: typeof core.Object; + export = Object; +} +declare module "core-js/libary/core/string" { + var String: typeof core.String; + export = String; +} +declare module "core-js/libary/fn/$for" { + import $for = core.$for; + export = $for; +} +declare module "core-js/libary/fn/_" { + var _: typeof core._; + export = _; +} +declare module "core-js/libary/fn/clear-immediate" { + var clearImmediate: typeof core.clearImmediate; + export = clearImmediate; +} +declare module "core-js/libary/fn/delay" { + var delay: typeof core.delay; + export = delay; +} +declare module "core-js/libary/fn/dict" { + var Dict: typeof core.Dict; + export = Dict; +} +declare module "core-js/libary/fn/get-iterator" { + var getIterator: typeof core.getIterator; + export = getIterator; +} +declare module "core-js/libary/fn/global" { + var global: typeof core.global; + export = global; +} +declare module "core-js/libary/fn/is-iterable" { + var isIterable: typeof core.isIterable; + export = isIterable; +} +declare module "core-js/libary/fn/log" { + var log: typeof core.log; + export = log; +} +declare module "core-js/libary/fn/map" { + var Map: typeof core.Map; + export = Map; +} +declare module "core-js/libary/fn/promise" { + var Promise: typeof core.Promise; + export = Promise; +} +declare module "core-js/libary/fn/set" { + var Set: typeof core.Set; + export = Set; +} +declare module "core-js/libary/fn/set-immediate" { + var setImmediate: typeof core.setImmediate; + export = setImmediate; +} +declare module "core-js/libary/fn/set-interval" { + var setInterval: typeof core.setInterval; + export = setInterval; +} +declare module "core-js/libary/fn/set-timeout" { + var setTimeout: typeof core.setTimeout; + export = setTimeout; +} +declare module "core-js/libary/fn/weak-map" { + var WeakMap: typeof core.WeakMap; + export = WeakMap; +} +declare module "core-js/libary/fn/weak-set" { + var WeakSet: typeof core.WeakSet; + export = WeakSet; +} +declare module "core-js/libary/fn/array" { + var Array: typeof core.Array; + export = Array; +} +declare module "core-js/libary/fn/array/concat" { + var concat: typeof core.Array.concat; + export = concat; +} +declare module "core-js/libary/fn/array/copy-within" { + var copyWithin: typeof core.Array.copyWithin; + export = copyWithin; +} +declare module "core-js/libary/fn/array/entries" { + var entries: typeof core.Array.entries; + export = entries; +} +declare module "core-js/libary/fn/array/every" { + var every: typeof core.Array.every; + export = every; +} +declare module "core-js/libary/fn/array/fill" { + var fill: typeof core.Array.fill; + export = fill; +} +declare module "core-js/libary/fn/array/filter" { + var filter: typeof core.Array.filter; + export = filter; +} +declare module "core-js/libary/fn/array/find" { + var find: typeof core.Array.find; + export = find; +} +declare module "core-js/libary/fn/array/find-index" { + var findIndex: typeof core.Array.findIndex; + export = findIndex; +} +declare module "core-js/libary/fn/array/for-each" { + var forEach: typeof core.Array.forEach; + export = forEach; +} +declare module "core-js/libary/fn/array/from" { + var from: typeof core.Array.from; + export = from; +} +declare module "core-js/libary/fn/array/includes" { + var includes: typeof core.Array.includes; + export = includes; +} +declare module "core-js/libary/fn/array/index-of" { + var indexOf: typeof core.Array.indexOf; + export = indexOf; +} +declare module "core-js/libary/fn/array/join" { + var join: typeof core.Array.join; + export = join; +} +declare module "core-js/libary/fn/array/keys" { + var keys: typeof core.Array.keys; + export = keys; +} +declare module "core-js/libary/fn/array/last-index-of" { + var lastIndexOf: typeof core.Array.lastIndexOf; + export = lastIndexOf; +} +declare module "core-js/libary/fn/array/map" { + var map: typeof core.Array.map; + export = map; +} +declare module "core-js/libary/fn/array/of" { + var of: typeof core.Array.of; + export = of; +} +declare module "core-js/libary/fn/array/pop" { + var pop: typeof core.Array.pop; + export = pop; +} +declare module "core-js/libary/fn/array/push" { + var push: typeof core.Array.push; + export = push; +} +declare module "core-js/libary/fn/array/reduce" { + var reduce: typeof core.Array.reduce; + export = reduce; +} +declare module "core-js/libary/fn/array/reduce-right" { + var reduceRight: typeof core.Array.reduceRight; + export = reduceRight; +} +declare module "core-js/libary/fn/array/reverse" { + var reverse: typeof core.Array.reverse; + export = reverse; +} +declare module "core-js/libary/fn/array/shift" { + var shift: typeof core.Array.shift; + export = shift; +} +declare module "core-js/libary/fn/array/slice" { + var slice: typeof core.Array.slice; + export = slice; +} +declare module "core-js/libary/fn/array/some" { + var some: typeof core.Array.some; + export = some; +} +declare module "core-js/libary/fn/array/sort" { + var sort: typeof core.Array.sort; + export = sort; +} +declare module "core-js/libary/fn/array/splice" { + var splice: typeof core.Array.splice; + export = splice; +} +declare module "core-js/libary/fn/array/turn" { + var turn: typeof core.Array.turn; + export = turn; +} +declare module "core-js/libary/fn/array/unshift" { + var unshift: typeof core.Array.unshift; + export = unshift; +} +declare module "core-js/libary/fn/array/values" { + var values: typeof core.Array.values; + export = values; +} +declare module "core-js/libary/fn/date" { + var Date: typeof core.Date; + export = Date; +} +declare module "core-js/libary/fn/date/add-locale" { + var addLocale: typeof core.addLocale; + export = addLocale; +} +declare module "core-js/libary/fn/date/format" { + var format: typeof core.Date.format; + export = format; +} +declare module "core-js/libary/fn/date/formatUTC" { + var formatUTC: typeof core.Date.formatUTC; + export = formatUTC; +} +declare module "core-js/libary/fn/function" { + var Function: typeof core.Function; + export = Function; +} +declare module "core-js/libary/fn/function/has-instance" { + var hasInstance: (value: any) => boolean; + export = hasInstance; +} +declare module "core-js/libary/fn/function/name" { +} +declare module "core-js/libary/fn/function/part" { + var part: typeof core.Function.part; + export = part; +} +declare module "core-js/libary/fn/math" { + var Math: typeof core.Math; + export = Math; +} +declare module "core-js/libary/fn/math/acosh" { + var acosh: typeof core.Math.acosh; + export = acosh; +} +declare module "core-js/libary/fn/math/asinh" { + var asinh: typeof core.Math.asinh; + export = asinh; +} +declare module "core-js/libary/fn/math/atanh" { + var atanh: typeof core.Math.atanh; + export = atanh; +} +declare module "core-js/libary/fn/math/cbrt" { + var cbrt: typeof core.Math.cbrt; + export = cbrt; +} +declare module "core-js/libary/fn/math/clz32" { + var clz32: typeof core.Math.clz32; + export = clz32; +} +declare module "core-js/libary/fn/math/cosh" { + var cosh: typeof core.Math.cosh; + export = cosh; +} +declare module "core-js/libary/fn/math/expm1" { + var expm1: typeof core.Math.expm1; + export = expm1; +} +declare module "core-js/libary/fn/math/fround" { + var fround: typeof core.Math.fround; + export = fround; +} +declare module "core-js/libary/fn/math/hypot" { + var hypot: typeof core.Math.hypot; + export = hypot; +} +declare module "core-js/libary/fn/math/imul" { + var imul: typeof core.Math.imul; + export = imul; +} +declare module "core-js/libary/fn/math/log10" { + var log10: typeof core.Math.log10; + export = log10; +} +declare module "core-js/libary/fn/math/log1p" { + var log1p: typeof core.Math.log1p; + export = log1p; +} +declare module "core-js/libary/fn/math/log2" { + var log2: typeof core.Math.log2; + export = log2; +} +declare module "core-js/libary/fn/math/sign" { + var sign: typeof core.Math.sign; + export = sign; +} +declare module "core-js/libary/fn/math/sinh" { + var sinh: typeof core.Math.sinh; + export = sinh; +} +declare module "core-js/libary/fn/math/tanh" { + var tanh: typeof core.Math.tanh; + export = tanh; +} +declare module "core-js/libary/fn/math/trunc" { + var trunc: typeof core.Math.trunc; + export = trunc; +} +declare module "core-js/libary/fn/number" { + var Number: typeof core.Number; + export = Number; +} +declare module "core-js/libary/fn/number/epsilon" { + var EPSILON: typeof core.Number.EPSILON; + export = EPSILON; +} +declare module "core-js/libary/fn/number/is-finite" { + var isFinite: typeof core.Number.isFinite; + export = isFinite; +} +declare module "core-js/libary/fn/number/is-integer" { + var isInteger: typeof core.Number.isInteger; + export = isInteger; +} +declare module "core-js/libary/fn/number/is-nan" { + var isNaN: typeof core.Number.isNaN; + export = isNaN; +} +declare module "core-js/libary/fn/number/is-safe-integer" { + var isSafeInteger: typeof core.Number.isSafeInteger; + export = isSafeInteger; +} +declare module "core-js/libary/fn/number/max-safe-integer" { + var MAX_SAFE_INTEGER: typeof core.Number.MAX_SAFE_INTEGER; + export = MAX_SAFE_INTEGER; +} +declare module "core-js/libary/fn/number/min-safe-interger" { + var MIN_SAFE_INTEGER: typeof core.Number.MIN_SAFE_INTEGER; + export = MIN_SAFE_INTEGER; +} +declare module "core-js/libary/fn/number/parse-float" { + var parseFloat: typeof core.Number.parseFloat; + export = parseFloat; +} +declare module "core-js/libary/fn/number/parse-int" { + var parseInt: typeof core.Number.parseInt; + export = parseInt; +} +declare module "core-js/libary/fn/number/random" { + var random: typeof core.Number.random; + export = random; +} +declare module "core-js/libary/fn/object" { + var Object: typeof core.Object; + export = Object; +} +declare module "core-js/libary/fn/object/assign" { + var assign: typeof core.Object.assign; + export = assign; +} +declare module "core-js/libary/fn/object/classof" { + var classof: typeof core.Object.classof; + export = classof; +} +declare module "core-js/libary/fn/object/create" { + var create: typeof core.Object.create; + export = create; +} +declare module "core-js/libary/fn/object/define" { + var define: typeof core.Object.define; + export = define; +} +declare module "core-js/libary/fn/object/define-properties" { + var defineProperties: typeof core.Object.defineProperties; + export = defineProperties; +} +declare module "core-js/libary/fn/object/define-property" { + var defineProperty: typeof core.Object.defineProperty; + export = defineProperty; +} +declare module "core-js/libary/fn/object/entries" { + var entries: typeof core.Object.entries; + export = entries; +} +declare module "core-js/libary/fn/object/freeze" { + var freeze: typeof core.Object.freeze; + export = freeze; +} +declare module "core-js/libary/fn/object/get-own-property-descriptor" { + var getOwnPropertyDescriptor: typeof core.Object.getOwnPropertyDescriptor; + export = getOwnPropertyDescriptor; +} +declare module "core-js/libary/fn/object/get-own-property-descriptors" { + var getOwnPropertyDescriptors: typeof core.Object.getOwnPropertyDescriptors; + export = getOwnPropertyDescriptors; +} +declare module "core-js/libary/fn/object/get-own-property-names" { + var getOwnPropertyNames: typeof core.Object.getOwnPropertyNames; + export = getOwnPropertyNames; +} +declare module "core-js/libary/fn/object/get-own-property-symbols" { + var getOwnPropertySymbols: typeof core.Object.getOwnPropertySymbols; + export = getOwnPropertySymbols; +} +declare module "core-js/libary/fn/object/get-prototype-of" { + var getPrototypeOf: typeof core.Object.getPrototypeOf; + export = getPrototypeOf; +} +declare module "core-js/libary/fn/object/is" { + var is: typeof core.Object.is; + export = is; +} +declare module "core-js/libary/fn/object/is-extensible" { + var isExtensible: typeof core.Object.isExtensible; + export = isExtensible; +} +declare module "core-js/libary/fn/object/is-frozen" { + var isFrozen: typeof core.Object.isFrozen; + export = isFrozen; +} +declare module "core-js/libary/fn/object/is-object" { + var isObject: typeof core.Object.isObject; + export = isObject; +} +declare module "core-js/libary/fn/object/is-sealed" { + var isSealed: typeof core.Object.isSealed; + export = isSealed; +} +declare module "core-js/libary/fn/object/keys" { + var keys: typeof core.Object.keys; + export = keys; +} +declare module "core-js/libary/fn/object/make" { + var make: typeof core.Object.make; + export = make; +} +declare module "core-js/libary/fn/object/prevent-extensions" { + var preventExtensions: typeof core.Object.preventExtensions; + export = preventExtensions; +} +declare module "core-js/libary/fn/object/seal" { + var seal: typeof core.Object.seal; + export = seal; +} +declare module "core-js/libary/fn/object/set-prototype-of" { + var setPrototypeOf: typeof core.Object.setPrototypeOf; + export = setPrototypeOf; +} +declare module "core-js/libary/fn/object/values" { + var values: typeof core.Object.values; + export = values; +} +declare module "core-js/libary/fn/reflect" { + var Reflect: typeof core.Reflect; + export = Reflect; +} +declare module "core-js/libary/fn/reflect/apply" { + var apply: typeof core.Reflect.apply; + export = apply; +} +declare module "core-js/libary/fn/reflect/construct" { + var construct: typeof core.Reflect.construct; + export = construct; +} +declare module "core-js/libary/fn/reflect/define-property" { + var defineProperty: typeof core.Reflect.defineProperty; + export = defineProperty; +} +declare module "core-js/libary/fn/reflect/delete-property" { + var deleteProperty: typeof core.Reflect.deleteProperty; + export = deleteProperty; +} +declare module "core-js/libary/fn/reflect/enumerate" { + var enumerate: typeof core.Reflect.enumerate; + export = enumerate; +} +declare module "core-js/libary/fn/reflect/get" { + var get: typeof core.Reflect.get; + export = get; +} +declare module "core-js/libary/fn/reflect/get-own-property-descriptor" { + var getOwnPropertyDescriptor: typeof core.Reflect.getOwnPropertyDescriptor; + export = getOwnPropertyDescriptor; +} +declare module "core-js/libary/fn/reflect/get-prototype-of" { + var getPrototypeOf: typeof core.Reflect.getPrototypeOf; + export = getPrototypeOf; +} +declare module "core-js/libary/fn/reflect/has" { + var has: typeof core.Reflect.has; + export = has; +} +declare module "core-js/libary/fn/reflect/is-extensible" { + var isExtensible: typeof core.Reflect.isExtensible; + export = isExtensible; +} +declare module "core-js/libary/fn/reflect/own-keys" { + var ownKeys: typeof core.Reflect.ownKeys; + export = ownKeys; +} +declare module "core-js/libary/fn/reflect/prevent-extensions" { + var preventExtensions: typeof core.Reflect.preventExtensions; + export = preventExtensions; +} +declare module "core-js/libary/fn/reflect/set" { + var set: typeof core.Reflect.set; + export = set; +} +declare module "core-js/libary/fn/reflect/set-prototype-of" { + var setPrototypeOf: typeof core.Reflect.setPrototypeOf; + export = setPrototypeOf; +} +declare module "core-js/libary/fn/regexp" { + var RegExp: typeof core.RegExp; + export = RegExp; +} +declare module "core-js/libary/fn/regexp/escape" { + var escape: typeof core.RegExp.escape; + export = escape; +} +declare module "core-js/libary/fn/string" { + var String: typeof core.String; + export = String; +} +declare module "core-js/libary/fn/string/at" { + var at: typeof core.String.at; + export = at; +} +declare module "core-js/libary/fn/string/code-point-at" { + var codePointAt: typeof core.String.codePointAt; + export = codePointAt; +} +declare module "core-js/libary/fn/string/ends-with" { + var endsWith: typeof core.String.endsWith; + export = endsWith; +} +declare module "core-js/libary/fn/string/escape-html" { + var escapeHTML: typeof core.String.escapeHTML; + export = escapeHTML; +} +declare module "core-js/libary/fn/string/from-code-point" { + var fromCodePoint: typeof core.String.fromCodePoint; + export = fromCodePoint; +} +declare module "core-js/libary/fn/string/includes" { + var includes: typeof core.String.includes; + export = includes; +} +declare module "core-js/libary/fn/string/lpad" { + var lpad: typeof core.String.lpad; + export = lpad; +} +declare module "core-js/libary/fn/string/raw" { + var raw: typeof core.String.raw; + export = raw; +} +declare module "core-js/libary/fn/string/repeat" { + var repeat: typeof core.String.repeat; + export = repeat; +} +declare module "core-js/libary/fn/string/rpad" { + var rpad: typeof core.String.rpad; + export = rpad; +} +declare module "core-js/libary/fn/string/starts-with" { + var startsWith: typeof core.String.startsWith; + export = startsWith; +} +declare module "core-js/libary/fn/string/unescape-html" { + var unescapeHTML: typeof core.String.unescapeHTML; + export = unescapeHTML; +} +declare module "core-js/libary/fn/symbol" { + var Symbol: typeof core.Symbol; + export = Symbol; +} +declare module "core-js/libary/fn/symbol/for" { + var _for: typeof core.Symbol.for; + export = _for; +} +declare module "core-js/libary/fn/symbol/has-instance" { + var hasInstance: typeof core.Symbol.hasInstance; + export = hasInstance; +} +declare module "core-js/libary/fn/symbol/is-concat-spreadable" { + var isConcatSpreadable: typeof core.Symbol.isConcatSpreadable; + export = isConcatSpreadable; +} +declare module "core-js/libary/fn/symbol/iterator" { + var iterator: typeof core.Symbol.iterator; + export = iterator; +} +declare module "core-js/libary/fn/symbol/key-for" { + var keyFor: typeof core.Symbol.keyFor; + export = keyFor; +} +declare module "core-js/libary/fn/symbol/match" { + var match: typeof core.Symbol.match; + export = match; +} +declare module "core-js/libary/fn/symbol/replace" { + var replace: typeof core.Symbol.replace; + export = replace; +} +declare module "core-js/libary/fn/symbol/search" { + var search: typeof core.Symbol.search; + export = search; +} +declare module "core-js/libary/fn/symbol/species" { + var species: typeof core.Symbol.species; + export = species; +} +declare module "core-js/libary/fn/symbol/split" { + var split: typeof core.Symbol.split; + export = split; +} +declare module "core-js/libary/fn/symbol/to-primitive" { + var toPrimitive: typeof core.Symbol.toPrimitive; + export = toPrimitive; +} +declare module "core-js/libary/fn/symbol/to-string-tag" { + var toStringTag: typeof core.Symbol.toStringTag; + export = toStringTag; +} +declare module "core-js/libary/fn/symbol/unscopables" { + var unscopables: typeof core.Symbol.unscopables; + export = unscopables; +} +declare module "core-js/libary/es5" { + export = core; +} +declare module "core-js/libary/es6" { + export = core; +} +declare module "core-js/libary/es6/array" { + var Array: typeof core.Array; + export = Array; +} +declare module "core-js/libary/es6/function" { + var Function: typeof core.Function; + export = Function; +} +declare module "core-js/libary/es6/map" { + var Map: typeof core.Map; + export = Map; +} +declare module "core-js/libary/es6/math" { + var Math: typeof core.Math; + export = Math; +} +declare module "core-js/libary/es6/number" { + var Number: typeof core.Number; + export = Number; +} +declare module "core-js/libary/es6/object" { + var Object: typeof core.Object; + export = Object; +} +declare module "core-js/libary/es6/promise" { + var Promise: typeof core.Promise; + export = Promise; +} +declare module "core-js/libary/es6/reflect" { + var Reflect: typeof core.Reflect; + export = Reflect; +} +declare module "core-js/libary/es6/regexp" { + var RegExp: typeof core.RegExp; + export = RegExp; +} +declare module "core-js/libary/es6/set" { + var Set: typeof core.Set; + export = Set; +} +declare module "core-js/libary/es6/string" { + var String: typeof core.String; + export = String; +} +declare module "core-js/libary/es6/symbol" { + var Symbol: typeof core.Symbol; + export = Symbol; +} +declare module "core-js/libary/es6/weak-map" { + var WeakMap: typeof core.WeakMap; + export = WeakMap; +} +declare module "core-js/libary/es6/weak-set" { + var WeakSet: typeof core.WeakSet; + export = WeakSet; +} +declare module "core-js/libary/es7" { + export = core; +} +declare module "core-js/libary/es7/array" { + var Array: typeof core.Array; + export = Array; +} +declare module "core-js/libary/es7/map" { + var Map: typeof core.Map; + export = Map; +} +declare module "core-js/libary/es7/object" { + var Object: typeof core.Object; + export = Object; +} +declare module "core-js/libary/es7/regexp" { + var RegExp: typeof core.RegExp; + export = RegExp; +} +declare module "core-js/libary/es7/set" { + var Set: typeof core.Set; + export = Set; +} +declare module "core-js/libary/es7/string" { + var String: typeof core.String; + export = String; +} +declare module "core-js/libary/js" { + export = core; +} +declare module "core-js/libary/js/array" { + var Array: typeof core.Array; + export = Array; +} +declare module "core-js/libary/web" { + export = core; +} +declare module "core-js/libary/web/dom" { + export = core; +} +declare module "core-js/libary/web/immediate" { + export = core; +} +declare module "core-js/libary/web/timers" { + export = core; +} diff --git a/jspm/src/greeter.ts b/jspm/src/greeter.ts new file mode 100644 index 0000000..5fa4cc2 --- /dev/null +++ b/jspm/src/greeter.ts @@ -0,0 +1,23 @@ +import repeat from "core-js/fn/string/repeat"; + +export class Greeter { + element: HTMLElement; + span: HTMLElement; + timerToken: number; + + constructor(element: HTMLElement) { + this.element = element; + this.element.innerText += "The time is: "; + this.span = document.createElement('span'); + this.element.appendChild(this.span); + this.span.innerText = new Date().toUTCString(); + } + + start() { + this.timerToken = setInterval(() => this.span.innerText = `"${repeat(new Date().toUTCString() + " ", 2)}"`, 500); + } + + stop() { + clearTimeout(this.timerToken); + } +} diff --git a/jspm/tsconfig.json b/jspm/tsconfig.json new file mode 100644 index 0000000..9be4eaf --- /dev/null +++ b/jspm/tsconfig.json @@ -0,0 +1,9 @@ +{ + "compilerOptions": { + "module": "system", + "sourceMap": true + }, + "exclude": [ + "jspm_packages" + ] +} \ No newline at end of file diff --git a/jsx/.gitignore b/jsx/.gitignore new file mode 100644 index 0000000..88c42ff --- /dev/null +++ b/jsx/.gitignore @@ -0,0 +1,2 @@ +bin/* +node_modules/* diff --git a/jsx/README.md b/jsx/README.md new file mode 100644 index 0000000..1ab3bd1 --- /dev/null +++ b/jsx/README.md @@ -0,0 +1,20 @@ +# jsx-demo + +## Overview +A demo project for showing off JSX in TypeScript + +## Install dependencies +``` +npm install +``` + +## Compile +``` +npm run build +``` + +## Start http server +``` +npm start +``` + diff --git a/jsx/index.html b/jsx/index.html new file mode 100644 index 0000000..cf42fc2 --- /dev/null +++ b/jsx/index.html @@ -0,0 +1,11 @@ + + + + JSX and TypeScript + + + + +
+ + diff --git a/jsx/package-lock.json b/jsx/package-lock.json new file mode 100644 index 0000000..5474654 --- /dev/null +++ b/jsx/package-lock.json @@ -0,0 +1,13 @@ +{ + "name": "jsx-demo", + "version": "0.0.1", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "jquery": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/jquery/-/jquery-3.3.1.tgz", + "integrity": "sha512-Ubldcmxp5np52/ENotGxlLe6aGMvmF4R8S6tZjsP6Knsaxd/xp3Zrh50cG93lR6nPXyUFwzN3ZSOQI0wRJNdGg==" + } + } +} diff --git a/jsx/package.json b/jsx/package.json new file mode 100644 index 0000000..8c62110 --- /dev/null +++ b/jsx/package.json @@ -0,0 +1,39 @@ +{ + "name": "jsx-demo", + "version": "0.0.1", + "description": "JSX in TypeScript Demo Project", + "main": "app.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "build": "node node_modules/typescript/bin/tsc", + "start": "node node_modules/http-server/bin/http-server -o" + }, + "repository": { + "type": "git", + "url": "https://github.com/Microsoft/TypeScriptSamples.git" + }, + "keywords": [ + "jsx", + "tsx", + "typescript", + "ts", + "react" + ], + "author": "Ryan Cavanaugh (Microsoft)", + "license": "Apache", + "bugs": { + "url": "https://github.com/Microsoft/TypeScriptSamples/issues" + }, + "homepage": "https://github.com/Microsoft/TypeScriptSamples", + "devDependencies": { + "typescript": "latest", + "http-server": "0.8.0", + "@types/react-dom": "^15", + "@types/react": "^15" + }, + "dependencies": { + "react": "^15.6.1", + "react-dom": "^15.6.1", + "requirejs": "^2.1.20" + } +} diff --git a/jsx/require-config.js b/jsx/require-config.js new file mode 100644 index 0000000..27bb21c --- /dev/null +++ b/jsx/require-config.js @@ -0,0 +1,7 @@ +requirejs.config({ + paths: { + "react": ['/node_modules/react/dist/react'], + "react-dom": ['/node_modules/react-dom/dist/react-dom'], + "jquery": ['/node_modules/jquery/dist/jquery'] + } +}); diff --git a/jsx/src/app.tsx b/jsx/src/app.tsx new file mode 100644 index 0000000..13a5613 --- /dev/null +++ b/jsx/src/app.tsx @@ -0,0 +1,21 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import {Greeter as Greetifier, GreeterProps as GreeterProps} from 'greeter'; + +function getRandomGreeting() { + switch (Math.floor(Math.random() * 4)) { + case 0: return 'Hello'; + case 1: return 'Howdy'; + case 2: return 'Greetings to you'; + case 3: return 'Hail'; + } +} + +(() => { + let props: GreeterProps = { + whomToGreet: 'world!', + }; + + ReactDOM.render(, $('#output').get(0)); +})(); + diff --git a/jsx/src/greeter.tsx b/jsx/src/greeter.tsx new file mode 100644 index 0000000..dc37a1f --- /dev/null +++ b/jsx/src/greeter.tsx @@ -0,0 +1,23 @@ +import * as React from 'react'; + +export interface GreeterProps extends React.Props { + whomToGreet: string; + greeting?: string | (() => string); +} + +export class Greeter extends React.Component { + render() { + let g = this.props.greeting; + + let greeting = 'Hello'; + + if (typeof g === 'string') { + greeting = g; + } + else if (g) { + greeting = g(); + } + + return
{greeting}, {this.props.whomToGreet}
; + } +} diff --git a/jsx/tsconfig.json b/jsx/tsconfig.json new file mode 100644 index 0000000..83479c8 --- /dev/null +++ b/jsx/tsconfig.json @@ -0,0 +1,10 @@ +{ + "compilerOptions": { + "jsx": "react", + "outDir": "bin", + "module": "amd" + }, + "exclude": [ + "node_modules" + ] +} diff --git a/mankala/Base.ts b/mankala/Base.ts index 69e4911..f80ad25 100644 --- a/mankala/Base.ts +++ b/mankala/Base.ts @@ -1,72 +1,68 @@ -/// - -module Base { - export interface IList { - isHead: boolean; - next: IList; - prev: IList; - insertAfter(entry: IList): IList; - insertBefore(entry: IList): IList; - item(); - empty(): boolean; - } - - export class List implements IList { - next: IList; - prev: IList; - - constructor (public isHead: boolean, public data) { } - - item() { - return this.data; - } - - empty(): boolean { - return this.next == this; - } - - insertAfter(entry: IList): IList { - entry.next = this.next; - entry.prev = this; - this.next = entry; - entry.next.prev = entry; - return (entry); - } - - insertBefore(entry: IList): IList { - this.prev.next = entry; - entry.next = this; - entry.prev = this.prev; - this.prev = entry; - return entry; - } - } - - export function listMakeEntry(data): IList { - var entry: List = new List(false, data); - entry.prev = entry; - entry.next = entry; - return entry; - } - - export function listMakeHead(): IList { - var entry: List = new List(true, null); - entry.prev = entry; - entry.next = entry; - return entry; - } - - export function listRemove(entry: IList): IList { - if (entry == null) { - return null; - } - else if (entry.isHead) { - return null; - } - else { - entry.next.prev = entry.prev; - entry.prev.next = entry.next; - } - return (entry); - } -} +/// + +namespace Base { + export interface IList { + isHead: boolean; + next: IList; + prev: IList; + data: T; + insertAfter(entry: IList): IList; + insertBefore(entry: IList): IList; + empty(): boolean; + } + + export class List implements IList { + next: IList; + prev: IList; + + constructor(public isHead: boolean, public data: T) { } + + empty(): boolean { + return this.next == this; + } + + insertAfter(entry: IList): IList { + entry.next = this.next; + entry.prev = this; + this.next = entry; + entry.next.prev = entry; + return (entry); + } + + insertBefore(entry: IList): IList { + this.prev.next = entry; + entry.next = this; + entry.prev = this.prev; + this.prev = entry; + return entry; + } + } + + export function listMakeEntry(data: T): IList { + var entry: List = new List(false, data); + entry.prev = entry; + entry.next = entry; + return entry; + } + + export function listMakeHead(): IList { + var entry: List = new List(true, null); + entry.prev = entry; + entry.next = entry; + return entry; + } + + export function listRemove(entry: IList): IList { + if (entry == null) { + return null; + } + else if (entry.isHead) { + return null; + } + else { + entry.next.prev = entry.prev; + entry.prev.next = entry.next; + } + return (entry); + } +} diff --git a/mankala/Driver.ts b/mankala/Driver.ts index 4549c93..091005b 100644 --- a/mankala/Driver.ts +++ b/mankala/Driver.ts @@ -1,10 +1,10 @@ -/// -/// -/// -/// -/// - -if (!this.document) { - var game = new Mankala.Game(); - game.test(); -} +/// +/// +/// +/// +/// + +if (!this.document) { + var game = new Mankala.Game(); + game.test(); +} diff --git a/mankala/Features.ts b/mankala/Features.ts index 395443d..0b32b3d 100644 --- a/mankala/Features.ts +++ b/mankala/Features.ts @@ -1,29 +1,29 @@ -/// - -module Mankala { - export class Features { - public turnContinues = false; - public seedStoredCount = 0; - public capturedCount = 0; - public spaceCaptured = NoSpace; - - public clear() { - this.turnContinues = false; - this.seedStoredCount = 0; - this.capturedCount = 0; - this.spaceCaptured = NoSpace; - } - - public toString() { - var stringBuilder = ""; - if (this.turnContinues) { - stringBuilder += " turn continues,"; - } - stringBuilder += " stores " + this.seedStoredCount; - if (this.capturedCount > 0) { - stringBuilder += " captures " + this.capturedCount + " from space " + this.spaceCaptured; - } - return stringBuilder; - } - } -} +/// + +namespace Mankala { + export class Features { + public turnContinues = false; + public seedStoredCount = 0; + public capturedCount = 0; + public spaceCaptured = NoSpace; + + public clear() { + this.turnContinues = false; + this.seedStoredCount = 0; + this.capturedCount = 0; + this.spaceCaptured = NoSpace; + } + + public toString() { + var stringBuilder = ""; + if (this.turnContinues) { + stringBuilder += " turn continues,"; + } + stringBuilder += " stores " + this.seedStoredCount; + if (this.capturedCount > 0) { + stringBuilder += " captures " + this.capturedCount + " from space " + this.spaceCaptured; + } + return stringBuilder; + } + } +} diff --git a/mankala/Game.ts b/mankala/Game.ts index acbb8b2..a678855 100644 --- a/mankala/Game.ts +++ b/mankala/Game.ts @@ -1,244 +1,240 @@ -/// - -module Mankala { - export var NoSpace = -1; - export var homeSpaces = [[0, 1, 2, 3, 4, 5], - [7, 8, 9, 10, 11, 12]]; - export var firstHomeSpace = [0, 7]; - export var lastHomeSpace = [5, 12]; - export var capturedSpaces = [12, 11, 10, 9, 8, 7, NoSpace, 5, 4, 3, 2, 1, 0, NoSpace]; - export var NoScore = 31; - export var NoMove = -1; - - export interface IPositionList extends Base.IList { - data: Position; - push(pos: Position); - pop(): Position; - } - - function pushPosition(pos: Position, l: IPositionList) { - l.insertAfter(Base.listMakeEntry(pos)); - } - - function popPosition(l: IPositionList) { - var entry: IPositionList = Base.listRemove(l.next); - if (entry != null) { - return entry.data; - } else { - return null; - } - } - - export function testBrowser() { - var game = new Game(); - game.interactive(); - var bod = document.getElementById("bod"); - bod.onresize = function() { - game.resize(); - } - } - - export class Game { - private position = new DisplayPosition([3, 3, 3, 3, 3, 3, 0, 3, 3, 3, 3, 3, 3, 0], NoMove, 0); - private prevConfig: SeedCoords[][]; - private q: IPositionList = null; - private scores: number[] = null; - private positionCount = 0; - private moveCount = 0; - private isInteractive = false; - - private features = new Features(); - private nextSeedCounts: number[] = new Array(14); - private bod: Element; - private boardElm: Element = null; - - public resize() { - if (this.boardElm != null) { - this.bod.removeChild(this.boardElm); - } - this.showMove(); - } - - private step(): boolean { - var move = this.findMove(); - if (move != NoMove) { - this.position.move(move, this.nextSeedCounts, this.features); - this.position = new DisplayPosition(this.nextSeedCounts.slice(0), NoMove, - this.features.turnContinues ? this.position.turn : 1 - this.position.turn); - this.position.config = this.prevConfig; - if ((!this.isInteractive) || (this.position.turn == 1)) { - this.setStep(); - } - return true; - } - return false; - } - - private setStep() { - setTimeout(/*function()*/ () => { - if (!this.step()) { - this.finish(); - } - this.bod.removeChild(this.boardElm); - this.showMove(); - }, 1000); - } - - private finish() { - var sum = 0; - var otherSpaces = homeSpaces[1 - this.position.turn]; - for (var k = 0, len = otherSpaces.length; k < len; k++) { - sum += this.position.seedCounts[otherSpaces[k]]; - this.position.seedCounts[otherSpaces[k]] = 0; - } - this.position.seedCounts[storeHouses[this.position.turn]] += sum; - } - - private auto() { - // initialize - this.bod = document.getElementById("bod"); - this.showMove(); - // run with timeout - this.setStep(); - } - - private showMove(): void { - var hsc = document.getElementById("humscore"); - var csc = document.getElementById("compscore"); - - var g = this; - if (!this.isInteractive) { - g = null; - } - this.boardElm = this.position.toCircleSVG(g); - this.prevConfig = this.position.config; - hsc.innerText = this.position.seedCounts[storeHouses[0]] + - ((this.position.turn == 0) ? " <-Turn" : ""); - csc.innerText = this.position.seedCounts[storeHouses[1]] + - ((this.position.turn == 1) ? " <-Turn" : ""); - this.bod.appendChild(this.boardElm); - } - - public humanMove(seed: number) { - if (this.position.turn == 0) { - this.position.move(seed, this.nextSeedCounts, this.features); - this.position = new DisplayPosition(this.nextSeedCounts.slice(0), NoMove, - this.features.turnContinues ? this.position.turn : 1 - this.position.turn); - this.position.config = this.prevConfig; - this.bod.removeChild(this.boardElm); - this.showMove(); - if (this.position.turn == 1) { - this.setStep(); - } - } - } - - public interactive() { - this.isInteractive = true; - this.bod = document.getElementById("bod"); - this.showMove(); - } - - private expand(curPos: Position, move: number, - startMove: number, nextSeedCounts: number[]) { - var features = new Features(); - if (curPos.move(move, nextSeedCounts, features)) { - var pos = new Position(nextSeedCounts.slice(0), startMove, curPos.turn); - this.positionCount++; - if (!features.turnContinues) { - pos.turn = 1 - pos.turn; - } - var score = pos.score(); - if (this.scores[startMove] == NoScore) { - this.scores[startMove] = score; - } - else { - this.scores[startMove] += score; - } - pushPosition(pos, this.q); - return true; - } - return false; - } - - private findMove() { - var timeStart = new Date().getTime(); - this.q = Base.listMakeHead(); - this.scores = [NoScore, NoScore, NoScore, NoScore, NoScore, NoScore]; - pushPosition(this.position, this.q); - var deltaTime = 0; - var moves = homeSpaces[this.position.turn]; - var nextSeedCounts: number[] = new Array(14); - var movePossible = false; - while ((!this.q.empty()) && (deltaTime < 500)) { - var firstPos = popPosition(this.q); - for (var i = 0, len = moves.length; i < len; i++) { - var startMove = firstPos.startMove; - if (startMove == NoMove) { - startMove = i; - } - if (this.expand(firstPos, moves[i], startMove, nextSeedCounts)) { - movePossible = true; - } - } - deltaTime = new Date().getTime() - timeStart; - } - if (movePossible) { - var bestScore = -100; - var bestMove = NoMove; - for (var j = 0, scoresLen = this.scores.length; j < scoresLen; j++) { - if ((this.scores[j] != NoScore) && ((this.scores[j] > bestScore) || (bestMove == NoMove))) { - bestScore = this.scores[j]; - bestMove = j; - } - } - if (bestMove != NoMove) { - return moves[bestMove]; - } else { - return NoMove; - } - } - return NoMove; - } - - public test() { - var features = new Features(); - var nextSeedCounts: number[] = new Array(14); - WScript.Echo("position: ") - WScript.Echo(this.position.seedCounts.slice(0, 7)); - WScript.Echo(this.position.seedCounts.slice(7)); - do { - var move = this.findMove(); - if (move == NoMove) { - // TODO: capture rest of other side - } else { - this.moveCount++; - WScript.Echo(this.position.turn + " moves seeds in space " + move); - this.position.move(move, nextSeedCounts, features); - WScript.Echo(features.toString()); - this.position = new DisplayPosition(nextSeedCounts.slice(0), NoMove, - features.turnContinues ? this.position.turn : 1 - this.position.turn); - WScript.Echo("position: ") - WScript.Echo(this.position.seedCounts.slice(0, 7)); - WScript.Echo(this.position.seedCounts.slice(7)); - } - } while (move != NoMove); - var sum = 0; - var otherSpaces = homeSpaces[1 - this.position.turn]; - for (var k = 0, len = otherSpaces.length; k < len; k++) { - sum += this.position.seedCounts[otherSpaces[k]]; - this.position.seedCounts[otherSpaces[k]] = 0; - } - this.position.seedCounts[storeHouses[this.position.turn]] += sum; - WScript.Echo("final position: ") - WScript.Echo(this.position.seedCounts.slice(0, 7)); - WScript.Echo(this.position.seedCounts.slice(7)); - var player1Count = this.position.seedCounts[storeHouses[0]]; - var player2Count = this.position.seedCounts[storeHouses[1]]; - WScript.Echo("storehouse 1 has " + player1Count); - WScript.Echo("storehouse 2 has " + player2Count); - WScript.Echo("average positions explored per move " + - (this.positionCount / this.moveCount).toFixed(2)); - } - } +/// + +namespace Mankala { + export var NoSpace = -1; + export var homeSpaces = [[0, 1, 2, 3, 4, 5], + [7, 8, 9, 10, 11, 12]]; + export var firstHomeSpace = [0, 7]; + export var lastHomeSpace = [5, 12]; + export var capturedSpaces = [12, 11, 10, 9, 8, 7, NoSpace, 5, 4, 3, 2, 1, 0, NoSpace]; + export var NoScore = 31; + export var NoMove = -1; + + const bodyId = "body"; + const humanScoreId = "humanScore"; + const computerScoreId = "computerScore" + + function pushPosition(pos: Position, l: Base.IList) { + l.insertAfter(Base.listMakeEntry(pos)); + } + + function popPosition(l: Base.IList) { + var entry = Base.listRemove(l.next); + if (entry != null) { + return entry.data; + } else { + return null; + } + } + + export function testBrowser() { + var game = new Game(); + game.interactive(); + var body = document.getElementById(bodyId); + body.onresize = () => { game.resize(); }; + } + + export class Game { + private position = new DisplayPosition([3, 3, 3, 3, 3, 3, 0, 3, 3, 3, 3, 3, 3, 0], NoMove, 0); + private prevConfig: SeedCoords[][]; + private q: Base.IList = null; + private scores: number[] = null; + private positionCount = 0; + private moveCount = 0; + private isInteractive = false; + + private features = new Features(); + private nextSeedCounts: number[] = new Array(14); + private body: Element; + private boardElm: Element = null; + + public resize() { + if (this.boardElm != null) { + this.body.removeChild(this.boardElm); + } + this.showMove(); + } + + private step(): boolean { + var move = this.findMove(); + if (move != NoMove) { + this.position.move(move, this.nextSeedCounts, this.features); + this.position = new DisplayPosition(this.nextSeedCounts.slice(0), NoMove, + this.features.turnContinues ? this.position.turn : 1 - this.position.turn); + this.position.config = this.prevConfig; + if ((!this.isInteractive) || (this.position.turn == 1)) { + this.setStep(); + } + return true; + } + return false; + } + + private setStep() { + setTimeout(/*function()*/ () => { + if (!this.step()) { + this.finish(); + } + this.body.removeChild(this.boardElm); + this.showMove(); + }, 1000); + } + + private finish() { + var sum = 0; + var otherSpaces = homeSpaces[1 - this.position.turn]; + for (var k = 0, len = otherSpaces.length; k < len; k++) { + sum += this.position.seedCounts[otherSpaces[k]]; + this.position.seedCounts[otherSpaces[k]] = 0; + } + this.position.seedCounts[storeHouses[this.position.turn]] += sum; + } + + private auto() { + // initialize + this.body = document.getElementById(bodyId); + this.showMove(); + // run with timeout + this.setStep(); + } + + private showMove(): void { + var hsc = document.getElementById(humanScoreId); + var csc = document.getElementById(computerScoreId); + + var g = this; + if (!this.isInteractive) { + g = null; + } + this.boardElm = this.position.toCircleSVG(g); + this.prevConfig = this.position.config; + hsc.innerText = this.position.seedCounts[storeHouses[0]] + + ((this.position.turn == 0) ? " <-Turn" : ""); + csc.innerText = this.position.seedCounts[storeHouses[1]] + + ((this.position.turn == 1) ? " <-Turn" : ""); + this.body.appendChild(this.boardElm); + } + + public humanMove(seed: number) { + if (this.position.turn == 0) { + this.position.move(seed, this.nextSeedCounts, this.features); + this.position = new DisplayPosition(this.nextSeedCounts.slice(0), NoMove, + this.features.turnContinues ? this.position.turn : 1 - this.position.turn); + this.position.config = this.prevConfig; + this.body.removeChild(this.boardElm); + this.showMove(); + if (this.position.turn == 1) { + this.setStep(); + } + } + } + + public interactive() { + this.isInteractive = true; + this.body = document.getElementById(bodyId); + this.showMove(); + } + + private expand(curPos: Position, move: number, + startMove: number, nextSeedCounts: number[]) { + var features = new Features(); + if (curPos.move(move, nextSeedCounts, features)) { + var pos = new Position(nextSeedCounts.slice(0), startMove, curPos.turn); + this.positionCount++; + if (!features.turnContinues) { + pos.turn = 1 - pos.turn; + } + var score = pos.score(); + if (this.scores[startMove] == NoScore) { + this.scores[startMove] = score; + } + else { + this.scores[startMove] += score; + } + pushPosition(pos, this.q); + return true; + } + return false; + } + + private findMove() { + var timeStart = new Date().getTime(); + this.q = Base.listMakeHead(); + this.scores = [NoScore, NoScore, NoScore, NoScore, NoScore, NoScore]; + pushPosition(this.position, this.q); + var deltaTime = 0; + var moves = homeSpaces[this.position.turn]; + var nextSeedCounts: number[] = new Array(14); + var movePossible = false; + while ((!this.q.empty()) && (deltaTime < 500)) { + var firstPos = popPosition(this.q); + for (var i = 0, len = moves.length; i < len; i++) { + var startMove = firstPos.startMove; + if (startMove == NoMove) { + startMove = i; + } + if (this.expand(firstPos, moves[i], startMove, nextSeedCounts)) { + movePossible = true; + } + } + deltaTime = new Date().getTime() - timeStart; + } + if (movePossible) { + var bestScore = -100; + var bestMove = NoMove; + for (var j = 0, scoresLen = this.scores.length; j < scoresLen; j++) { + if ((this.scores[j] != NoScore) && ((this.scores[j] > bestScore) || (bestMove == NoMove))) { + bestScore = this.scores[j]; + bestMove = j; + } + } + if (bestMove != NoMove) { + return moves[bestMove]; + } else { + return NoMove; + } + } + return NoMove; + } + + public test() { + var features = new Features(); + var nextSeedCounts: number[] = new Array(14); + WScript.Echo("position: ") + WScript.Echo(this.position.seedCounts.slice(0, 7)); + WScript.Echo(this.position.seedCounts.slice(7)); + do { + var move = this.findMove(); + if (move == NoMove) { + // TODO: capture rest of other side + } else { + this.moveCount++; + WScript.Echo(this.position.turn + " moves seeds in space " + move); + this.position.move(move, nextSeedCounts, features); + WScript.Echo(features.toString()); + this.position = new DisplayPosition(nextSeedCounts.slice(0), NoMove, + features.turnContinues ? this.position.turn : 1 - this.position.turn); + WScript.Echo("position: ") + WScript.Echo(this.position.seedCounts.slice(0, 7)); + WScript.Echo(this.position.seedCounts.slice(7)); + } + } while (move != NoMove); + var sum = 0; + var otherSpaces = homeSpaces[1 - this.position.turn]; + for (var k = 0, len = otherSpaces.length; k < len; k++) { + sum += this.position.seedCounts[otherSpaces[k]]; + this.position.seedCounts[otherSpaces[k]] = 0; + } + this.position.seedCounts[storeHouses[this.position.turn]] += sum; + WScript.Echo("final position: ") + WScript.Echo(this.position.seedCounts.slice(0, 7)); + WScript.Echo(this.position.seedCounts.slice(7)); + var player1Count = this.position.seedCounts[storeHouses[0]]; + var player2Count = this.position.seedCounts[storeHouses[1]]; + WScript.Echo("storehouse 1 has " + player1Count); + WScript.Echo("storehouse 2 has " + player2Count); + WScript.Echo("average positions explored per move " + + (this.positionCount / this.moveCount).toFixed(2)); + } + } } \ No newline at end of file diff --git a/mankala/Position.ts b/mankala/Position.ts index 2174094..34ed026 100644 --- a/mankala/Position.ts +++ b/mankala/Position.ts @@ -1,242 +1,241 @@ -/// - -module Mankala { - export var storeHouses = [6, 13]; - var svgNS = "http://www.w3.org/2000/svg"; - - function createSVGRect(r: Rectangle) { - var rect = document.createElementNS(svgNS, "rect"); - rect.setAttribute("x", r.x.toString()); - rect.setAttribute("y", r.y.toString()); - rect.setAttribute("width", r.width.toString()); - rect.setAttribute("height", r.height.toString()); - return rect; - } - - function createSVGEllipse(r: Rectangle) { - var ell = document.createElementNS(svgNS, "ellipse"); - ell.setAttribute("rx", (r.width / 2).toString()); - ell.setAttribute("ry", (r.height / 2).toString()); - ell.setAttribute("cx", (r.x + r.width / 2).toString()); - ell.setAttribute("cy", (r.y + r.height / 2).toString()); - return ell; - } - - function createSVGEllipsePolar(angle: number, radius: number, tx: number, ty: number, - cxo: number, cyo: number) { - var ell = document.createElementNS(svgNS, "ellipse"); - ell.setAttribute("rx", radius.toString()); - ell.setAttribute("ry", (radius / 3).toString()); - ell.setAttribute("cx", cxo.toString()); - ell.setAttribute("cy", cyo.toString()); - var dangle = angle * (180 / Math.PI); - ell.setAttribute("transform", "rotate(" + dangle + "," + cxo + "," + cyo + ") translate(" + tx + - "," + ty + ")"); - return ell; - } - - function createSVGInscribedCircle(sq: Square) { - var circle = document.createElementNS(svgNS, "circle"); - circle.setAttribute("r", (sq.len / 2).toString()); - circle.setAttribute("cx", (sq.x + (sq.len / 2)).toString()); - circle.setAttribute("cy", (sq.y + (sq.len / 2)).toString()); - return circle; - } - - export class Position { - constructor (public seedCounts: number[], public startMove: number, public turn: number) { } - public score() { - var baseScore = this.seedCounts[storeHouses[1 - this.turn]] - this.seedCounts[storeHouses[this.turn]]; - var otherSpaces = homeSpaces[this.turn]; - var sum = 0; - for (var k = 0, len = otherSpaces.length; k < len; k++) { - sum += this.seedCounts[otherSpaces[k]]; - } - if (sum == 0) { - var mySpaces = homeSpaces[1 - this.turn]; - var mySum = 0; - for (var j = 0, length = mySpaces.length; j < length; j++) { - mySum += this.seedCounts[mySpaces[j]]; - } - - baseScore -= mySum; - } - return baseScore; - } - - public move(space: number, nextSeedCounts: number[], features: Features) { - if ((space == storeHouses[0]) || (space == storeHouses[1])) { - // can't move seeds in storehouse - return false; - } - if (this.seedCounts[space] > 0) { - features.clear(); - var len = this.seedCounts.length; - for (var i = 0; i < len; i++) { - nextSeedCounts[i] = this.seedCounts[i]; - } - var seedCount = this.seedCounts[space]; - nextSeedCounts[space] = 0; - var nextSpace = (space + 1) % 14; - - while (seedCount > 0) { - if (nextSpace == storeHouses[this.turn]) { - features.seedStoredCount++; - } - if ((nextSpace != storeHouses[1 - this.turn])) { - nextSeedCounts[nextSpace]++; - seedCount--; - } - if (seedCount == 0) { - if (nextSpace == storeHouses[this.turn]) { - features.turnContinues = true; - } else if ((nextSeedCounts[nextSpace] == 1) && - (nextSpace >= firstHomeSpace[this.turn]) && - (nextSpace <= lastHomeSpace[this.turn])) { - // capture - var capturedSpace = capturedSpaces[nextSpace]; - if (capturedSpace >= 0) { - features.spaceCaptured = capturedSpace; - features.capturedCount = nextSeedCounts[capturedSpace]; - nextSeedCounts[capturedSpace] = 0; - nextSeedCounts[storeHouses[this.turn]] += features.capturedCount; - features.seedStoredCount += nextSeedCounts[capturedSpace]; - } - } - } - nextSpace = (nextSpace + 1) % 14; - } - return true; - } - else { - return false; - } - } - } - - export class SeedCoords { - constructor(public tx: number, public ty: number, public angle: number) { } - } - - export class DisplayPosition extends Position { - constructor (seedCounts: number[], startMove: number, turn: number) { - super(seedCounts, startMove, turn); - - for (var i = 0; i < seedCounts.length; i++) { - this.config[i] = []; - } - } - public config: SeedCoords[][] = []; - - - private seedCircleRect(rect: Rectangle, seedCount: number, board: Element, seed: number, circleClick: EventListener) { - var coords = this.config[seed]; - var sq = rect.inner(0.95).square(); - var cxo = (sq.width / 2) + sq.x; - var cyo = (sq.height / 2) + sq.y; - var seedNumbers = [5, 7, 9, 11]; - var ringIndex = 0; - var ringRem = seedNumbers[ringIndex]; - var angleDelta = (2 * Math.PI) / ringRem; - var angle = angleDelta; - var seedLength = sq.width / (seedNumbers.length << 1); - var crMax = sq.width / 2 - (seedLength / 2); - var pit = createSVGInscribedCircle(sq); - if (seed < 7) { - pit.setAttribute("fill", "brown"); - if (circleClick != null) { - pit.addEventListener('click', circleClick); - } - } else { - pit.setAttribute("fill", "saddlebrown"); - } - board.appendChild(pit); - var seedsSeen = 0; - while (seedCount > 0) { - if (ringRem == 0) { - ringIndex++; - ringRem = seedNumbers[ringIndex]; - angleDelta = (2 * Math.PI) / ringRem; - angle = angleDelta; - } - var tx: number; - var ty: number; - var tangle = angle; - if (coords.length > seedsSeen) { - tx = coords[seedsSeen].tx; - ty = coords[seedsSeen].ty; - tangle = coords[seedsSeen].angle; - } else { - tx = (Math.random() * crMax) - (crMax / 3); - ty = (Math.random() * crMax) - (crMax / 3); - coords[seedsSeen] = new SeedCoords(tx, ty, angle); - } - var ell = createSVGEllipsePolar(tangle, seedLength, tx, ty, cxo, cyo); - board.appendChild(ell); - angle += angleDelta; - ringRem--; - seedCount--; - seedsSeen++; - } - } - - public toCircleSVG(game: Game) { - var seedDivisions = 14; - var bod = document.getElementById("bod"); - var board = document.createElementNS(svgNS, "svg"); - var w = window.innerWidth - 40; - var h = window.innerHeight - 40; - var boardRect = new Rectangle(0, 0, w, h); - board.setAttribute("width", w.toString()); - board.setAttribute("height", h.toString()); - var whole = createSVGRect(boardRect); - whole.setAttribute("fill", "tan"); - board.appendChild(whole); - //var labPlayLab=boardRect.proportionalSplitVert(20,760,20); - //var playSurface=labPlayLab[1]; - var playSurface = boardRect; - var storeMainStore = playSurface.proportionalSplitHoriz(8, 48, 8); - var mainPair = storeMainStore[1].subDivideVert(2); - var playerRects = [mainPair[0].subDivideHoriz(6), - mainPair[1].subDivideHoriz(6)]; - // reverse top layer because storehouse on left - for (var k = 0; k < 3; k++) { - var temp = playerRects[0][k]; - playerRects[0][k] = playerRects[0][5 - k]; - playerRects[0][5 - k] = temp; - } - var storehouses = [storeMainStore[0], storeMainStore[2]]; - var playerSeeds = this.seedCounts.length >> 1; - for (var i = 0; i < 2; i++) { - var player = playerRects[i]; - var storehouse = storehouses[i]; - var r: Rectangle; - for (var j = 0; j < playerSeeds; j++) { - var seed = (i * playerSeeds) + j; - var seedCount = this.seedCounts[seed]; - if (j == (playerSeeds - 1)) { - r = storehouse; - } else { - r = player[j]; - } - if (game != null) { - this.seedCircleRect(r, seedCount, board, seed, - function(seed: number) { - return function(evt: Event) { - game.humanMove(seed); - } - }(seed)); - } - else { - this.seedCircleRect(r, seedCount, board, seed, null); - } - if (seedCount == 0) { - // clear - this.config[seed] = []; - } - } - } - return board; - } - } +/// + +namespace Mankala { + export var storeHouses = [6, 13]; + var svgNS = "http://www.w3.org/2000/svg"; + + function createSVGRect(r: Rectangle) { + var rect = document.createElementNS(svgNS, "rect"); + rect.setAttribute("x", r.x.toString()); + rect.setAttribute("y", r.y.toString()); + rect.setAttribute("width", r.width.toString()); + rect.setAttribute("height", r.height.toString()); + return rect; + } + + function createSVGEllipse(r: Rectangle) { + var ell = document.createElementNS(svgNS, "ellipse"); + ell.setAttribute("rx", (r.width / 2).toString()); + ell.setAttribute("ry", (r.height / 2).toString()); + ell.setAttribute("cx", (r.x + r.width / 2).toString()); + ell.setAttribute("cy", (r.y + r.height / 2).toString()); + return ell; + } + + function createSVGEllipsePolar(angle: number, radius: number, tx: number, ty: number, + cxo: number, cyo: number) { + var ell = document.createElementNS(svgNS, "ellipse"); + ell.setAttribute("rx", radius.toString()); + ell.setAttribute("ry", (radius / 3).toString()); + ell.setAttribute("cx", cxo.toString()); + ell.setAttribute("cy", cyo.toString()); + var dangle = angle * (180 / Math.PI); + ell.setAttribute("transform", "rotate(" + dangle + "," + cxo + "," + cyo + ") translate(" + tx + + "," + ty + ")"); + return ell; + } + + function createSVGInscribedCircle(sq: Square) { + var circle = document.createElementNS(svgNS, "circle"); + circle.setAttribute("r", (sq.len / 2).toString()); + circle.setAttribute("cx", (sq.x + (sq.len / 2)).toString()); + circle.setAttribute("cy", (sq.y + (sq.len / 2)).toString()); + return circle; + } + + export class Position { + constructor (public seedCounts: number[], public startMove: number, public turn: number) { } + public score() { + var baseScore = this.seedCounts[storeHouses[1 - this.turn]] - this.seedCounts[storeHouses[this.turn]]; + var otherSpaces = homeSpaces[this.turn]; + var sum = 0; + for (var k = 0, len = otherSpaces.length; k < len; k++) { + sum += this.seedCounts[otherSpaces[k]]; + } + if (sum == 0) { + var mySpaces = homeSpaces[1 - this.turn]; + var mySum = 0; + for (var j = 0, length = mySpaces.length; j < length; j++) { + mySum += this.seedCounts[mySpaces[j]]; + } + + baseScore -= mySum; + } + return baseScore; + } + + public move(space: number, nextSeedCounts: number[], features: Features) { + if ((space == storeHouses[0]) || (space == storeHouses[1])) { + // can't move seeds in storehouse + return false; + } + if (this.seedCounts[space] > 0) { + features.clear(); + var len = this.seedCounts.length; + for (var i = 0; i < len; i++) { + nextSeedCounts[i] = this.seedCounts[i]; + } + var seedCount = this.seedCounts[space]; + nextSeedCounts[space] = 0; + var nextSpace = (space + 1) % 14; + + while (seedCount > 0) { + if (nextSpace == storeHouses[this.turn]) { + features.seedStoredCount++; + } + if ((nextSpace != storeHouses[1 - this.turn])) { + nextSeedCounts[nextSpace]++; + seedCount--; + } + if (seedCount == 0) { + if (nextSpace == storeHouses[this.turn]) { + features.turnContinues = true; + } else if ((nextSeedCounts[nextSpace] == 1) && + (nextSpace >= firstHomeSpace[this.turn]) && + (nextSpace <= lastHomeSpace[this.turn])) { + // capture + var capturedSpace = capturedSpaces[nextSpace]; + if (capturedSpace >= 0) { + features.spaceCaptured = capturedSpace; + features.capturedCount = nextSeedCounts[capturedSpace]; + nextSeedCounts[capturedSpace] = 0; + nextSeedCounts[storeHouses[this.turn]] += features.capturedCount; + features.seedStoredCount += nextSeedCounts[capturedSpace]; + } + } + } + nextSpace = (nextSpace + 1) % 14; + } + return true; + } + else { + return false; + } + } + } + + export class SeedCoords { + constructor(public tx: number, public ty: number, public angle: number) { } + } + + export class DisplayPosition extends Position { + constructor (seedCounts: number[], startMove: number, turn: number) { + super(seedCounts, startMove, turn); + + for (var i = 0; i < seedCounts.length; i++) { + this.config[i] = []; + } + } + public config: SeedCoords[][] = []; + + + private seedCircleRect(rect: Rectangle, seedCount: number, board: Element, seed: number, circleClick: EventListener) { + var coords = this.config[seed]; + var sq = rect.inner(0.95).square(); + var cxo = (sq.width / 2) + sq.x; + var cyo = (sq.height / 2) + sq.y; + var seedNumbers = [5, 7, 9, 11]; + var ringIndex = 0; + var ringRem = seedNumbers[ringIndex]; + var angleDelta = (2 * Math.PI) / ringRem; + var angle = angleDelta; + var seedLength = sq.width / (seedNumbers.length << 1); + var crMax = sq.width / 2 - (seedLength / 2); + var pit = createSVGInscribedCircle(sq); + if (seed < 7) { + pit.setAttribute("fill", "brown"); + if (circleClick != null) { + pit.addEventListener('click', circleClick); + } + } else { + pit.setAttribute("fill", "saddlebrown"); + } + board.appendChild(pit); + var seedsSeen = 0; + while (seedCount > 0) { + if (ringRem == 0) { + ringIndex++; + ringRem = seedNumbers[ringIndex]; + angleDelta = (2 * Math.PI) / ringRem; + angle = angleDelta; + } + var tx: number; + var ty: number; + var tangle = angle; + if (coords.length > seedsSeen) { + tx = coords[seedsSeen].tx; + ty = coords[seedsSeen].ty; + tangle = coords[seedsSeen].angle; + } else { + tx = (Math.random() * crMax) - (crMax / 3); + ty = (Math.random() * crMax) - (crMax / 3); + coords[seedsSeen] = new SeedCoords(tx, ty, angle); + } + var ell = createSVGEllipsePolar(tangle, seedLength, tx, ty, cxo, cyo); + board.appendChild(ell); + angle += angleDelta; + ringRem--; + seedCount--; + seedsSeen++; + } + } + + public toCircleSVG(game: Game) { + var seedDivisions = 14; + var board = document.createElementNS(svgNS, "svg"); + var w = window.innerWidth - 40; + var h = window.innerHeight - 40; + var boardRect = new Rectangle(0, 0, w, h); + board.setAttribute("width", w.toString()); + board.setAttribute("height", h.toString()); + var whole = createSVGRect(boardRect); + whole.setAttribute("fill", "tan"); + board.appendChild(whole); + //var labPlayLab=boardRect.proportionalSplitVert(20,760,20); + //var playSurface=labPlayLab[1]; + var playSurface = boardRect; + var storeMainStore = playSurface.proportionalSplitHoriz(8, 48, 8); + var mainPair = storeMainStore[1].subDivideVert(2); + var playerRects = [mainPair[0].subDivideHoriz(6), + mainPair[1].subDivideHoriz(6)]; + // reverse top layer because storehouse on left + for (var k = 0; k < 3; k++) { + var temp = playerRects[0][k]; + playerRects[0][k] = playerRects[0][5 - k]; + playerRects[0][5 - k] = temp; + } + var storehouses = [storeMainStore[0], storeMainStore[2]]; + var playerSeeds = this.seedCounts.length >> 1; + for (var i = 0; i < 2; i++) { + var player = playerRects[i]; + var storehouse = storehouses[i]; + var r: Rectangle; + for (var j = 0; j < playerSeeds; j++) { + var seed = (i * playerSeeds) + j; + var seedCount = this.seedCounts[seed]; + if (j == (playerSeeds - 1)) { + r = storehouse; + } else { + r = player[j]; + } + if (game != null) { + this.seedCircleRect(r, seedCount, board, seed, + function(seed: number) { + return function(evt: Event) { + game.humanMove(seed); + } + }(seed)); + } + else { + this.seedCircleRect(r, seedCount, board, seed, null); + } + if (seedCount == 0) { + // clear + this.config[seed] = []; + } + } + } + return board; + } + } } \ No newline at end of file diff --git a/mankala/README.md b/mankala/README.md index 17cd0b1..3cfc2f1 100644 --- a/mankala/README.md +++ b/mankala/README.md @@ -11,9 +11,11 @@ features of TypeScript are highlighted: ## Running + ``` tsc Driver.ts --sourcemap -out game.js cscript game.js ``` -For web execution use play.htm. + +For web execution use play.html. diff --git a/mankala/geometry.ts b/mankala/geometry.ts index 9189b3a..613b752 100644 --- a/mankala/geometry.ts +++ b/mankala/geometry.ts @@ -1,140 +1,140 @@ -/// - -module Mankala { - export class Rectangle { - - constructor (public x: number, public y: number, - public width: number, public height: number) { } - - public square() { - var len = this.width; - var adj = 0; - if (len > this.height) { - len = this.height; - adj = (this.width - len) / 2; - return new Square(this.x + adj, this.y, len); - } else { - adj = (this.height - len) / 2; - return new Square(this.x, this.y + adj, len); - } - } - - public inner(factor: number) { - var iw = factor * this.width; - var ih = factor * this.height; - var ix = this.x + ((this.width - iw) / 2); - var iy = this.y + ((this.height - ih) / 2); - return (new Rectangle(ix, iy, iw, ih)); - } - - public proportionalSplitHoriz(...proportionalWidths: number[]) { - var totalPropWidth = 0; - var i:number; - - for (i = 0; i < proportionalWidths.length; i++) { - totalPropWidth += proportionalWidths[i]; - } - - var totalWidth = 0; - var widths: number[] = []; - for (i = 0; i < proportionalWidths.length; i++) { - widths[i] = (proportionalWidths[i] / totalPropWidth) * this.width; - totalWidth += widths[i]; - } - - var extraWidth = this.width - totalWidth; - /* Add back round-off error equally to all rectangles */ - i = 0; - while (extraWidth > 0) { - widths[i]++; - extraWidth--; - if ((++i) == widths.length) { - i = 0; - } - } - var rects: Rectangle[] = []; - var curX = this.x; - for (i = 0; i < widths.length; i++) { - rects[i] = new Rectangle(curX, this.y, widths[i], this.height); - curX += widths[i]; - } - return rects; - } - - private proportionalSplitVert(...proportionalHeights: number[]): Rectangle[]{ - var totalPropHeight = 0; - var i: number; - - for (i = 0; i < proportionalHeights.length; i++) { - totalPropHeight += proportionalHeights[i]; - } - - var totalHeight = 0; - var heights: number[] = []; - for (i = 0; i < proportionalHeights.length; i++) { - heights[i] = (proportionalHeights[i] / totalPropHeight) * this.height; - totalHeight += heights[i]; - } - - var extraHeight = this.height - totalHeight; - /* Add back round-off error equally to all rectangles */ - i = 0; - while (extraHeight > 0) { - heights[i]++; - extraHeight--; - if ((++i) == heights.length) { - i = 0; - } - } - var rects: Rectangle[] = []; - var curY = this.y; - for (i = 0; i < heights.length; i++) { - rects[i] = new Rectangle(this.x, curY, this.width, heights[i]); - curY += heights[i]; - } - return rects; - } - - public subDivideHoriz(n: number) { - var rects: Rectangle[] = []; - - var tileWidth = this.width / n; - var rem = this.width % n; - var tileX = this.x; - for (var i = 0; i < n; i++) { - rects[i] = new Rectangle(tileX, this.y, tileWidth, this.height); - if (rem > 0) { - rects[i].width++; - rem--; - } - tileX += rects[i].width; - } - return rects; - } - - public subDivideVert(n: number) { - var rects: Rectangle[] = []; - var tileHeight = this.height / n; - var rem = this.height % n; - var tileY = this.y; - for (var i = 0; i < n; i++) { - rects[i] = new Rectangle(this.x, tileY, this.width, tileHeight); - if (rem > 0) { - rects[i].height++; - rem--; - } - tileY += rects[i].height; - } - return rects; - } - } - - export class Square extends Rectangle { - len: number; - - constructor(x: number, y: number, len: number) { - super(x, y, len, len); - this.len = len; - } - } +/// + +namespace Mankala { + export class Rectangle { + + constructor (public x: number, public y: number, + public width: number, public height: number) { } + + public square() { + var len = this.width; + var adj = 0; + if (len > this.height) { + len = this.height; + adj = (this.width - len) / 2; + return new Square(this.x + adj, this.y, len); + } else { + adj = (this.height - len) / 2; + return new Square(this.x, this.y + adj, len); + } + } + + public inner(factor: number) { + var iw = factor * this.width; + var ih = factor * this.height; + var ix = this.x + ((this.width - iw) / 2); + var iy = this.y + ((this.height - ih) / 2); + return (new Rectangle(ix, iy, iw, ih)); + } + + public proportionalSplitHoriz(...proportionalWidths: number[]) { + var totalPropWidth = 0; + var i:number; + + for (i = 0; i < proportionalWidths.length; i++) { + totalPropWidth += proportionalWidths[i]; + } + + var totalWidth = 0; + var widths: number[] = []; + for (i = 0; i < proportionalWidths.length; i++) { + widths[i] = (proportionalWidths[i] / totalPropWidth) * this.width; + totalWidth += widths[i]; + } + + var extraWidth = this.width - totalWidth; + /* Add back round-off error equally to all rectangles */ + i = 0; + while (extraWidth > 0) { + widths[i]++; + extraWidth--; + if ((++i) == widths.length) { + i = 0; + } + } + var rects: Rectangle[] = []; + var curX = this.x; + for (i = 0; i < widths.length; i++) { + rects[i] = new Rectangle(curX, this.y, widths[i], this.height); + curX += widths[i]; + } + return rects; + } + + private proportionalSplitVert(...proportionalHeights: number[]): Rectangle[]{ + var totalPropHeight = 0; + var i: number; + + for (i = 0; i < proportionalHeights.length; i++) { + totalPropHeight += proportionalHeights[i]; + } + + var totalHeight = 0; + var heights: number[] = []; + for (i = 0; i < proportionalHeights.length; i++) { + heights[i] = (proportionalHeights[i] / totalPropHeight) * this.height; + totalHeight += heights[i]; + } + + var extraHeight = this.height - totalHeight; + /* Add back round-off error equally to all rectangles */ + i = 0; + while (extraHeight > 0) { + heights[i]++; + extraHeight--; + if ((++i) == heights.length) { + i = 0; + } + } + var rects: Rectangle[] = []; + var curY = this.y; + for (i = 0; i < heights.length; i++) { + rects[i] = new Rectangle(this.x, curY, this.width, heights[i]); + curY += heights[i]; + } + return rects; + } + + public subDivideHoriz(n: number) { + var rects: Rectangle[] = []; + + var tileWidth = this.width / n; + var rem = this.width % n; + var tileX = this.x; + for (var i = 0; i < n; i++) { + rects[i] = new Rectangle(tileX, this.y, tileWidth, this.height); + if (rem > 0) { + rects[i].width++; + rem--; + } + tileX += rects[i].width; + } + return rects; + } + + public subDivideVert(n: number) { + var rects: Rectangle[] = []; + var tileHeight = this.height / n; + var rem = this.height % n; + var tileY = this.y; + for (var i = 0; i < n; i++) { + rects[i] = new Rectangle(this.x, tileY, this.width, tileHeight); + if (rem > 0) { + rects[i].height++; + rem--; + } + tileY += rects[i].height; + } + return rects; + } + } + + export class Square extends Rectangle { + len: number; + + constructor(x: number, y: number, len: number) { + super(x, y, len, len); + this.len = len; + } + } } \ No newline at end of file diff --git a/mankala/play.css b/mankala/play.css index 0380036..3ae7ef2 100644 --- a/mankala/play.css +++ b/mankala/play.css @@ -1,11 +1,11 @@ -.hscore { - font-size: 14px; - font-weight: bold; - color: brown; -} - -.cscore { - font-size: 14px; - font-weight: bold; - color: saddlebrown; +.hscore { + font-size: 14px; + font-weight: bold; + color: brown; +} + +.cscore { + font-size: 14px; + font-weight: bold; + color: saddlebrown; } \ No newline at end of file diff --git a/mankala/play.htm b/mankala/play.html similarity index 56% rename from mankala/play.htm rename to mankala/play.html index b1e5b6d..5576202 100644 --- a/mankala/play.htm +++ b/mankala/play.html @@ -1,15 +1,15 @@ - - - - - - Mankala - - - - - -
Human: 0
-
Computer: 0
- - + + + + + + Mankala + + + + + +
Human: 0
+
Computer: 0
+ + diff --git a/mankala/tsconfig.json b/mankala/tsconfig.json new file mode 100644 index 0000000..1295238 --- /dev/null +++ b/mankala/tsconfig.json @@ -0,0 +1,6 @@ +{ + "compilerOptions": { + "sourceMap": true, + "outFile": "game.js" + } +} \ No newline at end of file diff --git a/node/.gitignore b/node/.gitignore new file mode 100644 index 0000000..320c107 --- /dev/null +++ b/node/.gitignore @@ -0,0 +1,3 @@ +node_modules/ +dist/ +package-lock.json diff --git a/node/HttpServer.ts b/node/HttpServer.ts deleted file mode 100644 index 00c3f15..0000000 --- a/node/HttpServer.ts +++ /dev/null @@ -1,9 +0,0 @@ -/// -import http = require("http"); - -http.createServer(function (req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.end('Hello World\n'); -}).listen(1337, '127.0.0.1'); - -console.log('Server running at http://127.0.0.1:1337/'); \ No newline at end of file diff --git a/node/README.md b/node/README.md index 032b1e7..ec0e9b3 100644 --- a/node/README.md +++ b/node/README.md @@ -1,18 +1,46 @@ # TypeScript Sample: Node.js +## Overview -## Overview +This sample implements a very basic [node.js](https://nodejs.org/) application using TypeScript. -This sample implements a very basic node.js application using TypeScript +## Running +First of all, install all dependencies with: +```bash +npm install +``` + +Then, you can run each of the listed [examples](#examples) with the following command from the this project root folder: +```bash +ts-node ./examples/example-name.ts +``` -## Running -For HttpServer +To run the HTTPS server example, just: +```bash +ts-node ./examples/HttpServer.ts ``` -tsc --sourcemap --module commonjs HttpServer.ts -node HttpServer.js + +This examples are running through [ts-node](https://github.com/TypeStrong/ts-node), which is not recommended in production environments. You can also build those examples with: +```bash +npm run build ``` -For TcpServer +And then running the compiled JavaScript (JS) example file with: +```bash +node ./dist/example-name.js ``` -tsc --sourcemap --module commonjs TcpServer.ts -node TcpServer.js -``` \ No newline at end of file + +## Examples +* [TcpServer](./src/TcpServer.ts) - a simple TCP server +* [HttpServer](./src/HttpServer.ts) - a simple HTTPS server +* [API Client](./src/APIClient.ts) - client that sends a "ping" +* [API Server](./src/APIServer.ts) - server the receives that "ping" and responds with a "pong" +* [Word counter](./src/WordCounter.ts) - shows how many of the desired words are presented in a file +* [Wikipedia Search](./src/Wikipedia.ts) - searches the [Wikipedia](https://en.wikipedia.org/w/api.php?) website + +**note**: due to HTTP/HTTPS distinct way of handle localhost requests, in the examples HTTP is used instead of HTTPS because is a more easy way to set it up. + +## Standards +A modified version of the [Microsoft Linter Standards](https://github.com/Microsoft/tslint-microsoft-contrib) is used. Please be mindful that they are here to help you out improve you code. + +## Git Hooks +Due to [Husky](https://github.com/typicode/husky) integration, before any push to this Github repository, [TSLint](https://github.com/palantir/tslint) will run and then point out all the fixes that needs to be done to follow the set of code [standards](#standards); if nothing needs to be corrected, you then can push it :) diff --git a/node/TcpServer.ts b/node/TcpServer.ts deleted file mode 100644 index ace207c..0000000 --- a/node/TcpServer.ts +++ /dev/null @@ -1,9 +0,0 @@ -/// -import net = require('net'); - -var server = net.createServer(function (socket) { - socket.write('Echo server\r\n'); - socket.pipe(socket); -}); - -server.listen(1337, '127.0.0.1'); diff --git a/node/index.ts b/node/index.ts new file mode 100644 index 0000000..06d7444 --- /dev/null +++ b/node/index.ts @@ -0,0 +1,18 @@ +/** + * Just running the command line program. + */ +import { ChildProcess, exec } from 'child_process'; + +const main: Function = (): ChildProcess => { + let command: string = `ts-node ./src/${process.argv[3]}.ts`; + + if (process.argv[2] === 'js') { + exec('tsc'); + + command = `node ./dist/${process.argv[3]}.js`; + } + + return exec(command); +}; + +main(); diff --git a/node/lorem.txt b/node/lorem.txt new file mode 100644 index 0000000..92fb55f --- /dev/null +++ b/node/lorem.txt @@ -0,0 +1 @@ +"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?" diff --git a/node/node.d.ts b/node/node.d.ts deleted file mode 100644 index 5ebb02d..0000000 --- a/node/node.d.ts +++ /dev/null @@ -1,1079 +0,0 @@ -/************************************************ -* * -* Node.js v0.8.8 API * -* * -************************************************/ - -/************************************************ -* * -* GLOBAL * -* * -************************************************/ -declare var process: NodeProcess; -declare var global: any; - -declare var __filename: string; -declare var __dirname: string; - -declare function setTimeout(callback: () => void , ms: number): any; -declare function clearTimeout(timeoutId: any); -declare function setInterval(callback: () => void , ms: number): any; -declare function clearInterval(intervalId: any); - -declare var require: { - (id: string): any; - resolve(): string; - cache: any; - extensions: any; -} - -declare var module: { - exports: any; - require(id: string): any; - id: string; - filename: string; - loaded: boolean; - parent: any; - children: any[]; -} - -// Same as module.exports -declare var exports: any; -declare var SlowBuffer: { - new (str: string, encoding?: string): NodeBuffer; - new (size: number): NodeBuffer; - new (array: any[]): NodeBuffer; - prototype: NodeBuffer; - isBuffer(obj: any): boolean; - byteLength(string: string, encoding?: string): number; - concat(list: NodeBuffer[], totalLength?: number): NodeBuffer; -}; -declare var Buffer: { - new (str: string, encoding?: string): NodeBuffer; - new (size: number): NodeBuffer; - new (array: any[]): NodeBuffer; - prototype: NodeBuffer; - isBuffer(obj: any): boolean; - byteLength(string: string, encoding?: string): number; - concat(list: NodeBuffer[], totalLength?: number): NodeBuffer; -} - -/************************************************ -* * -* INTERFACES * -* * -************************************************/ - -declare class EventEmitter { - addListener(event: string, listener: Function); - on(event: string, listener: Function); - once(event: string, listener: Function): void; - removeListener(event: string, listener: Function): void; - removeAllListener(event: string): void; - setMaxListeners(n: number): void; - listeners(event: string): { Function; }[]; - emit(event: string, arg1?: any, arg2?: any): void; -} - -declare class WritableStream extends EventEmitter { - writable: boolean; - write(str: string, encoding?: string, fd?: string): boolean; - write(buffer: NodeBuffer): boolean; - end(): void; - end(str: string, enconding: string): void; - end(buffer: NodeBuffer): void; - destroy(): void; - destroySoon(): void; -} - -declare class ReadableStream extends EventEmitter { - readable: boolean; - setEncoding(encoding: string): void; - pause(): void; - resume(): void; - destroy(): void; - pipe(destination: WritableStream, options?: { end?: boolean; }): void; -} - -declare class NodeProcess extends EventEmitter { - stdout: WritableStream; - stderr: WritableStream; - stdin: ReadableStream; - argv: string[]; - execPath: string; - abort(): void; - chdir(directory: string): void; - cwd(): string; - env: any; - exit(code?: number): void; - getgid(): number; - setgid(id: number): void; - getuid(): number; - setuid(id: number): void; - version: string; - versions: { http_parser: string; node: string; v8: string; ares: string; uv: string; zlib: string; openssl: string; }; - config: { - target_defaults: { - cflags: any[]; - default_configuration: string; - defines: string[]; - include_dirs: string[]; - libraries: string[]; - }; - variables: { - clang: number; - host_arch: string; - node_install_npm: boolean; - node_install_waf: boolean; - node_prefix: string; - node_shared_openssl: boolean; - node_shared_v8: boolean; - node_shared_zlib: boolean; - node_use_dtrace: boolean; - node_use_etw: boolean; - node_use_openssl: boolean; - target_arch: string; - v8_no_strict_aliasing: number; - v8_use_snapshot: boolean; - visibility: string; - }; - }; - kill(pid: number, signal?: string): void; - pid: number; - title: string; - arch: string; - platform: string; - memoryUsage(): { rss: number; heapTotal; number; heapUsed: number; }; - nextTick(callback: Function): void; - umask(mask?: number): number; - uptime(): number; - hrtime(): number[]; -} - -// Buffer class -interface NodeBuffer { - [index: number]: number; - write(string: string, offset?: number, length?: number, encoding?: string): number; - toString(encoding?: string, start?: number, end?: number): string; - length: number; - copy(targetBuffer: NodeBuffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): void; - slice(start?: number, end?: number): NodeBuffer; - readUInt8(offset: number, noAsset?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; - writeUInt8(value: number, offset: number, noAssert?: boolean): void; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): void; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): void; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): void; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): void; - writeInt8(value: number, offset: number, noAssert?: boolean): void; - writeInt16LE(value: number, offset: number, noAssert?: boolean): void; - writeInt16BE(value: number, offset: number, noAssert?: boolean): void; - writeInt32LE(value: number, offset: number, noAssert?: boolean): void; - writeInt32BE(value: number, offset: number, noAssert?: boolean): void; - writeFloatLE(value: number, offset: number, noAssert?: boolean): void; - writeFloatBE(value: number, offset: number, noAssert?: boolean): void; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): void; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): void; - fill(value: any, offset?: number, end?: number): void; - INSPECT_MAX_BYTES: number; -} - -/************************************************ -* * -* MODULES * -* * -************************************************/ -declare module "querystring" { - export function stringify(obj: any, sep?: string, eq?: string): string; - export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; - export function escape(): any; - export function unescape(): any; -} - -declare module "events" { - export class EventEmitter { - addListener(event: string, listener: Function); - on(event: string, listener: Function): any; - once(event: string, listener: Function): void; - removeListener(event: string, listener: Function): void; - removeAllListener(event: string): void; - setMaxListeners(n: number): void; - listeners(event: string): { Function; }[]; - emit(event: string, arg1?: any, arg2?: any): void; - } -} - -declare module "http" { - import events = require("events"); - import net = require("net"); - import stream = require("stream"); - - export class Server extends events.EventEmitter { - listen(port: number, hostname?: string, backlog?: number, callback?: Function): void; - listen(path: string, callback?: Function): void; - listen(handle: any, listeningListener?: Function): void; - close(cb?: any): void; - maxHeadersCount: number; - } - export class ServerRequest extends stream.ReadableStream { - method: string; - url: string; - headers: string; - trailers: string; - httpVersion: string; - setEncoding(encoding?: string): void; - pause(): void; - resume(): void; - connection: net.NodeSocket; - } - export class ServerResponse extends stream.WritableStream { - // Extended base methods - write(str: string, encoding?: string, fd?: string): boolean; - write(buffer: NodeBuffer): boolean; - - writeContinue(): void; - writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; - writeHead(statusCode: number, headers?: any): void; - statusCode: number; - setHeader(name: string, value: string): void; - sendDate: boolean; - getHeader(name: string): string; - removeHeader(name: string): void; - write(chunk: any, encoding?: string): any; - addTrailers(headers: any): void; - end(data?: any, encoding?: string): void; - } - export class ClientRequest extends stream.WritableStream { - // Extended base methods - write(str: string, encoding?: string, fd?: string): boolean; - write(buffer: NodeBuffer): boolean; - - write(chunk: any, encoding?: string): void; - end(data?: any, encoding?: string): void; - abort(): void; - setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: Function): void; - setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; - } - export class ClientResponse extends stream.ReadableStream { - statusCode: number; - httpVersion: string; - headers: any; - trailers: any; - setEncoding(encoding?: string): void; - pause(): void; - resume(): void; - } - export interface Agent { maxSockets: number; sockets: any; requests: any; } - - export var STATUS_CODES; - export function createServer(requestListener?: (request: ServerRequest, response: ServerResponse) =>void ): Server; - export function createClient(port?: number, host?: string): any; - export function request(options: any, callback?: Function): ClientRequest; - export function get(options: any, callback?: Function): ClientRequest; - export var globalAgent: Agent; -} - -declare module "cluster" { - import child_process = require("child_process"); - - export interface ClusterSettings { - exec: string; - args: string[]; - silent: boolean; - } - export interface Worker { - id: string; - process: child_process.ChildProcess; - suicide: boolean; - send(message: any, sendHandle?: any): void; - destroy(): void; - disconnect(): void; - } - - - export var settings: ClusterSettings; - export var isMaster: boolean; - export var isWorker: boolean; - export function setupMaster(settings?: ClusterSettings): void; - export function fork(env?: any): Worker; - export function disconnect(callback?: Function): void; - export var workers: any; - - // Event emitter - export function addListener(event: string, listener: Function): void; - export function on(event: string, listener: Function): any; - export function once(event: string, listener: Function): void; - export function removeListener(event: string, listener: Function): void; - export function removeAllListener(event: string): void; - export function setMaxListeners(n: number): void; - export function listeners(event: string): { Function; }[]; - export function emit(event: string, arg1?: any, arg2?: any): void; -} - -declare module "zlib" { - import stream = require("stream"); - export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } - - export class Gzip extends stream.ReadWriteStream { } - export class Gunzip extends stream.ReadWriteStream { } - export class Deflate extends stream.ReadWriteStream { } - export class Inflate extends stream.ReadWriteStream { } - export class DeflateRaw extends stream.ReadWriteStream { } - export class InflateRaw extends stream.ReadWriteStream { } - export class Unzip extends stream.ReadWriteStream { } - - export function createGzip(options: ZlibOptions): Gzip; - export function createGunzip(options: ZlibOptions): Gunzip; - export function createDeflate(options: ZlibOptions): Deflate; - export function createInflate(options: ZlibOptions): Inflate; - export function createDeflateRaw(options: ZlibOptions): DeflateRaw; - export function createInflateRaw(options: ZlibOptions): InflateRaw; - export function createUnzip(options: ZlibOptions): Unzip; - - export function deflate(buf: NodeBuffer, callback: (error: Error, result) =>void ): void; - export function deflateRaw(buf: NodeBuffer, callback: (error: Error, result) =>void ): void; - export function gzip(buf: NodeBuffer, callback: (error: Error, result) =>void ): void; - export function gunzip(buf: NodeBuffer, callback: (error: Error, result) =>void ): void; - export function inflate(buf: NodeBuffer, callback: (error: Error, result) =>void ): void; - export function inflateRaw(buf: NodeBuffer, callback: (error: Error, result) =>void ): void; - export function unzip(buf: NodeBuffer, callback: (error: Error, result) =>void ): void; - - // Constants - export var Z_NO_FLUSH: number; - export var Z_PARTIAL_FLUSH: number; - export var Z_SYNC_FLUSH: number; - export var Z_FULL_FLUSH: number; - export var Z_FINISH: number; - export var Z_BLOCK: number; - export var Z_TREES: number; - export var Z_OK: number; - export var Z_STREAM_END: number; - export var Z_NEED_DICT: number; - export var Z_ERRNO: number; - export var Z_STREAM_ERROR: number; - export var Z_DATA_ERROR: number; - export var Z_MEM_ERROR: number; - export var Z_BUF_ERROR: number; - export var Z_VERSION_ERROR: number; - export var Z_NO_COMPRESSION: number; - export var Z_BEST_SPEED: number; - export var Z_BEST_COMPRESSION: number; - export var Z_DEFAULT_COMPRESSION: number; - export var Z_FILTERED: number; - export var Z_HUFFMAN_ONLY: number; - export var Z_RLE: number; - export var Z_FIXED: number; - export var Z_DEFAULT_STRATEGY: number; - export var Z_BINARY: number; - export var Z_TEXT: number; - export var Z_ASCII: number; - export var Z_UNKNOWN: number; - export var Z_DEFLATED: number; - export var Z_NULL: number; -} - -declare module "os" { - export function tmpDir(): string; - export function hostname(): string; - export function type(): string; - export function platform(): string; - export function arch(): string; - export function release(): string; - export function uptime(): number; - export function loadavg(): number[]; - export function totalmem(): number; - export function freemem(): number; - export function cpus(): { model: string; speed: number; times: { user: number; nice: number; sys: number; idle: number; irq: number; }; }[]; - export function networkInterfaces(): any; - export var EOL: string; -} - -declare module "https" { - import tls = require("tls"); - import events = require("events"); - import http = require("http"); - - export interface ServerOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - crl?: any; - ciphers?: string; - honorCipherOrder?: boolean; - requestCert?: boolean; - rejectUnauthorized?: boolean; - NPNProtocols?: any; - SNICallback?: (servername: string) => any; - } - - export interface RequestOptions { - host?: string; - hostname?: string; - port?: number; - path?: string; - method?: string; - headers?: any; - auth?: string; - agent?: any; - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - ciphers?: string; - rejectUnauthorized?: boolean; - } - - export interface NodeAgent { - maxSockets: number; - sockets: any; - requests: any; - } - export var Agent: { - new (options?: RequestOptions): NodeAgent; - }; - export class Server extends tls.Server { } - export function createServer(options: ServerOptions, requestListener?: Function): Server; - export function request(options: RequestOptions, callback?: (res: events.EventEmitter) =>void ): http.ClientRequest; - export function get(options: RequestOptions, callback?: (res: events.EventEmitter) =>void ): http.ClientRequest; - export var globalAgent: NodeAgent; -} - -declare module "punycode" { - export function decode(string: string): string; - export function encode(string: string): string; - export function toUnicode(domain: string): string; - export function toASCII(domain: string): string; - export var ucs2: ucs2; - export interface ucs2 { - decode(string: string): string; - encode(codePoints: number[]): string; - } - export var version; -} - -declare module "repl" { - import stream = require("stream"); - import events = require("events"); - - export interface ReplOptions { - prompt?: string; - input?: stream.ReadableStream; - output?: stream.WritableStream; - terminal?: boolean; - eval?: Function; - useColors?: boolean; - useGlobal?: boolean; - ignoreUndefined?: boolean; - writer?: Function; - } - export function start(options: ReplOptions): events.EventEmitter; -} - -declare module "readline" { - import events = require("events"); - import stream = require("stream"); - - export class ReadLine extends events.EventEmitter { - setPrompt(prompt: string, length: number): void; - prompt(preserveCursor?: boolean): void; - question(query: string, callback: Function): void; - pause(): void; - resume(): void; - close(): void; - write(data: any, key?: any): void; - } - export interface ReadLineOptions { - input: stream.ReadableStream; - output: stream.WritableStream; - completer?: Function; - terminal?: boolean; - } - export function createInterface(options: ReadLineOptions): ReadLine; -} - -declare module "vm" { - export interface Context { } - export interface Script { - runInThisContext(): void; - runInNewContext(sandbox?: Context): void; - } - export function runInThisContext(code: string, filename?: string): void; - export function runInNewContext(code: string, sandbox?: Context, filename?: string): void; - export function runInContext(code: string, context: Context, filename?: string): void; - export function createContext(initSandbox?: Context): Context; - export function createScript(code: string, filename?: string): Script; -} - -declare module "child_process" { - import events = require("events"); - import stream = require("stream"); - - export class ChildProcess extends events.EventEmitter { - stdin: stream.WritableStream; - stdout: stream.ReadableStream; - stderr: stream.ReadableStream; - pid: number; - kill(signal?: string): void; - send(message: any, sendHandle: any): void; - disconnect(): void; - } - - export function spawn(command: string, args?: string[], options?: { - cwd?: string; - stdio?: any; - custom?: any; - env?: any; - detached?: boolean; - }): ChildProcess; - export function exec(command: string, options: { - cwd?: string; - stdio?: any; - customFds?: any; - env?: any; - encoding?: string; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - }, callback: (error: Error, stdout: NodeBuffer, stderr: NodeBuffer) =>void ): ChildProcess; - export function exec(command: string, callback: (error: Error, stdout: NodeBuffer, stderr: NodeBuffer) =>void ): ChildProcess; - export function execFile(file: string, args: string[], options: { - cwd?: string; - stdio?: any; - customFds?: any; - env?: any; - encoding?: string; - timeout?: number; - maxBuffer?: string; - killSignal?: string; - }, callback: (error: Error, stdout: NodeBuffer, stderr: NodeBuffer) =>void ): ChildProcess; - export function fork(modulePath: string, args?: string[], options?: { - cwd?: string; - env?: any; - encoding?: string; - }): ChildProcess; -} - -declare module "url" { - export interface Url { - href?: string; - protocol?: string; - auth?: string; - hostname?: string; - port?: string; - host?: string; - pathname?: string; - search?: string; - query?: string; - slashes?: boolean; - hash?: string; - } - - export function parse(urlStr: string, parseQueryString? , slashesDenoteHost? ): Url; - export function format(url: Url): string; - export function resolve(from: string, to: string): string; -} - -declare module "dns" { - export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string; - export function lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string; - export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve6(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; -} - -declare module "net" { - import stream = require("stream"); - - export class NodeSocket extends stream.ReadWriteStream { - // Extended base methods - write(str: string, encoding?: string, fd?: string): boolean; - write(buffer: NodeBuffer): boolean; - - connect(port: number, host?: string, connectionListener?: Function): void; - connect(path: string, connectionListener?: Function): void; - bufferSize: number; - setEncoding(encoding?: string): void; - write(data: any, encoding?: string, callback?: Function): void; - end(data?: any, encoding?: string): void; - destroy(): void; - pause(): void; - resume(): void; - setTimeout(timeout: number, callback?: Function); void; - setNoDelay(noDelay?: boolean): void; - setKeepAlive(enable?: boolean, initialDelay?: number): void; - address(): { port: number; family: string; address: string; }; - remoteAddress: string; - remotePort: number; - bytesRead: number; - bytesWritten: number; - } - - export var Socket: { - new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): NodeSocket; - }; - - export class Server extends NodeSocket { - listen(port: number, host?: string, backlog?: number, listeningListener?: Function): void; - listen(path: string, listeningListener?: Function): void; - listen(handle: any, listeningListener?: Function): void; - close(callback?: Function): void; - address(): { port: number; family: string; address: string; }; - maxConnections: number; - connections: number; - } - export function createServer(connectionListener?: (socket: NodeSocket) =>void ): Server; - export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: NodeSocket) =>void ): Server; - export function connect(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): void; - export function connect(port: number, host?: string, connectionListener?: Function): void; - export function connect(path: string, connectionListener?: Function): void; - export function createConnection(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): void; - export function createConnection(port: number, host?: string, connectionListener?: Function): void; - export function createConnection(path: string, connectionListener?: Function): void; - export function isIP(input: string): number; - export function isIPv4(input: string): boolean; - export function isIPv6(input: string): boolean; -} - -declare module "dgram" { - import events = require("events"); - - export function createSocket(type: string, callback?: Function): Socket; - - export class Socket extends events.EventEmitter { - send(buf: NodeBuffer, offset: number, length: number, port: number, address: string, callback?: Function): void; - bind(port: number, address?: string): void; - close(): void; - address: { address: string; family: string; port: number; }; - setBroadcast(flag: boolean): void; - setMulticastTTL(ttl: number): void; - setMulticastLoopback(flag: boolean): void; - addMembership(multicastAddress: string, multicastInterface?: string): void; - dropMembership(multicastAddress: string, multicastInterface?: string): void; - } -} - -declare module "fs" { - import stream = require("stream"); - - export interface Stats { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - dev: number; - ino: number; - mode: number; - nlink: number; - uid: number; - gid: number; - rdev: number; - size: number; - blksize: number; - blocks: number; - atime: Date; - mtime: Date; - ctime: Date; - } - - export interface FSWatcher { - close(): void; - } - - export class ReadStream extends stream.ReadableStream { } - export class WriteStream extends stream.WritableStream { } - - export function rename(oldPath: string, newPath: string, callback?: Function): void; - export function renameSync(oldPath: string, newPath: string): void; - export function truncate(fd: number, len: number, callback?: Function): void; - export function truncateSync(fd: number, len: number): void; - export function chown(path: string, uid: number, gid: number, callback?: Function): void; - export function chownSync(path: string, uid: number, gid: number): void; - export function fchown(fd: number, uid: number, gid: number, callback?: Function): void; - export function fchownSync(fd: number, uid: number, gid: number): void; - export function lchown(path: string, uid: number, gid: number, callback?: Function): void; - export function lchownSync(path: string, uid: number, gid: number): void; - export function chmod(path: string, mode: number, callback?: Function): void; - export function chmod(path: string, mode: string, callback?: Function): void; - export function chmodSync(path: string, mode: number): void; - export function chmodSync(path: string, mode: string): void; - export function fchmod(fd: number, mode: number, callback?: Function): void; - export function fchmod(fd: number, mode: string, callback?: Function): void; - export function fchmodSync(fd: number, mode: number): void; - export function fchmodSync(fd: number, mode: string): void; - export function lchmod(path: string, mode: string, callback?: Function): void; - export function lchmod(path: string, mode: number, callback?: Function): void; - export function lchmodSync(path: string, mode: number): void; - export function lchmodSync(path: string, mode: string): void; - export function stat(path: string, callback?: (err: Error, stats: Stats) =>any): Stats; - export function lstat(path: string, callback?: (err: Error, stats: Stats) =>any): Stats; - export function fstat(fd: number, callback?: (err: Error, stats: Stats) =>any): Stats; - export function statSync(path: string): Stats; - export function lstatSync(path: string): Stats; - export function fstatSync(fd: number): Stats; - export function link(srcpath: string, dstpath: string, callback?: Function): void; - export function linkSync(srcpath: string, dstpath: string): void; - export function symlink(srcpath: string, dstpath: string, type?: string, callback?: Function): void; - export function symlinkSync(srcpath: string, dstpath: string, type?: string): void; - export function readlink(path: string, callback?: (err: Error, linkString: string) =>any): void; - export function realpath(path: string, callback?: (err: Error, resolvedPath: string) =>any): void; - export function realpath(path: string, cache: string, callback: (err: Error, resolvedPath: string) =>any): void; - export function realpathSync(path: string, cache?: string): string; - export function unlink(path: string, callback?: Function): void; - export function unlinkSync(path: string): void; - export function rmdir(path: string, callback?: Function): void; - export function rmdirSync(path: string): void; - export function mkdir(path: string, mode?: number, callback?: Function): void; - export function mkdir(path: string, mode?: string, callback?: Function): void; - export function mkdirSync(path: string, mode?: number): void; - export function mkdirSync(path: string, mode?: string): void; - export function readdir(path: string, callback?: (err: Error, files: string[]) => void): void; - export function readdirSync(path: string): string[]; - export function close(fd: number, callback?: Function): void; - export function closeSync(fd: number): void; - export function open(path: string, flags: string, mode?: string, callback?: (err: Error, fd: number) =>any): void; - export function openSync(path: string, flags: string, mode?: string): number; - export function utimes(path: string, atime: number, mtime: number, callback?: Function): void; - export function utimesSync(path: string, atime: number, mtime: number): void; - export function futimes(fd: number, atime: number, mtime: number, callback?: Function): void; - export function futimesSync(fd: number, atime: number, mtime: number): void; - export function fsync(fd: number, callback?: Function): void; - export function fsyncSync(fd: number): void; - export function write(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: Error, written: number, buffer: NodeBuffer) =>any): void; - export function writeSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; - export function read(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: Error, bytesRead: number, buffer: NodeBuffer) => void): void; - export function readSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; - export function readFile(filename: string, encoding: string, callback: (err: Error, data: string) => void ): void; - export function readFile(filename: string, callback: (err: Error, data: NodeBuffer) => void ): void; - export function readFileSync(filename: string): NodeBuffer; - export function readFileSync(filename: string, encoding: string): string; - export function writeFile(filename: string, data: any, encoding?: string, callback?: Function): void; - export function writeFileSync(filename: string, data: any, encoding?: string): void; - export function appendFile(filename: string, data: any, encoding?: string, callback?: Function): void; - export function appendFileSync(filename: string, data: any, encoding?: string): void; - export function watchFile(filename: string, listener: { curr: Stats; prev: Stats; }): void; - export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: { curr: Stats; prev: Stats; }): void; - export function unwatchFile(filename: string, listener?: Stats): void; - export function watch(filename: string, options?: { persistent?: boolean; }, listener?: (event: string, filename: string) =>any): FSWatcher; - export function exists(path: string, callback?: (exists: boolean) =>void ): void; - export function existsSync(path: string): boolean; - export function createReadStream(path: string, options?: { - flags?: string; - encoding?: string; - fd?: string; - mode?: number; - bufferSize?: number; - }): ReadStream; - export function createWriteStream(path: string, options?: { - flags?: string; - encoding?: string; - string?: string; - }): WriteStream; -} - -declare module "path" { - export function normalize(p: string): string; - export function join(...paths: any[]): string; - export function resolve(from: string, to: string): string; - export function resolve(from: string, from2: string, to: string): string; - export function resolve(from: string, from2: string, from3: string, to: string): string; - export function resolve(from: string, from2: string, from3: string, from4: string, to: string): string; - export function resolve(from: string, from2: string, from3: string, from4: string, from5: string, to: string): string; - export function relative(from: string, to: string): string; - export function dirname(p: string): string; - export function basename(p: string, ext?: string): string; - export function extname(p: string): string; - export var sep: string; -} - -declare module "string_decoder" { - export interface NodeStringDecoder { - write(buffer: NodeBuffer): string; - detectIncompleteChar(buffer: NodeBuffer): number; - } - export var StringDecoder: { - new (encoding: string): NodeStringDecoder; - }; -} - -declare module "tls" { - import crypto = require("crypto"); - import net = require("net"); - import stream = require("stream"); - - export var CLIENT_RENEG_LIMIT: number; - export var CLIENT_RENEG_WINDOW: number; - - export interface TlsOptions { - pfx?: any; //string or buffer - key?: any; //string or buffer - passphrase?: string; - cert?: any; - ca?: any; //string or buffer - crl?: any; //string or string array - ciphers?: string; - honorCipherOrder?: any; - requestCert?: boolean; - rejectUnauthorized?: boolean; - NPNProtocols?: any; //array or Buffer; - SNICallback?: (servername: string) => any; - } - - export interface ConnectionOptions { - host?: string; - port?: number; - socket?: net.NodeSocket; - pfx?: any; //string | Buffer - key?: any; //string | Buffer - passphrase?: string; - cert?: any; //string | Buffer - ca?: any; //Array of string | Buffer - rejectUnauthorized?: boolean; - NPNProtocols?: any; //Array of string | Buffer - servername?: string; - } - - export class Server extends net.Server { - // Extended base methods - listen(port: number, host?: string, backlog?: number, listeningListener?: Function): void; - listen(path: string, listeningListener?: Function): void; - listen(handle: any, listeningListener?: Function): void; - - listen(port: number, host?: string, callback?: Function): void; - close(): void; - address(): { port: number; family: string; address: string; }; - addContext(hostName: string, credentials: { - key: string; - cert: string; - ca: string; - }): void; - maxConnections: number; - connections: number; - } - - export class ClearTextStream extends stream.ReadWriteStream { - authorized: boolean; - authorizationError: Error; - getPeerCertificate(): any; - getCipher: { - name: string; - version: string; - }; - address: { - port: number; - family: string; - address: string; - }; - remoteAddress: string; - remotePort: number; - } - - export interface SecurePair { - encrypted: any; - cleartext: any; - } - - export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) =>void ): Server; - export function connect(options: TlsOptions, secureConnectionListener?: () =>void ): ClearTextStream; - export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; - export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; - export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; -} - -declare module "crypto" { - export interface CredentialDetails { - pfx: string; - key: string; - passphrase: string; - cert: string; - ca: any; //string | string array - crl: any; //string | string array - ciphers: string; - } - export interface Credentials { context?: any; } - export function createCredentials(details: CredentialDetails): Credentials; - export function createHash(algorithm: string): Hash; - export function createHmac(algorithm: string, key: string): Hmac; - export interface Hash { - update(data: any, input_encoding?: string): void; - digest(encoding?: string): string; - } - export interface Hmac { - update(data: any): void; - digest(encoding?: string): void; - } - export function createCipher(algorithm: string, password: any): Cipher; - export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; - export interface Cipher { - update(data: any, input_encoding?: string, output_encoding?: string): string; - final(output_encoding?: string): string; - setAutoPadding(auto_padding: boolean): void; - createDecipher(algorithm: string, password: any): Decipher; - createDecipheriv(algorithm: string, key: any, iv: any): Decipher; - } - export interface Decipher { - update(data: any, input_encoding?: string, output_encoding?: string): void; - final(output_encoding?: string): string; - setAutoPadding(auto_padding: boolean): void; - } - export function createSign(algorithm: string): Signer; - export interface Signer { - update(data: any): void; - sign(private_key: string, output_format: string): string; - } - export function createVerify(algorith: string): Verify; - export interface Verify { - update(data: any): void; - verify(object: string, signature: string, signature_format?: string): boolean; - } - export function createDiffieHellman(prime_length: number): DiffieHellman; - export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman; - export interface DiffieHellman { - generateKeys(encoding?: string): string; - computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; - getPrime(encoding?: string): string; - getGenerator(encoding: string): string; - getPublicKey(encoding?: string): string; - getPrivateKey(encoding?: string): string; - setPublicKey(public_key: string, encoding?: string): void; - setPrivateKey(public_key: string, encoding?: string): void; - } - export function getDiffieHellman(group_name: string): DiffieHellman; - export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: string) => any): void; - export function randomBytes(size: number, callback?: (err: Error, buf: NodeBuffer) =>void ); -} - -declare module "stream" { - import events = require("events"); - - export interface WriteStream { - writable: boolean; - write(str: string, encoding?: string, fd?: string): boolean; - write(buffer: NodeBuffer): boolean; - end(): void; - end(str: string, enconding: string): void; - end(buffer: NodeBuffer): void; - destroy(): void; - destroySoon(): void; - } - - export class WritableStream extends events.EventEmitter implements WriteStream { - writable: boolean; - write(str: string, encoding?: string, fd?: string): boolean; - write(buffer: NodeBuffer): boolean; - end(): void; - end(str: string, enconding: string): void; - end(buffer: NodeBuffer): void; - destroy(): void; - destroySoon(): void; - } - - export class ReadableStream extends events.EventEmitter { - readable: boolean; - setEncoding(encoding: string): void; - pause(): void; - resume(): void; - destroy(): void; - pipe(destination: WriteStream, options?: { end?: boolean; }): void; - } - - export class ReadWriteStream extends events.EventEmitter implements WriteStream { - readable: boolean; - setEncoding(encoding: string): void; - pause(): void; - resume(): void; - pipe(destination: WriteStream, options?: { end?: boolean; }): void; - - writable: boolean; - write(str: string, encoding?: string, fd?: string): boolean; - write(buffer: NodeBuffer): boolean; - end(): void; - end(str: string, enconding: string): void; - end(buffer: NodeBuffer): void; - destroy(): void; - destroySoon(): void; - } -} - -declare module "util" { - export function format(format: any, ...param: any[]): string; - export function debug(string: string): void; - export function error(...param: any[]): void; - export function puts(...param: any[]): void; - export function print(...param: any[]): void; - export function log(string: string): void; - export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): void; - export function isArray(object: any): boolean; - export function isRegExp(object: any): boolean; - export function isDate(object: any): boolean; - export function isError(object: any): boolean; - export function inherits(constructor: any, superConstructor: any): void; -} - -declare module "assert" { - export function fail(actual: any, expected: any, message: string, operator: string): void; - export function assert(value: any, message: string): void; - export function ok(value: any, message?: string): void; - export function equal(actual: any, expected: any, message?: string): void; - export function notEqual(actual: any, expected: any, message?: string): void; - export function deepEqual(actual: any, expected: any, message?: string): void; - export function notDeepEqual(acutal: any, expected: any, message?: string): void; - export function strictEqual(actual: any, expected: any, message?: string): void; - export function notStrictEqual(actual: any, expected: any, message?: string): void; - export function throws(block: any, error?: any, messsage?: string): void; - export function doesNotThrow(block: any, error?: any, messsage?: string): void; - export function ifError(value: any): void; -} - -declare module "tty" { - import net = require("net"); - - export function isatty(fd: string): boolean; - export class ReadStream extends net.NodeSocket { - isRaw: boolean; - setRawMode(mode: boolean): void; - } - export class WriteStream extends net.NodeSocket { - columns: number; - rows: number; - } -} - -declare module "domain" { - import events = require("events"); - - export class Domain extends events.EventEmitter { } - - export function create(): Domain; - export function run(fn: Function): void; - export function add(emitter: events.EventEmitter): void; - export function remove(emitter: events.EventEmitter): void; - export function bind(cb: (er: Error, data: any) =>any): any; - export function intercept(cb: (data: any) => any): any; - export function dispose(): void; -} \ No newline at end of file diff --git a/node/package.json b/node/package.json new file mode 100644 index 0000000..8438908 --- /dev/null +++ b/node/package.json @@ -0,0 +1,32 @@ +{ + "name": "node", + "version": "1.0.0", + "description": "Node examples using TypeScript", + "scripts": { + "build": "tsc", + "lint": "tslint --config tslint.json --project ." + }, + "contributors": [ + { + "name": "Mohamed Hegazy", + "url": "https://github.com/mhegazy" + }, + { + "name": "Lucas de Almeida Carotta", + "url": "https://github.com/Fazendaaa" + } + ], + "devDependencies": { + "@types/node": "^10.11.4", + "ts-node": "^7.0.1", + "tslint": "^5.11.0", + "tslint-microsoft-contrib": "^5.2.1", + "typescript": "^3.1.1" + }, + "husky": { + "hooks": { + "pre-push": "npm run lint" + } + }, + "dependencies": {} +} diff --git a/node/src/APIClient.ts b/node/src/APIClient.ts new file mode 100644 index 0000000..84a8ef7 --- /dev/null +++ b/node/src/APIClient.ts @@ -0,0 +1,39 @@ +/** + * API client example. + */ +import { IncomingMessage, request } from 'http'; + +const handleResponse = (resolve: (data: string) => void, reject: (data: Error) => void, response: IncomingMessage): void => { + let chunk = ''; + const { statusCode } = response; + + if (statusCode !== 200) { + reject(new Error('Server error')); + } + + response.setEncoding('utf8') + .on('error', reject) + .on('uncaughtException', reject) + .on('data', (data: string) => chunk += data) + .on('end', () => { resolve(chunk); }); +}; + +const ping = async (): Promise => new Promise((resolve: (data: string) => void, reject: (data: Error) => void) => { + const post = request({ + path: '/', + port: 8080, + method: 'GET', + hostname: 'localhost', + headers: { + 'Content-Type': 'text/plain' + } + }); + const curriedHandleResponse = ((response: IncomingMessage) => { handleResponse(resolve, reject, response); }); + + post.write('ping'); + post.on('response', curriedHandleResponse); + post.on('error', () => { reject(new Error('Request error')); }); + post.end(); +}); + +ping().then(console.log).catch(console.error); diff --git a/node/src/APIServer.ts b/node/src/APIServer.ts new file mode 100644 index 0000000..38fe4d3 --- /dev/null +++ b/node/src/APIServer.ts @@ -0,0 +1,21 @@ +/** + * API example server. + */ +import { createServer, IncomingMessage, ServerResponse } from 'http'; + +const server = createServer((sent: IncomingMessage, res: ServerResponse) => { + const body = []; + + sent.on('data', (data: Buffer) => body.push(data)); + sent.on('error', (err) => { console.error(err); }); + sent.on('end', () => { + const message = Buffer.concat(body).toString(); + + console.log(message); + }); + + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.end('pong'); +}); + +server.listen(8080, 'localhost', () => { console.log('Server running at https://localhost:8080/'); }); diff --git a/node/src/HttpServer.ts b/node/src/HttpServer.ts new file mode 100644 index 0000000..9f55352 --- /dev/null +++ b/node/src/HttpServer.ts @@ -0,0 +1,14 @@ +/** + * HTTPS server example. + */ +import { createServer, IncomingMessage, ServerResponse } from 'http'; + +const host = 'localhost'; +const port = 1337; + +const server = createServer((_: IncomingMessage, res: ServerResponse) => { + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.end('Hello World\n'); +}); + +server.listen(port, host, () => { console.log(`Server running at ${host}:${port}`); }); diff --git a/node/src/TcpServer.ts b/node/src/TcpServer.ts new file mode 100644 index 0000000..d72bcfa --- /dev/null +++ b/node/src/TcpServer.ts @@ -0,0 +1,14 @@ +/** + * TCP server example. + */ +import { createServer, Socket } from 'net'; + +const host = 'localhost'; +const port = 1337; + +const server = createServer((socket: Socket) => { + socket.write('Echo server\r\n'); + socket.pipe(socket); +}); + +server.listen(port, host, () => { console.log(`Server running at ${host}:${port}`); }); diff --git a/node/src/Wikipedia.ts b/node/src/Wikipedia.ts new file mode 100644 index 0000000..bbd76a9 --- /dev/null +++ b/node/src/Wikipedia.ts @@ -0,0 +1,41 @@ +/** + * Searches Wikipedia database + */ +import { IncomingMessage } from 'http'; +import { request } from 'https'; + +const response = (res: IncomingMessage) => { + const { statusCode } = res; + let chunk = ''; + + if (statusCode !== 200) { + console.error(new Error(`[Request status ${statusCode}] Not accepted`)); + } else { + res.on('error', console.error) + .on('uncaughtException', console.error) + .on('data', (data: string) => chunk += data) + .on('end', () => { + const result = JSON.parse(chunk); + + console.log(result); + }); + } +}; + +const search = 'microsoft'; +const query = `action=query&format=json&list=search&srsearch=${encodeURI(search)}`; +const path = `/w/api.php?${query}`; +const options = { + path, + method: 'GET', + hostname: 'en.wikipedia.org', + headers: { + Accept: 'application/json', + 'Content-Type': 'text/html' + } +}; +const wikipedia = request(options); + +wikipedia.on('error', console.error) + .on('response', response) + .end(); diff --git a/node/src/WordCounter.ts b/node/src/WordCounter.ts new file mode 100644 index 0000000..a49dfa2 --- /dev/null +++ b/node/src/WordCounter.ts @@ -0,0 +1,13 @@ +/** + * Reads file then shows how many matching occurrences of a word is found + */ +import { readFileSync } from 'fs'; +import { join } from 'path'; + +const path = join(__dirname, '../lorem.txt'); +const ipsum = readFileSync(path, { encoding: 'utf8' }); +const word = 'ut'; +const re = new RegExp(word, 'gm'); +const matching = ipsum.match(re); + +console.log(`Number of occurrences of the \"${word}\" word is: ${matching.length}`); diff --git a/node/tsconfig.json b/node/tsconfig.json new file mode 100644 index 0000000..f7fc400 --- /dev/null +++ b/node/tsconfig.json @@ -0,0 +1,62 @@ +{ + "compilerOptions": { + /* Basic Options */ + "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ + "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ + // "lib": [], /* Specify library files to be included in the compilation. */ + // "allowJs": true, /* Allow javascript files to be compiled. */ + // "checkJs": true, /* Report errors in .js files. */ + // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ + // "declaration": true, /* Generates corresponding '.d.ts' file. */ + // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ + "sourceMap": true, /* Generates corresponding '.map' file. */ + // "outFile": "./", /* Concatenate and emit output to single file. */ + "outDir": "./dist", /* Redirect output structure to the directory. */ + "rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ + // "composite": true, /* Enable project compilation */ + // "removeComments": true, /* Do not emit comments to output. */ + // "noEmit": true, /* Do not emit outputs. */ + // "importHelpers": true, /* Import emit helpers from 'tslib'. */ + // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ + // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ + + /* Strict Type-Checking Options */ + "strict": true, /* Enable all strict type-checking options. */ + "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ + "strictNullChecks": true, /* Enable strict null checks. */ + "strictFunctionTypes": true, /* Enable strict checking of function types. */ + "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ + "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ + "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ + + /* Additional Checks */ + "noUnusedLocals": true, /* Report errors on unused locals. */ + "noUnusedParameters": true, /* Report errors on unused parameters. */ + "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ + + /* Module Resolution Options */ + "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ + "baseUrl": "./src", /* Base directory to resolve non-absolute module names. */ + // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ + // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ + // "typeRoots": [], /* List of folders to include type definitions from. */ + // "types": [], /* Type declaration files to be included in compilation. */ + "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ + "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ + // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + + /* Source Map Options */ + // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ + // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ + + /* Experimental Options */ + "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ + "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + }, + "exclude": [ + "./index.ts" + ] +} diff --git a/node/tslint.json b/node/tslint.json new file mode 100644 index 0000000..39a8b28 --- /dev/null +++ b/node/tslint.json @@ -0,0 +1,12 @@ +{ + "defaultSeverity": "error", + "extends": [ + "tslint-microsoft-contrib" + ], + "jsRules": {}, + "rules": { + "typedef": false, + "no-console": false + }, + "rulesDirectory": [] +} diff --git a/raytracer/raytracer.html b/raytracer/raytracer.html index 55b5f0b..77f89b1 100644 --- a/raytracer/raytracer.html +++ b/raytracer/raytracer.html @@ -1,8 +1,8 @@ - - - Raytracer - - - - + + + Raytracer + + + + \ No newline at end of file diff --git a/raytracer/raytracer.ts b/raytracer/raytracer.ts index 56f6cec..6b15fc7 100644 --- a/raytracer/raytracer.ts +++ b/raytracer/raytracer.ts @@ -1,277 +1,277 @@ - -class Vector { - constructor(public x: number, - public y: number, - public z: number) { - } - static times(k: number, v: Vector) { return new Vector(k * v.x, k * v.y, k * v.z); } - static minus(v1: Vector, v2: Vector) { return new Vector(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z); } - static plus(v1: Vector, v2: Vector) { return new Vector(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z); } - static dot(v1: Vector, v2: Vector) { return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z; } - static mag(v: Vector) { return Math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z); } - static norm(v: Vector) { - var mag = Vector.mag(v); - var div = (mag === 0) ? Infinity : 1.0 / mag; - return Vector.times(div, v); - } - static cross(v1: Vector, v2: Vector) { - return new Vector(v1.y * v2.z - v1.z * v2.y, - v1.z * v2.x - v1.x * v2.z, - v1.x * v2.y - v1.y * v2.x); - } -} - -class Color { - constructor(public r: number, - public g: number, - public b: number) { - } - static scale(k: number, v: Color) { return new Color(k * v.r, k * v.g, k * v.b); } - static plus(v1: Color, v2: Color) { return new Color(v1.r + v2.r, v1.g + v2.g, v1.b + v2.b); } - static times(v1: Color, v2: Color) { return new Color(v1.r * v2.r, v1.g * v2.g, v1.b * v2.b); } - static white = new Color(1.0, 1.0, 1.0); - static grey = new Color(0.5, 0.5, 0.5); - static black = new Color(0.0, 0.0, 0.0); - static background = Color.black; - static defaultColor = Color.black; - static toDrawingColor(c: Color) { - var legalize = d => d > 1 ? 1 : d; - return { - r: Math.floor(legalize(c.r) * 255), - g: Math.floor(legalize(c.g) * 255), - b: Math.floor(legalize(c.b) * 255) - } - } -} - -class Camera { - public forward: Vector; - public right: Vector; - public up: Vector; - - constructor(public pos: Vector, lookAt: Vector) { - var down = new Vector(0.0, -1.0, 0.0); - this.forward = Vector.norm(Vector.minus(lookAt, this.pos)); - this.right = Vector.times(1.5, Vector.norm(Vector.cross(this.forward, down))); - this.up = Vector.times(1.5, Vector.norm(Vector.cross(this.forward, this.right))); - } -} - -interface Ray { - start: Vector; - dir: Vector; -} - -interface Intersection { - thing: Thing; - ray: Ray; - dist: number; -} - -interface Surface { - diffuse: (pos: Vector) => Color; - specular: (pos: Vector) => Color; - reflect: (pos: Vector) => number; - roughness: number; -} - -interface Thing { - intersect: (ray: Ray) => Intersection; - normal: (pos: Vector) => Vector; - surface: Surface; -} - -interface Light { - pos: Vector; - color: Color; -} - -interface Scene { - things: Thing[]; - lights: Light[]; - camera: Camera; -} - -class Sphere implements Thing { - public radius2: number; - - constructor(public center: Vector, radius: number, public surface: Surface) { - this.radius2 = radius * radius; - } - normal(pos: Vector): Vector { return Vector.norm(Vector.minus(pos, this.center)); } - intersect(ray: Ray) { - var eo = Vector.minus(this.center, ray.start); - var v = Vector.dot(eo, ray.dir); - var dist = 0; - if (v >= 0) { - var disc = this.radius2 - (Vector.dot(eo, eo) - v * v); - if (disc >= 0) { - dist = v - Math.sqrt(disc); - } - } - if (dist === 0) { - return null; - } else { - return { thing: this, ray: ray, dist: dist }; - } - } -} - -class Plane implements Thing { - public normal: (pos: Vector) =>Vector; - public intersect: (ray: Ray) =>Intersection; - constructor(norm: Vector, offset: number, public surface: Surface) { - this.normal = function(pos: Vector) { return norm; } - this.intersect = function(ray: Ray): Intersection { - var denom = Vector.dot(norm, ray.dir); - if (denom > 0) { - return null; - } else { - var dist = (Vector.dot(norm, ray.start) + offset) / (-denom); - return { thing: this, ray: ray, dist: dist }; - } - } - } -} - -module Surfaces { - export var shiny: Surface = { - diffuse: function(pos) { return Color.white; }, - specular: function(pos) { return Color.grey; }, - reflect: function(pos) { return 0.7; }, - roughness: 250 - } - export var checkerboard: Surface = { - diffuse: function(pos) { - if ((Math.floor(pos.z) + Math.floor(pos.x)) % 2 !== 0) { - return Color.white; - } else { - return Color.black; - } - }, - specular: function(pos) { return Color.white; }, - reflect: function(pos) { - if ((Math.floor(pos.z) + Math.floor(pos.x)) % 2 !== 0) { - return 0.1; - } else { - return 0.7; - } - }, - roughness: 150 - } -} - - -class RayTracer { - private maxDepth = 5; - - private intersections(ray: Ray, scene: Scene) { - var closest = +Infinity; - var closestInter: Intersection = undefined; - for (var i in scene.things) { - var inter = scene.things[i].intersect(ray); - if (inter != null && inter.dist < closest) { - closestInter = inter; - closest = inter.dist; - } - } - return closestInter; - } - - private testRay(ray: Ray, scene: Scene) { - var isect = this.intersections(ray, scene); - if (isect != null) { - return isect.dist; - } else { - return undefined; - } - } - - private traceRay(ray: Ray, scene: Scene, depth: number): Color { - var isect = this.intersections(ray, scene); - if (isect === undefined) { - return Color.background; - } else { - return this.shade(isect, scene, depth); - } - } - - private shade(isect: Intersection, scene: Scene, depth: number) { - var d = isect.ray.dir; - var pos = Vector.plus(Vector.times(isect.dist, d), isect.ray.start); - var normal = isect.thing.normal(pos); - var reflectDir = Vector.minus(d, Vector.times(2, Vector.times(Vector.dot(normal, d), normal))); - var naturalColor = Color.plus(Color.background, - this.getNaturalColor(isect.thing, pos, normal, reflectDir, scene)); - var reflectedColor = (depth >= this.maxDepth) ? Color.grey : this.getReflectionColor(isect.thing, pos, normal, reflectDir, scene, depth); - return Color.plus(naturalColor, reflectedColor); - } - - private getReflectionColor(thing: Thing, pos: Vector, normal: Vector, rd: Vector, scene: Scene, depth: number) { - return Color.scale(thing.surface.reflect(pos), this.traceRay({ start: pos, dir: rd }, scene, depth + 1)); - } - - private getNaturalColor(thing: Thing, pos: Vector, norm: Vector, rd: Vector, scene: Scene) { - var addLight = (col, light) => { - var ldis = Vector.minus(light.pos, pos); - var livec = Vector.norm(ldis); - var neatIsect = this.testRay({ start: pos, dir: livec }, scene); - var isInShadow = (neatIsect === undefined) ? false : (neatIsect <= Vector.mag(ldis)); - if (isInShadow) { - return col; - } else { - var illum = Vector.dot(livec, norm); - var lcolor = (illum > 0) ? Color.scale(illum, light.color) - : Color.defaultColor; - var specular = Vector.dot(livec, Vector.norm(rd)); - var scolor = (specular > 0) ? Color.scale(Math.pow(specular, thing.surface.roughness), light.color) - : Color.defaultColor; - return Color.plus(col, Color.plus(Color.times(thing.surface.diffuse(pos), lcolor), - Color.times(thing.surface.specular(pos), scolor))); - } - } - return scene.lights.reduce(addLight, Color.defaultColor); - } - - render(scene, ctx, screenWidth, screenHeight) { - var getPoint = (x, y, camera) => { - var recenterX = x =>(x - (screenWidth / 2.0)) / 2.0 / screenWidth; - var recenterY = y => - (y - (screenHeight / 2.0)) / 2.0 / screenHeight; - return Vector.norm(Vector.plus(camera.forward, Vector.plus(Vector.times(recenterX(x), camera.right), Vector.times(recenterY(y), camera.up)))); - } - for (var y = 0; y < screenHeight; y++) { - for (var x = 0; x < screenWidth; x++) { - var color = this.traceRay({ start: scene.camera.pos, dir: getPoint(x, y, scene.camera) }, scene, 0); - var c = Color.toDrawingColor(color); - ctx.fillStyle = "rgb(" + String(c.r) + ", " + String(c.g) + ", " + String(c.b) + ")"; - ctx.fillRect(x, y, x + 1, y + 1); - } - } - } -} - - -function defaultScene(): Scene { - return { - things: [new Plane(new Vector(0.0, 1.0, 0.0), 0.0, Surfaces.checkerboard), - new Sphere(new Vector(0.0, 1.0, -0.25), 1.0, Surfaces.shiny), - new Sphere(new Vector(-1.0, 0.5, 1.5), 0.5, Surfaces.shiny)], - lights: [{ pos: new Vector(-2.0, 2.5, 0.0), color: new Color(0.49, 0.07, 0.07) }, - { pos: new Vector(1.5, 2.5, 1.5), color: new Color(0.07, 0.07, 0.49) }, - { pos: new Vector(1.5, 2.5, -1.5), color: new Color(0.07, 0.49, 0.071) }, - { pos: new Vector(0.0, 3.5, 0.0), color: new Color(0.21, 0.21, 0.35) }], - camera: new Camera(new Vector(3.0, 2.0, 4.0), new Vector(-1.0, 0.5, 0.0)) - }; -} - -function exec() { - var canv = document.createElement("canvas"); - canv.width = 256; - canv.height = 256; - document.body.appendChild(canv); - var ctx = canv.getContext("2d"); - var rayTracer = new RayTracer(); - return rayTracer.render(defaultScene(), ctx, 256, 256); -} - -exec(); + +class Vector { + constructor(public x: number, + public y: number, + public z: number) { + } + static times(k: number, v: Vector) { return new Vector(k * v.x, k * v.y, k * v.z); } + static minus(v1: Vector, v2: Vector) { return new Vector(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z); } + static plus(v1: Vector, v2: Vector) { return new Vector(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z); } + static dot(v1: Vector, v2: Vector) { return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z; } + static mag(v: Vector) { return Math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z); } + static norm(v: Vector) { + var mag = Vector.mag(v); + var div = (mag === 0) ? Infinity : 1.0 / mag; + return Vector.times(div, v); + } + static cross(v1: Vector, v2: Vector) { + return new Vector(v1.y * v2.z - v1.z * v2.y, + v1.z * v2.x - v1.x * v2.z, + v1.x * v2.y - v1.y * v2.x); + } +} + +class Color { + constructor(public r: number, + public g: number, + public b: number) { + } + static scale(k: number, v: Color) { return new Color(k * v.r, k * v.g, k * v.b); } + static plus(v1: Color, v2: Color) { return new Color(v1.r + v2.r, v1.g + v2.g, v1.b + v2.b); } + static times(v1: Color, v2: Color) { return new Color(v1.r * v2.r, v1.g * v2.g, v1.b * v2.b); } + static white = new Color(1.0, 1.0, 1.0); + static grey = new Color(0.5, 0.5, 0.5); + static black = new Color(0.0, 0.0, 0.0); + static background = Color.black; + static defaultColor = Color.black; + static toDrawingColor(c: Color) { + var legalize = d => d > 1 ? 1 : d; + return { + r: Math.floor(legalize(c.r) * 255), + g: Math.floor(legalize(c.g) * 255), + b: Math.floor(legalize(c.b) * 255) + } + } +} + +class Camera { + public forward: Vector; + public right: Vector; + public up: Vector; + + constructor(public pos: Vector, lookAt: Vector) { + var down = new Vector(0.0, -1.0, 0.0); + this.forward = Vector.norm(Vector.minus(lookAt, this.pos)); + this.right = Vector.times(1.5, Vector.norm(Vector.cross(this.forward, down))); + this.up = Vector.times(1.5, Vector.norm(Vector.cross(this.forward, this.right))); + } +} + +interface Ray { + start: Vector; + dir: Vector; +} + +interface Intersection { + thing: Thing; + ray: Ray; + dist: number; +} + +interface Surface { + diffuse: (pos: Vector) => Color; + specular: (pos: Vector) => Color; + reflect: (pos: Vector) => number; + roughness: number; +} + +interface Thing { + intersect: (ray: Ray) => Intersection; + normal: (pos: Vector) => Vector; + surface: Surface; +} + +interface Light { + pos: Vector; + color: Color; +} + +interface Scene { + things: Thing[]; + lights: Light[]; + camera: Camera; +} + +class Sphere implements Thing { + public radius2: number; + + constructor(public center: Vector, radius: number, public surface: Surface) { + this.radius2 = radius * radius; + } + normal(pos: Vector): Vector { return Vector.norm(Vector.minus(pos, this.center)); } + intersect(ray: Ray) { + var eo = Vector.minus(this.center, ray.start); + var v = Vector.dot(eo, ray.dir); + var dist = 0; + if (v >= 0) { + var disc = this.radius2 - (Vector.dot(eo, eo) - v * v); + if (disc >= 0) { + dist = v - Math.sqrt(disc); + } + } + if (dist === 0) { + return null; + } else { + return { thing: this, ray: ray, dist: dist }; + } + } +} + +class Plane implements Thing { + public normal: (pos: Vector) =>Vector; + public intersect: (ray: Ray) =>Intersection; + constructor(norm: Vector, offset: number, public surface: Surface) { + this.normal = function(pos: Vector) { return norm; } + this.intersect = function(ray: Ray): Intersection { + var denom = Vector.dot(norm, ray.dir); + if (denom > 0) { + return null; + } else { + var dist = (Vector.dot(norm, ray.start) + offset) / (-denom); + return { thing: this, ray: ray, dist: dist }; + } + } + } +} + +module Surfaces { + export var shiny: Surface = { + diffuse: function(pos) { return Color.white; }, + specular: function(pos) { return Color.grey; }, + reflect: function(pos) { return 0.7; }, + roughness: 250 + } + export var checkerboard: Surface = { + diffuse: function(pos) { + if ((Math.floor(pos.z) + Math.floor(pos.x)) % 2 !== 0) { + return Color.white; + } else { + return Color.black; + } + }, + specular: function(pos) { return Color.white; }, + reflect: function(pos) { + if ((Math.floor(pos.z) + Math.floor(pos.x)) % 2 !== 0) { + return 0.1; + } else { + return 0.7; + } + }, + roughness: 150 + } +} + + +class RayTracer { + private maxDepth = 5; + + private intersections(ray: Ray, scene: Scene) { + var closest = +Infinity; + var closestInter: Intersection = undefined; + for (var i in scene.things) { + var inter = scene.things[i].intersect(ray); + if (inter != null && inter.dist < closest) { + closestInter = inter; + closest = inter.dist; + } + } + return closestInter; + } + + private testRay(ray: Ray, scene: Scene) { + var isect = this.intersections(ray, scene); + if (isect != null) { + return isect.dist; + } else { + return undefined; + } + } + + private traceRay(ray: Ray, scene: Scene, depth: number): Color { + var isect = this.intersections(ray, scene); + if (isect === undefined) { + return Color.background; + } else { + return this.shade(isect, scene, depth); + } + } + + private shade(isect: Intersection, scene: Scene, depth: number) { + var d = isect.ray.dir; + var pos = Vector.plus(Vector.times(isect.dist, d), isect.ray.start); + var normal = isect.thing.normal(pos); + var reflectDir = Vector.minus(d, Vector.times(2, Vector.times(Vector.dot(normal, d), normal))); + var naturalColor = Color.plus(Color.background, + this.getNaturalColor(isect.thing, pos, normal, reflectDir, scene)); + var reflectedColor = (depth >= this.maxDepth) ? Color.grey : this.getReflectionColor(isect.thing, pos, normal, reflectDir, scene, depth); + return Color.plus(naturalColor, reflectedColor); + } + + private getReflectionColor(thing: Thing, pos: Vector, normal: Vector, rd: Vector, scene: Scene, depth: number) { + return Color.scale(thing.surface.reflect(pos), this.traceRay({ start: pos, dir: rd }, scene, depth + 1)); + } + + private getNaturalColor(thing: Thing, pos: Vector, norm: Vector, rd: Vector, scene: Scene) { + var addLight = (col, light) => { + var ldis = Vector.minus(light.pos, pos); + var livec = Vector.norm(ldis); + var neatIsect = this.testRay({ start: pos, dir: livec }, scene); + var isInShadow = (neatIsect === undefined) ? false : (neatIsect <= Vector.mag(ldis)); + if (isInShadow) { + return col; + } else { + var illum = Vector.dot(livec, norm); + var lcolor = (illum > 0) ? Color.scale(illum, light.color) + : Color.defaultColor; + var specular = Vector.dot(livec, Vector.norm(rd)); + var scolor = (specular > 0) ? Color.scale(Math.pow(specular, thing.surface.roughness), light.color) + : Color.defaultColor; + return Color.plus(col, Color.plus(Color.times(thing.surface.diffuse(pos), lcolor), + Color.times(thing.surface.specular(pos), scolor))); + } + } + return scene.lights.reduce(addLight, Color.defaultColor); + } + + render(scene, ctx, screenWidth, screenHeight) { + var getPoint = (x, y, camera) => { + var recenterX = x =>(x - (screenWidth / 2.0)) / 2.0 / screenWidth; + var recenterY = y => - (y - (screenHeight / 2.0)) / 2.0 / screenHeight; + return Vector.norm(Vector.plus(camera.forward, Vector.plus(Vector.times(recenterX(x), camera.right), Vector.times(recenterY(y), camera.up)))); + } + for (var y = 0; y < screenHeight; y++) { + for (var x = 0; x < screenWidth; x++) { + var color = this.traceRay({ start: scene.camera.pos, dir: getPoint(x, y, scene.camera) }, scene, 0); + var c = Color.toDrawingColor(color); + ctx.fillStyle = "rgb(" + String(c.r) + ", " + String(c.g) + ", " + String(c.b) + ")"; + ctx.fillRect(x, y, 1, 1); + } + } + } +} + + +function defaultScene(): Scene { + return { + things: [new Plane(new Vector(0.0, 1.0, 0.0), 0.0, Surfaces.checkerboard), + new Sphere(new Vector(0.0, 1.0, -0.25), 1.0, Surfaces.shiny), + new Sphere(new Vector(-1.0, 0.5, 1.5), 0.5, Surfaces.shiny)], + lights: [{ pos: new Vector(-2.0, 2.5, 0.0), color: new Color(0.49, 0.07, 0.07) }, + { pos: new Vector(1.5, 2.5, 1.5), color: new Color(0.07, 0.07, 0.49) }, + { pos: new Vector(1.5, 2.5, -1.5), color: new Color(0.07, 0.49, 0.071) }, + { pos: new Vector(0.0, 3.5, 0.0), color: new Color(0.21, 0.21, 0.35) }], + camera: new Camera(new Vector(3.0, 2.0, 4.0), new Vector(-1.0, 0.5, 0.0)) + }; +} + +function exec() { + var canv = document.createElement("canvas"); + canv.width = 256; + canv.height = 256; + document.body.appendChild(canv); + var ctx = canv.getContext("2d"); + var rayTracer = new RayTracer(); + return rayTracer.render(defaultScene(), ctx, canv.width, canv.height); +} + +exec(); diff --git a/raytracer/tsconfig.json b/raytracer/tsconfig.json new file mode 100644 index 0000000..8036243 --- /dev/null +++ b/raytracer/tsconfig.json @@ -0,0 +1,5 @@ +{ + "compilerOptions": { + "sourceMap": true + } +} \ No newline at end of file diff --git a/react-flux-babel-karma/.gitignore b/react-flux-babel-karma/.gitignore new file mode 100644 index 0000000..a983022 --- /dev/null +++ b/react-flux-babel-karma/.gitignore @@ -0,0 +1,201 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +build/ +bld/ +[Bb]in/ +[Oo]bj/ +dist/ + +# Visual Studo 2015 cache/options directory +.vs/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# JUnit test results +test-results + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opensdf +*.sdf +*.cachefile + +# Visual Studio profiler +*.psess +*.vsp +*.vspx + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding addin-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config + +# Windows Azure Build Output +csx/ +*.build.csdef + +# Windows Store app package directory +AppPackages/ + +# Others +*.[Cc]ache +ClientBin/ +[Ss]tyle[Cc]op.* +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +bower_components/ +typings/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt diff --git a/react-flux-babel-karma/LICENSE b/react-flux-babel-karma/LICENSE new file mode 100644 index 0000000..12a65bc --- /dev/null +++ b/react-flux-babel-karma/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 John Reilly + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/react-flux-babel-karma/README.md b/react-flux-babel-karma/README.md new file mode 100644 index 0000000..f7f2bf6 --- /dev/null +++ b/react-flux-babel-karma/README.md @@ -0,0 +1,45 @@ +# TypeScript, Babel, React, and Karma Sample + +## Getting started + +You'll need [node / npm](https://nodejs.org/) installed. To get up and running just enter: + +``` +npm install +npm run serve +``` + +This will: + +1. Download the npm packages you need (including the type definitions from DefinitelyTyped) +2. Compile the code and serve it up at [http://localhost:8080](http://localhost:8080) + +Now you need dev tools. There's a world of choice out there; there's [Atom](https://atom.io/), there's [VS Code](https://www.visualstudio.com/en-us/products/code-vs.aspx), there's [Sublime](http://www.sublimetext.com/). There's even something called [Visual Studio](http://www.visualstudio.com). It's all your choice really. + +For myself I've been using Atom combined with the mighty [atom-typescript package](https://atom.io/packages/atom-typescript). I advise you to give it a go. You won't look back. + +## I want to have an ASP.Net project and use Visual Studio + IIS Express to serve this instead + +If you drop this code into an empty Visual Studio ASP.Net project should should be good to go. You'll need this section in your `web.config` to ensure Visual Studio serves from the `dist` directory: + +``` + + + + + + + + + + + + +``` + +And rather than running `npm run serve` you'll want to use `npm run watch`. (This builds / watches your code / runs tests etc but does **not** spin up a web server.) + +Finally you'll want to set the following TypeScript options for your project + +- ECMAScript Version: ECMAScript 6 +- JSX compilation in TSX files: Preserve diff --git a/react-flux-babel-karma/gulp/.eslintrc b/react-flux-babel-karma/gulp/.eslintrc new file mode 100644 index 0000000..e91bbce --- /dev/null +++ b/react-flux-babel-karma/gulp/.eslintrc @@ -0,0 +1,73 @@ +{ + "root": true, + "env": { + "commonjs": true, + }, + "rules": { + "camelcase": 2, + "comma-spacing": 1, + "consistent-return": 2, + "curly": [ 2, "all" ], + "dot-notation": [ + 2, + { "allowKeywords": true } + ], + "eol-last": 2, + "eqeqeq": 2, + "keyword-spacing": 2, + "new-cap": 2, + "new-parens": 2, + "no-alert": 2, + "no-array-constructor": 2, + "no-caller": 2, + "no-catch-shadow": 2, + "no-eval": 2, + "no-extend-native": 2, + "no-extra-bind": 2, + "no-extra-parens": [ 2, "functions" ], + "no-implied-eval": 2, + "no-iterator": 2, + "no-labels": 2, + "no-label-var": 2, + "no-lone-blocks": 2, + "no-loop-func": 2, + "no-multi-str": 2, + "no-native-reassign": 2, + "no-new": 2, + "no-new-func": 2, + "no-new-object": 2, + "no-new-wrappers": 2, + "no-octal-escape": 2, + "no-proto": 2, + "no-return-assign": 2, + "no-script-url": 2, + "no-sequences": 2, + "no-shadow": 2, + "no-shadow-restricted-names": 2, + "no-spaced-func": 2, + "no-trailing-spaces": 1, + "no-undef-init": 2, + "no-unused-expressions": 2, + "no-use-before-define": [ 2, "nofunc" ], + "no-with": 2, + "quotes": [ 1, "single" ], + "semi": 2, + "semi-spacing": [ + 2, + { + "before": false, + "after": true + } + ], + "space-infix-ops": 2, + "space-unary-ops": [ + 2, + { + "words": true, + "nonwords": false + } + ], + "strict": [ 2, "global" ], + "yoda": [ 2, "never" ] + } +} diff --git a/react-flux-babel-karma/gulp/clean.js b/react-flux-babel-karma/gulp/clean.js new file mode 100644 index 0000000..c51b4e4 --- /dev/null +++ b/react-flux-babel-karma/gulp/clean.js @@ -0,0 +1,29 @@ +'use strict'; + +var del = require('del'); +var gutil = require('gulp-util'); +var fs = require('fs'); + +function run(done) { + fs.stat('./dist', function(err){ + if (err) { + // Never existed + done(); + } + else { + del(['./dist'], { force: true }) + .then(function(paths) { + gutil.log('Deleted files/folders:\n', paths.join('\n')); + done(); + }) + .catch(function(error) { + gutil.log('Problem deleting:\n', error); + done(); + }); + } + }); +} + +module.exports = { + run: function(done) { return run(done); } +}; diff --git a/react-flux-babel-karma/gulp/inject.js b/react-flux-babel-karma/gulp/inject.js new file mode 100644 index 0000000..e4133e5 --- /dev/null +++ b/react-flux-babel-karma/gulp/inject.js @@ -0,0 +1,55 @@ +'use strict'; + +var gulp = require('gulp'); +var inject = require('gulp-inject'); +var glob = require('glob'); + +function injectIndex(options) { + function run() { + var target = gulp.src('./src/index.html'); + var sources = gulp.src([ + //'./dist/styles/main*.css', + './dist/scripts/vendor*.js', + './dist/scripts/main*.js' + ], { read: false }); + + return target + .pipe(inject(sources, { ignorePath: '/dist/', addRootSlash: false, removeTags: true })) + .pipe(gulp.dest('./dist')); + } + + var jsCssGlob = 'dist/**/*.{js,css}'; + + function checkForInitialFilesThenRun() { + glob(jsCssGlob, function (er, files) { + var filesWeNeed = ['dist/scripts/main', 'dist/scripts/vendor'/*, 'dist/styles/main'*/]; + + function fileIsPresent(fileWeNeed) { + return files.some(function(file) { + return file.indexOf(fileWeNeed) !== -1; + }); + } + + if (filesWeNeed.every(fileIsPresent)) { + run('initial build'); + } else { + checkForInitialFilesThenRun(); + } + }); + } + + checkForInitialFilesThenRun(); + + if (options.shouldWatch) { + gulp.watch(jsCssGlob, function(evt) { + if (evt.path && evt.type === 'changed') { + run(evt.path); + } + }); + } +} + +module.exports = { + build: function() { return injectIndex({ shouldWatch: false }); }, + watch: function() { return injectIndex({ shouldWatch: true }); } +}; diff --git a/react-flux-babel-karma/gulp/staticFiles.js b/react-flux-babel-karma/gulp/staticFiles.js new file mode 100644 index 0000000..20327f2 --- /dev/null +++ b/react-flux-babel-karma/gulp/staticFiles.js @@ -0,0 +1,31 @@ +'use strict'; + +var gulp = require('gulp'); +var cache = require('gulp-cached'); + +var targets = [ + { description: 'INDEX', src: './src/index.html', dest: './dist' } +]; + +function copy(options) { + function run(target) { + gulp.src(target.src) + .pipe(cache(target.description)) + .pipe(gulp.dest(target.dest)); + } + + function watch(target) { + gulp.watch(target.src, function() { run(target); }); + } + + targets.forEach(run); + + if (options.shouldWatch) { + targets.forEach(watch); + } +} + +module.exports = { + build: function() { return copy({ shouldWatch: false }); }, + watch: function() { return copy({ shouldWatch: true }); } +}; diff --git a/react-flux-babel-karma/gulp/tests.js b/react-flux-babel-karma/gulp/tests.js new file mode 100644 index 0000000..05af0a5 --- /dev/null +++ b/react-flux-babel-karma/gulp/tests.js @@ -0,0 +1,45 @@ +'use strict'; + +var Server = require('karma').Server; +var path = require('path'); +var gutil = require('gulp-util'); + +function runTests(options) { + // Documentation: https://karma-runner.github.io/0.13/dev/public-api.html + var karmaConfig = { + configFile: path.join(__dirname, '../karma.conf.js'), + singleRun: !options.shouldWatch, + + plugins: ['karma-webpack', 'karma-jasmine', 'karma-mocha-reporter', 'karma-sourcemap-loader', 'karma-phantomjs-launcher'], + reporters: ['mocha'] + }; + + if (options.done) { + karmaConfig.plugins.push('karma-junit-reporter'); + karmaConfig.reporters.push('junit'); + } else { + karmaConfig.plugins.push('karma-notify-reporter'); + karmaConfig.reporters.push('notify'); + } + + new Server(karmaConfig, karmaCompleted).start(); + + function karmaCompleted(exitCode) { + if (options.done) { + if (exitCode === 1) { + gutil.log('Karma: tests failed with code ' + exitCode); + } else { + gutil.log('Karma completed!'); + } + options.done(); + } + else { + process.exit(exitCode); + } + } +} + +module.exports = { + run: function(done) { return runTests({ shouldWatch: false, done: done }); }, + watch: function() { return runTests({ shouldWatch: true }); } +}; diff --git a/react-flux-babel-karma/gulp/webpack.js b/react-flux-babel-karma/gulp/webpack.js new file mode 100644 index 0000000..2ecbf42 --- /dev/null +++ b/react-flux-babel-karma/gulp/webpack.js @@ -0,0 +1,100 @@ +'use strict'; + +var gulp = require('gulp'); +var gutil = require('gulp-util'); +var webpack = require('webpack'); +var WebpackNotifierPlugin = require('webpack-notifier'); +var failPlugin = require('webpack-fail-plugin'); +var webpackConfig = require('../webpack.config.js'); +var packageJson = require('../package.json'); + +function buildProduction(done) { + // modify some webpack config options + var myProdConfig = webpackConfig; + myProdConfig.output.filename = '[name].[hash].js'; + + myProdConfig.plugins = myProdConfig.plugins.concat( + new webpack.DefinePlugin({ + 'process.env': { + 'NODE_ENV': JSON.stringify('production') + } + }), + new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.[hash].js' }), + new webpack.optimize.UglifyJsPlugin({ + compress: { + warnings: true + } + }), + failPlugin + ); + + // run webpack + webpack(myProdConfig, function (err, stats) { + if (err) { throw new gutil.PluginError('webpack:build', err); } + gutil.log('[webpack:build]', stats.toString({ + colors: true + })); + + if (done) { done(); } + }); +} + +function createDevCompiler() { + // modify some webpack config options + var myDevConfig = webpackConfig; + myDevConfig.devtool = 'inline-source-map'; + + myDevConfig.plugins = myDevConfig.plugins.concat( + new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.js' }), + new WebpackNotifierPlugin({ title: 'Webpack build', excludeWarnings: true }) + ); + + // create a single instance of the compiler to allow caching + return webpack(myDevConfig); +} + +function build() { + return new Promise(function (resolve, reject) { + buildProduction(function (err) { + if (err) { + reject(err); + } else { + resolve('webpack built'); + } + }); + }); +} + +function watch() { + var firstBuildDone = false; + + return new Promise(function (resolve, reject) { + var devCompiler = createDevCompiler(); + devCompiler.watch({ // watch options: + aggregateTimeout: 300 // wait so long for more changes + }, function (err, stats) { + if (err) { + if (!firstBuildDone) { + firstBuildDone = true; + reject(err); + } + throw new gutil.PluginError('webpack:build-dev', err); + } else { + if (!firstBuildDone) { + firstBuildDone = true; + resolve('webpack built'); + } + } + + gutil.log('[webpack:build-dev]', stats.toString({ + chunks: false, + colors: true + })); + }); + }); +} + +module.exports = { + build: function () { return build(); }, + watch: function () { return watch(); } +}; diff --git a/react-flux-babel-karma/gulpFile.js b/react-flux-babel-karma/gulpFile.js new file mode 100644 index 0000000..0302283 --- /dev/null +++ b/react-flux-babel-karma/gulpFile.js @@ -0,0 +1,62 @@ +/* eslint-disable no-var, strict, prefer-arrow-callback */ +'use strict'; + +var gulp = require('gulp'); +var gutil = require('gulp-util'); +var eslint = require('gulp-eslint'); +var webpack = require('./gulp/webpack'); +var staticFiles = require('./gulp/staticFiles'); +var tests = require('./gulp/tests'); +var clean = require('./gulp/clean'); +var inject = require('./gulp/inject'); + +var lintSrcs = ['./gulp/**/*.js']; + +gulp.task('delete-dist', function (done) { + clean.run(done); +}); + +gulp.task('build-js', ['delete-dist'], function(done) { + webpack.build().then(function() { done(); }); +}); + +gulp.task('build-other', ['delete-dist'], function() { + staticFiles.build(); +}); + +gulp.task('build', ['build-js', 'build-other', 'lint'], function () { + inject.build(); +}); + +gulp.task('lint', function () { + return gulp.src(lintSrcs) + .pipe(eslint()) + .pipe(eslint.format()); +}); + +gulp.task('watch', ['delete-dist'], function(done) { + process.env.NODE_ENV = 'development'; + Promise.all([ + webpack.watch()//, + //less.watch() + ]).then(function() { + gutil.log('Now that initial assets (js and css) are generated inject will start...'); + inject.watch(); + done(); + }).catch(function(error) { + gutil.log('Problem generating initial assets (js and css)', error); + }); + + gulp.watch(lintSrcs, ['lint']); + staticFiles.watch(); + tests.watch(); +}); + +gulp.task('watch-and-serve', ['watch'], function() { + // local as not required for build + var express = require('express') + var app = express() + + app.use(express.static('dist', {'index': 'index.html'})) + app.listen(8080); +}); diff --git a/react-flux-babel-karma/karma.conf.js b/react-flux-babel-karma/karma.conf.js new file mode 100644 index 0000000..e43e261 --- /dev/null +++ b/react-flux-babel-karma/karma.conf.js @@ -0,0 +1,65 @@ +/* eslint-disable no-var, strict */ +'use strict'; + +var webpackConfig = require('./webpack.config.js'); + +module.exports = function(config) { + // Documentation: https://karma-runner.github.io/0.13/config/configuration-file.html + config.set({ + browsers: [ 'PhantomJS' ], + + files: [ + // This ensures we have the es6 shims in place from babel and that angular and angular-mocks are loaded + // and then loads all the tests + 'test/main.js' + ], + + port: 9876, + + frameworks: [ 'jasmine' ], + + logLevel: config.LOG_INFO, //config.LOG_DEBUG + + preprocessors: { + 'test/main.js': [ 'webpack', 'sourcemap' ] + }, + + webpack: { + devtool: 'inline-source-map', + module: webpackConfig.module, + resolve: webpackConfig.resolve + }, + + webpackMiddleware: { + quiet: true, + stats: { + colors: true + } + }, + + // reporter options + mochaReporter: { + colors: { + success: 'bgGreen', + info: 'cyan', + warning: 'bgBlue', + error: 'bgRed' + } + }, + + // the default configuration + junitReporter: { + outputDir: 'test-results', // results will be saved as $outputDir/$browserName.xml + outputFile: undefined, // if included, results will be saved as $outputDir/$browserName/$outputFile + suite: '' + }, + + coverageReporter: { + reporters:[ + //{type: 'html', dir:'coverage/'}, // https://github.com/karma-runner/karma-coverage/issues/123 + {type: 'text'}, + {type: 'text-summary'} + ], + } + }); +}; diff --git a/react-flux-babel-karma/package.json b/react-flux-babel-karma/package.json new file mode 100644 index 0000000..ad2ce3a --- /dev/null +++ b/react-flux-babel-karma/package.json @@ -0,0 +1,83 @@ +{ + "name": "react-flux-babel-karma", + "version": "1.0.0", + "description": "ES6 + TypeScript + Babel + React + Karma: The Secret Recipe", + "main": "index.js", + "scripts": { + "test": "karma start --reporters mocha,junit --single-run --browsers PhantomJS", + "serve": "gulp watch-and-serve", + "watch": "gulp watch", + "build": "gulp build" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/microsoft/typescriptsamples.git" + }, + "keywords": [ + "react", + "flux", + "es2016", + "typescript", + "webpack" + ], + "author": "John Reilly", + "license": "MIT", + "bugs": { + "url": "https://github.com/microsoft/typescriptsamples/issues" + }, + "homepage": "https://github.com/Microsoft/TypeScriptSamples/tree/master/react-flux-babel-karma#readme", + "devDependencies": { + "@types/fbemitter": "^2.0.32", + "@types/flux": "0.0.32", + "@types/jasmine": "^2.5.35", + "@types/react": "^0.14.41", + "@types/react-addons-test-utils": "^0.14.15", + "@types/react-bootstrap": "0.0.33", + "@types/react-dom": "^0.14.18", + "babel": "^6.0.0", + "babel-core": "^6.0.0", + "babel-loader": "^6.0.0", + "babel-preset-es2015": "^6.0.0", + "babel-preset-es2016": "^6.16.0", + "babel-preset-react": "^6.0.0", + "del": "^2.0.2", + "eslint": "^2.0.0", + "express": "^4.13.3", + "glob": "^7.0.0", + "gulp": "^3.9.0", + "gulp-autoprefixer": "^3.1.0", + "gulp-cached": "^1.1.0", + "gulp-cssmin": "^0.1.7", + "gulp-eslint": "^2.0.0", + "gulp-if": "^2.0.0", + "gulp-inject": "^3.0.0", + "gulp-notify": "^2.2.0", + "gulp-sourcemaps": "^1.5.2", + "gulp-streamify": "1.0.2", + "gulp-uglify": "^1.2.0", + "gulp-util": "^3.0.6", + "jasmine-core": "^2.3.4", + "karma": "^1.2.0", + "karma-jasmine": "^1.0.0", + "karma-junit-reporter": "^1.0.0", + "karma-mocha-reporter": "^2.0.0", + "karma-notify-reporter": "^1.0.0", + "karma-phantomjs-launcher": "^1.0.0", + "karma-sourcemap-loader": "^0.3.6", + "karma-webpack": "^2.0.2", + "phantomjs-prebuilt": "^2.1.4", + "ts-loader": "^2.0.1", + "typescript": "^2.1.4", + "webpack": "^2.2.1", + "webpack-fail-plugin": "^1.0.4", + "webpack-notifier": "^1.2.1" + }, + "dependencies": { + "babel-polyfill": "^6.0.0", + "flux": "^2.0.3", + "fbemitter": "^2.0.2", + "react": "^15.4.1", + "react-addons-test-utils": "^15.4.1", + "react-dom": "^15.4.1" + } +} diff --git a/react-flux-babel-karma/src/actions/GreetingActions.ts b/react-flux-babel-karma/src/actions/GreetingActions.ts new file mode 100644 index 0000000..147db5a --- /dev/null +++ b/react-flux-babel-karma/src/actions/GreetingActions.ts @@ -0,0 +1,17 @@ +import {TypedEvent, AppDispatcher} from '../dispatcher/AppDispatcher'; + +export class AddGreetingEvent extends TypedEvent {} +export class NewGreetingChanged extends TypedEvent {} +export class RemoveGreeting extends TypedEvent {} + +export function addGreeting(newGreeting: string) { + AppDispatcher.dispatch(new AddGreetingEvent(newGreeting)); +} + +export function newGreetingChanged(newGreeting: string) { + AppDispatcher.dispatch(new NewGreetingChanged(newGreeting)); +} + +export function removeGreeting(greetingToRemove: string) { + AppDispatcher.dispatch(new RemoveGreeting(greetingToRemove)); +} diff --git a/react-flux-babel-karma/src/components/App.tsx b/react-flux-babel-karma/src/components/App.tsx new file mode 100644 index 0000000..99cbd30 --- /dev/null +++ b/react-flux-babel-karma/src/components/App.tsx @@ -0,0 +1,45 @@ +import React from 'react'; +import FBEmitter from "fbemitter"; + +import GreetingStore from '../stores/GreetingStore'; +import GreetingState from '../types/GreetingState'; +import WhoToGreet from './WhoToGreet'; +import Greeting from './Greeting'; + +class App extends React.Component<{}, GreetingState> { + eventSubscription: FBEmitter.EventSubscription; + constructor(props: {}) { + super(props); + this.state = this.getStateFromStores(); + } + private onChange = () => { + this.setState(this.getStateFromStores()); + } + + public componentWillMount() { + this.eventSubscription = GreetingStore.addChangeListener(this.onChange); + } + + public componentWillUnmount() { + this.eventSubscription.remove(); + } + + render() { + const { greetings, newGreeting } = this.state; + return ( +
+

Hello People!

+ + + + { greetings.map((g, index) => ) } +
+ ); + } + + private getStateFromStores() { + return GreetingStore.getState(); + } +} + +export default App; diff --git a/react-flux-babel-karma/src/components/Greeting.tsx b/react-flux-babel-karma/src/components/Greeting.tsx new file mode 100644 index 0000000..0305fdb --- /dev/null +++ b/react-flux-babel-karma/src/components/Greeting.tsx @@ -0,0 +1,37 @@ +import React from 'react'; + +import * as GreetingActions from '../actions/GreetingActions'; + +interface Props { + key: number; + targetOfGreeting: string; +} + +class Greeting extends React.Component { + constructor(props: Props) { + super(props); + } + + static propTypes: React.ValidationMap = { + targetOfGreeting: React.PropTypes.string.isRequired + } + + render() { + return ( +

+ Hello { this.props.targetOfGreeting }! + + +

+ ); + } + + _onClick = (_event: React.MouseEvent) => { + GreetingActions.removeGreeting(this.props.targetOfGreeting); + } +} + +export default Greeting; diff --git a/react-flux-babel-karma/src/components/WhoToGreet.tsx b/react-flux-babel-karma/src/components/WhoToGreet.tsx new file mode 100644 index 0000000..eac78fe --- /dev/null +++ b/react-flux-babel-karma/src/components/WhoToGreet.tsx @@ -0,0 +1,53 @@ +import React from 'react'; + +import * as GreetingActions from '../actions/GreetingActions'; + +interface Props { + newGreeting: string; +} + +class WhoToGreet extends React.Component { + constructor(props: Props) { + super(props); + } + + static propTypes: React.ValidationMap = { + newGreeting: React.PropTypes.string.isRequired + } + + render() { + return ( +
+
+ + +
+
+ ); + } + + get _preventSubmission() { + return !this.props.newGreeting; + } + + _handleNewGreetingChange = (event: React.FormEvent) => { + const newGreeting = (event.target as HTMLInputElement).value; + GreetingActions.newGreetingChanged(newGreeting); + } + + _onSubmit = (event: React.FormEvent) => { + event.preventDefault(); + + if (!this._preventSubmission) { + GreetingActions.addGreeting(this.props.newGreeting); + } + } +} + +export default WhoToGreet; diff --git a/react-flux-babel-karma/src/dispatcher/AppDispatcher.ts b/react-flux-babel-karma/src/dispatcher/AppDispatcher.ts new file mode 100644 index 0000000..be9360f --- /dev/null +++ b/react-flux-babel-karma/src/dispatcher/AppDispatcher.ts @@ -0,0 +1,11 @@ +import { Dispatcher } from 'flux'; + +export class TypedEvent

{ + constructor(public payload: P) {} +} + +export type Event = TypedEvent; + +const dispatcherInstance: Dispatcher = new Dispatcher(); + +export { dispatcherInstance as AppDispatcher }; diff --git a/react-flux-babel-karma/src/index.html b/react-flux-babel-karma/src/index.html new file mode 100644 index 0000000..16013fa --- /dev/null +++ b/react-flux-babel-karma/src/index.html @@ -0,0 +1,19 @@ + + + + + + + + TypeScript, Babel, React, Flux, and Karma + + + + + + +

+ + + + diff --git a/react-flux-babel-karma/src/main.tsx b/react-flux-babel-karma/src/main.tsx new file mode 100644 index 0000000..65b3f94 --- /dev/null +++ b/react-flux-babel-karma/src/main.tsx @@ -0,0 +1,7 @@ +import 'babel-polyfill'; +import React from 'react'; +import ReactDOM from 'react-dom'; + +import App from './components/App'; + +ReactDOM.render(, document.getElementById('content')); diff --git a/react-flux-babel-karma/src/stores/FluxStore.ts b/react-flux-babel-karma/src/stores/FluxStore.ts new file mode 100644 index 0000000..758ec6c --- /dev/null +++ b/react-flux-babel-karma/src/stores/FluxStore.ts @@ -0,0 +1,54 @@ +import { EventEmitter } from 'fbemitter'; +import { Event } from '../dispatcher/AppDispatcher'; +import * as Flux from "flux"; + +const CHANGE_EVENT = 'change'; + +class FluxStore { + private changed: boolean; + private emitter: EventEmitter; + private dispatchToken: string; + private dispatcher: Flux.Dispatcher; + private cleanStateFn: () => TState; + protected state: TState; + + constructor(dispatcher: Flux.Dispatcher, public onDispatch: (action: Event) => void, cleanStateFn: () => TState) { + this.emitter = new EventEmitter(); + this.changed = false; + this.dispatcher = dispatcher; + this.dispatchToken = dispatcher.register(payload => { + this.invokeOnDispatch(payload); + }); + + this.cleanStateFn = cleanStateFn; + this.state = this.cleanStateFn(); + } + + /** + * Is idempotent per dispatched event + */ + emitChange() { + this.changed = true; + } + + hasChanged() { return this.changed; } + + addChangeListener(callback: () => void) { + return this.emitter.addListener(CHANGE_EVENT, callback); + } + + public cleanState() { + this.changed = false; + this.state = this.cleanStateFn(); + } + + private invokeOnDispatch(payload: Event) { + this.changed = false; + this.onDispatch(payload); + if (this.changed) { + this.emitter.emit(CHANGE_EVENT); + } + } +} + +export default FluxStore; diff --git a/react-flux-babel-karma/src/stores/GreetingStore.ts b/react-flux-babel-karma/src/stores/GreetingStore.ts new file mode 100644 index 0000000..9ea01b4 --- /dev/null +++ b/react-flux-babel-karma/src/stores/GreetingStore.ts @@ -0,0 +1,38 @@ +import FluxStore from './FluxStore'; +import {Event, AppDispatcher} from '../dispatcher/AppDispatcher'; +import GreetingState from '../types/GreetingState'; +import { AddGreetingEvent, RemoveGreeting, NewGreetingChanged } from '../actions/GreetingActions'; + +class GreeterStore extends FluxStore { + constructor(dispatcher: typeof AppDispatcher) { + const onDispatch = (action: Event) => { + if (action instanceof AddGreetingEvent) { + const {payload} = action; + this.state.newGreeting = ''; + this.state.greetings = this.state.greetings.concat(payload); + this.emitChange(); + } + else if (action instanceof RemoveGreeting) { + const {payload} = action; + this.state.greetings = this.state.greetings.filter(g => g !== payload); + this.emitChange(); + } + else if (action instanceof NewGreetingChanged) { + const {payload} = action; + this.state.newGreeting = payload; + this.emitChange(); + } + } + super(dispatcher, onDispatch, () => ({ + greetings: [], + newGreeting: '' + })); + } + + getState() { + return this.state + } +} + +const greeterStoreInstance = new GreeterStore(AppDispatcher); +export default greeterStoreInstance; diff --git a/react-flux-babel-karma/src/types/GreetingState.ts b/react-flux-babel-karma/src/types/GreetingState.ts new file mode 100644 index 0000000..656b201 --- /dev/null +++ b/react-flux-babel-karma/src/types/GreetingState.ts @@ -0,0 +1,6 @@ +interface GreetingState { + greetings: string[]; + newGreeting: string; +} + +export default GreetingState; diff --git a/react-flux-babel-karma/test/components/App.tests.tsx b/react-flux-babel-karma/test/components/App.tests.tsx new file mode 100644 index 0000000..468b7da --- /dev/null +++ b/react-flux-babel-karma/test/components/App.tests.tsx @@ -0,0 +1,32 @@ +import React from 'react'; +import TestUtils from 'react-addons-test-utils'; + +import App from '../../src/components/App'; +import WhoToGreet from '../../src/components/WhoToGreet'; +import Greeting from '../../src/components/Greeting'; +import GreetingStore from '../../src/stores/GreetingStore'; + +describe('App', () => { + it('renders expected HTML', () => { + const app = render({ greetings: ['James'], newGreeting: 'Benjamin' }); + expect(app).toEqual( +
+

Hello People!

+ + + + { [ + + ] } +
+ ); + }); + + function render(state: any) { + const shallowRenderer = TestUtils.createRenderer(); + spyOn(GreetingStore, 'getState').and.returnValue(state); + + shallowRenderer.render(); + return shallowRenderer.getRenderOutput(); + } +}); diff --git a/react-flux-babel-karma/test/components/Greeting.tests.tsx b/react-flux-babel-karma/test/components/Greeting.tests.tsx new file mode 100644 index 0000000..18a8724 --- /dev/null +++ b/react-flux-babel-karma/test/components/Greeting.tests.tsx @@ -0,0 +1,45 @@ +import React from 'react'; +import TestUtils from 'react-addons-test-utils'; + +import Greeting from '../../src/components/Greeting'; +import * as GreetingActions from '../../src/actions/GreetingActions'; + +describe('Greeting', () => { + let handleSelectionChangeSpy: jasmine.Spy; + beforeEach(() => { + handleSelectionChangeSpy = jasmine.createSpy('handleSelectionChange'); + }); + + it('given a targetOfGreeting of \'James\' it renders a p containing a greeting and a remove button', () => { + const targetOfGreeting = 'James'; + + const p = render({ targetOfGreeting }); + expect(p.type).toBe('p'); + expect(p.props.children[0]).toBe('Hello '); + expect(p.props.children[1]).toBe('James'); + expect(p.props.children[2]).toBe('!'); + + const [ , , , button ] = p.props.children; + + expect(button.type).toBe('button'); + expect(button.props.className).toBe('btn btn-default btn-danger'); + expect(button.props.children).toBe('Remove'); + }); + + it('button onClick triggers an removeGreeting action', () => { + const targetOfGreeting = 'Benjamin'; + const p = render({ targetOfGreeting }); + const [ , , , button ] = p.props.children; + spyOn(GreetingActions, 'removeGreeting'); + + button.props.onClick(); + + expect(GreetingActions.removeGreeting).toHaveBeenCalledWith(targetOfGreeting); + }); + + function render({ targetOfGreeting }: { targetOfGreeting: string; }) { + const shallowRenderer = TestUtils.createRenderer(); + shallowRenderer.render(); + return shallowRenderer.getRenderOutput(); + } +}); diff --git a/react-flux-babel-karma/test/components/WhoToGreet.tests.tsx b/react-flux-babel-karma/test/components/WhoToGreet.tests.tsx new file mode 100644 index 0000000..47ecdd4 --- /dev/null +++ b/react-flux-babel-karma/test/components/WhoToGreet.tests.tsx @@ -0,0 +1,68 @@ +import React from 'react'; +import TestUtils from 'react-addons-test-utils'; + +import WhoToGreet from '../../src/components/WhoToGreet'; +import * as GreetingActions from '../../src/actions/GreetingActions'; + +describe('WhoToGreet', () => { + let handleSelectionChangeSpy: jasmine.Spy; + beforeEach(() => { + handleSelectionChangeSpy = jasmine.createSpy('handleSelectionChange'); + }); + + it('given a newGreeting then it renders a form containing an input containing that text and an add button', () => { + const newGreeting = 'James'; + + const form = render({ newGreeting }); + expect(form.type).toBe('form'); + expect(form.props.role).toBe('form'); + + const formGroup = form.props.children; + expect(formGroup.type).toBe('div'); + expect(formGroup.props.className).toBe('form-group'); + + const [ input, button ] = formGroup.props.children; + + expect(input.type).toBe('input'); + expect(input.props.type).toBe('text'); + expect(input.props.className).toBe('form-control'); + expect(input.props.placeholder).toBe('Who would you like to greet?'); + expect(input.props.value).toBe(newGreeting); + + expect(button.type).toBe('button'); + expect(button.props.type).toBe('submit'); + expect(button.props.className).toBe('btn btn-default btn-primary'); + expect(button.props.disabled).toBe(false); + expect(button.props.children).toBe('Add greeting'); + }); + + it('input onChange triggers a newGreetingChanged action', () => { + const newGreeting = 'Benjamin'; + const form = render({ newGreeting }); + const formGroup = form.props.children; + const [ input ] = formGroup.props.children; + spyOn(GreetingActions, 'newGreetingChanged'); + + input.props.onChange({ target: { value: newGreeting }}); + + expect(GreetingActions.newGreetingChanged).toHaveBeenCalledWith(newGreeting); + }); + + it('button onClick triggers an addGreeting action', () => { + const newGreeting = 'Benjamin'; + const form = render({ newGreeting }); + const formGroup = form.props.children; + const [ , button ] = formGroup.props.children; + spyOn(GreetingActions, 'addGreeting'); + + button.props.onClick({ preventDefault: () => {} }); + + expect(GreetingActions.addGreeting).toHaveBeenCalledWith(newGreeting); + }); + + function render({ newGreeting }: { newGreeting: string }) { + const shallowRenderer = TestUtils.createRenderer(); + shallowRenderer.render(); + return shallowRenderer.getRenderOutput(); + } +}); diff --git a/react-flux-babel-karma/test/main.js b/react-flux-babel-karma/test/main.js new file mode 100644 index 0000000..1b332a7 --- /dev/null +++ b/react-flux-babel-karma/test/main.js @@ -0,0 +1,5 @@ +/* eslint-disable */ +import 'babel-polyfill'; + +const testsContext = require.context('./', true, /\.tests\.ts(x?)$/); +testsContext.keys().forEach(testsContext); \ No newline at end of file diff --git a/react-flux-babel-karma/test/stores/GreetingStore.tests.ts b/react-flux-babel-karma/test/stores/GreetingStore.tests.ts new file mode 100644 index 0000000..b060710 --- /dev/null +++ b/react-flux-babel-karma/test/stores/GreetingStore.tests.ts @@ -0,0 +1,44 @@ +import GreetingStore from '../../src/stores/GreetingStore'; +import { AddGreetingEvent, RemoveGreeting, NewGreetingChanged } from '../../src/actions/GreetingActions'; + +const registeredCallback = GreetingStore.onDispatch.bind(GreetingStore); + +describe('GreetingStore', () => { + beforeEach(() => { + GreetingStore.cleanState(); + }); + + it('given no actions, newGreeting should be an empty string and greetings should be an empty array', () => { + const { greetings, newGreeting } = GreetingStore.getState(); + + expect(greetings).toEqual([]); + expect(newGreeting).toBe(''); + }); + + it('given an ADD_GREETING action with a newGreeting of \'Benjamin\', the newGreeting should be an empty string and greetings should contain \'Benjamin\'', () => { + [new AddGreetingEvent('Benjamin')].forEach(registeredCallback); + + const { greetings, newGreeting } = GreetingStore.getState(); + + expect(greetings.find(g => g === 'Benjamin')).toBeTruthy(); + expect(newGreeting).toBe(''); + }); + + it('given an REMOVE_GREETING action with a greetingToRemove of \'Benjamin\', the state greetings should be an empty array', () => { + [new AddGreetingEvent('Benjamin'), new RemoveGreeting('Benjamin')].forEach(registeredCallback); + + const { greetings } = GreetingStore.getState(); + + expect(greetings.length).toBe(0); + expect(greetings.find(g => g === 'Benjamin')).toBeFalsy(); + }); + + it('given a NEW_GREETING_CHANGED action with a newGreeting of \'Benjamin\', the state newGreeting should be \'Benjamin\'', () => { + [new NewGreetingChanged('Benjamin')].forEach(registeredCallback); + + const { newGreeting } = GreetingStore.getState(); + + expect(newGreeting).toEqual('Benjamin'); + }); + +}); diff --git a/react-flux-babel-karma/tsconfig.json b/react-flux-babel-karma/tsconfig.json new file mode 100644 index 0000000..cb31633 --- /dev/null +++ b/react-flux-babel-karma/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compileOnSave": false, + "compilerOptions": { + "allowSyntheticDefaultImports": true, + "lib": [ + "dom", + "es2015", + "es2016" + ], + "jsx": "preserve", + "target": "es2016", + "module": "es2015", + "moduleResolution": "node", + "noImplicitAny": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "removeComments": false, + "preserveConstEnums": true, + "sourceMap": true, + "skipLibCheck": true + } +} \ No newline at end of file diff --git a/react-flux-babel-karma/webpack.config.js b/react-flux-babel-karma/webpack.config.js new file mode 100644 index 0000000..70f8201 --- /dev/null +++ b/react-flux-babel-karma/webpack.config.js @@ -0,0 +1,67 @@ +/* eslint-disable no-var, strict, prefer-arrow-callback */ +'use strict'; + +var path = require('path'); + + +var babelOptions = { + "presets": [ + "react", + [ + "es2015", + { + "modules": false + } + ], + "es2016" + ] +}; + +module.exports = { + cache: true, + entry: { + main: './src/main.tsx', + vendor: [ + 'babel-polyfill', + 'events', + 'fbemitter', + 'flux', + 'react', + 'react-dom' + ] + }, + output: { + path: path.resolve(__dirname, './dist/scripts'), + filename: '[name].js', + chunkFilename: '[chunkhash].js' + }, + module: { + rules: [{ + test: /\.ts(x?)$/, + exclude: /node_modules/, + use: [ + { + loader: 'babel-loader', + options: babelOptions + }, + { + loader: 'ts-loader' + } + ] + }, { + test: /\.js$/, + exclude: /node_modules/, + use: [ + { + loader: 'babel-loader', + options: babelOptions + } + ] + }] + }, + plugins: [ + ], + resolve: { + extensions: ['.ts', '.tsx', '.js'] + }, +}; \ No newline at end of file diff --git a/simple/animals.ts b/simple/animals.ts index 7200150..8113a9e 100644 --- a/simple/animals.ts +++ b/simple/animals.ts @@ -1,26 +1,26 @@ -class Animal { - constructor(public name) { } - move(meters) { - alert(this.name + " moved " + meters + "m."); - } -} - -class Snake extends Animal { - move() { - alert("Slithering..."); - super.move(5); - } -} - -class Horse extends Animal { - move() { - alert("Galloping..."); - super.move(45); - } -} - -var sam = new Snake("Sammy the Python") -var tom: Animal = new Horse("Tommy the Palomino") - -sam.move() -tom.move(34) +class Animal { + constructor(public name) { } + move(meters) { + console.log(this.name + " moved " + meters + "m."); + } +} + +class Snake extends Animal { + move() { + console.log("Slithering..."); + super.move(5); + } +} + +class Horse extends Animal { + move() { + console.log("Galloping..."); + super.move(45); + } +} + +var sam = new Snake("Sammy the Python") +var tom: Animal = new Horse("Tommy the Palomino") + +sam.move() +tom.move(34) diff --git a/simple/tsconfig.json b/simple/tsconfig.json new file mode 100644 index 0000000..8036243 --- /dev/null +++ b/simple/tsconfig.json @@ -0,0 +1,5 @@ +{ + "compilerOptions": { + "sourceMap": true + } +} \ No newline at end of file diff --git a/systemjs/.gitignore b/systemjs/.gitignore new file mode 100644 index 0000000..b512c09 --- /dev/null +++ b/systemjs/.gitignore @@ -0,0 +1 @@ +node_modules \ No newline at end of file diff --git a/systemjs/README.md b/systemjs/README.md new file mode 100644 index 0000000..dfd9acb --- /dev/null +++ b/systemjs/README.md @@ -0,0 +1,17 @@ +**Fetch dependencies:** +``` +npm install +``` + +**Run (using port 8080)** +``` +npm start +``` + +**Run server on custom port** +``` +node node_modules/http-server/bin/http-server -p 8080 +``` + +'-p' sets the port to use, default port is 8080. If it is taken pick any port that is free. +After server is started open 'localhost:8080' in a browser. \ No newline at end of file diff --git a/systemjs/app.css b/systemjs/app.css new file mode 100644 index 0000000..eb24fc6 --- /dev/null +++ b/systemjs/app.css @@ -0,0 +1,8 @@ +body +{ + font-family: 'Segoe UI', sans-serif +} + +span { + font-style: italic +} \ No newline at end of file diff --git a/systemjs/app.ts b/systemjs/app.ts new file mode 100644 index 0000000..eb60899 --- /dev/null +++ b/systemjs/app.ts @@ -0,0 +1,6 @@ +import { Greeter } from 'greeter' + +export function main(el: HTMLElement): void { + let greeter = new Greeter(el); + greeter.start(); +} \ No newline at end of file diff --git a/systemjs/greeter.ts b/systemjs/greeter.ts new file mode 100644 index 0000000..4592f91 --- /dev/null +++ b/systemjs/greeter.ts @@ -0,0 +1,25 @@ +export class Greeter +{ + element: HTMLElement; + span: HTMLElement; + timerToken: number; + + constructor (element: HTMLElement) + { + this.element = element; + this.element.innerText += "The time is: "; + this.span = document.createElement('span'); + this.element.appendChild(this.span); + this.span.innerText = new Date().toUTCString(); + } + + start() + { + this.timerToken = setInterval(() => this.span.innerText = new Date().toUTCString(), 500); + } + + stop() + { + clearTimeout(this.timerToken); + } +} diff --git a/systemjs/index.html b/systemjs/index.html new file mode 100644 index 0000000..545d88b --- /dev/null +++ b/systemjs/index.html @@ -0,0 +1,23 @@ + + + SystemJS/TypeScript Sample + + + + + +

SystemJS/TypeScript Sample

+
+ + \ No newline at end of file diff --git a/systemjs/package.json b/systemjs/package.json new file mode 100644 index 0000000..1a6cf45 --- /dev/null +++ b/systemjs/package.json @@ -0,0 +1,19 @@ +{ + "name": "typescript-systemjs", + "version": "1.0.0", + "description": "SystemJS/TypeScript demo", + "repository": { + "type": "git", + "url": "https://github.com/Microsoft/TypeScriptSamples.git" + }, + "dependencies": { + "http-server": "0.9.0", + "systemjs": "0.18.0" + }, + "devDependencies": { + "typescript": "^1.5.3" + }, + "scripts": { + "start": "node node_modules/http-server/bin/http-server -o" + } +} \ No newline at end of file diff --git a/systemjs/tsconfig.json b/systemjs/tsconfig.json new file mode 100644 index 0000000..12d911f --- /dev/null +++ b/systemjs/tsconfig.json @@ -0,0 +1,6 @@ +{ + "compilerOptions": { + "module": "system", + "sourceMap": true + } +} \ No newline at end of file diff --git a/todomvc/.gitignore b/todomvc/.gitignore new file mode 100644 index 0000000..38f2474 --- /dev/null +++ b/todomvc/.gitignore @@ -0,0 +1,2 @@ +js/*.js +js/*.js.map diff --git a/todomvc/README.md b/todomvc/README.md index 65c5361..969ea93 100644 --- a/todomvc/README.md +++ b/todomvc/README.md @@ -1,64 +1,64 @@ -# TypeScript Sample: Todo MVC - -## Overview - -This sample shows an implementation of the Backbone.js TODO sample derived from -https://github.com/documentcloud/backbone/tree/master/examples/todos. The following -TypeScript integration points are highlighted: -- Backbone.js: Using TypeScript classes to create Backbone models and views -- jQuery: Using jQuery for all DOM manipulation - - -## Running -``` -tsc --sourcemap js\todos.ts -start index.html -``` - -## Caveats - -``` -This sample uses local storage and will not run properly on Internet Explore if run -from the local filesystem. Instead, host the sample from a web server (eg. IIS). - - -Microsoft grants you the right to use these script files under the Apache 2.0 license. -Microsoft reserves all other rights to the files not expressly granted by Microsoft, -whether by implication, estoppel or otherwise. The copyright notices and MIT licenses -below are for informational purposes only. - -Portions Copyright © Microsoft Corporation -Apache 2.0 License - -Licensed under the Apache License, Version 2.0 (the "License"); you may not use this -file except in compliance with the License. You may obtain a copy of the License at -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software distributed under -the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF -ANY KIND, either express or implied. - -See the License for the specific language governing permissions and limitations -under the License. -``` - - -``` -Provided for Informational Purposes Only -MIT License -Permission is hereby granted, free of charge, to any person obtaining a copy of this -software and associated documentation files (the "Software"), to deal in the Software -without restriction, including without limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of the Software, and to permit -persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies -or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE -FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -``` +# TypeScript Sample: Todo MVC + +## Overview + +This sample shows an implementation of the Backbone.js TODO sample derived from +https://github.com/documentcloud/backbone/tree/master/examples/todos. The following +TypeScript integration points are highlighted: +- Backbone.js: Using TypeScript classes to create Backbone models and views +- jQuery: Using jQuery for all DOM manipulation + + +## Running +``` +npm install +npm start +``` + +## Caveats + +``` +This sample uses local storage and will not run properly on Internet Explorer if run +from the local filesystem. Instead, host the sample from a web server (eg. IIS). + + +Microsoft grants you the right to use these script files under the Apache 2.0 license. +Microsoft reserves all other rights to the files not expressly granted by Microsoft, +whether by implication, estoppel or otherwise. The copyright notices and MIT licenses +below are for informational purposes only. + +Portions Copyright © Microsoft Corporation +Apache 2.0 License + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this +file except in compliance with the License. You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed under +the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +ANY KIND, either express or implied. + +See the License for the specific language governing permissions and limitations +under the License. +``` + + +``` +Provided for Informational Purposes Only +MIT License +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies +or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +``` diff --git a/todomvc/js/todos.ts b/todomvc/js/todos.ts index 3ce687e..df6947e 100644 --- a/todomvc/js/todos.ts +++ b/todomvc/js/todos.ts @@ -1,376 +1,375 @@ -/* --------------------------------------------------------------------------------------- -Todos.ts -Microsoft grants you the right to use these script files under the Apache 2.0 license. -Microsoft reserves all other rights to the files not expressly granted by Microsoft, -whether by implication, estoppel or otherwise. The copyright notices and MIT licenses -below are for informational purposes only. - -Portions Copyright © Microsoft Corporation -Apache 2.0 License - -Licensed under the Apache License, Version 2.0 (the "License"); you may not use this -file except in compliance with the License. You may obtain a copy of the License at -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software distributed under -the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF -ANY KIND, either express or implied. - -See the License for the specific language governing permissions and limitations -under the License. ------------------------------------------------------------------------------------------- -Provided for Informational Purposes Only -MIT License -Permission is hereby granted, free of charge, to any person obtaining a copy of this -software and associated documentation files (the "Software"), to deal in the Software -without restriction, including without limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of the Software, and to permit -persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies -or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE -FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. ---------------------------------------------------------------------------------------- */ -// Todos.js -// https://github.com/documentcloud/backbone/blob/master/examples/todos/todos.js - -// An example Backbone application contributed by -// [Jérôme Gravel-Niquet](http://jgn.me/). This demo uses a simple -// [LocalStorage adapter](backbone-localstorage.js) -// to persist Backbone models within your browser. - -declare module Backbone { - export class Model { - constructor (attr? , opts? ); - get(name: string): any; - set(name: string, val: any): void; - set(obj: any): void; - save(attr? , opts? ): void; - destroy(): void; - bind(ev: string, f: Function, ctx?: any): void; - toJSON(): any; - } - export class Collection { - constructor (models? , opts? ); - bind(ev: string, f: Function, ctx?: any): void; - length: number; - create(attrs, opts? ): any; - each(f: (elem: T) => void ): void; - fetch(opts?: any): void; - last(): T; - last(n: number): T[]; - filter(f: (elem: T) => boolean): T[]; - without(...values: T[]): T[]; - } - export class View { - constructor (options? ); - $(selector: string): JQuery; - el: HTMLElement; - $el: JQuery; - model: Model; - remove(): void; - delegateEvents: any; - make(tagName: string, attrs? , opts? ): View; - setElement(element: HTMLElement, delegate?: boolean): void; - setElement(element: JQuery, delegate?: boolean): void; - tagName: string; - events: any; - - static extend: any; - } -} -interface JQuery { - fadeIn(): JQuery; - fadeOut(): JQuery; - focus(): JQuery; - html(): string; - html(val: string): JQuery; - show(): JQuery; - addClass(className: string): JQuery; - removeClass(className: string): JQuery; - append(el: HTMLElement): JQuery; - val(): string; - val(value: string): JQuery; - attr(attrName: string): string; -} -declare var $: { - (el: HTMLElement): JQuery; - (selector: string): JQuery; - (readyCallback: () => void ): JQuery; -}; -declare var _: { - each(arr: T[], f: (elem: T) => U): U[]; - delay(f: Function, wait: number, ...arguments: any[]): number; - template(template: string): (model: any) => string; - bindAll(object: any, ...methodNames: string[]): void; -}; -declare var Store: any; - - -// Todo Model -// ---------- - -// Our basic **Todo** model has `content`, `order`, and `done` attributes. -class Todo extends Backbone.Model { - - // Default attributes for the todo. - defaults() { - return { - content: "empty todo...", - done: false - } - } - - // Ensure that each todo created has `content`. - initialize() { - if (!this.get("content")) { - this.set({ "content": this.defaults().content }); - } - } - - // Toggle the `done` state of this todo item. - toggle() { - this.save({ done: !this.get("done") }); - } - - // Remove this Todo from *localStorage* and delete its view. - clear() { - this.destroy(); - } - -} - -// Todo Collection -// --------------- - -// The collection of todos is backed by *localStorage* instead of a remote -// server. -class TodoList extends Backbone.Collection { - - // Reference to this collection's model. - model = Todo; - - // Save all of the todo items under the `"todos"` namespace. - localStorage = new Store("todos-backbone"); - - // Filter down the list of all todo items that are finished. - done() { - return this.filter(todo => todo.get('done')); - } - - // Filter down the list to only todo items that are still not finished. - remaining() { - return this.without.apply(this, this.done()); - } - - // We keep the Todos in sequential order, despite being saved by unordered - // GUID in the database. This generates the next order number for new items. - nextOrder() { - if (!this.length) return 1; - return this.last().get('order') + 1; - } - - // Todos are sorted by their original insertion order. - comparator(todo: Todo) { - return todo.get('order'); - } - -} - -// Create our global collection of **Todos**. -var Todos = new TodoList(); - -// Todo Item View -// -------------- - -// The DOM element for a todo item... -class TodoView extends Backbone.View { - - // The TodoView listens for changes to its model, re-rendering. Since there's - // a one-to-one correspondence between a **Todo** and a **TodoView** in this - // app, we set a direct reference on the model for convenience. - template: (data: any) => string; - - // A TodoView model must be a Todo, redeclare with specific type - model: Todo; - input: JQuery; - - constructor (options? ) { - //... is a list tag. - this.tagName = "li"; - - // The DOM events specific to an item. - this.events = { - "click .check": "toggleDone", - "dblclick label.todo-content": "edit", - "click span.todo-destroy": "clear", - "keypress .todo-input": "updateOnEnter", - "blur .todo-input": "close" - }; - - super(options); - - // Cache the template function for a single item. - this.template = _.template($('#item-template').html()); - - _.bindAll(this, 'render', 'close', 'remove'); - this.model.bind('change', this.render); - this.model.bind('destroy', this.remove); - } - - // Re-render the contents of the todo item. - render() { - this.$el.html(this.template(this.model.toJSON())); - this.input = this.$('.todo-input'); - return this; - } - - // Toggle the `"done"` state of the model. - toggleDone() { - this.model.toggle(); - } - - // Switch this view into `"editing"` mode, displaying the input field. - edit() { - this.$el.addClass("editing"); - this.input.focus(); - } - - // Close the `"editing"` mode, saving changes to the todo. - close() { - this.model.save({ content: this.input.val() }); - this.$el.removeClass("editing"); - } - - // If you hit `enter`, we're through editing the item. - updateOnEnter(e) { - if (e.keyCode == 13) close(); - } - - // Remove the item, destroy the model. - clear() { - this.model.clear(); - } - -} - -// The Application -// --------------- - -// Our overall **AppView** is the top-level piece of UI. -class AppView extends Backbone.View { - - // Delegated events for creating new items, and clearing completed ones. - events = { - "keypress #new-todo": "createOnEnter", - "keyup #new-todo": "showTooltip", - "click .todo-clear a": "clearCompleted", - "click .mark-all-done": "toggleAllComplete" - }; - - input: JQuery; - allCheckbox: HTMLInputElement; - statsTemplate: (params: any) => string; - - constructor () { - super(); - // Instead of generating a new element, bind to the existing skeleton of - // the App already present in the HTML. - this.setElement($("#todoapp"), true); - - // At initialization we bind to the relevant events on the `Todos` - // collection, when items are added or changed. Kick things off by - // loading any preexisting todos that might be saved in *localStorage*. - _.bindAll(this, 'addOne', 'addAll', 'render', 'toggleAllComplete'); - - this.input = this.$("#new-todo"); - this.allCheckbox = this.$(".mark-all-done")[0]; - this.statsTemplate = _.template($('#stats-template').html()); - - Todos.bind('add', this.addOne); - Todos.bind('reset', this.addAll); - Todos.bind('all', this.render); - - Todos.fetch(); - } - - // Re-rendering the App just means refreshing the statistics -- the rest - // of the app doesn't change. - render() { - var done = Todos.done().length; - var remaining = Todos.remaining().length; - - this.$('#todo-stats').html(this.statsTemplate({ - total: Todos.length, - done: done, - remaining: remaining - })); - - this.allCheckbox.checked = !remaining; - } - - // Add a single todo item to the list by creating a view for it, and - // appending its element to the `
    `. - addOne(todo) { - var view = new TodoView({ model: todo }); - this.$("#todo-list").append(view.render().el); - } - - // Add all items in the **Todos** collection at once. - addAll() { - Todos.each(this.addOne); - } - - // Generate the attributes for a new Todo item. - newAttributes() { - return { - content: this.input.val(), - order: Todos.nextOrder(), - done: false - }; - } - - // If you hit return in the main input field, create new **Todo** model, - // persisting it to *localStorage*. - createOnEnter(e) { - if (e.keyCode != 13) return; - Todos.create(this.newAttributes()); - this.input.val(''); - } - - // Clear all done todo items, destroying their models. - clearCompleted() { - _.each(Todos.done(), todo => todo.clear()); - return false; - } - - tooltipTimeout: number = null; - // Lazily show the tooltip that tells you to press `enter` to save - // a new todo item, after one second. - showTooltip(e) { - var tooltip = $(".ui-tooltip-top"); - var val = this.input.val(); - tooltip.fadeOut(); - if (this.tooltipTimeout) clearTimeout(this.tooltipTimeout); - if (val == '' || val == this.input.attr('placeholder')) return; - this.tooltipTimeout = _.delay(() => tooltip.show().fadeIn(), 1000); - } - - toggleAllComplete() { - var done = this.allCheckbox.checked; - Todos.each(todo => todo.save({ 'done': done })); - } - -} - -// Load the application once the DOM is ready, using `jQuery.ready`: -$(() => { - // Finally, we kick things off by creating the **App**. - new AppView(); -}); \ No newline at end of file +/* --------------------------------------------------------------------------------------- +Todos.ts +Microsoft grants you the right to use these script files under the Apache 2.0 license. +Microsoft reserves all other rights to the files not expressly granted by Microsoft, +whether by implication, estoppel or otherwise. The copyright notices and MIT licenses +below are for informational purposes only. + +Portions Copyright © Microsoft Corporation +Apache 2.0 License + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this +file except in compliance with the License. You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed under +the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +ANY KIND, either express or implied. + +See the License for the specific language governing permissions and limitations +under the License. +------------------------------------------------------------------------------------------ +Provided for Informational Purposes Only +MIT License +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies +or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +--------------------------------------------------------------------------------------- */ +// Todos.js +// https://github.com/documentcloud/backbone/blob/master/examples/todos/todos.js + +// An example Backbone application contributed by +// [Jérôme Gravel-Niquet](http://jgn.me/). This demo uses a simple +// [LocalStorage adapter](backbone-localstorage.js) +// to persist Backbone models within your browser. + +declare module Backbone { + export class Model { + constructor (attr? , opts? ); + get(name: string): any; + set(name: string, val: any): void; + set(obj: any): void; + save(attr? , opts? ): void; + destroy(): void; + bind(ev: string, f: Function, ctx?: any): void; + toJSON(): any; + } + export class Collection { + constructor (models?, opts?); + bind(ev: string, f: Function, ctx?: any): void; + length: number; + create(attrs, opts? ): any; + each(f: (elem: T) => void ): void; + fetch(opts?: any): void; + last(): T; + last(n: number): T[]; + filter(f: (elem: T) => boolean): T[]; + without(...values: T[]): T[]; + } + export class View { + constructor (options?); + $(selector: string): JQuery; + el: HTMLElement; + $el: JQuery; + model: Model; + remove(): void; + delegateEvents: any; + make(tagName: string, attrs? , opts? ): View; + setElement(element: HTMLElement, delegate?: boolean): void; + setElement(element: JQuery, delegate?: boolean): void; + tagName: string; + events: any; + + static extend: any; + } +} +interface JQuery { + fadeIn(): JQuery; + fadeOut(): JQuery; + focus(): JQuery; + html(): string; + html(val: string): JQuery; + show(): JQuery; + addClass(className: string): JQuery; + removeClass(className: string): JQuery; + append(el: HTMLElement): JQuery; + val(): string; + val(value: string): JQuery; + attr(attrName: string): string; +} +declare var $: { + (el: HTMLElement): JQuery; + (selector: string): JQuery; + (readyCallback: () => void ): JQuery; +}; +declare var _: { + each(arr: T[], f: (elem: T) => U): U[]; + delay(f: Function, wait: number, ...arguments: any[]): number; + template(template: string): (model: any) => string; + bindAll(object: any, ...methodNames: string[]): void; +}; +declare var Store: any; + + +// Todo Model +// ---------- + +// Our basic **Todo** model has `content`, `order`, and `done` attributes. +class Todo extends Backbone.Model { + + // Default attributes for the todo. + defaults() { + return { + content: "empty todo...", + done: false + } + } + + // Ensure that each todo created has `content`. + initialize() { + if (!this.get("content")) { + this.set({ "content": this.defaults().content }); + } + } + + // Toggle the `done` state of this todo item. + toggle() { + this.save({ done: !this.get("done") }); + } + + // Remove this Todo from *localStorage* and delete its view. + clear() { + this.destroy(); + } + +} + +// Todo Collection +// --------------- + +// The collection of todos is backed by *localStorage* instead of a remote +// server. +class TodoList extends Backbone.Collection { + + // Reference to this collection's model. + model = Todo; + + // Save all of the todo items under the `"todos"` namespace. + localStorage = new Store("todos-backbone"); + + // Filter down the list of all todo items that are finished. + done() { + return this.filter(todo => todo.get('done')); + } + + // Filter down the list to only todo items that are still not finished. + remaining() { + return this.without.apply(this, this.done()); + } + + // We keep the Todos in sequential order, despite being saved by unordered + // GUID in the database. This generates the next order number for new items. + nextOrder() { + if (!this.length) return 1; + return this.last().get('order') + 1; + } + + // Todos are sorted by their original insertion order. + comparator(todo: Todo) { + return todo.get('order'); + } + +} + +// Create our global collection of **Todos**. +var Todos = new TodoList(); + +// Todo Item View +// -------------- + +// The DOM element for a todo item... +class TodoView extends Backbone.View { + + // The TodoView listens for changes to its model, re-rendering. Since there's + // a one-to-one correspondence between a **Todo** and a **TodoView** in this + // app, we set a direct reference on the model for convenience. + template: (data: any) => string; + + // A TodoView model must be a Todo, redeclare with specific type + model: Todo; + input: JQuery; + + constructor (options?) { + super(options); + //... is a list tag. + this.tagName = "li"; + + // The DOM events specific to an item. + this.events = { + "click .check": "toggleDone", + "dblclick label.todo-content": "edit", + "click span.todo-destroy": "clear", + "keypress .todo-input": "updateOnEnter", + "blur .todo-input": "close" + }; + + // Cache the template function for a single item. + this.template = _.template($('#item-template').html()); + + _.bindAll(this, 'render', 'close', 'remove'); + this.model.bind('change', this.render); + this.model.bind('destroy', this.remove); + } + + // Re-render the contents of the todo item. + render() { + this.$el.html(this.template(this.model.toJSON())); + this.input = this.$('.todo-input'); + return this; + } + + // Toggle the `"done"` state of the model. + toggleDone() { + this.model.toggle(); + } + + // Switch this view into `"editing"` mode, displaying the input field. + edit() { + this.$el.addClass("editing"); + this.input.focus(); + } + + // Close the `"editing"` mode, saving changes to the todo. + close() { + this.model.save({ content: this.input.val() }); + this.$el.removeClass("editing"); + } + + // If you hit `enter`, we're through editing the item. + updateOnEnter(e) { + if (e.keyCode == 13) close(); + } + + // Remove the item, destroy the model. + clear() { + this.model.clear(); + } + +} + +// The Application +// --------------- + +// Our overall **AppView** is the top-level piece of UI. +class AppView extends Backbone.View { + + // Delegated events for creating new items, and clearing completed ones. + events = { + "keypress #new-todo": "createOnEnter", + "keyup #new-todo": "showTooltip", + "click .todo-clear a": "clearCompleted", + "click .mark-all-done": "toggleAllComplete" + }; + + input: JQuery; + allCheckbox: HTMLInputElement; + statsTemplate: (params: any) => string; + + constructor () { + super(); + // Instead of generating a new element, bind to the existing skeleton of + // the App already present in the HTML. + this.setElement($("#todoapp"), true); + + // At initialization we bind to the relevant events on the `Todos` + // collection, when items are added or changed. Kick things off by + // loading any preexisting todos that might be saved in *localStorage*. + _.bindAll(this, 'addOne', 'addAll', 'render', 'toggleAllComplete'); + + this.input = this.$("#new-todo"); + this.allCheckbox = this.$(".mark-all-done")[0]; + this.statsTemplate = _.template($('#stats-template').html()); + + Todos.bind('add', this.addOne); + Todos.bind('reset', this.addAll); + Todos.bind('all', this.render); + + Todos.fetch(); + } + + // Re-rendering the App just means refreshing the statistics -- the rest + // of the app doesn't change. + render() { + var done = Todos.done().length; + var remaining = Todos.remaining().length; + + this.$('#todo-stats').html(this.statsTemplate({ + total: Todos.length, + done: done, + remaining: remaining + })); + + this.allCheckbox.checked = !remaining; + } + + // Add a single todo item to the list by creating a view for it, and + // appending its element to the `
      `. + addOne(todo) { + var view = new TodoView({ model: todo }); + this.$("#todo-list").append(view.render().el); + } + + // Add all items in the **Todos** collection at once. + addAll() { + Todos.each(this.addOne); + } + + // Generate the attributes for a new Todo item. + newAttributes() { + return { + content: this.input.val(), + order: Todos.nextOrder(), + done: false + }; + } + + // If you hit return in the main input field, create new **Todo** model, + // persisting it to *localStorage*. + createOnEnter(e) { + if (e.keyCode != 13) return; + Todos.create(this.newAttributes()); + this.input.val(''); + } + + // Clear all done todo items, destroying their models. + clearCompleted() { + _.each(Todos.done(), todo => todo.clear()); + return false; + } + + tooltipTimeout: number = null; + // Lazily show the tooltip that tells you to press `enter` to save + // a new todo item, after one second. + showTooltip(e) { + var tooltip = $(".ui-tooltip-top"); + var val = this.input.val(); + tooltip.fadeOut(); + if (this.tooltipTimeout) clearTimeout(this.tooltipTimeout); + if (val == '' || val == this.input.attr('placeholder')) return; + this.tooltipTimeout = _.delay(() => tooltip.show().fadeIn(), 1000); + } + + toggleAllComplete() { + var done = this.allCheckbox.checked; + Todos.each(todo => todo.save({ 'done': done })); + } + +} + +// Load the application once the DOM is ready, using `jQuery.ready`: +$(() => { + // Finally, we kick things off by creating the **App**. + new AppView(); +}); diff --git a/todomvc/package.json b/todomvc/package.json new file mode 100644 index 0000000..f16a933 --- /dev/null +++ b/todomvc/package.json @@ -0,0 +1,18 @@ +{ + "name": "typescript-todomvc", + "version": "1.0.0", + "description": "TodoMVC/TypeScript demo", + "repository": { + "type": "git", + "url": "https://github.com/Microsoft/TypeScriptSamples.git" + }, + "dependencies": { + "http-server": "^0.11.1" + }, + "devDependencies": { + "typescript": "^3.0.0" + }, + "scripts": { + "start": "tsc && http-server -o" + } +} diff --git a/todomvc/tsconfig.json b/todomvc/tsconfig.json new file mode 100644 index 0000000..8036243 --- /dev/null +++ b/todomvc/tsconfig.json @@ -0,0 +1,5 @@ +{ + "compilerOptions": { + "sourceMap": true + } +} \ No newline at end of file diff --git a/umd/.gitignore b/umd/.gitignore new file mode 100644 index 0000000..2bccbb0 --- /dev/null +++ b/umd/.gitignore @@ -0,0 +1,4 @@ +node_modules +shared/timeReporter.js +browser/app.js +node/app.js \ No newline at end of file diff --git a/umd/README.md b/umd/README.md new file mode 100644 index 0000000..7a6b3f8 --- /dev/null +++ b/umd/README.md @@ -0,0 +1,36 @@ +**Fetch dependencies:** +``` +npm install +``` + +**Compile TypeScript source code** + +``` +node node_modules/typescript/bin/tsc.js +``` + +**Start browser version of the sample using http-server on custom port (code should be compiled prior to this step)** +``` +node node_modules/http-server/bin/http-server -p 8080 -o +``` +'-p' sets the port to use, default port is 8080. If it is taken pick any port that is free. +After server is started open 'localhost:8080' in a browser. + + +**Run example using Node (code should be compiled prior to this step)** + +``` +node node/app.js +``` + +Shortcuts for doing compile\run steps from above: + +*Browser* +``` +npm run browser +``` + +*Node* +``` +npm run node +``` \ No newline at end of file diff --git a/umd/browser/app.css b/umd/browser/app.css new file mode 100644 index 0000000..eb24fc6 --- /dev/null +++ b/umd/browser/app.css @@ -0,0 +1,8 @@ +body +{ + font-family: 'Segoe UI', sans-serif +} + +span { + font-style: italic +} \ No newline at end of file diff --git a/umd/browser/app.ts b/umd/browser/app.ts new file mode 100644 index 0000000..0e9af1f --- /dev/null +++ b/umd/browser/app.ts @@ -0,0 +1,13 @@ +import { TimeReporter } from '../shared/timeReporter' + +let element = document.getElementById("content"); +element.innerText += "The time is: "; +let span = document.createElement("span"); +element.appendChild(span); + +function printer(s: string): void { + span.innerText = s; +} + +let timeReporter = new TimeReporter(printer); +timeReporter.start(); diff --git a/umd/index.html b/umd/index.html new file mode 100644 index 0000000..b0f2761 --- /dev/null +++ b/umd/index.html @@ -0,0 +1,15 @@ + + + + + + TypeScript HTML App + + + + +

      UMD/TypeScript sample

      + +
      + + \ No newline at end of file diff --git a/umd/node/app.ts b/umd/node/app.ts new file mode 100644 index 0000000..c7f1a4a --- /dev/null +++ b/umd/node/app.ts @@ -0,0 +1,8 @@ +import { TimeReporter } from '../shared/timeReporter' +import { EOL } from 'os'; +function printer(s): void { + console.log("The time is: " + s + EOL); +} + +let timeReporter = new TimeReporter(printer); +timeReporter.start(); \ No newline at end of file diff --git a/umd/node/os.d.ts b/umd/node/os.d.ts new file mode 100644 index 0000000..77f8bed --- /dev/null +++ b/umd/node/os.d.ts @@ -0,0 +1,3 @@ +declare module "os" { + export var EOL: string; +} \ No newline at end of file diff --git a/umd/package.json b/umd/package.json new file mode 100644 index 0000000..43f3ad3 --- /dev/null +++ b/umd/package.json @@ -0,0 +1,19 @@ +{ + "name": "typescript-umd", + "version": "1.0.0", + "description": "UMD/TypeScript demo", + "repository": { + "type": "git", + "url": "https://github.com/Microsoft/TypeScriptSamples.git" + }, + "dependencies": { + "http-server": "0.8.0" + }, + "devDependencies": { + "typescript": "^1.5.3" + }, + "scripts": { + "browser": "node node_modules/typescript/bin/tsc.js && node node_modules/http-server/bin/http-server -o", + "node": "node node_modules/typescript/bin/tsc.js && node node/app.js" + } +} \ No newline at end of file diff --git a/umd/shared/timeReporter.ts b/umd/shared/timeReporter.ts new file mode 100644 index 0000000..472e975 --- /dev/null +++ b/umd/shared/timeReporter.ts @@ -0,0 +1,23 @@ +export type Printer = (s: string) => void; + +export class TimeReporter +{ + printer: Printer + timerToken: number; + + constructor (printer: Printer) + { + this.printer = printer; + this.printer(new Date().toUTCString()); + } + + start() + { + this.timerToken = setInterval(() => this.printer(new Date().toUTCString()), 500); + } + + stop() + { + clearTimeout(this.timerToken); + } +} diff --git a/umd/tsconfig.json b/umd/tsconfig.json new file mode 100644 index 0000000..e870679 --- /dev/null +++ b/umd/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "module": "UMD", + "target": "es5" + }, + "files": [ + "shared/timeReporter.ts", + "browser/app.ts", + "node/os.d.ts", + "node/app.ts" + ] +} \ No newline at end of file diff --git a/warship/default.html b/warship/default.html index 0b1bb3a..91b09bd 100644 --- a/warship/default.html +++ b/warship/default.html @@ -1,22 +1,22 @@ - - - - - - - - - - Warship Combat - - - -
      -
      -
      -
      - - + + + + + + + + + + Warship Combat + + + +
      +
      +
      +
      + + diff --git a/warship/jquery.d.ts b/warship/jquery.d.ts index f9e09f4..ad9e934 100644 --- a/warship/jquery.d.ts +++ b/warship/jquery.d.ts @@ -1,703 +1,3178 @@ -/* ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -// Typing for the jQuery library, version 1.10 - -/* - Interface for the AJAX setting that will configure the AJAX request -*/ -interface JQueryAjaxSettings { - accepts?: any; - async?: boolean; - beforeSend? (jqXHR: JQueryXHR, settings: JQueryAjaxSettings): any; - cache?: boolean; - complete? (jqXHR: JQueryXHR, textStatus: string): any; - contents?: { [key: string]: any; }; - contentType?: any; - context?: any; - converters?: { [key: string]: any; }; - crossDomain?: boolean; - data?: any; - dataFilter? (data: any, ty: any): any; - dataType?: string; - error? (jqXHR: JQueryXHR, textStatus: string, errorThrow: string): any; - global?: boolean; - headers?: { [key: string]: any; }; - ifModified?: boolean; - isLocal?: boolean; - jsonp?: string; - jsonpCallback?: any; - mimeType?: string; - password?: string; - processData?: boolean; - scriptCharset?: string; - statusCode?: { [key: string]: any; }; - success? (data: any, textStatus: string, jqXHR: JQueryXHR): any; - timeout?: number; - traditional?: boolean; - type?: string; - url?: string; - username?: string; - xhr?: any; - xhrFields?: { [key: string]: any; }; -} - -/* - Interface for the jqXHR object -*/ -interface JQueryXHR extends XMLHttpRequest { - overrideMimeType(): any; -} - -/* - Interface for the JQuery callback -*/ -interface JQueryCallback { - add(...callbacks: any[]): any; - disable(): any; - empty(): any; - fire(...arguments: any[]): any; - fired(): boolean; - fireWith(context: any, ...args: any[]): any; - has(callback: any): boolean; - lock(): any; - locked(): boolean; - removed(...callbacks: any[]): any; -} - -/* - Interface for the JQuery promise, part of callbacks -*/ -interface JQueryPromise { - always(...alwaysCallbacks: any[]): JQueryDeferred; - done(...doneCallbacks: any[]): JQueryDeferred; - fail(...failCallbacks: any[]): JQueryDeferred; - pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; - then(doneCallbacks: any, failCallbacks: any, progressCallbacks?: any): JQueryDeferred; -} - -/* - Interface for the JQuery deferred, part of callbacks -*/ -interface JQueryDeferred extends JQueryPromise { - notify(...args: any[]): JQueryDeferred; - notifyWith(context: any, ...args: any[]): JQueryDeferred; - - progress(...progressCallbacks: any[]): JQueryDeferred; - reject(...args: any[]): JQueryDeferred; - rejectWith(context: any, ...args: any[]): JQueryDeferred; - resolve(...args: any[]): JQueryDeferred; - resolveWith(context: any, ...args: any[]): JQueryDeferred; - state(): string; - then(doneCallbacks: any, failCallbacks?: any, progressCallbacks?: any): JQueryDeferred; -} - -/* - Interface of the JQuery extension of the W3C event object -*/ -interface JQueryEventObject extends Event { - data: any; - delegateTarget: Element; - isDefaultPrevented(): boolean; - isImmediatePropogationStopped(): boolean; - isPropogationStopped(): boolean; - namespace: string; - preventDefault(): any; - relatedTarget: Element; - result: any; - stopImmediatePropagation(): void; - stopPropagation(): void; - pageX: number; - pageY: number; - which: number; - metaKey: any; -} - -/* - Collection of properties of the current browser -*/ -interface JQueryBrowserInfo { - safari: boolean; - opera: boolean; - msie: boolean; - mozilla: boolean; - version: string; -} - -interface JQuerySupport { - ajax?: boolean; - boxModel?: boolean; - changeBubbles?: boolean; - checkClone?: boolean; - checkOn?: boolean; - cors?: boolean; - cssFloat?: boolean; - hrefNormalized?: boolean; - htmlSerialize?: boolean; - leadingWhitespace?: boolean; - noCloneChecked?: boolean; - noCloneEvent?: boolean; - opacity?: boolean; - optDisabled?: boolean; - optSelected?: boolean; - scriptEval? (): boolean; - style?: boolean; - submitBubbles?: boolean; - tbody?: boolean; -} - -interface JQueryTransport { - send(headers: { [index: string]: string; }, completeCallback: (status: number, statusText: string, responses: { [dataType: string]: any; }, headers: string) => void): void; - abort(): void; -} - -/* - Static members of jQuery (those on $ and jQuery themselves) -*/ -interface JQueryStatic { - - // AJAX - ajax(settings: JQueryAjaxSettings): JQueryXHR; - ajax(url: string, settings: JQueryAjaxSettings): JQueryXHR; - - ajaxPrefilter(handler: (opts: any, originalOpts: any, jqXHR: JQueryXHR) => any): any; - ajaxPrefilter(dataTypes: string, handler: (opts: any, originalOpts: any, jqXHR: JQueryXHR) => any): any; - - ajaxSetup(options: any): void; - ajaxTransport(dataType: string, handler: (options: JQueryAjaxSettings, originalOptions: JQueryAjaxSettings, jqXHR: JQueryXHR) => JQueryTransport): void; - - get(url: string, data?: any, success?: any, dataType?: any): JQueryXHR; - getJSON(url: string, data?: any, success?: any): JQueryXHR; - getScript(url: string, success?: any): JQueryXHR; - - param(obj: any): string; - param(obj: any, traditional: boolean): string; - - post(url: string, data?: any, success?: any, dataType?: any): JQueryXHR; - - // Callbacks - Callbacks(flags: any): JQueryCallback; - - // Core - holdReady(hold: boolean): any; - - (): JQuery; - (selector: string, context?: any): JQuery; - (element: Element): JQuery; - (elementArray: Element[]): JQuery; - (object: JQuery): JQuery; - (func: Function): JQuery; - (object: {}): JQuery; - - noConflict(removeAll?: boolean): Object; - - when(...deferreds: any[]): JQueryPromise; - - // CSS - css(e: any, propertyName: string, value?: any): any; - css(e: any, propertyName: any, value?: any): any; - cssHooks: { [key: string]: any; }; - - // Data - data(element: Element, key: string, value: any): Object; - - dequeue(element: Element, queueName?: string): any; - - hasData(element: Element): boolean; - - queue(element: Element, queueName?: string): any[]; - queue(element: Element, queueName: string, newQueueOrCallback: any): JQuery; - - removeData(element: Element, name?: string): JQuery; - - // Deferred - Deferred(beforeStart?: (deferred: JQueryDeferred) => any): JQueryDeferred; - - // Effects - fx: { tick: () => void; interval: number; stop: () => void; speeds: { slow: number; fast: number; }; off: boolean; step: any; }; - - // Events - proxy(func: Function, context: any): any; - proxy(context: any, name: string): any; - - // Internals - error(message: any): void; - - // Miscellaneous - expr: any; - fn: any; //TODO: Decide how we want to type this - isReady: boolean; - - // Properties - browser: JQueryBrowserInfo; - support: JQuerySupport; - - // Utilities - contains(container: Element, contained: Element): boolean; - - each(collection: any, callback: (indexInArray: any, valueOfElement: any) => any): any; - - extend(deep: boolean, target: any, ...objs: any[]): Object; - extend(target: any, ...objs: any[]): Object; - - globalEval(code: string): any; - - grep(array: any[], func: any, invert: boolean): any[]; - - inArray(value: any, array: any[], fromIndex?: number): number; - - isArray(obj: any): boolean; - isEmptyObject(obj: any): boolean; - isFunction(obj: any): boolean; - isNumeric(value: any): boolean; - isPlainObject(obj: any): boolean; - isWindow(obj: any): boolean; - isXMLDoc(node: Node): boolean; - - makeArray(obj: any): any[]; - - map(array: any[], callback: (elementOfArray: any, indexInArray: any) => any): any[]; - - merge(first: any[], second: any[]): any[]; - - noop(): any; - - now(): number; - - parseHTML(data: string, context?: Element, keepScripts?: boolean): any[]; - parseJSON(json: string): any; - - //FIXME: This should return an XMLDocument - parseXML(data: string): any; - - queue(element: Element, queueName: string, newQueue: any[]): JQuery; - - trim(str: string): string; - - type(obj: any): string; - - unique(arr: any[]): any[]; -} - -/* - The jQuery instance members -*/ -interface JQuery { - // AJAX - ajaxComplete(handler: any): JQuery; - ajaxError(handler: (evt: any, xhr: any, opts: any) => any): JQuery; - ajaxSend(handler: (evt: any, xhr: any, opts: any) => any): JQuery; - ajaxStart(handler: () => any): JQuery; - ajaxStop(handler: () => any): JQuery; - ajaxSuccess(handler: (evt: any, xml: any, opts: any) => any): JQuery; - - serialize(): string; - serializeArray(): any[]; - - // Attributes - addClass(classNames: string): JQuery; - addClass(func: (index: any, currentClass: any) => JQuery): JQuery; - - attr(attributeName: string): string; - attr(attributeName: string, func: (index: any, attr: any) => any): JQuery; - attr(attributeName: string, value: any): JQuery; - attr(map: { [key: string]: any; }): JQuery; - - hasClass(className: string): boolean; - - html(): string; - html(htmlString: string): JQuery; - - prop(propertyName: string): any; - prop(propertyName: string, func: (index: any, oldPropertyValue: any) => any): JQuery; - prop(propertyName: string, value: any): JQuery; - prop(map: any): JQuery; - - removeAttr(attributeName: any): JQuery; - - removeClass(func: (index: any, cls: any) => any): JQuery; - removeClass(className?: string): JQuery; - - removeProp(propertyName: any): JQuery; - - toggleClass(func: (index: any, cls: any, swtch: any) => any): JQuery; - toggleClass(swtch?: boolean): JQuery; - toggleClass(className: any, swtch?: boolean): JQuery; - - val(): any; - val(value: string[]): JQuery; - val(value: string): JQuery; - val(func: (index: any, value: any) => any): JQuery; - - // CSS - css(propertyNames: any[]): string; - css(propertyName: string): string; - css(propertyName: string, value: any): JQuery; - css(propertyName: any, value?: any): JQuery; - - height(): number; - height(value: number): JQuery; - height(func: (index: any, height: any) => any): JQuery; - - innerHeight(): number; - innerWidth(): number; - - offset(): { top: number; left: number; }; - offset(func: (index: any, coords: any) => any): JQuery; - offset(coordinates: any): JQuery; - - outerHeight(includeMargin?: boolean): number; - outerWidth(includeMargin?: boolean): number; - - position(): { top: number; left: number; }; - - scrollLeft(): number; - scrollLeft(value: number): JQuery; - - scrollTop(): number; - scrollTop(value: number): JQuery; - - width(): number; - width(value: number): JQuery; - width(func: (index: any, height: any) => any): JQuery; - - // Data - clearQueue(queueName?: string): JQuery; - - data(key: string, value: any): JQuery; - data(obj: { [key: string]: any; }): JQuery; - data(key?: string): any; - - dequeue(queueName?: string): JQuery; - - queue(queueName?: string): any[]; - queue(queueName: string, newQueueOrCallback: any): JQuery; - queue(newQueueOrCallback: any): JQuery; - - removeData(nameOrList?: any): JQuery; - - // Deferred - promise(type?: any, target?: any): JQueryPromise; - - // Effects - animate(properties: any, options: { duration?: any; easing?: string; complete?: Function; step?: Function; queue?: boolean; specialEasing?: any; }): JQuery; - animate(properties: any, duration?: any, easing?: "linear", complete?: Function): JQuery; - animate(properties: any, duration?: any, easing?: "swing", complete?: Function): JQuery; - animate(properties: any, duration?: any, easing?: string, complete?: Function): JQuery; - - delay(duration: number, queueName?: string): JQuery; - - fadeIn(duration?: any, easing?: "linear", complete?: Function): JQuery; - fadeIn(duration?: any, easing?: "swing", complete?: Function): JQuery; - fadeIn(duration?: any, easing?: string, complete?: Function): JQuery; - fadeIn(duration?: any, complete?: Function): JQuery; - - - fadeOut(duration?: any, easing?: "linear", complete?: Function): JQuery; - fadeOut(duration?: any, easing?: "swing", complete?: Function): JQuery; - fadeOut(duration?: any, easing?: string, complete?: Function): JQuery; - fadeOut(duration?: any, complete?: any): JQuery; - - fadeTo(duration: any, opacity: number, easing?: "linear", complete?: Function): JQuery; - fadeTo(duration: any, opacity: number, easing?: "swing", complete?: Function): JQuery; - fadeTo(duration: any, opacity: number, easing?: string, complete?: Function): JQuery; - fadeTo(duration: any, opacity: number, complete?: Function): JQuery; - - fadeToggle(duration?: any, easing?: "linear", complete?: Function): JQuery; - fadeToggle(duration?: any, easing?: "swing", complete?: Function): JQuery; - fadeToggle(duration?: any, easing?: string, complete?: Function): JQuery; - - finish(queue?: string): JQuery; - - hide(duration?: any, easing?: "linear", callback?: Function): JQuery; - hide(duration?: any, easing?: "swing", callback?: Function): JQuery; - hide(duration?: any, easing?: string, callback?: Function): JQuery; - hide(duration?: any, callback?: Function): JQuery; - - show(duration?: any, easing?: "linear", complete?: Function): JQuery; - show(duration?: any, easing?: "swing", complete?: Function): JQuery; - show(duration?: any, easing?: string, complete?: Function): JQuery; - show(duration?: any, complete?: Function): JQuery; - - slideDown(duration?: any, easing?: "linear", complete?: Function): JQuery; - slideDown(duration?: any, easing?: "swing", complete?: Function): JQuery; - slideDown(duration?: any, easing?: string, complete?: Function): JQuery; - slideDown(duration?: any, complete?: Function): JQuery; - - slideToggle(duration?: any, easing?: "linear", complete?: Function): JQuery; - slideToggle(duration?: any, easing?: "swing", complete?: Function): JQuery; - slideToggle(duration?: any, easing?: string, complete?: Function): JQuery; - slideToggle(duration?: any, complete?: Function): JQuery; - - slideUp(duration?: any, easing?: "linear", complete?: Function): JQuery; - slideUp(duration?: any, easing?: "swing", complete?: Function): JQuery; - slideUp(duration?: any, easing?: string, complete?: Function): JQuery; - slideUp(duration?: any, complete?: Function): JQuery; - - stop(clearQueue?: boolean, jumpToEnd?: boolean): JQuery; - stop(queue?: any, clearQueue?: boolean, jumpToEnd?: boolean): JQuery; - - toggle(showOrHide: boolean): JQuery; - toggle(duration?: any, easing?: "linear", complete?: Function): JQuery; - toggle(duration?: any, easing?: "swing", complete?: Function): JQuery; - toggle(duration?: any, easing?: string, complete?: Function): JQuery; - toggle(duration?: any, complete?: Function): JQuery; - - // Events - bind(eventType: string, preventBubble: boolean): JQuery; - bind(eventType: string, eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - bind(eventType: string, eventData: any, preventBubble: boolean): JQuery; - bind(...events: any[]): JQuery; - - blur(handler: (eventObject: JQueryEventObject) => any): JQuery; - blur(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - change(handler: (eventObject: JQueryEventObject) => any): JQuery; - change(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - click(handler: (eventObject: JQueryEventObject) => any): JQuery; - click(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - dblclick(handler: (eventObject: JQueryEventObject) => any): JQuery; - dblclick(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - delegate(selector: any, eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; - - focus(handler: (eventObject: JQueryEventObject) => any): JQuery; - focus(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - focusin(handler: (eventObject: JQueryEventObject) => any): JQuery; - focusin(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - focusout(handler: (eventObject: JQueryEventObject) => any): JQuery; - focusout(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - hover(handlerIn: (eventObject: JQueryEventObject) => any, handlerOut: (eventObject: JQueryEventObject) => any): JQuery; - hover(handlerInOut: (eventObject: JQueryEventObject) => any): JQuery; - - keydown(handler: (eventObject: JQueryEventObject) => any): JQuery; - keydown(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - keypress(handler: (eventObject: JQueryEventObject) => any): JQuery; - keypress(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - keyup(handler: (eventObject: JQueryEventObject) => any): JQuery; - keyup(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - mousedown(handler: (eventObject: JQueryEventObject) => any): JQuery; - mousedown(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - mouseevent(handler: (eventObject: JQueryEventObject) => any): JQuery; - mouseevent(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - mouseenter(handler: (eventObject: JQueryEventObject) => any): JQuery; - mouseenter(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - mouseleave(handler: (eventObject: JQueryEventObject) => any): JQuery; - mouseleave(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - mousemove(handler: (eventObject: JQueryEventObject) => any): JQuery; - mousemove(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - mouseout(handler: (eventObject: JQueryEventObject) => any): JQuery; - mouseout(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - mouseover(handler: (eventObject: JQueryEventObject) => any): JQuery; - mouseover(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - mouseup(handler: (eventObject: JQueryEventObject) => any): JQuery; - mouseup(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - off(events?: string, selector?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - off(eventsMap: { [key: string]: any; }, selector?: any): JQuery; - - on(events: string, selector?: any, data?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - on(eventsMap: { [key: string]: any; }, selector?: any, data?: any): JQuery; - - one(events: string, selector?: any, data?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - one(eventsMap: { [key: string]: any; }, selector?: any, data?: any): JQuery; - - ready(handler: any): JQuery; - - resize(handler: (eventObject: JQueryEventObject) => any): JQuery; - resize(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - scroll(handler: (eventObject: JQueryEventObject) => any): JQuery; - scroll(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - select(handler: (eventObject: JQueryEventObject) => any): JQuery; - select(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - submit(handler: (eventObject: JQueryEventObject) => any): JQuery; - submit(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - trigger(eventType: string, ...extraParameters: any[]): JQuery; - trigger(event: JQueryEventObject): JQuery; - - triggerHandler(eventType: string, ...extraParameters: any[]): Object; - - unbind(eventType?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - unbind(eventType: string, fls: boolean): JQuery; - unbind(evt: any): JQuery; - - undelegate(): JQuery; - undelegate(selector: any, eventType: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - undelegate(selector: any, events: any): JQuery; - undelegate(namespace: string): JQuery; - - // Internals - context: Element; - jquery: string; - pushStack(elements: any[]): JQuery; - pushStack(elements: any[], name: any, arguments: any): JQuery; - - // Manipulation - after(func: (index: any) => any): JQuery; - after(...content: any[]): JQuery; - - append(func: (index: any, html: any) => any): JQuery; - append(...content: any[]): JQuery; - - appendTo(target: any): JQuery; - - before(func: (index: any) => any): JQuery; - before(...content: any[]): JQuery; - - clone(withDataAndEvents?: boolean, deepWithDataAndEvents?: boolean): JQuery; - - detach(selector?: any): JQuery; - - empty(): JQuery; - - insertAfter(target: any): JQuery; - insertBefore(target: any): JQuery; - - prepend(func: (index: any, html: any) => any): JQuery; - prepend(...content: any[]): JQuery; - - prependTo(target: any): JQuery; - - remove(selector?: any): JQuery; - - replaceAll(target: any): JQuery; - - replaceWith(func: any): JQuery; - - text(textString: string): JQuery; - text(): string; - - toArray(): any[]; - - unwrap(): JQuery; - - wrap(func: (index: any) => any): JQuery; - wrap(wrappingElement: any): JQuery; - - wrapAll(wrappingElement: any): JQuery; - - wrapInner(func: (index: any) => any): JQuery; - wrapInner(wrappingElement: any): JQuery; - - // Miscellaneous - each(func: (index: any, elem: Element) => any): JQuery; - - get(index?: number): any; - - index(selectorOrElement?: any): number; - - // Properties - length: number; - [x: number]: HTMLElement; - - // Traversing - add(selector: string, context?: any): JQuery; - add(html: string): JQuery; - add(obj: JQuery): JQuery; - add(...elements: any[]): JQuery; - - addBack(selector?: any): JQuery; - - children(selector?: any): JQuery; - - closest(selector: string): JQuery; - closest(selector: string, context?: Element): JQuery; - closest(obj: JQuery): JQuery; - closest(element: any): JQuery; - closest(selectors: any, context?: Element): any[]; - - contents(): JQuery; - - end(): JQuery; - - eq(index: number): JQuery; - - filter(selector: string): JQuery; - filter(func: (index: any) => any): JQuery; - filter(obj: JQuery): JQuery; - filter(element: any): JQuery; - - find(selector: string): JQuery; - find(element: any): JQuery; - find(obj: JQuery): JQuery; - - first(): JQuery; - - has(selector: string): JQuery; - has(contained: Element): JQuery; - - is(selector: string): boolean; - is(func: (index: any) => any): boolean; - is(obj: JQuery): boolean; - is(element: any): boolean; - - last(): JQuery; - - map(callback: (index: any, domElement: Element) => any): JQuery; - - next(selector?: string): JQuery; - - nextAll(selector?: string): JQuery; - - nextUntil(selector?: string, filter?: string): JQuery; - nextUntil(element?: Element, filter?: string): JQuery; - - not(selector: string): JQuery; - not(func: (index: any) => any): JQuery; - not(obj: JQuery): JQuery; - not(element: any): JQuery; - - offsetParent(): JQuery; - - parent(selector?: string): JQuery; - - parents(selector?: string): JQuery; - - parentsUntil(selector?: string, filter?: string): JQuery; - parentsUntil(element?: Element, filter?: string): JQuery; - - prev(selector?: string): JQuery; - - prevAll(selector?: string): JQuery; - - prevUntil(selector?: string, filter?: string): JQuery; - prevUntil(element?: Element, filter?: string): JQuery; - - siblings(selector?: string): JQuery; - - slice(start: number, end?: number): JQuery; -} - -declare var jQuery: JQueryStatic; -declare var $: JQueryStatic; +// Type definitions for jQuery 1.10.x / 2.0.x +// Project: http://jquery.com/ +// Definitions by: Boris Yankov , Christian Hoffmeister , Steve Fenton , Diullei Gomes , Tass Iliopoulos , Jason Swearingen , Sean Hill , Guus Goossens , Kelly Summerlin , Basarat Ali Syed , Nicholas Wolverson , Derek Cicerone , Andrew Gaspar , James Harrison Fisher , Seikichi Kondo , Benjamin Jackman , Poul Sorensen , Josh Strobl , John Reilly , Dick van den Brink +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + +/** + * Interface for the AJAX setting that will configure the AJAX request + */ +interface JQueryAjaxSettings { + /** + * The content type sent in the request header that tells the server what kind of response it will accept in return. If the accepts setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. + */ + accepts?: any; + /** + * By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success(). + */ + async?: boolean; + /** + * A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request. + */ + beforeSend? (jqXHR: JQueryXHR, settings: JQueryAjaxSettings): any; + /** + * If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET. + */ + cache?: boolean; + /** + * A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. + */ + complete? (jqXHR: JQueryXHR, textStatus: string): any; + /** + * An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type. (version added: 1.5) + */ + contents?: { [key: string]: any; }; + //According to jQuery.ajax source code, ajax's option actually allows contentType to set to "false" + // https://github.com/borisyankov/DefinitelyTyped/issues/742 + /** + * When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. + */ + contentType?: any; + /** + * This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). + */ + context?: any; + /** + * An object containing dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response. (version added: 1.5) + */ + converters?: { [key: string]: any; }; + /** + * If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain. (version added: 1.5) + */ + crossDomain?: boolean; + /** + * Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). + */ + data?: any; + /** + * A function to be used to handle the raw response data of XMLHttpRequest.This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter. + */ + dataFilter? (data: any, ty: any): any; + /** + * The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). + */ + dataType?: string; + /** + * A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event. + */ + error? (jqXHR: JQueryXHR, textStatus: string, errorThrown: string): any; + /** + * Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events. + */ + global?: boolean; + /** + * An object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport. The header X-Requested-With: XMLHttpRequest is always added, but its default XMLHttpRequest value can be changed here. Values in the headers setting can also be overwritten from within the beforeSend function. (version added: 1.5) + */ + headers?: { [key: string]: any; }; + /** + * Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data. + */ + ifModified?: boolean; + /** + * Allow the current environment to be recognized as "local," (e.g. the filesystem), even if jQuery does not recognize it as such by default. The following protocols are currently recognized as local: file, *-extension, and widget. If the isLocal setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. (version added: 1.5.1) + */ + isLocal?: boolean; + /** + * Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" } + */ + jsonp?: any; + /** + * Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function. + */ + jsonpCallback?: any; + /** + * The HTTP method to use for the request (e.g. "POST", "GET", "PUT"). (version added: 1.9.0) + */ + method?: string; + /** + * A mime type to override the XHR mime type. (version added: 1.5.1) + */ + mimeType?: string; + /** + * A password to be used with XMLHttpRequest in response to an HTTP access authentication request. + */ + password?: string; + /** + * By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false. + */ + processData?: boolean; + /** + * Only applies when the "script" transport is used (e.g., cross-domain requests with "jsonp" or "script" dataType and "GET" type). Sets the charset attribute on the script tag used in the request. Used when the character set on the local page is not the same as the one on the remote script. + */ + scriptCharset?: string; + /** + * An object of numeric HTTP codes and functions to be called when the response has the corresponding code. f the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback. (version added: 1.5) + */ + statusCode?: { [key: string]: any; }; + /** + * A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. + */ + success? (data: any, textStatus: string, jqXHR: JQueryXHR): any; + /** + * Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period. + */ + timeout?: number; + /** + * Set this to true if you wish to use the traditional style of param serialization. + */ + traditional?: boolean; + /** + * The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers. + */ + type?: string; + /** + * A string containing the URL to which the request is sent. + */ + url?: string; + /** + * A username to be used with XMLHttpRequest in response to an HTTP access authentication request. + */ + username?: string; + /** + * Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory. + */ + xhr?: any; + /** + * An object of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed. In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it. (version added: 1.5.1) + */ + xhrFields?: { [key: string]: any; }; +} + +/** + * Interface for the jqXHR object + */ +interface JQueryXHR extends XMLHttpRequest, JQueryPromise { + /** + * The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header. As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). + */ + overrideMimeType(mimeType: string): any; + /** + * Cancel the request. + * + * @param statusText A string passed as the textStatus parameter for the done callback. Default value: "canceled" + */ + abort(statusText?: string): void; + /** + * Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details. + */ + then(doneCallback: (data: any, textStatus: string, jqXHR: JQueryXHR) => void, failCallback?: (jqXHR: JQueryXHR, textStatus: string, errorThrown: any) => void): JQueryPromise; + /** + * Property containing the parsed response if the response Content-Type is json + */ + responseJSON?: any; + /** + * A function to be called if the request fails. + */ + error(xhr: JQueryXHR, textStatus: string, errorThrown: string): void; +} + +/** + * Interface for the JQuery callback + */ +interface JQueryCallback { + /** + * Add a callback or a collection of callbacks to a callback list. + * + * @param callbacks A function, or array of functions, that are to be added to the callback list. + */ + add(callbacks: Function): JQueryCallback; + /** + * Add a callback or a collection of callbacks to a callback list. + * + * @param callbacks A function, or array of functions, that are to be added to the callback list. + */ + add(callbacks: Function[]): JQueryCallback; + + /** + * Disable a callback list from doing anything more. + */ + disable(): JQueryCallback; + + /** + * Determine if the callbacks list has been disabled. + */ + disabled(): boolean; + + /** + * Remove all of the callbacks from a list. + */ + empty(): JQueryCallback; + + /** + * Call all of the callbacks with the given arguments + * + * @param arguments The argument or list of arguments to pass back to the callback list. + */ + fire(...arguments: any[]): JQueryCallback; + + /** + * Determine if the callbacks have already been called at least once. + */ + fired(): boolean; + + /** + * Call all callbacks in a list with the given context and arguments. + * + * @param context A reference to the context in which the callbacks in the list should be fired. + * @param arguments An argument, or array of arguments, to pass to the callbacks in the list. + */ + fireWith(context?: any, ...args: any[]): JQueryCallback; + + /** + * Determine whether a supplied callback is in a list + * + * @param callback The callback to search for. + */ + has(callback: Function): boolean; + + /** + * Lock a callback list in its current state. + */ + lock(): JQueryCallback; + + /** + * Determine if the callbacks list has been locked. + */ + locked(): boolean; + + /** + * Remove a callback or a collection of callbacks from a callback list. + * + * @param callbacks A function, or array of functions, that are to be removed from the callback list. + */ + remove(callbacks: Function): JQueryCallback; + /** + * Remove a callback or a collection of callbacks from a callback list. + * + * @param callbacks A function, or array of functions, that are to be removed from the callback list. + */ + remove(callbacks: Function[]): JQueryCallback; +} + +/** + * Allows jQuery Promises to interop with non-jQuery promises + */ +interface JQueryGenericPromise { + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + */ + then(doneFilter: (value?: T, ...values: any[]) => U|JQueryPromise, failFilter?: (...reasons: any[]) => any, progressFilter?: (...progression: any[]) => any): JQueryPromise; + + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + */ + then(doneFilter: (value?: T, ...values: any[]) => void, failFilter?: (...reasons: any[]) => any, progressFilter?: (...progression: any[]) => any): JQueryPromise; +} + +/** + * Interface for the JQuery promise/deferred callbacks + */ +interface JQueryPromiseCallback { + (value?: T, ...args: any[]): void; +} + +interface JQueryPromiseOperator { + (callback1: JQueryPromiseCallback|JQueryPromiseCallback[], ...callbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; +} + +/** + * Interface for the JQuery promise, part of callbacks + */ +interface JQueryPromise extends JQueryGenericPromise { + /** + * Determine the current state of a Deferred object. + */ + state(): string; + /** + * Add handlers to be called when the Deferred object is either resolved or rejected. + * + * @param alwaysCallbacks1 A function, or array of functions, that is called when the Deferred is resolved or rejected. + * @param alwaysCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. + */ + always(alwaysCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...alwaysCallbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; + /** + * Add handlers to be called when the Deferred object is resolved. + * + * @param doneCallbacks1 A function, or array of functions, that are called when the Deferred is resolved. + * @param doneCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. + */ + done(doneCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...doneCallbackN: Array|JQueryPromiseCallback[]>): JQueryPromise; + /** + * Add handlers to be called when the Deferred object is rejected. + * + * @param failCallbacks1 A function, or array of functions, that are called when the Deferred is rejected. + * @param failCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. + */ + fail(failCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...failCallbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; + /** + * Add handlers to be called when the Deferred object generates progress notifications. + * + * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications. + */ + progress(progressCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...progressCallbackN: Array|JQueryPromiseCallback[]>): JQueryPromise; + + // Deprecated - given no typings + pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; +} + +/** + * Interface for the JQuery deferred, part of callbacks + */ +interface JQueryDeferred extends JQueryGenericPromise { + /** + * Determine the current state of a Deferred object. + */ + state(): string; + /** + * Add handlers to be called when the Deferred object is either resolved or rejected. + * + * @param alwaysCallbacks1 A function, or array of functions, that is called when the Deferred is resolved or rejected. + * @param alwaysCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. + */ + always(alwaysCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...alwaysCallbacksN: Array|JQueryPromiseCallback[]>): JQueryDeferred; + /** + * Add handlers to be called when the Deferred object is resolved. + * + * @param doneCallbacks1 A function, or array of functions, that are called when the Deferred is resolved. + * @param doneCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. + */ + done(doneCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...doneCallbackN: Array|JQueryPromiseCallback[]>): JQueryDeferred; + /** + * Add handlers to be called when the Deferred object is rejected. + * + * @param failCallbacks1 A function, or array of functions, that are called when the Deferred is rejected. + * @param failCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. + */ + fail(failCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...failCallbacksN: Array|JQueryPromiseCallback[]>): JQueryDeferred; + /** + * Add handlers to be called when the Deferred object generates progress notifications. + * + * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications. + */ + progress(progressCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...progressCallbackN: Array|JQueryPromiseCallback[]>): JQueryDeferred; + + /** + * Call the progressCallbacks on a Deferred object with the given args. + * + * @param args Optional arguments that are passed to the progressCallbacks. + */ + notify(value?: any, ...args: any[]): JQueryDeferred; + + /** + * Call the progressCallbacks on a Deferred object with the given context and args. + * + * @param context Context passed to the progressCallbacks as the this object. + * @param args Optional arguments that are passed to the progressCallbacks. + */ + notifyWith(context: any, value?: any, ...args: any[]): JQueryDeferred; + + /** + * Reject a Deferred object and call any failCallbacks with the given args. + * + * @param args Optional arguments that are passed to the failCallbacks. + */ + reject(value?: any, ...args: any[]): JQueryDeferred; + /** + * Reject a Deferred object and call any failCallbacks with the given context and args. + * + * @param context Context passed to the failCallbacks as the this object. + * @param args An optional array of arguments that are passed to the failCallbacks. + */ + rejectWith(context: any, value?: any, ...args: any[]): JQueryDeferred; + + /** + * Resolve a Deferred object and call any doneCallbacks with the given args. + * + * @param value First argument passed to doneCallbacks. + * @param args Optional subsequent arguments that are passed to the doneCallbacks. + */ + resolve(value?: T, ...args: any[]): JQueryDeferred; + + /** + * Resolve a Deferred object and call any doneCallbacks with the given context and args. + * + * @param context Context passed to the doneCallbacks as the this object. + * @param args An optional array of arguments that are passed to the doneCallbacks. + */ + resolveWith(context: any, value?: T, ...args: any[]): JQueryDeferred; + + /** + * Return a Deferred's Promise object. + * + * @param target Object onto which the promise methods have to be attached + */ + promise(target?: any): JQueryPromise; + + // Deprecated - given no typings + pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; +} + +/** + * Interface of the JQuery extension of the W3C event object + */ +interface BaseJQueryEventObject extends Event { + data: any; + delegateTarget: Element; + isDefaultPrevented(): boolean; + isImmediatePropagationStopped(): boolean; + isPropagationStopped(): boolean; + namespace: string; + originalEvent: Event; + preventDefault(): any; + relatedTarget: Element; + result: any; + stopImmediatePropagation(): void; + stopPropagation(): void; + target: Element; + pageX: number; + pageY: number; + which: number; + metaKey: boolean; +} + +interface JQueryInputEventObject extends BaseJQueryEventObject { + altKey: boolean; + ctrlKey: boolean; + metaKey: boolean; + shiftKey: boolean; +} + +interface JQueryMouseEventObject extends JQueryInputEventObject { + button: number; + clientX: number; + clientY: number; + offsetX: number; + offsetY: number; + pageX: number; + pageY: number; + screenX: number; + screenY: number; +} + +interface JQueryKeyEventObject extends JQueryInputEventObject { + char: any; + charCode: number; + key: any; + keyCode: number; +} + +interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject{ +} + +/* + Collection of properties of the current browser +*/ + +interface JQuerySupport { + ajax?: boolean; + boxModel?: boolean; + changeBubbles?: boolean; + checkClone?: boolean; + checkOn?: boolean; + cors?: boolean; + cssFloat?: boolean; + hrefNormalized?: boolean; + htmlSerialize?: boolean; + leadingWhitespace?: boolean; + noCloneChecked?: boolean; + noCloneEvent?: boolean; + opacity?: boolean; + optDisabled?: boolean; + optSelected?: boolean; + scriptEval? (): boolean; + style?: boolean; + submitBubbles?: boolean; + tbody?: boolean; +} + +interface JQueryParam { + /** + * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. + * + * @param obj An array or object to serialize. + */ + (obj: any): string; + + /** + * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. + * + * @param obj An array or object to serialize. + * @param traditional A Boolean indicating whether to perform a traditional "shallow" serialization. + */ + (obj: any, traditional: boolean): string; +} + +/** + * The interface used to construct jQuery events (with $.Event). It is + * defined separately instead of inline in JQueryStatic to allow + * overriding the construction function with specific strings + * returning specific event objects. + */ +interface JQueryEventConstructor { + (name: string, eventProperties?: any): JQueryEventObject; + new (name: string, eventProperties?: any): JQueryEventObject; +} + +/** + * The interface used to specify coordinates. + */ +interface JQueryCoordinates { + left: number; + top: number; +} + +/** + * Elements in the array returned by serializeArray() + */ +interface JQuerySerializeArrayElement { + name: string; + value: string; +} + +interface JQueryAnimationOptions { + /** + * A string or number determining how long the animation will run. + */ + duration?: any; + /** + * A string indicating which easing function to use for the transition. + */ + easing?: string; + /** + * A function to call once the animation is complete. + */ + complete?: Function; + /** + * A function to be called for each animated property of each animated element. This function provides an opportunity to modify the Tween object to change the value of the property before it is set. + */ + step?: (now: number, tween: any) => any; + /** + * A function to be called after each step of the animation, only once per animated element regardless of the number of animated properties. (version added: 1.8) + */ + progress?: (animation: JQueryPromise, progress: number, remainingMs: number) => any; + /** + * A function to call when the animation begins. (version added: 1.8) + */ + start?: (animation: JQueryPromise) => any; + /** + * A function to be called when the animation completes (its Promise object is resolved). (version added: 1.8) + */ + done?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; + /** + * A function to be called when the animation fails to complete (its Promise object is rejected). (version added: 1.8) + */ + fail?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; + /** + * A function to be called when the animation completes or stops without completing (its Promise object is either resolved or rejected). (version added: 1.8) + */ + always?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; + /** + * A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case the animation is added to the queue represented by that string. When a custom queue name is used the animation does not automatically start; you must call .dequeue("queuename") to start it. + */ + queue?: any; + /** + * A map of one or more of the CSS properties defined by the properties argument and their corresponding easing functions. (version added: 1.4) + */ + specialEasing?: Object; +} + +/** + * Static members of jQuery (those on $ and jQuery themselves) + */ +interface JQueryStatic { + + /** + * Perform an asynchronous HTTP (Ajax) request. + * + * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). + */ + ajax(settings: JQueryAjaxSettings): JQueryXHR; + /** + * Perform an asynchronous HTTP (Ajax) request. + * + * @param url A string containing the URL to which the request is sent. + * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). + */ + ajax(url: string, settings?: JQueryAjaxSettings): JQueryXHR; + + /** + * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). + * + * @param dataTypes An optional string containing one or more space-separated dataTypes + * @param handler A handler to set default values for future Ajax requests. + */ + ajaxPrefilter(dataTypes: string, handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; + /** + * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). + * + * @param handler A handler to set default values for future Ajax requests. + */ + ajaxPrefilter(handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; + + ajaxSettings: JQueryAjaxSettings; + + /** + * Set default values for future Ajax requests. Its use is not recommended. + * + * @param options A set of key/value pairs that configure the default Ajax request. All options are optional. + */ + ajaxSetup(options: JQueryAjaxSettings): void; + + /** + * Load data from the server using a HTTP GET request. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). + */ + get(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + /** + * Load data from the server using a HTTP GET request. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). + */ + get(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + /** + * Load JSON-encoded data from the server using a GET HTTP request. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. + */ + getJSON(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; + /** + * Load JSON-encoded data from the server using a GET HTTP request. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. + */ + getJSON(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; + /** + * Load a JavaScript file from the server using a GET HTTP request, then execute it. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. + */ + getScript(url: string, success?: (script: string, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; + + /** + * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. + */ + param: JQueryParam; + + /** + * Load data from the server using a HTTP POST request. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). + */ + post(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + /** + * Load data from the server using a HTTP POST request. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). + */ + post(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + + /** + * A multi-purpose callbacks list object that provides a powerful way to manage callback lists. + * + * @param flags An optional list of space-separated flags that change how the callback list behaves. + */ + Callbacks(flags?: string): JQueryCallback; + + /** + * Holds or releases the execution of jQuery's ready event. + * + * @param hold Indicates whether the ready hold is being requested or released + */ + holdReady(hold: boolean): void; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param selector A string containing a selector expression + * @param context A DOM Element, Document, or jQuery to use as context + */ + (selector: string, context?: Element|JQuery): JQuery; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param element A DOM element to wrap in a jQuery object. + */ + (element: Element): JQuery; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param elementArray An array containing a set of DOM elements to wrap in a jQuery object. + */ + (elementArray: Element[]): JQuery; + + /** + * Binds a function to be executed when the DOM has finished loading. + * + * @param callback A function to execute after the DOM is ready. + */ + (callback: (jQueryAlias?: JQueryStatic) => any): JQuery; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param object A plain object to wrap in a jQuery object. + */ + (object: {}): JQuery; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param object An existing jQuery object to clone. + */ + (object: JQuery): JQuery; + + /** + * Specify a function to execute when the DOM is fully loaded. + */ + (): JQuery; + + /** + * Creates DOM elements on the fly from the provided string of raw HTML. + * + * @param html A string of HTML to create on the fly. Note that this parses HTML, not XML. + * @param ownerDocument A document in which the new elements will be created. + */ + (html: string, ownerDocument?: Document): JQuery; + + /** + * Creates DOM elements on the fly from the provided string of raw HTML. + * + * @param html A string defining a single, standalone, HTML element (e.g.
      or
      ). + * @param attributes An object of attributes, events, and methods to call on the newly-created element. + */ + (html: string, attributes: Object): JQuery; + + /** + * Relinquish jQuery's control of the $ variable. + * + * @param removeAll A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself). + */ + noConflict(removeAll?: boolean): Object; + + /** + * Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. + * + * @param deferreds One or more Deferred objects, or plain JavaScript objects. + */ + when(...deferreds: Array/* as JQueryDeferred */>): JQueryPromise; + + /** + * Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize CSS property naming, or create custom properties. + */ + cssHooks: { [key: string]: any; }; + cssNumber: any; + + /** + * Store arbitrary data associated with the specified element. Returns the value that was set. + * + * @param element The DOM element to associate with the data. + * @param key A string naming the piece of data to set. + * @param value The new data value. + */ + data(element: Element, key: string, value: T): T; + /** + * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. + * + * @param element The DOM element to associate with the data. + * @param key A string naming the piece of data to set. + */ + data(element: Element, key: string): any; + /** + * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. + * + * @param element The DOM element to associate with the data. + */ + data(element: Element): any; + + /** + * Execute the next function on the queue for the matched element. + * + * @param element A DOM element from which to remove and execute a queued function. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + dequeue(element: Element, queueName?: string): void; + + /** + * Determine whether an element has any jQuery data associated with it. + * + * @param element A DOM element to be checked for data. + */ + hasData(element: Element): boolean; + + /** + * Show the queue of functions to be executed on the matched element. + * + * @param element A DOM element to inspect for an attached queue. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + queue(element: Element, queueName?: string): any[]; + /** + * Manipulate the queue of functions to be executed on the matched element. + * + * @param element A DOM element where the array of queued functions is attached. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param newQueue An array of functions to replace the current queue contents. + */ + queue(element: Element, queueName: string, newQueue: Function[]): JQuery; + /** + * Manipulate the queue of functions to be executed on the matched element. + * + * @param element A DOM element on which to add a queued function. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param callback The new function to add to the queue. + */ + queue(element: Element, queueName: string, callback: Function): JQuery; + + /** + * Remove a previously-stored piece of data. + * + * @param element A DOM element from which to remove data. + * @param name A string naming the piece of data to remove. + */ + removeData(element: Element, name?: string): JQuery; + + /** + * A constructor function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function. + * + * @param beforeStart A function that is called just before the constructor returns. + */ + Deferred(beforeStart?: (deferred: JQueryDeferred) => any): JQueryDeferred; + + /** + * Effects + */ + fx: { + tick: () => void; + /** + * The rate (in milliseconds) at which animations fire. + */ + interval: number; + stop: () => void; + speeds: { slow: number; fast: number; }; + /** + * Globally disable all animations. + */ + off: boolean; + step: any; + }; + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fnction The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @param additionalArguments Any number of arguments to be passed to the function referenced in the function argument. + */ + proxy(fnction: (...args: any[]) => any, context: Object, ...additionalArguments: any[]): any; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param context The object to which the context (this) of the function should be set. + * @param name The name of the function whose context will be changed (should be a property of the context object). + * @param additionalArguments Any number of arguments to be passed to the function named in the name argument. + */ + proxy(context: Object, name: string, ...additionalArguments: any[]): any; + + Event: JQueryEventConstructor; + + /** + * Takes a string and throws an exception containing it. + * + * @param message The message to send out. + */ + error(message: any): JQuery; + + expr: any; + fn: any; //TODO: Decide how we want to type this + + isReady: boolean; + + // Properties + support: JQuerySupport; + + /** + * Check to see if a DOM element is a descendant of another DOM element. + * + * @param container The DOM element that may contain the other element. + * @param contained The DOM element that may be contained by (a descendant of) the other element. + */ + contains(container: Element, contained: Element): boolean; + + /** + * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. + * + * @param collection The object or array to iterate over. + * @param callback The function that will be executed on every object. + */ + each( + collection: T[], + callback: (indexInArray: number, valueOfElement: T) => any + ): any; + + /** + * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. + * + * @param collection The object or array to iterate over. + * @param callback The function that will be executed on every object. + */ + each( + collection: any, + callback: (indexInArray: any, valueOfElement: any) => any + ): any; + + /** + * Merge the contents of two or more objects together into the first object. + * + * @param target An object that will receive the new properties if additional objects are passed in or that will extend the jQuery namespace if it is the sole argument. + * @param object1 An object containing additional properties to merge in. + * @param objectN Additional objects containing properties to merge in. + */ + extend(target: any, object1?: any, ...objectN: any[]): any; + /** + * Merge the contents of two or more objects together into the first object. + * + * @param deep If true, the merge becomes recursive (aka. deep copy). + * @param target The object to extend. It will receive the new properties. + * @param object1 An object containing additional properties to merge in. + * @param objectN Additional objects containing properties to merge in. + */ + extend(deep: boolean, target: any, object1?: any, ...objectN: any[]): any; + + /** + * Execute some JavaScript code globally. + * + * @param code The JavaScript code to execute. + */ + globalEval(code: string): any; + + /** + * Finds the elements of an array which satisfy a filter function. The original array is not affected. + * + * @param array The array to search through. + * @param func The function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value. this will be the global window object. + * @param invert If "invert" is false, or not provided, then the function returns an array consisting of all elements for which "callback" returns true. If "invert" is true, then the function returns an array consisting of all elements for which "callback" returns false. + */ + grep(array: T[], func: (elementOfArray: T, indexInArray: number) => boolean, invert?: boolean): T[]; + + /** + * Search for a specified value within an array and return its index (or -1 if not found). + * + * @param value The value to search for. + * @param array An array through which to search. + * @param fromIndex he index of the array at which to begin the search. The default is 0, which will search the whole array. + */ + inArray(value: T, array: T[], fromIndex?: number): number; + + /** + * Determine whether the argument is an array. + * + * @param obj Object to test whether or not it is an array. + */ + isArray(obj: any): boolean; + /** + * Check to see if an object is empty (contains no enumerable properties). + * + * @param obj The object that will be checked to see if it's empty. + */ + isEmptyObject(obj: any): boolean; + /** + * Determine if the argument passed is a Javascript function object. + * + * @param obj Object to test whether or not it is a function. + */ + isFunction(obj: any): boolean; + /** + * Determines whether its argument is a number. + * + * @param obj The value to be tested. + */ + isNumeric(value: any): boolean; + /** + * Check to see if an object is a plain object (created using "{}" or "new Object"). + * + * @param obj The object that will be checked to see if it's a plain object. + */ + isPlainObject(obj: any): boolean; + /** + * Determine whether the argument is a window. + * + * @param obj Object to test whether or not it is a window. + */ + isWindow(obj: any): boolean; + /** + * Check to see if a DOM node is within an XML document (or is an XML document). + * + * @param node he DOM node that will be checked to see if it's in an XML document. + */ + isXMLDoc(node: Node): boolean; + + /** + * Convert an array-like object into a true JavaScript array. + * + * @param obj Any object to turn into a native Array. + */ + makeArray(obj: any): any[]; + + /** + * Translate all items in an array or object to new array of items. + * + * @param array The Array to translate. + * @param callback The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. Within the function, this refers to the global (window) object. + */ + map(array: T[], callback: (elementOfArray: T, indexInArray: number) => U): U[]; + /** + * Translate all items in an array or object to new array of items. + * + * @param arrayOrObject The Array or Object to translate. + * @param callback The function to process each item against. The first argument to the function is the value; the second argument is the index or key of the array or object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object. + */ + map(arrayOrObject: any, callback: (value: any, indexOrKey: any) => any): any; + + /** + * Merge the contents of two arrays together into the first array. + * + * @param first The first array to merge, the elements of second added. + * @param second The second array to merge into the first, unaltered. + */ + merge(first: T[], second: T[]): T[]; + + /** + * An empty function. + */ + noop(): any; + + /** + * Return a number representing the current time. + */ + now(): number; + + /** + * Takes a well-formed JSON string and returns the resulting JavaScript object. + * + * @param json The JSON string to parse. + */ + parseJSON(json: string): any; + + /** + * Parses a string into an XML document. + * + * @param data a well-formed XML string to be parsed + */ + parseXML(data: string): XMLDocument; + + /** + * Remove the whitespace from the beginning and end of a string. + * + * @param str Remove the whitespace from the beginning and end of a string. + */ + trim(str: string): string; + + /** + * Determine the internal JavaScript [[Class]] of an object. + * + * @param obj Object to get the internal JavaScript [[Class]] of. + */ + type(obj: any): string; + + /** + * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers. + * + * @param array The Array of DOM elements. + */ + unique(array: Element[]): Element[]; + + /** + * Parses a string into an array of DOM nodes. + * + * @param data HTML string to be parsed + * @param context DOM element to serve as the context in which the HTML fragment will be created + * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string + */ + parseHTML(data: string, context?: HTMLElement, keepScripts?: boolean): any[]; + + /** + * Parses a string into an array of DOM nodes. + * + * @param data HTML string to be parsed + * @param context DOM element to serve as the context in which the HTML fragment will be created + * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string + */ + parseHTML(data: string, context?: Document, keepScripts?: boolean): any[]; +} + +/** + * The jQuery instance members + */ +interface JQuery { + /** + * Register a handler to be called when Ajax requests complete. This is an AjaxEvent. + * + * @param handler The function to be invoked. + */ + ajaxComplete(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: any) => any): JQuery; + /** + * Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxError(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxSettings: JQueryAjaxSettings, thrownError: any) => any): JQuery; + /** + * Attach a function to be executed before an Ajax request is sent. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxSend(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxOptions: JQueryAjaxSettings) => any): JQuery; + /** + * Register a handler to be called when the first Ajax request begins. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxStart(handler: () => any): JQuery; + /** + * Register a handler to be called when all Ajax requests have completed. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxStop(handler: () => any): JQuery; + /** + * Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxSuccess(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: JQueryAjaxSettings) => any): JQuery; + + /** + * Load data from the server and place the returned HTML into the matched element. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param complete A callback function that is executed when the request completes. + */ + load(url: string, data?: string|Object, complete?: (responseText: string, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any): JQuery; + + /** + * Encode a set of form elements as a string for submission. + */ + serialize(): string; + /** + * Encode a set of form elements as an array of names and values. + */ + serializeArray(): JQuerySerializeArrayElement[]; + + /** + * Adds the specified class(es) to each of the set of matched elements. + * + * @param className One or more space-separated classes to be added to the class attribute of each matched element. + */ + addClass(className: string): JQuery; + /** + * Adds the specified class(es) to each of the set of matched elements. + * + * @param function A function returning one or more space-separated class names to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function, this refers to the current element in the set. + */ + addClass(func: (index: number, className: string) => string): JQuery; + + /** + * Add the previous set of elements on the stack to the current set, optionally filtered by a selector. + */ + addBack(selector?: string): JQuery; + + /** + * Get the value of an attribute for the first element in the set of matched elements. + * + * @param attributeName The name of the attribute to get. + */ + attr(attributeName: string): string; + /** + * Set one or more attributes for the set of matched elements. + * + * @param attributeName The name of the attribute to set. + * @param value A value to set for the attribute. + */ + attr(attributeName: string, value: string|number): JQuery; + /** + * Set one or more attributes for the set of matched elements. + * + * @param attributeName The name of the attribute to set. + * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments. + */ + attr(attributeName: string, func: (index: number, attr: string) => string|number): JQuery; + /** + * Set one or more attributes for the set of matched elements. + * + * @param attributes An object of attribute-value pairs to set. + */ + attr(attributes: Object): JQuery; + + /** + * Determine whether any of the matched elements are assigned the given class. + * + * @param className The class name to search for. + */ + hasClass(className: string): boolean; + + /** + * Get the HTML contents of the first element in the set of matched elements. + */ + html(): string; + /** + * Set the HTML contents of each element in the set of matched elements. + * + * @param htmlString A string of HTML to set as the content of each matched element. + */ + html(htmlString: string): JQuery; + /** + * Set the HTML contents of each element in the set of matched elements. + * + * @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. + */ + html(func: (index: number, oldhtml: string) => string): JQuery; + /** + * Set the HTML contents of each element in the set of matched elements. + * + * @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. + */ + + /** + * Get the value of a property for the first element in the set of matched elements. + * + * @param propertyName The name of the property to get. + */ + prop(propertyName: string): any; + /** + * Set one or more properties for the set of matched elements. + * + * @param propertyName The name of the property to set. + * @param value A value to set for the property. + */ + prop(propertyName: string, value: string|number|boolean): JQuery; + /** + * Set one or more properties for the set of matched elements. + * + * @param properties An object of property-value pairs to set. + */ + prop(properties: Object): JQuery; + /** + * Set one or more properties for the set of matched elements. + * + * @param propertyName The name of the property to set. + * @param func A function returning the value to set. Receives the index position of the element in the set and the old property value as arguments. Within the function, the keyword this refers to the current element. + */ + prop(propertyName: string, func: (index: number, oldPropertyValue: any) => any): JQuery; + + /** + * Remove an attribute from each element in the set of matched elements. + * + * @param attributeName An attribute to remove; as of version 1.7, it can be a space-separated list of attributes. + */ + removeAttr(attributeName: string): JQuery; + + /** + * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. + * + * @param className One or more space-separated classes to be removed from the class attribute of each matched element. + */ + removeClass(className?: string): JQuery; + /** + * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. + * + * @param function A function returning one or more space-separated class names to be removed. Receives the index position of the element in the set and the old class value as arguments. + */ + removeClass(func: (index: number, className: string) => string): JQuery; + + /** + * Remove a property for the set of matched elements. + * + * @param propertyName The name of the property to remove. + */ + removeProp(propertyName: string): JQuery; + + /** + * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. + * + * @param className One or more class names (separated by spaces) to be toggled for each element in the matched set. + * @param swtch A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed. + */ + toggleClass(className: string, swtch?: boolean): JQuery; + /** + * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. + * + * @param swtch A boolean value to determine whether the class should be added or removed. + */ + toggleClass(swtch?: boolean): JQuery; + /** + * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. + * + * @param func A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments. + * @param swtch A boolean value to determine whether the class should be added or removed. + */ + toggleClass(func: (index: number, className: string, swtch: boolean) => string, swtch?: boolean): JQuery; + + /** + * Get the current value of the first element in the set of matched elements. + */ + val(): any; + /** + * Set the value of each element in the set of matched elements. + * + * @param value A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked. + */ + val(value: string|string[]): JQuery; + /** + * Set the value of each element in the set of matched elements. + * + * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. + */ + val(func: (index: number, value: string) => string): JQuery; + + + /** + * Get the value of style properties for the first element in the set of matched elements. + * + * @param propertyName A CSS property. + */ + css(propertyName: string): string; + /** + * Set one or more CSS properties for the set of matched elements. + * + * @param propertyName A CSS property name. + * @param value A value to set for the property. + */ + css(propertyName: string, value: string|number): JQuery; + /** + * Set one or more CSS properties for the set of matched elements. + * + * @param propertyName A CSS property name. + * @param value A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. + */ + css(propertyName: string, value: (index: number, value: string) => string|number): JQuery; + /** + * Set one or more CSS properties for the set of matched elements. + * + * @param properties An object of property-value pairs to set. + */ + css(properties: Object): JQuery; + + /** + * Get the current computed height for the first element in the set of matched elements. + */ + height(): number; + /** + * Set the CSS height of every matched element. + * + * @param value An integer representing the number of pixels, or an integer with an optional unit of measure appended (as a string). + */ + height(value: number|string): JQuery; + /** + * Set the CSS height of every matched element. + * + * @param func A function returning the height to set. Receives the index position of the element in the set and the old height as arguments. Within the function, this refers to the current element in the set. + */ + height(func: (index: number, height: number) => number|string): JQuery; + + /** + * Get the current computed height for the first element in the set of matched elements, including padding but not border. + */ + innerHeight(): number; + + /** + * Sets the inner height on elements in the set of matched elements, including padding but not border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + innerHeight(height: number|string): JQuery; + + /** + * Get the current computed width for the first element in the set of matched elements, including padding but not border. + */ + innerWidth(): number; + + /** + * Sets the inner width on elements in the set of matched elements, including padding but not border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + innerWidth(width: number|string): JQuery; + + /** + * Get the current coordinates of the first element in the set of matched elements, relative to the document. + */ + offset(): JQueryCoordinates; + /** + * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. + * + * @param coordinates An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. + */ + offset(coordinates: JQueryCoordinates): JQuery; + /** + * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. + * + * @param func A function to return the coordinates to set. Receives the index of the element in the collection as the first argument and the current coordinates as the second argument. The function should return an object with the new top and left properties. + */ + offset(func: (index: number, coords: JQueryCoordinates) => JQueryCoordinates): JQuery; + + /** + * Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin. Returns an integer (without "px") representation of the value or null if called on an empty set of elements. + * + * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. + */ + outerHeight(includeMargin?: boolean): number; + + /** + * Sets the outer height on elements in the set of matched elements, including padding and border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + outerHeight(height: number|string): JQuery; + + /** + * Get the current computed width for the first element in the set of matched elements, including padding and border. + * + * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. + */ + outerWidth(includeMargin?: boolean): number; + + /** + * Sets the outer width on elements in the set of matched elements, including padding and border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + outerWidth(width: number|string): JQuery; + + /** + * Get the current coordinates of the first element in the set of matched elements, relative to the offset parent. + */ + position(): JQueryCoordinates; + + /** + * Get the current horizontal position of the scroll bar for the first element in the set of matched elements or set the horizontal position of the scroll bar for every matched element. + */ + scrollLeft(): number; + /** + * Set the current horizontal position of the scroll bar for each of the set of matched elements. + * + * @param value An integer indicating the new position to set the scroll bar to. + */ + scrollLeft(value: number): JQuery; + + /** + * Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element. + */ + scrollTop(): number; + /** + * Set the current vertical position of the scroll bar for each of the set of matched elements. + * + * @param value An integer indicating the new position to set the scroll bar to. + */ + scrollTop(value: number): JQuery; + + /** + * Get the current computed width for the first element in the set of matched elements. + */ + width(): number; + /** + * Set the CSS width of each element in the set of matched elements. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + width(value: number|string): JQuery; + /** + * Set the CSS width of each element in the set of matched elements. + * + * @param func A function returning the width to set. Receives the index position of the element in the set and the old width as arguments. Within the function, this refers to the current element in the set. + */ + width(func: (index: number, width: number) => number|string): JQuery; + + /** + * Remove from the queue all items that have not yet been run. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + clearQueue(queueName?: string): JQuery; + + /** + * Store arbitrary data associated with the matched elements. + * + * @param key A string naming the piece of data to set. + * @param value The new data value; it can be any Javascript type including Array or Object. + */ + data(key: string, value: any): JQuery; + /** + * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. + * + * @param key Name of the data stored. + */ + data(key: string): any; + /** + * Store arbitrary data associated with the matched elements. + * + * @param obj An object of key-value pairs of data to update. + */ + data(obj: { [key: string]: any; }): JQuery; + /** + * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. + */ + data(): any; + + /** + * Execute the next function on the queue for the matched elements. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + dequeue(queueName?: string): JQuery; + + /** + * Remove a previously-stored piece of data. + * + * @param name A string naming the piece of data to delete or space-separated string naming the pieces of data to delete. + */ + removeData(name: string): JQuery; + /** + * Remove a previously-stored piece of data. + * + * @param list An array of strings naming the pieces of data to delete. + */ + removeData(list: string[]): JQuery; + + /** + * Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished. + * + * @param type The type of queue that needs to be observed. (default: fx) + * @param target Object onto which the promise methods have to be attached + */ + promise(type?: string, target?: Object): JQueryPromise; + + /** + * Perform a custom animation of a set of CSS properties. + * + * @param properties An object of CSS properties and values that the animation will move toward. + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + animate(properties: Object, duration?: string|number, complete?: Function): JQuery; + /** + * Perform a custom animation of a set of CSS properties. + * + * @param properties An object of CSS properties and values that the animation will move toward. + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. (default: swing) + * @param complete A function to call once the animation is complete. + */ + animate(properties: Object, duration?: string|number, easing?: string, complete?: Function): JQuery; + /** + * Perform a custom animation of a set of CSS properties. + * + * @param properties An object of CSS properties and values that the animation will move toward. + * @param options A map of additional options to pass to the method. + */ + animate(properties: Object, options: JQueryAnimationOptions): JQuery; + + /** + * Set a timer to delay execution of subsequent items in the queue. + * + * @param duration An integer indicating the number of milliseconds to delay execution of the next item in the queue. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + delay(duration: number, queueName?: string): JQuery; + + /** + * Display the matched elements by fading them to opaque. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + fadeIn(duration?: number|string, complete?: Function): JQuery; + /** + * Display the matched elements by fading them to opaque. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeIn(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display the matched elements by fading them to opaque. + * + * @param options A map of additional options to pass to the method. + */ + fadeIn(options: JQueryAnimationOptions): JQuery; + + /** + * Hide the matched elements by fading them to transparent. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + fadeOut(duration?: number|string, complete?: Function): JQuery; + /** + * Hide the matched elements by fading them to transparent. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeOut(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Hide the matched elements by fading them to transparent. + * + * @param options A map of additional options to pass to the method. + */ + fadeOut(options: JQueryAnimationOptions): JQuery; + + /** + * Adjust the opacity of the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param opacity A number between 0 and 1 denoting the target opacity. + * @param complete A function to call once the animation is complete. + */ + fadeTo(duration: string|number, opacity: number, complete?: Function): JQuery; + /** + * Adjust the opacity of the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param opacity A number between 0 and 1 denoting the target opacity. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeTo(duration: string|number, opacity: number, easing?: string, complete?: Function): JQuery; + + /** + * Display or hide the matched elements by animating their opacity. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + fadeToggle(duration?: number|string, complete?: Function): JQuery; + /** + * Display or hide the matched elements by animating their opacity. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeToggle(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display or hide the matched elements by animating their opacity. + * + * @param options A map of additional options to pass to the method. + */ + fadeToggle(options: JQueryAnimationOptions): JQuery; + + /** + * Stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements. + * + * @param queue The name of the queue in which to stop animations. + */ + finish(queue?: string): JQuery; + + /** + * Hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + hide(duration?: number|string, complete?: Function): JQuery; + /** + * Hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + hide(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Hide the matched elements. + * + * @param options A map of additional options to pass to the method. + */ + hide(options: JQueryAnimationOptions): JQuery; + + /** + * Display the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + show(duration?: number|string, complete?: Function): JQuery; + /** + * Display the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + show(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display the matched elements. + * + * @param options A map of additional options to pass to the method. + */ + show(options: JQueryAnimationOptions): JQuery; + + /** + * Display the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + slideDown(duration?: number|string, complete?: Function): JQuery; + /** + * Display the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + slideDown(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display the matched elements with a sliding motion. + * + * @param options A map of additional options to pass to the method. + */ + slideDown(options: JQueryAnimationOptions): JQuery; + + /** + * Display or hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + slideToggle(duration?: number|string, complete?: Function): JQuery; + /** + * Display or hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + slideToggle(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display or hide the matched elements with a sliding motion. + * + * @param options A map of additional options to pass to the method. + */ + slideToggle(options: JQueryAnimationOptions): JQuery; + + /** + * Hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + slideUp(duration?: number|string, complete?: Function): JQuery; + /** + * Hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + slideUp(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Hide the matched elements with a sliding motion. + * + * @param options A map of additional options to pass to the method. + */ + slideUp(options: JQueryAnimationOptions): JQuery; + + /** + * Stop the currently-running animation on the matched elements. + * + * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. + * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. + */ + stop(clearQueue?: boolean, jumpToEnd?: boolean): JQuery; + /** + * Stop the currently-running animation on the matched elements. + * + * @param queue The name of the queue in which to stop animations. + * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. + * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. + */ + stop(queue?: string, clearQueue?: boolean, jumpToEnd?: boolean): JQuery; + + /** + * Display or hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + toggle(duration?: number|string, complete?: Function): JQuery; + /** + * Display or hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + toggle(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display or hide the matched elements. + * + * @param options A map of additional options to pass to the method. + */ + toggle(options: JQueryAnimationOptions): JQuery; + /** + * Display or hide the matched elements. + * + * @param showOrHide A Boolean indicating whether to show or hide the elements. + */ + toggle(showOrHide: boolean): JQuery; + + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + bind(eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param handler A function to execute each time the event is triggered. + */ + bind(eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param eventData An object containing data that will be passed to the event handler. + * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. + */ + bind(eventType: string, eventData: any, preventBubble: boolean): JQuery; + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. + */ + bind(eventType: string, preventBubble: boolean): JQuery; + /** + * Attach a handler to an event for the elements. + * + * @param events An object containing one or more DOM event types and functions to execute for them. + */ + bind(events: any): JQuery; + + /** + * Trigger the "blur" event on an element + */ + blur(): JQuery; + /** + * Bind an event handler to the "blur" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + blur(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "blur" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + blur(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "change" event on an element. + */ + change(): JQuery; + /** + * Bind an event handler to the "change" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + change(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "change" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + change(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "click" event on an element. + */ + click(): JQuery; + /** + * Bind an event handler to the "click" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + */ + click(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "click" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + click(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "dblclick" event on an element. + */ + dblclick(): JQuery; + /** + * Bind an event handler to the "dblclick" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + dblclick(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "dblclick" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + dblclick(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + delegate(selector: any, eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + delegate(selector: any, eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "focus" event on an element. + */ + focus(): JQuery; + /** + * Bind an event handler to the "focus" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + focus(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "focus" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + focus(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Bind an event handler to the "focusin" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + focusin(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "focusin" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + focusin(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Bind an event handler to the "focusout" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + focusout(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "focusout" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + focusout(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. + * + * @param handlerIn A function to execute when the mouse pointer enters the element. + * @param handlerOut A function to execute when the mouse pointer leaves the element. + */ + hover(handlerIn: (eventObject: JQueryEventObject) => any, handlerOut: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. + * + * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element. + */ + hover(handlerInOut: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "keydown" event on an element. + */ + keydown(): JQuery; + /** + * Bind an event handler to the "keydown" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + keydown(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; + /** + * Bind an event handler to the "keydown" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + keydown(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; + + /** + * Trigger the "keypress" event on an element. + */ + keypress(): JQuery; + /** + * Bind an event handler to the "keypress" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + keypress(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; + /** + * Bind an event handler to the "keypress" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + keypress(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; + + /** + * Trigger the "keyup" event on an element. + */ + keyup(): JQuery; + /** + * Bind an event handler to the "keyup" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + keyup(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; + /** + * Bind an event handler to the "keyup" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + keyup(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; + + /** + * Bind an event handler to the "load" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + load(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "load" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + load(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "mousedown" event on an element. + */ + mousedown(): JQuery; + /** + * Bind an event handler to the "mousedown" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mousedown(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "mousedown" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mousedown(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mouseenter" event on an element. + */ + mouseenter(): JQuery; + /** + * Bind an event handler to be fired when the mouse enters an element. + * + * @param handler A function to execute when the event is triggered. + */ + mouseenter(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to be fired when the mouse enters an element. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseenter(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mouseleave" event on an element. + */ + mouseleave(): JQuery; + /** + * Bind an event handler to be fired when the mouse leaves an element. + * + * @param handler A function to execute when the event is triggered. + */ + mouseleave(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to be fired when the mouse leaves an element. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseleave(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mousemove" event on an element. + */ + mousemove(): JQuery; + /** + * Bind an event handler to the "mousemove" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mousemove(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "mousemove" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mousemove(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mouseout" event on an element. + */ + mouseout(): JQuery; + /** + * Bind an event handler to the "mouseout" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mouseout(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "mouseout" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseout(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mouseover" event on an element. + */ + mouseover(): JQuery; + /** + * Bind an event handler to the "mouseover" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mouseover(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "mouseover" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseover(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mouseup" event on an element. + */ + mouseup(): JQuery; + /** + * Bind an event handler to the "mouseup" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mouseup(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "mouseup" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseup(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Remove an event handler. + */ + off(): JQuery; + /** + * Remove an event handler. + * + * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". + * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: string, selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Remove an event handler. + * + * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Remove an event handler. + * + * @param events An object where the string keys represent one or more space-separated event types and optional namespaces, and the values represent handler functions previously attached for the event(s). + * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. + */ + off(events: { [key: string]: any; }, selector?: string): JQuery; + + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: string, data : any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: string, selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + on(events: { [key: string]: any; }, selector?: string, data?: any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + on(events: { [key: string]: any; }, data?: any): JQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. + * @param handler A function to execute at the time the event is triggered. + */ + one(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. + * @param data An object containing data that will be passed to the event handler. + * @param handler A function to execute at the time the event is triggered. + */ + one(events: string, data: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + one(events: string, selector: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + one(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + one(events: { [key: string]: any; }, selector?: string, data?: any): JQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + one(events: { [key: string]: any; }, data?: any): JQuery; + + + /** + * Specify a function to execute when the DOM is fully loaded. + * + * @param handler A function to execute after the DOM is ready. + */ + ready(handler: (jQueryAlias?: JQueryStatic) => any): JQuery; + + /** + * Trigger the "resize" event on an element. + */ + resize(): JQuery; + /** + * Bind an event handler to the "resize" JavaScript event. + * + * @param handler A function to execute each time the event is triggered. + */ + resize(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "resize" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + resize(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "scroll" event on an element. + */ + scroll(): JQuery; + /** + * Bind an event handler to the "scroll" JavaScript event. + * + * @param handler A function to execute each time the event is triggered. + */ + scroll(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "scroll" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + scroll(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "select" event on an element. + */ + select(): JQuery; + /** + * Bind an event handler to the "select" JavaScript event. + * + * @param handler A function to execute each time the event is triggered. + */ + select(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "select" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + select(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "submit" event on an element. + */ + submit(): JQuery; + /** + * Bind an event handler to the "submit" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + submit(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "submit" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + submit(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Execute all handlers and behaviors attached to the matched elements for the given event type. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param extraParameters Additional parameters to pass along to the event handler. + */ + trigger(eventType: string, extraParameters?: any[]|Object): JQuery; + /** + * Execute all handlers and behaviors attached to the matched elements for the given event type. + * + * @param event A jQuery.Event object. + * @param extraParameters Additional parameters to pass along to the event handler. + */ + trigger(event: JQueryEventObject, extraParameters?: any[]|Object): JQuery; + + /** + * Execute all handlers attached to an element for an event. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param extraParameters An array of additional parameters to pass along to the event handler. + */ + triggerHandler(eventType: string, ...extraParameters: any[]): Object; + + /** + * Execute all handlers attached to an element for an event. + * + * @param event A jQuery.Event object. + * @param extraParameters An array of additional parameters to pass along to the event handler. + */ + triggerHandler(event: JQueryEventObject, ...extraParameters: any[]): Object; + + /** + * Remove a previously-attached event handler from the elements. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param handler The function that is to be no longer executed. + */ + unbind(eventType?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Remove a previously-attached event handler from the elements. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param fls Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ). + */ + unbind(eventType: string, fls: boolean): JQuery; + /** + * Remove a previously-attached event handler from the elements. + * + * @param evt A JavaScript event object as passed to an event handler. + */ + unbind(evt: any): JQuery; + + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + */ + undelegate(): JQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param selector A selector which will be used to filter the event results. + * @param eventType A string containing a JavaScript event type, such as "click" or "keydown" + * @param handler A function to execute at the time the event is triggered. + */ + undelegate(selector: string, eventType: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param selector A selector which will be used to filter the event results. + * @param events An object of one or more event types and previously bound functions to unbind from them. + */ + undelegate(selector: string, events: Object): JQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param namespace A string containing a namespace to unbind all events from. + */ + undelegate(namespace: string): JQuery; + + /** + * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) + * + * @param handler A function to execute when the event is triggered. + */ + unload(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) + * + * @param eventData A plain object of data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + unload(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document. (DEPRECATED from v1.10) + */ + context: Element; + + jquery: string; + + /** + * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) + * + * @param handler A function to execute when the event is triggered. + */ + error(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) + * + * @param eventData A plain object of data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + error(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Add a collection of DOM elements onto the jQuery stack. + * + * @param elements An array of elements to push onto the stack and make into a new jQuery object. + */ + pushStack(elements: any[]): JQuery; + /** + * Add a collection of DOM elements onto the jQuery stack. + * + * @param elements An array of elements to push onto the stack and make into a new jQuery object. + * @param name The name of a jQuery method that generated the array of elements. + * @param arguments The arguments that were passed in to the jQuery method (for serialization). + */ + pushStack(elements: any[], name: string, arguments: any[]): JQuery; + + /** + * Insert content, specified by the parameter, after each element in the set of matched elements. + * + * param content1 HTML string, DOM element, array of elements, or jQuery object to insert after each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements. + */ + after(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, after each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert after each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + after(func: (index: number, html: string) => string|Element|JQuery): JQuery; + + /** + * Insert content, specified by the parameter, to the end of each element in the set of matched elements. + * + * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements. + */ + append(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, to the end of each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. + */ + append(func: (index: number, html: string) => string|Element|JQuery): JQuery; + + /** + * Insert every element in the set of matched elements to the end of the target. + * + * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter. + */ + appendTo(target: JQuery|any[]|Element|string): JQuery; + + /** + * Insert content, specified by the parameter, before each element in the set of matched elements. + * + * param content1 HTML string, DOM element, array of elements, or jQuery object to insert before each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements. + */ + before(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, before each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert before each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + before(func: (index: number, html: string) => string|Element|JQuery): JQuery; + + /** + * Create a deep copy of the set of matched elements. + * + * param withDataAndEvents A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false. + * param deepWithDataAndEvents A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false). + */ + clone(withDataAndEvents?: boolean, deepWithDataAndEvents?: boolean): JQuery; + + /** + * Remove the set of matched elements from the DOM. + * + * param selector A selector expression that filters the set of matched elements to be removed. + */ + detach(selector?: string): JQuery; + + /** + * Remove all child nodes of the set of matched elements from the DOM. + */ + empty(): JQuery; + + /** + * Insert every element in the set of matched elements after the target. + * + * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter. + */ + insertAfter(target: JQuery|any[]|Element|Text|string): JQuery; + + /** + * Insert every element in the set of matched elements before the target. + * + * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter. + */ + insertBefore(target: JQuery|any[]|Element|Text|string): JQuery; + + /** + * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. + * + * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements. + */ + prepend(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the beginning of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. + */ + prepend(func: (index: number, html: string) => string|Element|JQuery): JQuery; + + /** + * Insert every element in the set of matched elements to the beginning of the target. + * + * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter. + */ + prependTo(target: JQuery|any[]|Element|string): JQuery; + + /** + * Remove the set of matched elements from the DOM. + * + * @param selector A selector expression that filters the set of matched elements to be removed. + */ + remove(selector?: string): JQuery; + + /** + * Replace each target element with the set of matched elements. + * + * @param target A selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace. + */ + replaceAll(target: JQuery|any[]|Element|string): JQuery; + + /** + * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. + * + * param newContent The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object. + */ + replaceWith(newContent: JQuery|any[]|Element|Text|string): JQuery; + /** + * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. + * + * param func A function that returns content with which to replace the set of matched elements. + */ + replaceWith(func: () => Element|JQuery): JQuery; + + /** + * Get the combined text contents of each element in the set of matched elements, including their descendants. + */ + text(): string; + /** + * Set the content of each element in the set of matched elements to the specified text. + * + * @param text The text to set as the content of each matched element. When Number or Boolean is supplied, it will be converted to a String representation. + */ + text(text: string|number|boolean): JQuery; + /** + * Set the content of each element in the set of matched elements to the specified text. + * + * @param func A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments. + */ + text(func: (index: number, text: string) => string): JQuery; + + /** + * Retrieve all the elements contained in the jQuery set, as an array. + */ + toArray(): any[]; + + /** + * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. + */ + unwrap(): JQuery; + + /** + * Wrap an HTML structure around each element in the set of matched elements. + * + * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. + */ + wrap(wrappingElement: JQuery|Element|string): JQuery; + /** + * Wrap an HTML structure around each element in the set of matched elements. + * + * @param func A callback function returning the HTML content or jQuery object to wrap around the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + wrap(func: (index: number) => string|JQuery): JQuery; + + /** + * Wrap an HTML structure around all elements in the set of matched elements. + * + * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. + */ + wrapAll(wrappingElement: JQuery|Element|string): JQuery; + wrapAll(func: (index: number) => string): JQuery; + + /** + * Wrap an HTML structure around the content of each element in the set of matched elements. + * + * @param wrappingElement An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements. + */ + wrapInner(wrappingElement: JQuery|Element|string): JQuery; + /** + * Wrap an HTML structure around the content of each element in the set of matched elements. + * + * @param func A callback function which generates a structure to wrap around the content of the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + wrapInner(func: (index: number) => string): JQuery; + + /** + * Iterate over a jQuery object, executing a function for each matched element. + * + * @param func A function to execute for each matched element. + */ + each(func: (index: number, elem: Element) => any): JQuery; + + /** + * Retrieve one of the elements matched by the jQuery object. + * + * @param index A zero-based integer indicating which element to retrieve. + */ + get(index: number): HTMLElement; + /** + * Retrieve the elements matched by the jQuery object. + */ + get(): any[]; + + /** + * Search for a given element from among the matched elements. + */ + index(): number; + /** + * Search for a given element from among the matched elements. + * + * @param selector A selector representing a jQuery collection in which to look for an element. + */ + index(selector: string|JQuery|Element): number; + + /** + * The number of elements in the jQuery object. + */ + length: number; + /** + * A selector representing selector passed to jQuery(), if any, when creating the original set. + * version deprecated: 1.7, removed: 1.9 + */ + selector: string; + [index: string]: any; + [index: number]: HTMLElement; + + /** + * Add elements to the set of matched elements. + * + * @param selector A string representing a selector expression to find additional elements to add to the set of matched elements. + * @param context The point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method. + */ + add(selector: string, context?: Element): JQuery; + /** + * Add elements to the set of matched elements. + * + * @param elements One or more elements to add to the set of matched elements. + */ + add(...elements: Element[]): JQuery; + /** + * Add elements to the set of matched elements. + * + * @param html An HTML fragment to add to the set of matched elements. + */ + add(html: string): JQuery; + /** + * Add elements to the set of matched elements. + * + * @param obj An existing jQuery object to add to the set of matched elements. + */ + add(obj: JQuery): JQuery; + + /** + * Get the children of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + children(selector?: string): JQuery; + + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param selector A string containing a selector expression to match elements against. + */ + closest(selector: string): JQuery; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param selector A string containing a selector expression to match elements against. + * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. + */ + closest(selector: string, context?: Element): JQuery; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param obj A jQuery object to match elements against. + */ + closest(obj: JQuery): JQuery; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param element An element to match elements against. + */ + closest(element: Element): JQuery; + + /** + * Get an array of all the elements and selectors matched against the current element up through the DOM tree. + * + * @param selectors An array or string containing a selector expression to match elements against (can also be a jQuery object). + * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. + */ + closest(selectors: any, context?: Element): any[]; + + /** + * Get the children of each element in the set of matched elements, including text and comment nodes. + */ + contents(): JQuery; + + /** + * End the most recent filtering operation in the current chain and return the set of matched elements to its previous state. + */ + end(): JQuery; + + /** + * Reduce the set of matched elements to the one at the specified index. + * + * @param index An integer indicating the 0-based position of the element. OR An integer indicating the position of the element, counting backwards from the last element in the set. + * + */ + eq(index: number): JQuery; + + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param selector A string containing a selector expression to match the current set of elements against. + */ + filter(selector: string): JQuery; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param func A function used as a test for each element in the set. this is the current DOM element. + */ + filter(func: (index: number, element: Element) => any): JQuery; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param element An element to match the current set of elements against. + */ + filter(element: Element): JQuery; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param obj An existing jQuery object to match the current set of elements against. + */ + filter(obj: JQuery): JQuery; + + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. + * + * @param selector A string containing a selector expression to match elements against. + */ + find(selector: string): JQuery; + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. + * + * @param element An element to match elements against. + */ + find(element: Element): JQuery; + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. + * + * @param obj A jQuery object to match elements against. + */ + find(obj: JQuery): JQuery; + + /** + * Reduce the set of matched elements to the first in the set. + */ + first(): JQuery; + + /** + * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. + * + * @param selector A string containing a selector expression to match elements against. + */ + has(selector: string): JQuery; + /** + * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. + * + * @param contained A DOM element to match elements against. + */ + has(contained: Element): JQuery; + + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param selector A string containing a selector expression to match elements against. + */ + is(selector: string): boolean; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param func A function used as a test for the set of elements. It accepts one argument, index, which is the element's index in the jQuery collection.Within the function, this refers to the current DOM element. + */ + is(func: (index: number, element: Element) => boolean): boolean; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param obj An existing jQuery object to match the current set of elements against. + */ + is(obj: JQuery): boolean; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param elements One or more elements to match the current set of elements against. + */ + is(elements: any): boolean; + + /** + * Reduce the set of matched elements to the final one in the set. + */ + last(): JQuery; + + /** + * Pass each element in the current matched set through a function, producing a new jQuery object containing the return values. + * + * @param callback A function object that will be invoked for each element in the current set. + */ + map(callback: (index: number, domElement: Element) => any): JQuery; + + /** + * Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + next(selector?: string): JQuery; + + /** + * Get all following siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + nextAll(selector?: string): JQuery; + + /** + * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. + * + * @param selector A string containing a selector expression to indicate where to stop matching following sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + nextUntil(selector?: string, filter?: string): JQuery; + /** + * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. + * + * @param element A DOM node or jQuery object indicating where to stop matching following sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + nextUntil(element?: Element, filter?: string): JQuery; + /** + * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. + * + * @param obj A DOM node or jQuery object indicating where to stop matching following sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + nextUntil(obj?: JQuery, filter?: string): JQuery; + + /** + * Remove elements from the set of matched elements. + * + * @param selector A string containing a selector expression to match elements against. + */ + not(selector: string): JQuery; + /** + * Remove elements from the set of matched elements. + * + * @param func A function used as a test for each element in the set. this is the current DOM element. + */ + not(func: (index: number, element: Element) => boolean): JQuery; + /** + * Remove elements from the set of matched elements. + * + * @param elements One or more DOM elements to remove from the matched set. + */ + not(...elements: Element[]): JQuery; + /** + * Remove elements from the set of matched elements. + * + * @param obj An existing jQuery object to match the current set of elements against. + */ + not(obj: JQuery): JQuery; + + /** + * Get the closest ancestor element that is positioned. + */ + offsetParent(): JQuery; + + /** + * Get the parent of each element in the current set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + parent(selector?: string): JQuery; + + /** + * Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + parents(selector?: string): JQuery; + + /** + * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param selector A string containing a selector expression to indicate where to stop matching ancestor elements. + * @param filter A string containing a selector expression to match elements against. + */ + parentsUntil(selector?: string, filter?: string): JQuery; + /** + * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param element A DOM node or jQuery object indicating where to stop matching ancestor elements. + * @param filter A string containing a selector expression to match elements against. + */ + parentsUntil(element?: Element, filter?: string): JQuery; + /** + * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param obj A DOM node or jQuery object indicating where to stop matching ancestor elements. + * @param filter A string containing a selector expression to match elements against. + */ + parentsUntil(obj?: JQuery, filter?: string): JQuery; + + /** + * Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + prev(selector?: string): JQuery; + + /** + * Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + prevAll(selector?: string): JQuery; + + /** + * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param selector A string containing a selector expression to indicate where to stop matching preceding sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + prevUntil(selector?: string, filter?: string): JQuery; + /** + * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param element A DOM node or jQuery object indicating where to stop matching preceding sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + prevUntil(element?: Element, filter?: string): JQuery; + /** + * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param obj A DOM node or jQuery object indicating where to stop matching preceding sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + prevUntil(obj?: JQuery, filter?: string): JQuery; + + /** + * Get the siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + siblings(selector?: string): JQuery; + + /** + * Reduce the set of matched elements to a subset specified by a range of indices. + * + * @param start An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set. + * @param end An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set. + */ + slice(start: number, end?: number): JQuery; + + /** + * Show the queue of functions to be executed on the matched elements. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + queue(queueName?: string): any[]; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param newQueue An array of functions to replace the current queue contents. + */ + queue(newQueue: Function[]): JQuery; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. + */ + queue(callback: Function): JQuery; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param newQueue An array of functions to replace the current queue contents. + */ + queue(queueName: string, newQueue: Function[]): JQuery; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. + */ + queue(queueName: string, callback: Function): JQuery; +} +declare module "jquery" { + export = $; +} +declare var jQuery: JQueryStatic; +declare var $: JQueryStatic; diff --git a/warship/jqueryui.d.ts b/warship/jqueryui.d.ts index 0823569..9295938 100644 --- a/warship/jqueryui.d.ts +++ b/warship/jqueryui.d.ts @@ -1,92 +1,92 @@ -/// - -// Partial typing for the jQueryUI library, version 1.8.x - -interface DraggableEventUIParam { - helper: JQuery; - position: { top: number; left: number;}; - offset: { top: number; left: number;}; -} - -interface DraggableEvent { - (event: Event, ui: DraggableEventUIParam): void; -} - -interface Draggable { - // Options - disabled?: boolean; - addClasses?: boolean; - appendTo?: any; - axis?: string; - cancel?: string; - connectToSortable?: string; - containment?: any; - cursor?: string; - cursorAt?: any; - delay?: number; - distance?: number; - grid?: number[]; - handle?: any; - helper?: any; - iframeFix?: any; - opacity?: number; - refreshPositions?: boolean; - revert?: any; - revertDuration?: number; - scope?: string; - scroll?: boolean; - scrollSensitivity?: number; - scrollSpeed?: number; - snap?: any; - snapMode?: string; - snapTolerance?: number; - stack?: string; - zIndex?: number; - // Events - create?: DraggableEvent; - start?: DraggableEvent; - drag?: DraggableEvent; - stop?: DraggableEvent; -} - -interface DroppableEventUIParam { - draggable: JQuery; - helper: JQuery; - position: { top: number; left: number;}; - offset: { top: number; left: number;}; -} - -interface DroppableEvent { - (event: Event, ui: DroppableEventUIParam): void; -} - -interface Droppable { - // Options - disabled?: boolean; - accept?: any; - activeClass?: string; - greedy?: boolean; - hoverClass?: string; - scope?: string; - tolerance?: string; - // Events - create?: DroppableEvent; - activate?: DroppableEvent; - deactivate?: DroppableEvent; - over?: DroppableEvent; - out?: DroppableEvent; - drop?: DroppableEvent; -} - -interface JQuery { - draggable(options: Draggable): JQuery; - draggable(optionLiteral: string, options: Draggable): JQuery; - draggable(optionLiteral: string, optionName: string, optionValue: any): JQuery; - draggable(optionLiteral: string, optionName: string): any; - // draggable(methodName: string): any; - droppable(options: Droppable): JQuery; - droppable(optionLiteral: string, options: Draggable): JQuery; - droppable(optionLiteral: string, optionName: string, optionValue: any): JQuery; - droppable(optionLiteral: string, optionName: string): any; - droppable(methodName: string): any; -} +/// + +// Partial typing for the jQueryUI library, version 1.8.x + +interface DraggableEventUIParam { + helper: JQuery; + position: { top: number; left: number;}; + offset: { top: number; left: number;}; +} + +interface DraggableEvent { + (event: Event, ui: DraggableEventUIParam): void; +} + +interface Draggable { + // Options + disabled?: boolean; + addClasses?: boolean; + appendTo?: any; + axis?: string; + cancel?: string; + connectToSortable?: string; + containment?: any; + cursor?: string; + cursorAt?: any; + delay?: number; + distance?: number; + grid?: number[]; + handle?: any; + helper?: any; + iframeFix?: any; + opacity?: number; + refreshPositions?: boolean; + revert?: any; + revertDuration?: number; + scope?: string; + scroll?: boolean; + scrollSensitivity?: number; + scrollSpeed?: number; + snap?: any; + snapMode?: string; + snapTolerance?: number; + stack?: string; + zIndex?: number; + // Events + create?: DraggableEvent; + start?: DraggableEvent; + drag?: DraggableEvent; + stop?: DraggableEvent; +} + +interface DroppableEventUIParam { + draggable: JQuery; + helper: JQuery; + position: { top: number; left: number;}; + offset: { top: number; left: number;}; +} + +interface DroppableEvent { + (event: Event, ui: DroppableEventUIParam): void; +} + +interface Droppable { + // Options + disabled?: boolean; + accept?: any; + activeClass?: string; + greedy?: boolean; + hoverClass?: string; + scope?: string; + tolerance?: string; + // Events + create?: DroppableEvent; + activate?: DroppableEvent; + deactivate?: DroppableEvent; + over?: DroppableEvent; + out?: DroppableEvent; + drop?: DroppableEvent; +} + +interface JQuery { + draggable(options: Draggable): JQuery; + draggable(optionLiteral: string, options: Draggable): JQuery; + draggable(optionLiteral: string, optionName: string, optionValue: any): JQuery; + draggable(optionLiteral: string, optionName: string): any; + // draggable(methodName: string): any; + droppable(options: Droppable): JQuery; + droppable(optionLiteral: string, options: Draggable): JQuery; + droppable(optionLiteral: string, optionName: string, optionValue: any): JQuery; + droppable(optionLiteral: string, optionName: string): any; + droppable(methodName: string): any; +} diff --git a/warship/styles.css b/warship/styles.css index 3a31b44..a43a269 100644 --- a/warship/styles.css +++ b/warship/styles.css @@ -1,111 +1,111 @@ -html -{ - width: 100%; - height: 100%; - -ms-content-zooming: none; - margin: 0px; - border: 0px; - padding: 0px; -} -body { - font-family: Verdana; - width: 100%; - height: 100%; - /*background-color: #b5caae;*/ - background: url('img/bg2.jpg'); - margin: 0px; - border: 0px; - padding: 0px; - min-height: 480px; - min-width: 640px; -} -#header { - width: 100%; - height: 25%; -} -#boards { - width: 100%; - height: 75%; -} -.quadrant -{ - display: inline-block; - box-sizing: border-box; - -moz-box-sizing: border-box; - width: 40%; - margin: 2%; - vertical-align: top; -} -#banner { - font-size: 40pt; - font-weight: 800; - font-style: italic; - color: white; - text-shadow: -1px 0 black, 0 2px black, 1px 0 black, 0 -1px black; - height: 100px; -} -#status -{ - width: 80%; - border: 1px dotted gray; - padding: 1%; - background-color: #CCCCCC; - height: 80%; -} -.board { - background-color: #111111; - border: 2px groove black; - height: 80%; - padding: 0%; - position: relative; -} -.cell { - box-sizing: border-box; - -moz-box-sizing: border-box; - float: left; - height: 10%; - width: 10%; - border: 1px dotted #A0A0FF; - margin: 0px; - padding: 0px; - position: relative; -} - -.notBombed { - opacity: 0.2; - background: url('img/bg.jpg') repeat; - /*background-color: black;*/ - z-index: 0; -} - -.cellHit { - opacity: 0.5; - background-color: #C00000; - z-index: 2; -} - -.cellMiss{ - opacity: 0.5; - background-color: #008000; - z-index: 2; -} - -.ship { - position: absolute; - box-sizing: border-box; - -moz-box-sizing: border-box; - margin: 0%; - padding: 0%; - width: 10%; - height: 10%; - border-radius: 20%; - /*background-color: #FFFF80;*/ - background: #666666; - border: 2px solid black; - z-index: 1; - -ms-touch-action: none; -} - -.dropTarget { - background-color: white; -} +html +{ + width: 100%; + height: 100%; + -ms-content-zooming: none; + margin: 0px; + border: 0px; + padding: 0px; +} +body { + font-family: Verdana; + width: 100%; + height: 100%; + /*background-color: #b5caae;*/ + background: url('img/bg2.jpg'); + margin: 0px; + border: 0px; + padding: 0px; + min-height: 480px; + min-width: 640px; +} +#header { + width: 100%; + height: 25%; +} +#boards { + width: 100%; + height: 75%; +} +.quadrant +{ + display: inline-block; + box-sizing: border-box; + -moz-box-sizing: border-box; + width: 40%; + margin: 2%; + vertical-align: top; +} +#banner { + font-size: 40pt; + font-weight: 800; + font-style: italic; + color: white; + text-shadow: -1px 0 black, 0 2px black, 1px 0 black, 0 -1px black; + height: 100px; +} +#status +{ + width: 80%; + border: 1px dotted gray; + padding: 1%; + background-color: #CCCCCC; + height: 80%; +} +.board { + background-color: #111111; + border: 2px groove black; + height: 80%; + padding: 0%; + position: relative; +} +.cell { + box-sizing: border-box; + -moz-box-sizing: border-box; + float: left; + height: 10%; + width: 10%; + border: 1px dotted #A0A0FF; + margin: 0px; + padding: 0px; + position: relative; +} + +.notBombed { + opacity: 0.2; + background: url('img/bg.jpg') repeat; + /*background-color: black;*/ + z-index: 0; +} + +.cellHit { + opacity: 0.5; + background-color: #C00000; + z-index: 2; +} + +.cellMiss{ + opacity: 0.5; + background-color: #008000; + z-index: 2; +} + +.ship { + position: absolute; + box-sizing: border-box; + -moz-box-sizing: border-box; + margin: 0%; + padding: 0%; + width: 10%; + height: 10%; + border-radius: 20%; + /*background-color: #FFFF80;*/ + background: #666666; + border: 2px solid black; + z-index: 1; + -ms-touch-action: none; +} + +.dropTarget { + background-color: white; +} diff --git a/warship/tsconfig.json b/warship/tsconfig.json new file mode 100644 index 0000000..7b0924e --- /dev/null +++ b/warship/tsconfig.json @@ -0,0 +1,6 @@ +{ + "compilerOptions": { + "target": "es5", + "sourceMap": true + } +} \ No newline at end of file diff --git a/warship/warship.ts b/warship/warship.ts index 5488af6..1988500 100644 --- a/warship/warship.ts +++ b/warship/warship.ts @@ -1,392 +1,392 @@ -/// -/// - -class Cell { - shipIndex: number; - hasHit: boolean; - element: HTMLElement; - - constructor(public row: number, public column: number) { - this.element = $("
      ")[0]; - } - - // Parse a cell location of the format "row,column" - static parseCellLocation(pos: string) { - var indices: string[] = pos.split(","); - return { 'row': parseInt(indices[0]), 'column': parseInt(indices[1]) }; - } - - // Return the cell location of the format "row,column" - cellLocation() { - return "" + this.row + "," + this.column; - } -} - -class Ship { - column = 0; - row = 0; - isVertical = true; - hits = 0; - element: HTMLElement; - - constructor(public size: number) { - this.element = $("
      ")[0]; - } - - updatePosition(row: number, column: number, vertical: boolean) { - this.row = row; - this.column = column; - this.isVertical = vertical; - this.updateLayout(); - } - - updateLayout() { - var width = "9.9%"; - var height = "" + (this.size * 9.9) + "%"; - this.element.style.left = "" + (this.column * 10) + "%"; - this.element.style.top = "" + (this.row * 10) + "%"; - this.element.style.width = this.isVertical ? width : height; - this.element.style.height = this.isVertical ? height : width; - } - - flipShip() { - this.isVertical = !this.isVertical; - if (this.isVertical) { - if (this.row + this.size > 10) { - this.row = 10 - this.size; - } - } else { - if (this.column + this.size > 10) { - this.column = 10 - this.size; - } - } - this.updateLayout(); - } - - getCellsCovered() { - var cells: string[] = []; - var row = this.row; - var col = this.column; - for (var i = 0; i < this.size; i++) { - cells.push(row.toString() + "," + col.toString()); - if (this.isVertical) { - row++; - } else { - col++; - } - } - return cells; - } - - isSunk() { - return this.hits === this.size; - } -} - -class Board { - ships: Ship[]; - cells: Cell[][]; // Indexed by [rows][columns] - playerTurn = false; // Set to true when player can move - onEvent: Function; // Callback function when an action on the board occurs - shipSizes = [5, 4, 3, 3, 2]; - - private positioningEnabled: boolean; // Set to true when the player can position the ships - - constructor(public element: HTMLElement, playerBoard: boolean = true) { - this.positioningEnabled = playerBoard; - this.cells = []; - this.ships = []; - var cell: Cell = null; - - // Create the cells for the board - for (var row = 0; row < 10; row++) { - this.cells[row] = []; - for (var column = 0; column < 10; column++) { - cell = new Cell(row, column); - this.cells[row][column] = cell; - element.appendChild(cell.element); - $(cell.element).data("cellLocation", cell.cellLocation()); - if (playerBoard) { - $(cell.element).droppable({ - disabled: false, - drop: (event, ui) => { - var shipElement = ui.draggable[0]; - var shipIndex: number = $(shipElement).data("shipIndex"); - var ship = this.ships[shipIndex]; - var shipX = Math.round(shipElement.offsetLeft / cell.element.offsetWidth); - var shipY = Math.round(shipElement.offsetTop / cell.element.offsetHeight); - ship.updatePosition(shipY, shipX, ship.isVertical); - } - }); - } - } - } - - var referenceCell = $(cell.element); - for (var i = 0; i < this.shipSizes.length; i++) { - var ship = new Ship(this.shipSizes[i]); - this.ships[i] = ship; - ship.updatePosition(i, 0, false); - if (playerBoard) { // Show the ships for positioning. - this.element.appendChild(ship.element); - ship.updateLayout(); - $(ship.element).data("shipIndex", i).draggable({ - disabled: false, - containment: 'parent', - // Reduce size slightly to avoid overlap issues blocking the last cell - grid: [referenceCell.width() * 0.99 + 2, referenceCell.height() * 0.99 + 2], - cursor: 'crosshair' - }).click((evt: JQueryEventObject) => { - if (this.positioningEnabled) { - var shipIndex: number = $(evt.target).data("shipIndex"); - this.ships[shipIndex].flipShip(); - } - }); - } - } - - $(window).resize((evt) => { - $(this.element).children(".ship").draggable("option", "grid", [referenceCell.width() * 0.99 + 2, referenceCell.height() * 0.99 + 2]); - }); - - if (!playerBoard) { - // Computer board, this is where the player clicks to bomb - $(element).click((evt: JQueryEventObject) => this.onCellClick(evt)); - } - } - - set dragAndDropEnabled(val: boolean) { - var cells = $(this.element).children(".cell"); - var ships = $(this.element).children(".ship"); - - this.positioningEnabled = val; - ships.draggable("option", "disabled", !val); - cells.droppable("option", "disabled", !val); - } - - static getRandomPosition() { - return { - "row": Math.floor(Math.random() * 10), - "column": Math.floor(Math.random() * 10), - "vertical": (Math.floor(Math.random() * 2) === 1) - } - } - - onCellClick(evt: JQueryEventObject) { - var x = evt.target; - if ($(x).hasClass("cell") === false) { - return; - } - if (!this.playerTurn) { - this.onEvent.call(this, 'click'); - } - if (this.playerTurn) { // May be updated by prior onEvent call, so check again - this.bombCell(x); - } - } - - bombCell(cellElem: HTMLElement) { - var cellPos = Cell.parseCellLocation($(cellElem).data("cellLocation")); - var cell = this.cells[cellPos.row][cellPos.column]; - - if (cell.hasHit) { - return; // Already been clicked on - } - cell.hasHit = true; - if (cell.shipIndex >= 0) { // Has a ship - $(cellElem).removeClass("notBombed"); - $(cellElem).addClass("cellHit"); - var ship = this.ships[cell.shipIndex]; - ship.hits++; - if (ship.isSunk()) { - if (this.allShipsSunk()) { - this.onEvent.call(this, 'allSunk'); - } else { - this.onEvent.call(this, 'shipSunk'); - } - } else { - this.onEvent.call(this, 'hit'); - } - } else { - $(cellElem).removeClass("notBombed"); - $(cellElem).addClass("cellMiss"); - this.onEvent.call(this, 'playerMissed'); - } - } - - randomize() { - var shipCount = this.ships.length; - do { - for (var shipIndex = 0; shipIndex < shipCount; shipIndex++) { - var pos = Board.getRandomPosition(); - this.ships[shipIndex].updatePosition(pos.row, pos.column, pos.vertical); - } - } while (!this.boardIsValid()); - } - - boardIsValid() { - // Check if any ships overlap my checking their cells for duplicates. - // Do this by putting into a flat array, sorting, and seeing if any adjacent cells are equal - var allCells: string[] = []; - for (var i = 0; i < this.ships.length; i++) { - allCells = allCells.concat(this.ships[i].getCellsCovered()); - } - allCells.sort(); - var dups = allCells.some(function (val, idx, arr) { return val === arr[idx + 1]; }); - - // See if any ship cells are off the board - var outOfRange = allCells.some(function (val: string) { - var pos = Cell.parseCellLocation(val); - return !(pos.column >= 0 && pos.column <= 9 && pos.row >= 0 && pos.row <= 9); - }); - if (dups || outOfRange) { - return false; - } else { - this.updateCellData(); - return true; - } - } - - chooseMove() { - do { - var pos = Board.getRandomPosition(); - var cell = this.cells[pos.row][pos.column]; - } while (cell.hasHit); - this.bombCell(cell.element); - } - - private updateCellData() { - for (var i = 0; i < 100; i++) { - var x = this.cells[Math.floor(i / 10)][i % 10]; - x.hasHit = false; - x.shipIndex = -1; - } - - for (var index = 0; index < this.ships.length; index++) { - var ship = this.ships[index] - ship.hits = 0; - var cells = ship.getCellsCovered(); - for (var cell = 0; cell < cells.length; cell++) { - var cellPos = Cell.parseCellLocation(cells[cell]); - var targetCell = this.cells[cellPos.row][cellPos.column]; - targetCell.shipIndex = index; - } - } - - $(this.element).children(".cell").removeClass("cellHit cellMiss").addClass("notBombed"); - } - - private allShipsSunk() { - return this.ships.every(function (val) { return val.isSunk(); }); - } -} - -class Game { - static gameState = { begin: 0, computerTurn: 1, playerTurn: 2, finished: 3 }; - static msgs = { - gameStart: "Drag your ships to the desired location on your board (on the right), then bomb a square on the left board to start the game!", - invalidPositions: "All ships must be in valid positions before the game can begin.", - wait: "Wait your turn!", - gameOn: "Game on!", - hit: "Good hit!", - shipSunk: "You sunk a ship!", - lostShip: "You lost a ship :-(", - lostGame: "You lost this time. Click anywhere on the left board to play again.", - allSunk: "Congratulations! You won! Click anywhere on the left board to play again." - }; - - state = Game.gameState.begin; - playerBoard: Board; - computerBoard: Board; - - constructor() { - this.updateStatus(Game.msgs.gameStart); - this.playerBoard = new Board($("#playerBoard")[0]); - this.computerBoard = new Board($("#computerBoard")[0], false); - this.computerBoard.randomize(); - this.playerBoard.randomize(); - this.playerBoard.dragAndDropEnabled = true; - this.computerBoard.onEvent = (evt: string) => { - switch (evt) { - case 'click': // The user has click outside a turn. Action depends on current state - switch (this.state) { - case Game.gameState.begin: - this.startGame(); - break; - case Game.gameState.computerTurn: // Not their turn yet. Ask to wait. - this.updateStatus(Game.msgs.wait); - break; - case Game.gameState.finished: // Start a new game - this.computerBoard.randomize(); - this.playerBoard.randomize(); - this.playerBoard.dragAndDropEnabled = true; - this.updateStatus(Game.msgs.gameStart); - this.state = Game.gameState.begin; - break; - } - break; - case 'playerMissed': - this.computersTurn(); - break; - case 'hit': - this.updateStatus(Game.msgs.hit); - this.computersTurn(); - break; - case 'shipSunk': - this.updateStatus(Game.msgs.shipSunk); - this.computersTurn(); - break; - case 'allSunk': - this.state = Game.gameState.finished; - this.computerBoard.playerTurn = false; - this.updateStatus(Game.msgs.allSunk); - break; - } - }; - this.playerBoard.onEvent = (evt: string) => { - switch (evt) { - case 'playerMissed': - case 'hit': - this.computerBoard.playerTurn = true; - break; - case 'shipSunk': - this.updateStatus(Game.msgs.lostShip); - this.computerBoard.playerTurn = true; - break; - case 'allSunk': - this.updateStatus(Game.msgs.lostGame); - this.computerBoard.playerTurn = false; - this.state = Game.gameState.finished; - break; - } - }; - } - - private computersTurn() { - this.computerBoard.playerTurn = false; - this.state = Game.gameState.computerTurn; - setTimeout(() => { - this.playerBoard.chooseMove(); - }, 250); - } - - private startGame() { - if (this.playerBoard.boardIsValid()) { - this.state = Game.gameState.playerTurn; - this.playerBoard.dragAndDropEnabled = false; - this.computerBoard.playerTurn = true; - this.updateStatus(Game.msgs.gameOn); - } - else { - this.updateStatus(Game.msgs.invalidPositions); - } - } - - private updateStatus(msg: string) { - $("#status").slideUp('fast', function () { // Slide out the old text - $(this).text(msg).slideDown('fast'); // Then slide in the new text - }); - } -} - -$(new Function("var game = new Game();")); +/// +/// + +class Cell { + shipIndex: number; + hasHit: boolean; + element: HTMLElement; + + constructor(public row: number, public column: number) { + this.element = $("
      ")[0]; + } + + // Parse a cell location of the format "row,column" + static parseCellLocation(pos: string) { + var indices: string[] = pos.split(","); + return { 'row': parseInt(indices[0]), 'column': parseInt(indices[1]) }; + } + + // Return the cell location of the format "row,column" + cellLocation() { + return "" + this.row + "," + this.column; + } +} + +class Ship { + column = 0; + row = 0; + isVertical = true; + hits = 0; + element: HTMLElement; + + constructor(public size: number) { + this.element = $("
      ")[0]; + } + + updatePosition(row: number, column: number, vertical: boolean) { + this.row = row; + this.column = column; + this.isVertical = vertical; + this.updateLayout(); + } + + updateLayout() { + var width = "9.9%"; + var height = "" + (this.size * 9.9) + "%"; + this.element.style.left = "" + (this.column * 10) + "%"; + this.element.style.top = "" + (this.row * 10) + "%"; + this.element.style.width = this.isVertical ? width : height; + this.element.style.height = this.isVertical ? height : width; + } + + flipShip() { + this.isVertical = !this.isVertical; + if (this.isVertical) { + if (this.row + this.size > 10) { + this.row = 10 - this.size; + } + } else { + if (this.column + this.size > 10) { + this.column = 10 - this.size; + } + } + this.updateLayout(); + } + + getCellsCovered() { + var cells: string[] = []; + var row = this.row; + var col = this.column; + for (var i = 0; i < this.size; i++) { + cells.push(row.toString() + "," + col.toString()); + if (this.isVertical) { + row++; + } else { + col++; + } + } + return cells; + } + + isSunk() { + return this.hits === this.size; + } +} + +class Board { + ships: Ship[]; + cells: Cell[][]; // Indexed by [rows][columns] + playerTurn = false; // Set to true when player can move + onEvent: Function; // Callback function when an action on the board occurs + shipSizes = [5, 4, 3, 3, 2]; + + private positioningEnabled: boolean; // Set to true when the player can position the ships + + constructor(public element: HTMLElement, playerBoard: boolean = true) { + this.positioningEnabled = playerBoard; + this.cells = []; + this.ships = []; + var cell: Cell = null; + + // Create the cells for the board + for (var row = 0; row < 10; row++) { + this.cells[row] = []; + for (var column = 0; column < 10; column++) { + cell = new Cell(row, column); + this.cells[row][column] = cell; + element.appendChild(cell.element); + $(cell.element).data("cellLocation", cell.cellLocation()); + if (playerBoard) { + $(cell.element).droppable({ + disabled: false, + drop: (event, ui) => { + var shipElement = ui.draggable[0]; + var shipIndex: number = $(shipElement).data("shipIndex"); + var ship = this.ships[shipIndex]; + var shipX = Math.round(shipElement.offsetLeft / cell.element.offsetWidth); + var shipY = Math.round(shipElement.offsetTop / cell.element.offsetHeight); + ship.updatePosition(shipY, shipX, ship.isVertical); + } + }); + } + } + } + + var referenceCell = $(cell.element); + for (var i = 0; i < this.shipSizes.length; i++) { + var ship = new Ship(this.shipSizes[i]); + this.ships[i] = ship; + ship.updatePosition(i, 0, false); + if (playerBoard) { // Show the ships for positioning. + this.element.appendChild(ship.element); + ship.updateLayout(); + $(ship.element).data("shipIndex", i).draggable({ + disabled: false, + containment: 'parent', + // Reduce size slightly to avoid overlap issues blocking the last cell + grid: [referenceCell.width() * 0.99 + 2, referenceCell.height() * 0.99 + 2], + cursor: 'crosshair' + }).click((evt: JQueryEventObject) => { + if (this.positioningEnabled) { + var shipIndex: number = $(evt.target).data("shipIndex"); + this.ships[shipIndex].flipShip(); + } + }); + } + } + + $(window).resize((evt) => { + $(this.element).children(".ship").draggable("option", "grid", [referenceCell.width() * 0.99 + 2, referenceCell.height() * 0.99 + 2]); + }); + + if (!playerBoard) { + // Computer board, this is where the player clicks to bomb + $(element).click((evt: JQueryEventObject) => this.onCellClick(evt)); + } + } + + set dragAndDropEnabled(val: boolean) { + var cells = $(this.element).children(".cell"); + var ships = $(this.element).children(".ship"); + + this.positioningEnabled = val; + ships.draggable("option", "disabled", !val); + cells.droppable("option", "disabled", !val); + } + + static getRandomPosition() { + return { + "row": Math.floor(Math.random() * 10), + "column": Math.floor(Math.random() * 10), + "vertical": (Math.floor(Math.random() * 2) === 1) + } + } + + onCellClick(evt: JQueryEventObject) { + var x = evt.target; + if ($(x).hasClass("cell") === false) { + return; + } + if (!this.playerTurn) { + this.onEvent.call(this, 'click'); + } + if (this.playerTurn) { // May be updated by prior onEvent call, so check again + this.bombCell(x); + } + } + + bombCell(cellElem: HTMLElement) { + var cellPos = Cell.parseCellLocation($(cellElem).data("cellLocation")); + var cell = this.cells[cellPos.row][cellPos.column]; + + if (cell.hasHit) { + return; // Already been clicked on + } + cell.hasHit = true; + if (cell.shipIndex >= 0) { // Has a ship + $(cellElem).removeClass("notBombed"); + $(cellElem).addClass("cellHit"); + var ship = this.ships[cell.shipIndex]; + ship.hits++; + if (ship.isSunk()) { + if (this.allShipsSunk()) { + this.onEvent.call(this, 'allSunk'); + } else { + this.onEvent.call(this, 'shipSunk'); + } + } else { + this.onEvent.call(this, 'hit'); + } + } else { + $(cellElem).removeClass("notBombed"); + $(cellElem).addClass("cellMiss"); + this.onEvent.call(this, 'playerMissed'); + } + } + + randomize() { + var shipCount = this.ships.length; + do { + for (var shipIndex = 0; shipIndex < shipCount; shipIndex++) { + var pos = Board.getRandomPosition(); + this.ships[shipIndex].updatePosition(pos.row, pos.column, pos.vertical); + } + } while (!this.boardIsValid()); + } + + boardIsValid() { + // Check if any ships overlap my checking their cells for duplicates. + // Do this by putting into a flat array, sorting, and seeing if any adjacent cells are equal + var allCells: string[] = []; + for (var i = 0; i < this.ships.length; i++) { + allCells = allCells.concat(this.ships[i].getCellsCovered()); + } + allCells.sort(); + var dups = allCells.some(function (val, idx, arr) { return val === arr[idx + 1]; }); + + // See if any ship cells are off the board + var outOfRange = allCells.some(function (val: string) { + var pos = Cell.parseCellLocation(val); + return !(pos.column >= 0 && pos.column <= 9 && pos.row >= 0 && pos.row <= 9); + }); + if (dups || outOfRange) { + return false; + } else { + this.updateCellData(); + return true; + } + } + + chooseMove() { + do { + var pos = Board.getRandomPosition(); + var cell = this.cells[pos.row][pos.column]; + } while (cell.hasHit); + this.bombCell(cell.element); + } + + private updateCellData() { + for (var i = 0; i < 100; i++) { + var x = this.cells[Math.floor(i / 10)][i % 10]; + x.hasHit = false; + x.shipIndex = -1; + } + + for (var index = 0; index < this.ships.length; index++) { + var ship = this.ships[index] + ship.hits = 0; + var cells = ship.getCellsCovered(); + for (var cell = 0; cell < cells.length; cell++) { + var cellPos = Cell.parseCellLocation(cells[cell]); + var targetCell = this.cells[cellPos.row][cellPos.column]; + targetCell.shipIndex = index; + } + } + + $(this.element).children(".cell").removeClass("cellHit cellMiss").addClass("notBombed"); + } + + private allShipsSunk() { + return this.ships.every(function (val) { return val.isSunk(); }); + } +} + +class Game { + static gameState = { begin: 0, computerTurn: 1, playerTurn: 2, finished: 3 }; + static msgs = { + gameStart: "Drag your ships to the desired location on your board (on the right), then bomb a square on the left board to start the game!", + invalidPositions: "All ships must be in valid positions before the game can begin.", + wait: "Wait your turn!", + gameOn: "Game on!", + hit: "Good hit!", + shipSunk: "You sunk a ship!", + lostShip: "You lost a ship :-(", + lostGame: "You lost this time. Click anywhere on the left board to play again.", + allSunk: "Congratulations! You won! Click anywhere on the left board to play again." + }; + + state = Game.gameState.begin; + playerBoard: Board; + computerBoard: Board; + + constructor() { + this.updateStatus(Game.msgs.gameStart); + this.playerBoard = new Board($("#playerBoard")[0]); + this.computerBoard = new Board($("#computerBoard")[0], false); + this.computerBoard.randomize(); + this.playerBoard.randomize(); + this.playerBoard.dragAndDropEnabled = true; + this.computerBoard.onEvent = (evt: string) => { + switch (evt) { + case 'click': // The user has click outside a turn. Action depends on current state + switch (this.state) { + case Game.gameState.begin: + this.startGame(); + break; + case Game.gameState.computerTurn: // Not their turn yet. Ask to wait. + this.updateStatus(Game.msgs.wait); + break; + case Game.gameState.finished: // Start a new game + this.computerBoard.randomize(); + this.playerBoard.randomize(); + this.playerBoard.dragAndDropEnabled = true; + this.updateStatus(Game.msgs.gameStart); + this.state = Game.gameState.begin; + break; + } + break; + case 'playerMissed': + this.computersTurn(); + break; + case 'hit': + this.updateStatus(Game.msgs.hit); + this.computersTurn(); + break; + case 'shipSunk': + this.updateStatus(Game.msgs.shipSunk); + this.computersTurn(); + break; + case 'allSunk': + this.state = Game.gameState.finished; + this.computerBoard.playerTurn = false; + this.updateStatus(Game.msgs.allSunk); + break; + } + }; + this.playerBoard.onEvent = (evt: string) => { + switch (evt) { + case 'playerMissed': + case 'hit': + this.computerBoard.playerTurn = true; + break; + case 'shipSunk': + this.updateStatus(Game.msgs.lostShip); + this.computerBoard.playerTurn = true; + break; + case 'allSunk': + this.updateStatus(Game.msgs.lostGame); + this.computerBoard.playerTurn = false; + this.state = Game.gameState.finished; + break; + } + }; + } + + private computersTurn() { + this.computerBoard.playerTurn = false; + this.state = Game.gameState.computerTurn; + setTimeout(() => { + this.playerBoard.chooseMove(); + }, 250); + } + + private startGame() { + if (this.playerBoard.boardIsValid()) { + this.state = Game.gameState.playerTurn; + this.playerBoard.dragAndDropEnabled = false; + this.computerBoard.playerTurn = true; + this.updateStatus(Game.msgs.gameOn); + } + else { + this.updateStatus(Game.msgs.invalidPositions); + } + } + + private updateStatus(msg: string) { + $("#status").slideUp('fast', function () { // Slide out the old text + $(this).text(msg).slideDown('fast'); // Then slide in the new text + }); + } +} + +$(new Function("var game = new Game();")); diff --git a/win8.1/README.md b/win8.1/README.md deleted file mode 100644 index 0e7c5ab..0000000 --- a/win8.1/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# TypeScript Sample: Windows 8.1 Windows store app - -## Overview - -The encyclopedia includes a complete sample app for a Windows 8.1 app -built using TypeScript. The following features of TypeScript are highlighted: -- VS project integration: TypeScript compilation integrated into VS build -- Typing WinJS and WinRT: Early work on typing these libraries -- Mostly JS in TypeScript: Code is mostly the original JS, with a little - TypeScript - -## Running -``` -Open encyclopedia\Encyclopedia.sln in Visual Studio 2013 -F5 -``` diff --git a/win8.1/encyclopedia/Encyclopedia.sln b/win8.1/encyclopedia/Encyclopedia.sln deleted file mode 100644 index 7e55419..0000000 --- a/win8.1/encyclopedia/Encyclopedia.sln +++ /dev/null @@ -1,46 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2012 -Project("{262852C6-CD72-467D-83FE-5EEB1973A190}") = "Encyclopedia", "Encyclopedia\Encyclopedia.jsproj", "{CB97C74A-DB4A-42FA-8B3B-FFED5198621B}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|ARM = Debug|ARM - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|ARM = Release|ARM - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Debug|Any CPU.Deploy.0 = Debug|Any CPU - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Debug|ARM.ActiveCfg = Debug|ARM - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Debug|ARM.Build.0 = Debug|ARM - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Debug|ARM.Deploy.0 = Debug|ARM - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Debug|x64.ActiveCfg = Debug|x64 - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Debug|x64.Build.0 = Debug|x64 - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Debug|x64.Deploy.0 = Debug|x64 - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Debug|x86.ActiveCfg = Debug|x86 - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Debug|x86.Build.0 = Debug|x86 - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Debug|x86.Deploy.0 = Debug|x86 - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Release|Any CPU.Build.0 = Release|Any CPU - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Release|Any CPU.Deploy.0 = Release|Any CPU - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Release|ARM.ActiveCfg = Release|ARM - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Release|ARM.Build.0 = Release|ARM - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Release|ARM.Deploy.0 = Release|ARM - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Release|x64.ActiveCfg = Release|x64 - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Release|x64.Build.0 = Release|x64 - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Release|x64.Deploy.0 = Release|x64 - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Release|x86.ActiveCfg = Release|x86 - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Release|x86.Build.0 = Release|x86 - {CB97C74A-DB4A-42FA-8B3B-FFED5198621B}.Release|x86.Deploy.0 = Release|x86 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/win8.1/encyclopedia/Encyclopedia/Encyclopedia.jsproj b/win8.1/encyclopedia/Encyclopedia/Encyclopedia.jsproj deleted file mode 100644 index 901144d..0000000 --- a/win8.1/encyclopedia/Encyclopedia/Encyclopedia.jsproj +++ /dev/null @@ -1,117 +0,0 @@ - - - - - Debug - AnyCPU - - - Debug - ARM - - - Debug - x64 - - - Debug - x86 - - - Release - AnyCPU - - - Release - ARM - - - Release - x64 - - - Release - x86 - - - - {cb97c74a-db4a-42fa-8b3b-ffed5198621b} - - - - - - Windows - 8.1 - en-US - 12.0 - 12.0 - - - - Designer - - - - - - - - - - - - - - - - - - - - - - - - - - - - groupDetailPage.ts - - - default.ts - - - navigator.ts - - - data.ts - - - itemDetailPage.ts - - - groupedItemsPage.ts - - - topic.ts - - - - - - - - - ES5 - true - true - - - ES5 - false - false - - - \ No newline at end of file diff --git a/win8.1/encyclopedia/Encyclopedia/css/default.css b/win8.1/encyclopedia/Encyclopedia/css/default.css deleted file mode 100644 index bf447d5..0000000 --- a/win8.1/encyclopedia/Encyclopedia/css/default.css +++ /dev/null @@ -1,181 +0,0 @@ -html { - cursor: default; -} - -#contenthost { - height: 100%; - width: 100%; -} - -.fragment { - /* Define a grid with rows for a banner and a body */ - -ms-grid-columns: 1fr; - -ms-grid-rows: 128px 1fr 0px; - display: -ms-grid; - height: 100%; - width: 100%; -} - - .fragment header[role=banner] { - /* Define a grid with columns for the back button and page title. */ - -ms-grid-columns: 120px 1fr; - -ms-grid-rows: 1fr; - display: -ms-grid; - } - - .fragment header[role=banner] .win-backbutton { - margin-left: 39px; - margin-top: 59px; - } - - .fragment header[role=banner] .titlearea { - -ms-grid-column: 2; - margin-top: 37px; - } - - .fragment header[role=banner] .titlearea .pagetitle { - width: calc(100% - 20px); - } - - .fragment section[role=main] { - -ms-grid-row: 2; - height: 100%; - width: 100%; - } - -@media screen and (-ms-view-state: snapped) { - .fragment header[role=banner] { - -ms-grid-columns: auto 1fr; - margin-left: 20px; - } - - .fragment header[role=banner] .win-backbutton { - margin: 0; - margin-right: 10px; - margin-top: 76px; - } - - .fragment header[role=banner] .win-backbutton:disabled { - display: none; - } - - .fragment header[role=banner] .titlearea { - -ms-grid-column: 2; - margin-left: 0; - margin-top: 68px; - } -} - -@media screen and (-ms-view-state: fullscreen-portrait) { - .fragment header[role=banner] { - -ms-grid-columns: 100px 1fr; - } - - .fragment header[role=banner] .win-backbutton { - margin-left: 29px; - } -} - - -/*html -{ - cursor: default; -} - -#contentHost -{ - height: 100%; - width: 100%; -} - -.fragment -{ - -ms-grid-columns: 1fr; - -ms-grid-rows: 133px 1fr 0px; - display: -ms-grid; - height: 100%; - width: 100%; -} - - .fragment header[role=banner] - { - -ms-grid-columns: 120px 1fr; - -ms-grid-rows: 1fr; - display: -ms-grid; - } - - .fragment header[role=banner] .win-backbutton - { - margin-left: 39px; - margin-top: 59px; - } - - .fragment header[role=banner] .titleArea - { - -ms-grid-column: 2; - margin-top: 44px; - } - - .fragment header[role=banner] .titleArea .win-type-xx-large - { - display: inline; - height: 60pt; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - width: calc(100% - 20px); - } - - .fragment section[role=main] - { - -ms-grid-row: 2; - height: 100%; - width: 100%; - } - -@media screen and (-ms-view-state: snapped) -{ - .fragment .win-type-x-large - { - font-size: 11pt; - line-height: 15pt; - } - - .fragment header[role=banner] - { - -ms-grid-columns: 60px 1fr; - -ms-grid-rows: 1fr; - display: -ms-grid; - } - - .fragment header[role=banner] .win-backbutton - { - margin-left: 20px; - margin-top: 75px; - } - - .fragment header[role=banner] .titleArea - { - margin-top: 71px; - max-width: 260px; - } - - .fragment header[role=banner] .titleArea .win-type-xx-large - { - font-size: 20pt; - line-height: 24pt; - } - } - -@media screen and (-ms-view-state: fullscreen-portrait) -{ - .fragment header[role=banner] - { - -ms-grid-columns: 100px 1fr; - } - - .fragment header[role=banner] .win-backbutton - { - margin-left: 29px; - } - }*/ diff --git a/win8.1/encyclopedia/Encyclopedia/css/groupDetailPage.css b/win8.1/encyclopedia/Encyclopedia/css/groupDetailPage.css deleted file mode 100644 index c1ac94c..0000000 --- a/win8.1/encyclopedia/Encyclopedia/css/groupDetailPage.css +++ /dev/null @@ -1,173 +0,0 @@ -.groupDetailPage .groupList -{ - height: 100%; - margin-bottom: 4px; - position: relative; - width: 100%; - z-index: 0; -} - - .groupDetailPage .groupList .win-groupheader - { - -ms-grid-columns: 1fr; - -ms-grid-rows: auto 11px auto 20px 1fr 36px; - display: -ms-grid; - font-family: "Segoe UI"; - font-size: 11pt; - height: 100%; - line-height: 15pt; - margin-left: 120px; - margin-right: 70px; - overflow: visible; - padding: 0; - width: 480px; - } - - .groupDetailPage .groupList .win-groupheader .win-type-x-large - { - -ms-grid-row: 1; - margin: 0; - max-height: 48pt; - overflow: hidden; - padding-bottom: 4px; - } - - .groupDetailPage .groupList .win-groupheader .image - { - -ms-grid-row: 3; - background-color: rgba(147, 149, 152, 1); - height: 238px; - margin: 0; - width: 480px; - } - - .groupDetailPage .groupList .win-groupheader .description - { - -ms-grid-row: 5; - column-fill: auto; - column-gap: 70px; - columns: 480px auto; - margin-bottom: 12px; - margin-top: -2px; - overflow: hidden; - } - - .groupDetailPage .groupList .win-groupheader .description p - { - margin-top: 0; - } - - .groupDetailPage .groupList .item - { - -ms-grid-columns: 110px 10px 1fr; - -ms-grid-rows: 1fr; - display: -ms-grid; - height: 100%; - width: 100%; - } - - .groupDetailPage .groupList .item .item-info - { - -ms-grid-column: 3; - } - - .groupDetailPage .groupList .item .item-info .item-title - { - margin-top: 4px; - max-height: 20px; - opacity: 0.8; - overflow: hidden; - } - - .groupDetailPage .groupList .item .item-info .item-subtitle - { - max-height: 20px; - opacity: 0.49; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - } - - .groupDetailPage .groupList .item .item-info .item-description - { - max-height: 60px; - opacity: 0.8; - overflow: hidden; - } - - .groupDetailPage .groupList .win-item - { - height: 110px; - margin-bottom: 10px; - margin-right: 60px; - padding: 10px; - width: 472px; - } - -.groupDetailPage header[role=banner] .menu -{ - background-color: #FFFFFF; -} - - .groupDetailPage header[role=banner] .menu .win-command - { - color: #2A2A2A; - font-size: 20pt; - line-height: 24pt; - margin-bottom: 13px; - margin-top: 6px; - padding-left: 20px; - padding-right: 20px; - } - -@media screen and (-ms-view-state: snapped) -{ - .groupDetailPage .groupList - { - width: calc(100% - 10px); - margin-left: 10px; - } - - .groupDetailPage .groupList .win-groupheader - { - visibility: hidden; - } - - .groupDetailPage .groupList .win-item - { - height: 64px; - margin: 0; - margin-right: 18px; - padding: 10px 0px 10px 10px; - width: 282px; - } - - .groupDetailPage .groupList .item - { - -ms-grid-columns: 60px 10px 1fr; - -ms-grid-rows: 1fr; - display: -ms-grid; - height: 100%; - width: 100%; - } - - .groupDetailPage .groupList .item .item-info .item-title - { - max-height: 30pt; - overflow: hidden; - text-overflow: ellipsis; - } - - .groupDetailPage .groupList .item .item-info .item-description - { - visibility: hidden; - } - } - -@media screen and (-ms-view-state: fullscreen-portrait) -{ - .groupDetailPage .groupList .win-groupheader - { - margin-left: 100px; - } -} diff --git a/win8.1/encyclopedia/Encyclopedia/css/groupedItemsPage.css b/win8.1/encyclopedia/Encyclopedia/css/groupedItemsPage.css deleted file mode 100644 index 03bc11e..0000000 --- a/win8.1/encyclopedia/Encyclopedia/css/groupedItemsPage.css +++ /dev/null @@ -1,140 +0,0 @@ -.wiki -{ - font-weight:300; - font-family: 'Segoe UI'; - color: black; -} -.bee -{ - font-weight:300; - font-family: 'Segoe UI'; - color: #ffdd33; -} - -/* This selector is used to prevent ui-dark/light.css from overwriting changes - to .win-surface. */ -.groupeditemspage .groupeditemslist .win-horizontal.win-viewport .win-surface { - margin-left: 45px; - margin-bottom: 60px; -} - -.groupeditemspage .groupeditemslist { - height: 100%; - position: relative; - width: 100%; - z-index: 0; -} - - .groupeditemspage .groupeditemslist .win-groupheader { - margin-top: 5px; - margin-left: 70px; - padding: 0; - } - - .groupeditemspage .groupeditemslist .win-groupheader .group-title { - margin-bottom: 10px; - margin-left: 5px; - margin-top: 0; - } - - .groupeditemspage .groupeditemslist .item { - -ms-grid-columns: 1fr; - -ms-grid-rows: 1fr 90px; - display: -ms-grid; - height: 250px; - width: 250px; - } - - .groupeditemspage .groupeditemslist .item .item-image { - -ms-grid-row-span: 2; - width: 100%; - height: 100%; - } - - .groupeditemspage .groupeditemslist .item .item-overlay { - -ms-grid-row: 2; - -ms-grid-rows: 1fr 21px; - display: -ms-grid; - padding: 6px 15px 2px 15px; - } - - .groupeditemspage .groupeditemslist .item .item-overlay .item-title { - -ms-grid-row: 1; - overflow: hidden; - width: 220px; - } - - .groupeditemspage .groupeditemslist .item .item-overlay .item-subtitle { - -ms-grid-row: 2; - width: 220px; - } - -@media screen and (-ms-view-state: fullscreen-landscape), screen and (-ms-view-state: fullscreen-portrait), screen and (-ms-view-state: filled) { - .groupeditemspage .groupeditemslist .item .item-overlay { - background: rgba(0,0,0,0.65); - } - - .groupeditemspage .groupeditemslist .item .item-overlay .item-title { - color: rgba(255,255,255,0.87); - } - - .groupeditemspage .groupeditemslist .item .item-overlay .item-subtitle { - color: rgba(255,255,255,0.6); - } -} - -@media screen and (-ms-view-state: snapped) { - - .groupeditemspage .groupeditemslist .win-vertical.win-viewport .win-surface { - margin-bottom: 30px; - margin-left: 6px; - } - - .groupeditemspage .groupeditemslist .win-vertical.win-viewport .win-container { - margin-right: 42px; - margin-bottom: 15px; - padding: 7px; - } - - .groupeditemspage .groupeditemslist .item { - -ms-grid-columns: 60px 1fr; - -ms-grid-rows: 1fr; - display: -ms-grid; - height: 60px; - width: 272px; - } - - .groupeditemspage .groupeditemslist .item .item-image { - -ms-grid-column: 1; - -ms-grid-row-span: 1; - height: 60px; - width: 60px; - } - - .groupeditemspage .groupeditemslist .item .item-overlay { - -ms-grid-column: 2; - -ms-grid-row: 1; - -ms-grid-row-align: stretch; - background: transparent; - display: inline-block; - margin-left: 10px; - padding: 0; - } - - .groupeditemspage .groupeditemslist .item .item-overlay .item-title { - margin-top: 4px; - max-height: 40px; - width: 202px; - } - - .groupeditemspage .groupeditemslist .item .item-overlay .item-subtitle { - opacity: 0.6; - width: 202px; - } -} - -@media screen and (-ms-view-state: fullscreen-portrait) { - .groupeditemspage .groupeditemslist .win-horizontal.win-viewport .win-surface { - margin-left: 25px; - } -} diff --git a/win8.1/encyclopedia/Encyclopedia/css/itemDetailPage.css b/win8.1/encyclopedia/Encyclopedia/css/itemDetailPage.css deleted file mode 100644 index d0187ce..0000000 --- a/win8.1/encyclopedia/Encyclopedia/css/itemDetailPage.css +++ /dev/null @@ -1,103 +0,0 @@ -.itemDetailPage section[role=main] -{ - -ms-grid-row: 2; - display: block; - height: 100%; - overflow-x: auto; - position: relative; - width: 100%; - z-index: 0; -} - - .itemDetailPage section[role=main] article - { - column-fill: auto; - column-gap: 80px; - column-width: 480px; - height: calc(100% - 50px); - margin-left: 120px; - width: 480px; - } - - .itemDetailPage section[role=main] article header .win-type-x-large - { - margin-bottom: 20px; - margin-top: 0; - } - - .itemDetailPage section[role=main] article header .win-type-medium - { - margin-bottom: 20px; - margin-top: 0; - } - - .itemDetailPage section[role=main] article .image - { - height: 240px; - margin-bottom: 3px; - width: 460px; - } - - .itemDetailPage section[role=main] article p - { - margin-bottom: 20px; - margin-right: 20px; - vertical-align: baseline; - } - -.itemDetailPage header[role=banner] .menu -{ - background-color: #FFFFFF; -} - - .itemDetailPage header[role=banner] .menu .win-command - { - color: #2A2A2A; - font-size: 20pt; - line-height: 24pt; - margin-bottom: 13px; - margin-top: 6px; - padding-left: 20px; - padding-right: 20px; - } - -@media screen and (-ms-view-state: snapped) -{ - .itemDetailPage section[role=main] article - { - -ms-grid-columns: 300px 1fr; - -ms-grid-row: 2; - -ms-grid-rows: auto 60px; - display: -ms-grid; - height: 100%; - margin-left: 20px; - overflow-x: hidden; - overflow-y: auto; - width: 300px; - } - - .itemDetailPage section[role=main] article header .win-type-x-large - { - font-size: 11pt; - line-height: 15pt; - } - - .itemDetailPage section[role=main] article .image - { - height: 140px; - width: 280px; - } - - .itemDetailPage section[role=main] article .content - { - padding-bottom: 60px; - } - } - -@media screen and (-ms-view-state: fullscreen-portrait) -{ - .detailPage section[role=main] article - { - margin-left: 100px; - } -} diff --git a/win8.1/encyclopedia/Encyclopedia/css/wikipedia.css b/win8.1/encyclopedia/Encyclopedia/css/wikipedia.css deleted file mode 100644 index 259ca56..0000000 --- a/win8.1/encyclopedia/Encyclopedia/css/wikipedia.css +++ /dev/null @@ -1,283 +0,0 @@ -/* -body -{ - word-wrap: break-word !important; - font-size:1.5em !important; -} - -h2 -{ - font-size: 1.5em; -} - -h3 -{ - font-size: 1.5em; -} -h4 -{ - font-size: 1.5em; -} - */ - -h2, h3, h4, h5, h6, h7 -{ - break-after: avoid; -} - -img.tex -{ - /*max-width: 380px !important;*/ -} - -a -{ - text-decoration:none !important; -} - -.firstHeading -{ - display:none !important; -} - -.noprint -{ - display:none !important; -} - -.printfooter -{ - display: none !important; -} - -.catlinks -{ - display: none !important; -} - -.metadata -{ - display: none !important; -} - -#footer -{ - display:none !important; -} - -#jump-to-nav -{ - display:none !important; -} - -.toc -{ - display:none !important; -} - -#siteSub { display:none !important; } -#contentSub { display: none !important; } - - -.dablink -{ - float:none !important; - width: 100%!important; - display:block !important; - background-color:rgb(230, 230, 230) !important; - margin: 2px 2px 2px 2px !important; - font-size: .6em !important; - font-style: italic !important; -} - -.infobox -{ - float:none !important; - width: 100% !important; - background-color: rgb(230, 230, 230) !important; - margin: 2px 2px 2px 2px !important; - border-style:solid !important; - border-width: 1px !important; - border-color: rgb(200,200,200) !important; - font-size: .75em !important; -} - -.infobox caption -{ - display:none; -} - -#coordinates -{ - display: block !important; - border-style:outset !important; - border-width: 2px !important; - border-color: rgb(200,200,200) !important; -} - -.floatnone -{ - float:none !important; -} - -.rellink -{ - font-size: .9em !important; - margin: 10px 10px 10px 10px !important; - font-style: italic !important; - background-color:rgb(230, 230, 230) !important; - break-inside: avoid; - break-before: avoid; -} - -.editsection -{ - display:none !important; -} - -.magnify -{ - display:none !important; -} - -.thumb -{ - display:block; - - margin-top: 0.5em; - margin-bottom: 0.8em; - border-width: 1px; - border-color: #cccccc !important; - break-inside:avoid !important; - text-align: center; - background-color: white; -} - -.tright -{ - width:40% !important; - float:right !important; - clear:both !important; - margin-top: 0.5em; - margin-left: 0.8em; - /*margin-right: 0px;*/ - margin-bottom: 0.8em; -} - -.tleft -{ - width:40% !important; - float:left !important; - clear:both !important; - margin-top: 0.5em; - margin-right: 0.4em; - /*margin-left: 0px;*/ - margin-bottom: 0.8em; -} - -.tnone -{ - margin-top: 0.5em; - margin-right: 0.4em; - margin-left: 0.4em; - margin-bottom: 0.8em; -} - -.thumbinner -{ - text-align: center; - overflow: hidden; - padding: 3px; - font-size: 94%; - border-width: 1px; - border-style: solid; - width: 90% !important; -} - -.thumbimage -{ - width:100% !important; - height:100% !important; -} - -.thumbcaption -{ - font-size:0.8em; -} - -.references-small -{ - font-size:0.5em; -} - -.wikitable -{ - float:none !important; - width: 400px !important; - max-width: 400px !important; - background-color: rgb(230, 230, 230) !important; - margin: 2px 2px 2px 2px !important; - font-size: .6em !important; -} - -.wikitable th -{ - background-color: rgb(220,220,220); - border-style: solid !important; - border-width: 1px !important; - border-color: rgb(200,200,200) !important; -} - -.wikitable td -{ - border-style: solid !important; - border-width: 1px !important; - border-color: rgb(200,200,200) !important; -} - -table.autocollapse tbody tr -{ - display:none !important; -} - -table.autocollapse tbody tr:first -{ - display: block !important; -} - -table.collapsed tr.collapsable { - display: none !important; -} - -.collapseButton { /* 'show'/'hide' buttons created dynamically by the */ - float: right; /* CollapsibleTables JavaScript in [[MediaWiki:Common.js]] */ - font-weight: normal; /* are styled here so they can be customised. */ - text-align: right; - width: auto; -} - -.NavFrame -{ - width: 100% !important; -} - -/*#ogg_player_1 -{ - width: 100% !important; -} - -a.image img -{ - width: 100% !important; -} - - -div.thumbinner div div button -{ - width: 100% !important; -}*/ - -.multicol -{ - font-size: .8em !important; -} diff --git a/win8.1/encyclopedia/Encyclopedia/default.html b/win8.1/encyclopedia/Encyclopedia/default.html deleted file mode 100644 index 6dffb86..0000000 --- a/win8.1/encyclopedia/Encyclopedia/default.html +++ /dev/null @@ -1,34 +0,0 @@ - - - - - Encyclopedia - - - - - - - - - - - - - - - - - -
      -
      -
      -
      - - diff --git a/win8.1/encyclopedia/Encyclopedia/html/groupDetailPage.html b/win8.1/encyclopedia/Encyclopedia/html/groupDetailPage.html deleted file mode 100644 index 0741fcb..0000000 --- a/win8.1/encyclopedia/Encyclopedia/html/groupDetailPage.html +++ /dev/null @@ -1,50 +0,0 @@ - - - - - groupDetailPage - - - - - - - - - - - - - -
      -

      - -
      -
      -
      -
      - -
      -
      -
      - -
      -
      -
      - - -
      -
      - -
      -

      -
      - -
      -
      -
      -
      -
      - - diff --git a/win8.1/encyclopedia/Encyclopedia/html/groupedItemsPage.html b/win8.1/encyclopedia/Encyclopedia/html/groupedItemsPage.html deleted file mode 100644 index 7666094..0000000 --- a/win8.1/encyclopedia/Encyclopedia/html/groupedItemsPage.html +++ /dev/null @@ -1,45 +0,0 @@ - - - - - groupedItemsPage - - - - - - - - - - - - - -
      -

      -
      -
      -
      - - -
      -

      -
      -
      -
      - - -
      -
      - -

      - Encyclopedia -

      -
      -
      -
      -
      -
      - - diff --git a/win8.1/encyclopedia/Encyclopedia/html/itemDetailPage.html b/win8.1/encyclopedia/Encyclopedia/html/itemDetailPage.html deleted file mode 100644 index 2e6a292..0000000 --- a/win8.1/encyclopedia/Encyclopedia/html/itemDetailPage.html +++ /dev/null @@ -1,41 +0,0 @@ - - - - - itemDetailPage - - - - - - - - - - - - - - -
      -
      - -

      - -

      -
      -
      -
      -
      - -
      -
      -
      -
      -
      - - diff --git a/win8.1/encyclopedia/Encyclopedia/images/ep-badge.bmp b/win8.1/encyclopedia/Encyclopedia/images/ep-badge.bmp deleted file mode 100644 index d180a9c..0000000 Binary files a/win8.1/encyclopedia/Encyclopedia/images/ep-badge.bmp and /dev/null differ diff --git a/win8.1/encyclopedia/Encyclopedia/images/ep-badge.png b/win8.1/encyclopedia/Encyclopedia/images/ep-badge.png deleted file mode 100644 index e5a2612..0000000 Binary files a/win8.1/encyclopedia/Encyclopedia/images/ep-badge.png and /dev/null differ diff --git a/win8.1/encyclopedia/Encyclopedia/images/ep-logo-small.png b/win8.1/encyclopedia/Encyclopedia/images/ep-logo-small.png deleted file mode 100644 index 927483c..0000000 Binary files a/win8.1/encyclopedia/Encyclopedia/images/ep-logo-small.png and /dev/null differ diff --git a/win8.1/encyclopedia/Encyclopedia/images/ep-logo.png b/win8.1/encyclopedia/Encyclopedia/images/ep-logo.png deleted file mode 100644 index d559db4..0000000 Binary files a/win8.1/encyclopedia/Encyclopedia/images/ep-logo.png and /dev/null differ diff --git a/win8.1/encyclopedia/Encyclopedia/images/ep-splashscreen.png b/win8.1/encyclopedia/Encyclopedia/images/ep-splashscreen.png deleted file mode 100644 index 53bb89a..0000000 Binary files a/win8.1/encyclopedia/Encyclopedia/images/ep-splashscreen.png and /dev/null differ diff --git a/win8.1/encyclopedia/Encyclopedia/images/ep-storelogo.png b/win8.1/encyclopedia/Encyclopedia/images/ep-storelogo.png deleted file mode 100644 index 34f3626..0000000 Binary files a/win8.1/encyclopedia/Encyclopedia/images/ep-storelogo.png and /dev/null differ diff --git a/win8.1/encyclopedia/Encyclopedia/images/ep-widetile.png b/win8.1/encyclopedia/Encyclopedia/images/ep-widetile.png deleted file mode 100644 index 216dddc..0000000 Binary files a/win8.1/encyclopedia/Encyclopedia/images/ep-widetile.png and /dev/null differ diff --git a/win8.1/encyclopedia/Encyclopedia/js/data.ts b/win8.1/encyclopedia/Encyclopedia/js/data.ts deleted file mode 100644 index dee0dea..0000000 --- a/win8.1/encyclopedia/Encyclopedia/js/data.ts +++ /dev/null @@ -1,117 +0,0 @@ -/// -/// -/// - -module Data { - "use strict"; - - export interface UserData { - favorites: string[]; - recent: string[]; - today: string[]; - } - - export interface Group { - key: string; - title: string; - } - - interface Groups { - [idx: string]: Group; - } - - var groupsHash = ({ - recent: { key: 'recent', title: 'Recent' }, - favorites: { key: 'favorites', title: 'Favorites' }, - today: { key: 'today', title: 'Today' }, - nearby: { key: 'xxnearby', title: 'Nearby' } - }); - - var list = new WinJS.Binding.List([]); - - function saveUserData() { - Windows.Storage.ApplicationData.current.localSettings.values["userdata"] = JSON.stringify(userData); - } - - var userdatastring: string = Windows.Storage.ApplicationData.current.localSettings.values["userdata"]; - var userData: UserData; - //if (userdatastring != null) { - // userData = JSON.parse(userdatastring); - //} else { - userData = { - favorites: ['Topology', 'Windows 8', 'Windows Phone 7'], - recent: ['Einstein', 'Quantum Field Theory', 'Einstein Field Equations', 'Macleay\'s Swallowtail', 'Gödel metric'], - today: ['Transformers', 'XBox', 'Mount Rainier', 'Independence Day (film)', 'Independence Day', 'Roland Emmerich', 'Padmanabhaswamy Temple'] - }; - saveUserData(); - //} - Object.keys(userData).forEach(function (groupName) { - msSetImmediate(function () { populate(groupName, userData[groupName]); }); - }); - - function populate(groupName: string, itemTitles: string[]) { - for (var i = 0; i < itemTitles.length; i++) { - list.push(createTopicFromTitle(itemTitles[i], groupsHash[groupName])); - } - } - var locator = new Windows.Devices.Geolocation.Geolocator(); - locator.getGeopositionAsync().then(function (pos) { - var lat = pos.coordinate.latitude; - var long = pos.coordinate.longitude; - var url = 'http://api.wikilocation.org/articles?radius=100000&limit=10&lat=' + lat + '&lng=' + long; - return WinJS.xhr({ url: url }); - }).then(function (xhr) { - var data = JSON.parse(xhr.responseText); - addTopicsToGroup(data.articles, groupsHash['nearby']); - }).done(); - - function addTopicsToGroup(articles: { title: string; }[], group: Data.Group) { - articles.forEach(function (article) { - msSetImmediate(function () { - list.push(createTopicFromTitle(article.title, group)); - }); - }); - } - - export function addFavorite(title: string) { - if (userData.favorites.indexOf(title) == -1) { - userData.favorites.push(title); - saveUserData(); - var topic = createTopicFromTitle(title, groupsHash['favorites']) - list.push(topic); - Encyclopedia.addToTile(title, topic.localImageSrc); - } - } - - export function removeFavorite(title: string) { - var i = userData.favorites.indexOf(title); - if (i != -1) { - userData.favorites.splice(i, 1); - saveUserData(); - var j = list.indexOf(createTopicFromTitle(title, groupsHash['favorites'])); - if (j != -1) { - list.splice(j, 1); - } - } - } - - var groupedItems = list.createGrouped(groupKeySelector, groupDataSelector); - - function groupKeySelector(item) { - return item.group.key; - } - - function groupDataSelector(item) { - return item.group; - } - - export function getItemsFromGroup(group: Group) { - return list.createFiltered(function (item) { return item.group.key === group.key; }); - } - - export var items = groupedItems; - export var groups = groupedItems.groups; - export function getItemReference(item) { - return [item.group.key, item.title]; - } -} diff --git a/win8.1/encyclopedia/Encyclopedia/js/default.ts b/win8.1/encyclopedia/Encyclopedia/js/default.ts deleted file mode 100644 index 5bad58c..0000000 --- a/win8.1/encyclopedia/Encyclopedia/js/default.ts +++ /dev/null @@ -1,82 +0,0 @@ -/// -/// - -module Default { - "use strict"; - - var app = WinJS.Application; - var activation = Windows.ApplicationModel.Activation; - var nav = WinJS.Navigation; - //WinJS.strictProcessing(); - - var searchPane = Windows.ApplicationModel.Search.SearchPane.getForCurrentView(); - searchPane.onquerysubmitted = function (ev: Windows.ApplicationModel.Search.ISearchPaneQuerySubmittedEventArgs) { - var topic = createTopicFromTitle(ev.queryText, null); - WinJS.Navigation.navigate('/html/itemDetailPage.html', { item: topic }); - } - - searchPane.onsuggestionsrequested = function (ev: Windows.ApplicationModel.Search.SearchPaneSuggestionsRequestedEventArgs) { - var deferral = ev.request.getDeferral(); - var url = 'http://en.wikipedia.org/w/api.php?action=opensearch&limit=20&search=' - + encodeURI(ev.queryText); - WinJS.xhr({ url: url }).then(function (xhr) { - var data = JSON.parse(xhr.response); - ev.request.searchSuggestionCollection.appendQuerySuggestions(data[1]); - deferral.complete(); - }); - } - - var settingsPane = Windows.UI.ApplicationSettings.SettingsPane.getForCurrentView(); - settingsPane.oncommandsrequested = function (ev: Windows.UI.ApplicationSettings.SettingsPaneCommandsRequestedEventArgs) { - ev.request.applicationCommands.push(new Windows.UI.ApplicationSettings.SettingsCommand("1", "Encyclopedia Settings", function (a) { - var panel = document.getElementById('KnownSettingsCommand.Preferences'); - WinJS.UI.process(panel); - })); - }; - - app.addEventListener("activated", function (args: WinJS.Application.ApplicationActivationEvent) { - if (args.detail.kind === activation.ActivationKind.launch) { - var launchEv = args.detail; - - if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) { - // TODO: This application has been newly launched. Initialize - // your application here. - } else { - // TODO: This application has been reactivated from suspension. - // Restore application state here. - } - - if (app.sessionState.history) { - nav.history = app.sessionState.history; - } - args.setPromise(WinJS.UI.processAll().then(function () { - if (nav.location) { - nav.history.current.initialPlaceholder = true; - return nav.navigate(nav.location, nav.state); - } else { - if (launchEv.arguments !== '') { - var topic = createTopicFromTitle(launchEv.arguments, null); - nav.navigate('/html/itemDetailPage.html', { item: topic }); - } else { - return nav.navigate(Encyclopedia.navigator.home); - } - } - })); - } else if (args.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.search) { - var searchEv = args.detail; - WinJS.UI.processAll(); - var topic = createTopicFromTitle(searchEv.queryText, null); - WinJS.Navigation.navigate('/html/itemDetailPage.html', { item: topic }); - } - }); - - app.oncheckpoint = function (args) { - // TODO: This application is about to be suspended. Save any state - // that needs to persist across suspensions here. If you need to - // complete an asynchronous operation before your application is - // suspended, call args.setPromise(). - app.sessionState.history = nav.history; - }; - - app.start(); -} diff --git a/win8.1/encyclopedia/Encyclopedia/js/groupDetailPage.ts b/win8.1/encyclopedia/Encyclopedia/js/groupDetailPage.ts deleted file mode 100644 index e36a930..0000000 --- a/win8.1/encyclopedia/Encyclopedia/js/groupDetailPage.ts +++ /dev/null @@ -1,76 +0,0 @@ -/// -/// - -module GroupDetailPage { - "use strict"; - - var nav = WinJS.Navigation; - var ui = WinJS.UI; - var utils = WinJS.Utilities; - var views = Windows.UI.ViewManagement; - var group: Data.Group; - var items; - - function updateLayout(element: HTMLElement) { - var listView = element.querySelector(".groupList").winControl; - - if (views.ApplicationView.value === views.ApplicationViewState.snapped) { - listView.layout = new ui.ListLayout(); - } else { - listView.layout = new ui.GridLayout({ groupHeaderPosition: "left" }); - } - } - - function ready(element: HTMLElement, options: { group: Data.Group; }) { - group = (options && options.group) ? options.group : Data.groups.getAt(0); - items = Data.getItemsFromGroup(group); - var pageList = items.createGrouped( - function (item) { return group.key; }, - function (item) { return group; } - ); - var groupDataSource = pageList.groups.dataSource; - - element.querySelector("header[role=banner] .win-type-xx-large").textContent = group.title; - setupMenu(element); - - var listView = element.querySelector(".groupList").winControl; - ui.setOptions(listView, { - itemDataSource: pageList.dataSource, - itemTemplate: element.querySelector(".itemTemplate"), - groupDataSource: pageList.groups.dataSource, - groupHeaderTemplate: element.querySelector(".headerTemplate"), - oniteminvoked: itemInvoked - }); - } - - function itemInvoked(e) { - var item = items.getAt(e.detail.itemIndex); - nav.navigate("/html/itemDetailPage.html", { item: item }); - } - - function setupMenu(element: HTMLElement) { - var commandList = []; - Data.groups.forEach(function (group) { - commandList.push({ - label: group.title, onclick: function () { - nav.navigate("/html/groupDetailPage.html", { group: group }); - } - }); - }); - - var menu = new ui.Menu(element.querySelector("header[role=banner] .menu"), { commands: commandList }); - var title = element.querySelector(".titleArea .win-type-xx-large"); - - title.onclick = function (eventObject) { menu.show(title, "bottom", "left"); }; - title.onkeypress = function (eventObject) { - if (eventObject.keyCode === utils.Key.enter || eventObject.keyCode === utils.Key.space) { - menu.show(title, "bottom", "left"); - } - }; - } - - ui.Pages.define("/html/groupDetailPage.html", { - ready: ready, - updateLayout: updateLayout - }); -} diff --git a/win8.1/encyclopedia/Encyclopedia/js/groupedItemsPage.ts b/win8.1/encyclopedia/Encyclopedia/js/groupedItemsPage.ts deleted file mode 100644 index 97ab53d..0000000 --- a/win8.1/encyclopedia/Encyclopedia/js/groupedItemsPage.ts +++ /dev/null @@ -1,163 +0,0 @@ -/// -/// - -module GroupedItemsPage { - "use strict"; - - var appView = Windows.UI.ViewManagement.ApplicationView; - var appViewState = Windows.UI.ViewManagement.ApplicationViewState; - var nav = WinJS.Navigation; - var ui = WinJS.UI; - var utils = WinJS.Utilities; - - ui.Pages.define("/html/groupedItemsPage.html", { - - // This function updates the ListView with new layouts - initializeLayout: function (listView, viewState) { - - if (viewState === appViewState.snapped) { - listView.itemDataSource = Data.groups.dataSource; - listView.groupDataSource = null; - listView.layout = new ui.ListLayout(); - } else { - listView.itemDataSource = Data.items.dataSource; - listView.groupDataSource = Data.groups.dataSource; - listView.layout = new ui.GridLayout({ groupHeaderPosition: "top" }); - } - }, - - itemInvoked: function (args) { - if (appView.value === appViewState.snapped) { - // If the page is snapped, the user invoked a group. - var group = Data.groups.getAt(args.detail.itemIndex); - nav.navigate("/html/groupDetailPage.html", { groupKey: group.key }); - } else { - // If the page is not snapped, the user invoked an item. - var item = Data.items.getAt(args.detail.itemIndex); - nav.navigate("/html/itemDetailPage.html", { item: item }); - } - }, - - // This function is called whenever a user navigates to this page. It - // populates the page elements with the app's data. - ready: function (element, options) { - var listView = element.querySelector(".groupeditemslist").winControl; - listView.groupHeaderTemplate = element.querySelector(".headerTemplate"); - listView.itemTemplate = element.querySelector(".itemtemplate"); - listView.oniteminvoked = this.itemInvoked.bind(this); - - var appbarControl = ( document.querySelector('#appbar')).winControl; - appbarControl.hideCommands(['addfavorite', 'removefavorite', 'pin']); - - this.initializeLayout(listView, appView.value); - listView.element.focus(); - }, - - // This function updates the page layout in response to viewState changes. - updateLayout: function (element, viewState, lastViewState) { - - var listView = element.querySelector(".groupeditemslist").winControl; - if (lastViewState !== viewState) { - if (lastViewState === appViewState.snapped || viewState === appViewState.snapped) { - var handler: (e: Event) => void = function (e) { - listView.removeEventListener("contentanimating", handler, false); - e.preventDefault(); - } - listView.addEventListener("contentanimating", handler, false); - this.initializeLayout(listView, viewState); - } - } - } - }); - - - - //"use strict"; - - //var appView = Windows.UI.ViewManagement.ApplicationView; - //var appViewState = Windows.UI.ViewManagement.ApplicationViewState; - //var nav = WinJS.Navigation; - //var ui = WinJS.UI; - //var utils = WinJS.Utilities; - - //function updateLayout(element: HTMLElement) { - // var listView = element.querySelector(".landingList").winControl; - // if (appLayout.value === appLayoutState.snapped) { - // ui.setOptions(listView, { - // itemDataSource: data.items.dataSource, - // itemTemplate: element.querySelector(".itemTemplate"), - // groupDataSource: null, - // oniteminvoked: itemInvoked - // }); - - // listView.layout = new ui.ListLayout(); - // } else { - // var groupDataSource = data.items.createGrouped(groupKeySelector, groupDataSelector).groups; - - // ui.setOptions(listView, { - // itemDataSource: data.items.dataSource, - // itemTemplate: element.querySelector(".itemTemplate"), - // groupDataSource: groupDataSource.dataSource, - // groupHeaderTemplate: element.querySelector(".headerTemplate"), - // oniteminvoked: itemInvoked - // }); - // listView.layout = new ui.GridLayout({ groupHeaderPosition: "top" }); - // } - //} - - //function groupKeySelector(item) { - // return item.group.key; - //} - - //function groupDataSelector(item) { - // return { - // title: item.group.title, - // click: function () { - // nav.navigate("/html/groupDetailPage.html", { group: item.group }); - // } - // } - //} - - //function ready(element: HTMLElement, options) { - // var appbarControl = ( document.querySelector('#appbar')).winControl; - // appbarControl.hideCommands(['addfavorite', 'removefavorite', 'pin']); - - // setupMenu(element); - //} - - //function itemInvoked(e: {detail: {itemIndex: number; }; }) { - // //if (appLayout.value === appLayoutState.snapped) { - // // var group = data.groups.getAt(e.detail.itemIndex); - // // nav.navigate("/html/groupDetailPage.html", { group: group }); - // //} else { - // var item = data.items.getAt(e.detail.itemIndex); - // nav.navigate("/html/itemDetailPage.html", { item: item }); - // //} - //} - - //function setupMenu(element: HTMLElement) { - // var commandList = []; - // //data.groups.forEach(function (group) { - // // commandList.push({ - // // label: group.title, onclick: function () { - // // nav.navigate("/html/groupDetailPage.html", { group: group }); - // // } - // // }); - // //}); - - // var menu = new ui.Menu(element.querySelector("header[role=banner] .menu"), { commands: commandList }); - // var title = element.querySelector(".titleArea .win-type-xx-large"); - - // //title.onclick = function (eventObject) { menu.show(title, "bottom", "left"); }; - // //title.onkeypress = function (eventObject) { - // // if (eventObject.keyCode === utils.Key.enter || eventObject.keyCode === utils.Key.space) { - // // menu.show(title, "bottom", "left"); - // // } - // //}; - //} - - //ui.Pages.define("/html/groupedItemsPage.html", { - // ready: ready, - // updateLayout: updateLayout - //}); -} diff --git a/win8.1/encyclopedia/Encyclopedia/js/itemDetailPage.ts b/win8.1/encyclopedia/Encyclopedia/js/itemDetailPage.ts deleted file mode 100644 index 3aec0cd..0000000 --- a/win8.1/encyclopedia/Encyclopedia/js/itemDetailPage.ts +++ /dev/null @@ -1,88 +0,0 @@ -/// -/// -/// - -module ItemDetailPage { - "use strict"; - - var ui = WinJS.UI; - var utils = WinJS.Utilities; - - function ready(element: HTMLElement, options: { item: Topic; }) { - - var item: Topic = options && options.item ? options.item : Data.items.getAt(0); - element.querySelector(".titlearea .pagetitle").textContent = item.title; - var content = element.querySelector('.content'); - goToPage(content, item); - document.body.focus(); - setupMenu(element); - - var appbarControl = document.querySelector('#appbar').winControl; - appbarControl.showCommands(['addfavorite', 'removefavorite', 'pin']); - var pin = appbarControl.getCommandById('pin'); - pin.onclick = function handler() { - var uri = new Windows.Foundation.Uri("ms-appdata:///local/" + item.localImageSrc); - var tile = new Windows.UI.StartScreen.SecondaryTile(); - tile.tileId = encodeURIComponent(item.title); - tile.displayName = item.title; - tile.shortName = item.title; - tile.arguments = item.title; - tile.tileOptions = Windows.UI.StartScreen.TileOptions.showNameOnLogo; - tile.logo = uri; - tile.foregroundText = Windows.UI.StartScreen.ForegroundText.light; - tile.requestCreateAsync().done(); - } - } - - function setupMenu(elements: Element) { - var commandList = []; - var menu = new ui.Menu(elements.querySelector('header[role=banner] .menu'), { commands: commandList }); - var title = elements.querySelector('.titleArea .win-type-xx-large'); - } - - - function goToPage(rootElem: HTMLElement, topic: Topic) { - - topic.htmlContent.done(function(bodyInnerText: string) { - //document.querySelector(".win-contentTitle").innerText = topic.title; - MSApp.execUnsafeLocalFunction(function() { - rootElem.innerHTML = toStaticHTML(bodyInnerText); - Array.prototype.forEach.call(rootElem.querySelectorAll('*[href]'), function(a: HTMLAnchorElement) { - a.addEventListener("click", function(ev) { - //console.log("Clicked: " + ev.target + ", " + ev.currentTarget.href); - ev.preventDefault(); - var url = a.href; - if (url.indexOf('ms-appx:') == 0) { - var i = a.href.lastIndexOf('\/'); - var topicRef = decodeURIComponent(a.href.slice(i + 1)).replace(/_/g, " "); - var topic = createTopicFromTitle(topicRef, null); - WinJS.Navigation.navigate("/html/itemDetailPage.html", { item: topic }); - } - else { - var dialog = new Windows.UI.Popups.MessageDialog("This link will take you to an external page. Would you like to launch the browser?", "Open external browser?"); - dialog.commands.push(new Windows.UI.Popups.UICommand("launch browser", function() { - // External page - Windows.System.Launcher.launchUriAsync(new Windows.Foundation.Uri(url)).done(); - })); - dialog.commands.push(new Windows.UI.Popups.UICommand("cancel", function() { })); - dialog.showAsync().done(); - } - }) - }); - }); - - }, noInternetConnection); - } - - function refreshCurrent(element: Element) { - var title = element.querySelector(".itemDetailPage header[role=banner] .pagetitle").textContent; - var topic = createTopicFromTitle(title, null); - downloadAndCacheLocally(topic); - goToPage(element.querySelector('.content'), topic); - } - - ui.Pages.define("/html/itemDetailPage.html", { - ready: ready, - refreshCurrent: refreshCurrent - }); -} diff --git a/win8.1/encyclopedia/Encyclopedia/js/navigator.ts b/win8.1/encyclopedia/Encyclopedia/js/navigator.ts deleted file mode 100644 index 640e66b..0000000 --- a/win8.1/encyclopedia/Encyclopedia/js/navigator.ts +++ /dev/null @@ -1,194 +0,0 @@ -/// -/// - -module Encyclopedia { - "use strict"; - - var appView = Windows.UI.ViewManagement.ApplicationView; - var displayProps = Windows.Graphics.Display.DisplayProperties; - var nav = WinJS.Navigation; - var ui = WinJS.UI; - var utils = WinJS.Utilities; - - export var navigator: PageControlNavigator = null; - - export class PageControlNavigator { - - public element = null; - public home = ""; - public lastViewstate = 0; - - // Define the constructor function for the PageControlNavigator. - constructor(element: Element, options: { home: string; }) { - this.element = (element || document.createElement("div")); - this.element.appendChild(this._createPageElement()); - - this.home = options.home; - this.lastViewstate = appView.value; - - nav.onnavigated = this._navigated.bind(this); - window.onresize = this._resized.bind(this); - - document.body.onkeyup = this._keyupHandler.bind(this); - document.body.onkeypress = this._keypressHandler.bind(this); - document.body.onmspointerup = this._mspointerupHandler.bind(this); - - Encyclopedia.navigator = this; - } - - private get pageControl() { return this.pageElement && this.pageElement.winControl; } - private get pageElement() { return this.element.firstElementChild; } - - // This function creates a new container for each page. - private _createPageElement() { - var element = document.createElement("div"); - element.style.width = "100%"; - element.style.height = "100%"; - return element; - } - - // This function responds to keypresses to only navigate when - // the backspace key is not used elsewhere. - private _keypressHandler(args) { - if (args.key === "Backspace") { - nav.back(); - } - } - - private _keyupHandler(args) { - if ((args.key === "Left" && args.altKey) || (args.key === "BrowserBack")) { - nav.back(); - } else if ((args.key === "Right" && args.altKey) || (args.key === "BrowserForward")) { - nav.forward(); - } - } - - private _mspointerupHandler(args) { - if (args.button === 3) { - nav.back(); - } else if (args.button === 4) { - nav.forward(); - } - } - - private _fwdbackHandler(e: KeyboardEvent) { - if (e.altKey) { - switch (e.keyCode) { - case utils.Key.leftArrow: nav.back(); break; - case utils.Key.rightArrow: nav.forward(); break; - } - } - } - - //private _viewstatechanged(e) { - // this._updateLayout()(this.pageElement, e.layout, displayProps.currentOrientation); - //} - - // This function responds to navigation by adding new pages - // to the DOM. - private _navigated(args) { - var oldElement = this.pageElement; - var newElement = this._createPageElement(); - var parentedComplete; - var parented = new WinJS.Promise(function(c) { parentedComplete = c; }); - - args.detail.setPromise( - WinJS.Promise.timeout().then(function() { - if (oldElement.winControl && oldElement.winControl.unload) { - oldElement.winControl.unload(); - } - return WinJS.UI.Pages.render(args.detail.location, newElement, args.detail.state, parented); - }).then((control) => { - this.element.appendChild(newElement); - this.element.removeChild(oldElement); - oldElement.innerText = ""; - this.navigated(); - parentedComplete(); - }) - ); - } - - private _resized(args) { - if (this.pageControl && this.pageControl.updateLayout) { - this.pageControl.updateLayout.call(this.pageControl, this.pageElement, appView.value, this.lastViewstate); - } - this.lastViewstate = appView.value; - } - - //private _updateLayout() { return (this.pageControl() && this.pageControl().updateLayout) || function() { }; } - - // This function updates application controls once a navigation - // has completed. - public navigated() { - // Do application specific on-navigated work here - var backButton = this.pageElement.querySelector("header[role=banner] .win-backbutton"); - if (backButton != null) { - backButton.onclick = function() { nav.back(); }; - - if (nav.canGoBack) { - backButton.removeAttribute("disabled"); - } - else { - backButton.setAttribute("disabled", "disabled"); - } - } - } - - } - WinJS.Utilities.markSupportedForProcessing(PageControlNavigator); - - export function navigateHome() { - var home = document.querySelector("#contenthost").winControl.home; - var loc = nav.location; - if (loc !== "" && loc !== home) { - nav.navigate(home); - } - } - WinJS.Utilities.markSupportedForProcessing(navigateHome); - - export function refresh() { - var control = (document.querySelector("#contenthost")).winControl; - if (control && control.pageControl && control.pageControl.refreshCurrent) { - control.pageControl.refreshCurrent(control.element); - } - } - WinJS.Utilities.markSupportedForProcessing(refresh); - - export function addFavorite() { - var control = (document.querySelector("#contenthost")).winControl; - if (control && control.pageControl && control.pageControl.refreshCurrent) { - var elem: Element = control.element.querySelector(".itemDetailPage header[role=banner] .pagetitle"); - var title = elem.textContent; - Data.addFavorite(title); - } - } - WinJS.Utilities.markSupportedForProcessing(addFavorite); - - export function removeFavorite() { - var control = (document.querySelector("#contenthost")).winControl; - if (control && control.pageControl && control.pageControl.refreshCurrent) { - var title = control.element.querySelector(".itemDetailPage header[role=banner] .pagetitle").textContent; - Data.removeFavorite(title); - } - } - WinJS.Utilities.markSupportedForProcessing(removeFavorite); - - export function addToTile(text: string, imgSrc: string) { - var tileUpdater = Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication(); - var template = Windows.UI.Notifications.TileTemplateType.tileWideImageAndText01; - var tileXml = Windows.UI.Notifications.TileUpdateManager.getTemplateContent(template); - var tileTextAttributes = tileXml.getElementsByTagName("text"); - tileTextAttributes.forEach(function(value, index) { - value.appendChild(tileXml.createTextNode("textField " + (index + 1))); - }); - var tileImageAttributes = tileXml.getElementsByTagName("image"); - var imgUri = new Windows.Foundation.Uri(Windows.Storage.ApplicationData.current.localFolder.path + "/").combineUri(imgSrc); - var elem = tileImageAttributes.getAt(0); - elem.setAttribute("src", imgUri.absoluteUri); - elem.setAttribute("alt", "graphic"); - elem.setAttribute("id", "1"); - var tileNotification = new Windows.UI.Notifications.TileNotification(tileXml); - tileUpdater.enableNotificationQueue(true); - tileUpdater.update(tileNotification); - } -} \ No newline at end of file diff --git a/win8.1/encyclopedia/Encyclopedia/js/topic.ts b/win8.1/encyclopedia/Encyclopedia/js/topic.ts deleted file mode 100644 index 0625335..0000000 --- a/win8.1/encyclopedia/Encyclopedia/js/topic.ts +++ /dev/null @@ -1,180 +0,0 @@ -/// -/// - -interface Topic { - group: any; - title: string; - imageSrc: string; - localImageSrc: string; - htmlContent: any; -} - -var topiccache: { [name: string]: Topic } = {}; - -function createTopicFromUrl(url: string, group: Data.Group): Topic { - var encodedName = url.slice(url.lastIndexOf('/') + 1); - var title = decodeURIComponent(encodedName).replace('_', ' '); - return createTopicFromTitle(title, group); -} - -function downloadImageAndStoreLocal(bodyInnerText: string, topic: Topic) { - var imageSrc = findImage(bodyInnerText); - WinJS.xhr({ url: imageSrc, responseType: "blob" }).then(function (xhr) { - var blob = xhr.response; - topic.imageSrc = URL.createObjectURL(blob); - var encodedImageUri = imageSrc.slice(imageSrc.lastIndexOf('/') + 1); - topic.localImageSrc = encodedImageUri; - Windows.Storage.ApplicationData.current.localFolder.createFileAsync(encodedImageUri, Windows.Storage.CreationCollisionOption.replaceExisting).then(function (file) { - file.openAsync(Windows.Storage.FileAccessMode.readWrite).then(function (ras) { - var inputStream = blob.msDetachStream().getInputStreamAt(0); - var outputStream = ras.getOutputStreamAt(0); - Windows.Storage.Streams.RandomAccessStream.copyAsync(inputStream, outputStream).then(function () { - inputStream.close(); - return outputStream.flushAsync(); - }).done(); - }).then(function () { - Windows.Storage.ApplicationData.current.localSettings.values[topic.title + "image"] = encodedImageUri; - }); - }); - }); -} - -function createTopicFromTitle(title: string, group: Data.Group): Topic { - var topic = topiccache[title + "--" + (group && group.title)]; - if (topic) - return topic; - - // Create the topic as a databindable object - topic = WinJS.Binding.as({ - group: group, - title: title, - imageSrc: null, - localImageSrc: null - }); - - // Kick off the work to aquire the HTML content - var url = "http://en.wikipedia.org/w/index.php?title=" + encodeURI(title); - - var htmlContentPromise: WinJS.Promise; - var localContent = Windows.Storage.ApplicationData.current.localSettings.values[title]; - - // - htmlContentPromise = localContent ? retrieveCached(topic) : downloadAndCacheLocally(topic); - - // Don't want the topic to be tracked by the observable (TODO: I'm sure there is a 'better' way to do this) - topic.htmlContent = htmlContentPromise; - - topiccache[title + "--" + (group && group.title)] = topic; - return topic; -} - -function retrieveCached(topic: Topic) { - // If content is already available locally: - // 1) set the htmlContentPromise to read it from disk - // 2) in parallel, grab the image from disk and display it. - var title = topic.title; - var encodedTitle = encodeURIComponent(title); - var htmlContentPromise = WinJS.Application.local.readText(encodedTitle + ".html"); - var localImageSrc = Windows.Storage.ApplicationData.current.localSettings.values[title + "image"]; - topic.localImageSrc = localImageSrc; - - Windows.Storage.ApplicationData.current.localFolder.getFileAsync(localImageSrc) - .then(function (file) { - return file.openAsync(Windows.Storage.FileAccessMode.read); - }).then(function (ras) { - var blob = MSApp.createBlobFromRandomAccessStream("image/png", ras); - topic.imageSrc = URL.createObjectURL(blob); - }).then(null, function (err) { - // The image file wasn't available for some reason, - // retry downloading the image. - return htmlContentPromise.then(function (bodyInnerHtml) { - downloadImageAndStoreLocal(bodyInnerHtml, topic); - }); - }).done(); - - return htmlContentPromise; -} - -function downloadAndCacheLocally(topic: Topic) { - // If content is *not* already available locally, set htmlContentPromise to do the following: - // 1) read it from the network - // 2) then write it to local disk - // 2.5) also record in local settings that it is stored locally - // 3) find the associated image - // 4) set that as the databound imageSrc - // 5) write the image to disk - // 5.5) also record in local settings that it is stored locally - var title = topic.title; - var url = "http://en.wikipedia.org/w/index.php?title=" + encodeURI(title); - var htmlContentPromise = WinJS.xhr({ url: url }) - .then(function (result) { - var text = result.response; - var bodyStartStart = text.indexOf("", bodyStartStart) + 1; - var bodyEndStart = text.indexOf(""); - text = text.slice(bodyStartEnd, bodyEndStart); - text = text.replace(/"\/\//g, '"http://'); - return text; - }); - - var encodedTitle = encodeURIComponent(title); - - var bodyInnerText: string = null; - htmlContentPromise.then(function (innerText) { - bodyInnerText = innerText; - // Store text to local storage - return WinJS.Application.local.writeText(encodedTitle + ".html", bodyInnerText); - }).then(function () { - Windows.Storage.ApplicationData.current.localSettings.values[title] = encodedTitle + ".html"; - // Download the image and store to local storage - return downloadImageAndStoreLocal(bodyInnerText, topic); - }).done(null, function (err) { - if (err instanceof XMLHttpRequest) { - return; - } else { - throw err; - } - }); - return htmlContentPromise; -} - -function findImage(bodyHtml: string) { - var dummyDiv = document.createElement('div'); - dummyDiv.innerHTML = toStaticHTML(bodyHtml); - var imgs: HTMLImageElement[] = Array.prototype.slice.call(dummyDiv.getElementsByTagName('img'), 0); - imgs = imgs.filter(function (img) { - var widthAttr = img.attributes["width"]; - if (!widthAttr) return false; - var keep = (+widthAttr.value) > 100; - return keep; - }); - imgs.forEach(function (img, i) { - img.attributes["width"].value *= (1 - (i / imgs.length) / 2); - img.attributes["height"].value *= (1 - (i / imgs.length) / 2); - }); - imgs.sort(function (img1, img2) { - var awidth = +img1.attributes["width"].value; - var aheight = +img1.attributes["height"].value; - var bwidth = +img2.attributes["width"].value; - var bheight = +img2.attributes["height"].value; - return Math.min(bwidth, bheight) - Math.min(awidth, aheight); - }); - var jpgs = imgs.filter(function (img) { - var s = img.src; - if (s.slice(s.length - 4) == ".jpg" || s.slice(s.length - 5) == ".jpeg") - return true; - return false; - }); - if (jpgs.length > 0 && (+jpgs[0].attributes["width"].value > 100) && (+jpgs[0].attributes["height"].value > 100)) { - return jpgs[0].src; - } else if (imgs.length > 0) { - return (imgs[0]).src; - } else { - return "http://upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png"; - } -} - -function noInternetConnection(err) { - var flyout = new Windows.UI.Popups.MessageDialog("No internet connection"); - flyout.showAsync().done(); -} diff --git a/win8.1/encyclopedia/Encyclopedia/js/typings/winjs.d.ts b/win8.1/encyclopedia/Encyclopedia/js/typings/winjs.d.ts deleted file mode 100644 index 5d82286..0000000 --- a/win8.1/encyclopedia/Encyclopedia/js/typings/winjs.d.ts +++ /dev/null @@ -1,208 +0,0 @@ -/* ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -declare module WinJS { - function strictProcessing(): void; - module Binding { - function as(data: any): any; - class List { - constructor(data: any[]); - public push(item: any): any; - public indexOf(item: any): number; - public splice(index: number, count: number, newelems: any[]): any[]; - public splice(index: number, count: number): any[]; - public splice(index: number): any[]; - public createFiltered(predicate: (x: any) => boolean): List; - public createGrouped(keySelector: (x: any) => any, dataSelector: (x: any) => any): List; - public groups: any; - public dataSource: any; - public getAt: any; - } - } - module Namespace { - var define: any; - var defineWithParent: any; - } - module Class { - function define(constructor: any, instanceMembers: any): any; - function derive(baseClass: any, constructor: any, instanceMembers: any): any; - function mix(constructor: any, mixin: any): any; - } - function xhr(options: { type?: string; url?: string; user?: string; password?: string; headers?: any; data?: any; responseType?: string; }): WinJS.Promise; - module Application { - interface IOHelper { - exists(filename: string): boolean; - readText(fileName: string, def: string): WinJS.Promise; - readText(fileName: string): WinJS.Promise; - writeText(fileName: string, text: string): WinJS.Promise; - remove(fileName: string): WinJS.Promise; - } - var local: IOHelper; - var roaming: IOHelper; - var onactivated: EventListener; - var sessionState: any; - interface ApplicationActivationEvent extends Event { - detail: any; - setPromise(p: Promise): any; - } - function addEventListener(type: string, listener: EventListener, capture?: boolean): void; - var oncheckpoint: EventListener; - function start(): void; - function stop(): void; - } - class Promise { - constructor(init: (c: any, e: any, p: any) => void); - then(success?: (value: T) => Promise, error?: (error: any) => Promise, progress?: (progress: any) => void): Promise; - then(success?: (value: T) => Promise, error?: (error: any) => U, progress?: (progress: any) => void): Promise; - then(success?: (value: T) => U, error?: (error: any) => Promise, progress?: (progress: any) => void): Promise; - then(success?: (value: T) => U, error?: (error: any) => U, progress?: (progress: any) => void): Promise; - done(success?: (value: T) => any, error?: (error: any) => any, progress?: (progress: any) => void): void; - static join: any; - static timeout: any; - } - module Navigation { - var history: any; - var canGoBack: boolean; - var canGoForward: boolean; - var location: string; - var state: any; - function addEventListener(type: string, listener: EventListener, capture: boolean): void; - function back(): void; - function forward(): void; - function navigate(location: any, initialState: any); - function navigate(location: any); - function removeEventListener(type: string, listener: EventListener, capture: boolean): void; - var onbeforenavigate: CustomEvent; - var onnavigated: CustomEvent; - var onnavigating: CustomEvent; - } - module Utilities { - function markSupportedForProcessing(obj: any): void; - enum Key { - backspace, - tab, - enter, - shift, - ctrl, - alt, - pause, - capsLock, - escape, - space, - pageUp, - pageDown, - end, - home, - leftArrow, - upArrow, - rightArrow, - downArrow, - insert, - deleteKey, - num0, - num1, - num2, - num3, - num4, - num5, - num6, - num7, - num8, - num9, - a, - b, - c, - d, - e, - f, - g, - h, - i, - j, - k, - l, - m, - n, - o, - p, - q, - r, - s, - t, - u, - v, - w, - x, - y, - z, - leftWindows, - rightWindows, - numPad0, - numPad1, - numPad2, - numPad3, - numPad4, - numPad5, - numPad6, - numPad7, - numPad8, - numPad9, - multiply, - add, - subtract, - decimalPoint, - divide, - f1, - f2, - f3, - f4, - f5, - f6, - f7, - f8, - f9, - f10, - f11, - f12, - numLock, - scrollLock, - semicolon, - equal, - comma, - dash, - period, - forwardSlash, - graveAccent, - openBracket, - backSlash, - closeBracket, - singleQuote - } - } - module UI { - var process: any; - var processAll: any; - var ListLayout: any; - var GridLayout: any; - var Pages: any; - var Menu: any; - var setOptions: any; - } -} - -interface Element { - winControl: any; // TODO: This should be control? -} - diff --git a/win8.1/encyclopedia/Encyclopedia/js/typings/winrt.d.ts b/win8.1/encyclopedia/Encyclopedia/js/typings/winrt.d.ts deleted file mode 100644 index 3a9bb98..0000000 --- a/win8.1/encyclopedia/Encyclopedia/js/typings/winrt.d.ts +++ /dev/null @@ -1,14644 +0,0 @@ -/* ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -declare module Windows { - export module Foundation { - export module Collections { - export enum CollectionChange { - reset, - itemInserted, - itemRemoved, - itemChanged, - } - export interface IVectorChangedEventArgs { - collectionChange: Windows.Foundation.Collections.CollectionChange; - index: number; - } - export interface IPropertySet extends Windows.Foundation.Collections.IObservableMap, Windows.Foundation.Collections.IMap, Windows.Foundation.Collections.IIterable> { - } - export class PropertySet implements Windows.Foundation.Collections.IPropertySet, Windows.Foundation.Collections.IObservableMap, Windows.Foundation.Collections.IMap, Windows.Foundation.Collections.IIterable> { - size: number; - onmapchanged: any/* TODO */; - lookup(key: string): any; - hasKey(key: string): boolean; - getView(): Windows.Foundation.Collections.IMapView; - insert(key: string, value: any): boolean; - remove(key: string): void; - clear(): void; - first(): Windows.Foundation.Collections.IIterator>; - } - export interface IIterable { - first(): Windows.Foundation.Collections.IIterator; - } - export interface IIterator { - current: T; - hasCurrent: boolean; - moveNext(): boolean; - getMany(): { items: T[]; returnValue: number; }; - } - export interface IVectorView extends Windows.Foundation.Collections.IIterable { - size: number; - getAt(index: number): T; - indexOf(value: T): { index: number; returnValue: boolean; }; - getMany(startIndex: number): { items: T[]; returnValue: number; }; - - toString(): string; - toLocaleString(): string; - concat(...items: T[][]): T[]; - join(seperator: string): string; - pop(): T; - push(...items: T[]): void; - reverse(): T[]; - shift(): T; - slice(start: number): T[]; - slice(start: number, end: number): T[]; - sort(): T[]; - sort(compareFn: (a: T, b: T) => number): T[]; - splice(start: number): T[]; - splice(start: number, deleteCount: number, ...items: T[]): T[]; - unshift(...items: T[]): number; - lastIndexOf(searchElement: T): number; - lastIndexOf(searchElement: T, fromIndex: number): number; - every(callbackfn: (value: T, index: number, array: T[]) => boolean): boolean; - every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg: any): boolean; - some(callbackfn: (value: T, index: number, array: T[]) => boolean): boolean; - some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg: any): boolean; - forEach(callbackfn: (value: T, index: number, array: T[]) => void ): void; - forEach(callbackfn: (value: T, index: number, array: T[]) => void , thisArg: any): void; - map(callbackfn: (value: T, index: number, array: T[]) => any): any[]; - map(callbackfn: (value: T, index: number, array: T[]) => any, thisArg: any): any[]; - filter(callbackfn: (value: T, index: number, array: T[]) => boolean): T[]; - filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg: any): T[]; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => any): any; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => any, initialValue: any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => any, initialValue: any): any; - length: number; - } - export interface IVector extends Windows.Foundation.Collections.IIterable { - size: number; - getAt(index: number): T; - getView(): Windows.Foundation.Collections.IVectorView; - indexOf(value: T): { index: number; returnValue: boolean; }; - setAt(index: number, value: T): void; - insertAt(index: number, value: T): void; - removeAt(index: number): void; - append(value: T): void; - removeAtEnd(): void; - clear(): void; - getMany(startIndex: number): { items: T[]; returnValue: number; }; - replaceAll(items: T[]): void; - - toString(): string; - toLocaleString(): string; - concat(...items: T[][]): T[]; - join(seperator: string): string; - pop(): T; - push(...items: T[]): void; - reverse(): T[]; - shift(): T; - slice(start: number): T[]; - slice(start: number, end: number): T[]; - sort(): T[]; - sort(compareFn: (a: T, b: T) => number): T[]; - splice(start: number): T[]; - splice(start: number, deleteCount: number, ...items: T[]): T[]; - unshift(...items: T[]): number; - lastIndexOf(searchElement: T): number; - lastIndexOf(searchElement: T, fromIndex: number): number; - every(callbackfn: (value: T, index: number, array: T[]) => boolean): boolean; - every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg: any): boolean; - some(callbackfn: (value: T, index: number, array: T[]) => boolean): boolean; - some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg: any): boolean; - forEach(callbackfn: (value: T, index: number, array: T[]) => void ): void; - forEach(callbackfn: (value: T, index: number, array: T[]) => void , thisArg: any): void; - map(callbackfn: (value: T, index: number, array: T[]) => any): any[]; - map(callbackfn: (value: T, index: number, array: T[]) => any, thisArg: any): any[]; - filter(callbackfn: (value: T, index: number, array: T[]) => boolean): T[]; - filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg: any): T[]; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => any): any; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => any, initialValue: any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => any, initialValue: any): any; - length: number; - } - export interface IKeyValuePair { - key: K; - value: V; - } - export interface IMap extends Windows.Foundation.Collections.IIterable> { - size: number; - lookup(key: K): V; - hasKey(key: K): boolean; - getView(): Windows.Foundation.Collections.IMapView; - insert(key: K, value: V): boolean; - remove(key: K): void; - clear(): void; - } - export interface IMapView extends Windows.Foundation.Collections.IIterable> { - size: number; - lookup(key: K): V; - hasKey(key: K): boolean; - split(): { first: Windows.Foundation.Collections.IMapView; second: Windows.Foundation.Collections.IMapView; }; - } - export interface VectorChangedEventHandler { - (sender: Windows.Foundation.Collections.IObservableVector, event: Windows.Foundation.Collections.IVectorChangedEventArgs): void; - } - export interface IObservableVector extends Windows.Foundation.Collections.IVector, Windows.Foundation.Collections.IIterable { - onvectorchanged: any/* TODO */; - } - export interface IMapChangedEventArgs { - collectionChange: Windows.Foundation.Collections.CollectionChange; - key: K; - } - export interface MapChangedEventHandler { - (sender: Windows.Foundation.Collections.IObservableMap, event: Windows.Foundation.Collections.IMapChangedEventArgs): void; - } - export interface IObservableMap extends Windows.Foundation.Collections.IMap, Windows.Foundation.Collections.IIterable> { - onmapchanged: any/* TODO */; - } - } - } -} -declare module Windows { - export module Foundation { - export interface IUriRuntimeClass { - absoluteUri: string; - displayUri: string; - domain: string; - extension: string; - fragment: string; - host: string; - password: string; - path: string; - port: number; - query: string; - queryParsed: Windows.Foundation.WwwFormUrlDecoder; - rawUri: string; - schemeName: string; - suspicious: boolean; - userName: string; - equals(pUri: Windows.Foundation.Uri): boolean; - combineUri(relativeUri: string): Windows.Foundation.Uri; - } - export class WwwFormUrlDecoder implements Windows.Foundation.IWwwFormUrlDecoderRuntimeClass, Windows.Foundation.Collections.IIterable, Windows.Foundation.Collections.IVectorView { - constructor(query: string); - size: number; - getFirstValueByName(name: string): string; - first(): Windows.Foundation.Collections.IIterator; - getAt(index: number): Windows.Foundation.IWwwFormUrlDecoderEntry; - indexOf(value: Windows.Foundation.IWwwFormUrlDecoderEntry): { index: number; returnValue: boolean; }; - getMany(startIndex: number): { items: Windows.Foundation.IWwwFormUrlDecoderEntry[]; returnValue: number; }; - toString(): string; - toLocaleString(): string; - concat(...items: Windows.Foundation.IWwwFormUrlDecoderEntry[][]): Windows.Foundation.IWwwFormUrlDecoderEntry[]; - join(seperator: string): string; - pop(): Windows.Foundation.IWwwFormUrlDecoderEntry; - push(...items: Windows.Foundation.IWwwFormUrlDecoderEntry[]): void; - reverse(): Windows.Foundation.IWwwFormUrlDecoderEntry[]; - shift(): Windows.Foundation.IWwwFormUrlDecoderEntry; - slice(start: number): Windows.Foundation.IWwwFormUrlDecoderEntry[]; - slice(start: number, end: number): Windows.Foundation.IWwwFormUrlDecoderEntry[]; - sort(): Windows.Foundation.IWwwFormUrlDecoderEntry[]; - sort(compareFn: (a: Windows.Foundation.IWwwFormUrlDecoderEntry, b: Windows.Foundation.IWwwFormUrlDecoderEntry) => number): Windows.Foundation.IWwwFormUrlDecoderEntry[]; - splice(start: number): Windows.Foundation.IWwwFormUrlDecoderEntry[]; - splice(start: number, deleteCount: number, ...items: Windows.Foundation.IWwwFormUrlDecoderEntry[]): Windows.Foundation.IWwwFormUrlDecoderEntry[]; - unshift(...items: Windows.Foundation.IWwwFormUrlDecoderEntry[]): number; - lastIndexOf(searchElement: Windows.Foundation.IWwwFormUrlDecoderEntry): number; - lastIndexOf(searchElement: Windows.Foundation.IWwwFormUrlDecoderEntry, fromIndex: number): number; - every(callbackfn: (value: Windows.Foundation.IWwwFormUrlDecoderEntry, index: number, array: Windows.Foundation.IWwwFormUrlDecoderEntry[]) => boolean): boolean; - every(callbackfn: (value: Windows.Foundation.IWwwFormUrlDecoderEntry, index: number, array: Windows.Foundation.IWwwFormUrlDecoderEntry[]) => boolean, thisArg: any): boolean; - some(callbackfn: (value: Windows.Foundation.IWwwFormUrlDecoderEntry, index: number, array: Windows.Foundation.IWwwFormUrlDecoderEntry[]) => boolean): boolean; - some(callbackfn: (value: Windows.Foundation.IWwwFormUrlDecoderEntry, index: number, array: Windows.Foundation.IWwwFormUrlDecoderEntry[]) => boolean, thisArg: any): boolean; - forEach(callbackfn: (value: Windows.Foundation.IWwwFormUrlDecoderEntry, index: number, array: Windows.Foundation.IWwwFormUrlDecoderEntry[]) => void ): void; - forEach(callbackfn: (value: Windows.Foundation.IWwwFormUrlDecoderEntry, index: number, array: Windows.Foundation.IWwwFormUrlDecoderEntry[]) => void , thisArg: any): void; - map(callbackfn: (value: Windows.Foundation.IWwwFormUrlDecoderEntry, index: number, array: Windows.Foundation.IWwwFormUrlDecoderEntry[]) => any): any[]; - map(callbackfn: (value: Windows.Foundation.IWwwFormUrlDecoderEntry, index: number, array: Windows.Foundation.IWwwFormUrlDecoderEntry[]) => any, thisArg: any): any[]; - filter(callbackfn: (value: Windows.Foundation.IWwwFormUrlDecoderEntry, index: number, array: Windows.Foundation.IWwwFormUrlDecoderEntry[]) => boolean): Windows.Foundation.IWwwFormUrlDecoderEntry[]; - filter(callbackfn: (value: Windows.Foundation.IWwwFormUrlDecoderEntry, index: number, array: Windows.Foundation.IWwwFormUrlDecoderEntry[]) => boolean, thisArg: any): Windows.Foundation.IWwwFormUrlDecoderEntry[]; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Foundation.IWwwFormUrlDecoderEntry[]) => any): any; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Foundation.IWwwFormUrlDecoderEntry[]) => any, initialValue: any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Foundation.IWwwFormUrlDecoderEntry[]) => any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Foundation.IWwwFormUrlDecoderEntry[]) => any, initialValue: any): any; - length: number; - } - export class Uri implements Windows.Foundation.IUriRuntimeClass, Windows.Foundation.IUriRuntimeClassWithAbsoluteCanonicalUri { - constructor(uri: string); - constructor(baseUri: string, relativeUri: string); - absoluteUri: string; - displayUri: string; - domain: string; - extension: string; - fragment: string; - host: string; - password: string; - path: string; - port: number; - query: string; - queryParsed: Windows.Foundation.WwwFormUrlDecoder; - rawUri: string; - schemeName: string; - suspicious: boolean; - userName: string; - absoluteCanonicalUri: string; - displayIri: string; - equals(pUri: Windows.Foundation.Uri): boolean; - combineUri(relativeUri: string): Windows.Foundation.Uri; - static unescapeComponent(toUnescape: string): string; - static escapeComponent(toEscape: string): string; - } - export interface IUriRuntimeClassWithAbsoluteCanonicalUri { - absoluteCanonicalUri: string; - displayIri: string; - } - export interface IUriEscapeStatics { - unescapeComponent(toUnescape: string): string; - escapeComponent(toEscape: string): string; - } - export interface IUriRuntimeClassFactory { - createUri(uri: string): Windows.Foundation.Uri; - createUri(baseUri: string, relativeUri: string): Windows.Foundation.Uri; - } - export interface IWwwFormUrlDecoderEntry { - name: string; - value: string; - } - export interface IWwwFormUrlDecoderRuntimeClass extends Windows.Foundation.Collections.IIterable, Windows.Foundation.Collections.IVectorView { - getFirstValueByName(name: string): string; - } - export interface IWwwFormUrlDecoderRuntimeClassFactory { - createWwwFormUrlDecoder(query: string): Windows.Foundation.WwwFormUrlDecoder; - } - export interface IGetActivationFactory { - getActivationFactory(activatableClassId: string): any; - } - export interface IClosable { - close(): void; - } - export enum PropertyType { - empty, - uInt8, - int16, - uInt16, - int32, - uInt32, - int64, - uInt64, - single, - double, - char16, - boolean, - string, - inspectable, - dateTime, - timeSpan, - guid, - point, - size, - rect, - otherType, - uInt8Array, - int16Array, - uInt16Array, - int32Array, - uInt32Array, - int64Array, - uInt64Array, - singleArray, - doubleArray, - char16Array, - booleanArray, - stringArray, - inspectableArray, - dateTimeArray, - timeSpanArray, - guidArray, - pointArray, - sizeArray, - rectArray, - otherTypeArray, - } - export interface Point { - x: number; - y: number; - } - export interface Size { - width: number; - height: number; - } - export interface Rect { - x: number; - y: number; - width: number; - height: number; - } - export interface DateTime { - universalTime: number; - } - export interface TimeSpan { - duration: number; - } - export interface IPropertyValue { - isNumericScalar: boolean; - type: Windows.Foundation.PropertyType; - getUInt8(): number; - getInt16(): number; - getUInt16(): number; - getInt32(): number; - getUInt32(): number; - getInt64(): number; - getUInt64(): number; - getSingle(): number; - getDouble(): number; - getChar16(): string; - getBoolean(): boolean; - getString(): string; - getGuid(): string; - getDateTime(): Date; - getTimeSpan(): number; - getPoint(): Windows.Foundation.Point; - getSize(): Windows.Foundation.Size; - getRect(): Windows.Foundation.Rect; - getUInt8Array(): Uint8Array; - getInt16Array(): Int16Array; - getUInt16Array(): Uint16Array; - getInt32Array(): Int32Array; - getUInt32Array(): Uint32Array; - getInt64Array(): number[]; - getUInt64Array(): number[]; - getSingleArray(): Float32Array; - getDoubleArray(): Float64Array; - getChar16Array(): string[]; - getBooleanArray(): boolean[]; - getStringArray(): string[]; - getInspectableArray(): any[]; - getGuidArray(): string[]; - getDateTimeArray(): Date[]; - getTimeSpanArray(): number[]; - getPointArray(): Windows.Foundation.Point[]; - getSizeArray(): Windows.Foundation.Size[]; - getRectArray(): Windows.Foundation.Rect[]; - } - export interface IPropertyValueStatics { - createEmpty(): any; - createUInt8(value: number): any; - createInt16(value: number): any; - createUInt16(value: number): any; - createInt32(value: number): any; - createUInt32(value: number): any; - createInt64(value: number): any; - createUInt64(value: number): any; - createSingle(value: number): any; - createDouble(value: number): any; - createChar16(value: string): any; - createBoolean(value: boolean): any; - createString(value: string): any; - createInspectable(value: any): any; - createGuid(value: string): any; - createDateTime(value: Date): any; - createTimeSpan(value: number): any; - createPoint(value: Windows.Foundation.Point): any; - createSize(value: Windows.Foundation.Size): any; - createRect(value: Windows.Foundation.Rect): any; - createUInt8Array(value: Uint8Array): any; - createInt16Array(value: Int16Array): any; - createUInt16Array(value: Uint16Array): any; - createInt32Array(value: Int32Array): any; - createUInt32Array(value: Uint32Array): any; - createInt64Array(value: number[]): any; - createUInt64Array(value: number[]): any; - createSingleArray(value: Float32Array): any; - createDoubleArray(value: Float64Array): any; - createChar16Array(value: string[]): any; - createBooleanArray(value: boolean[]): any; - createStringArray(value: string[]): any; - createInspectableArray(value: any[]): any; - createGuidArray(value: string[]): any; - createDateTimeArray(value: Date[]): any; - createTimeSpanArray(value: number[]): any; - createPointArray(value: Windows.Foundation.Point[]): any; - createSizeArray(value: Windows.Foundation.Size[]): any; - createRectArray(value: Windows.Foundation.Rect[]): any; - } - export class PropertyValue { - static createEmpty(): any; - static createUInt8(value: number): any; - static createInt16(value: number): any; - static createUInt16(value: number): any; - static createInt32(value: number): any; - static createUInt32(value: number): any; - static createInt64(value: number): any; - static createUInt64(value: number): any; - static createSingle(value: number): any; - static createDouble(value: number): any; - static createChar16(value: string): any; - static createBoolean(value: boolean): any; - static createString(value: string): any; - static createInspectable(value: any): any; - static createGuid(value: string): any; - static createDateTime(value: Date): any; - static createTimeSpan(value: number): any; - static createPoint(value: Windows.Foundation.Point): any; - static createSize(value: Windows.Foundation.Size): any; - static createRect(value: Windows.Foundation.Rect): any; - static createUInt8Array(value: Uint8Array): any; - static createInt16Array(value: Int16Array): any; - static createUInt16Array(value: Uint16Array): any; - static createInt32Array(value: Int32Array): any; - static createUInt32Array(value: Uint32Array): any; - static createInt64Array(value: number[]): any; - static createUInt64Array(value: number[]): any; - static createSingleArray(value: Float32Array): any; - static createDoubleArray(value: Float64Array): any; - static createChar16Array(value: string[]): any; - static createBooleanArray(value: boolean[]): any; - static createStringArray(value: string[]): any; - static createInspectableArray(value: any[]): any; - static createGuidArray(value: string[]): any; - static createDateTimeArray(value: Date[]): any; - static createTimeSpanArray(value: number[]): any; - static createPointArray(value: Windows.Foundation.Point[]): any; - static createSizeArray(value: Windows.Foundation.Size[]): any; - static createRectArray(value: Windows.Foundation.Rect[]): any; - } - export interface AsyncActionCompletedHandler { - (asyncInfo: Windows.Foundation.IAsyncAction, asyncStatus: Windows.Foundation.AsyncStatus): void; - } - export enum AsyncStatus { - canceled, - completed, - error, - started, - } - export interface EventRegistrationToken { - value: number; - } - export interface HResult { - value: number; - } - export interface IAsyncInfo { - errorCode: number; - id: number; - status: Windows.Foundation.AsyncStatus; - cancel(): void; - close(): void; - } - export interface IAsyncAction extends Windows.Foundation.IAsyncInfo { - completed: Windows.Foundation.AsyncActionCompletedHandler; - getResults(): void; - } - export interface AsyncOperationWithProgressCompletedHandler { - (asyncInfo: Windows.Foundation.IAsyncOperationWithProgress, asyncStatus: Windows.Foundation.AsyncStatus): void; - } - export interface IAsyncOperationWithProgress extends Windows.Foundation.IPromise { - operation: { - progress: Windows.Foundation.AsyncOperationProgressHandler; - completed: Windows.Foundation.AsyncOperationWithProgressCompletedHandler; - getResults(): TResult; - } - } - export interface AsyncOperationCompletedHandler { - (asyncInfo: Windows.Foundation.IAsyncOperation, asyncStatus: Windows.Foundation.AsyncStatus): void; - } - export interface IAsyncOperation extends Windows.Foundation.IPromise { - operation: { - completed: Windows.Foundation.AsyncOperationCompletedHandler; - getResults(): TResult; - } - } - export interface AsyncActionWithProgressCompletedHandler { - (asyncInfo: Windows.Foundation.IAsyncActionWithProgress, asyncStatus: Windows.Foundation.AsyncStatus): void; - } - export interface IAsyncActionWithProgress extends Windows.Foundation.IAsyncInfo { - progress: Windows.Foundation.AsyncActionProgressHandler; - completed: Windows.Foundation.AsyncActionWithProgressCompletedHandler; - getResults(): void; - } - export interface AsyncOperationProgressHandler { - (asyncInfo: Windows.Foundation.IAsyncOperationWithProgress, progressInfo: TProgress): void; - } - export interface AsyncActionProgressHandler { - (asyncInfo: Windows.Foundation.IAsyncActionWithProgress, progressInfo: TProgress): void; - } - export interface IReference extends Windows.Foundation.IPropertyValue { - value: T; - } - export interface IReferenceArray extends Windows.Foundation.IPropertyValue { - value: T[]; - } - export interface TypedEventHandler { - (sender: TSender, args: TResult): void; - } - export interface EventHandler { - (sender: any, args: T): void; - } - } -} -declare module Windows { - export module Foundation { - export module Metadata { - export class WebHostHiddenAttribute { - } - export class VariantAttribute { - } - export class HasVariantAttribute { - } - export class DualApiPartitionAttribute { - } - export class MuseAttribute { - } - export enum GCPressureAmount { - low, - medium, - high, - } - export class GCPressureAttribute { - } - export class ActivatableAttribute { - constructor(version: number); - constructor(type: string /* TODO: really? */, version: number); - } - export class VersionAttribute { - constructor(version: number); - } - export class AllowMultipleAttribute { - } - export class AttributeUsageAttribute { - constructor(targets: Windows.Foundation.Metadata.AttributeTargets /* TODO: Really part of WinRT? */); - } - export enum AttributeTargets { - all, - delegate, - enum, - event, - field, - interface, - method, - parameter, - property, - runtimeClass, - struct, - interfaceImpl, - } - export class DefaultOverloadAttribute { - } - export class DefaultAttribute { - } - export class GuidAttribute { - constructor(a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number, k: number); - } - export class ComposableAttribute { - constructor(type: string /* TODO: really? */, compositionType: Windows.Foundation.Metadata.CompositionType, version: number); - } - export enum CompositionType { - protected, - public, - } - export class OverloadAttribute { - constructor(method: string); - } - export class StaticAttribute { - constructor(type: string /* TODO: really? */, version: number); - } - export class OverridableAttribute { - } - export class ProtectedAttribute { - } - export class ThreadingAttribute { - constructor(model: Windows.Foundation.Metadata.ThreadingModel); - } - export enum ThreadingModel { - sTA, - mTA, - both, - invalidThreading, - } - export class MarshalingBehaviorAttribute { - constructor(behavior: Windows.Foundation.Metadata.MarshalingType); - } - export enum MarshalingType { - none, - agile, - standard, - invalidMarshaling, - } - export class ExclusiveToAttribute { - constructor(typeName: string /* TODO: really? */); - } - export class LengthIsAttribute { - constructor(indexLengthParameter: number); - } - export class RangeAttribute { - constructor(minValue: number, maxValue: number); - } - } - } -} -declare module Windows { - export module Foundation { - export module Diagnostics { - export enum ErrorOptions { - none, - suppressExceptions, - forceExceptions, - useSetErrorInfo, - suppressSetErrorInfo, - } - export interface IErrorReportingSettings { - setErrorOptions(value: Windows.Foundation.Diagnostics.ErrorOptions): void; - getErrorOptions(): Windows.Foundation.Diagnostics.ErrorOptions; - } - export class RuntimeBrokerErrorSettings implements Windows.Foundation.Diagnostics.IErrorReportingSettings { - setErrorOptions(value: Windows.Foundation.Diagnostics.ErrorOptions): void; - getErrorOptions(): Windows.Foundation.Diagnostics.ErrorOptions; - } - } - } -} -declare module Windows { - export module ApplicationModel { - export module Background { - export enum BackgroundAccessStatus { - unspecified, - allowedWithAlwaysOnRealTimeConnectivity, - allowedMayUseActiveRealTimeConnectivity, - denied, - } - export interface IBackgroundExecutionManagerStatics { - requestAccessAsync(): Windows.Foundation.IAsyncOperation; - requestAccessAsync(applicationId: string): Windows.Foundation.IAsyncOperation; - removeAccess(): void; - removeAccess(applicationId: string): void; - getAccessStatus(): Windows.ApplicationModel.Background.BackgroundAccessStatus; - getAccessStatus(applicationId: string): Windows.ApplicationModel.Background.BackgroundAccessStatus; - } - export class BackgroundExecutionManager { - static requestAccessAsync(): Windows.Foundation.IAsyncOperation; - static requestAccessAsync(applicationId: string): Windows.Foundation.IAsyncOperation; - static removeAccess(): void; - static removeAccess(applicationId: string): void; - static getAccessStatus(): Windows.ApplicationModel.Background.BackgroundAccessStatus; - static getAccessStatus(applicationId: string): Windows.ApplicationModel.Background.BackgroundAccessStatus; - } - export enum BackgroundTaskCancellationReason { - abort, - terminating, - loggingOff, - servicingUpdate, - } - export interface BackgroundTaskCanceledEventHandler { - (sender: Windows.ApplicationModel.Background.IBackgroundTaskInstance, reason: Windows.ApplicationModel.Background.BackgroundTaskCancellationReason): void; - } - export interface IBackgroundTaskInstance { - instanceId: string; - progress: number; - suspendedCount: number; - task: Windows.ApplicationModel.Background.BackgroundTaskRegistration; - triggerDetails: any; - oncanceled: any/* TODO */; - getDeferral(): Windows.ApplicationModel.Background.BackgroundTaskDeferral; - } - export class BackgroundTaskRegistration implements Windows.ApplicationModel.Background.IBackgroundTaskRegistration { - name: string; - taskId: string; - onprogress: any/* TODO */; - oncompleted: any/* TODO */; - unregister(cancelTask: boolean): void; - static allTasks: Windows.Foundation.Collections.IMapView; - } - export class BackgroundTaskDeferral implements Windows.ApplicationModel.Background.IBackgroundTaskDeferral { - complete(): void; - } - export interface BackgroundTaskProgressEventHandler { - (sender: Windows.ApplicationModel.Background.BackgroundTaskRegistration, args: Windows.ApplicationModel.Background.BackgroundTaskProgressEventArgs): void; - } - export class BackgroundTaskProgressEventArgs implements Windows.ApplicationModel.Background.IBackgroundTaskProgressEventArgs { - instanceId: string; - progress: number; - } - export interface BackgroundTaskCompletedEventHandler { - (sender: Windows.ApplicationModel.Background.BackgroundTaskRegistration, args: Windows.ApplicationModel.Background.BackgroundTaskCompletedEventArgs): void; - } - export class BackgroundTaskCompletedEventArgs implements Windows.ApplicationModel.Background.IBackgroundTaskCompletedEventArgs { - instanceId: string; - checkResult(): void; - } - export interface IBackgroundTaskDeferral { - complete(): void; - } - export interface IBackgroundTask { - run(taskInstance: Windows.ApplicationModel.Background.IBackgroundTaskInstance): void; - } - export interface IBackgroundTaskRegistration { - name: string; - taskId: string; - onprogress: any/* TODO */; - oncompleted: any/* TODO */; - unregister(cancelTask: boolean): void; - } - export interface IBackgroundTaskRegistrationStatics { - allTasks: Windows.Foundation.Collections.IMapView; - } - export interface IBackgroundTaskBuilder { - name: string; - taskEntryPoint: string; - setTrigger(trigger: Windows.ApplicationModel.Background.IBackgroundTrigger): void; - addCondition(condition: Windows.ApplicationModel.Background.IBackgroundCondition): void; - register(): Windows.ApplicationModel.Background.BackgroundTaskRegistration; - } - export interface IBackgroundTrigger { - } - export interface IBackgroundCondition { - } - export interface IBackgroundTaskCompletedEventArgs { - instanceId: string; - checkResult(): void; - } - export interface IBackgroundTaskProgressEventArgs { - instanceId: string; - progress: number; - } - export class BackgroundTaskBuilder implements Windows.ApplicationModel.Background.IBackgroundTaskBuilder { - name: string; - taskEntryPoint: string; - setTrigger(trigger: Windows.ApplicationModel.Background.IBackgroundTrigger): void; - addCondition(condition: Windows.ApplicationModel.Background.IBackgroundCondition): void; - register(): Windows.ApplicationModel.Background.BackgroundTaskRegistration; - } - export enum SystemTriggerType { - invalid, - smsReceived, - userPresent, - userAway, - networkStateChange, - controlChannelReset, - internetAvailable, - sessionConnected, - servicingComplete, - lockScreenApplicationAdded, - lockScreenApplicationRemoved, - timeZoneChange, - onlineIdConnectedStateChange, - } - export enum SystemConditionType { - invalid, - userPresent, - userNotPresent, - internetAvailable, - internetNotAvailable, - sessionConnected, - sessionDisconnected, - } - export interface ISystemTrigger extends Windows.ApplicationModel.Background.IBackgroundTrigger { - oneShot: boolean; - triggerType: Windows.ApplicationModel.Background.SystemTriggerType; - } - export interface ISystemTriggerFactory { - create(triggerType: Windows.ApplicationModel.Background.SystemTriggerType, oneShot: boolean): Windows.ApplicationModel.Background.SystemTrigger; - } - export class SystemTrigger implements Windows.ApplicationModel.Background.ISystemTrigger, Windows.ApplicationModel.Background.IBackgroundTrigger { - constructor(triggerType: Windows.ApplicationModel.Background.SystemTriggerType, oneShot: boolean); - oneShot: boolean; - triggerType: Windows.ApplicationModel.Background.SystemTriggerType; - } - export interface ISystemCondition extends Windows.ApplicationModel.Background.IBackgroundCondition { - conditionType: Windows.ApplicationModel.Background.SystemConditionType; - } - export interface ISystemConditionFactory { - create(conditionType: Windows.ApplicationModel.Background.SystemConditionType): Windows.ApplicationModel.Background.SystemCondition; - } - export class SystemCondition implements Windows.ApplicationModel.Background.ISystemCondition, Windows.ApplicationModel.Background.IBackgroundCondition { - constructor(conditionType: Windows.ApplicationModel.Background.SystemConditionType); - conditionType: Windows.ApplicationModel.Background.SystemConditionType; - } - export interface INetworkOperatorNotificationTrigger extends Windows.ApplicationModel.Background.IBackgroundTrigger { - networkAccountId: string; - } - export interface INetworkOperatorNotificationTriggerFactory { - create(networkAccountId: string): Windows.ApplicationModel.Background.NetworkOperatorNotificationTrigger; - } - export class NetworkOperatorNotificationTrigger implements Windows.ApplicationModel.Background.INetworkOperatorNotificationTrigger, Windows.ApplicationModel.Background.IBackgroundTrigger { - constructor(networkAccountId: string); - networkAccountId: string; - } - export interface ITimeTrigger extends Windows.ApplicationModel.Background.IBackgroundTrigger { - freshnessTime: number; - oneShot: boolean; - } - export interface ITimeTriggerFactory { - create(freshnessTime: number, oneShot: boolean): Windows.ApplicationModel.Background.TimeTrigger; - } - export class TimeTrigger implements Windows.ApplicationModel.Background.ITimeTrigger, Windows.ApplicationModel.Background.IBackgroundTrigger { - constructor(freshnessTime: number, oneShot: boolean); - freshnessTime: number; - oneShot: boolean; - } - export interface IMaintenanceTrigger extends Windows.ApplicationModel.Background.IBackgroundTrigger { - freshnessTime: number; - oneShot: boolean; - } - export interface IMaintenanceTriggerFactory { - create(freshnessTime: number, oneShot: boolean): Windows.ApplicationModel.Background.MaintenanceTrigger; - } - export class MaintenanceTrigger implements Windows.ApplicationModel.Background.IMaintenanceTrigger, Windows.ApplicationModel.Background.IBackgroundTrigger { - constructor(freshnessTime: number, oneShot: boolean); - freshnessTime: number; - oneShot: boolean; - } - export interface INetworkOperatorHotspotAuthenticationTrigger extends Windows.ApplicationModel.Background.IBackgroundTrigger { - } - export class NetworkOperatorHotspotAuthenticationTrigger implements Windows.ApplicationModel.Background.INetworkOperatorHotspotAuthenticationTrigger, Windows.ApplicationModel.Background.IBackgroundTrigger { - } - export interface IPushNotificationTriggerFactory { - create(applicationId: string): Windows.ApplicationModel.Background.PushNotificationTrigger; - } - export class PushNotificationTrigger implements Windows.ApplicationModel.Background.IBackgroundTrigger { - constructor(applicationId: string); - constructor(); - } - } - } -} -declare module Windows { - export module ApplicationModel { - export module Contacts { - export enum ContactFieldType { - email, - phoneNumber, - location, - instantMessage, - custom, - } - export enum ContactFieldCategory { - none, - home, - work, - mobile, - other, - } - export enum ContactSelectionMode { - contacts, - fields, - } - export interface IContactField { - category: Windows.ApplicationModel.Contacts.ContactFieldCategory; - name: string; - type: Windows.ApplicationModel.Contacts.ContactFieldType; - value: string; - } - export class ContactField implements Windows.ApplicationModel.Contacts.IContactField { - constructor(value: string, type: Windows.ApplicationModel.Contacts.ContactFieldType); - constructor(value: string, type: Windows.ApplicationModel.Contacts.ContactFieldType, category: Windows.ApplicationModel.Contacts.ContactFieldCategory); - constructor(name: string, value: string, type: Windows.ApplicationModel.Contacts.ContactFieldType, category: Windows.ApplicationModel.Contacts.ContactFieldCategory); - category: Windows.ApplicationModel.Contacts.ContactFieldCategory; - name: string; - type: Windows.ApplicationModel.Contacts.ContactFieldType; - value: string; - } - export interface IContactLocationField extends Windows.ApplicationModel.Contacts.IContactField { - city: string; - country: string; - postalCode: string; - region: string; - street: string; - unstructuredAddress: string; - } - export class ContactLocationField implements Windows.ApplicationModel.Contacts.IContactLocationField, Windows.ApplicationModel.Contacts.IContactField { - constructor(unstructuredAddress: string); - constructor(unstructuredAddress: string, category: Windows.ApplicationModel.Contacts.ContactFieldCategory); - constructor(unstructuredAddress: string, category: Windows.ApplicationModel.Contacts.ContactFieldCategory, street: string, city: string, region: string, country: string, postalCode: string); - city: string; - country: string; - postalCode: string; - region: string; - street: string; - unstructuredAddress: string; - category: Windows.ApplicationModel.Contacts.ContactFieldCategory; - name: string; - type: Windows.ApplicationModel.Contacts.ContactFieldType; - value: string; - } - export interface IContactInstantMessageField extends Windows.ApplicationModel.Contacts.IContactField { - displayText: string; - launchUri: Windows.Foundation.Uri; - service: string; - userName: string; - } - export class ContactInstantMessageField implements Windows.ApplicationModel.Contacts.IContactInstantMessageField, Windows.ApplicationModel.Contacts.IContactField { - constructor(userName: string); - constructor(userName: string, category: Windows.ApplicationModel.Contacts.ContactFieldCategory); - constructor(userName: string, category: Windows.ApplicationModel.Contacts.ContactFieldCategory, service: string, displayText: string, verb: Windows.Foundation.Uri); - displayText: string; - launchUri: Windows.Foundation.Uri; - service: string; - userName: string; - category: Windows.ApplicationModel.Contacts.ContactFieldCategory; - name: string; - type: Windows.ApplicationModel.Contacts.ContactFieldType; - value: string; - } - export interface IKnownContactFieldStatics { - email: string; - instantMessage: string; - location: string; - phoneNumber: string; - convertNameToType(name: string): Windows.ApplicationModel.Contacts.ContactFieldType; - convertTypeToName(type: Windows.ApplicationModel.Contacts.ContactFieldType): string; - } - export class KnownContactField { - static email: string; - static instantMessage: string; - static location: string; - static phoneNumber: string; - static convertNameToType(name: string): Windows.ApplicationModel.Contacts.ContactFieldType; - static convertTypeToName(type: Windows.ApplicationModel.Contacts.ContactFieldType): string; - } - export interface IContactInformation { - customFields: Windows.Foundation.Collections.IVectorView; - emails: Windows.Foundation.Collections.IVectorView; - instantMessages: Windows.Foundation.Collections.IVectorView; - locations: Windows.Foundation.Collections.IVectorView; - name: string; - phoneNumbers: Windows.Foundation.Collections.IVectorView; - getThumbnailAsync(): Windows.Foundation.IAsyncOperation; - queryCustomFields(customName: string): Windows.Foundation.Collections.IVectorView; - } - export class ContactInformation implements Windows.ApplicationModel.Contacts.IContactInformation { - customFields: Windows.Foundation.Collections.IVectorView; - emails: Windows.Foundation.Collections.IVectorView; - instantMessages: Windows.Foundation.Collections.IVectorView; - locations: Windows.Foundation.Collections.IVectorView; - name: string; - phoneNumbers: Windows.Foundation.Collections.IVectorView; - getThumbnailAsync(): Windows.Foundation.IAsyncOperation; - queryCustomFields(customName: string): Windows.Foundation.Collections.IVectorView; - } - export interface IContactPicker { - commitButtonText: string; - desiredFields: Windows.Foundation.Collections.IVector; - selectionMode: Windows.ApplicationModel.Contacts.ContactSelectionMode; - pickSingleContactAsync(): Windows.Foundation.IAsyncOperation; - pickMultipleContactsAsync(): Windows.Foundation.IAsyncOperation>; - } - export class ContactPicker implements Windows.ApplicationModel.Contacts.IContactPicker { - commitButtonText: string; - desiredFields: Windows.Foundation.Collections.IVector; - selectionMode: Windows.ApplicationModel.Contacts.ContactSelectionMode; - pickSingleContactAsync(): Windows.Foundation.IAsyncOperation; - pickMultipleContactsAsync(): Windows.Foundation.IAsyncOperation>; - } - export interface IContact { - fields: Windows.Foundation.Collections.IVector; - name: string; - thumbnail: Windows.Storage.Streams.IRandomAccessStreamReference; - } - export class Contact implements Windows.ApplicationModel.Contacts.IContact { - fields: Windows.Foundation.Collections.IVector; - name: string; - thumbnail: Windows.Storage.Streams.IRandomAccessStreamReference; - } - export interface IContactFieldFactory { - createField(value: string, type: Windows.ApplicationModel.Contacts.ContactFieldType): Windows.ApplicationModel.Contacts.ContactField; - createField(value: string, type: Windows.ApplicationModel.Contacts.ContactFieldType, category: Windows.ApplicationModel.Contacts.ContactFieldCategory): Windows.ApplicationModel.Contacts.ContactField; - createField(name: string, value: string, type: Windows.ApplicationModel.Contacts.ContactFieldType, category: Windows.ApplicationModel.Contacts.ContactFieldCategory): Windows.ApplicationModel.Contacts.ContactField; - } - export interface IContactLocationFieldFactory { - createLocation(unstructuredAddress: string): Windows.ApplicationModel.Contacts.ContactLocationField; - createLocation(unstructuredAddress: string, category: Windows.ApplicationModel.Contacts.ContactFieldCategory): Windows.ApplicationModel.Contacts.ContactLocationField; - createLocation(unstructuredAddress: string, category: Windows.ApplicationModel.Contacts.ContactFieldCategory, street: string, city: string, region: string, country: string, postalCode: string): Windows.ApplicationModel.Contacts.ContactLocationField; - } - export interface IContactInstantMessageFieldFactory { - createInstantMessage(userName: string): Windows.ApplicationModel.Contacts.ContactInstantMessageField; - createInstantMessage(userName: string, category: Windows.ApplicationModel.Contacts.ContactFieldCategory): Windows.ApplicationModel.Contacts.ContactInstantMessageField; - createInstantMessage(userName: string, category: Windows.ApplicationModel.Contacts.ContactFieldCategory, service: string, displayText: string, verb: Windows.Foundation.Uri): Windows.ApplicationModel.Contacts.ContactInstantMessageField; - } - export class ContactFieldFactory implements Windows.ApplicationModel.Contacts.IContactFieldFactory, Windows.ApplicationModel.Contacts.IContactLocationFieldFactory, Windows.ApplicationModel.Contacts.IContactInstantMessageFieldFactory { - createField(value: string, type: Windows.ApplicationModel.Contacts.ContactFieldType): Windows.ApplicationModel.Contacts.ContactField; - createField(value: string, type: Windows.ApplicationModel.Contacts.ContactFieldType, category: Windows.ApplicationModel.Contacts.ContactFieldCategory): Windows.ApplicationModel.Contacts.ContactField; - createField(name: string, value: string, type: Windows.ApplicationModel.Contacts.ContactFieldType, category: Windows.ApplicationModel.Contacts.ContactFieldCategory): Windows.ApplicationModel.Contacts.ContactField; - createLocation(unstructuredAddress: string): Windows.ApplicationModel.Contacts.ContactLocationField; - createLocation(unstructuredAddress: string, category: Windows.ApplicationModel.Contacts.ContactFieldCategory): Windows.ApplicationModel.Contacts.ContactLocationField; - createLocation(unstructuredAddress: string, category: Windows.ApplicationModel.Contacts.ContactFieldCategory, street: string, city: string, region: string, country: string, postalCode: string): Windows.ApplicationModel.Contacts.ContactLocationField; - createInstantMessage(userName: string): Windows.ApplicationModel.Contacts.ContactInstantMessageField; - createInstantMessage(userName: string, category: Windows.ApplicationModel.Contacts.ContactFieldCategory): Windows.ApplicationModel.Contacts.ContactInstantMessageField; - createInstantMessage(userName: string, category: Windows.ApplicationModel.Contacts.ContactFieldCategory, service: string, displayText: string, verb: Windows.Foundation.Uri): Windows.ApplicationModel.Contacts.ContactInstantMessageField; - } - } - } -} -declare module Windows { - export module ApplicationModel { - export module Contacts { - export module Provider { - export interface IContactRemovedEventArgs { - id: string; - } - export class ContactRemovedEventArgs implements Windows.ApplicationModel.Contacts.Provider.IContactRemovedEventArgs { - id: string; - } - export enum AddContactResult { - added, - alreadyAdded, - unavailable, - } - export interface IContactPickerUI { - desiredFields: Windows.Foundation.Collections.IVectorView; - selectionMode: Windows.ApplicationModel.Contacts.ContactSelectionMode; - addContact(id: string, contact: Windows.ApplicationModel.Contacts.Contact): Windows.ApplicationModel.Contacts.Provider.AddContactResult; - removeContact(id: string): void; - containsContact(id: string): boolean; - oncontactremoved: any/* TODO */; - } - export class ContactPickerUI implements Windows.ApplicationModel.Contacts.Provider.IContactPickerUI { - desiredFields: Windows.Foundation.Collections.IVectorView; - selectionMode: Windows.ApplicationModel.Contacts.ContactSelectionMode; - addContact(id: string, contact: Windows.ApplicationModel.Contacts.Contact): Windows.ApplicationModel.Contacts.Provider.AddContactResult; - removeContact(id: string): void; - containsContact(id: string): boolean; - oncontactremoved: any/* TODO */; - } - } - } - } -} -declare module Windows { - export module ApplicationModel { - export module DataTransfer { - export interface IStandardDataFormatsStatics { - bitmap: string; - html: string; - rtf: string; - storageItems: string; - text: string; - uri: string; - } - export class StandardDataFormats { - static bitmap: string; - static html: string; - static rtf: string; - static storageItems: string; - static text: string; - static uri: string; - } - export interface IDataPackagePropertySetView extends Windows.Foundation.Collections.IMapView, Windows.Foundation.Collections.IIterable> { - applicationListingUri: Windows.Foundation.Uri; - applicationName: string; - description: string; - fileTypes: Windows.Foundation.Collections.IVectorView; - thumbnail: Windows.Storage.Streams.RandomAccessStreamReference; - title: string; - } - export interface IDataPackagePropertySet extends Windows.Foundation.Collections.IMap, Windows.Foundation.Collections.IIterable> { - applicationListingUri: Windows.Foundation.Uri; - applicationName: string; - description: string; - fileTypes: Windows.Foundation.Collections.IVector; - thumbnail: Windows.Storage.Streams.IRandomAccessStreamReference; - title: string; - } - export class DataPackagePropertySetView implements Windows.ApplicationModel.DataTransfer.IDataPackagePropertySetView, Windows.Foundation.Collections.IMapView, Windows.Foundation.Collections.IIterable> { - applicationListingUri: Windows.Foundation.Uri; - applicationName: string; - description: string; - fileTypes: Windows.Foundation.Collections.IVectorView; - thumbnail: Windows.Storage.Streams.RandomAccessStreamReference; - title: string; - size: number; - lookup(key: string): any; - hasKey(key: string): boolean; - split(): { first: Windows.Foundation.Collections.IMapView; second: Windows.Foundation.Collections.IMapView; }; - first(): Windows.Foundation.Collections.IIterator>; - } - export class DataPackagePropertySet implements Windows.ApplicationModel.DataTransfer.IDataPackagePropertySet, Windows.Foundation.Collections.IMap, Windows.Foundation.Collections.IIterable> { - applicationListingUri: Windows.Foundation.Uri; - applicationName: string; - description: string; - fileTypes: Windows.Foundation.Collections.IVector; - thumbnail: Windows.Storage.Streams.IRandomAccessStreamReference; - title: string; - size: number; - lookup(key: string): any; - hasKey(key: string): boolean; - getView(): Windows.Foundation.Collections.IMapView; - insert(key: string, value: any): boolean; - remove(key: string): void; - clear(): void; - first(): Windows.Foundation.Collections.IIterator>; - } - export interface IDataProviderDeferral { - complete(): void; - } - export class DataProviderDeferral implements Windows.ApplicationModel.DataTransfer.IDataProviderDeferral { - complete(): void; - } - export interface IDataProviderRequest { - deadline: Date; - formatId: string; - getDeferral(): Windows.ApplicationModel.DataTransfer.DataProviderDeferral; - setData(value: any): void; - } - export class DataProviderRequest implements Windows.ApplicationModel.DataTransfer.IDataProviderRequest { - deadline: Date; - formatId: string; - getDeferral(): Windows.ApplicationModel.DataTransfer.DataProviderDeferral; - setData(value: any): void; - } - export interface DataProviderHandler { - (request: Windows.ApplicationModel.DataTransfer.DataProviderRequest): void; - } - export enum DataPackageOperation { - none, - copy, - move, - link, - } - export interface IOperationCompletedEventArgs { - operation: Windows.ApplicationModel.DataTransfer.DataPackageOperation; - } - export class OperationCompletedEventArgs implements Windows.ApplicationModel.DataTransfer.IOperationCompletedEventArgs { - operation: Windows.ApplicationModel.DataTransfer.DataPackageOperation; - } - export interface IDataPackageView { - availableFormats: Windows.Foundation.Collections.IVectorView; - properties: Windows.ApplicationModel.DataTransfer.DataPackagePropertySetView; - requestedOperation: Windows.ApplicationModel.DataTransfer.DataPackageOperation; - reportOperationCompleted(value: Windows.ApplicationModel.DataTransfer.DataPackageOperation): void; - contains(formatId: string): boolean; - getDataAsync(formatId: string): Windows.Foundation.IAsyncOperation; - getTextAsync(): Windows.Foundation.IAsyncOperation; - getTextAsync(formatId: string): Windows.Foundation.IAsyncOperation; - getUriAsync(): Windows.Foundation.IAsyncOperation; - getHtmlFormatAsync(): Windows.Foundation.IAsyncOperation; - getResourceMapAsync(): Windows.Foundation.IAsyncOperation>; - getRtfAsync(): Windows.Foundation.IAsyncOperation; - getBitmapAsync(): Windows.Foundation.IAsyncOperation; - getStorageItemsAsync(): Windows.Foundation.IAsyncOperation>; - } - export interface IDataPackage { - properties: Windows.ApplicationModel.DataTransfer.DataPackagePropertySet; - requestedOperation: Windows.ApplicationModel.DataTransfer.DataPackageOperation; - resourceMap: Windows.Foundation.Collections.IMap; - getView(): Windows.ApplicationModel.DataTransfer.DataPackageView; - onoperationcompleted: any/* TODO */; - ondestroyed: any/* TODO */; - setData(formatId: string, value: any): void; - setDataProvider(formatId: string, delayRenderer: Windows.ApplicationModel.DataTransfer.DataProviderHandler): void; - setText(value: string): void; - setUri(value: Windows.Foundation.Uri): void; - setHtmlFormat(value: string): void; - setRtf(value: string): void; - setBitmap(value: Windows.Storage.Streams.RandomAccessStreamReference): void; - setStorageItems(value: Windows.Foundation.Collections.IIterable): void; - setStorageItems(value: Windows.Foundation.Collections.IIterable, readOnly: boolean): void; - } - export class DataPackageView implements Windows.ApplicationModel.DataTransfer.IDataPackageView { - availableFormats: Windows.Foundation.Collections.IVectorView; - properties: Windows.ApplicationModel.DataTransfer.DataPackagePropertySetView; - requestedOperation: Windows.ApplicationModel.DataTransfer.DataPackageOperation; - reportOperationCompleted(value: Windows.ApplicationModel.DataTransfer.DataPackageOperation): void; - contains(formatId: string): boolean; - getDataAsync(formatId: string): Windows.Foundation.IAsyncOperation; - getTextAsync(): Windows.Foundation.IAsyncOperation; - getTextAsync(formatId: string): Windows.Foundation.IAsyncOperation; - getUriAsync(): Windows.Foundation.IAsyncOperation; - getHtmlFormatAsync(): Windows.Foundation.IAsyncOperation; - getResourceMapAsync(): Windows.Foundation.IAsyncOperation>; - getRtfAsync(): Windows.Foundation.IAsyncOperation; - getBitmapAsync(): Windows.Foundation.IAsyncOperation; - getStorageItemsAsync(): Windows.Foundation.IAsyncOperation>; - } - export class DataPackage implements Windows.ApplicationModel.DataTransfer.IDataPackage { - properties: Windows.ApplicationModel.DataTransfer.DataPackagePropertySet; - requestedOperation: Windows.ApplicationModel.DataTransfer.DataPackageOperation; - resourceMap: Windows.Foundation.Collections.IMap; - getView(): Windows.ApplicationModel.DataTransfer.DataPackageView; - onoperationcompleted: any/* TODO */; - ondestroyed: any/* TODO */; - setData(formatId: string, value: any): void; - setDataProvider(formatId: string, delayRenderer: Windows.ApplicationModel.DataTransfer.DataProviderHandler): void; - setText(value: string): void; - setUri(value: Windows.Foundation.Uri): void; - setHtmlFormat(value: string): void; - setRtf(value: string): void; - setBitmap(value: Windows.Storage.Streams.RandomAccessStreamReference): void; - setStorageItems(value: Windows.Foundation.Collections.IIterable): void; - setStorageItems(value: Windows.Foundation.Collections.IIterable, readOnly: boolean): void; - } - export interface IHtmlFormatHelperStatics { - getStaticFragment(htmlFormat: string): string; - createHtmlFormat(htmlFragment: string): string; - } - export class HtmlFormatHelper { - static getStaticFragment(htmlFormat: string): string; - static createHtmlFormat(htmlFragment: string): string; - } - export interface IClipboardStatics { - getContent(): Windows.ApplicationModel.DataTransfer.DataPackageView; - setContent(content: Windows.ApplicationModel.DataTransfer.DataPackage): void; - flush(): void; - clear(): void; - oncontentchanged: any/* TODO */; - } - export class Clipboard { - static getContent(): Windows.ApplicationModel.DataTransfer.DataPackageView; - static setContent(content: Windows.ApplicationModel.DataTransfer.DataPackage): void; - static flush(): void; - static clear(): void; - static oncontentchanged: any/* TODO */; - } - export interface IDataRequestDeferral { - complete(): void; - } - export class DataRequestDeferral implements Windows.ApplicationModel.DataTransfer.IDataRequestDeferral { - complete(): void; - } - export interface IDataRequest { - data: Windows.ApplicationModel.DataTransfer.DataPackage; - deadline: Date; - failWithDisplayText(value: string): void; - getDeferral(): Windows.ApplicationModel.DataTransfer.DataRequestDeferral; - } - export class DataRequest implements Windows.ApplicationModel.DataTransfer.IDataRequest { - data: Windows.ApplicationModel.DataTransfer.DataPackage; - deadline: Date; - failWithDisplayText(value: string): void; - getDeferral(): Windows.ApplicationModel.DataTransfer.DataRequestDeferral; - } - export interface IDataRequestedEventArgs { - request: Windows.ApplicationModel.DataTransfer.DataRequest; - } - export class DataRequestedEventArgs implements Windows.ApplicationModel.DataTransfer.IDataRequestedEventArgs { - request: Windows.ApplicationModel.DataTransfer.DataRequest; - } - export interface ITargetApplicationChosenEventArgs { - applicationName: string; - } - export class TargetApplicationChosenEventArgs implements Windows.ApplicationModel.DataTransfer.ITargetApplicationChosenEventArgs { - applicationName: string; - } - export interface IDataTransferManager { - ondatarequested: any/* TODO */; - ontargetapplicationchosen: any/* TODO */; - } - export class DataTransferManager implements Windows.ApplicationModel.DataTransfer.IDataTransferManager { - ondatarequested: any/* TODO */; - ontargetapplicationchosen: any/* TODO */; - static showShareUI(): void; - static getForCurrentView(): Windows.ApplicationModel.DataTransfer.DataTransferManager; - } - export interface IDataTransferManagerStatics { - showShareUI(): void; - getForCurrentView(): Windows.ApplicationModel.DataTransfer.DataTransferManager; - } - } - } -} -declare module Windows { - export module ApplicationModel { - export module Search { - export interface ISearchPaneQueryLinguisticDetails { - queryTextAlternatives: Windows.Foundation.Collections.IVectorView; - queryTextCompositionLength: number; - queryTextCompositionStart: number; - } - export class SearchPaneQueryLinguisticDetails implements Windows.ApplicationModel.Search.ISearchPaneQueryLinguisticDetails { - queryTextAlternatives: Windows.Foundation.Collections.IVectorView; - queryTextCompositionLength: number; - queryTextCompositionStart: number; - } - export interface ISearchPaneVisibilityChangedEventArgs { - visible: boolean; - } - export class SearchPaneVisibilityChangedEventArgs implements Windows.ApplicationModel.Search.ISearchPaneVisibilityChangedEventArgs { - visible: boolean; - } - export interface ISearchPaneQueryChangedEventArgs { - language: string; - linguisticDetails: Windows.ApplicationModel.Search.SearchPaneQueryLinguisticDetails; - queryText: string; - } - export class SearchPaneQueryChangedEventArgs implements Windows.ApplicationModel.Search.ISearchPaneQueryChangedEventArgs { - language: string; - linguisticDetails: Windows.ApplicationModel.Search.SearchPaneQueryLinguisticDetails; - queryText: string; - } - export interface ISearchPaneQuerySubmittedEventArgs { - language: string; - queryText: string; - } - export class SearchPaneQuerySubmittedEventArgs implements Windows.ApplicationModel.Search.ISearchPaneQuerySubmittedEventArgs { - language: string; - queryText: string; - } - export interface ISearchPaneResultSuggestionChosenEventArgs { - tag: string; - } - export class SearchPaneResultSuggestionChosenEventArgs implements Windows.ApplicationModel.Search.ISearchPaneResultSuggestionChosenEventArgs { - tag: string; - } - export interface ISearchSuggestionCollection { - size: number; - appendQuerySuggestion(text: string): void; - appendQuerySuggestions(suggestions: Windows.Foundation.Collections.IIterable): void; - appendResultSuggestion(text: string, detailText: string, tag: string, image: Windows.Storage.Streams.IRandomAccessStreamReference, imageAlternateText: string): void; - appendSearchSeparator(label: string): void; - } - export class SearchSuggestionCollection implements Windows.ApplicationModel.Search.ISearchSuggestionCollection { - size: number; - appendQuerySuggestion(text: string): void; - appendQuerySuggestions(suggestions: Windows.Foundation.Collections.IIterable): void; - appendResultSuggestion(text: string, detailText: string, tag: string, image: Windows.Storage.Streams.IRandomAccessStreamReference, imageAlternateText: string): void; - appendSearchSeparator(label: string): void; - } - export interface ISearchPaneSuggestionsRequestDeferral { - complete(): void; - } - export interface ISearchPaneSuggestionsRequest { - isCanceled: boolean; - searchSuggestionCollection: Windows.ApplicationModel.Search.SearchSuggestionCollection; - getDeferral(): Windows.ApplicationModel.Search.SearchPaneSuggestionsRequestDeferral; - } - export class SearchPaneSuggestionsRequestDeferral implements Windows.ApplicationModel.Search.ISearchPaneSuggestionsRequestDeferral { - complete(): void; - } - export class SearchPaneSuggestionsRequest implements Windows.ApplicationModel.Search.ISearchPaneSuggestionsRequest { - isCanceled: boolean; - searchSuggestionCollection: Windows.ApplicationModel.Search.SearchSuggestionCollection; - getDeferral(): Windows.ApplicationModel.Search.SearchPaneSuggestionsRequestDeferral; - } - export interface ISearchPaneSuggestionsRequestedEventArgs extends Windows.ApplicationModel.Search.ISearchPaneQueryChangedEventArgs { - request: Windows.ApplicationModel.Search.SearchPaneSuggestionsRequest; - } - export class SearchPaneSuggestionsRequestedEventArgs implements Windows.ApplicationModel.Search.ISearchPaneSuggestionsRequestedEventArgs, Windows.ApplicationModel.Search.ISearchPaneQueryChangedEventArgs { - request: Windows.ApplicationModel.Search.SearchPaneSuggestionsRequest; - language: string; - linguisticDetails: Windows.ApplicationModel.Search.SearchPaneQueryLinguisticDetails; - queryText: string; - } - export interface ILocalContentSuggestionSettings { - aqsFilter: string; - enabled: boolean; - locations: Windows.Foundation.Collections.IVector; - propertiesToMatch: Windows.Foundation.Collections.IVector; - } - export class LocalContentSuggestionSettings implements Windows.ApplicationModel.Search.ILocalContentSuggestionSettings { - aqsFilter: string; - enabled: boolean; - locations: Windows.Foundation.Collections.IVector; - propertiesToMatch: Windows.Foundation.Collections.IVector; - } - export interface ISearchPaneStatics { - getForCurrentView(): Windows.ApplicationModel.Search.SearchPane; - } - export class SearchPane implements Windows.ApplicationModel.Search.ISearchPane { - language: string; - placeholderText: string; - queryText: string; - searchHistoryContext: string; - searchHistoryEnabled: boolean; - showOnKeyboardInput: boolean; - visible: boolean; - onvisibilitychanged: any/* TODO */; - onquerychanged: any/* TODO */; - onsuggestionsrequested: any/* TODO */; - onquerysubmitted: any/* TODO */; - onresultsuggestionchosen: any/* TODO */; - setLocalContentSuggestionSettings(settings: Windows.ApplicationModel.Search.LocalContentSuggestionSettings): void; - show(): void; - show(query: string): void; - trySetQueryText(query: string): boolean; - static getForCurrentView(): Windows.ApplicationModel.Search.SearchPane; - } - export interface ISearchPane { - language: string; - placeholderText: string; - queryText: string; - searchHistoryContext: string; - searchHistoryEnabled: boolean; - showOnKeyboardInput: boolean; - visible: boolean; - onvisibilitychanged: any/* TODO */; - onquerychanged: any/* TODO */; - onsuggestionsrequested: any/* TODO */; - onquerysubmitted: any/* TODO */; - onresultsuggestionchosen: any/* TODO */; - setLocalContentSuggestionSettings(settings: Windows.ApplicationModel.Search.LocalContentSuggestionSettings): void; - show(): void; - show(query: string): void; - trySetQueryText(query: string): boolean; - } - } - } -} -declare module Windows { - export module ApplicationModel { - export module DataTransfer { - export module ShareTarget { - export interface IQuickLink { - id: string; - supportedDataFormats: Windows.Foundation.Collections.IVector; - supportedFileTypes: Windows.Foundation.Collections.IVector; - thumbnail: Windows.Storage.Streams.RandomAccessStreamReference; - title: string; - } - export class QuickLink implements Windows.ApplicationModel.DataTransfer.ShareTarget.IQuickLink { - id: string; - supportedDataFormats: Windows.Foundation.Collections.IVector; - supportedFileTypes: Windows.Foundation.Collections.IVector; - thumbnail: Windows.Storage.Streams.RandomAccessStreamReference; - title: string; - } - export interface IShareOperation { - data: Windows.ApplicationModel.DataTransfer.DataPackageView; - quickLinkId: string; - removeThisQuickLink(): void; - reportStarted(): void; - reportDataRetrieved(): void; - reportSubmittedBackgroundTask(): void; - reportCompleted(quicklink: Windows.ApplicationModel.DataTransfer.ShareTarget.QuickLink): void; - reportCompleted(): void; - reportError(value: string): void; - } - export class ShareOperation implements Windows.ApplicationModel.DataTransfer.ShareTarget.IShareOperation { - data: Windows.ApplicationModel.DataTransfer.DataPackageView; - quickLinkId: string; - removeThisQuickLink(): void; - reportStarted(): void; - reportDataRetrieved(): void; - reportSubmittedBackgroundTask(): void; - reportCompleted(quicklink: Windows.ApplicationModel.DataTransfer.ShareTarget.QuickLink): void; - reportCompleted(): void; - reportError(value: string): void; - } - } - } - } -} -declare module Windows { - export module ApplicationModel { - export module Activation { - export interface ISplashScreen { - imageLocation: Windows.Foundation.Rect; - ondismissed: any/* TODO */; - } - export class SplashScreen implements Windows.ApplicationModel.Activation.ISplashScreen { - imageLocation: Windows.Foundation.Rect; - ondismissed: any/* TODO */; - } - export enum ApplicationExecutionState { - notRunning, - running, - suspended, - terminated, - closedByUser, - } - export enum ActivationKind { - launch, - search, - shareTarget, - file, - protocol, - fileOpenPicker, - fileSavePicker, - cachedFileUpdater, - contactPicker, - device, - printTaskSettings, - cameraSettings, - } - export interface IActivatedEventArgs { - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - } - export interface ILaunchActivatedEventArgs extends Windows.ApplicationModel.Activation.IActivatedEventArgs { - arguments: string; - tileId: string; - } - export class LaunchActivatedEventArgs implements Windows.ApplicationModel.Activation.ILaunchActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs { - arguments: string; - tileId: string; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - } - export interface ISearchActivatedEventArgs extends Windows.ApplicationModel.Activation.IActivatedEventArgs { - language: string; - queryText: string; - } - export class SearchActivatedEventArgs implements Windows.ApplicationModel.Activation.ISearchActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs { - language: string; - queryText: string; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - } - export interface IShareTargetActivatedEventArgs extends Windows.ApplicationModel.Activation.IActivatedEventArgs { - shareOperation: Windows.ApplicationModel.DataTransfer.ShareTarget.ShareOperation; - } - export class ShareTargetActivatedEventArgs implements Windows.ApplicationModel.Activation.IShareTargetActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs { - shareOperation: Windows.ApplicationModel.DataTransfer.ShareTarget.ShareOperation; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - } - export interface IFileActivatedEventArgs extends Windows.ApplicationModel.Activation.IActivatedEventArgs { - files: Windows.Foundation.Collections.IVectorView; - verb: string; - } - export class FileActivatedEventArgs implements Windows.ApplicationModel.Activation.IFileActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs { - files: Windows.Foundation.Collections.IVectorView; - verb: string; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - } - export interface IProtocolActivatedEventArgs extends Windows.ApplicationModel.Activation.IActivatedEventArgs { - uri: Windows.Foundation.Uri; - } - export class ProtocolActivatedEventArgs implements Windows.ApplicationModel.Activation.IProtocolActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs { - uri: Windows.Foundation.Uri; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - } - export interface IFileOpenPickerActivatedEventArgs extends Windows.ApplicationModel.Activation.IActivatedEventArgs { - fileOpenPickerUI: Windows.Storage.Pickers.Provider.FileOpenPickerUI; - } - export class FileOpenPickerActivatedEventArgs implements Windows.ApplicationModel.Activation.IFileOpenPickerActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs { - fileOpenPickerUI: Windows.Storage.Pickers.Provider.FileOpenPickerUI; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - } - export interface IFileSavePickerActivatedEventArgs extends Windows.ApplicationModel.Activation.IActivatedEventArgs { - fileSavePickerUI: Windows.Storage.Pickers.Provider.FileSavePickerUI; - } - export class FileSavePickerActivatedEventArgs implements Windows.ApplicationModel.Activation.IFileSavePickerActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs { - fileSavePickerUI: Windows.Storage.Pickers.Provider.FileSavePickerUI; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - } - export interface ICachedFileUpdaterActivatedEventArgs extends Windows.ApplicationModel.Activation.IActivatedEventArgs { - cachedFileUpdaterUI: Windows.Storage.Provider.CachedFileUpdaterUI; - } - export class CachedFileUpdaterActivatedEventArgs implements Windows.ApplicationModel.Activation.ICachedFileUpdaterActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs { - cachedFileUpdaterUI: Windows.Storage.Provider.CachedFileUpdaterUI; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - } - export interface IContactPickerActivatedEventArgs extends Windows.ApplicationModel.Activation.IActivatedEventArgs { - contactPickerUI: Windows.ApplicationModel.Contacts.Provider.ContactPickerUI; - } - export class ContactPickerActivatedEventArgs implements Windows.ApplicationModel.Activation.IContactPickerActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs { - contactPickerUI: Windows.ApplicationModel.Contacts.Provider.ContactPickerUI; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - } - export interface IDeviceActivatedEventArgs extends Windows.ApplicationModel.Activation.IActivatedEventArgs { - deviceInformationId: string; - verb: string; - } - export class DeviceActivatedEventArgs implements Windows.ApplicationModel.Activation.IDeviceActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs { - deviceInformationId: string; - verb: string; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - } - export interface IPrintTaskSettingsActivatedEventArgs extends Windows.ApplicationModel.Activation.IActivatedEventArgs { - configuration: Windows.Devices.Printers.Extensions.PrintTaskConfiguration; - } - export class PrintTaskSettingsActivatedEventArgs implements Windows.ApplicationModel.Activation.IPrintTaskSettingsActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs { - configuration: Windows.Devices.Printers.Extensions.PrintTaskConfiguration; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - } - export interface ICameraSettingsActivatedEventArgs extends Windows.ApplicationModel.Activation.IActivatedEventArgs { - videoDeviceController: any; - videoDeviceExtension: any; - } - export class CameraSettingsActivatedEventArgs implements Windows.ApplicationModel.Activation.ICameraSettingsActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs { - videoDeviceController: any; - videoDeviceExtension: any; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - } - } - } -} -declare module Windows { - export module ApplicationModel { - export module Core { - export class CoreApplication { - static mainView: Windows.ApplicationModel.Core.CoreApplicationView; - static views: Windows.Foundation.Collections.IVectorView; - static id: string; - static properties: Windows.Foundation.Collections.IPropertySet; - static incrementApplicationUseCount(): void; - static decrementApplicationUseCount(): void; - static createNewView(runtimeType: string, entryPoint: string): Windows.ApplicationModel.Core.CoreApplicationView; - static exit(): void; - static onexiting: any/* TODO */; - static onsuspending: any/* TODO */; - static onresuming: any/* TODO */; - static getCurrentView(): Windows.ApplicationModel.Core.CoreApplicationView; - static run(viewSource: Windows.ApplicationModel.Core.IFrameworkViewSource): void; - static runWithActivationFactories(activationFactoryCallback: Windows.Foundation.IGetActivationFactory): void; - } - export class CoreApplicationView implements Windows.ApplicationModel.Core.ICoreApplicationView { - coreWindow: Windows.UI.Core.CoreWindow; - isHosted: boolean; - isMain: boolean; - onactivated: any/* TODO */; - } - export interface IFrameworkView { - initialize(applicationView: Windows.ApplicationModel.Core.CoreApplicationView): void; - setWindow(window: Windows.UI.Core.CoreWindow): void; - load(entryPoint: string): void; - run(): void; - uninitialize(): void; - } - export interface IFrameworkViewSource { - createView(): Windows.ApplicationModel.Core.IFrameworkView; - } - export interface ICoreApplication { - id: string; - properties: Windows.Foundation.Collections.IPropertySet; - onsuspending: any/* TODO */; - onresuming: any/* TODO */; - getCurrentView(): Windows.ApplicationModel.Core.CoreApplicationView; - run(viewSource: Windows.ApplicationModel.Core.IFrameworkViewSource): void; - runWithActivationFactories(activationFactoryCallback: Windows.Foundation.IGetActivationFactory): void; - } - export interface ICoreApplicationUseCount { - incrementApplicationUseCount(): void; - decrementApplicationUseCount(): void; - } - export interface ICoreApplicationExit { - exit(): void; - onexiting: any/* TODO */; - } - export interface ICoreImmersiveApplication { - mainView: Windows.ApplicationModel.Core.CoreApplicationView; - views: Windows.Foundation.Collections.IVectorView; - createNewView(runtimeType: string, entryPoint: string): Windows.ApplicationModel.Core.CoreApplicationView; - } - export interface ICoreApplicationView { - coreWindow: Windows.UI.Core.CoreWindow; - isHosted: boolean; - isMain: boolean; - onactivated: any/* TODO */; - } - } - } -} -declare module Windows { - export module ApplicationModel { - export class SuspendingEventArgs implements Windows.ApplicationModel.ISuspendingEventArgs { - suspendingOperation: Windows.ApplicationModel.SuspendingOperation; - } - export interface ISuspendingDeferral { - complete(): void; - } - export class SuspendingDeferral implements Windows.ApplicationModel.ISuspendingDeferral { - complete(): void; - } - export interface ISuspendingOperation { - deadline: Date; - getDeferral(): Windows.ApplicationModel.SuspendingDeferral; - } - export class SuspendingOperation implements Windows.ApplicationModel.ISuspendingOperation { - deadline: Date; - getDeferral(): Windows.ApplicationModel.SuspendingDeferral; - } - export interface ISuspendingEventArgs { - suspendingOperation: Windows.ApplicationModel.SuspendingOperation; - } - export interface PackageVersion { - major: number; - minor: number; - build: number; - revision: number; - } - export interface IPackageId { - architecture: Windows.System.ProcessorArchitecture; - familyName: string; - fullName: string; - name: string; - publisher: string; - publisherId: string; - resourceId: string; - version: Windows.ApplicationModel.PackageVersion; - } - export class PackageId implements Windows.ApplicationModel.IPackageId { - architecture: Windows.System.ProcessorArchitecture; - familyName: string; - fullName: string; - name: string; - publisher: string; - publisherId: string; - resourceId: string; - version: Windows.ApplicationModel.PackageVersion; - } - export interface IPackage { - dependencies: Windows.Foundation.Collections.IVectorView; - id: Windows.ApplicationModel.PackageId; - installedLocation: Windows.Storage.StorageFolder; - isFramework: boolean; - } - export class Package implements Windows.ApplicationModel.IPackage { - dependencies: Windows.Foundation.Collections.IVectorView; - id: Windows.ApplicationModel.PackageId; - installedLocation: Windows.Storage.StorageFolder; - isFramework: boolean; - static current: Windows.ApplicationModel.Package; - } - export interface IPackageStatics { - current: Windows.ApplicationModel.Package; - } - export interface IDesignModeStatics { - designModeEnabled: boolean; - } - export class DesignMode { - static designModeEnabled: boolean; - } - } -} -declare module Windows { - export module ApplicationModel { - export module Resources { - export interface IResourceLoader { - getString(resource: string): string; - } - export class ResourceLoader implements Windows.ApplicationModel.Resources.IResourceLoader { - constructor(name: string); - constructor(); - getString(resource: string): string; - static getStringForReference(uri: Windows.Foundation.Uri): string; - } - export interface IResourceLoaderStatics { - getStringForReference(uri: Windows.Foundation.Uri): string; - } - export interface IResourceLoaderFactory { - createResourceLoaderByName(name: string): Windows.ApplicationModel.Resources.ResourceLoader; - } - } - } -} -declare module Windows { - export module ApplicationModel { - export module Resources { - export module Core { - export interface IResourceManager { - allResourceMaps: Windows.Foundation.Collections.IMapView; - defaultContext: Windows.ApplicationModel.Resources.Core.ResourceContext; - mainResourceMap: Windows.ApplicationModel.Resources.Core.ResourceMap; - loadPriFiles(files: Windows.Foundation.Collections.IIterable): void; - unloadPriFiles(files: Windows.Foundation.Collections.IIterable): void; - } - export class ResourceMap implements Windows.ApplicationModel.Resources.Core.IResourceMap, Windows.Foundation.Collections.IMapView, Windows.Foundation.Collections.IIterable> { - uri: Windows.Foundation.Uri; - size: number; - getValue(resource: string): Windows.ApplicationModel.Resources.Core.ResourceCandidate; - getValue(resource: string, context: Windows.ApplicationModel.Resources.Core.ResourceContext): Windows.ApplicationModel.Resources.Core.ResourceCandidate; - getSubtree(reference: string): Windows.ApplicationModel.Resources.Core.ResourceMap; - lookup(key: string): Windows.ApplicationModel.Resources.Core.NamedResource; - hasKey(key: string): boolean; - split(): { first: Windows.Foundation.Collections.IMapView; second: Windows.Foundation.Collections.IMapView; }; - first(): Windows.Foundation.Collections.IIterator>; - } - export class ResourceContext implements Windows.ApplicationModel.Resources.Core.IResourceContext { - languages: Windows.Foundation.Collections.IVectorView; - qualifierValues: Windows.Foundation.Collections.IObservableMap; - reset(): void; - reset(qualifierNames: Windows.Foundation.Collections.IIterable): void; - overrideToMatch(result: Windows.Foundation.Collections.IIterable): void; - clone(): Windows.ApplicationModel.Resources.Core.ResourceContext; - static createMatchingContext(result: Windows.Foundation.Collections.IIterable): Windows.ApplicationModel.Resources.Core.ResourceContext; - } - export interface IResourceManagerStatics { - current: Windows.ApplicationModel.Resources.Core.ResourceManager; - isResourceReference(resourceReference: string): boolean; - } - export class ResourceManager implements Windows.ApplicationModel.Resources.Core.IResourceManager { - allResourceMaps: Windows.Foundation.Collections.IMapView; - defaultContext: Windows.ApplicationModel.Resources.Core.ResourceContext; - mainResourceMap: Windows.ApplicationModel.Resources.Core.ResourceMap; - loadPriFiles(files: Windows.Foundation.Collections.IIterable): void; - unloadPriFiles(files: Windows.Foundation.Collections.IIterable): void; - static current: Windows.ApplicationModel.Resources.Core.ResourceManager; - static isResourceReference(resourceReference: string): boolean; - } - export interface IResourceQualifier { - isDefault: boolean; - isMatch: boolean; - qualifierName: string; - qualifierValue: string; - score: number; - } - export class ResourceQualifier implements Windows.ApplicationModel.Resources.Core.IResourceQualifier { - isDefault: boolean; - isMatch: boolean; - qualifierName: string; - qualifierValue: string; - score: number; - } - export interface IResourceContext { - languages: Windows.Foundation.Collections.IVectorView; - qualifierValues: Windows.Foundation.Collections.IObservableMap; - reset(): void; - reset(qualifierNames: Windows.Foundation.Collections.IIterable): void; - overrideToMatch(result: Windows.Foundation.Collections.IIterable): void; - clone(): Windows.ApplicationModel.Resources.Core.ResourceContext; - } - export interface IResourceContextStatics { - createMatchingContext(result: Windows.Foundation.Collections.IIterable): Windows.ApplicationModel.Resources.Core.ResourceContext; - } - export interface IResourceCandidate { - isDefault: boolean; - isMatch: boolean; - isMatchAsDefault: boolean; - qualifiers: Windows.Foundation.Collections.IVectorView; - valueAsString: string; - getValueAsFileAsync(): Windows.Foundation.IAsyncOperation; - getQualifierValue(qualifierName: string): string; - } - export class ResourceCandidate implements Windows.ApplicationModel.Resources.Core.IResourceCandidate { - isDefault: boolean; - isMatch: boolean; - isMatchAsDefault: boolean; - qualifiers: Windows.Foundation.Collections.IVectorView; - valueAsString: string; - getValueAsFileAsync(): Windows.Foundation.IAsyncOperation; - getQualifierValue(qualifierName: string): string; - } - export interface INamedResource { - candidates: Windows.Foundation.Collections.IVectorView; - uri: Windows.Foundation.Uri; - resolve(): Windows.ApplicationModel.Resources.Core.ResourceCandidate; - resolve(resourceContext: Windows.ApplicationModel.Resources.Core.ResourceContext): Windows.ApplicationModel.Resources.Core.ResourceCandidate; - resolveAll(): Windows.Foundation.Collections.IVectorView; - resolveAll(resourceContext: Windows.ApplicationModel.Resources.Core.ResourceContext): Windows.Foundation.Collections.IVectorView; - } - export class NamedResource implements Windows.ApplicationModel.Resources.Core.INamedResource { - candidates: Windows.Foundation.Collections.IVectorView; - uri: Windows.Foundation.Uri; - resolve(): Windows.ApplicationModel.Resources.Core.ResourceCandidate; - resolve(resourceContext: Windows.ApplicationModel.Resources.Core.ResourceContext): Windows.ApplicationModel.Resources.Core.ResourceCandidate; - resolveAll(): Windows.Foundation.Collections.IVectorView; - resolveAll(resourceContext: Windows.ApplicationModel.Resources.Core.ResourceContext): Windows.Foundation.Collections.IVectorView; - } - export interface IResourceMap extends Windows.Foundation.Collections.IMapView, Windows.Foundation.Collections.IIterable> { - uri: Windows.Foundation.Uri; - getValue(resource: string): Windows.ApplicationModel.Resources.Core.ResourceCandidate; - getValue(resource: string, context: Windows.ApplicationModel.Resources.Core.ResourceContext): Windows.ApplicationModel.Resources.Core.ResourceCandidate; - getSubtree(reference: string): Windows.ApplicationModel.Resources.Core.ResourceMap; - } - export class ResourceMapIterator implements Windows.Foundation.Collections.IIterator> { - current: Windows.Foundation.Collections.IKeyValuePair; - hasCurrent: boolean; - moveNext(): boolean; - getMany(): { items: Windows.Foundation.Collections.IKeyValuePair[]; returnValue: number; }; - } - export class ResourceMapMapView implements Windows.Foundation.Collections.IMapView, Windows.Foundation.Collections.IIterable> { - size: number; - lookup(key: string): Windows.ApplicationModel.Resources.Core.ResourceMap; - hasKey(key: string): boolean; - split(): { first: Windows.Foundation.Collections.IMapView; second: Windows.Foundation.Collections.IMapView; }; - first(): Windows.Foundation.Collections.IIterator>; - } - export class ResourceMapMapViewIterator implements Windows.Foundation.Collections.IIterator> { - current: Windows.Foundation.Collections.IKeyValuePair; - hasCurrent: boolean; - moveNext(): boolean; - getMany(): { items: Windows.Foundation.Collections.IKeyValuePair[]; returnValue: number; }; - } - export class ResourceQualifierObservableMap implements Windows.Foundation.Collections.IObservableMap, Windows.Foundation.Collections.IMap, Windows.Foundation.Collections.IIterable> { - size: number; - onmapchanged: any/* TODO */; - lookup(key: string): string; - hasKey(key: string): boolean; - getView(): Windows.Foundation.Collections.IMapView; - insert(key: string, value: string): boolean; - remove(key: string): void; - clear(): void; - first(): Windows.Foundation.Collections.IIterator>; - } - export class ResourceQualifierMapView implements Windows.Foundation.Collections.IMapView, Windows.Foundation.Collections.IIterable> { - size: number; - lookup(key: string): string; - hasKey(key: string): boolean; - split(): { first: Windows.Foundation.Collections.IMapView; second: Windows.Foundation.Collections.IMapView; }; - first(): Windows.Foundation.Collections.IIterator>; - } - export class ResourceQualifierVectorView implements Windows.Foundation.Collections.IVectorView, Windows.Foundation.Collections.IIterable { - size: number; - getAt(index: number): Windows.ApplicationModel.Resources.Core.ResourceQualifier; - indexOf(value: Windows.ApplicationModel.Resources.Core.ResourceQualifier): { index: number; returnValue: boolean; }; - getMany(startIndex: number): { items: Windows.ApplicationModel.Resources.Core.ResourceQualifier[]; returnValue: number; }; - first(): Windows.Foundation.Collections.IIterator; - toString(): string; - toLocaleString(): string; - concat(...items: Windows.ApplicationModel.Resources.Core.ResourceQualifier[][]): Windows.ApplicationModel.Resources.Core.ResourceQualifier[]; - join(seperator: string): string; - pop(): Windows.ApplicationModel.Resources.Core.ResourceQualifier; - push(...items: Windows.ApplicationModel.Resources.Core.ResourceQualifier[]): void; - reverse(): Windows.ApplicationModel.Resources.Core.ResourceQualifier[]; - shift(): Windows.ApplicationModel.Resources.Core.ResourceQualifier; - slice(start: number): Windows.ApplicationModel.Resources.Core.ResourceQualifier[]; - slice(start: number, end: number): Windows.ApplicationModel.Resources.Core.ResourceQualifier[]; - sort(): Windows.ApplicationModel.Resources.Core.ResourceQualifier[]; - sort(compareFn: (a: Windows.ApplicationModel.Resources.Core.ResourceQualifier, b: Windows.ApplicationModel.Resources.Core.ResourceQualifier) => number): Windows.ApplicationModel.Resources.Core.ResourceQualifier[]; - splice(start: number): Windows.ApplicationModel.Resources.Core.ResourceQualifier[]; - splice(start: number, deleteCount: number, ...items: Windows.ApplicationModel.Resources.Core.ResourceQualifier[]): Windows.ApplicationModel.Resources.Core.ResourceQualifier[]; - unshift(...items: Windows.ApplicationModel.Resources.Core.ResourceQualifier[]): number; - lastIndexOf(searchElement: Windows.ApplicationModel.Resources.Core.ResourceQualifier): number; - lastIndexOf(searchElement: Windows.ApplicationModel.Resources.Core.ResourceQualifier, fromIndex: number): number; - every(callbackfn: (value: Windows.ApplicationModel.Resources.Core.ResourceQualifier, index: number, array: Windows.ApplicationModel.Resources.Core.ResourceQualifier[]) => boolean): boolean; - every(callbackfn: (value: Windows.ApplicationModel.Resources.Core.ResourceQualifier, index: number, array: Windows.ApplicationModel.Resources.Core.ResourceQualifier[]) => boolean, thisArg: any): boolean; - some(callbackfn: (value: Windows.ApplicationModel.Resources.Core.ResourceQualifier, index: number, array: Windows.ApplicationModel.Resources.Core.ResourceQualifier[]) => boolean): boolean; - some(callbackfn: (value: Windows.ApplicationModel.Resources.Core.ResourceQualifier, index: number, array: Windows.ApplicationModel.Resources.Core.ResourceQualifier[]) => boolean, thisArg: any): boolean; - forEach(callbackfn: (value: Windows.ApplicationModel.Resources.Core.ResourceQualifier, index: number, array: Windows.ApplicationModel.Resources.Core.ResourceQualifier[]) => void ): void; - forEach(callbackfn: (value: Windows.ApplicationModel.Resources.Core.ResourceQualifier, index: number, array: Windows.ApplicationModel.Resources.Core.ResourceQualifier[]) => void , thisArg: any): void; - map(callbackfn: (value: Windows.ApplicationModel.Resources.Core.ResourceQualifier, index: number, array: Windows.ApplicationModel.Resources.Core.ResourceQualifier[]) => any): any[]; - map(callbackfn: (value: Windows.ApplicationModel.Resources.Core.ResourceQualifier, index: number, array: Windows.ApplicationModel.Resources.Core.ResourceQualifier[]) => any, thisArg: any): any[]; - filter(callbackfn: (value: Windows.ApplicationModel.Resources.Core.ResourceQualifier, index: number, array: Windows.ApplicationModel.Resources.Core.ResourceQualifier[]) => boolean): Windows.ApplicationModel.Resources.Core.ResourceQualifier[]; - filter(callbackfn: (value: Windows.ApplicationModel.Resources.Core.ResourceQualifier, index: number, array: Windows.ApplicationModel.Resources.Core.ResourceQualifier[]) => boolean, thisArg: any): Windows.ApplicationModel.Resources.Core.ResourceQualifier[]; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.ApplicationModel.Resources.Core.ResourceQualifier[]) => any): any; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.ApplicationModel.Resources.Core.ResourceQualifier[]) => any, initialValue: any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.ApplicationModel.Resources.Core.ResourceQualifier[]) => any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.ApplicationModel.Resources.Core.ResourceQualifier[]) => any, initialValue: any): any; - length: number; - } - export class ResourceCandidateVectorView implements Windows.Foundation.Collections.IVectorView, Windows.Foundation.Collections.IIterable { - size: number; - getAt(index: number): Windows.ApplicationModel.Resources.Core.ResourceCandidate; - indexOf(value: Windows.ApplicationModel.Resources.Core.ResourceCandidate): { index: number; returnValue: boolean; }; - getMany(startIndex: number): { items: Windows.ApplicationModel.Resources.Core.ResourceCandidate[]; returnValue: number; }; - first(): Windows.Foundation.Collections.IIterator; - toString(): string; - toLocaleString(): string; - concat(...items: Windows.ApplicationModel.Resources.Core.ResourceCandidate[][]): Windows.ApplicationModel.Resources.Core.ResourceCandidate[]; - join(seperator: string): string; - pop(): Windows.ApplicationModel.Resources.Core.ResourceCandidate; - push(...items: Windows.ApplicationModel.Resources.Core.ResourceCandidate[]): void; - reverse(): Windows.ApplicationModel.Resources.Core.ResourceCandidate[]; - shift(): Windows.ApplicationModel.Resources.Core.ResourceCandidate; - slice(start: number): Windows.ApplicationModel.Resources.Core.ResourceCandidate[]; - slice(start: number, end: number): Windows.ApplicationModel.Resources.Core.ResourceCandidate[]; - sort(): Windows.ApplicationModel.Resources.Core.ResourceCandidate[]; - sort(compareFn: (a: Windows.ApplicationModel.Resources.Core.ResourceCandidate, b: Windows.ApplicationModel.Resources.Core.ResourceCandidate) => number): Windows.ApplicationModel.Resources.Core.ResourceCandidate[]; - splice(start: number): Windows.ApplicationModel.Resources.Core.ResourceCandidate[]; - splice(start: number, deleteCount: number, ...items: Windows.ApplicationModel.Resources.Core.ResourceCandidate[]): Windows.ApplicationModel.Resources.Core.ResourceCandidate[]; - unshift(...items: Windows.ApplicationModel.Resources.Core.ResourceCandidate[]): number; - lastIndexOf(searchElement: Windows.ApplicationModel.Resources.Core.ResourceCandidate): number; - lastIndexOf(searchElement: Windows.ApplicationModel.Resources.Core.ResourceCandidate, fromIndex: number): number; - every(callbackfn: (value: Windows.ApplicationModel.Resources.Core.ResourceCandidate, index: number, array: Windows.ApplicationModel.Resources.Core.ResourceCandidate[]) => boolean): boolean; - every(callbackfn: (value: Windows.ApplicationModel.Resources.Core.ResourceCandidate, index: number, array: Windows.ApplicationModel.Resources.Core.ResourceCandidate[]) => boolean, thisArg: any): boolean; - some(callbackfn: (value: Windows.ApplicationModel.Resources.Core.ResourceCandidate, index: number, array: Windows.ApplicationModel.Resources.Core.ResourceCandidate[]) => boolean): boolean; - some(callbackfn: (value: Windows.ApplicationModel.Resources.Core.ResourceCandidate, index: number, array: Windows.ApplicationModel.Resources.Core.ResourceCandidate[]) => boolean, thisArg: any): boolean; - forEach(callbackfn: (value: Windows.ApplicationModel.Resources.Core.ResourceCandidate, index: number, array: Windows.ApplicationModel.Resources.Core.ResourceCandidate[]) => void ): void; - forEach(callbackfn: (value: Windows.ApplicationModel.Resources.Core.ResourceCandidate, index: number, array: Windows.ApplicationModel.Resources.Core.ResourceCandidate[]) => void , thisArg: any): void; - map(callbackfn: (value: Windows.ApplicationModel.Resources.Core.ResourceCandidate, index: number, array: Windows.ApplicationModel.Resources.Core.ResourceCandidate[]) => any): any[]; - map(callbackfn: (value: Windows.ApplicationModel.Resources.Core.ResourceCandidate, index: number, array: Windows.ApplicationModel.Resources.Core.ResourceCandidate[]) => any, thisArg: any): any[]; - filter(callbackfn: (value: Windows.ApplicationModel.Resources.Core.ResourceCandidate, index: number, array: Windows.ApplicationModel.Resources.Core.ResourceCandidate[]) => boolean): Windows.ApplicationModel.Resources.Core.ResourceCandidate[]; - filter(callbackfn: (value: Windows.ApplicationModel.Resources.Core.ResourceCandidate, index: number, array: Windows.ApplicationModel.Resources.Core.ResourceCandidate[]) => boolean, thisArg: any): Windows.ApplicationModel.Resources.Core.ResourceCandidate[]; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.ApplicationModel.Resources.Core.ResourceCandidate[]) => any): any; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.ApplicationModel.Resources.Core.ResourceCandidate[]) => any, initialValue: any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.ApplicationModel.Resources.Core.ResourceCandidate[]) => any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.ApplicationModel.Resources.Core.ResourceCandidate[]) => any, initialValue: any): any; - length: number; - } - export class ResourceContextLanguagesVectorView implements Windows.Foundation.Collections.IVectorView, Windows.Foundation.Collections.IIterable { - size: number; - getAt(index: number): string; - indexOf(value: string): { index: number; returnValue: boolean; }; - getMany(startIndex: number): { items: string[]; returnValue: number; }; - first(): Windows.Foundation.Collections.IIterator; - toString(): string; - toLocaleString(): string; - concat(...items: string[][]): string[]; - join(seperator: string): string; - pop(): string; - push(...items: string[]): void; - reverse(): string[]; - shift(): string; - slice(start: number): string[]; - slice(start: number, end: number): string[]; - sort(): string[]; - sort(compareFn: (a: string, b: string) => number): string[]; - splice(start: number): string[]; - splice(start: number, deleteCount: number, ...items: string[]): string[]; - unshift(...items: string[]): number; - lastIndexOf(searchElement: string): number; - lastIndexOf(searchElement: string, fromIndex: number): number; - every(callbackfn: (value: string, index: number, array: string[]) => boolean): boolean; - every(callbackfn: (value: string, index: number, array: string[]) => boolean, thisArg: any): boolean; - some(callbackfn: (value: string, index: number, array: string[]) => boolean): boolean; - some(callbackfn: (value: string, index: number, array: string[]) => boolean, thisArg: any): boolean; - forEach(callbackfn: (value: string, index: number, array: string[]) => void ): void; - forEach(callbackfn: (value: string, index: number, array: string[]) => void , thisArg: any): void; - map(callbackfn: (value: string, index: number, array: string[]) => any): any[]; - map(callbackfn: (value: string, index: number, array: string[]) => any, thisArg: any): any[]; - filter(callbackfn: (value: string, index: number, array: string[]) => boolean): string[]; - filter(callbackfn: (value: string, index: number, array: string[]) => boolean, thisArg: any): string[]; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: string[]) => any): any; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: string[]) => any, initialValue: any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: string[]) => any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: string[]) => any, initialValue: any): any; - length: number; - } - } - } - } -} -declare module Windows { - export module ApplicationModel { - export module Resources { - export module Management { - export enum IndexedResourceType { - string, - path, - } - export interface IResourceIndexer { - indexFilePath(filePath: Windows.Foundation.Uri): Windows.ApplicationModel.Resources.Management.IndexedResourceCandidate; - indexFileContentsAsync(file: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperation>; - } - export class IndexedResourceCandidate implements Windows.ApplicationModel.Resources.Management.IIndexedResourceCandidate { - metadata: Windows.Foundation.Collections.IMapView; - qualifiers: Windows.Foundation.Collections.IVectorView; - type: Windows.ApplicationModel.Resources.Management.IndexedResourceType; - uri: Windows.Foundation.Uri; - valueAsString: string; - getQualifierValue(qualifierName: string): string; - } - export interface IResourceIndexerFactory { - createResourceIndexer(projectRoot: Windows.Foundation.Uri): Windows.ApplicationModel.Resources.Management.ResourceIndexer; - } - export class ResourceIndexer implements Windows.ApplicationModel.Resources.Management.IResourceIndexer { - constructor(projectRoot: Windows.Foundation.Uri); - indexFilePath(filePath: Windows.Foundation.Uri): Windows.ApplicationModel.Resources.Management.IndexedResourceCandidate; - indexFileContentsAsync(file: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperation>; - } - export interface IIndexedResourceQualifier { - qualifierName: string; - qualifierValue: string; - } - export interface IIndexedResourceCandidate { - metadata: Windows.Foundation.Collections.IMapView; - qualifiers: Windows.Foundation.Collections.IVectorView; - type: Windows.ApplicationModel.Resources.Management.IndexedResourceType; - uri: Windows.Foundation.Uri; - valueAsString: string; - getQualifierValue(qualifierName: string): string; - } - export class IndexedResourceQualifier implements Windows.ApplicationModel.Resources.Management.IIndexedResourceQualifier { - qualifierName: string; - qualifierValue: string; - } - } - } - } -} -declare module Windows { - export module ApplicationModel { - export module Store { - export interface LicenseChangedEventHandler { - (): void; - } - export interface ICurrentApp { - appId: string; - licenseInformation: Windows.ApplicationModel.Store.LicenseInformation; - linkUri: Windows.Foundation.Uri; - requestAppPurchaseAsync(includeReceipt: boolean): Windows.Foundation.IAsyncOperation; - requestProductPurchaseAsync(productId: string, includeReceipt: boolean): Windows.Foundation.IAsyncOperation; - loadListingInformationAsync(): Windows.Foundation.IAsyncOperation; - getAppReceiptAsync(): Windows.Foundation.IAsyncOperation; - getProductReceiptAsync(productId: string): Windows.Foundation.IAsyncOperation; - } - export class LicenseInformation implements Windows.ApplicationModel.Store.ILicenseInformation { - expirationDate: Date; - isActive: boolean; - isTrial: boolean; - productLicenses: Windows.Foundation.Collections.IMapView; - onlicensechanged: any/* TODO */; - } - export class ListingInformation implements Windows.ApplicationModel.Store.IListingInformation { - ageRating: number; - currentMarket: string; - description: string; - formattedPrice: string; - name: string; - productListings: Windows.Foundation.Collections.IMapView; - } - export interface ICurrentAppSimulator { - appId: string; - licenseInformation: Windows.ApplicationModel.Store.LicenseInformation; - linkUri: Windows.Foundation.Uri; - requestAppPurchaseAsync(includeReceipt: boolean): Windows.Foundation.IAsyncOperation; - requestProductPurchaseAsync(productId: string, includeReceipt: boolean): Windows.Foundation.IAsyncOperation; - loadListingInformationAsync(): Windows.Foundation.IAsyncOperation; - getAppReceiptAsync(): Windows.Foundation.IAsyncOperation; - getProductReceiptAsync(productId: string): Windows.Foundation.IAsyncOperation; - reloadSimulatorAsync(simulatorSettingsFile: Windows.Storage.StorageFile): Windows.Foundation.IAsyncAction; - } - export interface ILicenseInformation { - expirationDate: Date; - isActive: boolean; - isTrial: boolean; - productLicenses: Windows.Foundation.Collections.IMapView; - onlicensechanged: any/* TODO */; - } - export class ProductLicense implements Windows.ApplicationModel.Store.IProductLicense { - expirationDate: Date; - isActive: boolean; - productId: string; - } - export interface IProductLicense { - expirationDate: Date; - isActive: boolean; - productId: string; - } - export interface IListingInformation { - ageRating: number; - currentMarket: string; - description: string; - formattedPrice: string; - name: string; - productListings: Windows.Foundation.Collections.IMapView; - } - export class ProductListing implements Windows.ApplicationModel.Store.IProductListing { - formattedPrice: string; - name: string; - productId: string; - } - export interface IProductListing { - formattedPrice: string; - name: string; - productId: string; - } - export class CurrentApp { - static appId: string; - static licenseInformation: Windows.ApplicationModel.Store.LicenseInformation; - static linkUri: Windows.Foundation.Uri; - static requestAppPurchaseAsync(includeReceipt: boolean): Windows.Foundation.IAsyncOperation; - static requestProductPurchaseAsync(productId: string, includeReceipt: boolean): Windows.Foundation.IAsyncOperation; - static loadListingInformationAsync(): Windows.Foundation.IAsyncOperation; - static getAppReceiptAsync(): Windows.Foundation.IAsyncOperation; - static getProductReceiptAsync(productId: string): Windows.Foundation.IAsyncOperation; - } - export class CurrentAppSimulator { - static appId: string; - static licenseInformation: Windows.ApplicationModel.Store.LicenseInformation; - static linkUri: Windows.Foundation.Uri; - static requestAppPurchaseAsync(includeReceipt: boolean): Windows.Foundation.IAsyncOperation; - static requestProductPurchaseAsync(productId: string, includeReceipt: boolean): Windows.Foundation.IAsyncOperation; - static loadListingInformationAsync(): Windows.Foundation.IAsyncOperation; - static getAppReceiptAsync(): Windows.Foundation.IAsyncOperation; - static getProductReceiptAsync(productId: string): Windows.Foundation.IAsyncOperation; - static reloadSimulatorAsync(simulatorSettingsFile: Windows.Storage.StorageFile): Windows.Foundation.IAsyncAction; - } - } - } -} -declare module Windows { - export module Data { - export module Html { - export interface IHtmlUtilities { - convertToText(html: string): string; - } - export class HtmlUtilities { - static convertToText(html: string): string; - } - } - } -} -declare module Windows { - export module Data { - export module Json { - export enum JsonValueType { - null_, - boolean, - number, - string, - array, - object, - } - export enum JsonErrorStatus { - unknown, - invalidJsonString, - invalidJsonNumber, - jsonValueNotFound, - implementationLimit, - } - export interface IJsonValue { - valueType: Windows.Data.Json.JsonValueType; - stringify(): string; - getString(): string; - getNumber(): number; - getBoolean(): boolean; - getArray(): Windows.Data.Json.JsonArray; - getObject(): Windows.Data.Json.JsonObject; - } - export class JsonArray implements Windows.Data.Json.IJsonArray, Windows.Data.Json.IJsonValue, Windows.Foundation.Collections.IVector, Windows.Foundation.Collections.IIterable { - valueType: Windows.Data.Json.JsonValueType; - size: number; - getObjectAt(index: number): Windows.Data.Json.JsonObject; - getArrayAt(index: number): Windows.Data.Json.JsonArray; - getStringAt(index: number): string; - getNumberAt(index: number): number; - getBooleanAt(index: number): boolean; - stringify(): string; - getString(): string; - getNumber(): number; - getBoolean(): boolean; - getArray(): Windows.Data.Json.JsonArray; - getObject(): Windows.Data.Json.JsonObject; - getAt(index: number): Windows.Data.Json.IJsonValue; - getView(): Windows.Foundation.Collections.IVectorView; - indexOf(value: Windows.Data.Json.IJsonValue): { index: number; returnValue: boolean; }; - setAt(index: number, value: Windows.Data.Json.IJsonValue): void; - insertAt(index: number, value: Windows.Data.Json.IJsonValue): void; - removeAt(index: number): void; - append(value: Windows.Data.Json.IJsonValue): void; - removeAtEnd(): void; - clear(): void; - getMany(startIndex: number): { items: Windows.Data.Json.IJsonValue[]; returnValue: number; }; - replaceAll(items: Windows.Data.Json.IJsonValue[]): void; - first(): Windows.Foundation.Collections.IIterator; - static parse(input: string): Windows.Data.Json.JsonArray; - static tryParse(input: string): { result: Windows.Data.Json.JsonArray; succeeded: boolean; }; - toString(): string; - toLocaleString(): string; - concat(...items: Windows.Data.Json.IJsonValue[][]): Windows.Data.Json.IJsonValue[]; - join(seperator: string): string; - pop(): Windows.Data.Json.IJsonValue; - push(...items: Windows.Data.Json.IJsonValue[]): void; - reverse(): Windows.Data.Json.IJsonValue[]; - shift(): Windows.Data.Json.IJsonValue; - slice(start: number): Windows.Data.Json.IJsonValue[]; - slice(start: number, end: number): Windows.Data.Json.IJsonValue[]; - sort(): Windows.Data.Json.IJsonValue[]; - sort(compareFn: (a: Windows.Data.Json.IJsonValue, b: Windows.Data.Json.IJsonValue) => number): Windows.Data.Json.IJsonValue[]; - splice(start: number): Windows.Data.Json.IJsonValue[]; - splice(start: number, deleteCount: number, ...items: Windows.Data.Json.IJsonValue[]): Windows.Data.Json.IJsonValue[]; - unshift(...items: Windows.Data.Json.IJsonValue[]): number; - lastIndexOf(searchElement: Windows.Data.Json.IJsonValue): number; - lastIndexOf(searchElement: Windows.Data.Json.IJsonValue, fromIndex: number): number; - every(callbackfn: (value: Windows.Data.Json.IJsonValue, index: number, array: Windows.Data.Json.IJsonValue[]) => boolean): boolean; - every(callbackfn: (value: Windows.Data.Json.IJsonValue, index: number, array: Windows.Data.Json.IJsonValue[]) => boolean, thisArg: any): boolean; - some(callbackfn: (value: Windows.Data.Json.IJsonValue, index: number, array: Windows.Data.Json.IJsonValue[]) => boolean): boolean; - some(callbackfn: (value: Windows.Data.Json.IJsonValue, index: number, array: Windows.Data.Json.IJsonValue[]) => boolean, thisArg: any): boolean; - forEach(callbackfn: (value: Windows.Data.Json.IJsonValue, index: number, array: Windows.Data.Json.IJsonValue[]) => void ): void; - forEach(callbackfn: (value: Windows.Data.Json.IJsonValue, index: number, array: Windows.Data.Json.IJsonValue[]) => void , thisArg: any): void; - map(callbackfn: (value: Windows.Data.Json.IJsonValue, index: number, array: Windows.Data.Json.IJsonValue[]) => any): any[]; - map(callbackfn: (value: Windows.Data.Json.IJsonValue, index: number, array: Windows.Data.Json.IJsonValue[]) => any, thisArg: any): any[]; - filter(callbackfn: (value: Windows.Data.Json.IJsonValue, index: number, array: Windows.Data.Json.IJsonValue[]) => boolean): Windows.Data.Json.IJsonValue[]; - filter(callbackfn: (value: Windows.Data.Json.IJsonValue, index: number, array: Windows.Data.Json.IJsonValue[]) => boolean, thisArg: any): Windows.Data.Json.IJsonValue[]; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Data.Json.IJsonValue[]) => any): any; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Data.Json.IJsonValue[]) => any, initialValue: any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Data.Json.IJsonValue[]) => any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Data.Json.IJsonValue[]) => any, initialValue: any): any; - length: number; - } - export class JsonObject implements Windows.Data.Json.IJsonObject, Windows.Data.Json.IJsonValue, Windows.Foundation.Collections.IMap, Windows.Foundation.Collections.IIterable> { - valueType: Windows.Data.Json.JsonValueType; - size: number; - getNamedValue(name: string): Windows.Data.Json.JsonValue; - setNamedValue(name: string, value: Windows.Data.Json.IJsonValue): void; - getNamedObject(name: string): Windows.Data.Json.JsonObject; - getNamedArray(name: string): Windows.Data.Json.JsonArray; - getNamedString(name: string): string; - getNamedNumber(name: string): number; - getNamedBoolean(name: string): boolean; - stringify(): string; - getString(): string; - getNumber(): number; - getBoolean(): boolean; - getArray(): Windows.Data.Json.JsonArray; - getObject(): Windows.Data.Json.JsonObject; - lookup(key: string): Windows.Data.Json.IJsonValue; - hasKey(key: string): boolean; - getView(): Windows.Foundation.Collections.IMapView; - insert(key: string, value: Windows.Data.Json.IJsonValue): boolean; - remove(key: string): void; - clear(): void; - first(): Windows.Foundation.Collections.IIterator>; - static parse(input: string): Windows.Data.Json.JsonObject; - static tryParse(input: string): { result: Windows.Data.Json.JsonObject; succeeded: boolean; }; - } - export interface IJsonValueStatics { - parse(input: string): Windows.Data.Json.JsonValue; - tryParse(input: string): { result: Windows.Data.Json.JsonValue; succeeded: boolean; }; - createBooleanValue(input: boolean): Windows.Data.Json.JsonValue; - createNumberValue(input: number): Windows.Data.Json.JsonValue; - createStringValue(input: string): Windows.Data.Json.JsonValue; - } - export class JsonValue implements Windows.Data.Json.IJsonValue { - valueType: Windows.Data.Json.JsonValueType; - stringify(): string; - getString(): string; - getNumber(): number; - getBoolean(): boolean; - getArray(): Windows.Data.Json.JsonArray; - getObject(): Windows.Data.Json.JsonObject; - static parse(input: string): Windows.Data.Json.JsonValue; - static tryParse(input: string): { result: Windows.Data.Json.JsonValue; succeeded: boolean; }; - static createBooleanValue(input: boolean): Windows.Data.Json.JsonValue; - static createNumberValue(input: number): Windows.Data.Json.JsonValue; - static createStringValue(input: string): Windows.Data.Json.JsonValue; - } - export interface IJsonObject extends Windows.Data.Json.IJsonValue { - getNamedValue(name: string): Windows.Data.Json.JsonValue; - setNamedValue(name: string, value: Windows.Data.Json.IJsonValue): void; - getNamedObject(name: string): Windows.Data.Json.JsonObject; - getNamedArray(name: string): Windows.Data.Json.JsonArray; - getNamedString(name: string): string; - getNamedNumber(name: string): number; - getNamedBoolean(name: string): boolean; - } - export interface IJsonObjectStatics { - parse(input: string): Windows.Data.Json.JsonObject; - tryParse(input: string): { result: Windows.Data.Json.JsonObject; succeeded: boolean; }; - } - export interface IJsonArray extends Windows.Data.Json.IJsonValue { - getObjectAt(index: number): Windows.Data.Json.JsonObject; - getArrayAt(index: number): Windows.Data.Json.JsonArray; - getStringAt(index: number): string; - getNumberAt(index: number): number; - getBooleanAt(index: number): boolean; - } - export interface IJsonArrayStatics { - parse(input: string): Windows.Data.Json.JsonArray; - tryParse(input: string): { result: Windows.Data.Json.JsonArray; succeeded: boolean; }; - } - export interface IJsonErrorStatics { - getStatus(hresult: number): Windows.Data.Json.JsonErrorStatus; - } - export class JsonError { - static getStatus(hresult: number): Windows.Data.Json.JsonErrorStatus; - } - } - } -} -declare module Windows { - export module Data { - export module Xml { - export module Dom { - export enum NodeType { - invalid, - elementNode, - attributeNode, - textNode, - dataSectionNode, - entityReferenceNode, - entityNode, - processingInstructionNode, - commentNode, - documentNode, - documentTypeNode, - documentFragmentNode, - notationNode, - } - export interface IXmlNodeSelector { - selectSingleNode(xpath: string): Windows.Data.Xml.Dom.IXmlNode; - selectNodes(xpath: string): Windows.Data.Xml.Dom.XmlNodeList; - selectSingleNodeNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.IXmlNode; - selectNodesNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.XmlNodeList; - } - export class XmlNodeList implements Windows.Data.Xml.Dom.IXmlNodeList, Windows.Foundation.Collections.IVectorView, Windows.Foundation.Collections.IIterable { - length: number; - size: number; - item(index: number): Windows.Data.Xml.Dom.IXmlNode; - getAt(index: number): Windows.Data.Xml.Dom.IXmlNode; - indexOf(value: Windows.Data.Xml.Dom.IXmlNode): { index: number; returnValue: boolean; }; - getMany(startIndex: number): { items: Windows.Data.Xml.Dom.IXmlNode[]; returnValue: number; }; - first(): Windows.Foundation.Collections.IIterator; - toString(): string; - toLocaleString(): string; - concat(...items: Windows.Data.Xml.Dom.IXmlNode[][]): Windows.Data.Xml.Dom.IXmlNode[]; - join(seperator: string): string; - pop(): Windows.Data.Xml.Dom.IXmlNode; - push(...items: Windows.Data.Xml.Dom.IXmlNode[]): void; - reverse(): Windows.Data.Xml.Dom.IXmlNode[]; - shift(): Windows.Data.Xml.Dom.IXmlNode; - slice(start: number): Windows.Data.Xml.Dom.IXmlNode[]; - slice(start: number, end: number): Windows.Data.Xml.Dom.IXmlNode[]; - sort(): Windows.Data.Xml.Dom.IXmlNode[]; - sort(compareFn: (a: Windows.Data.Xml.Dom.IXmlNode, b: Windows.Data.Xml.Dom.IXmlNode) => number): Windows.Data.Xml.Dom.IXmlNode[]; - splice(start: number): Windows.Data.Xml.Dom.IXmlNode[]; - splice(start: number, deleteCount: number, ...items: Windows.Data.Xml.Dom.IXmlNode[]): Windows.Data.Xml.Dom.IXmlNode[]; - unshift(...items: Windows.Data.Xml.Dom.IXmlNode[]): number; - lastIndexOf(searchElement: Windows.Data.Xml.Dom.IXmlNode): number; - lastIndexOf(searchElement: Windows.Data.Xml.Dom.IXmlNode, fromIndex: number): number; - every(callbackfn: (value: Windows.Data.Xml.Dom.IXmlNode, index: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => boolean): boolean; - every(callbackfn: (value: Windows.Data.Xml.Dom.IXmlNode, index: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => boolean, thisArg: any): boolean; - some(callbackfn: (value: Windows.Data.Xml.Dom.IXmlNode, index: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => boolean): boolean; - some(callbackfn: (value: Windows.Data.Xml.Dom.IXmlNode, index: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => boolean, thisArg: any): boolean; - forEach(callbackfn: (value: Windows.Data.Xml.Dom.IXmlNode, index: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => void ): void; - forEach(callbackfn: (value: Windows.Data.Xml.Dom.IXmlNode, index: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => void , thisArg: any): void; - map(callbackfn: (value: Windows.Data.Xml.Dom.IXmlNode, index: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => any): any[]; - map(callbackfn: (value: Windows.Data.Xml.Dom.IXmlNode, index: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => any, thisArg: any): any[]; - filter(callbackfn: (value: Windows.Data.Xml.Dom.IXmlNode, index: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => boolean): Windows.Data.Xml.Dom.IXmlNode[]; - filter(callbackfn: (value: Windows.Data.Xml.Dom.IXmlNode, index: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => boolean, thisArg: any): Windows.Data.Xml.Dom.IXmlNode[]; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => any): any; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => any, initialValue: any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => any, initialValue: any): any; - } - export class XmlNamedNodeMap implements Windows.Data.Xml.Dom.IXmlNamedNodeMap, Windows.Foundation.Collections.IVectorView, Windows.Foundation.Collections.IIterable { - length: number; - size: number; - item(index: number): Windows.Data.Xml.Dom.IXmlNode; - getNamedItem(name: string): Windows.Data.Xml.Dom.IXmlNode; - setNamedItem(node: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - removeNamedItem(name: string): Windows.Data.Xml.Dom.IXmlNode; - getNamedItemNS(namespaceUri: any, name: string): Windows.Data.Xml.Dom.IXmlNode; - removeNamedItemNS(namespaceUri: any, name: string): Windows.Data.Xml.Dom.IXmlNode; - setNamedItemNS(node: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - getAt(index: number): Windows.Data.Xml.Dom.IXmlNode; - indexOf(value: Windows.Data.Xml.Dom.IXmlNode): { index: number; returnValue: boolean; }; - getMany(startIndex: number): { items: Windows.Data.Xml.Dom.IXmlNode[]; returnValue: number; }; - first(): Windows.Foundation.Collections.IIterator; - toString(): string; - toLocaleString(): string; - concat(...items: Windows.Data.Xml.Dom.IXmlNode[][]): Windows.Data.Xml.Dom.IXmlNode[]; - join(seperator: string): string; - pop(): Windows.Data.Xml.Dom.IXmlNode; - push(...items: Windows.Data.Xml.Dom.IXmlNode[]): void; - reverse(): Windows.Data.Xml.Dom.IXmlNode[]; - shift(): Windows.Data.Xml.Dom.IXmlNode; - slice(start: number): Windows.Data.Xml.Dom.IXmlNode[]; - slice(start: number, end: number): Windows.Data.Xml.Dom.IXmlNode[]; - sort(): Windows.Data.Xml.Dom.IXmlNode[]; - sort(compareFn: (a: Windows.Data.Xml.Dom.IXmlNode, b: Windows.Data.Xml.Dom.IXmlNode) => number): Windows.Data.Xml.Dom.IXmlNode[]; - splice(start: number): Windows.Data.Xml.Dom.IXmlNode[]; - splice(start: number, deleteCount: number, ...items: Windows.Data.Xml.Dom.IXmlNode[]): Windows.Data.Xml.Dom.IXmlNode[]; - unshift(...items: Windows.Data.Xml.Dom.IXmlNode[]): number; - lastIndexOf(searchElement: Windows.Data.Xml.Dom.IXmlNode): number; - lastIndexOf(searchElement: Windows.Data.Xml.Dom.IXmlNode, fromIndex: number): number; - every(callbackfn: (value: Windows.Data.Xml.Dom.IXmlNode, index: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => boolean): boolean; - every(callbackfn: (value: Windows.Data.Xml.Dom.IXmlNode, index: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => boolean, thisArg: any): boolean; - some(callbackfn: (value: Windows.Data.Xml.Dom.IXmlNode, index: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => boolean): boolean; - some(callbackfn: (value: Windows.Data.Xml.Dom.IXmlNode, index: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => boolean, thisArg: any): boolean; - forEach(callbackfn: (value: Windows.Data.Xml.Dom.IXmlNode, index: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => void ): void; - forEach(callbackfn: (value: Windows.Data.Xml.Dom.IXmlNode, index: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => void , thisArg: any): void; - map(callbackfn: (value: Windows.Data.Xml.Dom.IXmlNode, index: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => any): any[]; - map(callbackfn: (value: Windows.Data.Xml.Dom.IXmlNode, index: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => any, thisArg: any): any[]; - filter(callbackfn: (value: Windows.Data.Xml.Dom.IXmlNode, index: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => boolean): Windows.Data.Xml.Dom.IXmlNode[]; - filter(callbackfn: (value: Windows.Data.Xml.Dom.IXmlNode, index: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => boolean, thisArg: any): Windows.Data.Xml.Dom.IXmlNode[]; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => any): any; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => any, initialValue: any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Data.Xml.Dom.IXmlNode[]) => any, initialValue: any): any; - } - export class XmlDocument implements Windows.Data.Xml.Dom.IXmlDocument, Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer, Windows.Data.Xml.Dom.IXmlDocumentIO { - doctype: Windows.Data.Xml.Dom.XmlDocumentType; - documentElement: Windows.Data.Xml.Dom.XmlElement; - documentUri: string; - implementation: Windows.Data.Xml.Dom.XmlDomImplementation; - attributes: Windows.Data.Xml.Dom.XmlNamedNodeMap; - childNodes: Windows.Data.Xml.Dom.XmlNodeList; - firstChild: Windows.Data.Xml.Dom.IXmlNode; - lastChild: Windows.Data.Xml.Dom.IXmlNode; - localName: any; - namespaceUri: any; - nextSibling: Windows.Data.Xml.Dom.IXmlNode; - nodeName: string; - nodeType: Windows.Data.Xml.Dom.NodeType; - nodeValue: any; - ownerDocument: Windows.Data.Xml.Dom.XmlDocument; - parentNode: Windows.Data.Xml.Dom.IXmlNode; - prefix: any; - previousSibling: Windows.Data.Xml.Dom.IXmlNode; - innerText: string; - createElement(tagName: string): Windows.Data.Xml.Dom.XmlElement; - createDocumentFragment(): Windows.Data.Xml.Dom.XmlDocumentFragment; - createTextNode(data: string): Windows.Data.Xml.Dom.XmlText; - createComment(data: string): Windows.Data.Xml.Dom.XmlComment; - createProcessingInstruction(target: string, data: string): Windows.Data.Xml.Dom.XmlProcessingInstruction; - createAttribute(name: string): Windows.Data.Xml.Dom.XmlAttribute; - createEntityReference(name: string): Windows.Data.Xml.Dom.XmlEntityReference; - getElementsByTagName(tagName: string): Windows.Data.Xml.Dom.XmlNodeList; - createCDataSection(data: string): Windows.Data.Xml.Dom.XmlCDataSection; - createAttributeNS(namespaceUri: any, qualifiedName: string): Windows.Data.Xml.Dom.XmlAttribute; - createElementNS(namespaceUri: any, qualifiedName: string): Windows.Data.Xml.Dom.XmlElement; - getElementById(elementId: string): Windows.Data.Xml.Dom.XmlElement; - importNode(node: Windows.Data.Xml.Dom.IXmlNode, deep: boolean): Windows.Data.Xml.Dom.IXmlNode; - hasChildNodes(): boolean; - insertBefore(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - replaceChild(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - removeChild(childNode: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - appendChild(newChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - cloneNode(deep: boolean): Windows.Data.Xml.Dom.IXmlNode; - normalize(): void; - selectSingleNode(xpath: string): Windows.Data.Xml.Dom.IXmlNode; - selectNodes(xpath: string): Windows.Data.Xml.Dom.XmlNodeList; - selectSingleNodeNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.IXmlNode; - selectNodesNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.XmlNodeList; - getXml(): string; - loadXml(xml: string): void; - loadXml(xml: string, loadSettings: Windows.Data.Xml.Dom.XmlLoadSettings): void; - saveToFileAsync(file: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncAction; - static loadFromUriAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperation; - static loadFromUriAsync(uri: Windows.Foundation.Uri, loadSettings: Windows.Data.Xml.Dom.XmlLoadSettings): Windows.Foundation.IAsyncOperation; - static loadFromFileAsync(file: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncOperation; - static loadFromFileAsync(file: Windows.Storage.IStorageFile, loadSettings: Windows.Data.Xml.Dom.XmlLoadSettings): Windows.Foundation.IAsyncOperation; - } - export interface IXmlNodeSerializer { - innerText: string; - getXml(): string; - } - export interface IXmlNode extends Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - attributes: Windows.Data.Xml.Dom.XmlNamedNodeMap; - childNodes: Windows.Data.Xml.Dom.XmlNodeList; - firstChild: Windows.Data.Xml.Dom.IXmlNode; - lastChild: Windows.Data.Xml.Dom.IXmlNode; - localName: any; - namespaceUri: any; - nextSibling: Windows.Data.Xml.Dom.IXmlNode; - nodeName: string; - nodeType: Windows.Data.Xml.Dom.NodeType; - nodeValue: any; - ownerDocument: Windows.Data.Xml.Dom.XmlDocument; - parentNode: Windows.Data.Xml.Dom.IXmlNode; - prefix: any; - previousSibling: Windows.Data.Xml.Dom.IXmlNode; - hasChildNodes(): boolean; - insertBefore(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - replaceChild(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - removeChild(childNode: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - appendChild(newChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - cloneNode(deep: boolean): Windows.Data.Xml.Dom.IXmlNode; - normalize(): void; - } - export interface IXmlDomImplementation { - hasFeature(feature: string, version: any): boolean; - } - export interface IXmlDocumentType extends Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - entities: Windows.Data.Xml.Dom.XmlNamedNodeMap; - name: string; - notations: Windows.Data.Xml.Dom.XmlNamedNodeMap; - } - export interface IXmlAttribute extends Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - name: string; - specified: boolean; - value: string; - } - export interface IXmlDocumentFragment extends Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - } - export interface IXmlElement extends Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - tagName: string; - getAttribute(attributeName: string): string; - setAttribute(attributeName: string, attributeValue: string): void; - removeAttribute(attributeName: string): void; - getAttributeNode(attributeName: string): Windows.Data.Xml.Dom.XmlAttribute; - setAttributeNode(newAttribute: Windows.Data.Xml.Dom.XmlAttribute): Windows.Data.Xml.Dom.XmlAttribute; - removeAttributeNode(attributeNode: Windows.Data.Xml.Dom.XmlAttribute): Windows.Data.Xml.Dom.XmlAttribute; - getElementsByTagName(tagName: string): Windows.Data.Xml.Dom.XmlNodeList; - setAttributeNS(namespaceUri: any, qualifiedName: string, value: string): void; - getAttributeNS(namespaceUri: any, localName: string): string; - removeAttributeNS(namespaceUri: any, localName: string): void; - setAttributeNodeNS(newAttribute: Windows.Data.Xml.Dom.XmlAttribute): Windows.Data.Xml.Dom.XmlAttribute; - getAttributeNodeNS(namespaceUri: any, localName: string): Windows.Data.Xml.Dom.XmlAttribute; - } - export class XmlAttribute implements Windows.Data.Xml.Dom.IXmlAttribute, Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - name: string; - specified: boolean; - value: string; - attributes: Windows.Data.Xml.Dom.XmlNamedNodeMap; - childNodes: Windows.Data.Xml.Dom.XmlNodeList; - firstChild: Windows.Data.Xml.Dom.IXmlNode; - lastChild: Windows.Data.Xml.Dom.IXmlNode; - localName: any; - namespaceUri: any; - nextSibling: Windows.Data.Xml.Dom.IXmlNode; - nodeName: string; - nodeType: Windows.Data.Xml.Dom.NodeType; - nodeValue: any; - ownerDocument: Windows.Data.Xml.Dom.XmlDocument; - parentNode: Windows.Data.Xml.Dom.IXmlNode; - prefix: any; - previousSibling: Windows.Data.Xml.Dom.IXmlNode; - innerText: string; - hasChildNodes(): boolean; - insertBefore(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - replaceChild(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - removeChild(childNode: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - appendChild(newChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - cloneNode(deep: boolean): Windows.Data.Xml.Dom.IXmlNode; - normalize(): void; - selectSingleNode(xpath: string): Windows.Data.Xml.Dom.IXmlNode; - selectNodes(xpath: string): Windows.Data.Xml.Dom.XmlNodeList; - selectSingleNodeNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.IXmlNode; - selectNodesNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.XmlNodeList; - getXml(): string; - } - export interface IDtdNotation extends Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - publicId: any; - systemId: any; - } - export interface IDtdEntity extends Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - notationName: any; - publicId: any; - systemId: any; - } - export interface IXmlEntityReference extends Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - } - export interface IXmlProcessingInstruction extends Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - data: string; - target: string; - } - export interface IXmlCharacterData extends Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - data: string; - length: number; - substringData(offset: number, count: number): string; - appendData(data: string): void; - insertData(offset: number, data: string): void; - deleteData(offset: number, count: number): void; - replaceData(offset: number, count: number, data: string): void; - } - export interface IXmlComment extends Windows.Data.Xml.Dom.IXmlCharacterData, Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - } - export interface IXmlText extends Windows.Data.Xml.Dom.IXmlCharacterData, Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - splitText(offset: number): Windows.Data.Xml.Dom.IXmlText; - } - export interface IXmlCDataSection extends Windows.Data.Xml.Dom.IXmlText, Windows.Data.Xml.Dom.IXmlCharacterData, Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - } - export interface IXmlDocument extends Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - doctype: Windows.Data.Xml.Dom.XmlDocumentType; - documentElement: Windows.Data.Xml.Dom.XmlElement; - documentUri: string; - implementation: Windows.Data.Xml.Dom.XmlDomImplementation; - createElement(tagName: string): Windows.Data.Xml.Dom.XmlElement; - createDocumentFragment(): Windows.Data.Xml.Dom.XmlDocumentFragment; - createTextNode(data: string): Windows.Data.Xml.Dom.XmlText; - createComment(data: string): Windows.Data.Xml.Dom.XmlComment; - createProcessingInstruction(target: string, data: string): Windows.Data.Xml.Dom.XmlProcessingInstruction; - createAttribute(name: string): Windows.Data.Xml.Dom.XmlAttribute; - createEntityReference(name: string): Windows.Data.Xml.Dom.XmlEntityReference; - getElementsByTagName(tagName: string): Windows.Data.Xml.Dom.XmlNodeList; - createCDataSection(data: string): Windows.Data.Xml.Dom.XmlCDataSection; - createAttributeNS(namespaceUri: any, qualifiedName: string): Windows.Data.Xml.Dom.XmlAttribute; - createElementNS(namespaceUri: any, qualifiedName: string): Windows.Data.Xml.Dom.XmlElement; - getElementById(elementId: string): Windows.Data.Xml.Dom.XmlElement; - importNode(node: Windows.Data.Xml.Dom.IXmlNode, deep: boolean): Windows.Data.Xml.Dom.IXmlNode; - } - export class XmlDocumentType implements Windows.Data.Xml.Dom.IXmlDocumentType, Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - entities: Windows.Data.Xml.Dom.XmlNamedNodeMap; - name: string; - notations: Windows.Data.Xml.Dom.XmlNamedNodeMap; - attributes: Windows.Data.Xml.Dom.XmlNamedNodeMap; - childNodes: Windows.Data.Xml.Dom.XmlNodeList; - firstChild: Windows.Data.Xml.Dom.IXmlNode; - lastChild: Windows.Data.Xml.Dom.IXmlNode; - localName: any; - namespaceUri: any; - nextSibling: Windows.Data.Xml.Dom.IXmlNode; - nodeName: string; - nodeType: Windows.Data.Xml.Dom.NodeType; - nodeValue: any; - ownerDocument: Windows.Data.Xml.Dom.XmlDocument; - parentNode: Windows.Data.Xml.Dom.IXmlNode; - prefix: any; - previousSibling: Windows.Data.Xml.Dom.IXmlNode; - innerText: string; - hasChildNodes(): boolean; - insertBefore(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - replaceChild(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - removeChild(childNode: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - appendChild(newChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - cloneNode(deep: boolean): Windows.Data.Xml.Dom.IXmlNode; - normalize(): void; - selectSingleNode(xpath: string): Windows.Data.Xml.Dom.IXmlNode; - selectNodes(xpath: string): Windows.Data.Xml.Dom.XmlNodeList; - selectSingleNodeNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.IXmlNode; - selectNodesNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.XmlNodeList; - getXml(): string; - } - export class XmlDomImplementation implements Windows.Data.Xml.Dom.IXmlDomImplementation { - hasFeature(feature: string, version: any): boolean; - } - export class XmlElement implements Windows.Data.Xml.Dom.IXmlElement, Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - tagName: string; - attributes: Windows.Data.Xml.Dom.XmlNamedNodeMap; - childNodes: Windows.Data.Xml.Dom.XmlNodeList; - firstChild: Windows.Data.Xml.Dom.IXmlNode; - lastChild: Windows.Data.Xml.Dom.IXmlNode; - localName: any; - namespaceUri: any; - nextSibling: Windows.Data.Xml.Dom.IXmlNode; - nodeName: string; - nodeType: Windows.Data.Xml.Dom.NodeType; - nodeValue: any; - ownerDocument: Windows.Data.Xml.Dom.XmlDocument; - parentNode: Windows.Data.Xml.Dom.IXmlNode; - prefix: any; - previousSibling: Windows.Data.Xml.Dom.IXmlNode; - innerText: string; - getAttribute(attributeName: string): string; - setAttribute(attributeName: string, attributeValue: string): void; - removeAttribute(attributeName: string): void; - getAttributeNode(attributeName: string): Windows.Data.Xml.Dom.XmlAttribute; - setAttributeNode(newAttribute: Windows.Data.Xml.Dom.XmlAttribute): Windows.Data.Xml.Dom.XmlAttribute; - removeAttributeNode(attributeNode: Windows.Data.Xml.Dom.XmlAttribute): Windows.Data.Xml.Dom.XmlAttribute; - getElementsByTagName(tagName: string): Windows.Data.Xml.Dom.XmlNodeList; - setAttributeNS(namespaceUri: any, qualifiedName: string, value: string): void; - getAttributeNS(namespaceUri: any, localName: string): string; - removeAttributeNS(namespaceUri: any, localName: string): void; - setAttributeNodeNS(newAttribute: Windows.Data.Xml.Dom.XmlAttribute): Windows.Data.Xml.Dom.XmlAttribute; - getAttributeNodeNS(namespaceUri: any, localName: string): Windows.Data.Xml.Dom.XmlAttribute; - hasChildNodes(): boolean; - insertBefore(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - replaceChild(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - removeChild(childNode: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - appendChild(newChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - cloneNode(deep: boolean): Windows.Data.Xml.Dom.IXmlNode; - normalize(): void; - selectSingleNode(xpath: string): Windows.Data.Xml.Dom.IXmlNode; - selectNodes(xpath: string): Windows.Data.Xml.Dom.XmlNodeList; - selectSingleNodeNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.IXmlNode; - selectNodesNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.XmlNodeList; - getXml(): string; - } - export class XmlDocumentFragment implements Windows.Data.Xml.Dom.IXmlDocumentFragment, Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - attributes: Windows.Data.Xml.Dom.XmlNamedNodeMap; - childNodes: Windows.Data.Xml.Dom.XmlNodeList; - firstChild: Windows.Data.Xml.Dom.IXmlNode; - lastChild: Windows.Data.Xml.Dom.IXmlNode; - localName: any; - namespaceUri: any; - nextSibling: Windows.Data.Xml.Dom.IXmlNode; - nodeName: string; - nodeType: Windows.Data.Xml.Dom.NodeType; - nodeValue: any; - ownerDocument: Windows.Data.Xml.Dom.XmlDocument; - parentNode: Windows.Data.Xml.Dom.IXmlNode; - prefix: any; - previousSibling: Windows.Data.Xml.Dom.IXmlNode; - innerText: string; - hasChildNodes(): boolean; - insertBefore(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - replaceChild(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - removeChild(childNode: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - appendChild(newChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - cloneNode(deep: boolean): Windows.Data.Xml.Dom.IXmlNode; - normalize(): void; - selectSingleNode(xpath: string): Windows.Data.Xml.Dom.IXmlNode; - selectNodes(xpath: string): Windows.Data.Xml.Dom.XmlNodeList; - selectSingleNodeNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.IXmlNode; - selectNodesNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.XmlNodeList; - getXml(): string; - } - export class XmlText implements Windows.Data.Xml.Dom.IXmlText, Windows.Data.Xml.Dom.IXmlCharacterData, Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - data: string; - length: number; - attributes: Windows.Data.Xml.Dom.XmlNamedNodeMap; - childNodes: Windows.Data.Xml.Dom.XmlNodeList; - firstChild: Windows.Data.Xml.Dom.IXmlNode; - lastChild: Windows.Data.Xml.Dom.IXmlNode; - localName: any; - namespaceUri: any; - nextSibling: Windows.Data.Xml.Dom.IXmlNode; - nodeName: string; - nodeType: Windows.Data.Xml.Dom.NodeType; - nodeValue: any; - ownerDocument: Windows.Data.Xml.Dom.XmlDocument; - parentNode: Windows.Data.Xml.Dom.IXmlNode; - prefix: any; - previousSibling: Windows.Data.Xml.Dom.IXmlNode; - innerText: string; - splitText(offset: number): Windows.Data.Xml.Dom.IXmlText; - substringData(offset: number, count: number): string; - appendData(data: string): void; - insertData(offset: number, data: string): void; - deleteData(offset: number, count: number): void; - replaceData(offset: number, count: number, data: string): void; - hasChildNodes(): boolean; - insertBefore(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - replaceChild(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - removeChild(childNode: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - appendChild(newChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - cloneNode(deep: boolean): Windows.Data.Xml.Dom.IXmlNode; - normalize(): void; - selectSingleNode(xpath: string): Windows.Data.Xml.Dom.IXmlNode; - selectNodes(xpath: string): Windows.Data.Xml.Dom.XmlNodeList; - selectSingleNodeNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.IXmlNode; - selectNodesNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.XmlNodeList; - getXml(): string; - } - export class XmlComment implements Windows.Data.Xml.Dom.IXmlComment, Windows.Data.Xml.Dom.IXmlCharacterData, Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - data: string; - length: number; - attributes: Windows.Data.Xml.Dom.XmlNamedNodeMap; - childNodes: Windows.Data.Xml.Dom.XmlNodeList; - firstChild: Windows.Data.Xml.Dom.IXmlNode; - lastChild: Windows.Data.Xml.Dom.IXmlNode; - localName: any; - namespaceUri: any; - nextSibling: Windows.Data.Xml.Dom.IXmlNode; - nodeName: string; - nodeType: Windows.Data.Xml.Dom.NodeType; - nodeValue: any; - ownerDocument: Windows.Data.Xml.Dom.XmlDocument; - parentNode: Windows.Data.Xml.Dom.IXmlNode; - prefix: any; - previousSibling: Windows.Data.Xml.Dom.IXmlNode; - innerText: string; - substringData(offset: number, count: number): string; - appendData(data: string): void; - insertData(offset: number, data: string): void; - deleteData(offset: number, count: number): void; - replaceData(offset: number, count: number, data: string): void; - hasChildNodes(): boolean; - insertBefore(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - replaceChild(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - removeChild(childNode: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - appendChild(newChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - cloneNode(deep: boolean): Windows.Data.Xml.Dom.IXmlNode; - normalize(): void; - selectSingleNode(xpath: string): Windows.Data.Xml.Dom.IXmlNode; - selectNodes(xpath: string): Windows.Data.Xml.Dom.XmlNodeList; - selectSingleNodeNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.IXmlNode; - selectNodesNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.XmlNodeList; - getXml(): string; - } - export class XmlProcessingInstruction implements Windows.Data.Xml.Dom.IXmlProcessingInstruction, Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - data: string; - target: string; - attributes: Windows.Data.Xml.Dom.XmlNamedNodeMap; - childNodes: Windows.Data.Xml.Dom.XmlNodeList; - firstChild: Windows.Data.Xml.Dom.IXmlNode; - lastChild: Windows.Data.Xml.Dom.IXmlNode; - localName: any; - namespaceUri: any; - nextSibling: Windows.Data.Xml.Dom.IXmlNode; - nodeName: string; - nodeType: Windows.Data.Xml.Dom.NodeType; - nodeValue: any; - ownerDocument: Windows.Data.Xml.Dom.XmlDocument; - parentNode: Windows.Data.Xml.Dom.IXmlNode; - prefix: any; - previousSibling: Windows.Data.Xml.Dom.IXmlNode; - innerText: string; - hasChildNodes(): boolean; - insertBefore(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - replaceChild(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - removeChild(childNode: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - appendChild(newChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - cloneNode(deep: boolean): Windows.Data.Xml.Dom.IXmlNode; - normalize(): void; - selectSingleNode(xpath: string): Windows.Data.Xml.Dom.IXmlNode; - selectNodes(xpath: string): Windows.Data.Xml.Dom.XmlNodeList; - selectSingleNodeNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.IXmlNode; - selectNodesNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.XmlNodeList; - getXml(): string; - } - export class XmlEntityReference implements Windows.Data.Xml.Dom.IXmlEntityReference, Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - attributes: Windows.Data.Xml.Dom.XmlNamedNodeMap; - childNodes: Windows.Data.Xml.Dom.XmlNodeList; - firstChild: Windows.Data.Xml.Dom.IXmlNode; - lastChild: Windows.Data.Xml.Dom.IXmlNode; - localName: any; - namespaceUri: any; - nextSibling: Windows.Data.Xml.Dom.IXmlNode; - nodeName: string; - nodeType: Windows.Data.Xml.Dom.NodeType; - nodeValue: any; - ownerDocument: Windows.Data.Xml.Dom.XmlDocument; - parentNode: Windows.Data.Xml.Dom.IXmlNode; - prefix: any; - previousSibling: Windows.Data.Xml.Dom.IXmlNode; - innerText: string; - hasChildNodes(): boolean; - insertBefore(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - replaceChild(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - removeChild(childNode: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - appendChild(newChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - cloneNode(deep: boolean): Windows.Data.Xml.Dom.IXmlNode; - normalize(): void; - selectSingleNode(xpath: string): Windows.Data.Xml.Dom.IXmlNode; - selectNodes(xpath: string): Windows.Data.Xml.Dom.XmlNodeList; - selectSingleNodeNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.IXmlNode; - selectNodesNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.XmlNodeList; - getXml(): string; - } - export class XmlCDataSection implements Windows.Data.Xml.Dom.IXmlCDataSection, Windows.Data.Xml.Dom.IXmlText, Windows.Data.Xml.Dom.IXmlCharacterData, Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - data: string; - length: number; - attributes: Windows.Data.Xml.Dom.XmlNamedNodeMap; - childNodes: Windows.Data.Xml.Dom.XmlNodeList; - firstChild: Windows.Data.Xml.Dom.IXmlNode; - lastChild: Windows.Data.Xml.Dom.IXmlNode; - localName: any; - namespaceUri: any; - nextSibling: Windows.Data.Xml.Dom.IXmlNode; - nodeName: string; - nodeType: Windows.Data.Xml.Dom.NodeType; - nodeValue: any; - ownerDocument: Windows.Data.Xml.Dom.XmlDocument; - parentNode: Windows.Data.Xml.Dom.IXmlNode; - prefix: any; - previousSibling: Windows.Data.Xml.Dom.IXmlNode; - innerText: string; - splitText(offset: number): Windows.Data.Xml.Dom.IXmlText; - substringData(offset: number, count: number): string; - appendData(data: string): void; - insertData(offset: number, data: string): void; - deleteData(offset: number, count: number): void; - replaceData(offset: number, count: number, data: string): void; - hasChildNodes(): boolean; - insertBefore(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - replaceChild(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - removeChild(childNode: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - appendChild(newChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - cloneNode(deep: boolean): Windows.Data.Xml.Dom.IXmlNode; - normalize(): void; - selectSingleNode(xpath: string): Windows.Data.Xml.Dom.IXmlNode; - selectNodes(xpath: string): Windows.Data.Xml.Dom.XmlNodeList; - selectSingleNodeNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.IXmlNode; - selectNodesNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.XmlNodeList; - getXml(): string; - } - export interface IXmlNamedNodeMap extends Windows.Foundation.Collections.IVectorView, Windows.Foundation.Collections.IIterable { - length: number; - item(index: number): Windows.Data.Xml.Dom.IXmlNode; - getNamedItem(name: string): Windows.Data.Xml.Dom.IXmlNode; - setNamedItem(node: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - removeNamedItem(name: string): Windows.Data.Xml.Dom.IXmlNode; - getNamedItemNS(namespaceUri: any, name: string): Windows.Data.Xml.Dom.IXmlNode; - removeNamedItemNS(namespaceUri: any, name: string): Windows.Data.Xml.Dom.IXmlNode; - setNamedItemNS(node: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - } - export interface IXmlNodeList extends Windows.Foundation.Collections.IVectorView, Windows.Foundation.Collections.IIterable { - length: number; - item(index: number): Windows.Data.Xml.Dom.IXmlNode; - } - export interface IXmlLoadSettings { - elementContentWhiteSpace: boolean; - maxElementDepth: number; - prohibitDtd: boolean; - resolveExternals: boolean; - validateOnParse: boolean; - } - export interface IXmlDocumentIO { - loadXml(xml: string): void; - loadXml(xml: string, loadSettings: Windows.Data.Xml.Dom.XmlLoadSettings): void; - saveToFileAsync(file: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncAction; - } - export class XmlLoadSettings implements Windows.Data.Xml.Dom.IXmlLoadSettings { - elementContentWhiteSpace: boolean; - maxElementDepth: number; - prohibitDtd: boolean; - resolveExternals: boolean; - validateOnParse: boolean; - } - export interface IXmlDocumentStatics { - loadFromUriAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperation; - loadFromUriAsync(uri: Windows.Foundation.Uri, loadSettings: Windows.Data.Xml.Dom.XmlLoadSettings): Windows.Foundation.IAsyncOperation; - loadFromFileAsync(file: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncOperation; - loadFromFileAsync(file: Windows.Storage.IStorageFile, loadSettings: Windows.Data.Xml.Dom.XmlLoadSettings): Windows.Foundation.IAsyncOperation; - } - export class DtdNotation implements Windows.Data.Xml.Dom.IDtdNotation, Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - publicId: any; - systemId: any; - attributes: Windows.Data.Xml.Dom.XmlNamedNodeMap; - childNodes: Windows.Data.Xml.Dom.XmlNodeList; - firstChild: Windows.Data.Xml.Dom.IXmlNode; - lastChild: Windows.Data.Xml.Dom.IXmlNode; - localName: any; - namespaceUri: any; - nextSibling: Windows.Data.Xml.Dom.IXmlNode; - nodeName: string; - nodeType: Windows.Data.Xml.Dom.NodeType; - nodeValue: any; - ownerDocument: Windows.Data.Xml.Dom.XmlDocument; - parentNode: Windows.Data.Xml.Dom.IXmlNode; - prefix: any; - previousSibling: Windows.Data.Xml.Dom.IXmlNode; - innerText: string; - hasChildNodes(): boolean; - insertBefore(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - replaceChild(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - removeChild(childNode: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - appendChild(newChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - cloneNode(deep: boolean): Windows.Data.Xml.Dom.IXmlNode; - normalize(): void; - selectSingleNode(xpath: string): Windows.Data.Xml.Dom.IXmlNode; - selectNodes(xpath: string): Windows.Data.Xml.Dom.XmlNodeList; - selectSingleNodeNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.IXmlNode; - selectNodesNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.XmlNodeList; - getXml(): string; - } - export class DtdEntity implements Windows.Data.Xml.Dom.IDtdEntity, Windows.Data.Xml.Dom.IXmlNode, Windows.Data.Xml.Dom.IXmlNodeSelector, Windows.Data.Xml.Dom.IXmlNodeSerializer { - notationName: any; - publicId: any; - systemId: any; - attributes: Windows.Data.Xml.Dom.XmlNamedNodeMap; - childNodes: Windows.Data.Xml.Dom.XmlNodeList; - firstChild: Windows.Data.Xml.Dom.IXmlNode; - lastChild: Windows.Data.Xml.Dom.IXmlNode; - localName: any; - namespaceUri: any; - nextSibling: Windows.Data.Xml.Dom.IXmlNode; - nodeName: string; - nodeType: Windows.Data.Xml.Dom.NodeType; - nodeValue: any; - ownerDocument: Windows.Data.Xml.Dom.XmlDocument; - parentNode: Windows.Data.Xml.Dom.IXmlNode; - prefix: any; - previousSibling: Windows.Data.Xml.Dom.IXmlNode; - innerText: string; - hasChildNodes(): boolean; - insertBefore(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - replaceChild(newChild: Windows.Data.Xml.Dom.IXmlNode, referenceChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - removeChild(childNode: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - appendChild(newChild: Windows.Data.Xml.Dom.IXmlNode): Windows.Data.Xml.Dom.IXmlNode; - cloneNode(deep: boolean): Windows.Data.Xml.Dom.IXmlNode; - normalize(): void; - selectSingleNode(xpath: string): Windows.Data.Xml.Dom.IXmlNode; - selectNodes(xpath: string): Windows.Data.Xml.Dom.XmlNodeList; - selectSingleNodeNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.IXmlNode; - selectNodesNS(xpath: string, namespaces: any): Windows.Data.Xml.Dom.XmlNodeList; - getXml(): string; - } - } - } - } -} -declare module Windows { - export module Data { - export module Xml { - export module Xsl { - export interface IXsltProcessor { - transformToString(inputNode: Windows.Data.Xml.Dom.IXmlNode): string; - } - export interface IXsltProcessorFactory { - createInstance(document: Windows.Data.Xml.Dom.XmlDocument): Windows.Data.Xml.Xsl.XsltProcessor; - } - export class XsltProcessor implements Windows.Data.Xml.Xsl.IXsltProcessor { - constructor(document: Windows.Data.Xml.Dom.XmlDocument); - transformToString(inputNode: Windows.Data.Xml.Dom.IXmlNode): string; - } - } - } - } -} -declare module Windows { - export module Devices { - export module Sms { - export enum SmsMessageClass { - none, - class0, - class1, - class2, - class3, - } - export interface ISmsMessage { - id: number; - messageClass: Windows.Devices.Sms.SmsMessageClass; - } - export enum SmsDataFormat { - unknown, - cdmaSubmit, - gsmSubmit, - cdmaDeliver, - gsmDeliver, - } - export interface ISmsBinaryMessage extends Windows.Devices.Sms.ISmsMessage { - format: Windows.Devices.Sms.SmsDataFormat; - getData(): Uint8Array; - setData(value: Uint8Array): void; - } - export class SmsBinaryMessage implements Windows.Devices.Sms.ISmsBinaryMessage, Windows.Devices.Sms.ISmsMessage { - format: Windows.Devices.Sms.SmsDataFormat; - id: number; - messageClass: Windows.Devices.Sms.SmsMessageClass; - getData(): Uint8Array; - setData(value: Uint8Array): void; - } - export enum SmsEncoding { - unknown, - optimal, - sevenBitAscii, - unicode, - gsmSevenBit, - } - export interface ISmsTextMessage extends Windows.Devices.Sms.ISmsMessage { - body: string; - encoding: Windows.Devices.Sms.SmsEncoding; - from: string; - partCount: number; - partNumber: number; - partReferenceId: number; - timestamp: Date; - to: string; - toBinaryMessages(format: Windows.Devices.Sms.SmsDataFormat): Windows.Foundation.Collections.IVectorView; - } - export interface ISmsTextMessageStatics { - fromBinaryMessage(binaryMessage: Windows.Devices.Sms.SmsBinaryMessage): Windows.Devices.Sms.SmsTextMessage; - fromBinaryData(format: Windows.Devices.Sms.SmsDataFormat, value: Uint8Array): Windows.Devices.Sms.SmsTextMessage; - } - export class SmsTextMessage implements Windows.Devices.Sms.ISmsTextMessage, Windows.Devices.Sms.ISmsMessage { - body: string; - encoding: Windows.Devices.Sms.SmsEncoding; - from: string; - partCount: number; - partNumber: number; - partReferenceId: number; - timestamp: Date; - to: string; - id: number; - messageClass: Windows.Devices.Sms.SmsMessageClass; - toBinaryMessages(format: Windows.Devices.Sms.SmsDataFormat): Windows.Foundation.Collections.IVectorView; - static fromBinaryMessage(binaryMessage: Windows.Devices.Sms.SmsBinaryMessage): Windows.Devices.Sms.SmsTextMessage; - static fromBinaryData(format: Windows.Devices.Sms.SmsDataFormat, value: Uint8Array): Windows.Devices.Sms.SmsTextMessage; - } - export enum SmsMessageFilter { - all, - unread, - read, - sent, - draft, - } - export enum SmsMessageType { - binary, - text, - } - export class DeleteSmsMessageOperation implements Windows.Foundation.IAsyncAction, Windows.Foundation.IAsyncInfo { - completed: Windows.Foundation.AsyncActionCompletedHandler; - errorCode: number; - id: number; - status: Windows.Foundation.AsyncStatus; - getResults(): void; - cancel(): void; - close(): void; - then(success?: (value: any) => U, error?: (error: any) => U, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: any) => Windows.Foundation.IPromise, error?: (error: any) => U, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: any) => U, error?: (error: any) => Windows.Foundation.IPromise, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: any) => Windows.Foundation.IPromise, error?: (error: any) => Windows.Foundation.IPromise, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - done(success?: (value: any) => any, error?: (error: any) => any, progress?: (progress: any) => void ): void; - operation: { - completed: Windows.Foundation.AsyncOperationCompletedHandler; - getResults(): any; - } - } - export class DeleteSmsMessagesOperation implements Windows.Foundation.IAsyncAction, Windows.Foundation.IAsyncInfo { - completed: Windows.Foundation.AsyncActionCompletedHandler; - errorCode: number; - id: number; - status: Windows.Foundation.AsyncStatus; - getResults(): void; - cancel(): void; - close(): void; - then(success?: (value: any) => U, error?: (error: any) => U, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: any) => Windows.Foundation.IPromise, error?: (error: any) => U, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: any) => U, error?: (error: any) => Windows.Foundation.IPromise, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: any) => Windows.Foundation.IPromise, error?: (error: any) => Windows.Foundation.IPromise, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - done(success?: (value: any) => any, error?: (error: any) => any, progress?: (progress: any) => void ): void; - operation: { - completed: Windows.Foundation.AsyncOperationCompletedHandler; - getResults(): any; - } - } - export class GetSmsMessageOperation implements Windows.Foundation.IAsyncOperation, Windows.Foundation.IAsyncInfo { - completed: Windows.Foundation.AsyncOperationCompletedHandler; - errorCode: number; - id: number; - status: Windows.Foundation.AsyncStatus; - getResults(): Windows.Devices.Sms.ISmsMessage; - cancel(): void; - close(): void; - then(success?: (value: Windows.Devices.Sms.ISmsMessage) => U, error?: (error: any) => U, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: Windows.Devices.Sms.ISmsMessage) => Windows.Foundation.IPromise, error?: (error: any) => U, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: Windows.Devices.Sms.ISmsMessage) => U, error?: (error: any) => Windows.Foundation.IPromise, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: Windows.Devices.Sms.ISmsMessage) => Windows.Foundation.IPromise, error?: (error: any) => Windows.Foundation.IPromise, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - done(success?: (value: Windows.Devices.Sms.ISmsMessage) => any, error?: (error: any) => any, progress?: (progress: any) => void ): void; - operation: { - completed: Windows.Foundation.AsyncOperationCompletedHandler; - getResults(): Windows.Devices.Sms.ISmsMessage; - } - } - export class GetSmsMessagesOperation implements Windows.Foundation.IAsyncOperationWithProgress, number>, Windows.Foundation.IAsyncInfo { - completed: Windows.Foundation.AsyncOperationWithProgressCompletedHandler, number>; - progress: Windows.Foundation.AsyncOperationProgressHandler, number>; - errorCode: number; - id: number; - status: Windows.Foundation.AsyncStatus; - getResults(): Windows.Foundation.Collections.IVectorView; - cancel(): void; - close(): void; - then(success?: (value: Windows.Foundation.Collections.IVectorView) => U, error?: (error: any) => U, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: Windows.Foundation.Collections.IVectorView) => Windows.Foundation.IPromise, error?: (error: any) => U, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: Windows.Foundation.Collections.IVectorView) => U, error?: (error: any) => Windows.Foundation.IPromise, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: Windows.Foundation.Collections.IVectorView) => Windows.Foundation.IPromise, error?: (error: any) => Windows.Foundation.IPromise, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - done(success?: (value: Windows.Foundation.Collections.IVectorView) => any, error?: (error: any) => any, progress?: (progress: any) => void ): void; - operation: { - progress: Windows.Foundation.AsyncOperationProgressHandler, number>; - completed: Windows.Foundation.AsyncOperationWithProgressCompletedHandler, number>; - getResults(): Windows.Foundation.Collections.IVectorView; - } - } - export interface ISmsDeviceMessageStore { - maxMessages: number; - deleteMessageAsync(messageId: number): Windows.Foundation.IAsyncAction; - deleteMessagesAsync(messageFilter: Windows.Devices.Sms.SmsMessageFilter): Windows.Foundation.IAsyncAction; - getMessageAsync(messageId: number): Windows.Foundation.IAsyncOperation; - getMessagesAsync(messageFilter: Windows.Devices.Sms.SmsMessageFilter): Windows.Foundation.IAsyncOperationWithProgress, number>; - } - export class SmsDeviceMessageStore implements Windows.Devices.Sms.ISmsDeviceMessageStore { - maxMessages: number; - deleteMessageAsync(messageId: number): Windows.Foundation.IAsyncAction; - deleteMessagesAsync(messageFilter: Windows.Devices.Sms.SmsMessageFilter): Windows.Foundation.IAsyncAction; - getMessageAsync(messageId: number): Windows.Foundation.IAsyncOperation; - getMessagesAsync(messageFilter: Windows.Devices.Sms.SmsMessageFilter): Windows.Foundation.IAsyncOperationWithProgress, number>; - } - export interface SmsEncodedLength { - segmentCount: number; - characterCountLastSegment: number; - charactersPerSegment: number; - byteCountLastSegment: number; - bytesPerSegment: number; - } - export enum CellularClass { - none, - gsm, - cdma, - } - export enum SmsDeviceStatus { - off, - ready, - simNotInserted, - badSim, - deviceFailure, - subscriptionNotActivated, - deviceLocked, - deviceBlocked, - } - export class SendSmsMessageOperation implements Windows.Foundation.IAsyncAction, Windows.Foundation.IAsyncInfo { - completed: Windows.Foundation.AsyncActionCompletedHandler; - errorCode: number; - id: number; - status: Windows.Foundation.AsyncStatus; - getResults(): void; - cancel(): void; - close(): void; - then(success: (value: any) => U, error?: (error: any) => U, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success: (value: any) => Windows.Foundation.IPromise, error?: (error: any) => U, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success: (value: any) => U, error?: (error: any) => Windows.Foundation.IPromise, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success: (value: any) => Windows.Foundation.IPromise, error?: (error: any) => Windows.Foundation.IPromise, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - done(success: (value: any) => any, error?: (error: any) => any, progress?: (progress: any) => void ): void; - operation: { - completed: Windows.Foundation.AsyncOperationCompletedHandler; - getResults(): any; - } - } - export interface ISmsMessageReceivedEventArgs { - binaryMessage: Windows.Devices.Sms.SmsBinaryMessage; - textMessage: Windows.Devices.Sms.SmsTextMessage; - } - export class SmsMessageReceivedEventArgs implements Windows.Devices.Sms.ISmsMessageReceivedEventArgs { - binaryMessage: Windows.Devices.Sms.SmsBinaryMessage; - textMessage: Windows.Devices.Sms.SmsTextMessage; - } - export interface SmsMessageReceivedEventHandler { - (sender: Windows.Devices.Sms.SmsDevice, e: Windows.Devices.Sms.SmsMessageReceivedEventArgs): void; - } - export class SmsDevice implements Windows.Devices.Sms.ISmsDevice { - accountPhoneNumber: string; - cellularClass: Windows.Devices.Sms.CellularClass; - deviceStatus: Windows.Devices.Sms.SmsDeviceStatus; - messageStore: Windows.Devices.Sms.SmsDeviceMessageStore; - sendMessageAsync(message: Windows.Devices.Sms.ISmsMessage): Windows.Devices.Sms.SendSmsMessageOperation; - calculateLength(message: Windows.Devices.Sms.SmsTextMessage): Windows.Devices.Sms.SmsEncodedLength; - onsmsmessagereceived: any/* TODO */; - onsmsdevicestatuschanged: any/* TODO */; - static getDeviceSelector(): string; - static fromIdAsync(deviceInstanceId: string): Windows.Foundation.IAsyncOperation; - static getDefaultAsync(): Windows.Foundation.IAsyncOperation; - } - export interface SmsDeviceStatusChangedEventHandler { - (sender: Windows.Devices.Sms.SmsDevice): void; - } - export class GetSmsDeviceOperation implements Windows.Foundation.IAsyncOperation, Windows.Foundation.IAsyncInfo { - completed: Windows.Foundation.AsyncOperationCompletedHandler; - errorCode: number; - id: number; - status: Windows.Foundation.AsyncStatus; - getResults(): Windows.Devices.Sms.SmsDevice; - cancel(): void; - close(): void; - then(success?: (value: Windows.Devices.Sms.SmsDevice) => U, error?: (error: any) => U, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: Windows.Devices.Sms.SmsDevice) => Windows.Foundation.IPromise, error?: (error: any) => U, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: Windows.Devices.Sms.SmsDevice) => U, error?: (error: any) => Windows.Foundation.IPromise, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: Windows.Devices.Sms.SmsDevice) => Windows.Foundation.IPromise, error?: (error: any) => Windows.Foundation.IPromise, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - done(success?: (value: Windows.Devices.Sms.SmsDevice) => any, error?: (error: any) => any, progress?: (progress: any) => void ): void; - operation: { - completed: Windows.Foundation.AsyncOperationCompletedHandler; - getResults(): Windows.Devices.Sms.SmsDevice; - } - } - export interface ISmsDeviceStatics { - getDeviceSelector(): string; - fromIdAsync(deviceInstanceId: string): Windows.Foundation.IAsyncOperation; - getDefaultAsync(): Windows.Foundation.IAsyncOperation; - } - export interface ISmsDevice { - accountPhoneNumber: string; - cellularClass: Windows.Devices.Sms.CellularClass; - deviceStatus: Windows.Devices.Sms.SmsDeviceStatus; - messageStore: Windows.Devices.Sms.SmsDeviceMessageStore; - sendMessageAsync(message: Windows.Devices.Sms.ISmsMessage): Windows.Devices.Sms.SendSmsMessageOperation; - calculateLength(message: Windows.Devices.Sms.SmsTextMessage): Windows.Devices.Sms.SmsEncodedLength; - onsmsmessagereceived: any/* TODO */; - onsmsdevicestatuschanged: any/* TODO */; - } - export interface ISmsReceivedEventDetails { - deviceId: string; - messageIndex: number; - } - export class SmsReceivedEventDetails implements Windows.Devices.Sms.ISmsReceivedEventDetails { - deviceId: string; - messageIndex: number; - } - } - } -} -declare module Windows { - export module Devices { - export module Enumeration { - export enum DeviceClass { - all, - audioCapture, - audioRender, - portableStorageDevice, - videoCapture, - } - export enum DeviceWatcherStatus { - created, - started, - enumerationCompleted, - stopping, - stopped, - aborted, - } - export class DeviceThumbnail implements Windows.Storage.Streams.IRandomAccessStreamWithContentType, Windows.Storage.Streams.IRandomAccessStream, Windows.Foundation.IClosable, Windows.Storage.Streams.IInputStream, Windows.Storage.Streams.IOutputStream, Windows.Storage.Streams.IContentTypeProvider { - canRead: boolean; - canWrite: boolean; - position: number; - size: number; - contentType: string; - getInputStreamAt(position: number): Windows.Storage.Streams.IInputStream; - getOutputStreamAt(position: number): Windows.Storage.Streams.IOutputStream; - seek(position: number): void; - cloneStream(): Windows.Storage.Streams.IRandomAccessStream; - dispose(): void; - readAsync(buffer: Windows.Storage.Streams.IBuffer, count: number, options: Windows.Storage.Streams.InputStreamOptions): Windows.Foundation.IAsyncOperationWithProgress; - writeAsync(buffer: Windows.Storage.Streams.IBuffer): Windows.Foundation.IAsyncOperationWithProgress; - flushAsync(): Windows.Foundation.IAsyncOperation; - close(): void; - } - export enum Panel { - unknown, - front, - back, - top, - bottom, - left, - right, - } - export interface IEnclosureLocation { - inDock: boolean; - inLid: boolean; - panel: Windows.Devices.Enumeration.Panel; - } - export class EnclosureLocation implements Windows.Devices.Enumeration.IEnclosureLocation { - inDock: boolean; - inLid: boolean; - panel: Windows.Devices.Enumeration.Panel; - } - export interface IDeviceInformationUpdate { - id: string; - properties: Windows.Foundation.Collections.IMapView; - } - export class DeviceInformationUpdate implements Windows.Devices.Enumeration.IDeviceInformationUpdate { - id: string; - properties: Windows.Foundation.Collections.IMapView; - } - export class DeviceInformationCollection implements Windows.Foundation.Collections.IVectorView, Windows.Foundation.Collections.IIterable { - size: number; - getAt(index: number): Windows.Devices.Enumeration.DeviceInformation; - indexOf(value: Windows.Devices.Enumeration.DeviceInformation): { index: number; returnValue: boolean; }; - getMany(startIndex: number): { items: Windows.Devices.Enumeration.DeviceInformation[]; returnValue: number; }; - first(): Windows.Foundation.Collections.IIterator; - toString(): string; - toLocaleString(): string; - concat(...items: Windows.Devices.Enumeration.DeviceInformation[][]): Windows.Devices.Enumeration.DeviceInformation[]; - join(seperator: string): string; - pop(): Windows.Devices.Enumeration.DeviceInformation; - push(...items: Windows.Devices.Enumeration.DeviceInformation[]): void; - reverse(): Windows.Devices.Enumeration.DeviceInformation[]; - shift(): Windows.Devices.Enumeration.DeviceInformation; - slice(start: number): Windows.Devices.Enumeration.DeviceInformation[]; - slice(start: number, end: number): Windows.Devices.Enumeration.DeviceInformation[]; - sort(): Windows.Devices.Enumeration.DeviceInformation[]; - sort(compareFn: (a: Windows.Devices.Enumeration.DeviceInformation, b: Windows.Devices.Enumeration.DeviceInformation) => number): Windows.Devices.Enumeration.DeviceInformation[]; - splice(start: number): Windows.Devices.Enumeration.DeviceInformation[]; - splice(start: number, deleteCount: number, ...items: Windows.Devices.Enumeration.DeviceInformation[]): Windows.Devices.Enumeration.DeviceInformation[]; - unshift(...items: Windows.Devices.Enumeration.DeviceInformation[]): number; - lastIndexOf(searchElement: Windows.Devices.Enumeration.DeviceInformation): number; - lastIndexOf(searchElement: Windows.Devices.Enumeration.DeviceInformation, fromIndex: number): number; - every(callbackfn: (value: Windows.Devices.Enumeration.DeviceInformation, index: number, array: Windows.Devices.Enumeration.DeviceInformation[]) => boolean): boolean; - every(callbackfn: (value: Windows.Devices.Enumeration.DeviceInformation, index: number, array: Windows.Devices.Enumeration.DeviceInformation[]) => boolean, thisArg: any): boolean; - some(callbackfn: (value: Windows.Devices.Enumeration.DeviceInformation, index: number, array: Windows.Devices.Enumeration.DeviceInformation[]) => boolean): boolean; - some(callbackfn: (value: Windows.Devices.Enumeration.DeviceInformation, index: number, array: Windows.Devices.Enumeration.DeviceInformation[]) => boolean, thisArg: any): boolean; - forEach(callbackfn: (value: Windows.Devices.Enumeration.DeviceInformation, index: number, array: Windows.Devices.Enumeration.DeviceInformation[]) => void ): void; - forEach(callbackfn: (value: Windows.Devices.Enumeration.DeviceInformation, index: number, array: Windows.Devices.Enumeration.DeviceInformation[]) => void , thisArg: any): void; - map(callbackfn: (value: Windows.Devices.Enumeration.DeviceInformation, index: number, array: Windows.Devices.Enumeration.DeviceInformation[]) => any): any[]; - map(callbackfn: (value: Windows.Devices.Enumeration.DeviceInformation, index: number, array: Windows.Devices.Enumeration.DeviceInformation[]) => any, thisArg: any): any[]; - filter(callbackfn: (value: Windows.Devices.Enumeration.DeviceInformation, index: number, array: Windows.Devices.Enumeration.DeviceInformation[]) => boolean): Windows.Devices.Enumeration.DeviceInformation[]; - filter(callbackfn: (value: Windows.Devices.Enumeration.DeviceInformation, index: number, array: Windows.Devices.Enumeration.DeviceInformation[]) => boolean, thisArg: any): Windows.Devices.Enumeration.DeviceInformation[]; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Devices.Enumeration.DeviceInformation[]) => any): any; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Devices.Enumeration.DeviceInformation[]) => any, initialValue: any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Devices.Enumeration.DeviceInformation[]) => any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Devices.Enumeration.DeviceInformation[]) => any, initialValue: any): any; - length: number; - } - export interface IDeviceWatcher { - status: Windows.Devices.Enumeration.DeviceWatcherStatus; - onadded: any/* TODO */; - onupdated: any/* TODO */; - onremoved: any/* TODO */; - onenumerationcompleted: any/* TODO */; - onstopped: any/* TODO */; - start(): void; - stop(): void; - } - export class DeviceWatcher implements Windows.Devices.Enumeration.IDeviceWatcher { - status: Windows.Devices.Enumeration.DeviceWatcherStatus; - onadded: any/* TODO */; - onupdated: any/* TODO */; - onremoved: any/* TODO */; - onenumerationcompleted: any/* TODO */; - onstopped: any/* TODO */; - start(): void; - stop(): void; - } - export class DeviceInformation implements Windows.Devices.Enumeration.IDeviceInformation { - enclosureLocation: Windows.Devices.Enumeration.EnclosureLocation; - id: string; - isDefault: boolean; - isEnabled: boolean; - name: string; - properties: Windows.Foundation.Collections.IMapView; - update(updateInfo: Windows.Devices.Enumeration.DeviceInformationUpdate): void; - getThumbnailAsync(): Windows.Foundation.IAsyncOperation; - getGlyphThumbnailAsync(): Windows.Foundation.IAsyncOperation; - static createFromIdAsync(id: string): Windows.Foundation.IAsyncOperation; - static createFromIdAsync(id: string, additionalProperties: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncOperation; - static findAllAsync(): Windows.Foundation.IAsyncOperation; - static findAllAsync(deviceClass: Windows.Devices.Enumeration.DeviceClass): Windows.Foundation.IAsyncOperation; - static findAllAsync(aqsFilter: string): Windows.Foundation.IAsyncOperation; - static findAllAsync(aqsFilter: string, additionalProperties: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncOperation; - static createWatcher(): Windows.Devices.Enumeration.DeviceWatcher; - static createWatcher(deviceClass: Windows.Devices.Enumeration.DeviceClass): Windows.Devices.Enumeration.DeviceWatcher; - static createWatcher(aqsFilter: string): Windows.Devices.Enumeration.DeviceWatcher; - static createWatcher(aqsFilter: string, additionalProperties: Windows.Foundation.Collections.IIterable): Windows.Devices.Enumeration.DeviceWatcher; - } - export interface IDeviceInformationStatics { - createFromIdAsync(id: string): Windows.Foundation.IAsyncOperation; - createFromIdAsync(id: string, additionalProperties: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncOperation; - findAllAsync(): Windows.Foundation.IAsyncOperation; - findAllAsync(deviceClass: Windows.Devices.Enumeration.DeviceClass): Windows.Foundation.IAsyncOperation; - findAllAsync(aqsFilter: string): Windows.Foundation.IAsyncOperation; - findAllAsync(aqsFilter: string, additionalProperties: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncOperation; - createWatcher(): Windows.Devices.Enumeration.DeviceWatcher; - createWatcher(deviceClass: Windows.Devices.Enumeration.DeviceClass): Windows.Devices.Enumeration.DeviceWatcher; - createWatcher(aqsFilter: string): Windows.Devices.Enumeration.DeviceWatcher; - createWatcher(aqsFilter: string, additionalProperties: Windows.Foundation.Collections.IIterable): Windows.Devices.Enumeration.DeviceWatcher; - } - export interface IDeviceInformation { - enclosureLocation: Windows.Devices.Enumeration.EnclosureLocation; - id: string; - isDefault: boolean; - isEnabled: boolean; - name: string; - properties: Windows.Foundation.Collections.IMapView; - update(updateInfo: Windows.Devices.Enumeration.DeviceInformationUpdate): void; - getThumbnailAsync(): Windows.Foundation.IAsyncOperation; - getGlyphThumbnailAsync(): Windows.Foundation.IAsyncOperation; - } - } - } -} -declare module Windows { - export module Devices { - export module Enumeration { - export module Pnp { - export enum PnpObjectType { - unknown, - deviceInterface, - deviceContainer, - device, - deviceInterfaceClass, - } - export interface IPnpObjectUpdate { - id: string; - properties: Windows.Foundation.Collections.IMapView; - type: Windows.Devices.Enumeration.Pnp.PnpObjectType; - } - export class PnpObjectUpdate implements Windows.Devices.Enumeration.Pnp.IPnpObjectUpdate { - id: string; - properties: Windows.Foundation.Collections.IMapView; - type: Windows.Devices.Enumeration.Pnp.PnpObjectType; - } - export class PnpObjectCollection implements Windows.Foundation.Collections.IVectorView, Windows.Foundation.Collections.IIterable { - size: number; - getAt(index: number): Windows.Devices.Enumeration.Pnp.PnpObject; - indexOf(value: Windows.Devices.Enumeration.Pnp.PnpObject): { index: number; returnValue: boolean; }; - getMany(startIndex: number): { items: Windows.Devices.Enumeration.Pnp.PnpObject[]; returnValue: number; }; - first(): Windows.Foundation.Collections.IIterator; - toString(): string; - toLocaleString(): string; - concat(...items: Windows.Devices.Enumeration.Pnp.PnpObject[][]): Windows.Devices.Enumeration.Pnp.PnpObject[]; - join(seperator: string): string; - pop(): Windows.Devices.Enumeration.Pnp.PnpObject; - push(...items: Windows.Devices.Enumeration.Pnp.PnpObject[]): void; - reverse(): Windows.Devices.Enumeration.Pnp.PnpObject[]; - shift(): Windows.Devices.Enumeration.Pnp.PnpObject; - slice(start: number): Windows.Devices.Enumeration.Pnp.PnpObject[]; - slice(start: number, end: number): Windows.Devices.Enumeration.Pnp.PnpObject[]; - sort(): Windows.Devices.Enumeration.Pnp.PnpObject[]; - sort(compareFn: (a: Windows.Devices.Enumeration.Pnp.PnpObject, b: Windows.Devices.Enumeration.Pnp.PnpObject) => number): Windows.Devices.Enumeration.Pnp.PnpObject[]; - splice(start: number): Windows.Devices.Enumeration.Pnp.PnpObject[]; - splice(start: number, deleteCount: number, ...items: Windows.Devices.Enumeration.Pnp.PnpObject[]): Windows.Devices.Enumeration.Pnp.PnpObject[]; - unshift(...items: Windows.Devices.Enumeration.Pnp.PnpObject[]): number; - lastIndexOf(searchElement: Windows.Devices.Enumeration.Pnp.PnpObject): number; - lastIndexOf(searchElement: Windows.Devices.Enumeration.Pnp.PnpObject, fromIndex: number): number; - every(callbackfn: (value: Windows.Devices.Enumeration.Pnp.PnpObject, index: number, array: Windows.Devices.Enumeration.Pnp.PnpObject[]) => boolean): boolean; - every(callbackfn: (value: Windows.Devices.Enumeration.Pnp.PnpObject, index: number, array: Windows.Devices.Enumeration.Pnp.PnpObject[]) => boolean, thisArg: any): boolean; - some(callbackfn: (value: Windows.Devices.Enumeration.Pnp.PnpObject, index: number, array: Windows.Devices.Enumeration.Pnp.PnpObject[]) => boolean): boolean; - some(callbackfn: (value: Windows.Devices.Enumeration.Pnp.PnpObject, index: number, array: Windows.Devices.Enumeration.Pnp.PnpObject[]) => boolean, thisArg: any): boolean; - forEach(callbackfn: (value: Windows.Devices.Enumeration.Pnp.PnpObject, index: number, array: Windows.Devices.Enumeration.Pnp.PnpObject[]) => void ): void; - forEach(callbackfn: (value: Windows.Devices.Enumeration.Pnp.PnpObject, index: number, array: Windows.Devices.Enumeration.Pnp.PnpObject[]) => void , thisArg: any): void; - map(callbackfn: (value: Windows.Devices.Enumeration.Pnp.PnpObject, index: number, array: Windows.Devices.Enumeration.Pnp.PnpObject[]) => any): any[]; - map(callbackfn: (value: Windows.Devices.Enumeration.Pnp.PnpObject, index: number, array: Windows.Devices.Enumeration.Pnp.PnpObject[]) => any, thisArg: any): any[]; - filter(callbackfn: (value: Windows.Devices.Enumeration.Pnp.PnpObject, index: number, array: Windows.Devices.Enumeration.Pnp.PnpObject[]) => boolean): Windows.Devices.Enumeration.Pnp.PnpObject[]; - filter(callbackfn: (value: Windows.Devices.Enumeration.Pnp.PnpObject, index: number, array: Windows.Devices.Enumeration.Pnp.PnpObject[]) => boolean, thisArg: any): Windows.Devices.Enumeration.Pnp.PnpObject[]; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Devices.Enumeration.Pnp.PnpObject[]) => any): any; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Devices.Enumeration.Pnp.PnpObject[]) => any, initialValue: any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Devices.Enumeration.Pnp.PnpObject[]) => any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Devices.Enumeration.Pnp.PnpObject[]) => any, initialValue: any): any; - length: number; - } - export interface IPnpObjectWatcher { - status: Windows.Devices.Enumeration.DeviceWatcherStatus; - onadded: any/* TODO */; - onupdated: any/* TODO */; - onremoved: any/* TODO */; - onenumerationcompleted: any/* TODO */; - onstopped: any/* TODO */; - start(): void; - stop(): void; - } - export class PnpObjectWatcher implements Windows.Devices.Enumeration.Pnp.IPnpObjectWatcher { - status: Windows.Devices.Enumeration.DeviceWatcherStatus; - onadded: any/* TODO */; - onupdated: any/* TODO */; - onremoved: any/* TODO */; - onenumerationcompleted: any/* TODO */; - onstopped: any/* TODO */; - start(): void; - stop(): void; - } - export class PnpObject implements Windows.Devices.Enumeration.Pnp.IPnpObject { - id: string; - properties: Windows.Foundation.Collections.IMapView; - type: Windows.Devices.Enumeration.Pnp.PnpObjectType; - update(updateInfo: Windows.Devices.Enumeration.Pnp.PnpObjectUpdate): void; - static createFromIdAsync(type: Windows.Devices.Enumeration.Pnp.PnpObjectType, id: string, requestedProperties: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncOperation; - static findAllAsync(type: Windows.Devices.Enumeration.Pnp.PnpObjectType, requestedProperties: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncOperation; - static findAllAsync(type: Windows.Devices.Enumeration.Pnp.PnpObjectType, requestedProperties: Windows.Foundation.Collections.IIterable, aqsFilter: string): Windows.Foundation.IAsyncOperation; - static createWatcher(type: Windows.Devices.Enumeration.Pnp.PnpObjectType, requestedProperties: Windows.Foundation.Collections.IIterable): Windows.Devices.Enumeration.Pnp.PnpObjectWatcher; - static createWatcher(type: Windows.Devices.Enumeration.Pnp.PnpObjectType, requestedProperties: Windows.Foundation.Collections.IIterable, aqsFilter: string): Windows.Devices.Enumeration.Pnp.PnpObjectWatcher; - } - export interface IPnpObjectStatics { - createFromIdAsync(type: Windows.Devices.Enumeration.Pnp.PnpObjectType, id: string, requestedProperties: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncOperation; - findAllAsync(type: Windows.Devices.Enumeration.Pnp.PnpObjectType, requestedProperties: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncOperation; - findAllAsync(type: Windows.Devices.Enumeration.Pnp.PnpObjectType, requestedProperties: Windows.Foundation.Collections.IIterable, aqsFilter: string): Windows.Foundation.IAsyncOperation; - createWatcher(type: Windows.Devices.Enumeration.Pnp.PnpObjectType, requestedProperties: Windows.Foundation.Collections.IIterable): Windows.Devices.Enumeration.Pnp.PnpObjectWatcher; - createWatcher(type: Windows.Devices.Enumeration.Pnp.PnpObjectType, requestedProperties: Windows.Foundation.Collections.IIterable, aqsFilter: string): Windows.Devices.Enumeration.Pnp.PnpObjectWatcher; - } - export interface IPnpObject { - id: string; - properties: Windows.Foundation.Collections.IMapView; - type: Windows.Devices.Enumeration.Pnp.PnpObjectType; - update(updateInfo: Windows.Devices.Enumeration.Pnp.PnpObjectUpdate): void; - } - } - } - } -} -declare module Windows { - export module Devices { - export module Geolocation { - export enum PositionAccuracy { - default, - high, - } - export enum PositionStatus { - ready, - initializing, - noData, - disabled, - notInitialized, - notAvailable, - } - export interface IGeocoordinate { - accuracy: number; - altitude: number; - altitudeAccuracy: number; - heading: number; - latitude: number; - longitude: number; - speed: number; - timestamp: Date; - } - export class Geocoordinate implements Windows.Devices.Geolocation.IGeocoordinate { - accuracy: number; - altitude: number; - altitudeAccuracy: number; - heading: number; - latitude: number; - longitude: number; - speed: number; - timestamp: Date; - } - export interface ICivicAddress { - city: string; - country: string; - postalCode: string; - state: string; - timestamp: Date; - } - export class CivicAddress implements Windows.Devices.Geolocation.ICivicAddress { - city: string; - country: string; - postalCode: string; - state: string; - timestamp: Date; - } - export interface IGeoposition { - civicAddress: Windows.Devices.Geolocation.CivicAddress; - coordinate: Windows.Devices.Geolocation.Geocoordinate; - } - export class Geoposition implements Windows.Devices.Geolocation.IGeoposition { - civicAddress: Windows.Devices.Geolocation.CivicAddress; - coordinate: Windows.Devices.Geolocation.Geocoordinate; - } - export interface IPositionChangedEventArgs { - position: Windows.Devices.Geolocation.Geoposition; - } - export class PositionChangedEventArgs implements Windows.Devices.Geolocation.IPositionChangedEventArgs { - position: Windows.Devices.Geolocation.Geoposition; - } - export interface IStatusChangedEventArgs { - status: Windows.Devices.Geolocation.PositionStatus; - } - export class StatusChangedEventArgs implements Windows.Devices.Geolocation.IStatusChangedEventArgs { - status: Windows.Devices.Geolocation.PositionStatus; - } - export interface IGeolocator { - desiredAccuracy: Windows.Devices.Geolocation.PositionAccuracy; - locationStatus: Windows.Devices.Geolocation.PositionStatus; - movementThreshold: number; - reportInterval: number; - getGeopositionAsync(): Windows.Foundation.IAsyncOperation; - getGeopositionAsync(maximumAge: number, timeout: number): Windows.Foundation.IAsyncOperation; - onpositionchanged: any/* TODO */; - onstatuschanged: any/* TODO */; - } - export class Geolocator implements Windows.Devices.Geolocation.IGeolocator { - desiredAccuracy: Windows.Devices.Geolocation.PositionAccuracy; - locationStatus: Windows.Devices.Geolocation.PositionStatus; - movementThreshold: number; - reportInterval: number; - getGeopositionAsync(): Windows.Foundation.IAsyncOperation; - getGeopositionAsync(maximumAge: number, timeout: number): Windows.Foundation.IAsyncOperation; - onpositionchanged: any/* TODO */; - onstatuschanged: any/* TODO */; - } - } - } -} -declare module Windows { - export module Devices { - export module Input { - export enum PointerDeviceType { - touch, - pen, - mouse, - } - export interface PointerDeviceUsage { - usagePage: number; - usage: number; - minLogical: number; - maxLogical: number; - minPhysical: number; - maxPhysical: number; - unit: number; - physicalMultiplier: number; - } - export interface MouseDelta { - x: number; - y: number; - } - export interface IMouseCapabilities { - horizontalWheelPresent: number; - mousePresent: number; - numberOfButtons: number; - swapButtons: number; - verticalWheelPresent: number; - } - export interface IKeyboardCapabilities { - keyboardPresent: number; - } - export interface ITouchCapabilities { - contacts: number; - touchPresent: number; - } - export interface IPointerDeviceStatics { - getPointerDevice(pointerId: number): Windows.Devices.Input.PointerDevice; - getPointerDevices(): Windows.Foundation.Collections.IVectorView; - } - export class PointerDevice implements Windows.Devices.Input.IPointerDevice { - isIntegrated: boolean; - maxContacts: number; - physicalDeviceRect: Windows.Foundation.Rect; - pointerDeviceType: Windows.Devices.Input.PointerDeviceType; - screenRect: Windows.Foundation.Rect; - supportedUsages: Windows.Foundation.Collections.IVectorView; - static getPointerDevice(pointerId: number): Windows.Devices.Input.PointerDevice; - static getPointerDevices(): Windows.Foundation.Collections.IVectorView; - } - export interface IPointerDevice { - isIntegrated: boolean; - maxContacts: number; - physicalDeviceRect: Windows.Foundation.Rect; - pointerDeviceType: Windows.Devices.Input.PointerDeviceType; - screenRect: Windows.Foundation.Rect; - supportedUsages: Windows.Foundation.Collections.IVectorView; - } - export interface IMouseEventArgs { - mouseDelta: Windows.Devices.Input.MouseDelta; - } - export interface IMouseDevice { - onmousemoved: any/* TODO */; - } - export class MouseDevice implements Windows.Devices.Input.IMouseDevice { - onmousemoved: any/* TODO */; - static getForCurrentView(): Windows.Devices.Input.MouseDevice; - } - export class MouseEventArgs implements Windows.Devices.Input.IMouseEventArgs { - mouseDelta: Windows.Devices.Input.MouseDelta; - } - export interface IMouseDeviceStatics { - getForCurrentView(): Windows.Devices.Input.MouseDevice; - } - export class MouseCapabilities implements Windows.Devices.Input.IMouseCapabilities { - horizontalWheelPresent: number; - mousePresent: number; - numberOfButtons: number; - swapButtons: number; - verticalWheelPresent: number; - } - export class KeyboardCapabilities implements Windows.Devices.Input.IKeyboardCapabilities { - keyboardPresent: number; - } - export class TouchCapabilities implements Windows.Devices.Input.ITouchCapabilities { - contacts: number; - touchPresent: number; - } - } - } -} -declare module Windows { - export module Devices { - export module Portable { - export enum ServiceDeviceType { - calendarService, - contactsService, - deviceStatusService, - notesService, - ringtonesService, - smsService, - tasksService, - } - export interface IStorageDeviceStatics { - fromId(interfaceId: string): Windows.Storage.StorageFolder; - getDeviceSelector(): string; - } - export interface IServiceDeviceStatics { - getDeviceSelector(serviceType: Windows.Devices.Portable.ServiceDeviceType): string; - getDeviceSelectorFromServiceId(serviceId: string): string; - } - export class StorageDevice { - static fromId(interfaceId: string): Windows.Storage.StorageFolder; - static getDeviceSelector(): string; - } - export class ServiceDevice { - static getDeviceSelector(serviceType: Windows.Devices.Portable.ServiceDeviceType): string; - static getDeviceSelectorFromServiceId(serviceId: string): string; - } - } - } -} -declare module Windows { - export module Devices { - export module Printers { - export module Extensions { - export interface IPrintTaskConfigurationSaveRequestedDeferral { - complete(): void; - } - export class PrintTaskConfigurationSaveRequestedDeferral implements Windows.Devices.Printers.Extensions.IPrintTaskConfigurationSaveRequestedDeferral { - complete(): void; - } - export interface IPrintTaskConfigurationSaveRequest { - deadline: Date; - cancel(): void; - save(printerExtensionContext: any): void; - getDeferral(): Windows.Devices.Printers.Extensions.PrintTaskConfigurationSaveRequestedDeferral; - } - export class PrintTaskConfigurationSaveRequest implements Windows.Devices.Printers.Extensions.IPrintTaskConfigurationSaveRequest { - deadline: Date; - cancel(): void; - save(printerExtensionContext: any): void; - getDeferral(): Windows.Devices.Printers.Extensions.PrintTaskConfigurationSaveRequestedDeferral; - } - export interface IPrintTaskConfigurationSaveRequestedEventArgs { - request: Windows.Devices.Printers.Extensions.PrintTaskConfigurationSaveRequest; - } - export class PrintTaskConfigurationSaveRequestedEventArgs implements Windows.Devices.Printers.Extensions.IPrintTaskConfigurationSaveRequestedEventArgs { - request: Windows.Devices.Printers.Extensions.PrintTaskConfigurationSaveRequest; - } - export interface IPrintTaskConfiguration { - printerExtensionContext: any; - onsaverequested: any/* TODO */; - } - export class PrintTaskConfiguration implements Windows.Devices.Printers.Extensions.IPrintTaskConfiguration { - printerExtensionContext: any; - onsaverequested: any/* TODO */; - } - export interface IPrintNotificationEventDetails { - eventData: string; - printerName: string; - } - export class PrintNotificationEventDetails implements Windows.Devices.Printers.Extensions.IPrintNotificationEventDetails { - eventData: string; - printerName: string; - } - export interface IPrintExtensionContextStatic { - fromDeviceId(deviceId: string): any; - } - export class PrintExtensionContext { - static fromDeviceId(deviceId: string): any; - } - } - } - } -} -declare module Windows { - export module Devices { - export module Sensors { - export interface IAccelerometerStatics { - getDefault(): Windows.Devices.Sensors.Accelerometer; - } - export class Accelerometer implements Windows.Devices.Sensors.IAccelerometer { - minimumReportInterval: number; - reportInterval: number; - getCurrentReading(): Windows.Devices.Sensors.AccelerometerReading; - onreadingchanged: any/* TODO */; - onshaken: any/* TODO */; - static getDefault(): Windows.Devices.Sensors.Accelerometer; - } - export interface IAccelerometer { - minimumReportInterval: number; - reportInterval: number; - getCurrentReading(): Windows.Devices.Sensors.AccelerometerReading; - onreadingchanged: any/* TODO */; - onshaken: any/* TODO */; - } - export class AccelerometerReading implements Windows.Devices.Sensors.IAccelerometerReading { - accelerationX: number; - accelerationY: number; - accelerationZ: number; - timestamp: Date; - } - export class AccelerometerReadingChangedEventArgs implements Windows.Devices.Sensors.IAccelerometerReadingChangedEventArgs { - reading: Windows.Devices.Sensors.AccelerometerReading; - } - export class AccelerometerShakenEventArgs implements Windows.Devices.Sensors.IAccelerometerShakenEventArgs { - timestamp: Date; - } - export interface IAccelerometerReading { - accelerationX: number; - accelerationY: number; - accelerationZ: number; - timestamp: Date; - } - export interface IAccelerometerReadingChangedEventArgs { - reading: Windows.Devices.Sensors.AccelerometerReading; - } - export interface IAccelerometerShakenEventArgs { - timestamp: Date; - } - export interface IInclinometerStatics { - getDefault(): Windows.Devices.Sensors.Inclinometer; - } - export class Inclinometer implements Windows.Devices.Sensors.IInclinometer { - minimumReportInterval: number; - reportInterval: number; - getCurrentReading(): Windows.Devices.Sensors.InclinometerReading; - onreadingchanged: any/* TODO */; - static getDefault(): Windows.Devices.Sensors.Inclinometer; - } - export interface IInclinometer { - minimumReportInterval: number; - reportInterval: number; - getCurrentReading(): Windows.Devices.Sensors.InclinometerReading; - onreadingchanged: any/* TODO */; - } - export class InclinometerReading implements Windows.Devices.Sensors.IInclinometerReading { - pitchDegrees: number; - rollDegrees: number; - timestamp: Date; - yawDegrees: number; - } - export class InclinometerReadingChangedEventArgs implements Windows.Devices.Sensors.IInclinometerReadingChangedEventArgs { - reading: Windows.Devices.Sensors.InclinometerReading; - } - export interface IInclinometerReading { - pitchDegrees: number; - rollDegrees: number; - timestamp: Date; - yawDegrees: number; - } - export interface IInclinometerReadingChangedEventArgs { - reading: Windows.Devices.Sensors.InclinometerReading; - } - export interface IGyrometerStatics { - getDefault(): Windows.Devices.Sensors.Gyrometer; - } - export class Gyrometer implements Windows.Devices.Sensors.IGyrometer { - minimumReportInterval: number; - reportInterval: number; - getCurrentReading(): Windows.Devices.Sensors.GyrometerReading; - onreadingchanged: any/* TODO */; - static getDefault(): Windows.Devices.Sensors.Gyrometer; - } - export interface IGyrometer { - minimumReportInterval: number; - reportInterval: number; - getCurrentReading(): Windows.Devices.Sensors.GyrometerReading; - onreadingchanged: any/* TODO */; - } - export class GyrometerReading implements Windows.Devices.Sensors.IGyrometerReading { - angularVelocityX: number; - angularVelocityY: number; - angularVelocityZ: number; - timestamp: Date; - } - export class GyrometerReadingChangedEventArgs implements Windows.Devices.Sensors.IGyrometerReadingChangedEventArgs { - reading: Windows.Devices.Sensors.GyrometerReading; - } - export interface IGyrometerReading { - angularVelocityX: number; - angularVelocityY: number; - angularVelocityZ: number; - timestamp: Date; - } - export interface IGyrometerReadingChangedEventArgs { - reading: Windows.Devices.Sensors.GyrometerReading; - } - export interface ICompassStatics { - getDefault(): Windows.Devices.Sensors.Compass; - } - export class Compass implements Windows.Devices.Sensors.ICompass { - minimumReportInterval: number; - reportInterval: number; - getCurrentReading(): Windows.Devices.Sensors.CompassReading; - onreadingchanged: any/* TODO */; - static getDefault(): Windows.Devices.Sensors.Compass; - } - export interface ICompass { - minimumReportInterval: number; - reportInterval: number; - getCurrentReading(): Windows.Devices.Sensors.CompassReading; - onreadingchanged: any/* TODO */; - } - export class CompassReading implements Windows.Devices.Sensors.ICompassReading { - headingMagneticNorth: number; - headingTrueNorth: number; - timestamp: Date; - } - export class CompassReadingChangedEventArgs implements Windows.Devices.Sensors.ICompassReadingChangedEventArgs { - reading: Windows.Devices.Sensors.CompassReading; - } - export interface ICompassReading { - headingMagneticNorth: number; - headingTrueNorth: number; - timestamp: Date; - } - export interface ICompassReadingChangedEventArgs { - reading: Windows.Devices.Sensors.CompassReading; - } - export interface ILightSensorStatics { - getDefault(): Windows.Devices.Sensors.LightSensor; - } - export class LightSensor implements Windows.Devices.Sensors.ILightSensor { - minimumReportInterval: number; - reportInterval: number; - getCurrentReading(): Windows.Devices.Sensors.LightSensorReading; - onreadingchanged: any/* TODO */; - static getDefault(): Windows.Devices.Sensors.LightSensor; - } - export interface ILightSensor { - minimumReportInterval: number; - reportInterval: number; - getCurrentReading(): Windows.Devices.Sensors.LightSensorReading; - onreadingchanged: any/* TODO */; - } - export class LightSensorReading implements Windows.Devices.Sensors.ILightSensorReading { - illuminanceInLux: number; - timestamp: Date; - } - export class LightSensorReadingChangedEventArgs implements Windows.Devices.Sensors.ILightSensorReadingChangedEventArgs { - reading: Windows.Devices.Sensors.LightSensorReading; - } - export interface ILightSensorReading { - illuminanceInLux: number; - timestamp: Date; - } - export interface ILightSensorReadingChangedEventArgs { - reading: Windows.Devices.Sensors.LightSensorReading; - } - export interface ISensorRotationMatrix { - m11: number; - m12: number; - m13: number; - m21: number; - m22: number; - m23: number; - m31: number; - m32: number; - m33: number; - } - export interface ISensorQuaternion { - w: number; - x: number; - y: number; - z: number; - } - export class SensorRotationMatrix implements Windows.Devices.Sensors.ISensorRotationMatrix { - m11: number; - m12: number; - m13: number; - m21: number; - m22: number; - m23: number; - m31: number; - m32: number; - m33: number; - } - export class SensorQuaternion implements Windows.Devices.Sensors.ISensorQuaternion { - w: number; - x: number; - y: number; - z: number; - } - export interface IOrientationSensorStatics { - getDefault(): Windows.Devices.Sensors.OrientationSensor; - } - export class OrientationSensor implements Windows.Devices.Sensors.IOrientationSensor { - minimumReportInterval: number; - reportInterval: number; - getCurrentReading(): Windows.Devices.Sensors.OrientationSensorReading; - onreadingchanged: any/* TODO */; - static getDefault(): Windows.Devices.Sensors.OrientationSensor; - } - export interface IOrientationSensor { - minimumReportInterval: number; - reportInterval: number; - getCurrentReading(): Windows.Devices.Sensors.OrientationSensorReading; - onreadingchanged: any/* TODO */; - } - export class OrientationSensorReading implements Windows.Devices.Sensors.IOrientationSensorReading { - quaternion: Windows.Devices.Sensors.SensorQuaternion; - rotationMatrix: Windows.Devices.Sensors.SensorRotationMatrix; - timestamp: Date; - } - export class OrientationSensorReadingChangedEventArgs implements Windows.Devices.Sensors.IOrientationSensorReadingChangedEventArgs { - reading: Windows.Devices.Sensors.OrientationSensorReading; - } - export interface IOrientationSensorReading { - quaternion: Windows.Devices.Sensors.SensorQuaternion; - rotationMatrix: Windows.Devices.Sensors.SensorRotationMatrix; - timestamp: Date; - } - export interface IOrientationSensorReadingChangedEventArgs { - reading: Windows.Devices.Sensors.OrientationSensorReading; - } - export enum SimpleOrientation { - notRotated, - rotated90DegreesCounterclockwise, - rotated180DegreesCounterclockwise, - rotated270DegreesCounterclockwise, - faceup, - facedown, - } - export interface ISimpleOrientationSensorStatics { - getDefault(): Windows.Devices.Sensors.SimpleOrientationSensor; - } - export class SimpleOrientationSensor implements Windows.Devices.Sensors.ISimpleOrientationSensor { - getCurrentOrientation(): Windows.Devices.Sensors.SimpleOrientation; - onorientationchanged: any/* TODO */; - static getDefault(): Windows.Devices.Sensors.SimpleOrientationSensor; - } - export interface ISimpleOrientationSensor { - getCurrentOrientation(): Windows.Devices.Sensors.SimpleOrientation; - onorientationchanged: any/* TODO */; - } - export class SimpleOrientationSensorOrientationChangedEventArgs implements Windows.Devices.Sensors.ISimpleOrientationSensorOrientationChangedEventArgs { - orientation: Windows.Devices.Sensors.SimpleOrientation; - timestamp: Date; - } - export interface ISimpleOrientationSensorOrientationChangedEventArgs { - orientation: Windows.Devices.Sensors.SimpleOrientation; - timestamp: Date; - } - } - } -} -declare module Windows { - export module Globalization { - export module Fonts { - export interface ILanguageFontGroup { - documentAlternate1Font: Windows.Globalization.Fonts.LanguageFont; - documentAlternate2Font: Windows.Globalization.Fonts.LanguageFont; - documentHeadingFont: Windows.Globalization.Fonts.LanguageFont; - fixedWidthTextFont: Windows.Globalization.Fonts.LanguageFont; - modernDocumentFont: Windows.Globalization.Fonts.LanguageFont; - traditionalDocumentFont: Windows.Globalization.Fonts.LanguageFont; - uICaptionFont: Windows.Globalization.Fonts.LanguageFont; - uIHeadingFont: Windows.Globalization.Fonts.LanguageFont; - uINotificationHeadingFont: Windows.Globalization.Fonts.LanguageFont; - uITextFont: Windows.Globalization.Fonts.LanguageFont; - uITitleFont: Windows.Globalization.Fonts.LanguageFont; - } - export class LanguageFont implements Windows.Globalization.Fonts.ILanguageFont { - fontFamily: string; - fontStretch: Windows.UI.Text.FontStretch; - fontStyle: Windows.UI.Text.FontStyle; - fontWeight: Windows.UI.Text.FontWeight; - scaleFactor: number; - } - export interface ILanguageFontGroupFactory { - createLanguageFontGroup(languageTag: string): Windows.Globalization.Fonts.LanguageFontGroup; - } - export class LanguageFontGroup implements Windows.Globalization.Fonts.ILanguageFontGroup { - constructor(languageTag: string); - documentAlternate1Font: Windows.Globalization.Fonts.LanguageFont; - documentAlternate2Font: Windows.Globalization.Fonts.LanguageFont; - documentHeadingFont: Windows.Globalization.Fonts.LanguageFont; - fixedWidthTextFont: Windows.Globalization.Fonts.LanguageFont; - modernDocumentFont: Windows.Globalization.Fonts.LanguageFont; - traditionalDocumentFont: Windows.Globalization.Fonts.LanguageFont; - uICaptionFont: Windows.Globalization.Fonts.LanguageFont; - uIHeadingFont: Windows.Globalization.Fonts.LanguageFont; - uINotificationHeadingFont: Windows.Globalization.Fonts.LanguageFont; - uITextFont: Windows.Globalization.Fonts.LanguageFont; - uITitleFont: Windows.Globalization.Fonts.LanguageFont; - } - export interface ILanguageFont { - fontFamily: string; - fontStretch: Windows.UI.Text.FontStretch; - fontStyle: Windows.UI.Text.FontStyle; - fontWeight: Windows.UI.Text.FontWeight; - scaleFactor: number; - } - } - } -} -declare module Windows { - export module Globalization { - export enum DayOfWeek { - sunday, - monday, - tuesday, - wednesday, - thursday, - friday, - saturday, - } - export interface ICalendarIdentifiersStatics { - gregorian: string; - hebrew: string; - hijri: string; - japanese: string; - julian: string; - korean: string; - taiwan: string; - thai: string; - umAlQura: string; - } - export class CalendarIdentifiers { - static gregorian: string; - static hebrew: string; - static hijri: string; - static japanese: string; - static julian: string; - static korean: string; - static taiwan: string; - static thai: string; - static umAlQura: string; - } - export interface IClockIdentifiersStatics { - twelveHour: string; - twentyFourHour: string; - } - export class ClockIdentifiers { - static twelveHour: string; - static twentyFourHour: string; - } - export interface IGeographicRegion { - code: string; - codeThreeDigit: string; - codeThreeLetter: string; - codeTwoLetter: string; - currenciesInUse: Windows.Foundation.Collections.IVectorView; - displayName: string; - nativeName: string; - } - export interface IGeographicRegionFactory { - createGeographicRegion(geographicRegionCode: string): Windows.Globalization.GeographicRegion; - } - export class GeographicRegion implements Windows.Globalization.IGeographicRegion { - constructor(geographicRegionCode: string); - constructor(); - code: string; - codeThreeDigit: string; - codeThreeLetter: string; - codeTwoLetter: string; - currenciesInUse: Windows.Foundation.Collections.IVectorView; - displayName: string; - nativeName: string; - static isSupported(geographicRegionCode: string): boolean; - } - export interface IGeographicRegionStatics { - isSupported(geographicRegionCode: string): boolean; - } - export interface ILanguage { - displayName: string; - languageTag: string; - nativeName: string; - script: string; - } - export interface ILanguageFactory { - createLanguage(languageTag: string): Windows.Globalization.Language; - } - export class Language implements Windows.Globalization.ILanguage { - constructor(languageTag: string); - displayName: string; - languageTag: string; - nativeName: string; - script: string; - static currentInputMethodLanguageTag: string; - static isWellFormed(languageTag: string): boolean; - } - export interface ILanguageStatics { - currentInputMethodLanguageTag: string; - isWellFormed(languageTag: string): boolean; - } - export interface ICalendar { - day: number; - dayOfWeek: Windows.Globalization.DayOfWeek; - era: number; - firstDayInThisMonth: number; - firstEra: number; - firstHourInThisPeriod: number; - firstMinuteInThisHour: number; - firstMonthInThisYear: number; - firstPeriodInThisDay: number; - firstSecondInThisMinute: number; - firstYearInThisEra: number; - hour: number; - isDaylightSavingTime: boolean; - languages: Windows.Foundation.Collections.IVectorView; - lastDayInThisMonth: number; - lastEra: number; - lastHourInThisPeriod: number; - lastMinuteInThisHour: number; - lastMonthInThisYear: number; - lastPeriodInThisDay: number; - lastSecondInThisMinute: number; - lastYearInThisEra: number; - minute: number; - month: number; - nanosecond: number; - numberOfDaysInThisMonth: number; - numberOfEras: number; - numberOfHoursInThisPeriod: number; - numberOfMinutesInThisHour: number; - numberOfMonthsInThisYear: number; - numberOfPeriodsInThisDay: number; - numberOfSecondsInThisMinute: number; - numberOfYearsInThisEra: number; - numeralSystem: string; - period: number; - resolvedLanguage: string; - second: number; - year: number; - clone(): Windows.Globalization.Calendar; - setToMin(): void; - setToMax(): void; - getCalendarSystem(): string; - changeCalendarSystem(value: string): void; - getClock(): string; - changeClock(value: string): void; - getDateTime(): Date; - setDateTime(value: Date): void; - setToNow(): void; - addEras(eras: number): void; - eraAsString(): string; - eraAsString(idealLength: number): string; - addYears(years: number): void; - yearAsString(): string; - yearAsTruncatedString(remainingDigits: number): string; - yearAsPaddedString(minDigits: number): string; - addMonths(months: number): void; - monthAsString(): string; - monthAsString(idealLength: number): string; - monthAsSoloString(): string; - monthAsSoloString(idealLength: number): string; - monthAsNumericString(): string; - monthAsPaddedNumericString(minDigits: number): string; - addWeeks(weeks: number): void; - addDays(days: number): void; - dayAsString(): string; - dayAsPaddedString(minDigits: number): string; - dayOfWeekAsString(): string; - dayOfWeekAsString(idealLength: number): string; - dayOfWeekAsSoloString(): string; - dayOfWeekAsSoloString(idealLength: number): string; - addPeriods(periods: number): void; - periodAsString(): string; - periodAsString(idealLength: number): string; - addHours(hours: number): void; - hourAsString(): string; - hourAsPaddedString(minDigits: number): string; - addMinutes(minutes: number): void; - minuteAsString(): string; - minuteAsPaddedString(minDigits: number): string; - addSeconds(seconds: number): void; - secondAsString(): string; - secondAsPaddedString(minDigits: number): string; - addNanoseconds(nanoseconds: number): void; - nanosecondAsString(): string; - nanosecondAsPaddedString(minDigits: number): string; - compare(other: Windows.Globalization.Calendar): number; - compareDateTime(other: Date): number; - copyTo(other: Windows.Globalization.Calendar): void; - } - export class Calendar implements Windows.Globalization.ICalendar { - constructor(languages: Windows.Foundation.Collections.IIterable); - constructor(languages: Windows.Foundation.Collections.IIterable, calendar: string, clock: string); - constructor(); - day: number; - dayOfWeek: Windows.Globalization.DayOfWeek; - era: number; - firstDayInThisMonth: number; - firstEra: number; - firstHourInThisPeriod: number; - firstMinuteInThisHour: number; - firstMonthInThisYear: number; - firstPeriodInThisDay: number; - firstSecondInThisMinute: number; - firstYearInThisEra: number; - hour: number; - isDaylightSavingTime: boolean; - languages: Windows.Foundation.Collections.IVectorView; - lastDayInThisMonth: number; - lastEra: number; - lastHourInThisPeriod: number; - lastMinuteInThisHour: number; - lastMonthInThisYear: number; - lastPeriodInThisDay: number; - lastSecondInThisMinute: number; - lastYearInThisEra: number; - minute: number; - month: number; - nanosecond: number; - numberOfDaysInThisMonth: number; - numberOfEras: number; - numberOfHoursInThisPeriod: number; - numberOfMinutesInThisHour: number; - numberOfMonthsInThisYear: number; - numberOfPeriodsInThisDay: number; - numberOfSecondsInThisMinute: number; - numberOfYearsInThisEra: number; - numeralSystem: string; - period: number; - resolvedLanguage: string; - second: number; - year: number; - clone(): Windows.Globalization.Calendar; - setToMin(): void; - setToMax(): void; - getCalendarSystem(): string; - changeCalendarSystem(value: string): void; - getClock(): string; - changeClock(value: string): void; - getDateTime(): Date; - setDateTime(value: Date): void; - setToNow(): void; - addEras(eras: number): void; - eraAsString(): string; - eraAsString(idealLength: number): string; - addYears(years: number): void; - yearAsString(): string; - yearAsTruncatedString(remainingDigits: number): string; - yearAsPaddedString(minDigits: number): string; - addMonths(months: number): void; - monthAsString(): string; - monthAsString(idealLength: number): string; - monthAsSoloString(): string; - monthAsSoloString(idealLength: number): string; - monthAsNumericString(): string; - monthAsPaddedNumericString(minDigits: number): string; - addWeeks(weeks: number): void; - addDays(days: number): void; - dayAsString(): string; - dayAsPaddedString(minDigits: number): string; - dayOfWeekAsString(): string; - dayOfWeekAsString(idealLength: number): string; - dayOfWeekAsSoloString(): string; - dayOfWeekAsSoloString(idealLength: number): string; - addPeriods(periods: number): void; - periodAsString(): string; - periodAsString(idealLength: number): string; - addHours(hours: number): void; - hourAsString(): string; - hourAsPaddedString(minDigits: number): string; - addMinutes(minutes: number): void; - minuteAsString(): string; - minuteAsPaddedString(minDigits: number): string; - addSeconds(seconds: number): void; - secondAsString(): string; - secondAsPaddedString(minDigits: number): string; - addNanoseconds(nanoseconds: number): void; - nanosecondAsString(): string; - nanosecondAsPaddedString(minDigits: number): string; - compare(other: Windows.Globalization.Calendar): number; - compareDateTime(other: Date): number; - copyTo(other: Windows.Globalization.Calendar): void; - } - export interface ICalendarFactory { - createCalendarDefaultCalendarAndClock(languages: Windows.Foundation.Collections.IIterable): Windows.Globalization.Calendar; - createCalendar(languages: Windows.Foundation.Collections.IIterable, calendar: string, clock: string): Windows.Globalization.Calendar; - } - export interface IApplicationLanguagesStatics { - languages: Windows.Foundation.Collections.IVectorView; - manifestLanguages: Windows.Foundation.Collections.IVectorView; - primaryLanguageOverride: string; - } - export class ApplicationLanguages { - static languages: Windows.Foundation.Collections.IVectorView; - static manifestLanguages: Windows.Foundation.Collections.IVectorView; - static primaryLanguageOverride: string; - } - } -} -declare module Windows { - export module Globalization { - export module DateTimeFormatting { - export enum YearFormat { - none, - default, - abbreviated, - full, - } - export enum MonthFormat { - none, - default, - abbreviated, - full, - numeric, - } - export enum DayOfWeekFormat { - none, - default, - abbreviated, - full, - } - export enum DayFormat { - none, - default, - } - export enum HourFormat { - none, - default, - } - export enum MinuteFormat { - none, - default, - } - export enum SecondFormat { - none, - default, - } - export interface IDateTimeFormatter { - calendar: string; - clock: string; - geographicRegion: string; - includeDay: Windows.Globalization.DateTimeFormatting.DayFormat; - includeDayOfWeek: Windows.Globalization.DateTimeFormatting.DayOfWeekFormat; - includeHour: Windows.Globalization.DateTimeFormatting.HourFormat; - includeMinute: Windows.Globalization.DateTimeFormatting.MinuteFormat; - includeMonth: Windows.Globalization.DateTimeFormatting.MonthFormat; - includeSecond: Windows.Globalization.DateTimeFormatting.SecondFormat; - includeYear: Windows.Globalization.DateTimeFormatting.YearFormat; - languages: Windows.Foundation.Collections.IVectorView; - numeralSystem: string; - patterns: Windows.Foundation.Collections.IVectorView; - resolvedGeographicRegion: string; - resolvedLanguage: string; - template: string; - format(value: Date): string; - } - export interface IDateTimeFormatterFactory { - createDateTimeFormatter(formatTemplate: string): Windows.Globalization.DateTimeFormatting.DateTimeFormatter; - createDateTimeFormatterLanguages(formatTemplate: string, languages: Windows.Foundation.Collections.IIterable): Windows.Globalization.DateTimeFormatting.DateTimeFormatter; - createDateTimeFormatterContext(formatTemplate: string, languages: Windows.Foundation.Collections.IIterable, geographicRegion: string, calendar: string, clock: string): Windows.Globalization.DateTimeFormatting.DateTimeFormatter; - createDateTimeFormatterDate(yearFormat: Windows.Globalization.DateTimeFormatting.YearFormat, monthFormat: Windows.Globalization.DateTimeFormatting.MonthFormat, dayFormat: Windows.Globalization.DateTimeFormatting.DayFormat, dayOfWeekFormat: Windows.Globalization.DateTimeFormatting.DayOfWeekFormat): Windows.Globalization.DateTimeFormatting.DateTimeFormatter; - createDateTimeFormatterTime(hourFormat: Windows.Globalization.DateTimeFormatting.HourFormat, minuteFormat: Windows.Globalization.DateTimeFormatting.MinuteFormat, secondFormat: Windows.Globalization.DateTimeFormatting.SecondFormat): Windows.Globalization.DateTimeFormatting.DateTimeFormatter; - createDateTimeFormatterDateTimeLanguages(yearFormat: Windows.Globalization.DateTimeFormatting.YearFormat, monthFormat: Windows.Globalization.DateTimeFormatting.MonthFormat, dayFormat: Windows.Globalization.DateTimeFormatting.DayFormat, dayOfWeekFormat: Windows.Globalization.DateTimeFormatting.DayOfWeekFormat, hourFormat: Windows.Globalization.DateTimeFormatting.HourFormat, minuteFormat: Windows.Globalization.DateTimeFormatting.MinuteFormat, secondFormat: Windows.Globalization.DateTimeFormatting.SecondFormat, languages: Windows.Foundation.Collections.IIterable): Windows.Globalization.DateTimeFormatting.DateTimeFormatter; - createDateTimeFormatterDateTimeContext(yearFormat: Windows.Globalization.DateTimeFormatting.YearFormat, monthFormat: Windows.Globalization.DateTimeFormatting.MonthFormat, dayFormat: Windows.Globalization.DateTimeFormatting.DayFormat, dayOfWeekFormat: Windows.Globalization.DateTimeFormatting.DayOfWeekFormat, hourFormat: Windows.Globalization.DateTimeFormatting.HourFormat, minuteFormat: Windows.Globalization.DateTimeFormatting.MinuteFormat, secondFormat: Windows.Globalization.DateTimeFormatting.SecondFormat, languages: Windows.Foundation.Collections.IIterable, geographicRegion: string, calendar: string, clock: string): Windows.Globalization.DateTimeFormatting.DateTimeFormatter; - } - export class DateTimeFormatter implements Windows.Globalization.DateTimeFormatting.IDateTimeFormatter { - constructor(formatTemplate: string); - constructor(formatTemplate: string, languages: Windows.Foundation.Collections.IIterable); - constructor(formatTemplate: string, languages: Windows.Foundation.Collections.IIterable, geographicRegion: string, calendar: string, clock: string); - constructor(yearFormat: Windows.Globalization.DateTimeFormatting.YearFormat, monthFormat: Windows.Globalization.DateTimeFormatting.MonthFormat, dayFormat: Windows.Globalization.DateTimeFormatting.DayFormat, dayOfWeekFormat: Windows.Globalization.DateTimeFormatting.DayOfWeekFormat); - constructor(hourFormat: Windows.Globalization.DateTimeFormatting.HourFormat, minuteFormat: Windows.Globalization.DateTimeFormatting.MinuteFormat, secondFormat: Windows.Globalization.DateTimeFormatting.SecondFormat); - constructor(yearFormat: Windows.Globalization.DateTimeFormatting.YearFormat, monthFormat: Windows.Globalization.DateTimeFormatting.MonthFormat, dayFormat: Windows.Globalization.DateTimeFormatting.DayFormat, dayOfWeekFormat: Windows.Globalization.DateTimeFormatting.DayOfWeekFormat, hourFormat: Windows.Globalization.DateTimeFormatting.HourFormat, minuteFormat: Windows.Globalization.DateTimeFormatting.MinuteFormat, secondFormat: Windows.Globalization.DateTimeFormatting.SecondFormat, languages: Windows.Foundation.Collections.IIterable); - constructor(yearFormat: Windows.Globalization.DateTimeFormatting.YearFormat, monthFormat: Windows.Globalization.DateTimeFormatting.MonthFormat, dayFormat: Windows.Globalization.DateTimeFormatting.DayFormat, dayOfWeekFormat: Windows.Globalization.DateTimeFormatting.DayOfWeekFormat, hourFormat: Windows.Globalization.DateTimeFormatting.HourFormat, minuteFormat: Windows.Globalization.DateTimeFormatting.MinuteFormat, secondFormat: Windows.Globalization.DateTimeFormatting.SecondFormat, languages: Windows.Foundation.Collections.IIterable, geographicRegion: string, calendar: string, clock: string); - calendar: string; - clock: string; - geographicRegion: string; - includeDay: Windows.Globalization.DateTimeFormatting.DayFormat; - includeDayOfWeek: Windows.Globalization.DateTimeFormatting.DayOfWeekFormat; - includeHour: Windows.Globalization.DateTimeFormatting.HourFormat; - includeMinute: Windows.Globalization.DateTimeFormatting.MinuteFormat; - includeMonth: Windows.Globalization.DateTimeFormatting.MonthFormat; - includeSecond: Windows.Globalization.DateTimeFormatting.SecondFormat; - includeYear: Windows.Globalization.DateTimeFormatting.YearFormat; - languages: Windows.Foundation.Collections.IVectorView; - numeralSystem: string; - patterns: Windows.Foundation.Collections.IVectorView; - resolvedGeographicRegion: string; - resolvedLanguage: string; - template: string; - format(value: Date): string; - static longDate: Windows.Globalization.DateTimeFormatting.DateTimeFormatter; - static longTime: Windows.Globalization.DateTimeFormatting.DateTimeFormatter; - static shortDate: Windows.Globalization.DateTimeFormatting.DateTimeFormatter; - static shortTime: Windows.Globalization.DateTimeFormatting.DateTimeFormatter; - } - export interface IDateTimeFormatterStatics { - longDate: Windows.Globalization.DateTimeFormatting.DateTimeFormatter; - longTime: Windows.Globalization.DateTimeFormatting.DateTimeFormatter; - shortDate: Windows.Globalization.DateTimeFormatting.DateTimeFormatter; - shortTime: Windows.Globalization.DateTimeFormatting.DateTimeFormatter; - } - } - } -} -declare module Windows { - export module Globalization { - export module NumberFormatting { - export interface INumberFormatter { - format(value: number): string; - } - export interface INumberFormatter2 { - formatInt(value: number): string; - formatUInt(value: number): string; - formatDouble(value: number): string; - } - export interface INumberParser { - parseInt(text: string): number; - parseUInt(text: string): number; - parseDouble(text: string): number; - } - export interface INumberFormatterOptions { - fractionDigits: number; - geographicRegion: string; - integerDigits: number; - isDecimalPointAlwaysDisplayed: boolean; - isGrouped: boolean; - languages: Windows.Foundation.Collections.IVectorView; - numeralSystem: string; - resolvedGeographicRegion: string; - resolvedLanguage: string; - } - export interface IDecimalFormatterFactory { - createDecimalFormatter(languages: Windows.Foundation.Collections.IIterable, geographicRegion: string): Windows.Globalization.NumberFormatting.DecimalFormatter; - } - export class DecimalFormatter implements Windows.Globalization.NumberFormatting.INumberFormatterOptions, Windows.Globalization.NumberFormatting.INumberFormatter, Windows.Globalization.NumberFormatting.INumberFormatter2, Windows.Globalization.NumberFormatting.INumberParser { - constructor(languages: Windows.Foundation.Collections.IIterable, geographicRegion: string); - constructor(); - fractionDigits: number; - geographicRegion: string; - integerDigits: number; - isDecimalPointAlwaysDisplayed: boolean; - isGrouped: boolean; - languages: Windows.Foundation.Collections.IVectorView; - numeralSystem: string; - resolvedGeographicRegion: string; - resolvedLanguage: string; - format(value: number): string; - formatInt(value: number): string; - formatUInt(value: number): string; - formatDouble(value: number): string; - parseInt(text: string): number; - parseUInt(text: string): number; - parseDouble(text: string): number; - } - export interface IPercentFormatterFactory { - createPercentFormatter(languages: Windows.Foundation.Collections.IIterable, geographicRegion: string): Windows.Globalization.NumberFormatting.PercentFormatter; - } - export class PercentFormatter implements Windows.Globalization.NumberFormatting.INumberFormatterOptions, Windows.Globalization.NumberFormatting.INumberFormatter, Windows.Globalization.NumberFormatting.INumberFormatter2, Windows.Globalization.NumberFormatting.INumberParser { - constructor(languages: Windows.Foundation.Collections.IIterable, geographicRegion: string); - constructor(); - fractionDigits: number; - geographicRegion: string; - integerDigits: number; - isDecimalPointAlwaysDisplayed: boolean; - isGrouped: boolean; - languages: Windows.Foundation.Collections.IVectorView; - numeralSystem: string; - resolvedGeographicRegion: string; - resolvedLanguage: string; - format(value: number): string; - formatInt(value: number): string; - formatUInt(value: number): string; - formatDouble(value: number): string; - parseInt(text: string): number; - parseUInt(text: string): number; - parseDouble(text: string): number; - } - export interface IPermilleFormatterFactory { - createPermilleFormatter(languages: Windows.Foundation.Collections.IIterable, geographicRegion: string): Windows.Globalization.NumberFormatting.PermilleFormatter; - } - export class PermilleFormatter implements Windows.Globalization.NumberFormatting.INumberFormatterOptions, Windows.Globalization.NumberFormatting.INumberFormatter, Windows.Globalization.NumberFormatting.INumberFormatter2, Windows.Globalization.NumberFormatting.INumberParser { - constructor(languages: Windows.Foundation.Collections.IIterable, geographicRegion: string); - constructor(); - fractionDigits: number; - geographicRegion: string; - integerDigits: number; - isDecimalPointAlwaysDisplayed: boolean; - isGrouped: boolean; - languages: Windows.Foundation.Collections.IVectorView; - numeralSystem: string; - resolvedGeographicRegion: string; - resolvedLanguage: string; - format(value: number): string; - formatInt(value: number): string; - formatUInt(value: number): string; - formatDouble(value: number): string; - parseInt(text: string): number; - parseUInt(text: string): number; - parseDouble(text: string): number; - } - export interface ICurrencyFormatterFactory { - createCurrencyFormatterCode(currencyCode: string): Windows.Globalization.NumberFormatting.CurrencyFormatter; - createCurrencyFormatterCodeContext(currencyCode: string, languages: Windows.Foundation.Collections.IIterable, geographicRegion: string): Windows.Globalization.NumberFormatting.CurrencyFormatter; - } - export class CurrencyFormatter implements Windows.Globalization.NumberFormatting.ICurrencyFormatter, Windows.Globalization.NumberFormatting.INumberFormatterOptions, Windows.Globalization.NumberFormatting.INumberFormatter, Windows.Globalization.NumberFormatting.INumberFormatter2, Windows.Globalization.NumberFormatting.INumberParser { - constructor(currencyCode: string); - constructor(currencyCode: string, languages: Windows.Foundation.Collections.IIterable, geographicRegion: string); - currency: string; - fractionDigits: number; - geographicRegion: string; - integerDigits: number; - isDecimalPointAlwaysDisplayed: boolean; - isGrouped: boolean; - languages: Windows.Foundation.Collections.IVectorView; - numeralSystem: string; - resolvedGeographicRegion: string; - resolvedLanguage: string; - format(value: number): string; - formatInt(value: number): string; - formatUInt(value: number): string; - formatDouble(value: number): string; - parseInt(text: string): number; - parseUInt(text: string): number; - parseDouble(text: string): number; - } - export interface ICurrencyFormatter extends Windows.Globalization.NumberFormatting.INumberFormatterOptions, Windows.Globalization.NumberFormatting.INumberFormatter, Windows.Globalization.NumberFormatting.INumberFormatter2, Windows.Globalization.NumberFormatting.INumberParser { - currency: string; - } - } - } -} -declare module Windows { - export module Globalization { - export module Collation { - export interface ICharacterGrouping { - first: string; - label: string; - } - export class CharacterGrouping implements Windows.Globalization.Collation.ICharacterGrouping { - first: string; - label: string; - } - export interface ICharacterGroupings extends Windows.Foundation.Collections.IVectorView, Windows.Foundation.Collections.IIterable { - lookup(text: string): string; - } - export class CharacterGroupings implements Windows.Globalization.Collation.ICharacterGroupings, Windows.Foundation.Collections.IVectorView, Windows.Foundation.Collections.IIterable { - size: number; - lookup(text: string): string; - getAt(index: number): Windows.Globalization.Collation.CharacterGrouping; - indexOf(value: Windows.Globalization.Collation.CharacterGrouping): { index: number; returnValue: boolean; }; - getMany(startIndex: number): { items: Windows.Globalization.Collation.CharacterGrouping[]; returnValue: number; }; - first(): Windows.Foundation.Collections.IIterator; - toString(): string; - toLocaleString(): string; - concat(...items: Windows.Globalization.Collation.CharacterGrouping[][]): Windows.Globalization.Collation.CharacterGrouping[]; - join(seperator: string): string; - pop(): Windows.Globalization.Collation.CharacterGrouping; - push(...items: Windows.Globalization.Collation.CharacterGrouping[]): void; - reverse(): Windows.Globalization.Collation.CharacterGrouping[]; - shift(): Windows.Globalization.Collation.CharacterGrouping; - slice(start: number): Windows.Globalization.Collation.CharacterGrouping[]; - slice(start: number, end: number): Windows.Globalization.Collation.CharacterGrouping[]; - sort(): Windows.Globalization.Collation.CharacterGrouping[]; - sort(compareFn: (a: Windows.Globalization.Collation.CharacterGrouping, b: Windows.Globalization.Collation.CharacterGrouping) => number): Windows.Globalization.Collation.CharacterGrouping[]; - splice(start: number): Windows.Globalization.Collation.CharacterGrouping[]; - splice(start: number, deleteCount: number, ...items: Windows.Globalization.Collation.CharacterGrouping[]): Windows.Globalization.Collation.CharacterGrouping[]; - unshift(...items: Windows.Globalization.Collation.CharacterGrouping[]): number; - lastIndexOf(searchElement: Windows.Globalization.Collation.CharacterGrouping): number; - lastIndexOf(searchElement: Windows.Globalization.Collation.CharacterGrouping, fromIndex: number): number; - every(callbackfn: (value: Windows.Globalization.Collation.CharacterGrouping, index: number, array: Windows.Globalization.Collation.CharacterGrouping[]) => boolean): boolean; - every(callbackfn: (value: Windows.Globalization.Collation.CharacterGrouping, index: number, array: Windows.Globalization.Collation.CharacterGrouping[]) => boolean, thisArg: any): boolean; - some(callbackfn: (value: Windows.Globalization.Collation.CharacterGrouping, index: number, array: Windows.Globalization.Collation.CharacterGrouping[]) => boolean): boolean; - some(callbackfn: (value: Windows.Globalization.Collation.CharacterGrouping, index: number, array: Windows.Globalization.Collation.CharacterGrouping[]) => boolean, thisArg: any): boolean; - forEach(callbackfn: (value: Windows.Globalization.Collation.CharacterGrouping, index: number, array: Windows.Globalization.Collation.CharacterGrouping[]) => void ): void; - forEach(callbackfn: (value: Windows.Globalization.Collation.CharacterGrouping, index: number, array: Windows.Globalization.Collation.CharacterGrouping[]) => void , thisArg: any): void; - map(callbackfn: (value: Windows.Globalization.Collation.CharacterGrouping, index: number, array: Windows.Globalization.Collation.CharacterGrouping[]) => any): any[]; - map(callbackfn: (value: Windows.Globalization.Collation.CharacterGrouping, index: number, array: Windows.Globalization.Collation.CharacterGrouping[]) => any, thisArg: any): any[]; - filter(callbackfn: (value: Windows.Globalization.Collation.CharacterGrouping, index: number, array: Windows.Globalization.Collation.CharacterGrouping[]) => boolean): Windows.Globalization.Collation.CharacterGrouping[]; - filter(callbackfn: (value: Windows.Globalization.Collation.CharacterGrouping, index: number, array: Windows.Globalization.Collation.CharacterGrouping[]) => boolean, thisArg: any): Windows.Globalization.Collation.CharacterGrouping[]; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Globalization.Collation.CharacterGrouping[]) => any): any; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Globalization.Collation.CharacterGrouping[]) => any, initialValue: any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Globalization.Collation.CharacterGrouping[]) => any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Globalization.Collation.CharacterGrouping[]) => any, initialValue: any): any; - length: number; - } - } - } -} -declare module Windows { - export module Graphics { - export module Display { - export interface DisplayPropertiesEventHandler { - (sender: any): void; - } - export enum DisplayOrientations { - none, - landscape, - portrait, - landscapeFlipped, - portraitFlipped, - } - export enum ResolutionScale { - invalid, - scale100Percent, - scale140Percent, - scale180Percent, - } - export interface IDisplayPropertiesStatics { - autoRotationPreferences: Windows.Graphics.Display.DisplayOrientations; - currentOrientation: Windows.Graphics.Display.DisplayOrientations; - logicalDpi: number; - nativeOrientation: Windows.Graphics.Display.DisplayOrientations; - resolutionScale: Windows.Graphics.Display.ResolutionScale; - stereoEnabled: boolean; - onorientationchanged: any/* TODO */; - onlogicaldpichanged: any/* TODO */; - onstereoenabledchanged: any/* TODO */; - getColorProfileAsync(): Windows.Foundation.IAsyncOperation; - oncolorprofilechanged: any/* TODO */; - ondisplaycontentsinvalidated: any/* TODO */; - } - export class DisplayProperties { - static autoRotationPreferences: Windows.Graphics.Display.DisplayOrientations; - static currentOrientation: Windows.Graphics.Display.DisplayOrientations; - static logicalDpi: number; - static nativeOrientation: Windows.Graphics.Display.DisplayOrientations; - static resolutionScale: Windows.Graphics.Display.ResolutionScale; - static stereoEnabled: boolean; - static onorientationchanged: any/* TODO */; - static onlogicaldpichanged: any/* TODO */; - static onstereoenabledchanged: any/* TODO */; - static getColorProfileAsync(): Windows.Foundation.IAsyncOperation; - static oncolorprofilechanged: any/* TODO */; - static ondisplaycontentsinvalidated: any/* TODO */; - } - } - } -} -declare module Windows { - export module Graphics { - export module Imaging { - export enum BitmapPixelFormat { - unknown, - rgba16, - rgba8, - bgra8, - } - export enum BitmapAlphaMode { - premultiplied, - straight, - ignore, - } - export enum BitmapInterpolationMode { - nearestNeighbor, - linear, - cubic, - fant, - } - export enum BitmapFlip { - none, - horizontal, - vertical, - } - export enum BitmapRotation { - none, - clockwise90Degrees, - clockwise180Degrees, - clockwise270Degrees, - } - export interface BitmapBounds { - x: number; - y: number; - width: number; - height: number; - } - export enum ColorManagementMode { - doNotColorManage, - colorManageToSRgb, - } - export enum ExifOrientationMode { - ignoreExifOrientation, - respectExifOrientation, - } - export enum PngFilterMode { - automatic, - none, - sub, - up, - average, - paeth, - adaptive, - } - export enum TiffCompressionMode { - automatic, - none, - ccitt3, - ccitt4, - lzw, - rle, - zip, - lzwhDifferencing, - } - export enum JpegSubsamplingMode { - default, - y4Cb2Cr0, - y4Cb2Cr2, - y4Cb4Cr4, - } - export interface IBitmapTransform { - bounds: Windows.Graphics.Imaging.BitmapBounds; - flip: Windows.Graphics.Imaging.BitmapFlip; - interpolationMode: Windows.Graphics.Imaging.BitmapInterpolationMode; - rotation: Windows.Graphics.Imaging.BitmapRotation; - scaledHeight: number; - scaledWidth: number; - } - export class BitmapTransform implements Windows.Graphics.Imaging.IBitmapTransform { - bounds: Windows.Graphics.Imaging.BitmapBounds; - flip: Windows.Graphics.Imaging.BitmapFlip; - interpolationMode: Windows.Graphics.Imaging.BitmapInterpolationMode; - rotation: Windows.Graphics.Imaging.BitmapRotation; - scaledHeight: number; - scaledWidth: number; - } - export interface IBitmapTypedValue { - type: Windows.Foundation.PropertyType; - value: any; - } - export interface IBitmapTypedValueFactory { - create(value: any, type: Windows.Foundation.PropertyType): Windows.Graphics.Imaging.BitmapTypedValue; - } - export class BitmapTypedValue implements Windows.Graphics.Imaging.IBitmapTypedValue { - constructor(value: any, type: Windows.Foundation.PropertyType); - type: Windows.Foundation.PropertyType; - value: any; - } - export class BitmapPropertySet implements Windows.Foundation.Collections.IMap, Windows.Foundation.Collections.IIterable> { - size: number; - lookup(key: string): Windows.Graphics.Imaging.BitmapTypedValue; - hasKey(key: string): boolean; - getView(): Windows.Foundation.Collections.IMapView; - insert(key: string, value: Windows.Graphics.Imaging.BitmapTypedValue): boolean; - remove(key: string): void; - clear(): void; - first(): Windows.Foundation.Collections.IIterator>; - } - export interface IBitmapPropertiesView { - getPropertiesAsync(propertiesToRetrieve: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncOperation; - } - export interface IBitmapProperties extends Windows.Graphics.Imaging.IBitmapPropertiesView { - setPropertiesAsync(propertiesToSet: Windows.Foundation.Collections.IIterable>): Windows.Foundation.IAsyncAction; - } - export class BitmapPropertiesView implements Windows.Graphics.Imaging.IBitmapPropertiesView { - getPropertiesAsync(propertiesToRetrieve: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncOperation; - } - export class BitmapProperties implements Windows.Graphics.Imaging.IBitmapProperties, Windows.Graphics.Imaging.IBitmapPropertiesView { - setPropertiesAsync(propertiesToSet: Windows.Foundation.Collections.IIterable>): Windows.Foundation.IAsyncAction; - getPropertiesAsync(propertiesToRetrieve: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncOperation; - } - export interface IPixelDataProvider { - detachPixelData(): Uint8Array; - } - export class PixelDataProvider implements Windows.Graphics.Imaging.IPixelDataProvider { - detachPixelData(): Uint8Array; - } - export class ImageStream implements Windows.Storage.Streams.IRandomAccessStreamWithContentType, Windows.Storage.Streams.IRandomAccessStream, Windows.Foundation.IClosable, Windows.Storage.Streams.IInputStream, Windows.Storage.Streams.IOutputStream, Windows.Storage.Streams.IContentTypeProvider { - canRead: boolean; - canWrite: boolean; - position: number; - size: number; - contentType: string; - getInputStreamAt(position: number): Windows.Storage.Streams.IInputStream; - getOutputStreamAt(position: number): Windows.Storage.Streams.IOutputStream; - seek(position: number): void; - cloneStream(): Windows.Storage.Streams.IRandomAccessStream; - dispose(): void; - readAsync(buffer: Windows.Storage.Streams.IBuffer, count: number, options: Windows.Storage.Streams.InputStreamOptions): Windows.Foundation.IAsyncOperationWithProgress; - writeAsync(buffer: Windows.Storage.Streams.IBuffer): Windows.Foundation.IAsyncOperationWithProgress; - flushAsync(): Windows.Foundation.IAsyncOperation; - close(): void; - } - export interface IBitmapFrame { - bitmapAlphaMode: Windows.Graphics.Imaging.BitmapAlphaMode; - bitmapPixelFormat: Windows.Graphics.Imaging.BitmapPixelFormat; - bitmapProperties: Windows.Graphics.Imaging.BitmapPropertiesView; - dpiX: number; - dpiY: number; - orientedPixelHeight: number; - orientedPixelWidth: number; - pixelHeight: number; - pixelWidth: number; - getThumbnailAsync(): Windows.Foundation.IAsyncOperation; - getPixelDataAsync(): Windows.Foundation.IAsyncOperation; - getPixelDataAsync(pixelFormat: Windows.Graphics.Imaging.BitmapPixelFormat, alphaMode: Windows.Graphics.Imaging.BitmapAlphaMode, transform: Windows.Graphics.Imaging.BitmapTransform, exifOrientationMode: Windows.Graphics.Imaging.ExifOrientationMode, colorManagementMode: Windows.Graphics.Imaging.ColorManagementMode): Windows.Foundation.IAsyncOperation; - } - export class BitmapFrame implements Windows.Graphics.Imaging.IBitmapFrame { - bitmapAlphaMode: Windows.Graphics.Imaging.BitmapAlphaMode; - bitmapPixelFormat: Windows.Graphics.Imaging.BitmapPixelFormat; - bitmapProperties: Windows.Graphics.Imaging.BitmapPropertiesView; - dpiX: number; - dpiY: number; - orientedPixelHeight: number; - orientedPixelWidth: number; - pixelHeight: number; - pixelWidth: number; - getThumbnailAsync(): Windows.Foundation.IAsyncOperation; - getPixelDataAsync(): Windows.Foundation.IAsyncOperation; - getPixelDataAsync(pixelFormat: Windows.Graphics.Imaging.BitmapPixelFormat, alphaMode: Windows.Graphics.Imaging.BitmapAlphaMode, transform: Windows.Graphics.Imaging.BitmapTransform, exifOrientationMode: Windows.Graphics.Imaging.ExifOrientationMode, colorManagementMode: Windows.Graphics.Imaging.ColorManagementMode): Windows.Foundation.IAsyncOperation; - } - export interface IBitmapCodecInformation { - codecId: string; - fileExtensions: Windows.Foundation.Collections.IVectorView; - friendlyName: string; - mimeTypes: Windows.Foundation.Collections.IVectorView; - } - export class BitmapCodecInformation implements Windows.Graphics.Imaging.IBitmapCodecInformation { - codecId: string; - fileExtensions: Windows.Foundation.Collections.IVectorView; - friendlyName: string; - mimeTypes: Windows.Foundation.Collections.IVectorView; - } - export interface IBitmapDecoderStatics { - bmpDecoderId: string; - gifDecoderId: string; - icoDecoderId: string; - jpegDecoderId: string; - jpegXRDecoderId: string; - pngDecoderId: string; - tiffDecoderId: string; - getDecoderInformationEnumerator(): Windows.Foundation.Collections.IVectorView; - createAsync(stream: Windows.Storage.Streams.IRandomAccessStream): Windows.Foundation.IAsyncOperation; - createAsync(decoderId: string, stream: Windows.Storage.Streams.IRandomAccessStream): Windows.Foundation.IAsyncOperation; - } - export class BitmapDecoder implements Windows.Graphics.Imaging.IBitmapDecoder, Windows.Graphics.Imaging.IBitmapFrame { - bitmapContainerProperties: Windows.Graphics.Imaging.BitmapPropertiesView; - decoderInformation: Windows.Graphics.Imaging.BitmapCodecInformation; - frameCount: number; - bitmapAlphaMode: Windows.Graphics.Imaging.BitmapAlphaMode; - bitmapPixelFormat: Windows.Graphics.Imaging.BitmapPixelFormat; - bitmapProperties: Windows.Graphics.Imaging.BitmapPropertiesView; - dpiX: number; - dpiY: number; - orientedPixelHeight: number; - orientedPixelWidth: number; - pixelHeight: number; - pixelWidth: number; - getPreviewAsync(): Windows.Foundation.IAsyncOperation; - getFrameAsync(frameIndex: number): Windows.Foundation.IAsyncOperation; - getThumbnailAsync(): Windows.Foundation.IAsyncOperation; - getPixelDataAsync(): Windows.Foundation.IAsyncOperation; - getPixelDataAsync(pixelFormat: Windows.Graphics.Imaging.BitmapPixelFormat, alphaMode: Windows.Graphics.Imaging.BitmapAlphaMode, transform: Windows.Graphics.Imaging.BitmapTransform, exifOrientationMode: Windows.Graphics.Imaging.ExifOrientationMode, colorManagementMode: Windows.Graphics.Imaging.ColorManagementMode): Windows.Foundation.IAsyncOperation; - static bmpDecoderId: string; - static gifDecoderId: string; - static icoDecoderId: string; - static jpegDecoderId: string; - static jpegXRDecoderId: string; - static pngDecoderId: string; - static tiffDecoderId: string; - static getDecoderInformationEnumerator(): Windows.Foundation.Collections.IVectorView; - static createAsync(stream: Windows.Storage.Streams.IRandomAccessStream): Windows.Foundation.IAsyncOperation; - static createAsync(decoderId: string, stream: Windows.Storage.Streams.IRandomAccessStream): Windows.Foundation.IAsyncOperation; - } - export interface IBitmapDecoder { - bitmapContainerProperties: Windows.Graphics.Imaging.BitmapPropertiesView; - decoderInformation: Windows.Graphics.Imaging.BitmapCodecInformation; - frameCount: number; - getPreviewAsync(): Windows.Foundation.IAsyncOperation; - getFrameAsync(frameIndex: number): Windows.Foundation.IAsyncOperation; - } - export interface IBitmapEncoderStatics { - bmpEncoderId: string; - gifEncoderId: string; - jpegEncoderId: string; - jpegXREncoderId: string; - pngEncoderId: string; - tiffEncoderId: string; - getEncoderInformationEnumerator(): Windows.Foundation.Collections.IVectorView; - createAsync(encoderId: string, stream: Windows.Storage.Streams.IRandomAccessStream): Windows.Foundation.IAsyncOperation; - createAsync(encoderId: string, stream: Windows.Storage.Streams.IRandomAccessStream, encodingOptions: Windows.Foundation.Collections.IIterable>): Windows.Foundation.IAsyncOperation; - createForTranscodingAsync(stream: Windows.Storage.Streams.IRandomAccessStream, bitmapDecoder: Windows.Graphics.Imaging.BitmapDecoder): Windows.Foundation.IAsyncOperation; - createForInPlacePropertyEncodingAsync(bitmapDecoder: Windows.Graphics.Imaging.BitmapDecoder): Windows.Foundation.IAsyncOperation; - } - export class BitmapEncoder implements Windows.Graphics.Imaging.IBitmapEncoder { - bitmapContainerProperties: Windows.Graphics.Imaging.BitmapProperties; - bitmapProperties: Windows.Graphics.Imaging.BitmapProperties; - bitmapTransform: Windows.Graphics.Imaging.BitmapTransform; - encoderInformation: Windows.Graphics.Imaging.BitmapCodecInformation; - generatedThumbnailHeight: number; - generatedThumbnailWidth: number; - isThumbnailGenerated: boolean; - setPixelData(pixelFormat: Windows.Graphics.Imaging.BitmapPixelFormat, alphaMode: Windows.Graphics.Imaging.BitmapAlphaMode, width: number, height: number, dpiX: number, dpiY: number, pixels: Uint8Array): void; - goToNextFrameAsync(): Windows.Foundation.IAsyncAction; - goToNextFrameAsync(encodingOptions: Windows.Foundation.Collections.IIterable>): Windows.Foundation.IAsyncAction; - flushAsync(): Windows.Foundation.IAsyncAction; - static bmpEncoderId: string; - static gifEncoderId: string; - static jpegEncoderId: string; - static jpegXREncoderId: string; - static pngEncoderId: string; - static tiffEncoderId: string; - static getEncoderInformationEnumerator(): Windows.Foundation.Collections.IVectorView; - static createAsync(encoderId: string, stream: Windows.Storage.Streams.IRandomAccessStream): Windows.Foundation.IAsyncOperation; - static createAsync(encoderId: string, stream: Windows.Storage.Streams.IRandomAccessStream, encodingOptions: Windows.Foundation.Collections.IIterable>): Windows.Foundation.IAsyncOperation; - static createForTranscodingAsync(stream: Windows.Storage.Streams.IRandomAccessStream, bitmapDecoder: Windows.Graphics.Imaging.BitmapDecoder): Windows.Foundation.IAsyncOperation; - static createForInPlacePropertyEncodingAsync(bitmapDecoder: Windows.Graphics.Imaging.BitmapDecoder): Windows.Foundation.IAsyncOperation; - } - export interface IBitmapEncoder { - bitmapContainerProperties: Windows.Graphics.Imaging.BitmapProperties; - bitmapProperties: Windows.Graphics.Imaging.BitmapProperties; - bitmapTransform: Windows.Graphics.Imaging.BitmapTransform; - encoderInformation: Windows.Graphics.Imaging.BitmapCodecInformation; - generatedThumbnailHeight: number; - generatedThumbnailWidth: number; - isThumbnailGenerated: boolean; - setPixelData(pixelFormat: Windows.Graphics.Imaging.BitmapPixelFormat, alphaMode: Windows.Graphics.Imaging.BitmapAlphaMode, width: number, height: number, dpiX: number, dpiY: number, pixels: Uint8Array): void; - goToNextFrameAsync(): Windows.Foundation.IAsyncAction; - goToNextFrameAsync(encodingOptions: Windows.Foundation.Collections.IIterable>): Windows.Foundation.IAsyncAction; - flushAsync(): Windows.Foundation.IAsyncAction; - } - } - } -} -declare module Windows { - export module Graphics { - export module Printing { - export module OptionDetails { - export enum PrintOptionStates { - none, - enabled, - constrained, - } - export enum PrintOptionType { - unknown, - number, - text, - itemList, - } - export interface IPrintOptionDetails { - errorText: string; - optionId: string; - optionType: Windows.Graphics.Printing.OptionDetails.PrintOptionType; - state: Windows.Graphics.Printing.OptionDetails.PrintOptionStates; - value: any; - trySetValue(value: any): boolean; - } - export interface IPrintNumberOptionDetails extends Windows.Graphics.Printing.OptionDetails.IPrintOptionDetails { - maxValue: number; - minValue: number; - } - export interface IPrintTextOptionDetails extends Windows.Graphics.Printing.OptionDetails.IPrintOptionDetails { - maxCharacters: number; - } - export interface IPrintItemListOptionDetails extends Windows.Graphics.Printing.OptionDetails.IPrintOptionDetails { - items: Windows.Foundation.Collections.IVectorView; - } - export class PrintCopiesOptionDetails implements Windows.Graphics.Printing.OptionDetails.IPrintOptionDetails, Windows.Graphics.Printing.OptionDetails.IPrintNumberOptionDetails { - errorText: string; - optionId: string; - optionType: Windows.Graphics.Printing.OptionDetails.PrintOptionType; - state: Windows.Graphics.Printing.OptionDetails.PrintOptionStates; - value: any; - maxValue: number; - minValue: number; - trySetValue(value: any): boolean; - } - export class PrintMediaSizeOptionDetails implements Windows.Graphics.Printing.OptionDetails.IPrintOptionDetails, Windows.Graphics.Printing.OptionDetails.IPrintItemListOptionDetails { - errorText: string; - optionId: string; - optionType: Windows.Graphics.Printing.OptionDetails.PrintOptionType; - state: Windows.Graphics.Printing.OptionDetails.PrintOptionStates; - value: any; - items: Windows.Foundation.Collections.IVectorView; - trySetValue(value: any): boolean; - } - export class PrintMediaTypeOptionDetails implements Windows.Graphics.Printing.OptionDetails.IPrintOptionDetails, Windows.Graphics.Printing.OptionDetails.IPrintItemListOptionDetails { - errorText: string; - optionId: string; - optionType: Windows.Graphics.Printing.OptionDetails.PrintOptionType; - state: Windows.Graphics.Printing.OptionDetails.PrintOptionStates; - value: any; - items: Windows.Foundation.Collections.IVectorView; - trySetValue(value: any): boolean; - } - export class PrintOrientationOptionDetails implements Windows.Graphics.Printing.OptionDetails.IPrintOptionDetails, Windows.Graphics.Printing.OptionDetails.IPrintItemListOptionDetails { - errorText: string; - optionId: string; - optionType: Windows.Graphics.Printing.OptionDetails.PrintOptionType; - state: Windows.Graphics.Printing.OptionDetails.PrintOptionStates; - value: any; - items: Windows.Foundation.Collections.IVectorView; - trySetValue(value: any): boolean; - } - export class PrintQualityOptionDetails implements Windows.Graphics.Printing.OptionDetails.IPrintOptionDetails, Windows.Graphics.Printing.OptionDetails.IPrintItemListOptionDetails { - errorText: string; - optionId: string; - optionType: Windows.Graphics.Printing.OptionDetails.PrintOptionType; - state: Windows.Graphics.Printing.OptionDetails.PrintOptionStates; - value: any; - items: Windows.Foundation.Collections.IVectorView; - trySetValue(value: any): boolean; - } - export class PrintColorModeOptionDetails implements Windows.Graphics.Printing.OptionDetails.IPrintOptionDetails, Windows.Graphics.Printing.OptionDetails.IPrintItemListOptionDetails { - errorText: string; - optionId: string; - optionType: Windows.Graphics.Printing.OptionDetails.PrintOptionType; - state: Windows.Graphics.Printing.OptionDetails.PrintOptionStates; - value: any; - items: Windows.Foundation.Collections.IVectorView; - trySetValue(value: any): boolean; - } - export class PrintDuplexOptionDetails implements Windows.Graphics.Printing.OptionDetails.IPrintOptionDetails, Windows.Graphics.Printing.OptionDetails.IPrintItemListOptionDetails { - errorText: string; - optionId: string; - optionType: Windows.Graphics.Printing.OptionDetails.PrintOptionType; - state: Windows.Graphics.Printing.OptionDetails.PrintOptionStates; - value: any; - items: Windows.Foundation.Collections.IVectorView; - trySetValue(value: any): boolean; - } - export class PrintCollationOptionDetails implements Windows.Graphics.Printing.OptionDetails.IPrintOptionDetails, Windows.Graphics.Printing.OptionDetails.IPrintItemListOptionDetails { - errorText: string; - optionId: string; - optionType: Windows.Graphics.Printing.OptionDetails.PrintOptionType; - state: Windows.Graphics.Printing.OptionDetails.PrintOptionStates; - value: any; - items: Windows.Foundation.Collections.IVectorView; - trySetValue(value: any): boolean; - } - export class PrintStapleOptionDetails implements Windows.Graphics.Printing.OptionDetails.IPrintOptionDetails, Windows.Graphics.Printing.OptionDetails.IPrintItemListOptionDetails { - errorText: string; - optionId: string; - optionType: Windows.Graphics.Printing.OptionDetails.PrintOptionType; - state: Windows.Graphics.Printing.OptionDetails.PrintOptionStates; - value: any; - items: Windows.Foundation.Collections.IVectorView; - trySetValue(value: any): boolean; - } - export class PrintHolePunchOptionDetails implements Windows.Graphics.Printing.OptionDetails.IPrintOptionDetails, Windows.Graphics.Printing.OptionDetails.IPrintItemListOptionDetails { - errorText: string; - optionId: string; - optionType: Windows.Graphics.Printing.OptionDetails.PrintOptionType; - state: Windows.Graphics.Printing.OptionDetails.PrintOptionStates; - value: any; - items: Windows.Foundation.Collections.IVectorView; - trySetValue(value: any): boolean; - } - export class PrintBindingOptionDetails implements Windows.Graphics.Printing.OptionDetails.IPrintOptionDetails, Windows.Graphics.Printing.OptionDetails.IPrintItemListOptionDetails { - errorText: string; - optionId: string; - optionType: Windows.Graphics.Printing.OptionDetails.PrintOptionType; - state: Windows.Graphics.Printing.OptionDetails.PrintOptionStates; - value: any; - items: Windows.Foundation.Collections.IVectorView; - trySetValue(value: any): boolean; - } - export interface IPrintCustomOptionDetails extends Windows.Graphics.Printing.OptionDetails.IPrintOptionDetails { - displayName: string; - } - export interface IPrintCustomTextOptionDetails extends Windows.Graphics.Printing.OptionDetails.IPrintCustomOptionDetails, Windows.Graphics.Printing.OptionDetails.IPrintOptionDetails { - maxCharacters: number; - } - export class PrintCustomTextOptionDetails implements Windows.Graphics.Printing.OptionDetails.IPrintOptionDetails, Windows.Graphics.Printing.OptionDetails.IPrintCustomOptionDetails, Windows.Graphics.Printing.OptionDetails.IPrintCustomTextOptionDetails { - errorText: string; - optionId: string; - optionType: Windows.Graphics.Printing.OptionDetails.PrintOptionType; - state: Windows.Graphics.Printing.OptionDetails.PrintOptionStates; - value: any; - displayName: string; - maxCharacters: number; - trySetValue(value: any): boolean; - } - export interface IPrintCustomItemDetails { - itemDisplayName: string; - itemId: string; - } - export class PrintCustomItemDetails implements Windows.Graphics.Printing.OptionDetails.IPrintCustomItemDetails { - itemDisplayName: string; - itemId: string; - } - export interface IPrintCustomItemListOptionDetails extends Windows.Graphics.Printing.OptionDetails.IPrintItemListOptionDetails, Windows.Graphics.Printing.OptionDetails.IPrintOptionDetails, Windows.Graphics.Printing.OptionDetails.IPrintCustomOptionDetails { - addItem(itemId: string, displayName: string): void; - } - export class PrintCustomItemListOptionDetails implements Windows.Graphics.Printing.OptionDetails.IPrintOptionDetails, Windows.Graphics.Printing.OptionDetails.IPrintCustomOptionDetails, Windows.Graphics.Printing.OptionDetails.IPrintItemListOptionDetails, Windows.Graphics.Printing.OptionDetails.IPrintCustomItemListOptionDetails { - errorText: string; - optionId: string; - optionType: Windows.Graphics.Printing.OptionDetails.PrintOptionType; - state: Windows.Graphics.Printing.OptionDetails.PrintOptionStates; - value: any; - displayName: string; - items: Windows.Foundation.Collections.IVectorView; - trySetValue(value: any): boolean; - addItem(itemId: string, displayName: string): void; - } - export interface IPrintTaskOptionChangedEventArgs { - optionId: any; - } - export class PrintTaskOptionChangedEventArgs implements Windows.Graphics.Printing.OptionDetails.IPrintTaskOptionChangedEventArgs { - optionId: any; - } - export interface IPrintTaskOptionDetails { - options: Windows.Foundation.Collections.IMapView; - createItemListOption(optionId: string, displayName: string): Windows.Graphics.Printing.OptionDetails.PrintCustomItemListOptionDetails; - createTextOption(optionId: string, displayName: string): Windows.Graphics.Printing.OptionDetails.PrintCustomTextOptionDetails; - onoptionchanged: any/* TODO */; - onbeginvalidation: any/* TODO */; - } - export class PrintTaskOptionDetails implements Windows.Graphics.Printing.OptionDetails.IPrintTaskOptionDetails, Windows.Graphics.Printing.IPrintTaskOptionsCore, Windows.Graphics.Printing.IPrintTaskOptionsCoreUIConfiguration { - options: Windows.Foundation.Collections.IMapView; - displayedOptions: Windows.Foundation.Collections.IVector; - createItemListOption(optionId: string, displayName: string): Windows.Graphics.Printing.OptionDetails.PrintCustomItemListOptionDetails; - createTextOption(optionId: string, displayName: string): Windows.Graphics.Printing.OptionDetails.PrintCustomTextOptionDetails; - onoptionchanged: any/* TODO */; - onbeginvalidation: any/* TODO */; - getPageDescription(jobPageNumber: number): Windows.Graphics.Printing.PrintPageDescription; - static getFromPrintTaskOptions(printTaskOptions: Windows.Graphics.Printing.PrintTaskOptions): Windows.Graphics.Printing.OptionDetails.PrintTaskOptionDetails; - } - export interface IPrintTaskOptionDetailsStatic { - getFromPrintTaskOptions(printTaskOptions: Windows.Graphics.Printing.PrintTaskOptions): Windows.Graphics.Printing.OptionDetails.PrintTaskOptionDetails; - } - } - } - } -} -declare module Windows { - export module Graphics { - export module Printing { - export interface PrintPageDescription { - pageSize: Windows.Foundation.Size; - imageableRect: Windows.Foundation.Rect; - dpiX: number; - dpiY: number; - } - export enum PrintMediaSize { - default, - notAvailable, - printerCustom, - businessCard, - creditCard, - isoA0, - isoA1, - isoA10, - isoA2, - isoA3, - isoA3Extra, - isoA3Rotated, - isoA4, - isoA4Extra, - isoA4Rotated, - isoA5, - isoA5Extra, - isoA5Rotated, - isoA6, - isoA6Rotated, - isoA7, - isoA8, - isoA9, - isoB0, - isoB1, - isoB10, - isoB2, - isoB3, - isoB4, - isoB4Envelope, - isoB5Envelope, - isoB5Extra, - isoB7, - isoB8, - isoB9, - isoC0, - isoC1, - isoC10, - isoC2, - isoC3, - isoC3Envelope, - isoC4, - isoC4Envelope, - isoC5, - isoC5Envelope, - isoC6, - isoC6C5Envelope, - isoC6Envelope, - isoC7, - isoC8, - isoC9, - isoDLEnvelope, - isoDLEnvelopeRotated, - isoSRA3, - japan2LPhoto, - japanChou3Envelope, - japanChou3EnvelopeRotated, - japanChou4Envelope, - japanChou4EnvelopeRotated, - japanDoubleHagakiPostcard, - japanDoubleHagakiPostcardRotated, - japanHagakiPostcard, - japanHagakiPostcardRotated, - japanKaku2Envelope, - japanKaku2EnvelopeRotated, - japanKaku3Envelope, - japanKaku3EnvelopeRotated, - japanLPhoto, - japanQuadrupleHagakiPostcard, - japanYou1Envelope, - japanYou2Envelope, - japanYou3Envelope, - japanYou4Envelope, - japanYou4EnvelopeRotated, - japanYou6Envelope, - japanYou6EnvelopeRotated, - jisB0, - jisB1, - jisB10, - jisB2, - jisB3, - jisB4, - jisB4Rotated, - jisB5, - jisB5Rotated, - jisB6, - jisB6Rotated, - jisB7, - jisB8, - jisB9, - northAmerica10x11, - northAmerica10x12, - northAmerica10x14, - northAmerica11x17, - northAmerica14x17, - northAmerica4x6, - northAmerica4x8, - northAmerica5x7, - northAmerica8x10, - northAmerica9x11, - northAmericaArchitectureASheet, - northAmericaArchitectureBSheet, - northAmericaArchitectureCSheet, - northAmericaArchitectureDSheet, - northAmericaArchitectureESheet, - northAmericaCSheet, - northAmericaDSheet, - northAmericaESheet, - northAmericaExecutive, - northAmericaGermanLegalFanfold, - northAmericaGermanStandardFanfold, - northAmericaLegal, - northAmericaLegalExtra, - northAmericaLetter, - northAmericaLetterExtra, - northAmericaLetterPlus, - northAmericaLetterRotated, - northAmericaMonarchEnvelope, - northAmericaNote, - northAmericaNumber10Envelope, - northAmericaNumber10EnvelopeRotated, - northAmericaNumber11Envelope, - northAmericaNumber12Envelope, - northAmericaNumber14Envelope, - northAmericaNumber9Envelope, - northAmericaPersonalEnvelope, - northAmericaQuarto, - northAmericaStatement, - northAmericaSuperA, - northAmericaSuperB, - northAmericaTabloid, - northAmericaTabloidExtra, - otherMetricA3Plus, - otherMetricA4Plus, - otherMetricFolio, - otherMetricInviteEnvelope, - otherMetricItalianEnvelope, - prc10Envelope, - prc10EnvelopeRotated, - prc16K, - prc16KRotated, - prc1Envelope, - prc1EnvelopeRotated, - prc2Envelope, - prc2EnvelopeRotated, - prc32K, - prc32KBig, - prc32KRotated, - prc3Envelope, - prc3EnvelopeRotated, - prc4Envelope, - prc4EnvelopeRotated, - prc5Envelope, - prc5EnvelopeRotated, - prc6Envelope, - prc6EnvelopeRotated, - prc7Envelope, - prc7EnvelopeRotated, - prc8Envelope, - prc8EnvelopeRotated, - prc9Envelope, - prc9EnvelopeRotated, - roll04Inch, - roll06Inch, - roll08Inch, - roll12Inch, - roll15Inch, - roll18Inch, - roll22Inch, - roll24Inch, - roll30Inch, - roll36Inch, - roll54Inch, - } - export enum PrintMediaType { - default, - notAvailable, - printerCustom, - autoSelect, - archival, - backPrintFilm, - bond, - cardStock, - continuous, - envelopePlain, - envelopeWindow, - fabric, - highResolution, - label, - multiLayerForm, - multiPartForm, - photographic, - photographicFilm, - photographicGlossy, - photographicHighGloss, - photographicMatte, - photographicSatin, - photographicSemiGloss, - plain, - screen, - screenPaged, - stationery, - tabStockFull, - tabStockPreCut, - transparency, - tShirtTransfer, - none, - } - export enum PrintOrientation { - default, - notAvailable, - printerCustom, - portrait, - portraitFlipped, - landscape, - landscapeFlipped, - } - export enum PrintQuality { - default, - notAvailable, - printerCustom, - automatic, - draft, - fax, - high, - normal, - photographic, - text, - } - export enum PrintColorMode { - default, - notAvailable, - printerCustom, - color, - grayscale, - monochrome, - } - export enum PrintDuplex { - default, - notAvailable, - printerCustom, - oneSided, - twoSidedShortEdge, - twoSidedLongEdge, - } - export enum PrintCollation { - default, - notAvailable, - printerCustom, - collated, - uncollated, - } - export enum PrintStaple { - default, - notAvailable, - printerCustom, - none, - stapleTopLeft, - stapleTopRight, - stapleBottomLeft, - stapleBottomRight, - stapleDualLeft, - stapleDualRight, - stapleDualTop, - stapleDualBottom, - saddleStitch, - } - export enum PrintHolePunch { - default, - notAvailable, - printerCustom, - none, - leftEdge, - rightEdge, - topEdge, - bottomEdge, - } - export enum PrintBinding { - default, - notAvailable, - printerCustom, - none, - bale, - bindBottom, - bindLeft, - bindRight, - bindTop, - booklet, - edgeStitchBottom, - edgeStitchLeft, - edgeStitchRight, - edgeStitchTop, - fold, - jogOffset, - trim, - } - export interface IPrintTaskOptionsCoreProperties { - binding: Windows.Graphics.Printing.PrintBinding; - collation: Windows.Graphics.Printing.PrintCollation; - colorMode: Windows.Graphics.Printing.PrintColorMode; - duplex: Windows.Graphics.Printing.PrintDuplex; - holePunch: Windows.Graphics.Printing.PrintHolePunch; - maxCopies: number; - mediaSize: Windows.Graphics.Printing.PrintMediaSize; - mediaType: Windows.Graphics.Printing.PrintMediaType; - minCopies: number; - numberOfCopies: number; - orientation: Windows.Graphics.Printing.PrintOrientation; - printQuality: Windows.Graphics.Printing.PrintQuality; - staple: Windows.Graphics.Printing.PrintStaple; - } - export interface IPrintTaskOptionsCoreUIConfiguration { - displayedOptions: Windows.Foundation.Collections.IVector; - } - export interface IPrintTaskOptionsCore { - getPageDescription(jobPageNumber: number): Windows.Graphics.Printing.PrintPageDescription; - } - export class PrintTaskOptions implements Windows.Graphics.Printing.IPrintTaskOptionsCore, Windows.Graphics.Printing.IPrintTaskOptionsCoreProperties, Windows.Graphics.Printing.IPrintTaskOptionsCoreUIConfiguration { - binding: Windows.Graphics.Printing.PrintBinding; - collation: Windows.Graphics.Printing.PrintCollation; - colorMode: Windows.Graphics.Printing.PrintColorMode; - duplex: Windows.Graphics.Printing.PrintDuplex; - holePunch: Windows.Graphics.Printing.PrintHolePunch; - maxCopies: number; - mediaSize: Windows.Graphics.Printing.PrintMediaSize; - mediaType: Windows.Graphics.Printing.PrintMediaType; - minCopies: number; - numberOfCopies: number; - orientation: Windows.Graphics.Printing.PrintOrientation; - printQuality: Windows.Graphics.Printing.PrintQuality; - staple: Windows.Graphics.Printing.PrintStaple; - displayedOptions: Windows.Foundation.Collections.IVector; - getPageDescription(jobPageNumber: number): Windows.Graphics.Printing.PrintPageDescription; - } - export interface IStandardPrintTaskOptionsStatic { - binding: string; - collation: string; - colorMode: string; - copies: string; - duplex: string; - holePunch: string; - inputBin: string; - mediaSize: string; - mediaType: string; - nUp: string; - orientation: string; - printQuality: string; - staple: string; - } - export class StandardPrintTaskOptions { - static binding: string; - static collation: string; - static colorMode: string; - static copies: string; - static duplex: string; - static holePunch: string; - static inputBin: string; - static mediaSize: string; - static mediaType: string; - static nUp: string; - static orientation: string; - static printQuality: string; - static staple: string; - } - export interface IPrintDocumentSource { - } - export interface IPrintTaskProgressingEventArgs { - documentPageCount: number; - } - export class PrintTaskProgressingEventArgs implements Windows.Graphics.Printing.IPrintTaskProgressingEventArgs { - documentPageCount: number; - } - export enum PrintTaskCompletion { - abandoned, - canceled, - failed, - submitted, - } - export interface IPrintTaskCompletedEventArgs { - completion: Windows.Graphics.Printing.PrintTaskCompletion; - } - export class PrintTaskCompletedEventArgs implements Windows.Graphics.Printing.IPrintTaskCompletedEventArgs { - completion: Windows.Graphics.Printing.PrintTaskCompletion; - } - export interface IPrintTask { - options: Windows.Graphics.Printing.PrintTaskOptions; - properties: Windows.ApplicationModel.DataTransfer.DataPackagePropertySet; - source: Windows.Graphics.Printing.IPrintDocumentSource; - onpreviewing: any/* TODO */; - onsubmitting: any/* TODO */; - onprogressing: any/* TODO */; - oncompleted: any/* TODO */; - } - export class PrintTask implements Windows.Graphics.Printing.IPrintTask { - options: Windows.Graphics.Printing.PrintTaskOptions; - properties: Windows.ApplicationModel.DataTransfer.DataPackagePropertySet; - source: Windows.Graphics.Printing.IPrintDocumentSource; - onpreviewing: any/* TODO */; - onsubmitting: any/* TODO */; - onprogressing: any/* TODO */; - oncompleted: any/* TODO */; - } - export interface IPrintTaskSourceRequestedDeferral { - complete(): void; - } - export class PrintTaskSourceRequestedDeferral implements Windows.Graphics.Printing.IPrintTaskSourceRequestedDeferral { - complete(): void; - } - export interface IPrintTaskSourceRequestedArgs { - deadline: Date; - setSource(source: Windows.Graphics.Printing.IPrintDocumentSource): void; - getDeferral(): Windows.Graphics.Printing.PrintTaskSourceRequestedDeferral; - } - export class PrintTaskSourceRequestedArgs implements Windows.Graphics.Printing.IPrintTaskSourceRequestedArgs { - deadline: Date; - setSource(source: Windows.Graphics.Printing.IPrintDocumentSource): void; - getDeferral(): Windows.Graphics.Printing.PrintTaskSourceRequestedDeferral; - } - export interface PrintTaskSourceRequestedHandler { - (args: Windows.Graphics.Printing.PrintTaskSourceRequestedArgs): void; - } - export interface IPrintTaskRequestedDeferral { - complete(): void; - } - export class PrintTaskRequestedDeferral implements Windows.Graphics.Printing.IPrintTaskRequestedDeferral { - complete(): void; - } - export interface IPrintTaskRequest { - deadline: Date; - createPrintTask(title: string, handler: Windows.Graphics.Printing.PrintTaskSourceRequestedHandler): Windows.Graphics.Printing.PrintTask; - getDeferral(): Windows.Graphics.Printing.PrintTaskRequestedDeferral; - } - export class PrintTaskRequest implements Windows.Graphics.Printing.IPrintTaskRequest { - deadline: Date; - createPrintTask(title: string, handler: Windows.Graphics.Printing.PrintTaskSourceRequestedHandler): Windows.Graphics.Printing.PrintTask; - getDeferral(): Windows.Graphics.Printing.PrintTaskRequestedDeferral; - } - export interface IPrintTaskRequestedEventArgs { - request: Windows.Graphics.Printing.PrintTaskRequest; - } - export class PrintTaskRequestedEventArgs implements Windows.Graphics.Printing.IPrintTaskRequestedEventArgs { - request: Windows.Graphics.Printing.PrintTaskRequest; - } - export interface IPrintManagerStatic { - getForCurrentView(): Windows.Graphics.Printing.PrintManager; - showPrintUIAsync(): Windows.Foundation.IAsyncOperation; - } - export class PrintManager implements Windows.Graphics.Printing.IPrintManager { - onprinttaskrequested: any/* TODO */; - static getForCurrentView(): Windows.Graphics.Printing.PrintManager; - static showPrintUIAsync(): Windows.Foundation.IAsyncOperation; - } - export interface IPrintManager { - onprinttaskrequested: any/* TODO */; - } - } - } -} -declare module Windows { - export module Management { - export module Deployment { - export enum DeploymentProgressState { - queued, - processing, - } - export interface DeploymentProgress { - state: Windows.Management.Deployment.DeploymentProgressState; - percentage: number; - } - export enum DeploymentOptions { - none, - forceApplicationShutdown, - developmentMode, - } - export interface IDeploymentResult { - activityId: string; - errorText: string; - extendedErrorCode: number; - } - export class DeploymentResult implements Windows.Management.Deployment.IDeploymentResult { - activityId: string; - errorText: string; - extendedErrorCode: number; - } - export enum PackageInstallState { - notInstalled, - staged, - installed, - } - export interface IPackageUserInformation { - installState: Windows.Management.Deployment.PackageInstallState; - userSecurityId: string; - } - export class PackageUserInformation implements Windows.Management.Deployment.IPackageUserInformation { - installState: Windows.Management.Deployment.PackageInstallState; - userSecurityId: string; - } - export enum PackageState { - normal, - licenseInvalid, - modified, - tampered, - } - export interface IPackageManager { - addPackageAsync(packageUri: Windows.Foundation.Uri, dependencyPackageUris: Windows.Foundation.Collections.IIterable, deploymentOptions: Windows.Management.Deployment.DeploymentOptions): Windows.Foundation.IAsyncOperationWithProgress; - updatePackageAsync(packageUri: Windows.Foundation.Uri, dependencyPackageUris: Windows.Foundation.Collections.IIterable, deploymentOptions: Windows.Management.Deployment.DeploymentOptions): Windows.Foundation.IAsyncOperationWithProgress; - removePackageAsync(packageFullName: string): Windows.Foundation.IAsyncOperationWithProgress; - stagePackageAsync(packageUri: Windows.Foundation.Uri, dependencyPackageUris: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncOperationWithProgress; - registerPackageAsync(manifestUri: Windows.Foundation.Uri, dependencyPackageUris: Windows.Foundation.Collections.IIterable, deploymentOptions: Windows.Management.Deployment.DeploymentOptions): Windows.Foundation.IAsyncOperationWithProgress; - findPackages(): Windows.Foundation.Collections.IIterable; - findPackagesForUser(userSecurityId: string): Windows.Foundation.Collections.IIterable; - findPackages(packageName: string, packagePublisher: string): Windows.Foundation.Collections.IIterable; - findPackagesForUser(userSecurityId: string, packageName: string, packagePublisher: string): Windows.Foundation.Collections.IIterable; - findUsers(packageFullName: string): Windows.Foundation.Collections.IIterable; - setPackageState(packageFullName: string, packageState: Windows.Management.Deployment.PackageState): void; - findPackage(packageFullName: string): Windows.ApplicationModel.Package; - cleanupPackageForUserAsync(packageName: string, userSecurityId: string): Windows.Foundation.IAsyncOperationWithProgress; - findPackages(packageFamilyName: string): Windows.Foundation.Collections.IIterable; - findPackagesForUser(userSecurityId: string, packageFamilyName: string): Windows.Foundation.Collections.IIterable; - findPackageForUser(userSecurityId: string, packageFullName: string): Windows.ApplicationModel.Package; - } - export class PackageManager implements Windows.Management.Deployment.IPackageManager { - addPackageAsync(packageUri: Windows.Foundation.Uri, dependencyPackageUris: Windows.Foundation.Collections.IIterable, deploymentOptions: Windows.Management.Deployment.DeploymentOptions): Windows.Foundation.IAsyncOperationWithProgress; - updatePackageAsync(packageUri: Windows.Foundation.Uri, dependencyPackageUris: Windows.Foundation.Collections.IIterable, deploymentOptions: Windows.Management.Deployment.DeploymentOptions): Windows.Foundation.IAsyncOperationWithProgress; - removePackageAsync(packageFullName: string): Windows.Foundation.IAsyncOperationWithProgress; - stagePackageAsync(packageUri: Windows.Foundation.Uri, dependencyPackageUris: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncOperationWithProgress; - registerPackageAsync(manifestUri: Windows.Foundation.Uri, dependencyPackageUris: Windows.Foundation.Collections.IIterable, deploymentOptions: Windows.Management.Deployment.DeploymentOptions): Windows.Foundation.IAsyncOperationWithProgress; - findPackages(): Windows.Foundation.Collections.IIterable; - findPackagesForUser(userSecurityId: string): Windows.Foundation.Collections.IIterable; - findPackages(packageName: string, packagePublisher: string): Windows.Foundation.Collections.IIterable; - findPackagesForUser(userSecurityId: string, packageName: string, packagePublisher: string): Windows.Foundation.Collections.IIterable; - findUsers(packageFullName: string): Windows.Foundation.Collections.IIterable; - setPackageState(packageFullName: string, packageState: Windows.Management.Deployment.PackageState): void; - findPackage(packageFullName: string): Windows.ApplicationModel.Package; - cleanupPackageForUserAsync(packageName: string, userSecurityId: string): Windows.Foundation.IAsyncOperationWithProgress; - findPackages(packageFamilyName: string): Windows.Foundation.Collections.IIterable; - findPackagesForUser(userSecurityId: string, packageFamilyName: string): Windows.Foundation.Collections.IIterable; - findPackageForUser(userSecurityId: string, packageFullName: string): Windows.ApplicationModel.Package; - } - } - } -} -declare module Windows { - export module Management { - export module Core { - export interface IApplicationDataManagerStatics { - createForPackageFamily(packageFamilyName: string): Windows.Storage.ApplicationData; - } - export interface IApplicationDataManager { - } - export class ApplicationDataManager implements Windows.Management.Core.IApplicationDataManager { - static createForPackageFamily(packageFamilyName: string): Windows.Storage.ApplicationData; - } - } - } -} -declare module Windows { - export module Media { - export module Capture { - export enum CameraCaptureUIMode { - photoOrVideo, - photo, - video, - } - export enum CameraCaptureUIPhotoFormat { - jpeg, - png, - jpegXR, - } - export enum CameraCaptureUIVideoFormat { - mp4, - wmv, - } - export enum CameraCaptureUIMaxVideoResolution { - highestAvailable, - lowDefinition, - standardDefinition, - highDefinition, - } - export enum CameraCaptureUIMaxPhotoResolution { - highestAvailable, - verySmallQvga, - smallVga, - mediumXga, - large3M, - veryLarge5M, - } - export interface ICameraCaptureUIPhotoCaptureSettings { - allowCropping: boolean; - croppedAspectRatio: Windows.Foundation.Size; - croppedSizeInPixels: Windows.Foundation.Size; - format: Windows.Media.Capture.CameraCaptureUIPhotoFormat; - maxResolution: Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution; - } - export class CameraCaptureUIPhotoCaptureSettings implements Windows.Media.Capture.ICameraCaptureUIPhotoCaptureSettings { - allowCropping: boolean; - croppedAspectRatio: Windows.Foundation.Size; - croppedSizeInPixels: Windows.Foundation.Size; - format: Windows.Media.Capture.CameraCaptureUIPhotoFormat; - maxResolution: Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution; - } - export interface ICameraCaptureUIVideoCaptureSettings { - allowTrimming: boolean; - format: Windows.Media.Capture.CameraCaptureUIVideoFormat; - maxDurationInSeconds: number; - maxResolution: Windows.Media.Capture.CameraCaptureUIMaxVideoResolution; - } - export class CameraCaptureUIVideoCaptureSettings implements Windows.Media.Capture.ICameraCaptureUIVideoCaptureSettings { - allowTrimming: boolean; - format: Windows.Media.Capture.CameraCaptureUIVideoFormat; - maxDurationInSeconds: number; - maxResolution: Windows.Media.Capture.CameraCaptureUIMaxVideoResolution; - } - export interface ICameraCaptureUI { - photoSettings: Windows.Media.Capture.CameraCaptureUIPhotoCaptureSettings; - videoSettings: Windows.Media.Capture.CameraCaptureUIVideoCaptureSettings; - captureFileAsync(mode: Windows.Media.Capture.CameraCaptureUIMode): Windows.Foundation.IAsyncOperation; - } - export class CameraCaptureUI implements Windows.Media.Capture.ICameraCaptureUI { - photoSettings: Windows.Media.Capture.CameraCaptureUIPhotoCaptureSettings; - videoSettings: Windows.Media.Capture.CameraCaptureUIVideoCaptureSettings; - captureFileAsync(mode: Windows.Media.Capture.CameraCaptureUIMode): Windows.Foundation.IAsyncOperation; - } - export interface ICameraOptionsUIStatics { - show(mediaCapture: Windows.Media.Capture.MediaCapture): void; - } - export class CameraOptionsUI { - static show(mediaCapture: Windows.Media.Capture.MediaCapture): void; - } - export enum MediaStreamType { - videoPreview, - videoRecord, - audio, - photo, - } - export enum StreamingCaptureMode { - audioAndVideo, - audio, - video, - } - export enum VideoRotation { - none, - clockwise90Degrees, - clockwise180Degrees, - clockwise270Degrees, - } - export enum PhotoCaptureSource { - auto, - videoPreview, - photo, - } - export enum VideoDeviceCharacteristic { - allStreamsIndependent, - previewRecordStreamsIdentical, - previewPhotoStreamsIdentical, - recordPhotoStreamsIdentical, - allStreamsIdentical, - } - export enum PowerlineFrequency { - disabled, - fiftyHertz, - sixtyHertz, - } - export interface IMediaCaptureFailedEventArgs { - code: number; - message: string; - } - export class MediaCaptureFailedEventArgs implements Windows.Media.Capture.IMediaCaptureFailedEventArgs { - code: number; - message: string; - } - export interface MediaCaptureFailedEventHandler { - (sender: Windows.Media.Capture.MediaCapture, errorEventArgs: Windows.Media.Capture.MediaCaptureFailedEventArgs): void; - } - export class MediaCapture implements Windows.Media.Capture.IMediaCapture, Windows.Media.Capture.IMediaCaptureVideoPreview { - audioDeviceController: Windows.Media.Devices.AudioDeviceController; - mediaCaptureSettings: Windows.Media.Capture.MediaCaptureSettings; - videoDeviceController: Windows.Media.Devices.VideoDeviceController; - initializeAsync(): Windows.Foundation.IAsyncAction; - initializeAsync(mediaCaptureInitializationSettings: Windows.Media.Capture.MediaCaptureInitializationSettings): Windows.Foundation.IAsyncAction; - startRecordToStorageFileAsync(encodingProfile: Windows.Media.MediaProperties.MediaEncodingProfile, file: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncAction; - startRecordToStreamAsync(encodingProfile: Windows.Media.MediaProperties.MediaEncodingProfile, stream: Windows.Storage.Streams.IRandomAccessStream): Windows.Foundation.IAsyncAction; - startRecordToCustomSinkAsync(encodingProfile: Windows.Media.MediaProperties.MediaEncodingProfile, customMediaSink: Windows.Media.IMediaExtension): Windows.Foundation.IAsyncAction; - startRecordToCustomSinkAsync(encodingProfile: Windows.Media.MediaProperties.MediaEncodingProfile, customSinkActivationId: string, customSinkSettings: Windows.Foundation.Collections.IPropertySet): Windows.Foundation.IAsyncAction; - stopRecordAsync(): Windows.Foundation.IAsyncAction; - capturePhotoToStorageFileAsync(type: Windows.Media.MediaProperties.ImageEncodingProperties, file: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncAction; - capturePhotoToStreamAsync(type: Windows.Media.MediaProperties.ImageEncodingProperties, stream: Windows.Storage.Streams.IRandomAccessStream): Windows.Foundation.IAsyncAction; - addEffectAsync(mediaStreamType: Windows.Media.Capture.MediaStreamType, effectActivationID: string, effectSettings: Windows.Foundation.Collections.IPropertySet): Windows.Foundation.IAsyncAction; - clearEffectsAsync(mediaStreamType: Windows.Media.Capture.MediaStreamType): Windows.Foundation.IAsyncAction; - setEncoderProperty(mediaStreamType: Windows.Media.Capture.MediaStreamType, propertyId: string, propertyValue: any): void; - getEncoderProperty(mediaStreamType: Windows.Media.Capture.MediaStreamType, propertyId: string): any; - onfailed: any/* TODO */; - onrecordlimitationexceeded: any/* TODO */; - setPreviewMirroring(value: boolean): void; - getPreviewMirroring(): boolean; - setPreviewRotation(value: Windows.Media.Capture.VideoRotation): void; - getPreviewRotation(): Windows.Media.Capture.VideoRotation; - setRecordRotation(value: Windows.Media.Capture.VideoRotation): void; - getRecordRotation(): Windows.Media.Capture.VideoRotation; - startPreviewAsync(): Windows.Foundation.IAsyncAction; - startPreviewToCustomSinkAsync(encodingProfile: Windows.Media.MediaProperties.MediaEncodingProfile, customMediaSink: Windows.Media.IMediaExtension): Windows.Foundation.IAsyncAction; - startPreviewToCustomSinkAsync(encodingProfile: Windows.Media.MediaProperties.MediaEncodingProfile, customSinkActivationId: string, customSinkSettings: Windows.Foundation.Collections.IPropertySet): Windows.Foundation.IAsyncAction; - stopPreviewAsync(): Windows.Foundation.IAsyncAction; - } - export interface RecordLimitationExceededEventHandler { - (sender: Windows.Media.Capture.MediaCapture): void; - } - export interface IMediaCaptureInitializationSettings { - audioDeviceId: string; - photoCaptureSource: Windows.Media.Capture.PhotoCaptureSource; - streamingCaptureMode: Windows.Media.Capture.StreamingCaptureMode; - videoDeviceId: string; - } - export class MediaCaptureInitializationSettings implements Windows.Media.Capture.IMediaCaptureInitializationSettings { - audioDeviceId: string; - photoCaptureSource: Windows.Media.Capture.PhotoCaptureSource; - streamingCaptureMode: Windows.Media.Capture.StreamingCaptureMode; - videoDeviceId: string; - } - export interface IMediaCapture { - audioDeviceController: Windows.Media.Devices.AudioDeviceController; - mediaCaptureSettings: Windows.Media.Capture.MediaCaptureSettings; - videoDeviceController: Windows.Media.Devices.VideoDeviceController; - initializeAsync(): Windows.Foundation.IAsyncAction; - initializeAsync(mediaCaptureInitializationSettings: Windows.Media.Capture.MediaCaptureInitializationSettings): Windows.Foundation.IAsyncAction; - startRecordToStorageFileAsync(encodingProfile: Windows.Media.MediaProperties.MediaEncodingProfile, file: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncAction; - startRecordToStreamAsync(encodingProfile: Windows.Media.MediaProperties.MediaEncodingProfile, stream: Windows.Storage.Streams.IRandomAccessStream): Windows.Foundation.IAsyncAction; - startRecordToCustomSinkAsync(encodingProfile: Windows.Media.MediaProperties.MediaEncodingProfile, customMediaSink: Windows.Media.IMediaExtension): Windows.Foundation.IAsyncAction; - startRecordToCustomSinkAsync(encodingProfile: Windows.Media.MediaProperties.MediaEncodingProfile, customSinkActivationId: string, customSinkSettings: Windows.Foundation.Collections.IPropertySet): Windows.Foundation.IAsyncAction; - stopRecordAsync(): Windows.Foundation.IAsyncAction; - capturePhotoToStorageFileAsync(type: Windows.Media.MediaProperties.ImageEncodingProperties, file: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncAction; - capturePhotoToStreamAsync(type: Windows.Media.MediaProperties.ImageEncodingProperties, stream: Windows.Storage.Streams.IRandomAccessStream): Windows.Foundation.IAsyncAction; - addEffectAsync(mediaStreamType: Windows.Media.Capture.MediaStreamType, effectActivationID: string, effectSettings: Windows.Foundation.Collections.IPropertySet): Windows.Foundation.IAsyncAction; - clearEffectsAsync(mediaStreamType: Windows.Media.Capture.MediaStreamType): Windows.Foundation.IAsyncAction; - setEncoderProperty(mediaStreamType: Windows.Media.Capture.MediaStreamType, propertyId: string, propertyValue: any): void; - getEncoderProperty(mediaStreamType: Windows.Media.Capture.MediaStreamType, propertyId: string): any; - onfailed: any/* TODO */; - onrecordlimitationexceeded: any/* TODO */; - setPreviewMirroring(value: boolean): void; - getPreviewMirroring(): boolean; - setPreviewRotation(value: Windows.Media.Capture.VideoRotation): void; - getPreviewRotation(): Windows.Media.Capture.VideoRotation; - setRecordRotation(value: Windows.Media.Capture.VideoRotation): void; - getRecordRotation(): Windows.Media.Capture.VideoRotation; - } - export class MediaCaptureSettings implements Windows.Media.Capture.IMediaCaptureSettings { - audioDeviceId: string; - photoCaptureSource: Windows.Media.Capture.PhotoCaptureSource; - streamingCaptureMode: Windows.Media.Capture.StreamingCaptureMode; - videoDeviceCharacteristic: Windows.Media.Capture.VideoDeviceCharacteristic; - videoDeviceId: string; - } - export interface IMediaCaptureVideoPreview { - startPreviewAsync(): Windows.Foundation.IAsyncAction; - startPreviewToCustomSinkAsync(encodingProfile: Windows.Media.MediaProperties.MediaEncodingProfile, customMediaSink: Windows.Media.IMediaExtension): Windows.Foundation.IAsyncAction; - startPreviewToCustomSinkAsync(encodingProfile: Windows.Media.MediaProperties.MediaEncodingProfile, customSinkActivationId: string, customSinkSettings: Windows.Foundation.Collections.IPropertySet): Windows.Foundation.IAsyncAction; - stopPreviewAsync(): Windows.Foundation.IAsyncAction; - } - export interface IMediaCaptureSettings { - audioDeviceId: string; - photoCaptureSource: Windows.Media.Capture.PhotoCaptureSource; - streamingCaptureMode: Windows.Media.Capture.StreamingCaptureMode; - videoDeviceCharacteristic: Windows.Media.Capture.VideoDeviceCharacteristic; - videoDeviceId: string; - } - } - } -} -declare module Windows { - export module Media { - export module Devices { - export enum TelephonyKey { - d0, - d1, - d2, - d3, - d4, - d5, - d6, - d7, - d8, - d9, - star, - pound, - a, - b, - c, - d, - } - export interface IDialRequestedEventArgs { - contact: any; - handled(): void; - } - export class DialRequestedEventArgs implements Windows.Media.Devices.IDialRequestedEventArgs { - contact: any; - handled(): void; - } - export interface IRedialRequestedEventArgs { - handled(): void; - } - export class RedialRequestedEventArgs implements Windows.Media.Devices.IRedialRequestedEventArgs { - handled(): void; - } - export interface IKeypadPressedEventArgs { - telephonyKey: Windows.Media.Devices.TelephonyKey; - } - export class KeypadPressedEventArgs implements Windows.Media.Devices.IKeypadPressedEventArgs { - telephonyKey: Windows.Media.Devices.TelephonyKey; - } - export interface CallControlEventHandler { - (sender: Windows.Media.Devices.CallControl): void; - } - export class CallControl implements Windows.Media.Devices.ICallControl { - hasRinger: boolean; - indicateNewIncomingCall(enableRinger: boolean, callerId: string): number; - indicateNewOutgoingCall(): number; - indicateActiveCall(callToken: number): void; - endCall(callToken: number): void; - onanswerrequested: any/* TODO */; - onhanguprequested: any/* TODO */; - ondialrequested: any/* TODO */; - onredialrequested: any/* TODO */; - onkeypadpressed: any/* TODO */; - onaudiotransferrequested: any/* TODO */; - static getDefault(): Windows.Media.Devices.CallControl; - static fromId(deviceInterfaceId: string): Windows.Media.Devices.CallControl; - } - export interface DialRequestedEventHandler { - (sender: Windows.Media.Devices.CallControl, e: Windows.Media.Devices.DialRequestedEventArgs): void; - } - export interface RedialRequestedEventHandler { - (sender: Windows.Media.Devices.CallControl, e: Windows.Media.Devices.RedialRequestedEventArgs): void; - } - export interface KeypadPressedEventHandler { - (sender: Windows.Media.Devices.CallControl, e: Windows.Media.Devices.KeypadPressedEventArgs): void; - } - export interface ICallControl { - hasRinger: boolean; - indicateNewIncomingCall(enableRinger: boolean, callerId: string): number; - indicateNewOutgoingCall(): number; - indicateActiveCall(callToken: number): void; - endCall(callToken: number): void; - onanswerrequested: any/* TODO */; - onhanguprequested: any/* TODO */; - ondialrequested: any/* TODO */; - onredialrequested: any/* TODO */; - onkeypadpressed: any/* TODO */; - onaudiotransferrequested: any/* TODO */; - } - export interface ICallControlStatics { - getDefault(): Windows.Media.Devices.CallControl; - fromId(deviceInterfaceId: string): Windows.Media.Devices.CallControl; - } - export enum AudioDeviceRole { - default, - communications, - } - export interface IDefaultAudioDeviceChangedEventArgs { - id: string; - role: Windows.Media.Devices.AudioDeviceRole; - } - export interface IMediaDeviceStatics { - getAudioCaptureSelector(): string; - getAudioRenderSelector(): string; - getVideoCaptureSelector(): string; - getDefaultAudioCaptureId(role: Windows.Media.Devices.AudioDeviceRole): string; - getDefaultAudioRenderId(role: Windows.Media.Devices.AudioDeviceRole): string; - ondefaultaudiocapturedevicechanged: any/* TODO */; - ondefaultaudiorenderdevicechanged: any/* TODO */; - } - export class DefaultAudioCaptureDeviceChangedEventArgs implements Windows.Media.Devices.IDefaultAudioDeviceChangedEventArgs { - id: string; - role: Windows.Media.Devices.AudioDeviceRole; - } - export class DefaultAudioRenderDeviceChangedEventArgs implements Windows.Media.Devices.IDefaultAudioDeviceChangedEventArgs { - id: string; - role: Windows.Media.Devices.AudioDeviceRole; - } - export class MediaDevice { - static getAudioCaptureSelector(): string; - static getAudioRenderSelector(): string; - static getVideoCaptureSelector(): string; - static getDefaultAudioCaptureId(role: Windows.Media.Devices.AudioDeviceRole): string; - static getDefaultAudioRenderId(role: Windows.Media.Devices.AudioDeviceRole): string; - static ondefaultaudiocapturedevicechanged: any/* TODO */; - static ondefaultaudiorenderdevicechanged: any/* TODO */; - } - export class AudioDeviceController implements Windows.Media.Devices.IAudioDeviceController, Windows.Media.Devices.IMediaDeviceController { - muted: boolean; - volumePercent: number; - getAvailableMediaStreamProperties(mediaStreamType: Windows.Media.Capture.MediaStreamType): Windows.Foundation.Collections.IVectorView; - getMediaStreamProperties(mediaStreamType: Windows.Media.Capture.MediaStreamType): Windows.Media.MediaProperties.IMediaEncodingProperties; - setMediaStreamPropertiesAsync(mediaStreamType: Windows.Media.Capture.MediaStreamType, mediaEncodingProperties: Windows.Media.MediaProperties.IMediaEncodingProperties): Windows.Foundation.IAsyncAction; - } - export class VideoDeviceController implements Windows.Media.Devices.IVideoDeviceController, Windows.Media.Devices.IMediaDeviceController, Windows.Media.Devices.IAdvancedVideoCaptureDeviceController { - backlightCompensation: Windows.Media.Devices.MediaDeviceControl; - brightness: Windows.Media.Devices.MediaDeviceControl; - contrast: Windows.Media.Devices.MediaDeviceControl; - exposure: Windows.Media.Devices.MediaDeviceControl; - focus: Windows.Media.Devices.MediaDeviceControl; - hue: Windows.Media.Devices.MediaDeviceControl; - pan: Windows.Media.Devices.MediaDeviceControl; - roll: Windows.Media.Devices.MediaDeviceControl; - tilt: Windows.Media.Devices.MediaDeviceControl; - whiteBalance: Windows.Media.Devices.MediaDeviceControl; - zoom: Windows.Media.Devices.MediaDeviceControl; - trySetPowerlineFrequency(value: Windows.Media.Capture.PowerlineFrequency): boolean; - tryGetPowerlineFrequency(): { value: Windows.Media.Capture.PowerlineFrequency; succeeded: boolean; }; - getAvailableMediaStreamProperties(mediaStreamType: Windows.Media.Capture.MediaStreamType): Windows.Foundation.Collections.IVectorView; - getMediaStreamProperties(mediaStreamType: Windows.Media.Capture.MediaStreamType): Windows.Media.MediaProperties.IMediaEncodingProperties; - setMediaStreamPropertiesAsync(mediaStreamType: Windows.Media.Capture.MediaStreamType, mediaEncodingProperties: Windows.Media.MediaProperties.IMediaEncodingProperties): Windows.Foundation.IAsyncAction; - setDeviceProperty(propertyId: string, propertyValue: any): void; - getDeviceProperty(propertyId: string): any; - } - export interface IMediaDeviceController { - getAvailableMediaStreamProperties(mediaStreamType: Windows.Media.Capture.MediaStreamType): Windows.Foundation.Collections.IVectorView; - getMediaStreamProperties(mediaStreamType: Windows.Media.Capture.MediaStreamType): Windows.Media.MediaProperties.IMediaEncodingProperties; - setMediaStreamPropertiesAsync(mediaStreamType: Windows.Media.Capture.MediaStreamType, mediaEncodingProperties: Windows.Media.MediaProperties.IMediaEncodingProperties): Windows.Foundation.IAsyncAction; - } - export interface IAudioDeviceController extends Windows.Media.Devices.IMediaDeviceController { - muted: boolean; - volumePercent: number; - } - export interface IVideoDeviceController extends Windows.Media.Devices.IMediaDeviceController { - backlightCompensation: Windows.Media.Devices.MediaDeviceControl; - brightness: Windows.Media.Devices.MediaDeviceControl; - contrast: Windows.Media.Devices.MediaDeviceControl; - exposure: Windows.Media.Devices.MediaDeviceControl; - focus: Windows.Media.Devices.MediaDeviceControl; - hue: Windows.Media.Devices.MediaDeviceControl; - pan: Windows.Media.Devices.MediaDeviceControl; - roll: Windows.Media.Devices.MediaDeviceControl; - tilt: Windows.Media.Devices.MediaDeviceControl; - whiteBalance: Windows.Media.Devices.MediaDeviceControl; - zoom: Windows.Media.Devices.MediaDeviceControl; - trySetPowerlineFrequency(value: Windows.Media.Capture.PowerlineFrequency): boolean; - tryGetPowerlineFrequency(): { value: Windows.Media.Capture.PowerlineFrequency; succeeded: boolean; }; - } - export class MediaDeviceControl implements Windows.Media.Devices.IMediaDeviceControl { - capabilities: Windows.Media.Devices.MediaDeviceControlCapabilities; - tryGetValue(): { value: number; succeeded: boolean; }; - trySetValue(value: number): boolean; - tryGetAuto(): { value: boolean; succeeded: boolean; }; - trySetAuto(value: boolean): boolean; - } - export interface IMediaDeviceControl { - capabilities: Windows.Media.Devices.MediaDeviceControlCapabilities; - tryGetValue(): { value: number; succeeded: boolean; }; - trySetValue(value: number): boolean; - tryGetAuto(): { value: boolean; succeeded: boolean; }; - trySetAuto(value: boolean): boolean; - } - export class MediaDeviceControlCapabilities implements Windows.Media.Devices.IMediaDeviceControlCapabilities { - autoModeSupported: boolean; - default: number; - max: number; - min: number; - step: number; - supported: boolean; - } - export interface IMediaDeviceControlCapabilities { - autoModeSupported: boolean; - default: number; - max: number; - min: number; - step: number; - supported: boolean; - } - export interface IAdvancedVideoCaptureDeviceController { - setDeviceProperty(propertyId: string, propertyValue: any): void; - getDeviceProperty(propertyId: string): any; - } - } - } -} -declare module Windows { - export module Media { - export enum SoundLevel { - muted, - low, - full, - } - export interface IMediaControl { - albumArt: Windows.Foundation.Uri; - artistName: string; - isPlaying: boolean; - soundLevel: Windows.Media.SoundLevel; - trackName: string; - onsoundlevelchanged: any/* TODO */; - onplaypressed: any/* TODO */; - onpausepressed: any/* TODO */; - onstoppressed: any/* TODO */; - onplaypausetogglepressed: any/* TODO */; - onrecordpressed: any/* TODO */; - onnexttrackpressed: any/* TODO */; - onprevioustrackpressed: any/* TODO */; - onfastforwardpressed: any/* TODO */; - onrewindpressed: any/* TODO */; - onchanneluppressed: any/* TODO */; - onchanneldownpressed: any/* TODO */; - } - export class MediaControl { - static albumArt: Windows.Foundation.Uri; - static artistName: string; - static isPlaying: boolean; - static soundLevel: Windows.Media.SoundLevel; - static trackName: string; - static onsoundlevelchanged: any/* TODO */; - static onplaypressed: any/* TODO */; - static onpausepressed: any/* TODO */; - static onstoppressed: any/* TODO */; - static onplaypausetogglepressed: any/* TODO */; - static onrecordpressed: any/* TODO */; - static onnexttrackpressed: any/* TODO */; - static onprevioustrackpressed: any/* TODO */; - static onfastforwardpressed: any/* TODO */; - static onrewindpressed: any/* TODO */; - static onchanneluppressed: any/* TODO */; - static onchanneldownpressed: any/* TODO */; - } - export interface IMediaExtension { - setProperties(configuration: Windows.Foundation.Collections.IPropertySet): void; - } - export interface IMediaExtensionManager { - registerSchemeHandler(activatableClassId: string, scheme: string): void; - registerSchemeHandler(activatableClassId: string, scheme: string, configuration: Windows.Foundation.Collections.IPropertySet): void; - registerByteStreamHandler(activatableClassId: string, fileExtension: string, mimeType: string): void; - registerByteStreamHandler(activatableClassId: string, fileExtension: string, mimeType: string, configuration: Windows.Foundation.Collections.IPropertySet): void; - registerAudioDecoder(activatableClassId: string, inputSubtype: string, outputSubtype: string): void; - registerAudioDecoder(activatableClassId: string, inputSubtype: string, outputSubtype: string, configuration: Windows.Foundation.Collections.IPropertySet): void; - registerAudioEncoder(activatableClassId: string, inputSubtype: string, outputSubtype: string): void; - registerAudioEncoder(activatableClassId: string, inputSubtype: string, outputSubtype: string, configuration: Windows.Foundation.Collections.IPropertySet): void; - registerVideoDecoder(activatableClassId: string, inputSubtype: string, outputSubtype: string): void; - registerVideoDecoder(activatableClassId: string, inputSubtype: string, outputSubtype: string, configuration: Windows.Foundation.Collections.IPropertySet): void; - registerVideoEncoder(activatableClassId: string, inputSubtype: string, outputSubtype: string): void; - registerVideoEncoder(activatableClassId: string, inputSubtype: string, outputSubtype: string, configuration: Windows.Foundation.Collections.IPropertySet): void; - } - export class MediaExtensionManager implements Windows.Media.IMediaExtensionManager { - registerSchemeHandler(activatableClassId: string, scheme: string): void; - registerSchemeHandler(activatableClassId: string, scheme: string, configuration: Windows.Foundation.Collections.IPropertySet): void; - registerByteStreamHandler(activatableClassId: string, fileExtension: string, mimeType: string): void; - registerByteStreamHandler(activatableClassId: string, fileExtension: string, mimeType: string, configuration: Windows.Foundation.Collections.IPropertySet): void; - registerAudioDecoder(activatableClassId: string, inputSubtype: string, outputSubtype: string): void; - registerAudioDecoder(activatableClassId: string, inputSubtype: string, outputSubtype: string, configuration: Windows.Foundation.Collections.IPropertySet): void; - registerAudioEncoder(activatableClassId: string, inputSubtype: string, outputSubtype: string): void; - registerAudioEncoder(activatableClassId: string, inputSubtype: string, outputSubtype: string, configuration: Windows.Foundation.Collections.IPropertySet): void; - registerVideoDecoder(activatableClassId: string, inputSubtype: string, outputSubtype: string): void; - registerVideoDecoder(activatableClassId: string, inputSubtype: string, outputSubtype: string, configuration: Windows.Foundation.Collections.IPropertySet): void; - registerVideoEncoder(activatableClassId: string, inputSubtype: string, outputSubtype: string): void; - registerVideoEncoder(activatableClassId: string, inputSubtype: string, outputSubtype: string, configuration: Windows.Foundation.Collections.IPropertySet): void; - } - export interface IVideoEffectsStatics { - videoStabilization: string; - } - export class VideoEffects { - static videoStabilization: string; - } - } -} -declare module Windows { - export module Media { - export module Playlists { - export enum PlaylistFormat { - windowsMedia, - zune, - m3u, - } - export interface IPlaylist { - files: Windows.Foundation.Collections.IVector; - saveAsync(): Windows.Foundation.IAsyncAction; - saveAsAsync(saveLocation: Windows.Storage.IStorageFolder, desiredName: string, option: Windows.Storage.NameCollisionOption): Windows.Foundation.IAsyncOperation; - saveAsAsync(saveLocation: Windows.Storage.IStorageFolder, desiredName: string, option: Windows.Storage.NameCollisionOption, playlistFormat: Windows.Media.Playlists.PlaylistFormat): Windows.Foundation.IAsyncOperation; - } - export interface IPlaylistStatics { - loadAsync(file: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncOperation; - } - export class Playlist implements Windows.Media.Playlists.IPlaylist { - files: Windows.Foundation.Collections.IVector; - saveAsync(): Windows.Foundation.IAsyncAction; - saveAsAsync(saveLocation: Windows.Storage.IStorageFolder, desiredName: string, option: Windows.Storage.NameCollisionOption): Windows.Foundation.IAsyncOperation; - saveAsAsync(saveLocation: Windows.Storage.IStorageFolder, desiredName: string, option: Windows.Storage.NameCollisionOption, playlistFormat: Windows.Media.Playlists.PlaylistFormat): Windows.Foundation.IAsyncOperation; - static loadAsync(file: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncOperation; - } - } - } -} -declare module Windows { - export module Media { - export module PlayTo { - export interface IPlayToSource { - connection: Windows.Media.PlayTo.PlayToConnection; - next: Windows.Media.PlayTo.PlayToSource; - playNext(): void; - } - export class PlayToConnection implements Windows.Media.PlayTo.IPlayToConnection { - state: Windows.Media.PlayTo.PlayToConnectionState; - onstatechanged: any/* TODO */; - ontransferred: any/* TODO */; - onerror: any/* TODO */; - } - export class PlayToSource implements Windows.Media.PlayTo.IPlayToSource { - connection: Windows.Media.PlayTo.PlayToConnection; - next: Windows.Media.PlayTo.PlayToSource; - playNext(): void; - } - export enum PlayToConnectionState { - disconnected, - connected, - rendering, - } - export interface IPlayToConnectionStateChangedEventArgs { - currentState: Windows.Media.PlayTo.PlayToConnectionState; - previousState: Windows.Media.PlayTo.PlayToConnectionState; - } - export class PlayToConnectionStateChangedEventArgs implements Windows.Media.PlayTo.IPlayToConnectionStateChangedEventArgs { - currentState: Windows.Media.PlayTo.PlayToConnectionState; - previousState: Windows.Media.PlayTo.PlayToConnectionState; - } - export interface IPlayToConnectionTransferredEventArgs { - currentSource: Windows.Media.PlayTo.PlayToSource; - previousSource: Windows.Media.PlayTo.PlayToSource; - } - export class PlayToConnectionTransferredEventArgs implements Windows.Media.PlayTo.IPlayToConnectionTransferredEventArgs { - currentSource: Windows.Media.PlayTo.PlayToSource; - previousSource: Windows.Media.PlayTo.PlayToSource; - } - export enum PlayToConnectionError { - none, - deviceNotResponding, - deviceError, - deviceLocked, - } - export interface IPlayToConnectionErrorEventArgs { - code: Windows.Media.PlayTo.PlayToConnectionError; - message: string; - } - export class PlayToConnectionErrorEventArgs implements Windows.Media.PlayTo.IPlayToConnectionErrorEventArgs { - code: Windows.Media.PlayTo.PlayToConnectionError; - message: string; - } - export interface IPlayToConnection { - state: Windows.Media.PlayTo.PlayToConnectionState; - onstatechanged: any/* TODO */; - ontransferred: any/* TODO */; - onerror: any/* TODO */; - } - export interface ISourceChangeRequestedEventArgs { - album: string; - author: string; - date: Date; - description: string; - genre: string; - properties: Windows.Foundation.Collections.IMapView; - rating: number; - stream: Windows.Storage.Streams.IRandomAccessStreamWithContentType; - thumbnail: Windows.Storage.Streams.IRandomAccessStreamReference; - title: string; - } - export class SourceChangeRequestedEventArgs implements Windows.Media.PlayTo.ISourceChangeRequestedEventArgs { - album: string; - author: string; - date: Date; - description: string; - genre: string; - properties: Windows.Foundation.Collections.IMapView; - rating: number; - stream: Windows.Storage.Streams.IRandomAccessStreamWithContentType; - thumbnail: Windows.Storage.Streams.IRandomAccessStreamReference; - title: string; - } - export interface IPlaybackRateChangeRequestedEventArgs { - rate: number; - } - export class PlaybackRateChangeRequestedEventArgs implements Windows.Media.PlayTo.IPlaybackRateChangeRequestedEventArgs { - rate: number; - } - export interface ICurrentTimeChangeRequestedEventArgs { - time: number; - } - export class CurrentTimeChangeRequestedEventArgs implements Windows.Media.PlayTo.ICurrentTimeChangeRequestedEventArgs { - time: number; - } - export interface IMuteChangeRequestedEventArgs { - mute: boolean; - } - export class MuteChangeRequestedEventArgs implements Windows.Media.PlayTo.IMuteChangeRequestedEventArgs { - mute: boolean; - } - export interface IVolumeChangeRequestedEventArgs { - volume: number; - } - export class VolumeChangeRequestedEventArgs implements Windows.Media.PlayTo.IVolumeChangeRequestedEventArgs { - volume: number; - } - export interface IPlayToReceiver { - friendlyName: string; - properties: Windows.Foundation.Collections.IPropertySet; - supportsAudio: boolean; - supportsImage: boolean; - supportsVideo: boolean; - onplayrequested: any/* TODO */; - onpauserequested: any/* TODO */; - onsourcechangerequested: any/* TODO */; - onplaybackratechangerequested: any/* TODO */; - oncurrenttimechangerequested: any/* TODO */; - onmutechangerequested: any/* TODO */; - onvolumechangerequested: any/* TODO */; - ontimeupdaterequested: any/* TODO */; - onstoprequested: any/* TODO */; - notifyVolumeChange(volume: number, mute: boolean): void; - notifyRateChange(rate: number): void; - notifyLoadedMetadata(): void; - notifyTimeUpdate(currentTime: number): void; - notifyDurationChange(duration: number): void; - notifySeeking(): void; - notifySeeked(): void; - notifyPaused(): void; - notifyPlaying(): void; - notifyEnded(): void; - notifyError(): void; - notifyStopped(): void; - startAsync(): Windows.Foundation.IAsyncAction; - stopAsync(): Windows.Foundation.IAsyncAction; - } - export class PlayToReceiver implements Windows.Media.PlayTo.IPlayToReceiver { - friendlyName: string; - properties: Windows.Foundation.Collections.IPropertySet; - supportsAudio: boolean; - supportsImage: boolean; - supportsVideo: boolean; - onplayrequested: any/* TODO */; - onpauserequested: any/* TODO */; - onsourcechangerequested: any/* TODO */; - onplaybackratechangerequested: any/* TODO */; - oncurrenttimechangerequested: any/* TODO */; - onmutechangerequested: any/* TODO */; - onvolumechangerequested: any/* TODO */; - ontimeupdaterequested: any/* TODO */; - onstoprequested: any/* TODO */; - notifyVolumeChange(volume: number, mute: boolean): void; - notifyRateChange(rate: number): void; - notifyLoadedMetadata(): void; - notifyTimeUpdate(currentTime: number): void; - notifyDurationChange(duration: number): void; - notifySeeking(): void; - notifySeeked(): void; - notifyPaused(): void; - notifyPlaying(): void; - notifyEnded(): void; - notifyError(): void; - notifyStopped(): void; - startAsync(): Windows.Foundation.IAsyncAction; - stopAsync(): Windows.Foundation.IAsyncAction; - } - export interface IPlayToSourceSelectedEventArgs { - friendlyName: string; - icon: Windows.Storage.Streams.IRandomAccessStreamWithContentType; - supportsAudio: boolean; - supportsImage: boolean; - supportsVideo: boolean; - } - export class PlayToSourceSelectedEventArgs implements Windows.Media.PlayTo.IPlayToSourceSelectedEventArgs { - friendlyName: string; - icon: Windows.Storage.Streams.IRandomAccessStreamWithContentType; - supportsAudio: boolean; - supportsImage: boolean; - supportsVideo: boolean; - } - export interface IPlayToSourceDeferral { - complete(): void; - } - export class PlayToSourceDeferral implements Windows.Media.PlayTo.IPlayToSourceDeferral { - complete(): void; - } - export interface IPlayToSourceRequest { - deadline: Date; - displayErrorString(errorString: string): void; - getDeferral(): Windows.Media.PlayTo.PlayToSourceDeferral; - setSource(value: Windows.Media.PlayTo.PlayToSource): void; - } - export class PlayToSourceRequest implements Windows.Media.PlayTo.IPlayToSourceRequest { - deadline: Date; - displayErrorString(errorString: string): void; - getDeferral(): Windows.Media.PlayTo.PlayToSourceDeferral; - setSource(value: Windows.Media.PlayTo.PlayToSource): void; - } - export interface IPlayToSourceRequestedEventArgs { - sourceRequest: Windows.Media.PlayTo.PlayToSourceRequest; - } - export class PlayToSourceRequestedEventArgs implements Windows.Media.PlayTo.IPlayToSourceRequestedEventArgs { - sourceRequest: Windows.Media.PlayTo.PlayToSourceRequest; - } - export interface IPlayToManager { - defaultSourceSelection: boolean; - onsourcerequested: any/* TODO */; - onsourceselected: any/* TODO */; - } - export class PlayToManager implements Windows.Media.PlayTo.IPlayToManager { - defaultSourceSelection: boolean; - onsourcerequested: any/* TODO */; - onsourceselected: any/* TODO */; - static getForCurrentView(): Windows.Media.PlayTo.PlayToManager; - static showPlayToUI(): void; - } - export interface IPlayToManagerStatics { - getForCurrentView(): Windows.Media.PlayTo.PlayToManager; - showPlayToUI(): void; - } - } - } -} -declare module Windows { - export module Media { - export module MediaProperties { - export interface IMediaRatio { - denominator: number; - numerator: number; - } - export class MediaRatio implements Windows.Media.MediaProperties.IMediaRatio { - denominator: number; - numerator: number; - } - export class MediaPropertySet implements Windows.Foundation.Collections.IMap, Windows.Foundation.Collections.IIterable> { - size: number; - lookup(key: string): any; - hasKey(key: string): boolean; - getView(): Windows.Foundation.Collections.IMapView; - insert(key: string, value: any): boolean; - remove(key: string): void; - clear(): void; - first(): Windows.Foundation.Collections.IIterator>; - } - export interface IMediaEncodingProperties { - properties: Windows.Media.MediaProperties.MediaPropertySet; - subtype: string; - type: string; - } - export interface IAudioEncodingProperties extends Windows.Media.MediaProperties.IMediaEncodingProperties { - bitrate: number; - bitsPerSample: number; - channelCount: number; - sampleRate: number; - } - export class AudioEncodingProperties implements Windows.Media.MediaProperties.IAudioEncodingProperties, Windows.Media.MediaProperties.IMediaEncodingProperties { - bitrate: number; - bitsPerSample: number; - channelCount: number; - sampleRate: number; - properties: Windows.Media.MediaProperties.MediaPropertySet; - subtype: string; - type: string; - } - export interface IVideoEncodingProperties extends Windows.Media.MediaProperties.IMediaEncodingProperties { - bitrate: number; - frameRate: Windows.Media.MediaProperties.MediaRatio; - height: number; - pixelAspectRatio: Windows.Media.MediaProperties.MediaRatio; - width: number; - } - export class VideoEncodingProperties implements Windows.Media.MediaProperties.IVideoEncodingProperties, Windows.Media.MediaProperties.IMediaEncodingProperties { - bitrate: number; - frameRate: Windows.Media.MediaProperties.MediaRatio; - height: number; - pixelAspectRatio: Windows.Media.MediaProperties.MediaRatio; - width: number; - properties: Windows.Media.MediaProperties.MediaPropertySet; - subtype: string; - type: string; - } - export interface IImageEncodingProperties extends Windows.Media.MediaProperties.IMediaEncodingProperties { - height: number; - width: number; - } - export interface IImageEncodingPropertiesStatics { - createJpeg(): Windows.Media.MediaProperties.ImageEncodingProperties; - createPng(): Windows.Media.MediaProperties.ImageEncodingProperties; - createJpegXR(): Windows.Media.MediaProperties.ImageEncodingProperties; - } - export class ImageEncodingProperties implements Windows.Media.MediaProperties.IImageEncodingProperties, Windows.Media.MediaProperties.IMediaEncodingProperties { - height: number; - width: number; - properties: Windows.Media.MediaProperties.MediaPropertySet; - subtype: string; - type: string; - static createJpeg(): Windows.Media.MediaProperties.ImageEncodingProperties; - static createPng(): Windows.Media.MediaProperties.ImageEncodingProperties; - static createJpegXR(): Windows.Media.MediaProperties.ImageEncodingProperties; - } - export interface IContainerEncodingProperties extends Windows.Media.MediaProperties.IMediaEncodingProperties { - } - export class ContainerEncodingProperties implements Windows.Media.MediaProperties.IContainerEncodingProperties, Windows.Media.MediaProperties.IMediaEncodingProperties { - properties: Windows.Media.MediaProperties.MediaPropertySet; - subtype: string; - type: string; - } - export enum AudioEncodingQuality { - auto, - high, - medium, - low, - } - export enum VideoEncodingQuality { - auto, - hD1080p, - hD720p, - wvga, - ntsc, - pal, - vga, - qvga, - } - export interface IMediaEncodingProfileStatics { - createM4a(quality: Windows.Media.MediaProperties.AudioEncodingQuality): Windows.Media.MediaProperties.MediaEncodingProfile; - createMp3(quality: Windows.Media.MediaProperties.AudioEncodingQuality): Windows.Media.MediaProperties.MediaEncodingProfile; - createWma(quality: Windows.Media.MediaProperties.AudioEncodingQuality): Windows.Media.MediaProperties.MediaEncodingProfile; - createMp4(quality: Windows.Media.MediaProperties.VideoEncodingQuality): Windows.Media.MediaProperties.MediaEncodingProfile; - createWmv(quality: Windows.Media.MediaProperties.VideoEncodingQuality): Windows.Media.MediaProperties.MediaEncodingProfile; - createFromFileAsync(file: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncOperation; - createFromStreamAsync(stream: Windows.Storage.Streams.IRandomAccessStream): Windows.Foundation.IAsyncOperation; - } - export class MediaEncodingProfile implements Windows.Media.MediaProperties.IMediaEncodingProfile { - audio: Windows.Media.MediaProperties.AudioEncodingProperties; - container: Windows.Media.MediaProperties.ContainerEncodingProperties; - video: Windows.Media.MediaProperties.VideoEncodingProperties; - static createM4a(quality: Windows.Media.MediaProperties.AudioEncodingQuality): Windows.Media.MediaProperties.MediaEncodingProfile; - static createMp3(quality: Windows.Media.MediaProperties.AudioEncodingQuality): Windows.Media.MediaProperties.MediaEncodingProfile; - static createWma(quality: Windows.Media.MediaProperties.AudioEncodingQuality): Windows.Media.MediaProperties.MediaEncodingProfile; - static createMp4(quality: Windows.Media.MediaProperties.VideoEncodingQuality): Windows.Media.MediaProperties.MediaEncodingProfile; - static createWmv(quality: Windows.Media.MediaProperties.VideoEncodingQuality): Windows.Media.MediaProperties.MediaEncodingProfile; - static createFromFileAsync(file: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncOperation; - static createFromStreamAsync(stream: Windows.Storage.Streams.IRandomAccessStream): Windows.Foundation.IAsyncOperation; - } - export interface IMediaEncodingProfile { - audio: Windows.Media.MediaProperties.AudioEncodingProperties; - container: Windows.Media.MediaProperties.ContainerEncodingProperties; - video: Windows.Media.MediaProperties.VideoEncodingProperties; - } - } - } -} -declare module Windows { - export module Media { - export module Protection { - export class MediaProtectionManager implements Windows.Media.Protection.IMediaProtectionManager { - properties: Windows.Foundation.Collections.IPropertySet; - onservicerequested: any/* TODO */; - onrebootneeded: any/* TODO */; - oncomponentloadfailed: any/* TODO */; - } - export class ServiceRequestedEventArgs implements Windows.Media.Protection.IServiceRequestedEventArgs { - completion: Windows.Media.Protection.MediaProtectionServiceCompletion; - request: Windows.Media.Protection.IMediaProtectionServiceRequest; - } - export class ComponentLoadFailedEventArgs implements Windows.Media.Protection.IComponentLoadFailedEventArgs { - completion: Windows.Media.Protection.MediaProtectionServiceCompletion; - information: Windows.Media.Protection.RevocationAndRenewalInformation; - } - export class MediaProtectionServiceCompletion implements Windows.Media.Protection.IMediaProtectionServiceCompletion { - complete(success: boolean): void; - } - export class RevocationAndRenewalInformation implements Windows.Media.Protection.IRevocationAndRenewalInformation { - items: Windows.Foundation.Collections.IVector; - } - export class RevocationAndRenewalItem implements Windows.Media.Protection.IRevocationAndRenewalItem { - headerHash: string; - name: string; - publicKeyHash: string; - reasons: Windows.Media.Protection.RevocationAndRenewalReasons; - renewalId: string; - } - export interface ServiceRequestedEventHandler { - (sender: Windows.Media.Protection.MediaProtectionManager, e: Windows.Media.Protection.ServiceRequestedEventArgs): void; - } - export interface RebootNeededEventHandler { - (sender: Windows.Media.Protection.MediaProtectionManager): void; - } - export interface ComponentLoadFailedEventHandler { - (sender: Windows.Media.Protection.MediaProtectionManager, e: Windows.Media.Protection.ComponentLoadFailedEventArgs): void; - } - export interface IMediaProtectionManager { - properties: Windows.Foundation.Collections.IPropertySet; - onservicerequested: any/* TODO */; - onrebootneeded: any/* TODO */; - oncomponentloadfailed: any/* TODO */; - } - export interface IMediaProtectionServiceCompletion { - complete(success: boolean): void; - } - export interface IServiceRequestedEventArgs { - completion: Windows.Media.Protection.MediaProtectionServiceCompletion; - request: Windows.Media.Protection.IMediaProtectionServiceRequest; - } - export interface IMediaProtectionServiceRequest { - protectionSystem: string; - type: string; - } - export interface IComponentLoadFailedEventArgs { - completion: Windows.Media.Protection.MediaProtectionServiceCompletion; - information: Windows.Media.Protection.RevocationAndRenewalInformation; - } - export interface IRevocationAndRenewalInformation { - items: Windows.Foundation.Collections.IVector; - } - export enum RevocationAndRenewalReasons { - userModeComponentLoad, - kernelModeComponentLoad, - appComponent, - globalRevocationListLoadFailed, - invalidGlobalRevocationListSignature, - globalRevocationListAbsent, - componentRevoked, - invalidComponentCertificateExtendedKeyUse, - componentCertificateRevoked, - invalidComponentCertificateRoot, - componentHighSecurityCertificateRevoked, - componentLowSecurityCertificateRevoked, - bootDriverVerificationFailed, - componentSignedWithTestCertificate, - encryptionFailure, - } - export interface IRevocationAndRenewalItem { - headerHash: string; - name: string; - publicKeyHash: string; - reasons: Windows.Media.Protection.RevocationAndRenewalReasons; - renewalId: string; - } - export class ComponentRenewal { - static renewSystemComponentsAsync(information: Windows.Media.Protection.RevocationAndRenewalInformation): Windows.Foundation.IAsyncOperationWithProgress; - } - export enum RenewalStatus { - notStarted, - updatesInProgress, - userCancelled, - appComponentsMayNeedUpdating, - noComponentsFound, - } - export interface IComponentRenewalStatics { - renewSystemComponentsAsync(information: Windows.Media.Protection.RevocationAndRenewalInformation): Windows.Foundation.IAsyncOperationWithProgress; - } - } - } -} -declare module Windows { - export module Media { - export module Transcoding { - export enum TranscodeFailureReason { - none, - unknown, - invalidProfile, - codecNotFound, - } - export interface IMediaTranscoder { - alwaysReencode: boolean; - hardwareAccelerationEnabled: boolean; - trimStartTime: number; - trimStopTime: number; - addAudioEffect(activatableClassId: string): void; - addAudioEffect(activatableClassId: string, effectRequired: boolean, configuration: Windows.Foundation.Collections.IPropertySet): void; - addVideoEffect(activatableClassId: string): void; - addVideoEffect(activatableClassId: string, effectRequired: boolean, configuration: Windows.Foundation.Collections.IPropertySet): void; - clearEffects(): void; - prepareFileTranscodeAsync(source: Windows.Storage.IStorageFile, destination: Windows.Storage.IStorageFile, profile: Windows.Media.MediaProperties.MediaEncodingProfile): Windows.Foundation.IAsyncOperation; - prepareStreamTranscodeAsync(source: Windows.Storage.Streams.IRandomAccessStream, destination: Windows.Storage.Streams.IRandomAccessStream, profile: Windows.Media.MediaProperties.MediaEncodingProfile): Windows.Foundation.IAsyncOperation; - } - export class PrepareTranscodeResult implements Windows.Media.Transcoding.IPrepareTranscodeResult { - canTranscode: boolean; - failureReason: Windows.Media.Transcoding.TranscodeFailureReason; - transcodeAsync(): Windows.Foundation.IAsyncActionWithProgress; - } - export interface IPrepareTranscodeResult { - canTranscode: boolean; - failureReason: Windows.Media.Transcoding.TranscodeFailureReason; - transcodeAsync(): Windows.Foundation.IAsyncActionWithProgress; - } - export class MediaTranscoder implements Windows.Media.Transcoding.IMediaTranscoder { - alwaysReencode: boolean; - hardwareAccelerationEnabled: boolean; - trimStartTime: number; - trimStopTime: number; - addAudioEffect(activatableClassId: string): void; - addAudioEffect(activatableClassId: string, effectRequired: boolean, configuration: Windows.Foundation.Collections.IPropertySet): void; - addVideoEffect(activatableClassId: string): void; - addVideoEffect(activatableClassId: string, effectRequired: boolean, configuration: Windows.Foundation.Collections.IPropertySet): void; - clearEffects(): void; - prepareFileTranscodeAsync(source: Windows.Storage.IStorageFile, destination: Windows.Storage.IStorageFile, profile: Windows.Media.MediaProperties.MediaEncodingProfile): Windows.Foundation.IAsyncOperation; - prepareStreamTranscodeAsync(source: Windows.Storage.Streams.IRandomAccessStream, destination: Windows.Storage.Streams.IRandomAccessStream, profile: Windows.Media.MediaProperties.MediaEncodingProfile): Windows.Foundation.IAsyncOperation; - } - } - } -} -declare module Windows { - export module Networking { - export module NetworkOperators { - export enum DataClasses { - none, - gprs, - edge, - umts, - hsdpa, - hsupa, - lteAdvanced, - cdma1xRtt, - cdma1xEvdo, - cdma1xEvdoRevA, - cdma1xEvdv, - cdma3xRtt, - cdma1xEvdoRevB, - cdmaUmb, - custom, - } - export enum MobileBroadbandDeviceType { - unknown, - embedded, - removable, - remote, - } - export enum NetworkDeviceStatus { - deviceNotReady, - deviceReady, - simNotInserted, - badSim, - deviceHardwareFailure, - accountNotActivated, - deviceLocked, - deviceBlocked, - } - export enum NetworkRegistrationState { - none, - deregistered, - searching, - home, - roaming, - partner, - denied, - } - export enum MobileBroadbandRadioState { - off, - on, - } - export enum NetworkOperatorEventMessageType { - gsm, - cdma, - ussd, - dataPlanThresholdReached, - dataPlanReset, - dataPlanDeleted, - profileConnected, - profileDisconnected, - registeredRoaming, - registeredHome, - } - export enum MobileBroadbandAccountWatcherStatus { - created, - started, - enumerationCompleted, - stopped, - aborted, - } - export interface IMobileBroadbandAccountStatics { - availableNetworkAccountIds: Windows.Foundation.Collections.IVectorView; - createFromNetworkAccountId(networkAccountId: string): Windows.Networking.NetworkOperators.MobileBroadbandAccount; - } - export class MobileBroadbandAccount implements Windows.Networking.NetworkOperators.IMobileBroadbandAccount { - currentDeviceInformation: Windows.Networking.NetworkOperators.MobileBroadbandDeviceInformation; - currentNetwork: Windows.Networking.NetworkOperators.MobileBroadbandNetwork; - networkAccountId: string; - serviceProviderGuid: string; - serviceProviderName: string; - static availableNetworkAccountIds: Windows.Foundation.Collections.IVectorView; - static createFromNetworkAccountId(networkAccountId: string): Windows.Networking.NetworkOperators.MobileBroadbandAccount; - } - export interface IMobileBroadbandAccount { - currentDeviceInformation: Windows.Networking.NetworkOperators.MobileBroadbandDeviceInformation; - currentNetwork: Windows.Networking.NetworkOperators.MobileBroadbandNetwork; - networkAccountId: string; - serviceProviderGuid: string; - serviceProviderName: string; - } - export class MobileBroadbandNetwork implements Windows.Networking.NetworkOperators.IMobileBroadbandNetwork { - accessPointName: string; - activationNetworkError: number; - networkAdapter: Windows.Networking.Connectivity.NetworkAdapter; - networkRegistrationState: Windows.Networking.NetworkOperators.NetworkRegistrationState; - packetAttachNetworkError: number; - registeredDataClass: Windows.Networking.NetworkOperators.DataClasses; - registeredProviderId: string; - registeredProviderName: string; - registrationNetworkError: number; - showConnectionUI(): void; - } - export class MobileBroadbandDeviceInformation implements Windows.Networking.NetworkOperators.IMobileBroadbandDeviceInformation { - cellularClass: Windows.Devices.Sms.CellularClass; - currentRadioState: Windows.Networking.NetworkOperators.MobileBroadbandRadioState; - customDataClass: string; - dataClasses: Windows.Networking.NetworkOperators.DataClasses; - deviceId: string; - deviceType: Windows.Networking.NetworkOperators.MobileBroadbandDeviceType; - firmwareInformation: string; - manufacturer: string; - mobileEquipmentId: string; - model: string; - networkDeviceStatus: Windows.Networking.NetworkOperators.NetworkDeviceStatus; - simIccId: string; - subscriberId: string; - telephoneNumbers: Windows.Foundation.Collections.IVectorView; - } - export interface IMobileBroadbandDeviceInformation { - cellularClass: Windows.Devices.Sms.CellularClass; - currentRadioState: Windows.Networking.NetworkOperators.MobileBroadbandRadioState; - customDataClass: string; - dataClasses: Windows.Networking.NetworkOperators.DataClasses; - deviceId: string; - deviceType: Windows.Networking.NetworkOperators.MobileBroadbandDeviceType; - firmwareInformation: string; - manufacturer: string; - mobileEquipmentId: string; - model: string; - networkDeviceStatus: Windows.Networking.NetworkOperators.NetworkDeviceStatus; - simIccId: string; - subscriberId: string; - telephoneNumbers: Windows.Foundation.Collections.IVectorView; - } - export interface IMobileBroadbandNetwork { - accessPointName: string; - activationNetworkError: number; - networkAdapter: Windows.Networking.Connectivity.NetworkAdapter; - networkRegistrationState: Windows.Networking.NetworkOperators.NetworkRegistrationState; - packetAttachNetworkError: number; - registeredDataClass: Windows.Networking.NetworkOperators.DataClasses; - registeredProviderId: string; - registeredProviderName: string; - registrationNetworkError: number; - showConnectionUI(): void; - } - export interface INetworkOperatorNotificationEventDetails { - encodingType: number; - message: string; - networkAccountId: string; - notificationType: Windows.Networking.NetworkOperators.NetworkOperatorEventMessageType; - ruleId: string; - smsMessage: Windows.Devices.Sms.ISmsMessage; - } - export class NetworkOperatorNotificationEventDetails implements Windows.Networking.NetworkOperators.INetworkOperatorNotificationEventDetails { - encodingType: number; - message: string; - networkAccountId: string; - notificationType: Windows.Networking.NetworkOperators.NetworkOperatorEventMessageType; - ruleId: string; - smsMessage: Windows.Devices.Sms.ISmsMessage; - } - export interface IMobileBroadbandAccountEventArgs { - networkAccountId: string; - } - export class MobileBroadbandAccountEventArgs implements Windows.Networking.NetworkOperators.IMobileBroadbandAccountEventArgs { - networkAccountId: string; - } - export interface IMobileBroadbandAccountUpdatedEventArgs { - hasDeviceInformationChanged: boolean; - hasNetworkChanged: boolean; - networkAccountId: string; - } - export class MobileBroadbandAccountUpdatedEventArgs implements Windows.Networking.NetworkOperators.IMobileBroadbandAccountUpdatedEventArgs { - hasDeviceInformationChanged: boolean; - hasNetworkChanged: boolean; - networkAccountId: string; - } - export interface IMobileBroadbandAccountWatcher { - status: Windows.Networking.NetworkOperators.MobileBroadbandAccountWatcherStatus; - onaccountadded: any/* TODO */; - onaccountupdated: any/* TODO */; - onaccountremoved: any/* TODO */; - onenumerationcompleted: any/* TODO */; - onstopped: any/* TODO */; - start(): void; - stop(): void; - } - export class MobileBroadbandAccountWatcher implements Windows.Networking.NetworkOperators.IMobileBroadbandAccountWatcher { - status: Windows.Networking.NetworkOperators.MobileBroadbandAccountWatcherStatus; - onaccountadded: any/* TODO */; - onaccountupdated: any/* TODO */; - onaccountremoved: any/* TODO */; - onenumerationcompleted: any/* TODO */; - onstopped: any/* TODO */; - start(): void; - stop(): void; - } - export interface IHotspotAuthenticationEventDetails { - eventToken: string; - } - export class HotspotAuthenticationEventDetails implements Windows.Networking.NetworkOperators.IHotspotAuthenticationEventDetails { - eventToken: string; - } - export interface IHotspotAuthenticationContextStatics { - tryGetAuthenticationContext(evenToken: string): { context: Windows.Networking.NetworkOperators.HotspotAuthenticationContext; isValid: boolean; }; - } - export class HotspotAuthenticationContext implements Windows.Networking.NetworkOperators.IHotspotAuthenticationContext { - authenticationUrl: Windows.Foundation.Uri; - networkAdapter: Windows.Networking.Connectivity.NetworkAdapter; - redirectMessageUrl: Windows.Foundation.Uri; - redirectMessageXml: Windows.Data.Xml.Dom.XmlDocument; - wirelessNetworkId: Uint8Array; - issueCredentials(userName: string, password: string, extraParameters: string, markAsManualConnectOnFailure: boolean): void; - abortAuthentication(markAsManual: boolean): void; - skipAuthentication(): void; - triggerAttentionRequired(packageRelativeApplicationId: string, applicationParameters: string): void; - static tryGetAuthenticationContext(evenToken: string): { context: Windows.Networking.NetworkOperators.HotspotAuthenticationContext; isValid: boolean; }; - } - export interface IHotspotAuthenticationContext { - authenticationUrl: Windows.Foundation.Uri; - networkAdapter: Windows.Networking.Connectivity.NetworkAdapter; - redirectMessageUrl: Windows.Foundation.Uri; - redirectMessageXml: Windows.Data.Xml.Dom.XmlDocument; - wirelessNetworkId: Uint8Array; - issueCredentials(userName: string, password: string, extraParameters: string, markAsManualConnectOnFailure: boolean): void; - abortAuthentication(markAsManual: boolean): void; - skipAuthentication(): void; - triggerAttentionRequired(packageRelativeApplicationId: string, applicationParameters: string): void; - } - export enum ProfileMediaType { - wlan, - wwan, - } - export interface IProvisionFromXmlDocumentResults { - allElementsProvisioned: boolean; - provisionResultsXml: string; - } - export class ProvisionFromXmlDocumentResults implements Windows.Networking.NetworkOperators.IProvisionFromXmlDocumentResults { - allElementsProvisioned: boolean; - provisionResultsXml: string; - } - export interface ProfileUsage { - usageInMegabytes: number; - lastSyncTime: Date; - } - export interface IProvisionedProfile { - updateCost(value: Windows.Networking.Connectivity.NetworkCostType): void; - updateUsage(value: Windows.Networking.NetworkOperators.ProfileUsage): void; - } - export class ProvisionedProfile implements Windows.Networking.NetworkOperators.IProvisionedProfile { - updateCost(value: Windows.Networking.Connectivity.NetworkCostType): void; - updateUsage(value: Windows.Networking.NetworkOperators.ProfileUsage): void; - } - export interface IProvisioningAgent { - provisionFromXmlDocumentAsync(provisioningXmlDocument: string): Windows.Foundation.IAsyncOperation; - getProvisionedProfile(mediaType: Windows.Networking.NetworkOperators.ProfileMediaType, profileName: string): Windows.Networking.NetworkOperators.ProvisionedProfile; - } - export interface IProvisioningAgentStaticMethods { - createFromNetworkAccountId(networkAccountId: string): Windows.Networking.NetworkOperators.ProvisioningAgent; - } - export class ProvisioningAgent implements Windows.Networking.NetworkOperators.IProvisioningAgent { - provisionFromXmlDocumentAsync(provisioningXmlDocument: string): Windows.Foundation.IAsyncOperation; - getProvisionedProfile(mediaType: Windows.Networking.NetworkOperators.ProfileMediaType, profileName: string): Windows.Networking.NetworkOperators.ProvisionedProfile; - static createFromNetworkAccountId(networkAccountId: string): Windows.Networking.NetworkOperators.ProvisioningAgent; - } - export enum UssdResultCode { - noActionRequired, - actionRequired, - terminated, - otherLocalClient, - operationNotSupported, - networkTimeout, - } - export interface IUssdMessage { - dataCodingScheme: number; - payloadAsText: string; - getPayload(): Uint8Array; - setPayload(value: Uint8Array): void; - } - export interface IUssdMessageFactory { - createMessage(messageText: string): Windows.Networking.NetworkOperators.UssdMessage; - } - export class UssdMessage implements Windows.Networking.NetworkOperators.IUssdMessage { - constructor(messageText: string); - dataCodingScheme: number; - payloadAsText: string; - getPayload(): Uint8Array; - setPayload(value: Uint8Array): void; - } - export interface IUssdReply { - message: Windows.Networking.NetworkOperators.UssdMessage; - resultCode: Windows.Networking.NetworkOperators.UssdResultCode; - } - export class UssdReply implements Windows.Networking.NetworkOperators.IUssdReply { - message: Windows.Networking.NetworkOperators.UssdMessage; - resultCode: Windows.Networking.NetworkOperators.UssdResultCode; - } - export interface IUssdSession { - sendMessageAndGetReplyAsync(message: Windows.Networking.NetworkOperators.UssdMessage): Windows.Foundation.IAsyncOperation; - close(): void; - } - export interface IUssdSessionStatics { - createFromNetworkAccountId(networkAccountId: string): Windows.Networking.NetworkOperators.UssdSession; - createFromNetworkInterfaceId(networkInterfaceId: string): Windows.Networking.NetworkOperators.UssdSession; - } - export class UssdSession implements Windows.Networking.NetworkOperators.IUssdSession { - sendMessageAndGetReplyAsync(message: Windows.Networking.NetworkOperators.UssdMessage): Windows.Foundation.IAsyncOperation; - close(): void; - static createFromNetworkAccountId(networkAccountId: string): Windows.Networking.NetworkOperators.UssdSession; - static createFromNetworkInterfaceId(networkInterfaceId: string): Windows.Networking.NetworkOperators.UssdSession; - } - } - } -} -declare module Windows { - export module Networking { - export module BackgroundTransfer { - export enum BackgroundTransferStatus { - idle, - running, - pausedByApplication, - pausedCostedNetwork, - pausedNoNetwork, - completed, - canceled, - error, - } - export enum BackgroundTransferCostPolicy { - default, - unrestrictedOnly, - always, - } - export interface BackgroundDownloadProgress { - bytesReceived: number; - totalBytesToReceive: number; - status: Windows.Networking.BackgroundTransfer.BackgroundTransferStatus; - hasResponseChanged: boolean; - hasRestarted: boolean; - } - export interface BackgroundUploadProgress { - bytesReceived: number; - bytesSent: number; - totalBytesToReceive: number; - totalBytesToSend: number; - status: Windows.Networking.BackgroundTransfer.BackgroundTransferStatus; - hasResponseChanged: boolean; - hasRestarted: boolean; - } - export interface IBackgroundTransferBase { - costPolicy: Windows.Networking.BackgroundTransfer.BackgroundTransferCostPolicy; - group: string; - method: string; - proxyCredential: Windows.Security.Credentials.PasswordCredential; - serverCredential: Windows.Security.Credentials.PasswordCredential; - setRequestHeader(headerName: string, headerValue: string): void; - } - export interface IBackgroundDownloader extends Windows.Networking.BackgroundTransfer.IBackgroundTransferBase { - createDownload(uri: Windows.Foundation.Uri, resultFile: Windows.Storage.IStorageFile): Windows.Networking.BackgroundTransfer.DownloadOperation; - createDownload(uri: Windows.Foundation.Uri, resultFile: Windows.Storage.IStorageFile, requestBodyFile: Windows.Storage.IStorageFile): Windows.Networking.BackgroundTransfer.DownloadOperation; - createDownloadAsync(uri: Windows.Foundation.Uri, resultFile: Windows.Storage.IStorageFile, requestBodyStream: Windows.Storage.Streams.IInputStream): Windows.Foundation.IAsyncOperation; - } - export class DownloadOperation implements Windows.Networking.BackgroundTransfer.IDownloadOperation, Windows.Networking.BackgroundTransfer.IBackgroundTransferOperation { - progress: Windows.Networking.BackgroundTransfer.BackgroundDownloadProgress; - resultFile: Windows.Storage.IStorageFile; - costPolicy: Windows.Networking.BackgroundTransfer.BackgroundTransferCostPolicy; - group: string; - guid: string; - method: string; - requestedUri: Windows.Foundation.Uri; - startAsync(): Windows.Foundation.IAsyncOperationWithProgress; - attachAsync(): Windows.Foundation.IAsyncOperationWithProgress; - pause(): void; - resume(): void; - getResultStreamAt(position: number): Windows.Storage.Streams.IInputStream; - getResponseInformation(): Windows.Networking.BackgroundTransfer.ResponseInformation; - } - export interface IBackgroundUploader extends Windows.Networking.BackgroundTransfer.IBackgroundTransferBase { - createUpload(uri: Windows.Foundation.Uri, sourceFile: Windows.Storage.IStorageFile): Windows.Networking.BackgroundTransfer.UploadOperation; - createUploadFromStreamAsync(uri: Windows.Foundation.Uri, sourceStream: Windows.Storage.Streams.IInputStream): Windows.Foundation.IAsyncOperation; - createUploadAsync(uri: Windows.Foundation.Uri, parts: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncOperation; - createUploadAsync(uri: Windows.Foundation.Uri, parts: Windows.Foundation.Collections.IIterable, subType: string): Windows.Foundation.IAsyncOperation; - createUploadAsync(uri: Windows.Foundation.Uri, parts: Windows.Foundation.Collections.IIterable, subType: string, boundary: string): Windows.Foundation.IAsyncOperation; - } - export class UploadOperation implements Windows.Networking.BackgroundTransfer.IUploadOperation, Windows.Networking.BackgroundTransfer.IBackgroundTransferOperation { - progress: Windows.Networking.BackgroundTransfer.BackgroundUploadProgress; - sourceFile: Windows.Storage.IStorageFile; - costPolicy: Windows.Networking.BackgroundTransfer.BackgroundTransferCostPolicy; - group: string; - guid: string; - method: string; - requestedUri: Windows.Foundation.Uri; - startAsync(): Windows.Foundation.IAsyncOperationWithProgress; - attachAsync(): Windows.Foundation.IAsyncOperationWithProgress; - getResultStreamAt(position: number): Windows.Storage.Streams.IInputStream; - getResponseInformation(): Windows.Networking.BackgroundTransfer.ResponseInformation; - } - export class BackgroundTransferContentPart implements Windows.Networking.BackgroundTransfer.IBackgroundTransferContentPart { - constructor(name: string); - constructor(name: string, fileName: string); - constructor(); - setHeader(headerName: string, headerValue: string): void; - setText(value: string): void; - setFile(value: Windows.Storage.IStorageFile): void; - } - export interface IBackgroundTransferOperation { - costPolicy: Windows.Networking.BackgroundTransfer.BackgroundTransferCostPolicy; - group: string; - guid: string; - method: string; - requestedUri: Windows.Foundation.Uri; - getResultStreamAt(position: number): Windows.Storage.Streams.IInputStream; - getResponseInformation(): Windows.Networking.BackgroundTransfer.ResponseInformation; - } - export class ResponseInformation implements Windows.Networking.BackgroundTransfer.IResponseInformation { - actualUri: Windows.Foundation.Uri; - headers: Windows.Foundation.Collections.IMapView; - isResumable: boolean; - statusCode: number; - } - export interface IDownloadOperation extends Windows.Networking.BackgroundTransfer.IBackgroundTransferOperation { - progress: Windows.Networking.BackgroundTransfer.BackgroundDownloadProgress; - resultFile: Windows.Storage.IStorageFile; - startAsync(): Windows.Foundation.IAsyncOperationWithProgress; - attachAsync(): Windows.Foundation.IAsyncOperationWithProgress; - pause(): void; - resume(): void; - } - export interface IUploadOperation extends Windows.Networking.BackgroundTransfer.IBackgroundTransferOperation { - progress: Windows.Networking.BackgroundTransfer.BackgroundUploadProgress; - sourceFile: Windows.Storage.IStorageFile; - startAsync(): Windows.Foundation.IAsyncOperationWithProgress; - attachAsync(): Windows.Foundation.IAsyncOperationWithProgress; - } - export interface IBackgroundDownloaderStaticMethods { - getCurrentDownloadsAsync(): Windows.Foundation.IAsyncOperation>; - getCurrentDownloadsAsync(group: string): Windows.Foundation.IAsyncOperation>; - } - export interface IBackgroundUploaderStaticMethods { - getCurrentUploadsAsync(): Windows.Foundation.IAsyncOperation>; - getCurrentUploadsAsync(group: string): Windows.Foundation.IAsyncOperation>; - } - export interface IResponseInformation { - actualUri: Windows.Foundation.Uri; - headers: Windows.Foundation.Collections.IMapView; - isResumable: boolean; - statusCode: number; - } - export interface IBackgroundTransferErrorStaticMethods { - getStatus(hresult: number): Windows.Web.WebErrorStatus; - } - export interface IBackgroundTransferContentPart { - setHeader(headerName: string, headerValue: string): void; - setText(value: string): void; - setFile(value: Windows.Storage.IStorageFile): void; - } - export interface IBackgroundTransferContentPartFactory { - createWithName(name: string): Windows.Networking.BackgroundTransfer.BackgroundTransferContentPart; - createWithNameAndFileName(name: string, fileName: string): Windows.Networking.BackgroundTransfer.BackgroundTransferContentPart; - } - export class BackgroundDownloader implements Windows.Networking.BackgroundTransfer.IBackgroundDownloader, Windows.Networking.BackgroundTransfer.IBackgroundTransferBase { - costPolicy: Windows.Networking.BackgroundTransfer.BackgroundTransferCostPolicy; - group: string; - method: string; - proxyCredential: Windows.Security.Credentials.PasswordCredential; - serverCredential: Windows.Security.Credentials.PasswordCredential; - createDownload(uri: Windows.Foundation.Uri, resultFile: Windows.Storage.IStorageFile): Windows.Networking.BackgroundTransfer.DownloadOperation; - createDownload(uri: Windows.Foundation.Uri, resultFile: Windows.Storage.IStorageFile, requestBodyFile: Windows.Storage.IStorageFile): Windows.Networking.BackgroundTransfer.DownloadOperation; - createDownloadAsync(uri: Windows.Foundation.Uri, resultFile: Windows.Storage.IStorageFile, requestBodyStream: Windows.Storage.Streams.IInputStream): Windows.Foundation.IAsyncOperation; - setRequestHeader(headerName: string, headerValue: string): void; - static getCurrentDownloadsAsync(): Windows.Foundation.IAsyncOperation>; - static getCurrentDownloadsAsync(group: string): Windows.Foundation.IAsyncOperation>; - } - export class BackgroundUploader implements Windows.Networking.BackgroundTransfer.IBackgroundUploader, Windows.Networking.BackgroundTransfer.IBackgroundTransferBase { - costPolicy: Windows.Networking.BackgroundTransfer.BackgroundTransferCostPolicy; - group: string; - method: string; - proxyCredential: Windows.Security.Credentials.PasswordCredential; - serverCredential: Windows.Security.Credentials.PasswordCredential; - createUpload(uri: Windows.Foundation.Uri, sourceFile: Windows.Storage.IStorageFile): Windows.Networking.BackgroundTransfer.UploadOperation; - createUploadFromStreamAsync(uri: Windows.Foundation.Uri, sourceStream: Windows.Storage.Streams.IInputStream): Windows.Foundation.IAsyncOperation; - createUploadAsync(uri: Windows.Foundation.Uri, parts: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncOperation; - createUploadAsync(uri: Windows.Foundation.Uri, parts: Windows.Foundation.Collections.IIterable, subType: string): Windows.Foundation.IAsyncOperation; - createUploadAsync(uri: Windows.Foundation.Uri, parts: Windows.Foundation.Collections.IIterable, subType: string, boundary: string): Windows.Foundation.IAsyncOperation; - setRequestHeader(headerName: string, headerValue: string): void; - static getCurrentUploadsAsync(): Windows.Foundation.IAsyncOperation>; - static getCurrentUploadsAsync(group: string): Windows.Foundation.IAsyncOperation>; - } - export class BackgroundTransferError { - static getStatus(hresult: number): Windows.Web.WebErrorStatus; - } - } - } -} -declare module Windows { - export module Networking { - export module Proximity { - export interface IProximityMessage { - data: Windows.Storage.Streams.IBuffer; - dataAsString: string; - messageType: string; - subscriptionId: number; - } - export class ProximityMessage implements Windows.Networking.Proximity.IProximityMessage { - data: Windows.Storage.Streams.IBuffer; - dataAsString: string; - messageType: string; - subscriptionId: number; - } - export interface MessageReceivedHandler { - (sender: Windows.Networking.Proximity.ProximityDevice, message: Windows.Networking.Proximity.ProximityMessage): void; - } - export class ProximityDevice implements Windows.Networking.Proximity.IProximityDevice { - bitsPerSecond: number; - deviceId: string; - maxMessageBytes: number; - subscribeForMessage(messageType: string, messageReceivedHandler: Windows.Networking.Proximity.MessageReceivedHandler): number; - publishMessage(messageType: string, message: string): number; - publishMessage(messageType: string, message: string, messageTransmittedHandler: Windows.Networking.Proximity.MessageTransmittedHandler): number; - publishBinaryMessage(messageType: string, message: Windows.Storage.Streams.IBuffer): number; - publishBinaryMessage(messageType: string, message: Windows.Storage.Streams.IBuffer, messageTransmittedHandler: Windows.Networking.Proximity.MessageTransmittedHandler): number; - publishUriMessage(message: Windows.Foundation.Uri): number; - publishUriMessage(message: Windows.Foundation.Uri, messageTransmittedHandler: Windows.Networking.Proximity.MessageTransmittedHandler): number; - stopSubscribingForMessage(subscriptionId: number): void; - stopPublishingMessage(messageId: number): void; - ondevicearrived: any/* TODO */; - ondevicedeparted: any/* TODO */; - static getDeviceSelector(): string; - static getDefault(): Windows.Networking.Proximity.ProximityDevice; - static fromId(deviceInterfaceId: string): Windows.Networking.Proximity.ProximityDevice; - } - export interface MessageTransmittedHandler { - (sender: Windows.Networking.Proximity.ProximityDevice, messageId: number): void; - } - export interface DeviceArrivedEventHandler { - (sender: Windows.Networking.Proximity.ProximityDevice): void; - } - export interface DeviceDepartedEventHandler { - (sender: Windows.Networking.Proximity.ProximityDevice): void; - } - export interface IProximityDevice { - bitsPerSecond: number; - deviceId: string; - maxMessageBytes: number; - subscribeForMessage(messageType: string, messageReceivedHandler: Windows.Networking.Proximity.MessageReceivedHandler): number; - publishMessage(messageType: string, message: string): number; - publishMessage(messageType: string, message: string, messageTransmittedHandler: Windows.Networking.Proximity.MessageTransmittedHandler): number; - publishBinaryMessage(messageType: string, message: Windows.Storage.Streams.IBuffer): number; - publishBinaryMessage(messageType: string, message: Windows.Storage.Streams.IBuffer, messageTransmittedHandler: Windows.Networking.Proximity.MessageTransmittedHandler): number; - publishUriMessage(message: Windows.Foundation.Uri): number; - publishUriMessage(message: Windows.Foundation.Uri, messageTransmittedHandler: Windows.Networking.Proximity.MessageTransmittedHandler): number; - stopSubscribingForMessage(subscriptionId: number): void; - stopPublishingMessage(messageId: number): void; - ondevicearrived: any/* TODO */; - ondevicedeparted: any/* TODO */; - } - export interface IProximityDeviceStatics { - getDeviceSelector(): string; - getDefault(): Windows.Networking.Proximity.ProximityDevice; - fromId(deviceInterfaceId: string): Windows.Networking.Proximity.ProximityDevice; - } - export enum TriggeredConnectState { - peerFound, - listening, - connecting, - completed, - canceled, - failed, - } - export interface ITriggeredConnectionStateChangedEventArgs { - id: number; - socket: Windows.Networking.Sockets.StreamSocket; - state: Windows.Networking.Proximity.TriggeredConnectState; - } - export class TriggeredConnectionStateChangedEventArgs implements Windows.Networking.Proximity.ITriggeredConnectionStateChangedEventArgs { - id: number; - socket: Windows.Networking.Sockets.StreamSocket; - state: Windows.Networking.Proximity.TriggeredConnectState; - } - export interface IPeerInformation { - displayName: string; - } - export class PeerInformation implements Windows.Networking.Proximity.IPeerInformation { - displayName: string; - } - export interface IConnectionRequestedEventArgs { - peerInformation: Windows.Networking.Proximity.PeerInformation; - } - export class ConnectionRequestedEventArgs implements Windows.Networking.Proximity.IConnectionRequestedEventArgs { - peerInformation: Windows.Networking.Proximity.PeerInformation; - } - export enum PeerDiscoveryTypes { - none, - browse, - triggered, - } - export interface IPeerFinderStatics { - allowBluetooth: boolean; - allowInfrastructure: boolean; - allowWiFiDirect: boolean; - alternateIdentities: Windows.Foundation.Collections.IMap; - displayName: string; - supportedDiscoveryTypes: Windows.Networking.Proximity.PeerDiscoveryTypes; - start(): void; - start(peerMessage: string): void; - stop(): void; - ontriggeredconnectionstatechanged: any/* TODO */; - onconnectionrequested: any/* TODO */; - findAllPeersAsync(): Windows.Foundation.IAsyncOperation>; - connectAsync(peerInformation: Windows.Networking.Proximity.PeerInformation): Windows.Foundation.IAsyncOperation; - } - export class PeerFinder { - static allowBluetooth: boolean; - static allowInfrastructure: boolean; - static allowWiFiDirect: boolean; - static alternateIdentities: Windows.Foundation.Collections.IMap; - static displayName: string; - static supportedDiscoveryTypes: Windows.Networking.Proximity.PeerDiscoveryTypes; - static start(): void; - static start(peerMessage: string): void; - static stop(): void; - static ontriggeredconnectionstatechanged: any/* TODO */; - static onconnectionrequested: any/* TODO */; - static findAllPeersAsync(): Windows.Foundation.IAsyncOperation>; - static connectAsync(peerInformation: Windows.Networking.Proximity.PeerInformation): Windows.Foundation.IAsyncOperation; - } - } - } -} -declare module Windows { - export module Networking { - export module Sockets { - export enum ControlChannelTriggerStatus { - hardwareSlotRequested, - softwareSlotAllocated, - hardwareSlotAllocated, - policyError, - systemError, - transportDisconnected, - serviceUnavailable, - } - export enum ControlChannelTriggerResourceType { - requestSoftwareSlot, - requestHardwareSlot, - } - export enum ControlChannelTriggerResetReason { - fastUserSwitched, - lowPowerExit, - } - export interface IControlChannelTrigger extends Windows.Foundation.IClosable { - controlChannelTriggerId: string; - currentKeepAliveIntervalInMinutes: number; - keepAliveTrigger: Windows.ApplicationModel.Background.IBackgroundTrigger; - pushNotificationTrigger: Windows.ApplicationModel.Background.IBackgroundTrigger; - serverKeepAliveIntervalInMinutes: number; - transportObject: any; - usingTransport(transport: any): void; - waitForPushEnabled(): Windows.Networking.Sockets.ControlChannelTriggerStatus; - decreaseNetworkKeepAliveInterval(): void; - flushTransport(): void; - } - export interface IControlChannelTriggerFactory { - createControlChannelTrigger(channelId: string, serverKeepAliveIntervalInMinutes: number): Windows.Networking.Sockets.ControlChannelTrigger; - createControlChannelTrigger(channelId: string, serverKeepAliveIntervalInMinutes: number, resourceRequestType: Windows.Networking.Sockets.ControlChannelTriggerResourceType): Windows.Networking.Sockets.ControlChannelTrigger; - } - export class ControlChannelTrigger implements Windows.Networking.Sockets.IControlChannelTrigger, Windows.Foundation.IClosable { - constructor(channelId: string, serverKeepAliveIntervalInMinutes: number); - constructor(channelId: string, serverKeepAliveIntervalInMinutes: number, resourceRequestType: Windows.Networking.Sockets.ControlChannelTriggerResourceType); - controlChannelTriggerId: string; - currentKeepAliveIntervalInMinutes: number; - keepAliveTrigger: Windows.ApplicationModel.Background.IBackgroundTrigger; - pushNotificationTrigger: Windows.ApplicationModel.Background.IBackgroundTrigger; - serverKeepAliveIntervalInMinutes: number; - transportObject: any; - usingTransport(transport: any): void; - waitForPushEnabled(): Windows.Networking.Sockets.ControlChannelTriggerStatus; - decreaseNetworkKeepAliveInterval(): void; - flushTransport(): void; - dispose(): void; - close(): void; - } - export interface IControlChannelTriggerEventDetails { - controlChannelTrigger: Windows.Networking.Sockets.ControlChannelTrigger; - } - export interface IControlChannelTriggerResetEventDetails { - hardwareSlotReset: boolean; - resetReason: Windows.Networking.Sockets.ControlChannelTriggerResetReason; - softwareSlotReset: boolean; - } - export enum SocketMessageType { - binary, - utf8, - } - export enum SocketProtectionLevel { - plainSocket, - ssl, - sslAllowNullEncryption, - } - export enum SocketQualityOfService { - normal, - lowLatency, - } - export enum SocketErrorStatus { - unknown, - operationAborted, - httpInvalidServerResponse, - connectionTimedOut, - addressFamilyNotSupported, - socketTypeNotSupported, - hostNotFound, - noDataRecordOfRequestedType, - nonAuthoritativeHostNotFound, - classTypeNotFound, - addressAlreadyInUse, - cannotAssignRequestedAddress, - connectionRefused, - networkIsUnreachable, - unreachableHost, - networkIsDown, - networkDroppedConnectionOnReset, - softwareCausedConnectionAbort, - connectionResetByPeer, - hostIsDown, - noAddressesFound, - tooManyOpenFiles, - messageTooLong, - certificateExpired, - certificateUntrustedRoot, - certificateCommonNameIsIncorrect, - certificateWrongUsage, - certificateRevoked, - certificateNoRevocationCheck, - certificateRevocationServerOffline, - certificateIsInvalid, - } - export interface RoundTripTimeStatistics { - variance: number; - max: number; - min: number; - sum: number; - } - export interface BandwidthStatistics { - outboundBitsPerSecond: number; - inboundBitsPerSecond: number; - outboundBitsPerSecondInstability: number; - inboundBitsPerSecondInstability: number; - outboundBandwidthPeaked: boolean; - inboundBandwidthPeaked: boolean; - } - export interface IDatagramSocketMessageReceivedEventArgs { - localAddress: Windows.Networking.HostName; - remoteAddress: Windows.Networking.HostName; - remotePort: string; - getDataReader(): Windows.Storage.Streams.DataReader; - getDataStream(): Windows.Storage.Streams.IInputStream; - } - export interface IMessageWebSocketMessageReceivedEventArgs { - messageType: Windows.Networking.Sockets.SocketMessageType; - getDataReader(): Windows.Storage.Streams.DataReader; - getDataStream(): Windows.Storage.Streams.IInputStream; - } - export interface IWebSocketClosedEventArgs { - code: number; - reason: string; - } - export interface IDatagramSocketInformation { - localAddress: Windows.Networking.HostName; - localPort: string; - remoteAddress: Windows.Networking.HostName; - remotePort: string; - } - export interface IDatagramSocketControl { - outboundUnicastHopLimit: number; - qualityOfService: Windows.Networking.Sockets.SocketQualityOfService; - } - export interface IDatagramSocketStatics { - getEndpointPairsAsync(remoteHostName: Windows.Networking.HostName, remoteServiceName: string): Windows.Foundation.IAsyncOperation>; - getEndpointPairsAsync(remoteHostName: Windows.Networking.HostName, remoteServiceName: string, sortOptions: Windows.Networking.HostNameSortOptions): Windows.Foundation.IAsyncOperation>; - } - export interface IDatagramSocket extends Windows.Foundation.IClosable { - control: Windows.Networking.Sockets.DatagramSocketControl; - information: Windows.Networking.Sockets.DatagramSocketInformation; - outputStream: Windows.Storage.Streams.IOutputStream; - connectAsync(remoteHostName: Windows.Networking.HostName, remoteServiceName: string): Windows.Foundation.IAsyncAction; - connectAsync(endpointPair: Windows.Networking.EndpointPair): Windows.Foundation.IAsyncAction; - bindServiceNameAsync(localServiceName: string): Windows.Foundation.IAsyncAction; - bindEndpointAsync(localHostName: Windows.Networking.HostName, localServiceName: string): Windows.Foundation.IAsyncAction; - joinMulticastGroup(host: Windows.Networking.HostName): void; - getOutputStreamAsync(remoteHostName: Windows.Networking.HostName, remoteServiceName: string): Windows.Foundation.IAsyncOperation; - getOutputStreamAsync(endpointPair: Windows.Networking.EndpointPair): Windows.Foundation.IAsyncOperation; - onmessagereceived: any/* TODO */; - } - export class DatagramSocketControl implements Windows.Networking.Sockets.IDatagramSocketControl { - outboundUnicastHopLimit: number; - qualityOfService: Windows.Networking.Sockets.SocketQualityOfService; - } - export class DatagramSocketInformation implements Windows.Networking.Sockets.IDatagramSocketInformation { - localAddress: Windows.Networking.HostName; - localPort: string; - remoteAddress: Windows.Networking.HostName; - remotePort: string; - } - export class DatagramSocket implements Windows.Networking.Sockets.IDatagramSocket, Windows.Foundation.IClosable { - control: Windows.Networking.Sockets.DatagramSocketControl; - information: Windows.Networking.Sockets.DatagramSocketInformation; - outputStream: Windows.Storage.Streams.IOutputStream; - connectAsync(remoteHostName: Windows.Networking.HostName, remoteServiceName: string): Windows.Foundation.IAsyncAction; - connectAsync(endpointPair: Windows.Networking.EndpointPair): Windows.Foundation.IAsyncAction; - bindServiceNameAsync(localServiceName: string): Windows.Foundation.IAsyncAction; - bindEndpointAsync(localHostName: Windows.Networking.HostName, localServiceName: string): Windows.Foundation.IAsyncAction; - joinMulticastGroup(host: Windows.Networking.HostName): void; - getOutputStreamAsync(remoteHostName: Windows.Networking.HostName, remoteServiceName: string): Windows.Foundation.IAsyncOperation; - getOutputStreamAsync(endpointPair: Windows.Networking.EndpointPair): Windows.Foundation.IAsyncOperation; - onmessagereceived: any/* TODO */; - dispose(): void; - static getEndpointPairsAsync(remoteHostName: Windows.Networking.HostName, remoteServiceName: string): Windows.Foundation.IAsyncOperation>; - static getEndpointPairsAsync(remoteHostName: Windows.Networking.HostName, remoteServiceName: string, sortOptions: Windows.Networking.HostNameSortOptions): Windows.Foundation.IAsyncOperation>; - close(): void; - } - export class DatagramSocketMessageReceivedEventArgs implements Windows.Networking.Sockets.IDatagramSocketMessageReceivedEventArgs { - localAddress: Windows.Networking.HostName; - remoteAddress: Windows.Networking.HostName; - remotePort: string; - getDataReader(): Windows.Storage.Streams.DataReader; - getDataStream(): Windows.Storage.Streams.IInputStream; - } - export interface IStreamSocketInformation { - bandwidthStatistics: Windows.Networking.Sockets.BandwidthStatistics; - localAddress: Windows.Networking.HostName; - localPort: string; - protectionLevel: Windows.Networking.Sockets.SocketProtectionLevel; - remoteAddress: Windows.Networking.HostName; - remoteHostName: Windows.Networking.HostName; - remotePort: string; - remoteServiceName: string; - roundTripTimeStatistics: Windows.Networking.Sockets.RoundTripTimeStatistics; - sessionKey: Windows.Storage.Streams.IBuffer; - } - export interface IStreamSocketControl { - keepAlive: boolean; - noDelay: boolean; - outboundBufferSizeInBytes: number; - outboundUnicastHopLimit: number; - qualityOfService: Windows.Networking.Sockets.SocketQualityOfService; - } - export interface IStreamSocket extends Windows.Foundation.IClosable { - control: Windows.Networking.Sockets.StreamSocketControl; - information: Windows.Networking.Sockets.StreamSocketInformation; - inputStream: Windows.Storage.Streams.IInputStream; - outputStream: Windows.Storage.Streams.IOutputStream; - connectAsync(endpointPair: Windows.Networking.EndpointPair): Windows.Foundation.IAsyncAction; - connectAsync(remoteHostName: Windows.Networking.HostName, remoteServiceName: string): Windows.Foundation.IAsyncAction; - connectAsync(endpointPair: Windows.Networking.EndpointPair, protectionLevel: Windows.Networking.Sockets.SocketProtectionLevel): Windows.Foundation.IAsyncAction; - connectAsync(remoteHostName: Windows.Networking.HostName, remoteServiceName: string, protectionLevel: Windows.Networking.Sockets.SocketProtectionLevel): Windows.Foundation.IAsyncAction; - upgradeToSslAsync(protectionLevel: Windows.Networking.Sockets.SocketProtectionLevel, validationHostName: Windows.Networking.HostName): Windows.Foundation.IAsyncAction; - } - export class StreamSocketControl implements Windows.Networking.Sockets.IStreamSocketControl { - keepAlive: boolean; - noDelay: boolean; - outboundBufferSizeInBytes: number; - outboundUnicastHopLimit: number; - qualityOfService: Windows.Networking.Sockets.SocketQualityOfService; - } - export class StreamSocketInformation implements Windows.Networking.Sockets.IStreamSocketInformation { - bandwidthStatistics: Windows.Networking.Sockets.BandwidthStatistics; - localAddress: Windows.Networking.HostName; - localPort: string; - protectionLevel: Windows.Networking.Sockets.SocketProtectionLevel; - remoteAddress: Windows.Networking.HostName; - remoteHostName: Windows.Networking.HostName; - remotePort: string; - remoteServiceName: string; - roundTripTimeStatistics: Windows.Networking.Sockets.RoundTripTimeStatistics; - sessionKey: Windows.Storage.Streams.IBuffer; - } - export interface IStreamSocketListenerControl { - qualityOfService: Windows.Networking.Sockets.SocketQualityOfService; - } - export interface IStreamSocketListenerInformation { - localPort: string; - } - export interface IStreamSocketListenerConnectionReceivedEventArgs { - socket: Windows.Networking.Sockets.StreamSocket; - } - export class StreamSocket implements Windows.Networking.Sockets.IStreamSocket, Windows.Foundation.IClosable { - control: Windows.Networking.Sockets.StreamSocketControl; - information: Windows.Networking.Sockets.StreamSocketInformation; - inputStream: Windows.Storage.Streams.IInputStream; - outputStream: Windows.Storage.Streams.IOutputStream; - connectAsync(endpointPair: Windows.Networking.EndpointPair): Windows.Foundation.IAsyncAction; - connectAsync(remoteHostName: Windows.Networking.HostName, remoteServiceName: string): Windows.Foundation.IAsyncAction; - connectAsync(endpointPair: Windows.Networking.EndpointPair, protectionLevel: Windows.Networking.Sockets.SocketProtectionLevel): Windows.Foundation.IAsyncAction; - connectAsync(remoteHostName: Windows.Networking.HostName, remoteServiceName: string, protectionLevel: Windows.Networking.Sockets.SocketProtectionLevel): Windows.Foundation.IAsyncAction; - upgradeToSslAsync(protectionLevel: Windows.Networking.Sockets.SocketProtectionLevel, validationHostName: Windows.Networking.HostName): Windows.Foundation.IAsyncAction; - dispose(): void; - close(): void; - } - export interface IStreamSocketListener extends Windows.Foundation.IClosable { - control: Windows.Networking.Sockets.StreamSocketListenerControl; - information: Windows.Networking.Sockets.StreamSocketListenerInformation; - bindServiceNameAsync(localServiceName: string): Windows.Foundation.IAsyncAction; - bindEndpointAsync(localHostName: Windows.Networking.HostName, localServiceName: string): Windows.Foundation.IAsyncAction; - onconnectionreceived: any/* TODO */; - } - export class StreamSocketListenerControl implements Windows.Networking.Sockets.IStreamSocketListenerControl { - qualityOfService: Windows.Networking.Sockets.SocketQualityOfService; - } - export class StreamSocketListenerInformation implements Windows.Networking.Sockets.IStreamSocketListenerInformation { - localPort: string; - } - export class StreamSocketListener implements Windows.Networking.Sockets.IStreamSocketListener, Windows.Foundation.IClosable { - control: Windows.Networking.Sockets.StreamSocketListenerControl; - information: Windows.Networking.Sockets.StreamSocketListenerInformation; - bindServiceNameAsync(localServiceName: string): Windows.Foundation.IAsyncAction; - bindEndpointAsync(localHostName: Windows.Networking.HostName, localServiceName: string): Windows.Foundation.IAsyncAction; - onconnectionreceived: any/* TODO */; - dispose(): void; - close(): void; - } - export class StreamSocketListenerConnectionReceivedEventArgs implements Windows.Networking.Sockets.IStreamSocketListenerConnectionReceivedEventArgs { - socket: Windows.Networking.Sockets.StreamSocket; - } - export interface IWebSocketControl { - outboundBufferSizeInBytes: number; - proxyCredential: Windows.Security.Credentials.PasswordCredential; - serverCredential: Windows.Security.Credentials.PasswordCredential; - supportedProtocols: Windows.Foundation.Collections.IVector; - } - export interface IWebSocketInformation { - bandwidthStatistics: Windows.Networking.Sockets.BandwidthStatistics; - localAddress: Windows.Networking.HostName; - protocol: string; - } - export interface IWebSocket extends Windows.Foundation.IClosable { - outputStream: Windows.Storage.Streams.IOutputStream; - connectAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncAction; - setRequestHeader(headerName: string, headerValue: string): void; - onclosed: any/* TODO */; - close(): void; - close(code: number, reason: string): void; - } - export class WebSocketClosedEventArgs implements Windows.Networking.Sockets.IWebSocketClosedEventArgs { - code: number; - reason: string; - } - export interface IMessageWebSocketControl extends Windows.Networking.Sockets.IWebSocketControl { - maxMessageSize: number; - messageType: Windows.Networking.Sockets.SocketMessageType; - } - export interface IMessageWebSocket extends Windows.Networking.Sockets.IWebSocket { - control: Windows.Networking.Sockets.MessageWebSocketControl; - information: Windows.Networking.Sockets.MessageWebSocketInformation; - onmessagereceived: any/* TODO */; - } - export class MessageWebSocketControl implements Windows.Networking.Sockets.IMessageWebSocketControl, Windows.Networking.Sockets.IWebSocketControl { - maxMessageSize: number; - messageType: Windows.Networking.Sockets.SocketMessageType; - outboundBufferSizeInBytes: number; - proxyCredential: Windows.Security.Credentials.PasswordCredential; - serverCredential: Windows.Security.Credentials.PasswordCredential; - supportedProtocols: Windows.Foundation.Collections.IVector; - } - export class MessageWebSocketInformation implements Windows.Networking.Sockets.IWebSocketInformation { - bandwidthStatistics: Windows.Networking.Sockets.BandwidthStatistics; - localAddress: Windows.Networking.HostName; - protocol: string; - } - export class MessageWebSocket implements Windows.Networking.Sockets.IMessageWebSocket, Windows.Networking.Sockets.IWebSocket, Windows.Foundation.IClosable { - control: Windows.Networking.Sockets.MessageWebSocketControl; - information: Windows.Networking.Sockets.MessageWebSocketInformation; - outputStream: Windows.Storage.Streams.IOutputStream; - onmessagereceived: any/* TODO */; - connectAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncAction; - setRequestHeader(headerName: string, headerValue: string): void; - onclosed: any/* TODO */; - close(code: number, reason: string): void; - dispose(): void; - close(): void; - } - export class MessageWebSocketMessageReceivedEventArgs implements Windows.Networking.Sockets.IMessageWebSocketMessageReceivedEventArgs { - messageType: Windows.Networking.Sockets.SocketMessageType; - getDataReader(): Windows.Storage.Streams.DataReader; - getDataStream(): Windows.Storage.Streams.IInputStream; - } - export interface IStreamWebSocketControl extends Windows.Networking.Sockets.IWebSocketControl { - noDelay: boolean; - } - export interface IStreamWebSocket extends Windows.Networking.Sockets.IWebSocket { - control: Windows.Networking.Sockets.StreamWebSocketControl; - information: Windows.Networking.Sockets.StreamWebSocketInformation; - inputStream: Windows.Storage.Streams.IInputStream; - } - export class StreamWebSocketControl implements Windows.Networking.Sockets.IStreamWebSocketControl, Windows.Networking.Sockets.IWebSocketControl { - noDelay: boolean; - outboundBufferSizeInBytes: number; - proxyCredential: Windows.Security.Credentials.PasswordCredential; - serverCredential: Windows.Security.Credentials.PasswordCredential; - supportedProtocols: Windows.Foundation.Collections.IVector; - } - export class StreamWebSocketInformation implements Windows.Networking.Sockets.IWebSocketInformation { - bandwidthStatistics: Windows.Networking.Sockets.BandwidthStatistics; - localAddress: Windows.Networking.HostName; - protocol: string; - } - export interface ISocketErrorStatics { - getStatus(hresult: number): Windows.Networking.Sockets.SocketErrorStatus; - } - export interface IWebSocketErrorStatics { - getStatus(hresult: number): Windows.Web.WebErrorStatus; - } - export class StreamWebSocket implements Windows.Networking.Sockets.IStreamWebSocket, Windows.Networking.Sockets.IWebSocket, Windows.Foundation.IClosable { - control: Windows.Networking.Sockets.StreamWebSocketControl; - information: Windows.Networking.Sockets.StreamWebSocketInformation; - inputStream: Windows.Storage.Streams.IInputStream; - outputStream: Windows.Storage.Streams.IOutputStream; - connectAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncAction; - setRequestHeader(headerName: string, headerValue: string): void; - onclosed: any/* TODO */; - close(code: number, reason: string): void; - dispose(): void; - close(): void; - } - export class WebSocketKeepAlive implements Windows.ApplicationModel.Background.IBackgroundTask { - run(taskInstance: Windows.ApplicationModel.Background.IBackgroundTaskInstance): void; - } - export class SocketError { - static getStatus(hresult: number): Windows.Networking.Sockets.SocketErrorStatus; - } - export class WebSocketError { - static getStatus(hresult: number): Windows.Web.WebErrorStatus; - } - } - } -} -declare module Windows { - export module Networking { - export enum HostNameSortOptions { - none, - optimizeForLongConnections, - } - export enum HostNameType { - domainName, - ipv4, - ipv6, - bluetooth, - } - export interface IHostNameStatics { - compare(value1: string, value2: string): number; - } - export interface IHostName { - canonicalName: string; - displayName: string; - iPInformation: Windows.Networking.Connectivity.IPInformation; - rawName: string; - type: Windows.Networking.HostNameType; - isEqual(hostName: Windows.Networking.HostName): boolean; - } - export class HostName implements Windows.Networking.IHostName { - constructor(hostName: string); - canonicalName: string; - displayName: string; - iPInformation: Windows.Networking.Connectivity.IPInformation; - rawName: string; - type: Windows.Networking.HostNameType; - isEqual(hostName: Windows.Networking.HostName): boolean; - static compare(value1: string, value2: string): number; - } - export interface IHostNameFactory { - createHostName(hostName: string): Windows.Networking.HostName; - } - export interface IEndpointPair { - localHostName: Windows.Networking.HostName; - localServiceName: string; - remoteHostName: Windows.Networking.HostName; - remoteServiceName: string; - } - export interface IEndpointPairFactory { - createEndpointPair(localHostName: Windows.Networking.HostName, localServiceName: string, remoteHostName: Windows.Networking.HostName, remoteServiceName: string): Windows.Networking.EndpointPair; - } - export class EndpointPair implements Windows.Networking.IEndpointPair { - constructor(localHostName: Windows.Networking.HostName, localServiceName: string, remoteHostName: Windows.Networking.HostName, remoteServiceName: string); - localHostName: Windows.Networking.HostName; - localServiceName: string; - remoteHostName: Windows.Networking.HostName; - remoteServiceName: string; - } - } -} -declare module Windows { - export module Networking { - export module Connectivity { - export class IPInformation implements Windows.Networking.Connectivity.IIPInformation { - networkAdapter: Windows.Networking.Connectivity.NetworkAdapter; - prefixLength: number; - } - export enum NetworkCostType { - unknown, - unrestricted, - fixed, - variable, - } - export enum NetworkConnectivityLevel { - none, - localAccess, - constrainedInternetAccess, - internetAccess, - } - export enum NetworkTypes { - none, - internet, - privateNetwork, - } - export enum RoamingStates { - none, - notRoaming, - roaming, - } - export enum NetworkAuthenticationType { - none, - unknown, - open80211, - sharedKey80211, - wpa, - wpaPsk, - wpaNone, - rsna, - rsnaPsk, - ihv, - } - export enum NetworkEncryptionType { - none, - unknown, - wep, - wep40, - wep104, - tkip, - ccmp, - wpaUseGroup, - rsnUseGroup, - ihv, - } - export interface IDataUsage { - bytesReceived: number; - bytesSent: number; - } - export interface IDataPlanUsage { - lastSyncTime: Date; - megabytesUsed: number; - } - export interface IDataPlanStatus { - dataLimitInMegabytes: number; - dataPlanUsage: Windows.Networking.Connectivity.DataPlanUsage; - inboundBitsPerSecond: number; - maxTransferSizeInMegabytes: number; - nextBillingCycle: Date; - outboundBitsPerSecond: number; - } - export class DataPlanUsage implements Windows.Networking.Connectivity.IDataPlanUsage { - lastSyncTime: Date; - megabytesUsed: number; - } - export interface IConnectionCost { - approachingDataLimit: boolean; - networkCostType: Windows.Networking.Connectivity.NetworkCostType; - overDataLimit: boolean; - roaming: boolean; - } - export interface INetworkSecuritySettings { - networkAuthenticationType: Windows.Networking.Connectivity.NetworkAuthenticationType; - networkEncryptionType: Windows.Networking.Connectivity.NetworkEncryptionType; - } - export interface IConnectionProfile { - networkAdapter: Windows.Networking.Connectivity.NetworkAdapter; - networkSecuritySettings: Windows.Networking.Connectivity.NetworkSecuritySettings; - profileName: string; - getNetworkConnectivityLevel(): Windows.Networking.Connectivity.NetworkConnectivityLevel; - getNetworkNames(): Windows.Foundation.Collections.IVectorView; - getConnectionCost(): Windows.Networking.Connectivity.ConnectionCost; - 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; - } - export class ConnectionCost implements Windows.Networking.Connectivity.IConnectionCost { - approachingDataLimit: boolean; - networkCostType: Windows.Networking.Connectivity.NetworkCostType; - overDataLimit: boolean; - roaming: boolean; - } - export class DataPlanStatus implements Windows.Networking.Connectivity.IDataPlanStatus { - dataLimitInMegabytes: number; - dataPlanUsage: Windows.Networking.Connectivity.DataPlanUsage; - inboundBitsPerSecond: number; - maxTransferSizeInMegabytes: number; - nextBillingCycle: Date; - outboundBitsPerSecond: number; - } - export class NetworkAdapter implements Windows.Networking.Connectivity.INetworkAdapter { - ianaInterfaceType: number; - inboundMaxBitsPerSecond: number; - networkAdapterId: string; - networkItem: Windows.Networking.Connectivity.NetworkItem; - outboundMaxBitsPerSecond: number; - getConnectedProfileAsync(): Windows.Foundation.IAsyncOperation; - } - export class DataUsage implements Windows.Networking.Connectivity.IDataUsage { - bytesReceived: number; - bytesSent: number; - } - export class NetworkSecuritySettings implements Windows.Networking.Connectivity.INetworkSecuritySettings { - networkAuthenticationType: Windows.Networking.Connectivity.NetworkAuthenticationType; - networkEncryptionType: Windows.Networking.Connectivity.NetworkEncryptionType; - } - export interface ILanIdentifierData { - type: number; - value: Windows.Foundation.Collections.IVectorView; - } - export interface ILanIdentifier { - infrastructureId: Windows.Networking.Connectivity.LanIdentifierData; - networkAdapterId: string; - portId: Windows.Networking.Connectivity.LanIdentifierData; - } - export class LanIdentifierData implements Windows.Networking.Connectivity.ILanIdentifierData { - type: number; - value: Windows.Foundation.Collections.IVectorView; - } - export interface NetworkStatusChangedEventHandler { - (sender: any): void; - } - export interface INetworkInformationStatics { - getConnectionProfiles(): Windows.Foundation.Collections.IVectorView; - getInternetConnectionProfile(): Windows.Networking.Connectivity.ConnectionProfile; - getLanIdentifiers(): Windows.Foundation.Collections.IVectorView; - getHostNames(): Windows.Foundation.Collections.IVectorView; - getProxyConfigurationAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperation; - getSortedEndpointPairs(destinationList: Windows.Foundation.Collections.IIterable, sortOptions: Windows.Networking.HostNameSortOptions): Windows.Foundation.Collections.IVectorView; - onnetworkstatuschanged: any/* TODO */; - } - export class ConnectionProfile implements Windows.Networking.Connectivity.IConnectionProfile { - networkAdapter: Windows.Networking.Connectivity.NetworkAdapter; - networkSecuritySettings: Windows.Networking.Connectivity.NetworkSecuritySettings; - profileName: string; - getNetworkConnectivityLevel(): Windows.Networking.Connectivity.NetworkConnectivityLevel; - getNetworkNames(): Windows.Foundation.Collections.IVectorView; - getConnectionCost(): Windows.Networking.Connectivity.ConnectionCost; - 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; - } - export class LanIdentifier implements Windows.Networking.Connectivity.ILanIdentifier { - infrastructureId: Windows.Networking.Connectivity.LanIdentifierData; - networkAdapterId: string; - portId: Windows.Networking.Connectivity.LanIdentifierData; - } - export class ProxyConfiguration implements Windows.Networking.Connectivity.IProxyConfiguration { - canConnectDirectly: boolean; - proxyUris: Windows.Foundation.Collections.IVectorView; - } - export interface INetworkItem { - networkId: string; - getNetworkTypes(): Windows.Networking.Connectivity.NetworkTypes; - } - export interface INetworkAdapter { - ianaInterfaceType: number; - inboundMaxBitsPerSecond: number; - networkAdapterId: string; - networkItem: Windows.Networking.Connectivity.NetworkItem; - outboundMaxBitsPerSecond: number; - getConnectedProfileAsync(): Windows.Foundation.IAsyncOperation; - } - export class NetworkItem implements Windows.Networking.Connectivity.INetworkItem { - networkId: string; - getNetworkTypes(): Windows.Networking.Connectivity.NetworkTypes; - } - export interface IIPInformation { - networkAdapter: Windows.Networking.Connectivity.NetworkAdapter; - prefixLength: number; - } - export interface IProxyConfiguration { - canConnectDirectly: boolean; - proxyUris: Windows.Foundation.Collections.IVectorView; - } - export class NetworkInformation { - static getConnectionProfiles(): Windows.Foundation.Collections.IVectorView; - static getInternetConnectionProfile(): Windows.Networking.Connectivity.ConnectionProfile; - static getLanIdentifiers(): Windows.Foundation.Collections.IVectorView; - static getHostNames(): Windows.Foundation.Collections.IVectorView; - static getProxyConfigurationAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperation; - static getSortedEndpointPairs(destinationList: Windows.Foundation.Collections.IIterable, sortOptions: Windows.Networking.HostNameSortOptions): Windows.Foundation.Collections.IVectorView; - static onnetworkstatuschanged: any/* TODO */; - } - } - } -} -declare module Windows { - export module Networking { - export module PushNotifications { - export enum PushNotificationType { - toast, - tile, - badge, - raw, - } - export interface IPushNotificationChannelManagerStatics { - createPushNotificationChannelForApplicationAsync(): Windows.Foundation.IAsyncOperation; - createPushNotificationChannelForApplicationAsync(applicationId: string): Windows.Foundation.IAsyncOperation; - createPushNotificationChannelForSecondaryTileAsync(tileId: string): Windows.Foundation.IAsyncOperation; - } - export class PushNotificationChannel implements Windows.Networking.PushNotifications.IPushNotificationChannel { - expirationTime: Date; - uri: string; - close(): void; - onpushnotificationreceived: any/* TODO */; - } - export interface IPushNotificationChannel { - expirationTime: Date; - uri: string; - close(): void; - onpushnotificationreceived: any/* TODO */; - } - export class PushNotificationReceivedEventArgs implements Windows.Networking.PushNotifications.IPushNotificationReceivedEventArgs { - badgeNotification: Windows.UI.Notifications.BadgeNotification; - cancel: boolean; - notificationType: Windows.Networking.PushNotifications.PushNotificationType; - rawNotification: Windows.Networking.PushNotifications.RawNotification; - tileNotification: Windows.UI.Notifications.TileNotification; - toastNotification: Windows.UI.Notifications.ToastNotification; - } - export interface IPushNotificationReceivedEventArgs { - badgeNotification: Windows.UI.Notifications.BadgeNotification; - cancel: boolean; - notificationType: Windows.Networking.PushNotifications.PushNotificationType; - rawNotification: Windows.Networking.PushNotifications.RawNotification; - tileNotification: Windows.UI.Notifications.TileNotification; - toastNotification: Windows.UI.Notifications.ToastNotification; - } - export class RawNotification implements Windows.Networking.PushNotifications.IRawNotification { - content: string; - } - export interface IRawNotification { - content: string; - } - export class PushNotificationChannelManager { - static createPushNotificationChannelForApplicationAsync(): Windows.Foundation.IAsyncOperation; - static createPushNotificationChannelForApplicationAsync(applicationId: string): Windows.Foundation.IAsyncOperation; - static createPushNotificationChannelForSecondaryTileAsync(tileId: string): Windows.Foundation.IAsyncOperation; - } - } - } -} -declare module Windows { - export module Security { - export module Authentication { - export module OnlineId { - export enum CredentialPromptType { - promptIfNeeded, - retypeCredentials, - doNotPrompt, - } - export interface IOnlineIdServiceTicketRequest { - policy: string; - service: string; - } - export interface IOnlineIdServiceTicketRequestFactory { - createOnlineIdServiceTicketRequest(service: string, policy: string): Windows.Security.Authentication.OnlineId.OnlineIdServiceTicketRequest; - createOnlineIdServiceTicketRequest(service: string): Windows.Security.Authentication.OnlineId.OnlineIdServiceTicketRequest; - } - export class OnlineIdServiceTicketRequest implements Windows.Security.Authentication.OnlineId.IOnlineIdServiceTicketRequest { - constructor(service: string, policy: string); - constructor(service: string); - policy: string; - service: string; - } - export interface IOnlineIdServiceTicket { - errorCode: number; - request: Windows.Security.Authentication.OnlineId.OnlineIdServiceTicketRequest; - value: string; - } - export interface IUserIdentity { - firstName: string; - id: string; - isBetaAccount: boolean; - isConfirmedPC: boolean; - lastName: string; - safeCustomerId: string; - signInName: string; - tickets: Windows.Foundation.Collections.IVectorView; - } - export class OnlineIdServiceTicket implements Windows.Security.Authentication.OnlineId.IOnlineIdServiceTicket { - errorCode: number; - request: Windows.Security.Authentication.OnlineId.OnlineIdServiceTicketRequest; - value: string; - } - export interface IOnlineIdAuthenticator { - applicationId: string; - authenticatedSafeCustomerId: string; - canSignOut: boolean; - authenticateUserAsync(request: Windows.Security.Authentication.OnlineId.OnlineIdServiceTicketRequest): Windows.Security.Authentication.OnlineId.UserAuthenticationOperation; - authenticateUserAsync(requests: Windows.Foundation.Collections.IIterable, credentialPromptType: Windows.Security.Authentication.OnlineId.CredentialPromptType): Windows.Security.Authentication.OnlineId.UserAuthenticationOperation; - signOutUserAsync(): Windows.Security.Authentication.OnlineId.SignOutUserOperation; - } - export class UserAuthenticationOperation implements Windows.Foundation.IAsyncOperation, Windows.Foundation.IAsyncInfo { - completed: Windows.Foundation.AsyncOperationCompletedHandler; - errorCode: number; - id: number; - status: Windows.Foundation.AsyncStatus; - getResults(): Windows.Security.Authentication.OnlineId.UserIdentity; - cancel(): void; - close(): void; - then(success?: (value: Windows.Security.Authentication.OnlineId.UserIdentity) => U, error?: (error: any) => U, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: Windows.Security.Authentication.OnlineId.UserIdentity) => Windows.Foundation.IPromise, error?: (error: any) => U, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: Windows.Security.Authentication.OnlineId.UserIdentity) => U, error?: (error: any) => Windows.Foundation.IPromise, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: Windows.Security.Authentication.OnlineId.UserIdentity) => Windows.Foundation.IPromise, error?: (error: any) => Windows.Foundation.IPromise, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - done(success?: (value: Windows.Security.Authentication.OnlineId.UserIdentity) => any, error?: (error: any) => any, progress?: (progress: any) => void ): void; - operation: { - completed: Windows.Foundation.AsyncOperationCompletedHandler; - getResults(): Windows.Security.Authentication.OnlineId.UserIdentity; - } - } - export class SignOutUserOperation implements Windows.Foundation.IAsyncAction, Windows.Foundation.IAsyncInfo { - completed: Windows.Foundation.AsyncActionCompletedHandler; - errorCode: number; - id: number; - status: Windows.Foundation.AsyncStatus; - getResults(): void; - cancel(): void; - close(): void; - then(success: (value: any) => U, error?: (error: any) => U, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success: (value: any) => Windows.Foundation.IPromise, error?: (error: any) => U, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success: (value: any) => U, error?: (error: any) => Windows.Foundation.IPromise, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success: (value: any) => Windows.Foundation.IPromise, error?: (error: any) => Windows.Foundation.IPromise, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - done(success: (value: any) => any, error?: (error: any) => any, progress?: (progress: any) => void ): void; - operation: { - completed: Windows.Foundation.AsyncOperationCompletedHandler; - getResults(): any; - } - } - export class UserIdentity implements Windows.Security.Authentication.OnlineId.IUserIdentity { - firstName: string; - id: string; - isBetaAccount: boolean; - isConfirmedPC: boolean; - lastName: string; - safeCustomerId: string; - signInName: string; - tickets: Windows.Foundation.Collections.IVectorView; - } - export class OnlineIdAuthenticator implements Windows.Security.Authentication.OnlineId.IOnlineIdAuthenticator { - applicationId: string; - authenticatedSafeCustomerId: string; - canSignOut: boolean; - authenticateUserAsync(request: Windows.Security.Authentication.OnlineId.OnlineIdServiceTicketRequest): Windows.Security.Authentication.OnlineId.UserAuthenticationOperation; - authenticateUserAsync(requests: Windows.Foundation.Collections.IIterable, credentialPromptType: Windows.Security.Authentication.OnlineId.CredentialPromptType): Windows.Security.Authentication.OnlineId.UserAuthenticationOperation; - signOutUserAsync(): Windows.Security.Authentication.OnlineId.SignOutUserOperation; - } - } - } - } -} -declare module Windows { - export module Security { - export module Authentication { - export module Web { - export enum WebAuthenticationStatus { - success, - userCancel, - errorHttp, - } - export enum WebAuthenticationOptions { - none, - silentMode, - useTitle, - useHttpPost, - useCorporateNetwork, - } - export interface IWebAuthenticationResult { - responseData: string; - responseErrorDetail: number; - responseStatus: Windows.Security.Authentication.Web.WebAuthenticationStatus; - } - export class WebAuthenticationResult implements Windows.Security.Authentication.Web.IWebAuthenticationResult { - responseData: string; - responseErrorDetail: number; - responseStatus: Windows.Security.Authentication.Web.WebAuthenticationStatus; - } - export interface IWebAuthenticationBrokerStatics { - authenticateAsync(options: Windows.Security.Authentication.Web.WebAuthenticationOptions, requestUri: Windows.Foundation.Uri, callbackUri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperation; - authenticateAsync(options: Windows.Security.Authentication.Web.WebAuthenticationOptions, requestUri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperation; - getCurrentApplicationCallbackUri(): Windows.Foundation.Uri; - } - export class WebAuthenticationBroker { - static authenticateAsync(options: Windows.Security.Authentication.Web.WebAuthenticationOptions, requestUri: Windows.Foundation.Uri, callbackUri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperation; - static authenticateAsync(options: Windows.Security.Authentication.Web.WebAuthenticationOptions, requestUri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperation; - static getCurrentApplicationCallbackUri(): Windows.Foundation.Uri; - } - } - } - } -} -declare module Windows { - export module Security { - export module Credentials { - export module UI { - export enum AuthenticationProtocol { - basic, - digest, - ntlm, - kerberos, - negotiate, - credSsp, - custom, - } - export enum CredentialSaveOption { - unselected, - selected, - hidden, - } - export interface ICredentialPickerOptions { - alwaysDisplayDialog: boolean; - authenticationProtocol: Windows.Security.Credentials.UI.AuthenticationProtocol; - callerSavesCredential: boolean; - caption: string; - credentialSaveOption: Windows.Security.Credentials.UI.CredentialSaveOption; - customAuthenticationProtocol: string; - errorCode: number; - message: string; - previousCredential: Windows.Storage.Streams.IBuffer; - targetName: string; - } - export class CredentialPickerOptions implements Windows.Security.Credentials.UI.ICredentialPickerOptions { - alwaysDisplayDialog: boolean; - authenticationProtocol: Windows.Security.Credentials.UI.AuthenticationProtocol; - callerSavesCredential: boolean; - caption: string; - credentialSaveOption: Windows.Security.Credentials.UI.CredentialSaveOption; - customAuthenticationProtocol: string; - errorCode: number; - message: string; - previousCredential: Windows.Storage.Streams.IBuffer; - targetName: string; - } - export interface ICredentialPickerStatics { - pickAsync(options: Windows.Security.Credentials.UI.CredentialPickerOptions): Windows.Foundation.IAsyncOperation; - pickAsync(targetName: string, message: string): Windows.Foundation.IAsyncOperation; - pickAsync(targetName: string, message: string, caption: string): Windows.Foundation.IAsyncOperation; - } - export class CredentialPickerResults implements Windows.Security.Credentials.UI.ICredentialPickerResults { - credential: Windows.Storage.Streams.IBuffer; - credentialDomainName: string; - credentialPassword: string; - credentialSaveOption: Windows.Security.Credentials.UI.CredentialSaveOption; - credentialSaved: boolean; - credentialUserName: string; - errorCode: number; - } - export class CredentialPicker { - static pickAsync(options: Windows.Security.Credentials.UI.CredentialPickerOptions): Windows.Foundation.IAsyncOperation; - static pickAsync(targetName: string, message: string): Windows.Foundation.IAsyncOperation; - static pickAsync(targetName: string, message: string, caption: string): Windows.Foundation.IAsyncOperation; - } - export interface ICredentialPickerResults { - credential: Windows.Storage.Streams.IBuffer; - credentialDomainName: string; - credentialPassword: string; - credentialSaveOption: Windows.Security.Credentials.UI.CredentialSaveOption; - credentialSaved: boolean; - credentialUserName: string; - errorCode: number; - } - } - } - } -} -declare module Windows { - export module Security { - export module Credentials { - export interface IPasswordCredential { - password: string; - properties: Windows.Foundation.Collections.IPropertySet; - resource: string; - userName: string; - retrievePassword(): void; - } - export class PasswordCredential implements Windows.Security.Credentials.IPasswordCredential { - constructor(resource: string, userName: string, password: string); - constructor(); - password: string; - properties: Windows.Foundation.Collections.IPropertySet; - resource: string; - userName: string; - retrievePassword(): void; - } - export interface ICredentialFactory { - createPasswordCredential(resource: string, userName: string, password: string): Windows.Security.Credentials.PasswordCredential; - } - export interface IPasswordVault { - add(credential: Windows.Security.Credentials.PasswordCredential): void; - remove(credential: Windows.Security.Credentials.PasswordCredential): void; - retrieve(resource: string, userName: string): Windows.Security.Credentials.PasswordCredential; - findAllByResource(resource: string): Windows.Foundation.Collections.IVectorView; - findAllByUserName(userName: string): Windows.Foundation.Collections.IVectorView; - retrieveAll(): Windows.Foundation.Collections.IVectorView; - } - export class PasswordVault implements Windows.Security.Credentials.IPasswordVault { - add(credential: Windows.Security.Credentials.PasswordCredential): void; - remove(credential: Windows.Security.Credentials.PasswordCredential): void; - retrieve(resource: string, userName: string): Windows.Security.Credentials.PasswordCredential; - findAllByResource(resource: string): Windows.Foundation.Collections.IVectorView; - findAllByUserName(userName: string): Windows.Foundation.Collections.IVectorView; - retrieveAll(): Windows.Foundation.Collections.IVectorView; - } - export class PasswordCredentialPropertyStore implements Windows.Foundation.Collections.IPropertySet, Windows.Foundation.Collections.IObservableMap, Windows.Foundation.Collections.IMap, Windows.Foundation.Collections.IIterable> { - size: number; - onmapchanged: any/* TODO */; - lookup(key: string): any; - hasKey(key: string): boolean; - getView(): Windows.Foundation.Collections.IMapView; - insert(key: string, value: any): boolean; - remove(key: string): void; - clear(): void; - first(): Windows.Foundation.Collections.IIterator>; - } - } - } -} -declare module Windows { - export module Security { - export module Cryptography { - export module Certificates { - export enum EnrollKeyUsages { - none, - decryption, - signing, - keyAgreement, - all, - } - export enum KeyProtectionLevel { - noConsent, - consentOnly, - consentWithPassword, - } - export enum ExportOption { - notExportable, - exportable, - } - export enum KeySize { - invalid, - rsa2048, - rsa4096, - } - export enum InstallOptions { - none, - deleteExpired, - } - export interface ICertificateRequestProperties { - exportable: Windows.Security.Cryptography.Certificates.ExportOption; - friendlyName: string; - hashAlgorithmName: string; - keyAlgorithmName: string; - keyProtectionLevel: Windows.Security.Cryptography.Certificates.KeyProtectionLevel; - keySize: number; - keyStorageProviderName: string; - keyUsages: Windows.Security.Cryptography.Certificates.EnrollKeyUsages; - subject: string; - } - export class CertificateRequestProperties implements Windows.Security.Cryptography.Certificates.ICertificateRequestProperties { - exportable: Windows.Security.Cryptography.Certificates.ExportOption; - friendlyName: string; - hashAlgorithmName: string; - keyAlgorithmName: string; - keyProtectionLevel: Windows.Security.Cryptography.Certificates.KeyProtectionLevel; - keySize: number; - keyStorageProviderName: string; - keyUsages: Windows.Security.Cryptography.Certificates.EnrollKeyUsages; - subject: string; - } - export interface ICertificateEnrollmentManagerStatics { - createRequestAsync(request: Windows.Security.Cryptography.Certificates.CertificateRequestProperties): Windows.Foundation.IAsyncOperation; - installCertificateAsync(certificate: string, installOption: Windows.Security.Cryptography.Certificates.InstallOptions): Windows.Foundation.IAsyncAction; - importPfxDataAsync(pfxData: string, password: string, exportable: Windows.Security.Cryptography.Certificates.ExportOption, keyProtectionLevel: Windows.Security.Cryptography.Certificates.KeyProtectionLevel, installOption: Windows.Security.Cryptography.Certificates.InstallOptions, friendlyName: string): Windows.Foundation.IAsyncAction; - } - export class CertificateEnrollmentManager { - static createRequestAsync(request: Windows.Security.Cryptography.Certificates.CertificateRequestProperties): Windows.Foundation.IAsyncOperation; - static installCertificateAsync(certificate: string, installOption: Windows.Security.Cryptography.Certificates.InstallOptions): Windows.Foundation.IAsyncAction; - static importPfxDataAsync(pfxData: string, password: string, exportable: Windows.Security.Cryptography.Certificates.ExportOption, keyProtectionLevel: Windows.Security.Cryptography.Certificates.KeyProtectionLevel, installOption: Windows.Security.Cryptography.Certificates.InstallOptions, friendlyName: string): Windows.Foundation.IAsyncAction; - } - export interface IKeyAlgorithmNamesStatics { - dsa: string; - ecdh256: string; - ecdh384: string; - ecdh521: string; - ecdsa256: string; - ecdsa384: string; - ecdsa521: string; - rsa: string; - } - export class KeyAlgorithmNames { - static dsa: string; - static ecdh256: string; - static ecdh384: string; - static ecdh521: string; - static ecdsa256: string; - static ecdsa384: string; - static ecdsa521: string; - static rsa: string; - } - export interface IKeyStorageProviderNamesStatics { - platformKeyStorageProvider: string; - smartcardKeyStorageProvider: string; - softwareKeyStorageProvider: string; - } - export class KeyStorageProviderNames { - static platformKeyStorageProvider: string; - static smartcardKeyStorageProvider: string; - static softwareKeyStorageProvider: string; - } - } - } - } -} -declare module Windows { - export module Security { - export module Cryptography { - export module Core { - export enum CryptographicPrivateKeyBlobType { - pkcs8RawPrivateKeyInfo, - pkcs1RsaPrivateKey, - bCryptPrivateKey, - capi1PrivateKey, - } - export enum CryptographicPublicKeyBlobType { - x509SubjectPublicKeyInfo, - pkcs1RsaPublicKey, - bCryptPublicKey, - capi1PublicKey, - } - export interface IKeyDerivationParameters { - iterationCount: number; - kdfGenericBinary: Windows.Storage.Streams.IBuffer; - } - export interface IKeyDerivationParametersStatics { - buildForPbkdf2(pbkdf2Salt: Windows.Storage.Streams.IBuffer, iterationCount: number): Windows.Security.Cryptography.Core.KeyDerivationParameters; - buildForSP800108(label: Windows.Storage.Streams.IBuffer, context: Windows.Storage.Streams.IBuffer): Windows.Security.Cryptography.Core.KeyDerivationParameters; - buildForSP80056a(algorithmId: Windows.Storage.Streams.IBuffer, partyUInfo: Windows.Storage.Streams.IBuffer, partyVInfo: Windows.Storage.Streams.IBuffer, suppPubInfo: Windows.Storage.Streams.IBuffer, suppPrivInfo: Windows.Storage.Streams.IBuffer): Windows.Security.Cryptography.Core.KeyDerivationParameters; - } - export class KeyDerivationParameters implements Windows.Security.Cryptography.Core.IKeyDerivationParameters { - iterationCount: number; - kdfGenericBinary: Windows.Storage.Streams.IBuffer; - static buildForPbkdf2(pbkdf2Salt: Windows.Storage.Streams.IBuffer, iterationCount: number): Windows.Security.Cryptography.Core.KeyDerivationParameters; - static buildForSP800108(label: Windows.Storage.Streams.IBuffer, context: Windows.Storage.Streams.IBuffer): Windows.Security.Cryptography.Core.KeyDerivationParameters; - static buildForSP80056a(algorithmId: Windows.Storage.Streams.IBuffer, partyUInfo: Windows.Storage.Streams.IBuffer, partyVInfo: Windows.Storage.Streams.IBuffer, suppPubInfo: Windows.Storage.Streams.IBuffer, suppPrivInfo: Windows.Storage.Streams.IBuffer): Windows.Security.Cryptography.Core.KeyDerivationParameters; - } - export interface ICryptographicKey { - keySize: number; - export(): Windows.Storage.Streams.IBuffer; - export(BlobType: Windows.Security.Cryptography.Core.CryptographicPrivateKeyBlobType): Windows.Storage.Streams.IBuffer; - exportPublicKey(): Windows.Storage.Streams.IBuffer; - exportPublicKey(BlobType: Windows.Security.Cryptography.Core.CryptographicPublicKeyBlobType): Windows.Storage.Streams.IBuffer; - } - export class CryptographicKey implements Windows.Security.Cryptography.Core.ICryptographicKey { - keySize: number; - export(): Windows.Storage.Streams.IBuffer; - export(BlobType: Windows.Security.Cryptography.Core.CryptographicPrivateKeyBlobType): Windows.Storage.Streams.IBuffer; - exportPublicKey(): Windows.Storage.Streams.IBuffer; - exportPublicKey(BlobType: Windows.Security.Cryptography.Core.CryptographicPublicKeyBlobType): Windows.Storage.Streams.IBuffer; - } - export interface IHashComputation { - append(data: Windows.Storage.Streams.IBuffer): void; - getValueAndReset(): Windows.Storage.Streams.IBuffer; - } - export class CryptographicHash implements Windows.Security.Cryptography.Core.IHashComputation { - append(data: Windows.Storage.Streams.IBuffer): void; - getValueAndReset(): Windows.Storage.Streams.IBuffer; - } - export interface IHashAlgorithmProvider { - algorithmName: string; - hashLength: number; - hashData(data: Windows.Storage.Streams.IBuffer): Windows.Storage.Streams.IBuffer; - createHash(): Windows.Security.Cryptography.Core.CryptographicHash; - } - export interface IMacAlgorithmProvider { - algorithmName: string; - macLength: number; - createKey(keyMaterial: Windows.Storage.Streams.IBuffer): Windows.Security.Cryptography.Core.CryptographicKey; - } - export interface IKeyDerivationAlgorithmProvider { - algorithmName: string; - createKey(keyMaterial: Windows.Storage.Streams.IBuffer): Windows.Security.Cryptography.Core.CryptographicKey; - } - export interface ISymmetricKeyAlgorithmProvider { - algorithmName: string; - blockLength: number; - createSymmetricKey(keyMaterial: Windows.Storage.Streams.IBuffer): Windows.Security.Cryptography.Core.CryptographicKey; - } - export interface IAsymmetricKeyAlgorithmProvider { - algorithmName: string; - createKeyPair(keySize: number): Windows.Security.Cryptography.Core.CryptographicKey; - importKeyPair(keyBlob: Windows.Storage.Streams.IBuffer): Windows.Security.Cryptography.Core.CryptographicKey; - importKeyPair(keyBlob: Windows.Storage.Streams.IBuffer, BlobType: Windows.Security.Cryptography.Core.CryptographicPrivateKeyBlobType): Windows.Security.Cryptography.Core.CryptographicKey; - importPublicKey(keyBlob: Windows.Storage.Streams.IBuffer): Windows.Security.Cryptography.Core.CryptographicKey; - importPublicKey(keyBlob: Windows.Storage.Streams.IBuffer, BlobType: Windows.Security.Cryptography.Core.CryptographicPublicKeyBlobType): Windows.Security.Cryptography.Core.CryptographicKey; - } - export interface IEncryptedAndAuthenticatedData { - authenticationTag: Windows.Storage.Streams.IBuffer; - encryptedData: Windows.Storage.Streams.IBuffer; - } - export class EncryptedAndAuthenticatedData implements Windows.Security.Cryptography.Core.IEncryptedAndAuthenticatedData { - authenticationTag: Windows.Storage.Streams.IBuffer; - encryptedData: Windows.Storage.Streams.IBuffer; - } - export interface ICryptographicEngineStatics { - encrypt(key: Windows.Security.Cryptography.Core.CryptographicKey, data: Windows.Storage.Streams.IBuffer, iv: Windows.Storage.Streams.IBuffer): Windows.Storage.Streams.IBuffer; - decrypt(key: Windows.Security.Cryptography.Core.CryptographicKey, data: Windows.Storage.Streams.IBuffer, iv: Windows.Storage.Streams.IBuffer): Windows.Storage.Streams.IBuffer; - encryptAndAuthenticate(key: Windows.Security.Cryptography.Core.CryptographicKey, data: Windows.Storage.Streams.IBuffer, nonce: Windows.Storage.Streams.IBuffer, authenticatedData: Windows.Storage.Streams.IBuffer): Windows.Security.Cryptography.Core.EncryptedAndAuthenticatedData; - decryptAndAuthenticate(key: Windows.Security.Cryptography.Core.CryptographicKey, data: Windows.Storage.Streams.IBuffer, nonce: Windows.Storage.Streams.IBuffer, authenticationTag: Windows.Storage.Streams.IBuffer, authenticatedData: Windows.Storage.Streams.IBuffer): Windows.Storage.Streams.IBuffer; - sign(key: Windows.Security.Cryptography.Core.CryptographicKey, data: Windows.Storage.Streams.IBuffer): Windows.Storage.Streams.IBuffer; - verifySignature(key: Windows.Security.Cryptography.Core.CryptographicKey, data: Windows.Storage.Streams.IBuffer, signature: Windows.Storage.Streams.IBuffer): boolean; - deriveKeyMaterial(key: Windows.Security.Cryptography.Core.CryptographicKey, parameters: Windows.Security.Cryptography.Core.KeyDerivationParameters, desiredKeySize: number): Windows.Storage.Streams.IBuffer; - } - export class CryptographicEngine { - static encrypt(key: Windows.Security.Cryptography.Core.CryptographicKey, data: Windows.Storage.Streams.IBuffer, iv: Windows.Storage.Streams.IBuffer): Windows.Storage.Streams.IBuffer; - static decrypt(key: Windows.Security.Cryptography.Core.CryptographicKey, data: Windows.Storage.Streams.IBuffer, iv: Windows.Storage.Streams.IBuffer): Windows.Storage.Streams.IBuffer; - static encryptAndAuthenticate(key: Windows.Security.Cryptography.Core.CryptographicKey, data: Windows.Storage.Streams.IBuffer, nonce: Windows.Storage.Streams.IBuffer, authenticatedData: Windows.Storage.Streams.IBuffer): Windows.Security.Cryptography.Core.EncryptedAndAuthenticatedData; - static decryptAndAuthenticate(key: Windows.Security.Cryptography.Core.CryptographicKey, data: Windows.Storage.Streams.IBuffer, nonce: Windows.Storage.Streams.IBuffer, authenticationTag: Windows.Storage.Streams.IBuffer, authenticatedData: Windows.Storage.Streams.IBuffer): Windows.Storage.Streams.IBuffer; - static sign(key: Windows.Security.Cryptography.Core.CryptographicKey, data: Windows.Storage.Streams.IBuffer): Windows.Storage.Streams.IBuffer; - static verifySignature(key: Windows.Security.Cryptography.Core.CryptographicKey, data: Windows.Storage.Streams.IBuffer, signature: Windows.Storage.Streams.IBuffer): boolean; - static deriveKeyMaterial(key: Windows.Security.Cryptography.Core.CryptographicKey, parameters: Windows.Security.Cryptography.Core.KeyDerivationParameters, desiredKeySize: number): Windows.Storage.Streams.IBuffer; - } - export interface IHashAlgorithmProviderStatics { - openAlgorithm(algorithm: string): Windows.Security.Cryptography.Core.HashAlgorithmProvider; - } - export class HashAlgorithmProvider implements Windows.Security.Cryptography.Core.IHashAlgorithmProvider { - algorithmName: string; - hashLength: number; - hashData(data: Windows.Storage.Streams.IBuffer): Windows.Storage.Streams.IBuffer; - createHash(): Windows.Security.Cryptography.Core.CryptographicHash; - static openAlgorithm(algorithm: string): Windows.Security.Cryptography.Core.HashAlgorithmProvider; - } - export interface IMacAlgorithmProviderStatics { - openAlgorithm(algorithm: string): Windows.Security.Cryptography.Core.MacAlgorithmProvider; - } - export class MacAlgorithmProvider implements Windows.Security.Cryptography.Core.IMacAlgorithmProvider { - algorithmName: string; - macLength: number; - createKey(keyMaterial: Windows.Storage.Streams.IBuffer): Windows.Security.Cryptography.Core.CryptographicKey; - static openAlgorithm(algorithm: string): Windows.Security.Cryptography.Core.MacAlgorithmProvider; - } - export interface IKeyDerivationAlgorithmProviderStatics { - openAlgorithm(algorithm: string): Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider; - } - export class KeyDerivationAlgorithmProvider implements Windows.Security.Cryptography.Core.IKeyDerivationAlgorithmProvider { - algorithmName: string; - createKey(keyMaterial: Windows.Storage.Streams.IBuffer): Windows.Security.Cryptography.Core.CryptographicKey; - static openAlgorithm(algorithm: string): Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider; - } - export interface ISymmetricKeyAlgorithmProviderStatics { - openAlgorithm(algorithm: string): Windows.Security.Cryptography.Core.SymmetricKeyAlgorithmProvider; - } - export class SymmetricKeyAlgorithmProvider implements Windows.Security.Cryptography.Core.ISymmetricKeyAlgorithmProvider { - algorithmName: string; - blockLength: number; - createSymmetricKey(keyMaterial: Windows.Storage.Streams.IBuffer): Windows.Security.Cryptography.Core.CryptographicKey; - static openAlgorithm(algorithm: string): Windows.Security.Cryptography.Core.SymmetricKeyAlgorithmProvider; - } - export interface IAsymmetricKeyAlgorithmProviderStatics { - openAlgorithm(algorithm: string): Windows.Security.Cryptography.Core.AsymmetricKeyAlgorithmProvider; - } - export class AsymmetricKeyAlgorithmProvider implements Windows.Security.Cryptography.Core.IAsymmetricKeyAlgorithmProvider { - algorithmName: string; - createKeyPair(keySize: number): Windows.Security.Cryptography.Core.CryptographicKey; - importKeyPair(keyBlob: Windows.Storage.Streams.IBuffer): Windows.Security.Cryptography.Core.CryptographicKey; - importKeyPair(keyBlob: Windows.Storage.Streams.IBuffer, BlobType: Windows.Security.Cryptography.Core.CryptographicPrivateKeyBlobType): Windows.Security.Cryptography.Core.CryptographicKey; - importPublicKey(keyBlob: Windows.Storage.Streams.IBuffer): Windows.Security.Cryptography.Core.CryptographicKey; - importPublicKey(keyBlob: Windows.Storage.Streams.IBuffer, BlobType: Windows.Security.Cryptography.Core.CryptographicPublicKeyBlobType): Windows.Security.Cryptography.Core.CryptographicKey; - static openAlgorithm(algorithm: string): Windows.Security.Cryptography.Core.AsymmetricKeyAlgorithmProvider; - } - export interface IHashAlgorithmNamesStatics { - md5: string; - sha1: string; - sha256: string; - sha384: string; - sha512: string; - } - export class HashAlgorithmNames { - static md5: string; - static sha1: string; - static sha256: string; - static sha384: string; - static sha512: string; - } - export interface IMacAlgorithmNamesStatics { - aesCmac: string; - hmacMd5: string; - hmacSha1: string; - hmacSha256: string; - hmacSha384: string; - hmacSha512: string; - } - export class MacAlgorithmNames { - static aesCmac: string; - static hmacMd5: string; - static hmacSha1: string; - static hmacSha256: string; - static hmacSha384: string; - static hmacSha512: string; - } - export interface ISymmetricAlgorithmNamesStatics { - aesCbc: string; - aesCbcPkcs7: string; - aesCcm: string; - aesEcb: string; - aesEcbPkcs7: string; - aesGcm: string; - desCbc: string; - desCbcPkcs7: string; - desEcb: string; - desEcbPkcs7: string; - rc2Cbc: string; - rc2CbcPkcs7: string; - rc2Ecb: string; - rc2EcbPkcs7: string; - rc4: string; - tripleDesCbc: string; - tripleDesCbcPkcs7: string; - tripleDesEcb: string; - tripleDesEcbPkcs7: string; - } - export class SymmetricAlgorithmNames { - static aesCbc: string; - static aesCbcPkcs7: string; - static aesCcm: string; - static aesEcb: string; - static aesEcbPkcs7: string; - static aesGcm: string; - static desCbc: string; - static desCbcPkcs7: string; - static desEcb: string; - static desEcbPkcs7: string; - static rc2Cbc: string; - static rc2CbcPkcs7: string; - static rc2Ecb: string; - static rc2EcbPkcs7: string; - static rc4: string; - static tripleDesCbc: string; - static tripleDesCbcPkcs7: string; - static tripleDesEcb: string; - static tripleDesEcbPkcs7: string; - } - export interface IAsymmetricAlgorithmNamesStatics { - dsaSha1: string; - dsaSha256: string; - ecdsaP256Sha256: string; - ecdsaP384Sha384: string; - ecdsaP521Sha512: string; - rsaOaepSha1: string; - rsaOaepSha256: string; - rsaOaepSha384: string; - rsaOaepSha512: string; - rsaPkcs1: string; - rsaSignPkcs1Sha1: string; - rsaSignPkcs1Sha256: string; - rsaSignPkcs1Sha384: string; - rsaSignPkcs1Sha512: string; - rsaSignPssSha1: string; - rsaSignPssSha256: string; - rsaSignPssSha384: string; - rsaSignPssSha512: string; - } - export class AsymmetricAlgorithmNames { - static dsaSha1: string; - static dsaSha256: string; - static ecdsaP256Sha256: string; - static ecdsaP384Sha384: string; - static ecdsaP521Sha512: string; - static rsaOaepSha1: string; - static rsaOaepSha256: string; - static rsaOaepSha384: string; - static rsaOaepSha512: string; - static rsaPkcs1: string; - static rsaSignPkcs1Sha1: string; - static rsaSignPkcs1Sha256: string; - static rsaSignPkcs1Sha384: string; - static rsaSignPkcs1Sha512: string; - static rsaSignPssSha1: string; - static rsaSignPssSha256: string; - static rsaSignPssSha384: string; - static rsaSignPssSha512: string; - } - export interface IKeyDerivationAlgorithmNamesStatics { - pbkdf2Md5: string; - pbkdf2Sha1: string; - pbkdf2Sha256: string; - pbkdf2Sha384: string; - pbkdf2Sha512: string; - sp800108CtrHmacMd5: string; - sp800108CtrHmacSha1: string; - sp800108CtrHmacSha256: string; - sp800108CtrHmacSha384: string; - sp800108CtrHmacSha512: string; - sp80056aConcatMd5: string; - sp80056aConcatSha1: string; - sp80056aConcatSha256: string; - sp80056aConcatSha384: string; - sp80056aConcatSha512: string; - } - export class KeyDerivationAlgorithmNames { - static pbkdf2Md5: string; - static pbkdf2Sha1: string; - static pbkdf2Sha256: string; - static pbkdf2Sha384: string; - static pbkdf2Sha512: string; - static sp800108CtrHmacMd5: string; - static sp800108CtrHmacSha1: string; - static sp800108CtrHmacSha256: string; - static sp800108CtrHmacSha384: string; - static sp800108CtrHmacSha512: string; - static sp80056aConcatMd5: string; - static sp80056aConcatSha1: string; - static sp80056aConcatSha256: string; - static sp80056aConcatSha384: string; - static sp80056aConcatSha512: string; - } - } - } - } -} -declare module Windows { - export module Security { - export module Cryptography { - export module DataProtection { - export interface IDataProtectionProvider { - protectAsync(data: Windows.Storage.Streams.IBuffer): Windows.Foundation.IAsyncOperation; - unprotectAsync(data: Windows.Storage.Streams.IBuffer): Windows.Foundation.IAsyncOperation; - protectStreamAsync(src: Windows.Storage.Streams.IInputStream, dest: Windows.Storage.Streams.IOutputStream): Windows.Foundation.IAsyncAction; - unprotectStreamAsync(src: Windows.Storage.Streams.IInputStream, dest: Windows.Storage.Streams.IOutputStream): Windows.Foundation.IAsyncAction; - } - export interface IDataProtectionProviderFactory { - createOverloadExplicit(protectionDescriptor: string): Windows.Security.Cryptography.DataProtection.DataProtectionProvider; - } - export class DataProtectionProvider implements Windows.Security.Cryptography.DataProtection.IDataProtectionProvider { - constructor(protectionDescriptor: string); - constructor(); - protectAsync(data: Windows.Storage.Streams.IBuffer): Windows.Foundation.IAsyncOperation; - unprotectAsync(data: Windows.Storage.Streams.IBuffer): Windows.Foundation.IAsyncOperation; - protectStreamAsync(src: Windows.Storage.Streams.IInputStream, dest: Windows.Storage.Streams.IOutputStream): Windows.Foundation.IAsyncAction; - unprotectStreamAsync(src: Windows.Storage.Streams.IInputStream, dest: Windows.Storage.Streams.IOutputStream): Windows.Foundation.IAsyncAction; - } - } - } - } -} -declare module Windows { - export module Security { - export module Cryptography { - export enum BinaryStringEncoding { - utf8, - utf16LE, - utf16BE, - } - export interface ICryptographicBufferStatics { - compare(object1: Windows.Storage.Streams.IBuffer, object2: Windows.Storage.Streams.IBuffer): boolean; - generateRandom(length: number): Windows.Storage.Streams.IBuffer; - generateRandomNumber(): number; - createFromByteArray(value: Uint8Array): Windows.Storage.Streams.IBuffer; - copyToByteArray(buffer: Windows.Storage.Streams.IBuffer): Uint8Array; - decodeFromHexString(value: string): Windows.Storage.Streams.IBuffer; - encodeToHexString(buffer: Windows.Storage.Streams.IBuffer): string; - decodeFromBase64String(value: string): Windows.Storage.Streams.IBuffer; - encodeToBase64String(buffer: Windows.Storage.Streams.IBuffer): string; - convertStringToBinary(value: string, encoding: Windows.Security.Cryptography.BinaryStringEncoding): Windows.Storage.Streams.IBuffer; - convertBinaryToString(encoding: Windows.Security.Cryptography.BinaryStringEncoding, buffer: Windows.Storage.Streams.IBuffer): string; - } - export class CryptographicBuffer { - static compare(object1: Windows.Storage.Streams.IBuffer, object2: Windows.Storage.Streams.IBuffer): boolean; - static generateRandom(length: number): Windows.Storage.Streams.IBuffer; - static generateRandomNumber(): number; - static createFromByteArray(value: Uint8Array): Windows.Storage.Streams.IBuffer; - static copyToByteArray(buffer: Windows.Storage.Streams.IBuffer): Uint8Array; - static decodeFromHexString(value: string): Windows.Storage.Streams.IBuffer; - static encodeToHexString(buffer: Windows.Storage.Streams.IBuffer): string; - static decodeFromBase64String(value: string): Windows.Storage.Streams.IBuffer; - static encodeToBase64String(buffer: Windows.Storage.Streams.IBuffer): string; - static convertStringToBinary(value: string, encoding: Windows.Security.Cryptography.BinaryStringEncoding): Windows.Storage.Streams.IBuffer; - static convertBinaryToString(encoding: Windows.Security.Cryptography.BinaryStringEncoding, buffer: Windows.Storage.Streams.IBuffer): string; - } - } - } -} -declare module Windows { - export module Security { - export module ExchangeActiveSyncProvisioning { - export enum EasRequireEncryptionResult { - notEvaluated, - compliant, - canBeCompliant, - notProvisionedOnAllVolumes, - deFixedDataNotSupported, - deHardwareNotCompliant, - deWinReNotConfigured, - deProtectionSuspended, - deOsVolumeNotProtected, - deProtectionNotYetEnabled, - noFeatureLicense, - osNotProtected, - } - export enum EasMinPasswordLengthResult { - notEvaluated, - compliant, - canBeCompliant, - requestedPolicyIsStricter, - requestedPolicyNotEnforceable, - invalidParameter, - currentUserHasBlankPassword, - adminsHaveBlankPassword, - userCannotChangePassword, - adminsCannotChangePassword, - localControlledUsersCannotChangePassword, - connectedAdminsProviderPolicyIsWeak, - connectedUserProviderPolicyIsWeak, - changeConnectedAdminsPassword, - changeConnectedUserPassword, - } - export enum EasDisallowConvenienceLogonResult { - notEvaluated, - compliant, - canBeCompliant, - requestedPolicyIsStricter, - } - export enum EasMinPasswordComplexCharactersResult { - notEvaluated, - compliant, - canBeCompliant, - requestedPolicyIsStricter, - requestedPolicyNotEnforceable, - invalidParameter, - currentUserHasBlankPassword, - adminsHaveBlankPassword, - userCannotChangePassword, - adminsCannotChangePassword, - localControlledUsersCannotChangePassword, - connectedAdminsProviderPolicyIsWeak, - connectedUserProviderPolicyIsWeak, - changeConnectedAdminsPassword, - changeConnectedUserPassword, - } - export enum EasPasswordExpirationResult { - notEvaluated, - compliant, - canBeCompliant, - requestedPolicyIsStricter, - requestedExpirationIncompatible, - invalidParameter, - userCannotChangePassword, - adminsCannotChangePassword, - localControlledUsersCannotChangePassword, - } - export enum EasPasswordHistoryResult { - notEvaluated, - compliant, - canBeCompliant, - requestedPolicyIsStricter, - invalidParameter, - } - export enum EasMaxPasswordFailedAttemptsResult { - notEvaluated, - compliant, - canBeCompliant, - requestedPolicyIsStricter, - invalidParameter, - } - export enum EasMaxInactivityTimeLockResult { - notEvaluated, - compliant, - canBeCompliant, - requestedPolicyIsStricter, - invalidParameter, - } - export interface IEasClientDeviceInformation { - friendlyName: string; - id: string; - operatingSystem: string; - systemManufacturer: string; - systemProductName: string; - systemSku: string; - } - export interface IEasClientSecurityPolicy { - disallowConvenienceLogon: boolean; - maxInactivityTimeLock: number; - maxPasswordFailedAttempts: number; - minPasswordComplexCharacters: number; - minPasswordLength: number; - passwordExpiration: number; - passwordHistory: number; - requireEncryption: boolean; - checkCompliance(): Windows.Security.ExchangeActiveSyncProvisioning.EasComplianceResults; - applyAsync(): Windows.Foundation.IAsyncOperation; - } - export class EasComplianceResults implements Windows.Security.ExchangeActiveSyncProvisioning.IEasComplianceResults { - compliant: boolean; - disallowConvenienceLogonResult: Windows.Security.ExchangeActiveSyncProvisioning.EasDisallowConvenienceLogonResult; - maxInactivityTimeLockResult: Windows.Security.ExchangeActiveSyncProvisioning.EasMaxInactivityTimeLockResult; - maxPasswordFailedAttemptsResult: Windows.Security.ExchangeActiveSyncProvisioning.EasMaxPasswordFailedAttemptsResult; - minPasswordComplexCharactersResult: Windows.Security.ExchangeActiveSyncProvisioning.EasMinPasswordComplexCharactersResult; - minPasswordLengthResult: Windows.Security.ExchangeActiveSyncProvisioning.EasMinPasswordLengthResult; - passwordExpirationResult: Windows.Security.ExchangeActiveSyncProvisioning.EasPasswordExpirationResult; - passwordHistoryResult: Windows.Security.ExchangeActiveSyncProvisioning.EasPasswordHistoryResult; - requireEncryptionResult: Windows.Security.ExchangeActiveSyncProvisioning.EasRequireEncryptionResult; - } - export interface IEasComplianceResults { - compliant: boolean; - disallowConvenienceLogonResult: Windows.Security.ExchangeActiveSyncProvisioning.EasDisallowConvenienceLogonResult; - maxInactivityTimeLockResult: Windows.Security.ExchangeActiveSyncProvisioning.EasMaxInactivityTimeLockResult; - maxPasswordFailedAttemptsResult: Windows.Security.ExchangeActiveSyncProvisioning.EasMaxPasswordFailedAttemptsResult; - minPasswordComplexCharactersResult: Windows.Security.ExchangeActiveSyncProvisioning.EasMinPasswordComplexCharactersResult; - minPasswordLengthResult: Windows.Security.ExchangeActiveSyncProvisioning.EasMinPasswordLengthResult; - passwordExpirationResult: Windows.Security.ExchangeActiveSyncProvisioning.EasPasswordExpirationResult; - passwordHistoryResult: Windows.Security.ExchangeActiveSyncProvisioning.EasPasswordHistoryResult; - requireEncryptionResult: Windows.Security.ExchangeActiveSyncProvisioning.EasRequireEncryptionResult; - } - export class EasClientSecurityPolicy implements Windows.Security.ExchangeActiveSyncProvisioning.IEasClientSecurityPolicy { - disallowConvenienceLogon: boolean; - maxInactivityTimeLock: number; - maxPasswordFailedAttempts: number; - minPasswordComplexCharacters: number; - minPasswordLength: number; - passwordExpiration: number; - passwordHistory: number; - requireEncryption: boolean; - checkCompliance(): Windows.Security.ExchangeActiveSyncProvisioning.EasComplianceResults; - applyAsync(): Windows.Foundation.IAsyncOperation; - } - export class EasClientDeviceInformation implements Windows.Security.ExchangeActiveSyncProvisioning.IEasClientDeviceInformation { - friendlyName: string; - id: string; - operatingSystem: string; - systemManufacturer: string; - systemProductName: string; - systemSku: string; - } - } - } -} -declare module Windows { - export module Storage { - export module Streams { - export enum ByteOrder { - littleEndian, - bigEndian, - } - export enum UnicodeEncoding { - utf8, - utf16LE, - utf16BE, - } - export class DataReaderLoadOperation implements Windows.Foundation.IAsyncOperation, Windows.Foundation.IAsyncInfo { - completed: Windows.Foundation.AsyncOperationCompletedHandler; - errorCode: number; - id: number; - status: Windows.Foundation.AsyncStatus; - getResults(): number; - cancel(): void; - close(): void; - then(success?: (value: number) => U, error?: (error: any) => U, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: number) => Windows.Foundation.IPromise, error?: (error: any) => U, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: number) => U, error?: (error: any) => Windows.Foundation.IPromise, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: number) => Windows.Foundation.IPromise, error?: (error: any) => Windows.Foundation.IPromise, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - done(success?: (value: number) => any, error?: (error: any) => any, progress?: (progress: any) => void ): void; - operation: { - completed: Windows.Foundation.AsyncOperationCompletedHandler; - getResults(): number; - } - } - export interface IDataReader { - byteOrder: Windows.Storage.Streams.ByteOrder; - inputStreamOptions: Windows.Storage.Streams.InputStreamOptions; - unconsumedBufferLength: number; - unicodeEncoding: Windows.Storage.Streams.UnicodeEncoding; - readByte(): number; - readBytes(): Uint8Array; - readBuffer(length: number): Windows.Storage.Streams.IBuffer; - readBoolean(): boolean; - readGuid(): string; - readInt16(): number; - readInt32(): number; - readInt64(): number; - readUInt16(): number; - readUInt32(): number; - readUInt64(): number; - readSingle(): number; - readDouble(): number; - readString(codeUnitCount: number): string; - readDateTime(): Date; - readTimeSpan(): number; - loadAsync(count: number): Windows.Storage.Streams.DataReaderLoadOperation; - detachBuffer(): Windows.Storage.Streams.IBuffer; - detachStream(): Windows.Storage.Streams.IInputStream; - } - export interface IDataReaderFactory { - createDataReader(inputStream: Windows.Storage.Streams.IInputStream): Windows.Storage.Streams.DataReader; - } - export class DataReader implements Windows.Storage.Streams.IDataReader, Windows.Foundation.IClosable { - constructor(inputStream: Windows.Storage.Streams.IInputStream); - byteOrder: Windows.Storage.Streams.ByteOrder; - inputStreamOptions: Windows.Storage.Streams.InputStreamOptions; - unconsumedBufferLength: number; - unicodeEncoding: Windows.Storage.Streams.UnicodeEncoding; - readByte(): number; - readBytes(): Uint8Array; - readBuffer(length: number): Windows.Storage.Streams.IBuffer; - readBoolean(): boolean; - readGuid(): string; - readInt16(): number; - readInt32(): number; - readInt64(): number; - readUInt16(): number; - readUInt32(): number; - readUInt64(): number; - readSingle(): number; - readDouble(): number; - readString(codeUnitCount: number): string; - readDateTime(): Date; - readTimeSpan(): number; - loadAsync(count: number): Windows.Storage.Streams.DataReaderLoadOperation; - detachBuffer(): Windows.Storage.Streams.IBuffer; - detachStream(): Windows.Storage.Streams.IInputStream; - dispose(): void; - static fromBuffer(buffer: Windows.Storage.Streams.IBuffer): Windows.Storage.Streams.DataReader; - close(): void; - } - export interface IDataReaderStatics { - fromBuffer(buffer: Windows.Storage.Streams.IBuffer): Windows.Storage.Streams.DataReader; - } - export class DataWriterStoreOperation implements Windows.Foundation.IAsyncOperation, Windows.Foundation.IAsyncInfo { - completed: Windows.Foundation.AsyncOperationCompletedHandler; - errorCode: number; - id: number; - status: Windows.Foundation.AsyncStatus; - getResults(): number; - cancel(): void; - close(): void; - then(success?: (value: number) => U, error?: (error: any) => U, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: number) => Windows.Foundation.IPromise, error?: (error: any) => U, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: number) => U, error?: (error: any) => Windows.Foundation.IPromise, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: number) => Windows.Foundation.IPromise, error?: (error: any) => Windows.Foundation.IPromise, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - done(success?: (value: number) => any, error?: (error: any) => any, progress?: (progress: any) => void ): void; - operation: { - completed: Windows.Foundation.AsyncOperationCompletedHandler; - getResults(): number; - } - } - export interface IDataWriter { - byteOrder: Windows.Storage.Streams.ByteOrder; - unicodeEncoding: Windows.Storage.Streams.UnicodeEncoding; - unstoredBufferLength: number; - writeByte(value: number): void; - writeBytes(value: Uint8Array): void; - writeBuffer(buffer: Windows.Storage.Streams.IBuffer): void; - writeBuffer(buffer: Windows.Storage.Streams.IBuffer, start: number, count: number): void; - writeBoolean(value: boolean): void; - writeGuid(value: string): void; - writeInt16(value: number): void; - writeInt32(value: number): void; - writeInt64(value: number): void; - writeUInt16(value: number): void; - writeUInt32(value: number): void; - writeUInt64(value: number): void; - writeSingle(value: number): void; - writeDouble(value: number): void; - writeDateTime(value: Date): void; - writeTimeSpan(value: number): void; - writeString(value: string): number; - measureString(value: string): number; - storeAsync(): Windows.Storage.Streams.DataWriterStoreOperation; - flushAsync(): Windows.Foundation.IAsyncOperation; - detachBuffer(): Windows.Storage.Streams.IBuffer; - detachStream(): Windows.Storage.Streams.IOutputStream; - } - export interface IDataWriterFactory { - createDataWriter(outputStream: Windows.Storage.Streams.IOutputStream): Windows.Storage.Streams.DataWriter; - } - export class DataWriter implements Windows.Storage.Streams.IDataWriter, Windows.Foundation.IClosable { - constructor(outputStream: Windows.Storage.Streams.IOutputStream); - constructor(); - byteOrder: Windows.Storage.Streams.ByteOrder; - unicodeEncoding: Windows.Storage.Streams.UnicodeEncoding; - unstoredBufferLength: number; - writeByte(value: number): void; - writeBytes(value: Uint8Array): void; - writeBuffer(buffer: Windows.Storage.Streams.IBuffer): void; - writeBuffer(buffer: Windows.Storage.Streams.IBuffer, start: number, count: number): void; - writeBoolean(value: boolean): void; - writeGuid(value: string): void; - writeInt16(value: number): void; - writeInt32(value: number): void; - writeInt64(value: number): void; - writeUInt16(value: number): void; - writeUInt32(value: number): void; - writeUInt64(value: number): void; - writeSingle(value: number): void; - writeDouble(value: number): void; - writeDateTime(value: Date): void; - writeTimeSpan(value: number): void; - writeString(value: string): number; - measureString(value: string): number; - storeAsync(): Windows.Storage.Streams.DataWriterStoreOperation; - flushAsync(): Windows.Foundation.IAsyncOperation; - detachBuffer(): Windows.Storage.Streams.IBuffer; - detachStream(): Windows.Storage.Streams.IOutputStream; - dispose(): void; - close(): void; - } - export interface IRandomAccessStreamStatics { - copyAsync(source: Windows.Storage.Streams.IInputStream, destination: Windows.Storage.Streams.IOutputStream): Windows.Foundation.IAsyncOperationWithProgress; - copyAsync(source: Windows.Storage.Streams.IInputStream, destination: Windows.Storage.Streams.IOutputStream, bytesToCopy: number): Windows.Foundation.IAsyncOperationWithProgress; - copyAndCloseAsync(source: Windows.Storage.Streams.IInputStream, destination: Windows.Storage.Streams.IOutputStream): Windows.Foundation.IAsyncOperationWithProgress; - } - export class RandomAccessStream { - static copyAsync(source: Windows.Storage.Streams.IInputStream, destination: Windows.Storage.Streams.IOutputStream): Windows.Foundation.IAsyncOperationWithProgress; - static copyAsync(source: Windows.Storage.Streams.IInputStream, destination: Windows.Storage.Streams.IOutputStream, bytesToCopy: number): Windows.Foundation.IAsyncOperationWithProgress; - static copyAndCloseAsync(source: Windows.Storage.Streams.IInputStream, destination: Windows.Storage.Streams.IOutputStream): Windows.Foundation.IAsyncOperationWithProgress; - } - export interface IBufferFactory { - create(capacity: number): Windows.Storage.Streams.Buffer; - } - export class Buffer implements Windows.Storage.Streams.IBuffer { - constructor(capacity: number); - capacity: number; - length: number; - } - export interface IBuffer { - capacity: number; - length: number; - } - export enum InputStreamOptions { - none, - partial, - readAhead, - } - export interface IContentTypeProvider { - contentType: string; - } - export interface IRandomAccessStreamReference { - openReadAsync(): Windows.Foundation.IAsyncOperation; - } - export interface IInputStreamReference { - openSequentialReadAsync(): Windows.Foundation.IAsyncOperation; - } - export interface IRandomAccessStreamReferenceStatics { - createFromFile(file: Windows.Storage.IStorageFile): Windows.Storage.Streams.RandomAccessStreamReference; - createFromUri(uri: Windows.Foundation.Uri): Windows.Storage.Streams.RandomAccessStreamReference; - createFromStream(stream: Windows.Storage.Streams.IRandomAccessStream): Windows.Storage.Streams.RandomAccessStreamReference; - } - export class RandomAccessStreamReference implements Windows.Storage.Streams.IRandomAccessStreamReference { - openReadAsync(): Windows.Foundation.IAsyncOperation; - static createFromFile(file: Windows.Storage.IStorageFile): Windows.Storage.Streams.RandomAccessStreamReference; - static createFromUri(uri: Windows.Foundation.Uri): Windows.Storage.Streams.RandomAccessStreamReference; - static createFromStream(stream: Windows.Storage.Streams.IRandomAccessStream): Windows.Storage.Streams.RandomAccessStreamReference; - } - export class FileRandomAccessStream implements Windows.Storage.Streams.IRandomAccessStream, Windows.Foundation.IClosable, Windows.Storage.Streams.IInputStream, Windows.Storage.Streams.IOutputStream { - canRead: boolean; - canWrite: boolean; - position: number; - size: number; - getInputStreamAt(position: number): Windows.Storage.Streams.IInputStream; - getOutputStreamAt(position: number): Windows.Storage.Streams.IOutputStream; - seek(position: number): void; - cloneStream(): Windows.Storage.Streams.IRandomAccessStream; - dispose(): void; - readAsync(buffer: Windows.Storage.Streams.IBuffer, count: number, options: Windows.Storage.Streams.InputStreamOptions): Windows.Foundation.IAsyncOperationWithProgress; - writeAsync(buffer: Windows.Storage.Streams.IBuffer): Windows.Foundation.IAsyncOperationWithProgress; - flushAsync(): Windows.Foundation.IAsyncOperation; - close(): void; - } - export class FileInputStream implements Windows.Storage.Streams.IInputStream, Windows.Foundation.IClosable { - readAsync(buffer: Windows.Storage.Streams.IBuffer, count: number, options: Windows.Storage.Streams.InputStreamOptions): Windows.Foundation.IAsyncOperationWithProgress; - dispose(): void; - close(): void; - } - export class FileOutputStream implements Windows.Storage.Streams.IOutputStream, Windows.Foundation.IClosable { - writeAsync(buffer: Windows.Storage.Streams.IBuffer): Windows.Foundation.IAsyncOperationWithProgress; - flushAsync(): Windows.Foundation.IAsyncOperation; - dispose(): void; - close(): void; - } - export class RandomAccessStreamOverStream implements Windows.Storage.Streams.IRandomAccessStream, Windows.Foundation.IClosable, Windows.Storage.Streams.IInputStream, Windows.Storage.Streams.IOutputStream { - canRead: boolean; - canWrite: boolean; - position: number; - size: number; - getInputStreamAt(position: number): Windows.Storage.Streams.IInputStream; - getOutputStreamAt(position: number): Windows.Storage.Streams.IOutputStream; - seek(position: number): void; - cloneStream(): Windows.Storage.Streams.IRandomAccessStream; - dispose(): void; - readAsync(buffer: Windows.Storage.Streams.IBuffer, count: number, options: Windows.Storage.Streams.InputStreamOptions): Windows.Foundation.IAsyncOperationWithProgress; - writeAsync(buffer: Windows.Storage.Streams.IBuffer): Windows.Foundation.IAsyncOperationWithProgress; - flushAsync(): Windows.Foundation.IAsyncOperation; - close(): void; - } - export class InputStreamOverStream implements Windows.Storage.Streams.IInputStream, Windows.Foundation.IClosable { - readAsync(buffer: Windows.Storage.Streams.IBuffer, count: number, options: Windows.Storage.Streams.InputStreamOptions): Windows.Foundation.IAsyncOperationWithProgress; - dispose(): void; - close(): void; - } - export class OutputStreamOverStream implements Windows.Storage.Streams.IOutputStream, Windows.Foundation.IClosable { - writeAsync(buffer: Windows.Storage.Streams.IBuffer): Windows.Foundation.IAsyncOperationWithProgress; - flushAsync(): Windows.Foundation.IAsyncOperation; - dispose(): void; - close(): void; - } - export class InMemoryRandomAccessStream implements Windows.Storage.Streams.IRandomAccessStream, Windows.Foundation.IClosable, Windows.Storage.Streams.IInputStream, Windows.Storage.Streams.IOutputStream { - canRead: boolean; - canWrite: boolean; - position: number; - size: number; - getInputStreamAt(position: number): Windows.Storage.Streams.IInputStream; - getOutputStreamAt(position: number): Windows.Storage.Streams.IOutputStream; - seek(position: number): void; - cloneStream(): Windows.Storage.Streams.IRandomAccessStream; - dispose(): void; - readAsync(buffer: Windows.Storage.Streams.IBuffer, count: number, options: Windows.Storage.Streams.InputStreamOptions): Windows.Foundation.IAsyncOperationWithProgress; - writeAsync(buffer: Windows.Storage.Streams.IBuffer): Windows.Foundation.IAsyncOperationWithProgress; - flushAsync(): Windows.Foundation.IAsyncOperation; - close(): void; - } - export interface IInputStream extends Windows.Foundation.IClosable { - readAsync(buffer: Windows.Storage.Streams.IBuffer, count: number, options: Windows.Storage.Streams.InputStreamOptions): Windows.Foundation.IAsyncOperationWithProgress; - } - export interface IOutputStream extends Windows.Foundation.IClosable { - writeAsync(buffer: Windows.Storage.Streams.IBuffer): Windows.Foundation.IAsyncOperationWithProgress; - flushAsync(): Windows.Foundation.IAsyncOperation; - } - export interface IRandomAccessStream extends Windows.Foundation.IClosable, Windows.Storage.Streams.IInputStream, Windows.Storage.Streams.IOutputStream { - canRead: boolean; - canWrite: boolean; - position: number; - size: number; - getInputStreamAt(position: number): Windows.Storage.Streams.IInputStream; - getOutputStreamAt(position: number): Windows.Storage.Streams.IOutputStream; - seek(position: number): void; - cloneStream(): Windows.Storage.Streams.IRandomAccessStream; - } - export interface IRandomAccessStreamWithContentType extends Windows.Storage.Streams.IRandomAccessStream, Windows.Foundation.IClosable, Windows.Storage.Streams.IInputStream, Windows.Storage.Streams.IOutputStream, Windows.Storage.Streams.IContentTypeProvider { - } - } - } -} -declare module Windows { - export module Storage { - export module Pickers { - export module Provider { - export interface IFileRemovedEventArgs { - id: string; - } - export class FileRemovedEventArgs implements Windows.Storage.Pickers.Provider.IFileRemovedEventArgs { - id: string; - } - export enum AddFileResult { - added, - alreadyAdded, - notAllowed, - unavailable, - } - export enum FileSelectionMode { - single, - multiple, - } - export interface IFileOpenPickerUI { - allowedFileTypes: Windows.Foundation.Collections.IVectorView; - selectionMode: Windows.Storage.Pickers.Provider.FileSelectionMode; - settingsIdentifier: string; - title: string; - addFile(id: string, file: Windows.Storage.IStorageFile): Windows.Storage.Pickers.Provider.AddFileResult; - removeFile(id: string): void; - containsFile(id: string): boolean; - canAddFile(file: Windows.Storage.IStorageFile): boolean; - onfileremoved: any/* TODO */; - onclosing: any/* TODO */; - } - export class FileOpenPickerUI implements Windows.Storage.Pickers.Provider.IFileOpenPickerUI { - allowedFileTypes: Windows.Foundation.Collections.IVectorView; - selectionMode: Windows.Storage.Pickers.Provider.FileSelectionMode; - settingsIdentifier: string; - title: string; - addFile(id: string, file: Windows.Storage.IStorageFile): Windows.Storage.Pickers.Provider.AddFileResult; - removeFile(id: string): void; - containsFile(id: string): boolean; - canAddFile(file: Windows.Storage.IStorageFile): boolean; - onfileremoved: any/* TODO */; - onclosing: any/* TODO */; - } - export class PickerClosingEventArgs implements Windows.Storage.Pickers.Provider.IPickerClosingEventArgs { - closingOperation: Windows.Storage.Pickers.Provider.PickerClosingOperation; - isCanceled: boolean; - } - export interface IPickerClosingEventArgs { - closingOperation: Windows.Storage.Pickers.Provider.PickerClosingOperation; - isCanceled: boolean; - } - export class PickerClosingOperation implements Windows.Storage.Pickers.Provider.IPickerClosingOperation { - deadline: Date; - getDeferral(): Windows.Storage.Pickers.Provider.PickerClosingDeferral; - } - export interface IPickerClosingOperation { - deadline: Date; - getDeferral(): Windows.Storage.Pickers.Provider.PickerClosingDeferral; - } - export class PickerClosingDeferral implements Windows.Storage.Pickers.Provider.IPickerClosingDeferral { - complete(): void; - } - export interface IPickerClosingDeferral { - complete(): void; - } - export enum SetFileNameResult { - succeeded, - notAllowed, - unavailable, - } - export interface IFileSavePickerUI { - allowedFileTypes: Windows.Foundation.Collections.IVectorView; - fileName: string; - settingsIdentifier: string; - title: string; - trySetFileName(value: string): Windows.Storage.Pickers.Provider.SetFileNameResult; - onfilenamechanged: any/* TODO */; - ontargetfilerequested: any/* TODO */; - } - export class FileSavePickerUI implements Windows.Storage.Pickers.Provider.IFileSavePickerUI { - allowedFileTypes: Windows.Foundation.Collections.IVectorView; - fileName: string; - settingsIdentifier: string; - title: string; - trySetFileName(value: string): Windows.Storage.Pickers.Provider.SetFileNameResult; - onfilenamechanged: any/* TODO */; - ontargetfilerequested: any/* TODO */; - } - export class TargetFileRequestedEventArgs implements Windows.Storage.Pickers.Provider.ITargetFileRequestedEventArgs { - request: Windows.Storage.Pickers.Provider.TargetFileRequest; - } - export interface ITargetFileRequestedEventArgs { - request: Windows.Storage.Pickers.Provider.TargetFileRequest; - } - export class TargetFileRequest implements Windows.Storage.Pickers.Provider.ITargetFileRequest { - targetFile: Windows.Storage.IStorageFile; - getDeferral(): Windows.Storage.Pickers.Provider.TargetFileRequestDeferral; - } - export interface ITargetFileRequest { - targetFile: Windows.Storage.IStorageFile; - getDeferral(): Windows.Storage.Pickers.Provider.TargetFileRequestDeferral; - } - export class TargetFileRequestDeferral implements Windows.Storage.Pickers.Provider.ITargetFileRequestDeferral { - complete(): void; - } - export interface ITargetFileRequestDeferral { - complete(): void; - } - } - } - } -} -declare module Windows { - export module Storage { - export module Provider { - export enum CachedFileTarget { - local, - remote, - } - export enum UIStatus { - unavailable, - hidden, - visible, - complete, - } - export interface ICachedFileUpdaterUI { - title: string; - uIStatus: Windows.Storage.Provider.UIStatus; - updateTarget: Windows.Storage.Provider.CachedFileTarget; - onfileupdaterequested: any/* TODO */; - onuirequested: any/* TODO */; - } - export class CachedFileUpdaterUI implements Windows.Storage.Provider.ICachedFileUpdaterUI { - title: string; - uIStatus: Windows.Storage.Provider.UIStatus; - updateTarget: Windows.Storage.Provider.CachedFileTarget; - onfileupdaterequested: any/* TODO */; - onuirequested: any/* TODO */; - } - export class FileUpdateRequestedEventArgs implements Windows.Storage.Provider.IFileUpdateRequestedEventArgs { - request: Windows.Storage.Provider.FileUpdateRequest; - } - export interface IFileUpdateRequestedEventArgs { - request: Windows.Storage.Provider.FileUpdateRequest; - } - export class FileUpdateRequest implements Windows.Storage.Provider.IFileUpdateRequest { - contentId: string; - file: Windows.Storage.StorageFile; - status: Windows.Storage.Provider.FileUpdateStatus; - getDeferral(): Windows.Storage.Provider.FileUpdateRequestDeferral; - updateLocalFile(value: Windows.Storage.IStorageFile): void; - } - export interface IFileUpdateRequest { - contentId: string; - file: Windows.Storage.StorageFile; - status: Windows.Storage.Provider.FileUpdateStatus; - getDeferral(): Windows.Storage.Provider.FileUpdateRequestDeferral; - updateLocalFile(value: Windows.Storage.IStorageFile): void; - } - export class FileUpdateRequestDeferral implements Windows.Storage.Provider.IFileUpdateRequestDeferral { - complete(): void; - } - export interface IFileUpdateRequestDeferral { - complete(): void; - } - export enum FileUpdateStatus { - incomplete, - complete, - userInputNeeded, - currentlyUnavailable, - failed, - completeAndRenamed, - } - export enum CachedFileOptions { - none, - requireUpdateOnAccess, - useCachedFileWhenOffline, - denyAccessWhenOffline, - } - export enum ReadActivationMode { - notNeeded, - beforeAccess, - } - export enum WriteActivationMode { - readOnly, - notNeeded, - afterWrite, - } - export interface ICachedFileUpdaterStatics { - setUpdateInformation(file: Windows.Storage.IStorageFile, contentId: string, readMode: Windows.Storage.Provider.ReadActivationMode, writeMode: Windows.Storage.Provider.WriteActivationMode, options: Windows.Storage.Provider.CachedFileOptions): void; - } - export class CachedFileUpdater { - static setUpdateInformation(file: Windows.Storage.IStorageFile, contentId: string, readMode: Windows.Storage.Provider.ReadActivationMode, writeMode: Windows.Storage.Provider.WriteActivationMode, options: Windows.Storage.Provider.CachedFileOptions): void; - } - } - } -} -declare module Windows { - export module Storage { - export module FileProperties { - export enum PropertyPrefetchOptions { - none, - musicProperties, - videoProperties, - imageProperties, - documentProperties, - basicProperties, - } - export enum ThumbnailType { - image, - icon, - } - export interface IThumbnailProperties { - originalHeight: number; - originalWidth: number; - returnedSmallerCachedSize: boolean; - type: Windows.Storage.FileProperties.ThumbnailType; - } - export class StorageItemThumbnail implements Windows.Storage.Streams.IRandomAccessStreamWithContentType, Windows.Storage.Streams.IRandomAccessStream, Windows.Foundation.IClosable, Windows.Storage.Streams.IInputStream, Windows.Storage.Streams.IOutputStream, Windows.Storage.Streams.IContentTypeProvider, Windows.Storage.FileProperties.IThumbnailProperties { - canRead: boolean; - canWrite: boolean; - position: number; - size: number; - contentType: string; - originalHeight: number; - originalWidth: number; - returnedSmallerCachedSize: boolean; - type: Windows.Storage.FileProperties.ThumbnailType; - getInputStreamAt(position: number): Windows.Storage.Streams.IInputStream; - getOutputStreamAt(position: number): Windows.Storage.Streams.IOutputStream; - seek(position: number): void; - cloneStream(): Windows.Storage.Streams.IRandomAccessStream; - dispose(): void; - readAsync(buffer: Windows.Storage.Streams.IBuffer, count: number, options: Windows.Storage.Streams.InputStreamOptions): Windows.Foundation.IAsyncOperationWithProgress; - writeAsync(buffer: Windows.Storage.Streams.IBuffer): Windows.Foundation.IAsyncOperationWithProgress; - flushAsync(): Windows.Foundation.IAsyncOperation; - close(): void; - } - export enum ThumbnailMode { - picturesView, - videosView, - musicView, - documentsView, - listView, - singleItem, - } - export enum ThumbnailOptions { - none, - returnOnlyIfCached, - resizeThumbnail, - useCurrentScale, - } - export enum PhotoOrientation { - unspecified, - normal, - flipHorizontal, - rotate180, - flipVertical, - transpose, - rotate270, - transverse, - rotate90, - } - export enum VideoOrientation { - normal, - rotate90, - rotate180, - rotate270, - } - export interface IStorageItemExtraProperties { - retrievePropertiesAsync(propertiesToRetrieve: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncOperation>; - savePropertiesAsync(propertiesToSave: Windows.Foundation.Collections.IIterable>): Windows.Foundation.IAsyncAction; - savePropertiesAsync(): Windows.Foundation.IAsyncAction; - } - export interface IStorageItemContentProperties extends Windows.Storage.FileProperties.IStorageItemExtraProperties { - getMusicPropertiesAsync(): Windows.Foundation.IAsyncOperation; - getVideoPropertiesAsync(): Windows.Foundation.IAsyncOperation; - getImagePropertiesAsync(): Windows.Foundation.IAsyncOperation; - getDocumentPropertiesAsync(): Windows.Foundation.IAsyncOperation; - } - export class MusicProperties implements Windows.Storage.FileProperties.IMusicProperties, Windows.Storage.FileProperties.IStorageItemExtraProperties { - album: string; - albumArtist: string; - artist: string; - bitrate: number; - composers: Windows.Foundation.Collections.IVector; - conductors: Windows.Foundation.Collections.IVector; - duration: number; - genre: Windows.Foundation.Collections.IVector; - producers: Windows.Foundation.Collections.IVector; - publisher: string; - rating: number; - subtitle: string; - title: string; - trackNumber: number; - writers: Windows.Foundation.Collections.IVector; - year: number; - retrievePropertiesAsync(propertiesToRetrieve: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncOperation>; - savePropertiesAsync(propertiesToSave: Windows.Foundation.Collections.IIterable>): Windows.Foundation.IAsyncAction; - savePropertiesAsync(): Windows.Foundation.IAsyncAction; - } - export class VideoProperties implements Windows.Storage.FileProperties.IVideoProperties, Windows.Storage.FileProperties.IStorageItemExtraProperties { - bitrate: number; - directors: Windows.Foundation.Collections.IVector; - duration: number; - height: number; - keywords: Windows.Foundation.Collections.IVector; - latitude: number; - longitude: number; - orientation: Windows.Storage.FileProperties.VideoOrientation; - producers: Windows.Foundation.Collections.IVector; - publisher: string; - rating: number; - subtitle: string; - title: string; - width: number; - writers: Windows.Foundation.Collections.IVector; - year: number; - retrievePropertiesAsync(propertiesToRetrieve: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncOperation>; - savePropertiesAsync(propertiesToSave: Windows.Foundation.Collections.IIterable>): Windows.Foundation.IAsyncAction; - savePropertiesAsync(): Windows.Foundation.IAsyncAction; - } - export class ImageProperties implements Windows.Storage.FileProperties.IImageProperties, Windows.Storage.FileProperties.IStorageItemExtraProperties { - cameraManufacturer: string; - cameraModel: string; - dateTaken: Date; - height: number; - keywords: Windows.Foundation.Collections.IVector; - latitude: number; - longitude: number; - orientation: Windows.Storage.FileProperties.PhotoOrientation; - peopleNames: Windows.Foundation.Collections.IVectorView; - rating: number; - title: string; - width: number; - retrievePropertiesAsync(propertiesToRetrieve: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncOperation>; - savePropertiesAsync(propertiesToSave: Windows.Foundation.Collections.IIterable>): Windows.Foundation.IAsyncAction; - savePropertiesAsync(): Windows.Foundation.IAsyncAction; - } - export class DocumentProperties implements Windows.Storage.FileProperties.IDocumentProperties, Windows.Storage.FileProperties.IStorageItemExtraProperties { - author: Windows.Foundation.Collections.IVector; - comment: string; - keywords: Windows.Foundation.Collections.IVector; - title: string; - retrievePropertiesAsync(propertiesToRetrieve: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncOperation>; - savePropertiesAsync(propertiesToSave: Windows.Foundation.Collections.IIterable>): Windows.Foundation.IAsyncAction; - savePropertiesAsync(): Windows.Foundation.IAsyncAction; - } - export interface IMusicProperties extends Windows.Storage.FileProperties.IStorageItemExtraProperties { - album: string; - albumArtist: string; - artist: string; - bitrate: number; - composers: Windows.Foundation.Collections.IVector; - conductors: Windows.Foundation.Collections.IVector; - duration: number; - genre: Windows.Foundation.Collections.IVector; - producers: Windows.Foundation.Collections.IVector; - publisher: string; - rating: number; - subtitle: string; - title: string; - trackNumber: number; - writers: Windows.Foundation.Collections.IVector; - year: number; - } - export interface IImageProperties extends Windows.Storage.FileProperties.IStorageItemExtraProperties { - cameraManufacturer: string; - cameraModel: string; - dateTaken: Date; - height: number; - keywords: Windows.Foundation.Collections.IVector; - latitude: number; - longitude: number; - orientation: Windows.Storage.FileProperties.PhotoOrientation; - peopleNames: Windows.Foundation.Collections.IVectorView; - rating: number; - title: string; - width: number; - } - export interface IVideoProperties extends Windows.Storage.FileProperties.IStorageItemExtraProperties { - bitrate: number; - directors: Windows.Foundation.Collections.IVector; - duration: number; - height: number; - keywords: Windows.Foundation.Collections.IVector; - latitude: number; - longitude: number; - orientation: Windows.Storage.FileProperties.VideoOrientation; - producers: Windows.Foundation.Collections.IVector; - publisher: string; - rating: number; - subtitle: string; - title: string; - width: number; - writers: Windows.Foundation.Collections.IVector; - year: number; - } - export interface IDocumentProperties extends Windows.Storage.FileProperties.IStorageItemExtraProperties { - author: Windows.Foundation.Collections.IVector; - comment: string; - keywords: Windows.Foundation.Collections.IVector; - title: string; - } - export interface IBasicProperties { - dateModified: Date; - itemDate: Date; - size: number; - } - export class StorageItemContentProperties implements Windows.Storage.FileProperties.IStorageItemContentProperties, Windows.Storage.FileProperties.IStorageItemExtraProperties { - getMusicPropertiesAsync(): Windows.Foundation.IAsyncOperation; - getVideoPropertiesAsync(): Windows.Foundation.IAsyncOperation; - getImagePropertiesAsync(): Windows.Foundation.IAsyncOperation; - getDocumentPropertiesAsync(): Windows.Foundation.IAsyncOperation; - retrievePropertiesAsync(propertiesToRetrieve: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncOperation>; - savePropertiesAsync(propertiesToSave: Windows.Foundation.Collections.IIterable>): Windows.Foundation.IAsyncAction; - savePropertiesAsync(): Windows.Foundation.IAsyncAction; - } - export class BasicProperties implements Windows.Storage.FileProperties.IBasicProperties, Windows.Storage.FileProperties.IStorageItemExtraProperties { - dateModified: Date; - itemDate: Date; - size: number; - retrievePropertiesAsync(propertiesToRetrieve: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncOperation>; - savePropertiesAsync(propertiesToSave: Windows.Foundation.Collections.IIterable>): Windows.Foundation.IAsyncAction; - savePropertiesAsync(): Windows.Foundation.IAsyncAction; - } - } - } -} -declare module Windows { - export module Storage { - export interface IKnownFoldersStatics { - documentsLibrary: Windows.Storage.StorageFolder; - homeGroup: Windows.Storage.StorageFolder; - mediaServerDevices: Windows.Storage.StorageFolder; - musicLibrary: Windows.Storage.StorageFolder; - picturesLibrary: Windows.Storage.StorageFolder; - removableDevices: Windows.Storage.StorageFolder; - videosLibrary: Windows.Storage.StorageFolder; - } - export class StorageFolder implements Windows.Storage.IStorageFolder, Windows.Storage.IStorageItem, Windows.Storage.Search.IStorageFolderQueryOperations, Windows.Storage.IStorageItemProperties { - attributes: Windows.Storage.FileAttributes; - dateCreated: Date; - name: string; - path: string; - displayName: string; - displayType: string; - folderRelativeId: string; - properties: Windows.Storage.FileProperties.StorageItemContentProperties; - createFileAsync(desiredName: string): Windows.Foundation.IAsyncOperation; - createFileAsync(desiredName: string, options: Windows.Storage.CreationCollisionOption): Windows.Foundation.IAsyncOperation; - createFolderAsync(desiredName: string): Windows.Foundation.IAsyncOperation; - createFolderAsync(desiredName: string, options: Windows.Storage.CreationCollisionOption): Windows.Foundation.IAsyncOperation; - getFileAsync(name: string): Windows.Foundation.IAsyncOperation; - getFolderAsync(name: string): Windows.Foundation.IAsyncOperation; - getItemAsync(name: string): Windows.Foundation.IAsyncOperation; - getFilesAsync(): Windows.Foundation.IAsyncOperation>; - getFoldersAsync(): Windows.Foundation.IAsyncOperation>; - getItemsAsync(): Windows.Foundation.IAsyncOperation>; - renameAsync(desiredName: string): Windows.Foundation.IAsyncAction; - renameAsync(desiredName: string, option: Windows.Storage.NameCollisionOption): Windows.Foundation.IAsyncAction; - deleteAsync(): Windows.Foundation.IAsyncAction; - deleteAsync(option: Windows.Storage.StorageDeleteOption): Windows.Foundation.IAsyncAction; - getBasicPropertiesAsync(): Windows.Foundation.IAsyncOperation; - isOfType(type: Windows.Storage.StorageItemTypes): boolean; - getIndexedStateAsync(): Windows.Foundation.IAsyncOperation; - createFileQuery(): Windows.Storage.Search.StorageFileQueryResult; - createFileQuery(query: Windows.Storage.Search.CommonFileQuery): Windows.Storage.Search.StorageFileQueryResult; - createFileQueryWithOptions(queryOptions: Windows.Storage.Search.QueryOptions): Windows.Storage.Search.StorageFileQueryResult; - createFolderQuery(): Windows.Storage.Search.StorageFolderQueryResult; - createFolderQuery(query: Windows.Storage.Search.CommonFolderQuery): Windows.Storage.Search.StorageFolderQueryResult; - createFolderQueryWithOptions(queryOptions: Windows.Storage.Search.QueryOptions): Windows.Storage.Search.StorageFolderQueryResult; - createItemQuery(): Windows.Storage.Search.StorageItemQueryResult; - createItemQueryWithOptions(queryOptions: Windows.Storage.Search.QueryOptions): Windows.Storage.Search.StorageItemQueryResult; - getFilesAsync(query: Windows.Storage.Search.CommonFileQuery, startIndex: number, maxItemsToRetrieve: number): Windows.Foundation.IAsyncOperation>; - getFilesAsync(query: Windows.Storage.Search.CommonFileQuery): Windows.Foundation.IAsyncOperation>; - getFoldersAsync(query: Windows.Storage.Search.CommonFolderQuery, startIndex: number, maxItemsToRetrieve: number): Windows.Foundation.IAsyncOperation>; - getFoldersAsync(query: Windows.Storage.Search.CommonFolderQuery): Windows.Foundation.IAsyncOperation>; - getItemsAsync(startIndex: number, maxItemsToRetrieve: number): Windows.Foundation.IAsyncOperation>; - areQueryOptionsSupported(queryOptions: Windows.Storage.Search.QueryOptions): boolean; - isCommonFolderQuerySupported(query: Windows.Storage.Search.CommonFolderQuery): boolean; - isCommonFileQuerySupported(query: Windows.Storage.Search.CommonFileQuery): boolean; - getThumbnailAsync(mode: Windows.Storage.FileProperties.ThumbnailMode): Windows.Foundation.IAsyncOperation; - getThumbnailAsync(mode: Windows.Storage.FileProperties.ThumbnailMode, requestedSize: number): Windows.Foundation.IAsyncOperation; - getThumbnailAsync(mode: Windows.Storage.FileProperties.ThumbnailMode, requestedSize: number, options: Windows.Storage.FileProperties.ThumbnailOptions): Windows.Foundation.IAsyncOperation; - static getFolderFromPathAsync(path: string): Windows.Foundation.IAsyncOperation; - } - export class KnownFolders { - static documentsLibrary: Windows.Storage.StorageFolder; - static homeGroup: Windows.Storage.StorageFolder; - static mediaServerDevices: Windows.Storage.StorageFolder; - static musicLibrary: Windows.Storage.StorageFolder; - static picturesLibrary: Windows.Storage.StorageFolder; - static removableDevices: Windows.Storage.StorageFolder; - static videosLibrary: Windows.Storage.StorageFolder; - } - export enum CreationCollisionOption { - generateUniqueName, - replaceExisting, - failIfExists, - openIfExists, - } - export interface IDownloadsFolderStatics { - createFileAsync(desiredName: string): Windows.Foundation.IAsyncOperation; - createFolderAsync(desiredName: string): Windows.Foundation.IAsyncOperation; - createFileAsync(desiredName: string, option: Windows.Storage.CreationCollisionOption): Windows.Foundation.IAsyncOperation; - createFolderAsync(desiredName: string, option: Windows.Storage.CreationCollisionOption): Windows.Foundation.IAsyncOperation; - } - export class StorageFile implements Windows.Storage.IStorageFile, Windows.Storage.IStorageItem, Windows.Storage.Streams.IRandomAccessStreamReference, Windows.Storage.Streams.IInputStreamReference, Windows.Storage.IStorageItemProperties { - contentType: string; - fileType: string; - attributes: Windows.Storage.FileAttributes; - dateCreated: Date; - name: string; - path: string; - displayName: string; - displayType: string; - folderRelativeId: string; - properties: Windows.Storage.FileProperties.StorageItemContentProperties; - openAsync(accessMode: Windows.Storage.FileAccessMode): Windows.Foundation.IAsyncOperation; - openTransactedWriteAsync(): Windows.Foundation.IAsyncOperation; - copyAsync(destinationFolder: Windows.Storage.IStorageFolder): Windows.Foundation.IAsyncOperation; - copyAsync(destinationFolder: Windows.Storage.IStorageFolder, desiredNewName: string): Windows.Foundation.IAsyncOperation; - copyAsync(destinationFolder: Windows.Storage.IStorageFolder, desiredNewName: string, option: Windows.Storage.NameCollisionOption): Windows.Foundation.IAsyncOperation; - copyAndReplaceAsync(fileToReplace: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncAction; - moveAsync(destinationFolder: Windows.Storage.IStorageFolder): Windows.Foundation.IAsyncAction; - moveAsync(destinationFolder: Windows.Storage.IStorageFolder, desiredNewName: string): Windows.Foundation.IAsyncAction; - moveAsync(destinationFolder: Windows.Storage.IStorageFolder, desiredNewName: string, option: Windows.Storage.NameCollisionOption): Windows.Foundation.IAsyncAction; - moveAndReplaceAsync(fileToReplace: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncAction; - renameAsync(desiredName: string): Windows.Foundation.IAsyncAction; - renameAsync(desiredName: string, option: Windows.Storage.NameCollisionOption): Windows.Foundation.IAsyncAction; - deleteAsync(): Windows.Foundation.IAsyncAction; - deleteAsync(option: Windows.Storage.StorageDeleteOption): Windows.Foundation.IAsyncAction; - getBasicPropertiesAsync(): Windows.Foundation.IAsyncOperation; - isOfType(type: Windows.Storage.StorageItemTypes): boolean; - openReadAsync(): Windows.Foundation.IAsyncOperation; - openSequentialReadAsync(): Windows.Foundation.IAsyncOperation; - getThumbnailAsync(mode: Windows.Storage.FileProperties.ThumbnailMode): Windows.Foundation.IAsyncOperation; - getThumbnailAsync(mode: Windows.Storage.FileProperties.ThumbnailMode, requestedSize: number): Windows.Foundation.IAsyncOperation; - getThumbnailAsync(mode: Windows.Storage.FileProperties.ThumbnailMode, requestedSize: number, options: Windows.Storage.FileProperties.ThumbnailOptions): Windows.Foundation.IAsyncOperation; - static getFileFromPathAsync(path: string): Windows.Foundation.IAsyncOperation; - static getFileFromApplicationUriAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperation; - static createStreamedFileAsync(displayNameWithExtension: string, dataRequested: Windows.Storage.StreamedFileDataRequestedHandler, thumbnail: Windows.Storage.Streams.IRandomAccessStreamReference): Windows.Foundation.IAsyncOperation; - static replaceWithStreamedFileAsync(fileToReplace: Windows.Storage.IStorageFile, dataRequested: Windows.Storage.StreamedFileDataRequestedHandler, thumbnail: Windows.Storage.Streams.IRandomAccessStreamReference): Windows.Foundation.IAsyncOperation; - static createStreamedFileFromUriAsync(displayNameWithExtension: string, uri: Windows.Foundation.Uri, thumbnail: Windows.Storage.Streams.IRandomAccessStreamReference): Windows.Foundation.IAsyncOperation; - static replaceWithStreamedFileFromUriAsync(fileToReplace: Windows.Storage.IStorageFile, uri: Windows.Foundation.Uri, thumbnail: Windows.Storage.Streams.IRandomAccessStreamReference): Windows.Foundation.IAsyncOperation; - } - export class DownloadsFolder { - static createFileAsync(desiredName: string): Windows.Foundation.IAsyncOperation; - static createFolderAsync(desiredName: string): Windows.Foundation.IAsyncOperation; - static createFileAsync(desiredName: string, option: Windows.Storage.CreationCollisionOption): Windows.Foundation.IAsyncOperation; - static createFolderAsync(desiredName: string, option: Windows.Storage.CreationCollisionOption): Windows.Foundation.IAsyncOperation; - } - export enum NameCollisionOption { - generateUniqueName, - replaceExisting, - failIfExists, - } - export enum StorageDeleteOption { - default, - permanentDelete, - } - export enum StorageItemTypes { - none, - file, - folder, - } - export enum FileAttributes { - normal, - readOnly, - directory, - archive, - temporary, - } - export enum FileAccessMode { - read, - readWrite, - } - export enum StreamedFileFailureMode { - failed, - currentlyUnavailable, - incomplete, - } - export interface IStreamedFileDataRequest { - failAndClose(failureMode: Windows.Storage.StreamedFileFailureMode): void; - } - export class StreamedFileDataRequest implements Windows.Storage.Streams.IOutputStream, Windows.Foundation.IClosable, Windows.Storage.IStreamedFileDataRequest { - writeAsync(buffer: Windows.Storage.Streams.IBuffer): Windows.Foundation.IAsyncOperationWithProgress; - flushAsync(): Windows.Foundation.IAsyncOperation; - dispose(): void; - failAndClose(failureMode: Windows.Storage.StreamedFileFailureMode): void; - close(): void; - } - export interface StreamedFileDataRequestedHandler { - (stream: Windows.Storage.StreamedFileDataRequest): void; - } - export interface IStorageFileStatics { - getFileFromPathAsync(path: string): Windows.Foundation.IAsyncOperation; - getFileFromApplicationUriAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperation; - createStreamedFileAsync(displayNameWithExtension: string, dataRequested: Windows.Storage.StreamedFileDataRequestedHandler, thumbnail: Windows.Storage.Streams.IRandomAccessStreamReference): Windows.Foundation.IAsyncOperation; - replaceWithStreamedFileAsync(fileToReplace: Windows.Storage.IStorageFile, dataRequested: Windows.Storage.StreamedFileDataRequestedHandler, thumbnail: Windows.Storage.Streams.IRandomAccessStreamReference): Windows.Foundation.IAsyncOperation; - createStreamedFileFromUriAsync(displayNameWithExtension: string, uri: Windows.Foundation.Uri, thumbnail: Windows.Storage.Streams.IRandomAccessStreamReference): Windows.Foundation.IAsyncOperation; - replaceWithStreamedFileFromUriAsync(fileToReplace: Windows.Storage.IStorageFile, uri: Windows.Foundation.Uri, thumbnail: Windows.Storage.Streams.IRandomAccessStreamReference): Windows.Foundation.IAsyncOperation; - } - export class StorageStreamTransaction implements Windows.Storage.IStorageStreamTransaction, Windows.Foundation.IClosable { - stream: Windows.Storage.Streams.IRandomAccessStream; - commitAsync(): Windows.Foundation.IAsyncAction; - dispose(): void; - close(): void; - } - export interface IStorageItem { - attributes: Windows.Storage.FileAttributes; - dateCreated: Date; - name: string; - path: string; - renameAsync(desiredName: string): Windows.Foundation.IAsyncAction; - renameAsync(desiredName: string, option: Windows.Storage.NameCollisionOption): Windows.Foundation.IAsyncAction; - deleteAsync(): Windows.Foundation.IAsyncAction; - deleteAsync(option: Windows.Storage.StorageDeleteOption): Windows.Foundation.IAsyncAction; - getBasicPropertiesAsync(): Windows.Foundation.IAsyncOperation; - isOfType(type: Windows.Storage.StorageItemTypes): boolean; - } - export interface IStorageFolder extends Windows.Storage.IStorageItem { - createFileAsync(desiredName: string): Windows.Foundation.IAsyncOperation; - createFileAsync(desiredName: string, options: Windows.Storage.CreationCollisionOption): Windows.Foundation.IAsyncOperation; - createFolderAsync(desiredName: string): Windows.Foundation.IAsyncOperation; - createFolderAsync(desiredName: string, options: Windows.Storage.CreationCollisionOption): Windows.Foundation.IAsyncOperation; - getFileAsync(name: string): Windows.Foundation.IAsyncOperation; - getFolderAsync(name: string): Windows.Foundation.IAsyncOperation; - getItemAsync(name: string): Windows.Foundation.IAsyncOperation; - getFilesAsync(): Windows.Foundation.IAsyncOperation>; - getFoldersAsync(): Windows.Foundation.IAsyncOperation>; - getItemsAsync(): Windows.Foundation.IAsyncOperation>; - } - export interface IStorageFile extends Windows.Storage.IStorageItem, Windows.Storage.Streams.IRandomAccessStreamReference, Windows.Storage.Streams.IInputStreamReference { - contentType: string; - fileType: string; - openAsync(accessMode: Windows.Storage.FileAccessMode): Windows.Foundation.IAsyncOperation; - openTransactedWriteAsync(): Windows.Foundation.IAsyncOperation; - copyAsync(destinationFolder: Windows.Storage.IStorageFolder): Windows.Foundation.IAsyncOperation; - copyAsync(destinationFolder: Windows.Storage.IStorageFolder, desiredNewName: string): Windows.Foundation.IAsyncOperation; - copyAsync(destinationFolder: Windows.Storage.IStorageFolder, desiredNewName: string, option: Windows.Storage.NameCollisionOption): Windows.Foundation.IAsyncOperation; - copyAndReplaceAsync(fileToReplace: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncAction; - moveAsync(destinationFolder: Windows.Storage.IStorageFolder): Windows.Foundation.IAsyncAction; - moveAsync(destinationFolder: Windows.Storage.IStorageFolder, desiredNewName: string): Windows.Foundation.IAsyncAction; - moveAsync(destinationFolder: Windows.Storage.IStorageFolder, desiredNewName: string, option: Windows.Storage.NameCollisionOption): Windows.Foundation.IAsyncAction; - moveAndReplaceAsync(fileToReplace: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncAction; - } - export interface IStorageFolderStatics { - getFolderFromPathAsync(path: string): Windows.Foundation.IAsyncOperation; - } - export interface IStorageItemProperties { - displayName: string; - displayType: string; - folderRelativeId: string; - properties: Windows.Storage.FileProperties.StorageItemContentProperties; - getThumbnailAsync(mode: Windows.Storage.FileProperties.ThumbnailMode): Windows.Foundation.IAsyncOperation; - getThumbnailAsync(mode: Windows.Storage.FileProperties.ThumbnailMode, requestedSize: number): Windows.Foundation.IAsyncOperation; - getThumbnailAsync(mode: Windows.Storage.FileProperties.ThumbnailMode, requestedSize: number, options: Windows.Storage.FileProperties.ThumbnailOptions): Windows.Foundation.IAsyncOperation; - } - export interface IFileIOStatics { - readTextAsync(file: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncOperation; - readTextAsync(file: Windows.Storage.IStorageFile, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncOperation; - writeTextAsync(file: Windows.Storage.IStorageFile, contents: string): Windows.Foundation.IAsyncAction; - writeTextAsync(file: Windows.Storage.IStorageFile, contents: string, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncAction; - appendTextAsync(file: Windows.Storage.IStorageFile, contents: string): Windows.Foundation.IAsyncAction; - appendTextAsync(file: Windows.Storage.IStorageFile, contents: string, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncAction; - readLinesAsync(file: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncOperation>; - readLinesAsync(file: Windows.Storage.IStorageFile, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncOperation>; - writeLinesAsync(file: Windows.Storage.IStorageFile, lines: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncAction; - writeLinesAsync(file: Windows.Storage.IStorageFile, lines: Windows.Foundation.Collections.IIterable, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncAction; - appendLinesAsync(file: Windows.Storage.IStorageFile, lines: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncAction; - appendLinesAsync(file: Windows.Storage.IStorageFile, lines: Windows.Foundation.Collections.IIterable, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncAction; - readBufferAsync(file: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncOperation; - writeBufferAsync(file: Windows.Storage.IStorageFile, buffer: Windows.Storage.Streams.IBuffer): Windows.Foundation.IAsyncAction; - writeBytesAsync(file: Windows.Storage.IStorageFile, buffer: Uint8Array): Windows.Foundation.IAsyncAction; - } - export class FileIO { - static readTextAsync(file: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncOperation; - static readTextAsync(file: Windows.Storage.IStorageFile, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncOperation; - static writeTextAsync(file: Windows.Storage.IStorageFile, contents: string): Windows.Foundation.IAsyncAction; - static writeTextAsync(file: Windows.Storage.IStorageFile, contents: string, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncAction; - static appendTextAsync(file: Windows.Storage.IStorageFile, contents: string): Windows.Foundation.IAsyncAction; - static appendTextAsync(file: Windows.Storage.IStorageFile, contents: string, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncAction; - static readLinesAsync(file: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncOperation>; - static readLinesAsync(file: Windows.Storage.IStorageFile, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncOperation>; - static writeLinesAsync(file: Windows.Storage.IStorageFile, lines: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncAction; - static writeLinesAsync(file: Windows.Storage.IStorageFile, lines: Windows.Foundation.Collections.IIterable, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncAction; - static appendLinesAsync(file: Windows.Storage.IStorageFile, lines: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncAction; - static appendLinesAsync(file: Windows.Storage.IStorageFile, lines: Windows.Foundation.Collections.IIterable, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncAction; - static readBufferAsync(file: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncOperation; - static writeBufferAsync(file: Windows.Storage.IStorageFile, buffer: Windows.Storage.Streams.IBuffer): Windows.Foundation.IAsyncAction; - static writeBytesAsync(file: Windows.Storage.IStorageFile, buffer: Uint8Array): Windows.Foundation.IAsyncAction; - } - export interface IPathIOStatics { - readTextAsync(absolutePath: string): Windows.Foundation.IAsyncOperation; - readTextAsync(absolutePath: string, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncOperation; - writeTextAsync(absolutePath: string, contents: string): Windows.Foundation.IAsyncAction; - writeTextAsync(absolutePath: string, contents: string, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncAction; - appendTextAsync(absolutePath: string, contents: string): Windows.Foundation.IAsyncAction; - appendTextAsync(absolutePath: string, contents: string, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncAction; - readLinesAsync(absolutePath: string): Windows.Foundation.IAsyncOperation>; - readLinesAsync(absolutePath: string, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncOperation>; - writeLinesAsync(absolutePath: string, lines: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncAction; - writeLinesAsync(absolutePath: string, lines: Windows.Foundation.Collections.IIterable, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncAction; - appendLinesAsync(absolutePath: string, lines: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncAction; - appendLinesAsync(absolutePath: string, lines: Windows.Foundation.Collections.IIterable, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncAction; - readBufferAsync(absolutePath: string): Windows.Foundation.IAsyncOperation; - writeBufferAsync(absolutePath: string, buffer: Windows.Storage.Streams.IBuffer): Windows.Foundation.IAsyncAction; - writeBytesAsync(absolutePath: string, buffer: Uint8Array): Windows.Foundation.IAsyncAction; - } - export class PathIO { - static readTextAsync(absolutePath: string): Windows.Foundation.IAsyncOperation; - static readTextAsync(absolutePath: string, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncOperation; - static writeTextAsync(absolutePath: string, contents: string): Windows.Foundation.IAsyncAction; - static writeTextAsync(absolutePath: string, contents: string, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncAction; - static appendTextAsync(absolutePath: string, contents: string): Windows.Foundation.IAsyncAction; - static appendTextAsync(absolutePath: string, contents: string, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncAction; - static readLinesAsync(absolutePath: string): Windows.Foundation.IAsyncOperation>; - static readLinesAsync(absolutePath: string, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncOperation>; - static writeLinesAsync(absolutePath: string, lines: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncAction; - static writeLinesAsync(absolutePath: string, lines: Windows.Foundation.Collections.IIterable, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncAction; - static appendLinesAsync(absolutePath: string, lines: Windows.Foundation.Collections.IIterable): Windows.Foundation.IAsyncAction; - static appendLinesAsync(absolutePath: string, lines: Windows.Foundation.Collections.IIterable, encoding: Windows.Storage.Streams.UnicodeEncoding): Windows.Foundation.IAsyncAction; - static readBufferAsync(absolutePath: string): Windows.Foundation.IAsyncOperation; - static writeBufferAsync(absolutePath: string, buffer: Windows.Storage.Streams.IBuffer): Windows.Foundation.IAsyncAction; - static writeBytesAsync(absolutePath: string, buffer: Uint8Array): Windows.Foundation.IAsyncAction; - } - export interface ICachedFileManagerStatics { - deferUpdates(file: Windows.Storage.IStorageFile): void; - completeUpdatesAsync(file: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncOperation; - } - export class CachedFileManager { - static deferUpdates(file: Windows.Storage.IStorageFile): void; - static completeUpdatesAsync(file: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncOperation; - } - export interface IStorageStreamTransaction extends Windows.Foundation.IClosable { - stream: Windows.Storage.Streams.IRandomAccessStream; - commitAsync(): Windows.Foundation.IAsyncAction; - } - export enum ApplicationDataLocality { - local, - roaming, - temporary, - } - export enum ApplicationDataCreateDisposition { - always, - existing, - } - export interface IApplicationDataStatics { - current: Windows.Storage.ApplicationData; - } - export class ApplicationData implements Windows.Storage.IApplicationData { - localFolder: Windows.Storage.StorageFolder; - localSettings: Windows.Storage.ApplicationDataContainer; - roamingFolder: Windows.Storage.StorageFolder; - roamingSettings: Windows.Storage.ApplicationDataContainer; - roamingStorageQuota: number; - temporaryFolder: Windows.Storage.StorageFolder; - version: number; - setVersionAsync(desiredVersion: number, handler: Windows.Storage.ApplicationDataSetVersionHandler): Windows.Foundation.IAsyncAction; - clearAsync(): Windows.Foundation.IAsyncAction; - clearAsync(locality: Windows.Storage.ApplicationDataLocality): Windows.Foundation.IAsyncAction; - ondatachanged: any/* TODO */; - signalDataChanged(): void; - static current: Windows.Storage.ApplicationData; - } - export interface IApplicationData { - localFolder: Windows.Storage.StorageFolder; - localSettings: Windows.Storage.ApplicationDataContainer; - roamingFolder: Windows.Storage.StorageFolder; - roamingSettings: Windows.Storage.ApplicationDataContainer; - roamingStorageQuota: number; - temporaryFolder: Windows.Storage.StorageFolder; - version: number; - setVersionAsync(desiredVersion: number, handler: Windows.Storage.ApplicationDataSetVersionHandler): Windows.Foundation.IAsyncAction; - clearAsync(): Windows.Foundation.IAsyncAction; - clearAsync(locality: Windows.Storage.ApplicationDataLocality): Windows.Foundation.IAsyncAction; - ondatachanged: any/* TODO */; - signalDataChanged(): void; - } - export interface ApplicationDataSetVersionHandler { - (setVersionRequest: Windows.Storage.SetVersionRequest): void; - } - export class SetVersionRequest implements Windows.Storage.ISetVersionRequest { - currentVersion: number; - desiredVersion: number; - getDeferral(): Windows.Storage.SetVersionDeferral; - } - export class ApplicationDataContainer implements Windows.Storage.IApplicationDataContainer { - containers: Windows.Foundation.Collections.IMapView; - locality: Windows.Storage.ApplicationDataLocality; - name: string; - values: Windows.Foundation.Collections.IPropertySet; - createContainer(name: string, disposition: Windows.Storage.ApplicationDataCreateDisposition): Windows.Storage.ApplicationDataContainer; - deleteContainer(name: string): void; - } - export interface ISetVersionRequest { - currentVersion: number; - desiredVersion: number; - getDeferral(): Windows.Storage.SetVersionDeferral; - } - export class SetVersionDeferral implements Windows.Storage.ISetVersionDeferral { - complete(): void; - } - export interface ISetVersionDeferral { - complete(): void; - } - export interface IApplicationDataContainer { - containers: Windows.Foundation.Collections.IMapView; - locality: Windows.Storage.ApplicationDataLocality; - name: string; - values: Windows.Foundation.Collections.IPropertySet; - createContainer(name: string, disposition: Windows.Storage.ApplicationDataCreateDisposition): Windows.Storage.ApplicationDataContainer; - deleteContainer(name: string): void; - } - export class ApplicationDataContainerSettings implements Windows.Foundation.Collections.IPropertySet, Windows.Foundation.Collections.IObservableMap, Windows.Foundation.Collections.IMap, Windows.Foundation.Collections.IIterable> { - size: number; - onmapchanged: any/* TODO */; - lookup(key: string): any; - hasKey(key: string): boolean; - getView(): Windows.Foundation.Collections.IMapView; - insert(key: string, value: any): boolean; - remove(key: string): void; - clear(): void; - first(): Windows.Foundation.Collections.IIterator>; - } - export class ApplicationDataCompositeValue implements Windows.Foundation.Collections.IPropertySet, Windows.Foundation.Collections.IObservableMap, Windows.Foundation.Collections.IMap, Windows.Foundation.Collections.IIterable> { - size: number; - onmapchanged: any/* TODO */; - lookup(key: string): any; - hasKey(key: string): boolean; - getView(): Windows.Foundation.Collections.IMapView; - insert(key: string, value: any): boolean; - remove(key: string): void; - clear(): void; - first(): Windows.Foundation.Collections.IIterator>; - } - } -} -declare module Windows { - export module Storage { - export module Search { - export interface SortEntry { - propertyName: string; - ascendingOrder: boolean; - } - export enum DateStackOption { - none, - year, - month, - } - export enum IndexerOption { - useIndexerWhenAvailable, - onlyUseIndexer, - doNotUseIndexer, - } - export enum FolderDepth { - shallow, - deep, - } - export enum CommonFileQuery { - defaultQuery, - orderByName, - orderByTitle, - orderByMusicProperties, - orderBySearchRank, - orderByDate, - } - export enum CommonFolderQuery { - defaultQuery, - groupByYear, - groupByMonth, - groupByArtist, - groupByAlbum, - groupByAlbumArtist, - groupByComposer, - groupByGenre, - groupByPublishedYear, - groupByRating, - groupByTag, - groupByAuthor, - groupByType, - } - export enum IndexedState { - unknown, - notIndexed, - partiallyIndexed, - fullyIndexed, - } - export interface IQueryOptions { - applicationSearchFilter: string; - dateStackOption: Windows.Storage.Search.DateStackOption; - fileTypeFilter: Windows.Foundation.Collections.IVector; - folderDepth: Windows.Storage.Search.FolderDepth; - groupPropertyName: string; - indexerOption: Windows.Storage.Search.IndexerOption; - language: string; - sortOrder: Windows.Foundation.Collections.IVector; - userSearchFilter: string; - saveToString(): string; - loadFromString(value: string): void; - setThumbnailPrefetch(mode: Windows.Storage.FileProperties.ThumbnailMode, requestedSize: number, options: Windows.Storage.FileProperties.ThumbnailOptions): void; - setPropertyPrefetch(options: Windows.Storage.FileProperties.PropertyPrefetchOptions, propertiesToRetrieve: Windows.Foundation.Collections.IIterable): void; - } - export interface IQueryOptionsFactory { - createCommonFileQuery(query: Windows.Storage.Search.CommonFileQuery, fileTypeFilter: Windows.Foundation.Collections.IIterable): Windows.Storage.Search.QueryOptions; - createCommonFolderQuery(query: Windows.Storage.Search.CommonFolderQuery): Windows.Storage.Search.QueryOptions; - } - export class QueryOptions implements Windows.Storage.Search.IQueryOptions { - constructor(query: Windows.Storage.Search.CommonFileQuery, fileTypeFilter: Windows.Foundation.Collections.IIterable); - constructor(query: Windows.Storage.Search.CommonFolderQuery); - constructor(); - applicationSearchFilter: string; - dateStackOption: Windows.Storage.Search.DateStackOption; - fileTypeFilter: Windows.Foundation.Collections.IVector; - folderDepth: Windows.Storage.Search.FolderDepth; - groupPropertyName: string; - indexerOption: Windows.Storage.Search.IndexerOption; - language: string; - sortOrder: Windows.Foundation.Collections.IVector; - userSearchFilter: string; - saveToString(): string; - loadFromString(value: string): void; - setThumbnailPrefetch(mode: Windows.Storage.FileProperties.ThumbnailMode, requestedSize: number, options: Windows.Storage.FileProperties.ThumbnailOptions): void; - setPropertyPrefetch(options: Windows.Storage.FileProperties.PropertyPrefetchOptions, propertiesToRetrieve: Windows.Foundation.Collections.IIterable): void; - } - export interface IStorageQueryResultBase { - folder: Windows.Storage.StorageFolder; - getItemCountAsync(): Windows.Foundation.IAsyncOperation; - oncontentschanged: any/* TODO */; - onoptionschanged: any/* TODO */; - findStartIndexAsync(value: any): Windows.Foundation.IAsyncOperation; - getCurrentQueryOptions(): Windows.Storage.Search.QueryOptions; - applyNewQueryOptions(newQueryOptions: Windows.Storage.Search.QueryOptions): void; - } - export interface IStorageFileQueryResult extends Windows.Storage.Search.IStorageQueryResultBase { - getFilesAsync(startIndex: number, maxNumberOfItems: number): Windows.Foundation.IAsyncOperation>; - getFilesAsync(): Windows.Foundation.IAsyncOperation>; - } - export interface IStorageFolderQueryResult extends Windows.Storage.Search.IStorageQueryResultBase { - getFoldersAsync(startIndex: number, maxNumberOfItems: number): Windows.Foundation.IAsyncOperation>; - getFoldersAsync(): Windows.Foundation.IAsyncOperation>; - } - export interface IStorageItemQueryResult extends Windows.Storage.Search.IStorageQueryResultBase { - getItemsAsync(startIndex: number, maxNumberOfItems: number): Windows.Foundation.IAsyncOperation>; - getItemsAsync(): Windows.Foundation.IAsyncOperation>; - } - export interface IStorageFolderQueryOperations { - getIndexedStateAsync(): Windows.Foundation.IAsyncOperation; - createFileQuery(): Windows.Storage.Search.StorageFileQueryResult; - createFileQuery(query: Windows.Storage.Search.CommonFileQuery): Windows.Storage.Search.StorageFileQueryResult; - createFileQueryWithOptions(queryOptions: Windows.Storage.Search.QueryOptions): Windows.Storage.Search.StorageFileQueryResult; - createFolderQuery(): Windows.Storage.Search.StorageFolderQueryResult; - createFolderQuery(query: Windows.Storage.Search.CommonFolderQuery): Windows.Storage.Search.StorageFolderQueryResult; - createFolderQueryWithOptions(queryOptions: Windows.Storage.Search.QueryOptions): Windows.Storage.Search.StorageFolderQueryResult; - createItemQuery(): Windows.Storage.Search.StorageItemQueryResult; - createItemQueryWithOptions(queryOptions: Windows.Storage.Search.QueryOptions): Windows.Storage.Search.StorageItemQueryResult; - getFilesAsync(query: Windows.Storage.Search.CommonFileQuery, startIndex: number, maxItemsToRetrieve: number): Windows.Foundation.IAsyncOperation>; - getFilesAsync(query: Windows.Storage.Search.CommonFileQuery): Windows.Foundation.IAsyncOperation>; - getFoldersAsync(query: Windows.Storage.Search.CommonFolderQuery, startIndex: number, maxItemsToRetrieve: number): Windows.Foundation.IAsyncOperation>; - getFoldersAsync(query: Windows.Storage.Search.CommonFolderQuery): Windows.Foundation.IAsyncOperation>; - getItemsAsync(startIndex: number, maxItemsToRetrieve: number): Windows.Foundation.IAsyncOperation>; - areQueryOptionsSupported(queryOptions: Windows.Storage.Search.QueryOptions): boolean; - isCommonFolderQuerySupported(query: Windows.Storage.Search.CommonFolderQuery): boolean; - isCommonFileQuerySupported(query: Windows.Storage.Search.CommonFileQuery): boolean; - } - export class StorageFileQueryResult implements Windows.Storage.Search.IStorageFileQueryResult, Windows.Storage.Search.IStorageQueryResultBase { - folder: Windows.Storage.StorageFolder; - getFilesAsync(startIndex: number, maxNumberOfItems: number): Windows.Foundation.IAsyncOperation>; - getFilesAsync(): Windows.Foundation.IAsyncOperation>; - getItemCountAsync(): Windows.Foundation.IAsyncOperation; - oncontentschanged: any/* TODO */; - onoptionschanged: any/* TODO */; - findStartIndexAsync(value: any): Windows.Foundation.IAsyncOperation; - getCurrentQueryOptions(): Windows.Storage.Search.QueryOptions; - applyNewQueryOptions(newQueryOptions: Windows.Storage.Search.QueryOptions): void; - } - export class StorageFolderQueryResult implements Windows.Storage.Search.IStorageFolderQueryResult, Windows.Storage.Search.IStorageQueryResultBase { - folder: Windows.Storage.StorageFolder; - getFoldersAsync(startIndex: number, maxNumberOfItems: number): Windows.Foundation.IAsyncOperation>; - getFoldersAsync(): Windows.Foundation.IAsyncOperation>; - getItemCountAsync(): Windows.Foundation.IAsyncOperation; - oncontentschanged: any/* TODO */; - onoptionschanged: any/* TODO */; - findStartIndexAsync(value: any): Windows.Foundation.IAsyncOperation; - getCurrentQueryOptions(): Windows.Storage.Search.QueryOptions; - applyNewQueryOptions(newQueryOptions: Windows.Storage.Search.QueryOptions): void; - } - export class StorageItemQueryResult implements Windows.Storage.Search.IStorageItemQueryResult, Windows.Storage.Search.IStorageQueryResultBase { - folder: Windows.Storage.StorageFolder; - getItemsAsync(startIndex: number, maxNumberOfItems: number): Windows.Foundation.IAsyncOperation>; - getItemsAsync(): Windows.Foundation.IAsyncOperation>; - getItemCountAsync(): Windows.Foundation.IAsyncOperation; - oncontentschanged: any/* TODO */; - onoptionschanged: any/* TODO */; - findStartIndexAsync(value: any): Windows.Foundation.IAsyncOperation; - getCurrentQueryOptions(): Windows.Storage.Search.QueryOptions; - applyNewQueryOptions(newQueryOptions: Windows.Storage.Search.QueryOptions): void; - } - export class SortEntryVector implements Windows.Foundation.Collections.IVector, Windows.Foundation.Collections.IIterable { - size: number; - getAt(index: number): Windows.Storage.Search.SortEntry; - getView(): Windows.Foundation.Collections.IVectorView; - indexOf(value: Windows.Storage.Search.SortEntry): { index: number; returnValue: boolean; }; - setAt(index: number, value: Windows.Storage.Search.SortEntry): void; - insertAt(index: number, value: Windows.Storage.Search.SortEntry): void; - removeAt(index: number): void; - append(value: Windows.Storage.Search.SortEntry): void; - removeAtEnd(): void; - clear(): void; - getMany(startIndex: number): { items: Windows.Storage.Search.SortEntry[]; returnValue: number; }; - replaceAll(items: Windows.Storage.Search.SortEntry[]): void; - first(): Windows.Foundation.Collections.IIterator; - toString(): string; - toLocaleString(): string; - concat(...items: Windows.Storage.Search.SortEntry[][]): Windows.Storage.Search.SortEntry[]; - join(seperator: string): string; - pop(): Windows.Storage.Search.SortEntry; - push(...items: Windows.Storage.Search.SortEntry[]): void; - reverse(): Windows.Storage.Search.SortEntry[]; - shift(): Windows.Storage.Search.SortEntry; - slice(start: number): Windows.Storage.Search.SortEntry[]; - slice(start: number, end: number): Windows.Storage.Search.SortEntry[]; - sort(): Windows.Storage.Search.SortEntry[]; - sort(compareFn: (a: Windows.Storage.Search.SortEntry, b: Windows.Storage.Search.SortEntry) => number): Windows.Storage.Search.SortEntry[]; - splice(start: number): Windows.Storage.Search.SortEntry[]; - splice(start: number, deleteCount: number, ...items: Windows.Storage.Search.SortEntry[]): Windows.Storage.Search.SortEntry[]; - unshift(...items: Windows.Storage.Search.SortEntry[]): number; - lastIndexOf(searchElement: Windows.Storage.Search.SortEntry): number; - lastIndexOf(searchElement: Windows.Storage.Search.SortEntry, fromIndex: number): number; - every(callbackfn: (value: Windows.Storage.Search.SortEntry, index: number, array: Windows.Storage.Search.SortEntry[]) => boolean): boolean; - every(callbackfn: (value: Windows.Storage.Search.SortEntry, index: number, array: Windows.Storage.Search.SortEntry[]) => boolean, thisArg: any): boolean; - some(callbackfn: (value: Windows.Storage.Search.SortEntry, index: number, array: Windows.Storage.Search.SortEntry[]) => boolean): boolean; - some(callbackfn: (value: Windows.Storage.Search.SortEntry, index: number, array: Windows.Storage.Search.SortEntry[]) => boolean, thisArg: any): boolean; - forEach(callbackfn: (value: Windows.Storage.Search.SortEntry, index: number, array: Windows.Storage.Search.SortEntry[]) => void ): void; - forEach(callbackfn: (value: Windows.Storage.Search.SortEntry, index: number, array: Windows.Storage.Search.SortEntry[]) => void , thisArg: any): void; - map(callbackfn: (value: Windows.Storage.Search.SortEntry, index: number, array: Windows.Storage.Search.SortEntry[]) => any): any[]; - map(callbackfn: (value: Windows.Storage.Search.SortEntry, index: number, array: Windows.Storage.Search.SortEntry[]) => any, thisArg: any): any[]; - filter(callbackfn: (value: Windows.Storage.Search.SortEntry, index: number, array: Windows.Storage.Search.SortEntry[]) => boolean): Windows.Storage.Search.SortEntry[]; - filter(callbackfn: (value: Windows.Storage.Search.SortEntry, index: number, array: Windows.Storage.Search.SortEntry[]) => boolean, thisArg: any): Windows.Storage.Search.SortEntry[]; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Storage.Search.SortEntry[]) => any): any; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Storage.Search.SortEntry[]) => any, initialValue: any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Storage.Search.SortEntry[]) => any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Storage.Search.SortEntry[]) => any, initialValue: any): any; - length: number; - } - } - } -} -declare module Windows { - export module Storage { - export module AccessCache { - export interface AccessListEntry { - token: string; - metadata: string; - } - export interface IItemRemovedEventArgs { - removedEntry: Windows.Storage.AccessCache.AccessListEntry; - } - export class AccessListEntryView implements Windows.Foundation.Collections.IVectorView, Windows.Foundation.Collections.IIterable { - size: number; - getAt(index: number): Windows.Storage.AccessCache.AccessListEntry; - indexOf(value: Windows.Storage.AccessCache.AccessListEntry): { index: number; returnValue: boolean; }; - getMany(startIndex: number): { items: Windows.Storage.AccessCache.AccessListEntry[]; returnValue: number; }; - first(): Windows.Foundation.Collections.IIterator; - toString(): string; - toLocaleString(): string; - concat(...items: Windows.Storage.AccessCache.AccessListEntry[][]): Windows.Storage.AccessCache.AccessListEntry[]; - join(seperator: string): string; - pop(): Windows.Storage.AccessCache.AccessListEntry; - push(...items: Windows.Storage.AccessCache.AccessListEntry[]): void; - reverse(): Windows.Storage.AccessCache.AccessListEntry[]; - shift(): Windows.Storage.AccessCache.AccessListEntry; - slice(start: number): Windows.Storage.AccessCache.AccessListEntry[]; - slice(start: number, end: number): Windows.Storage.AccessCache.AccessListEntry[]; - sort(): Windows.Storage.AccessCache.AccessListEntry[]; - sort(compareFn: (a: Windows.Storage.AccessCache.AccessListEntry, b: Windows.Storage.AccessCache.AccessListEntry) => number): Windows.Storage.AccessCache.AccessListEntry[]; - splice(start: number): Windows.Storage.AccessCache.AccessListEntry[]; - splice(start: number, deleteCount: number, ...items: Windows.Storage.AccessCache.AccessListEntry[]): Windows.Storage.AccessCache.AccessListEntry[]; - unshift(...items: Windows.Storage.AccessCache.AccessListEntry[]): number; - lastIndexOf(searchElement: Windows.Storage.AccessCache.AccessListEntry): number; - lastIndexOf(searchElement: Windows.Storage.AccessCache.AccessListEntry, fromIndex: number): number; - every(callbackfn: (value: Windows.Storage.AccessCache.AccessListEntry, index: number, array: Windows.Storage.AccessCache.AccessListEntry[]) => boolean): boolean; - every(callbackfn: (value: Windows.Storage.AccessCache.AccessListEntry, index: number, array: Windows.Storage.AccessCache.AccessListEntry[]) => boolean, thisArg: any): boolean; - some(callbackfn: (value: Windows.Storage.AccessCache.AccessListEntry, index: number, array: Windows.Storage.AccessCache.AccessListEntry[]) => boolean): boolean; - some(callbackfn: (value: Windows.Storage.AccessCache.AccessListEntry, index: number, array: Windows.Storage.AccessCache.AccessListEntry[]) => boolean, thisArg: any): boolean; - forEach(callbackfn: (value: Windows.Storage.AccessCache.AccessListEntry, index: number, array: Windows.Storage.AccessCache.AccessListEntry[]) => void ): void; - forEach(callbackfn: (value: Windows.Storage.AccessCache.AccessListEntry, index: number, array: Windows.Storage.AccessCache.AccessListEntry[]) => void , thisArg: any): void; - map(callbackfn: (value: Windows.Storage.AccessCache.AccessListEntry, index: number, array: Windows.Storage.AccessCache.AccessListEntry[]) => any): any[]; - map(callbackfn: (value: Windows.Storage.AccessCache.AccessListEntry, index: number, array: Windows.Storage.AccessCache.AccessListEntry[]) => any, thisArg: any): any[]; - filter(callbackfn: (value: Windows.Storage.AccessCache.AccessListEntry, index: number, array: Windows.Storage.AccessCache.AccessListEntry[]) => boolean): Windows.Storage.AccessCache.AccessListEntry[]; - filter(callbackfn: (value: Windows.Storage.AccessCache.AccessListEntry, index: number, array: Windows.Storage.AccessCache.AccessListEntry[]) => boolean, thisArg: any): Windows.Storage.AccessCache.AccessListEntry[]; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Storage.AccessCache.AccessListEntry[]) => any): any; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Storage.AccessCache.AccessListEntry[]) => any, initialValue: any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Storage.AccessCache.AccessListEntry[]) => any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Storage.AccessCache.AccessListEntry[]) => any, initialValue: any): any; - length: number; - } - export enum AccessCacheOptions { - none, - disallowUserInput, - fastLocationsOnly, - useReadOnlyCachedCopy, - suppressAccessTimeUpdate, - } - export interface IStorageItemAccessList { - entries: Windows.Storage.AccessCache.AccessListEntryView; - maximumItemsAllowed: number; - add(file: Windows.Storage.IStorageItem): string; - add(file: Windows.Storage.IStorageItem, metadata: string): string; - addOrReplace(token: string, file: Windows.Storage.IStorageItem): void; - addOrReplace(token: string, file: Windows.Storage.IStorageItem, metadata: string): void; - getItemAsync(token: string): Windows.Foundation.IAsyncOperation; - getFileAsync(token: string): Windows.Foundation.IAsyncOperation; - getFolderAsync(token: string): Windows.Foundation.IAsyncOperation; - getItemAsync(token: string, options: Windows.Storage.AccessCache.AccessCacheOptions): Windows.Foundation.IAsyncOperation; - getFileAsync(token: string, options: Windows.Storage.AccessCache.AccessCacheOptions): Windows.Foundation.IAsyncOperation; - getFolderAsync(token: string, options: Windows.Storage.AccessCache.AccessCacheOptions): Windows.Foundation.IAsyncOperation; - remove(token: string): void; - containsItem(token: string): boolean; - clear(): void; - checkAccess(file: Windows.Storage.IStorageItem): boolean; - } - export interface IStorageItemMostRecentlyUsedList extends Windows.Storage.AccessCache.IStorageItemAccessList { - onitemremoved: any/* TODO */; - } - export class StorageItemMostRecentlyUsedList implements Windows.Storage.AccessCache.IStorageItemMostRecentlyUsedList, Windows.Storage.AccessCache.IStorageItemAccessList { - entries: Windows.Storage.AccessCache.AccessListEntryView; - maximumItemsAllowed: number; - onitemremoved: any/* TODO */; - add(file: Windows.Storage.IStorageItem): string; - add(file: Windows.Storage.IStorageItem, metadata: string): string; - addOrReplace(token: string, file: Windows.Storage.IStorageItem): void; - addOrReplace(token: string, file: Windows.Storage.IStorageItem, metadata: string): void; - getItemAsync(token: string): Windows.Foundation.IAsyncOperation; - getFileAsync(token: string): Windows.Foundation.IAsyncOperation; - getFolderAsync(token: string): Windows.Foundation.IAsyncOperation; - getItemAsync(token: string, options: Windows.Storage.AccessCache.AccessCacheOptions): Windows.Foundation.IAsyncOperation; - getFileAsync(token: string, options: Windows.Storage.AccessCache.AccessCacheOptions): Windows.Foundation.IAsyncOperation; - getFolderAsync(token: string, options: Windows.Storage.AccessCache.AccessCacheOptions): Windows.Foundation.IAsyncOperation; - remove(token: string): void; - containsItem(token: string): boolean; - clear(): void; - checkAccess(file: Windows.Storage.IStorageItem): boolean; - } - export class ItemRemovedEventArgs implements Windows.Storage.AccessCache.IItemRemovedEventArgs { - removedEntry: Windows.Storage.AccessCache.AccessListEntry; - } - export interface IStorageApplicationPermissionsStatics { - futureAccessList: Windows.Storage.AccessCache.StorageItemAccessList; - mostRecentlyUsedList: Windows.Storage.AccessCache.StorageItemMostRecentlyUsedList; - } - export class StorageItemAccessList implements Windows.Storage.AccessCache.IStorageItemAccessList { - entries: Windows.Storage.AccessCache.AccessListEntryView; - maximumItemsAllowed: number; - add(file: Windows.Storage.IStorageItem): string; - add(file: Windows.Storage.IStorageItem, metadata: string): string; - addOrReplace(token: string, file: Windows.Storage.IStorageItem): void; - addOrReplace(token: string, file: Windows.Storage.IStorageItem, metadata: string): void; - getItemAsync(token: string): Windows.Foundation.IAsyncOperation; - getFileAsync(token: string): Windows.Foundation.IAsyncOperation; - getFolderAsync(token: string): Windows.Foundation.IAsyncOperation; - getItemAsync(token: string, options: Windows.Storage.AccessCache.AccessCacheOptions): Windows.Foundation.IAsyncOperation; - getFileAsync(token: string, options: Windows.Storage.AccessCache.AccessCacheOptions): Windows.Foundation.IAsyncOperation; - getFolderAsync(token: string, options: Windows.Storage.AccessCache.AccessCacheOptions): Windows.Foundation.IAsyncOperation; - remove(token: string): void; - containsItem(token: string): boolean; - clear(): void; - checkAccess(file: Windows.Storage.IStorageItem): boolean; - } - export class StorageApplicationPermissions { - static futureAccessList: Windows.Storage.AccessCache.StorageItemAccessList; - static mostRecentlyUsedList: Windows.Storage.AccessCache.StorageItemMostRecentlyUsedList; - } - } - } -} -declare module Windows { - export module Storage { - export module BulkAccess { - export interface IStorageItemInformation { - basicProperties: Windows.Storage.FileProperties.BasicProperties; - documentProperties: Windows.Storage.FileProperties.DocumentProperties; - imageProperties: Windows.Storage.FileProperties.ImageProperties; - musicProperties: Windows.Storage.FileProperties.MusicProperties; - thumbnail: Windows.Storage.FileProperties.StorageItemThumbnail; - videoProperties: Windows.Storage.FileProperties.VideoProperties; - onthumbnailupdated: any/* TODO */; - onpropertiesupdated: any/* TODO */; - } - export interface IFileInformationFactoryFactory { - createWithMode(queryResult: Windows.Storage.Search.IStorageQueryResultBase, mode: Windows.Storage.FileProperties.ThumbnailMode): Windows.Storage.BulkAccess.FileInformationFactory; - createWithModeAndSize(queryResult: Windows.Storage.Search.IStorageQueryResultBase, mode: Windows.Storage.FileProperties.ThumbnailMode, requestedThumbnailSize: number): Windows.Storage.BulkAccess.FileInformationFactory; - createWithModeAndSizeAndOptions(queryResult: Windows.Storage.Search.IStorageQueryResultBase, mode: Windows.Storage.FileProperties.ThumbnailMode, requestedThumbnailSize: number, thumbnailOptions: Windows.Storage.FileProperties.ThumbnailOptions): Windows.Storage.BulkAccess.FileInformationFactory; - createWithModeAndSizeAndOptionsAndFlags(queryResult: Windows.Storage.Search.IStorageQueryResultBase, mode: Windows.Storage.FileProperties.ThumbnailMode, requestedThumbnailSize: number, thumbnailOptions: Windows.Storage.FileProperties.ThumbnailOptions, delayLoad: boolean): Windows.Storage.BulkAccess.FileInformationFactory; - } - export class FileInformationFactory implements Windows.Storage.BulkAccess.IFileInformationFactory { - constructor(queryResult: Windows.Storage.Search.IStorageQueryResultBase, mode: Windows.Storage.FileProperties.ThumbnailMode); - constructor(queryResult: Windows.Storage.Search.IStorageQueryResultBase, mode: Windows.Storage.FileProperties.ThumbnailMode, requestedThumbnailSize: number); - constructor(queryResult: Windows.Storage.Search.IStorageQueryResultBase, mode: Windows.Storage.FileProperties.ThumbnailMode, requestedThumbnailSize: number, thumbnailOptions: Windows.Storage.FileProperties.ThumbnailOptions); - constructor(queryResult: Windows.Storage.Search.IStorageQueryResultBase, mode: Windows.Storage.FileProperties.ThumbnailMode, requestedThumbnailSize: number, thumbnailOptions: Windows.Storage.FileProperties.ThumbnailOptions, delayLoad: boolean); - getItemsAsync(startIndex: number, maxItemsToRetrieve: number): Windows.Foundation.IAsyncOperation>; - getItemsAsync(): Windows.Foundation.IAsyncOperation>; - getFilesAsync(startIndex: number, maxItemsToRetrieve: number): Windows.Foundation.IAsyncOperation>; - getFilesAsync(): Windows.Foundation.IAsyncOperation>; - getFoldersAsync(startIndex: number, maxItemsToRetrieve: number): Windows.Foundation.IAsyncOperation>; - getFoldersAsync(): Windows.Foundation.IAsyncOperation>; - getVirtualizedItemsVector(): any; - getVirtualizedFilesVector(): any; - getVirtualizedFoldersVector(): any; - } - export interface IFileInformationFactory { - getItemsAsync(startIndex: number, maxItemsToRetrieve: number): Windows.Foundation.IAsyncOperation>; - getItemsAsync(): Windows.Foundation.IAsyncOperation>; - getFilesAsync(startIndex: number, maxItemsToRetrieve: number): Windows.Foundation.IAsyncOperation>; - getFilesAsync(): Windows.Foundation.IAsyncOperation>; - getFoldersAsync(startIndex: number, maxItemsToRetrieve: number): Windows.Foundation.IAsyncOperation>; - getFoldersAsync(): Windows.Foundation.IAsyncOperation>; - getVirtualizedItemsVector(): any; - getVirtualizedFilesVector(): any; - getVirtualizedFoldersVector(): any; - } - export class FileInformation implements Windows.Storage.BulkAccess.IStorageItemInformation, Windows.Storage.IStorageFile, Windows.Storage.IStorageItem, Windows.Storage.Streams.IRandomAccessStreamReference, Windows.Storage.Streams.IInputStreamReference, Windows.Storage.IStorageItemProperties { - basicProperties: Windows.Storage.FileProperties.BasicProperties; - documentProperties: Windows.Storage.FileProperties.DocumentProperties; - imageProperties: Windows.Storage.FileProperties.ImageProperties; - musicProperties: Windows.Storage.FileProperties.MusicProperties; - thumbnail: Windows.Storage.FileProperties.StorageItemThumbnail; - videoProperties: Windows.Storage.FileProperties.VideoProperties; - contentType: string; - fileType: string; - attributes: Windows.Storage.FileAttributes; - dateCreated: Date; - name: string; - path: string; - displayName: string; - displayType: string; - folderRelativeId: string; - properties: Windows.Storage.FileProperties.StorageItemContentProperties; - onthumbnailupdated: any/* TODO */; - onpropertiesupdated: any/* TODO */; - openAsync(accessMode: Windows.Storage.FileAccessMode): Windows.Foundation.IAsyncOperation; - openTransactedWriteAsync(): Windows.Foundation.IAsyncOperation; - copyAsync(destinationFolder: Windows.Storage.IStorageFolder): Windows.Foundation.IAsyncOperation; - copyAsync(destinationFolder: Windows.Storage.IStorageFolder, desiredNewName: string): Windows.Foundation.IAsyncOperation; - copyAsync(destinationFolder: Windows.Storage.IStorageFolder, desiredNewName: string, option: Windows.Storage.NameCollisionOption): Windows.Foundation.IAsyncOperation; - copyAndReplaceAsync(fileToReplace: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncAction; - moveAsync(destinationFolder: Windows.Storage.IStorageFolder): Windows.Foundation.IAsyncAction; - moveAsync(destinationFolder: Windows.Storage.IStorageFolder, desiredNewName: string): Windows.Foundation.IAsyncAction; - moveAsync(destinationFolder: Windows.Storage.IStorageFolder, desiredNewName: string, option: Windows.Storage.NameCollisionOption): Windows.Foundation.IAsyncAction; - moveAndReplaceAsync(fileToReplace: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncAction; - renameAsync(desiredName: string): Windows.Foundation.IAsyncAction; - renameAsync(desiredName: string, option: Windows.Storage.NameCollisionOption): Windows.Foundation.IAsyncAction; - deleteAsync(): Windows.Foundation.IAsyncAction; - deleteAsync(option: Windows.Storage.StorageDeleteOption): Windows.Foundation.IAsyncAction; - getBasicPropertiesAsync(): Windows.Foundation.IAsyncOperation; - isOfType(type: Windows.Storage.StorageItemTypes): boolean; - openReadAsync(): Windows.Foundation.IAsyncOperation; - openSequentialReadAsync(): Windows.Foundation.IAsyncOperation; - getThumbnailAsync(mode: Windows.Storage.FileProperties.ThumbnailMode): Windows.Foundation.IAsyncOperation; - getThumbnailAsync(mode: Windows.Storage.FileProperties.ThumbnailMode, requestedSize: number): Windows.Foundation.IAsyncOperation; - getThumbnailAsync(mode: Windows.Storage.FileProperties.ThumbnailMode, requestedSize: number, options: Windows.Storage.FileProperties.ThumbnailOptions): Windows.Foundation.IAsyncOperation; - } - export class FolderInformation implements Windows.Storage.BulkAccess.IStorageItemInformation, Windows.Storage.IStorageFolder, Windows.Storage.IStorageItem, Windows.Storage.IStorageItemProperties, Windows.Storage.Search.IStorageFolderQueryOperations { - basicProperties: Windows.Storage.FileProperties.BasicProperties; - documentProperties: Windows.Storage.FileProperties.DocumentProperties; - imageProperties: Windows.Storage.FileProperties.ImageProperties; - musicProperties: Windows.Storage.FileProperties.MusicProperties; - thumbnail: Windows.Storage.FileProperties.StorageItemThumbnail; - videoProperties: Windows.Storage.FileProperties.VideoProperties; - attributes: Windows.Storage.FileAttributes; - dateCreated: Date; - name: string; - path: string; - displayName: string; - displayType: string; - folderRelativeId: string; - properties: Windows.Storage.FileProperties.StorageItemContentProperties; - onthumbnailupdated: any/* TODO */; - onpropertiesupdated: any/* TODO */; - createFileAsync(desiredName: string): Windows.Foundation.IAsyncOperation; - createFileAsync(desiredName: string, options: Windows.Storage.CreationCollisionOption): Windows.Foundation.IAsyncOperation; - createFolderAsync(desiredName: string): Windows.Foundation.IAsyncOperation; - createFolderAsync(desiredName: string, options: Windows.Storage.CreationCollisionOption): Windows.Foundation.IAsyncOperation; - getFileAsync(name: string): Windows.Foundation.IAsyncOperation; - getFolderAsync(name: string): Windows.Foundation.IAsyncOperation; - getItemAsync(name: string): Windows.Foundation.IAsyncOperation; - getFilesAsync(): Windows.Foundation.IAsyncOperation>; - getFoldersAsync(): Windows.Foundation.IAsyncOperation>; - getItemsAsync(): Windows.Foundation.IAsyncOperation>; - renameAsync(desiredName: string): Windows.Foundation.IAsyncAction; - renameAsync(desiredName: string, option: Windows.Storage.NameCollisionOption): Windows.Foundation.IAsyncAction; - deleteAsync(): Windows.Foundation.IAsyncAction; - deleteAsync(option: Windows.Storage.StorageDeleteOption): Windows.Foundation.IAsyncAction; - getBasicPropertiesAsync(): Windows.Foundation.IAsyncOperation; - isOfType(type: Windows.Storage.StorageItemTypes): boolean; - getThumbnailAsync(mode: Windows.Storage.FileProperties.ThumbnailMode): Windows.Foundation.IAsyncOperation; - getThumbnailAsync(mode: Windows.Storage.FileProperties.ThumbnailMode, requestedSize: number): Windows.Foundation.IAsyncOperation; - getThumbnailAsync(mode: Windows.Storage.FileProperties.ThumbnailMode, requestedSize: number, options: Windows.Storage.FileProperties.ThumbnailOptions): Windows.Foundation.IAsyncOperation; - getIndexedStateAsync(): Windows.Foundation.IAsyncOperation; - createFileQuery(): Windows.Storage.Search.StorageFileQueryResult; - createFileQuery(query: Windows.Storage.Search.CommonFileQuery): Windows.Storage.Search.StorageFileQueryResult; - createFileQueryWithOptions(queryOptions: Windows.Storage.Search.QueryOptions): Windows.Storage.Search.StorageFileQueryResult; - createFolderQuery(): Windows.Storage.Search.StorageFolderQueryResult; - createFolderQuery(query: Windows.Storage.Search.CommonFolderQuery): Windows.Storage.Search.StorageFolderQueryResult; - createFolderQueryWithOptions(queryOptions: Windows.Storage.Search.QueryOptions): Windows.Storage.Search.StorageFolderQueryResult; - createItemQuery(): Windows.Storage.Search.StorageItemQueryResult; - createItemQueryWithOptions(queryOptions: Windows.Storage.Search.QueryOptions): Windows.Storage.Search.StorageItemQueryResult; - getFilesAsync(query: Windows.Storage.Search.CommonFileQuery, startIndex: number, maxItemsToRetrieve: number): Windows.Foundation.IAsyncOperation>; - getFilesAsync(query: Windows.Storage.Search.CommonFileQuery): Windows.Foundation.IAsyncOperation>; - getFoldersAsync(query: Windows.Storage.Search.CommonFolderQuery, startIndex: number, maxItemsToRetrieve: number): Windows.Foundation.IAsyncOperation>; - getFoldersAsync(query: Windows.Storage.Search.CommonFolderQuery): Windows.Foundation.IAsyncOperation>; - getItemsAsync(startIndex: number, maxItemsToRetrieve: number): Windows.Foundation.IAsyncOperation>; - areQueryOptionsSupported(queryOptions: Windows.Storage.Search.QueryOptions): boolean; - isCommonFolderQuerySupported(query: Windows.Storage.Search.CommonFolderQuery): boolean; - isCommonFileQuerySupported(query: Windows.Storage.Search.CommonFileQuery): boolean; - } - } - } -} -declare module Windows { - export module Storage { - export module Pickers { - export enum PickerViewMode { - list, - thumbnail, - } - export enum PickerLocationId { - documentsLibrary, - computerFolder, - desktop, - downloads, - homeGroup, - musicLibrary, - picturesLibrary, - videosLibrary, - } - export class FilePickerSelectedFilesArray implements Windows.Foundation.Collections.IVectorView, Windows.Foundation.Collections.IIterable { - size: number; - getAt(index: number): Windows.Storage.StorageFile; - indexOf(value: Windows.Storage.StorageFile): { index: number; returnValue: boolean; }; - getMany(startIndex: number): { items: Windows.Storage.StorageFile[]; returnValue: number; }; - first(): Windows.Foundation.Collections.IIterator; - toString(): string; - toLocaleString(): string; - concat(...items: Windows.Storage.StorageFile[][]): Windows.Storage.StorageFile[]; - join(seperator: string): string; - pop(): Windows.Storage.StorageFile; - push(...items: Windows.Storage.StorageFile[]): void; - reverse(): Windows.Storage.StorageFile[]; - shift(): Windows.Storage.StorageFile; - slice(start: number): Windows.Storage.StorageFile[]; - slice(start: number, end: number): Windows.Storage.StorageFile[]; - sort(): Windows.Storage.StorageFile[]; - sort(compareFn: (a: Windows.Storage.StorageFile, b: Windows.Storage.StorageFile) => number): Windows.Storage.StorageFile[]; - splice(start: number): Windows.Storage.StorageFile[]; - splice(start: number, deleteCount: number, ...items: Windows.Storage.StorageFile[]): Windows.Storage.StorageFile[]; - unshift(...items: Windows.Storage.StorageFile[]): number; - lastIndexOf(searchElement: Windows.Storage.StorageFile): number; - lastIndexOf(searchElement: Windows.Storage.StorageFile, fromIndex: number): number; - every(callbackfn: (value: Windows.Storage.StorageFile, index: number, array: Windows.Storage.StorageFile[]) => boolean): boolean; - every(callbackfn: (value: Windows.Storage.StorageFile, index: number, array: Windows.Storage.StorageFile[]) => boolean, thisArg: any): boolean; - some(callbackfn: (value: Windows.Storage.StorageFile, index: number, array: Windows.Storage.StorageFile[]) => boolean): boolean; - some(callbackfn: (value: Windows.Storage.StorageFile, index: number, array: Windows.Storage.StorageFile[]) => boolean, thisArg: any): boolean; - forEach(callbackfn: (value: Windows.Storage.StorageFile, index: number, array: Windows.Storage.StorageFile[]) => void ): void; - forEach(callbackfn: (value: Windows.Storage.StorageFile, index: number, array: Windows.Storage.StorageFile[]) => void , thisArg: any): void; - map(callbackfn: (value: Windows.Storage.StorageFile, index: number, array: Windows.Storage.StorageFile[]) => any): any[]; - map(callbackfn: (value: Windows.Storage.StorageFile, index: number, array: Windows.Storage.StorageFile[]) => any, thisArg: any): any[]; - filter(callbackfn: (value: Windows.Storage.StorageFile, index: number, array: Windows.Storage.StorageFile[]) => boolean): Windows.Storage.StorageFile[]; - filter(callbackfn: (value: Windows.Storage.StorageFile, index: number, array: Windows.Storage.StorageFile[]) => boolean, thisArg: any): Windows.Storage.StorageFile[]; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Storage.StorageFile[]) => any): any; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Storage.StorageFile[]) => any, initialValue: any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Storage.StorageFile[]) => any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: Windows.Storage.StorageFile[]) => any, initialValue: any): any; - length: number; - } - export class FilePickerFileTypesOrderedMap implements Windows.Foundation.Collections.IMap>, Windows.Foundation.Collections.IIterable>> { - size: number; - lookup(key: string): Windows.Foundation.Collections.IVector; - hasKey(key: string): boolean; - getView(): Windows.Foundation.Collections.IMapView>; - insert(key: string, value: Windows.Foundation.Collections.IVector): boolean; - remove(key: string): void; - clear(): void; - first(): Windows.Foundation.Collections.IIterator>>; - } - export class FileExtensionVector implements Windows.Foundation.Collections.IVector, Windows.Foundation.Collections.IIterable { - size: number; - getAt(index: number): string; - getView(): Windows.Foundation.Collections.IVectorView; - indexOf(value: string): { index: number; returnValue: boolean; }; - setAt(index: number, value: string): void; - insertAt(index: number, value: string): void; - removeAt(index: number): void; - append(value: string): void; - removeAtEnd(): void; - clear(): void; - getMany(startIndex: number): { items: string[]; returnValue: number; }; - replaceAll(items: string[]): void; - first(): Windows.Foundation.Collections.IIterator; - toString(): string; - toLocaleString(): string; - concat(...items: string[][]): string[]; - join(seperator: string): string; - pop(): string; - push(...items: string[]): void; - reverse(): string[]; - shift(): string; - slice(start: number): string[]; - slice(start: number, end: number): string[]; - sort(): string[]; - sort(compareFn: (a: string, b: string) => number): string[]; - splice(start: number): string[]; - splice(start: number, deleteCount: number, ...items: string[]): string[]; - unshift(...items: string[]): number; - lastIndexOf(searchElement: string): number; - lastIndexOf(searchElement: string, fromIndex: number): number; - every(callbackfn: (value: string, index: number, array: string[]) => boolean): boolean; - every(callbackfn: (value: string, index: number, array: string[]) => boolean, thisArg: any): boolean; - some(callbackfn: (value: string, index: number, array: string[]) => boolean): boolean; - some(callbackfn: (value: string, index: number, array: string[]) => boolean, thisArg: any): boolean; - forEach(callbackfn: (value: string, index: number, array: string[]) => void ): void; - forEach(callbackfn: (value: string, index: number, array: string[]) => void , thisArg: any): void; - map(callbackfn: (value: string, index: number, array: string[]) => any): any[]; - map(callbackfn: (value: string, index: number, array: string[]) => any, thisArg: any): any[]; - filter(callbackfn: (value: string, index: number, array: string[]) => boolean): string[]; - filter(callbackfn: (value: string, index: number, array: string[]) => boolean, thisArg: any): string[]; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: string[]) => any): any; - reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: string[]) => any, initialValue: any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: string[]) => any): any; - reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: string[]) => any, initialValue: any): any; - length: number; - } - export interface IFileOpenPicker { - commitButtonText: string; - fileTypeFilter: Windows.Foundation.Collections.IVector; - settingsIdentifier: string; - suggestedStartLocation: Windows.Storage.Pickers.PickerLocationId; - viewMode: Windows.Storage.Pickers.PickerViewMode; - pickSingleFileAsync(): Windows.Foundation.IAsyncOperation; - pickMultipleFilesAsync(): Windows.Foundation.IAsyncOperation>; - } - export interface IFileSavePicker { - commitButtonText: string; - defaultFileExtension: string; - fileTypeChoices: Windows.Foundation.Collections.IMap>; - settingsIdentifier: string; - suggestedFileName: string; - suggestedSaveFile: Windows.Storage.StorageFile; - suggestedStartLocation: Windows.Storage.Pickers.PickerLocationId; - pickSaveFileAsync(): Windows.Foundation.IAsyncOperation; - } - export interface IFolderPicker { - commitButtonText: string; - fileTypeFilter: Windows.Foundation.Collections.IVector; - settingsIdentifier: string; - suggestedStartLocation: Windows.Storage.Pickers.PickerLocationId; - viewMode: Windows.Storage.Pickers.PickerViewMode; - pickSingleFolderAsync(): Windows.Foundation.IAsyncOperation; - } - export class FileOpenPicker implements Windows.Storage.Pickers.IFileOpenPicker { - commitButtonText: string; - fileTypeFilter: Windows.Foundation.Collections.IVector; - settingsIdentifier: string; - suggestedStartLocation: Windows.Storage.Pickers.PickerLocationId; - viewMode: Windows.Storage.Pickers.PickerViewMode; - pickSingleFileAsync(): Windows.Foundation.IAsyncOperation; - pickMultipleFilesAsync(): Windows.Foundation.IAsyncOperation>; - } - export class FileSavePicker implements Windows.Storage.Pickers.IFileSavePicker { - commitButtonText: string; - defaultFileExtension: string; - fileTypeChoices: Windows.Foundation.Collections.IMap>; - settingsIdentifier: string; - suggestedFileName: string; - suggestedSaveFile: Windows.Storage.StorageFile; - suggestedStartLocation: Windows.Storage.Pickers.PickerLocationId; - pickSaveFileAsync(): Windows.Foundation.IAsyncOperation; - } - export class FolderPicker implements Windows.Storage.Pickers.IFolderPicker { - commitButtonText: string; - fileTypeFilter: Windows.Foundation.Collections.IVector; - settingsIdentifier: string; - suggestedStartLocation: Windows.Storage.Pickers.PickerLocationId; - viewMode: Windows.Storage.Pickers.PickerViewMode; - pickSingleFolderAsync(): Windows.Foundation.IAsyncOperation; - } - } - } -} -declare module Windows { - export module Storage { - export module Compression { - export enum CompressAlgorithm { - invalidAlgorithm, - nullAlgorithm, - mszip, - xpress, - xpressHuff, - lzms, - } - export interface ICompressor extends Windows.Storage.Streams.IOutputStream, Windows.Foundation.IClosable { - finishAsync(): Windows.Foundation.IAsyncOperation; - detachStream(): Windows.Storage.Streams.IOutputStream; - } - export class Compressor implements Windows.Storage.Compression.ICompressor, Windows.Storage.Streams.IOutputStream, Windows.Foundation.IClosable { - constructor(underlyingStream: Windows.Storage.Streams.IOutputStream); - constructor(underlyingStream: Windows.Storage.Streams.IOutputStream, algorithm: Windows.Storage.Compression.CompressAlgorithm, blockSize: number); - finishAsync(): Windows.Foundation.IAsyncOperation; - detachStream(): Windows.Storage.Streams.IOutputStream; - writeAsync(buffer: Windows.Storage.Streams.IBuffer): Windows.Foundation.IAsyncOperationWithProgress; - flushAsync(): Windows.Foundation.IAsyncOperation; - dispose(): void; - close(): void; - } - export interface IDecompressor extends Windows.Storage.Streams.IInputStream, Windows.Foundation.IClosable { - detachStream(): Windows.Storage.Streams.IInputStream; - } - export class Decompressor implements Windows.Storage.Compression.IDecompressor, Windows.Storage.Streams.IInputStream, Windows.Foundation.IClosable { - constructor(underlyingStream: Windows.Storage.Streams.IInputStream); - detachStream(): Windows.Storage.Streams.IInputStream; - readAsync(buffer: Windows.Storage.Streams.IBuffer, count: number, options: Windows.Storage.Streams.InputStreamOptions): Windows.Foundation.IAsyncOperationWithProgress; - dispose(): void; - close(): void; - } - export interface ICompressorFactory { - createCompressor(underlyingStream: Windows.Storage.Streams.IOutputStream): Windows.Storage.Compression.Compressor; - createCompressorEx(underlyingStream: Windows.Storage.Streams.IOutputStream, algorithm: Windows.Storage.Compression.CompressAlgorithm, blockSize: number): Windows.Storage.Compression.Compressor; - } - export interface IDecompressorFactory { - createDecompressor(underlyingStream: Windows.Storage.Streams.IInputStream): Windows.Storage.Compression.Decompressor; - } - } - } -} -declare module Windows { - export module System { - export module Profile { - export interface IHardwareToken { - certificate: Windows.Storage.Streams.IBuffer; - id: Windows.Storage.Streams.IBuffer; - signature: Windows.Storage.Streams.IBuffer; - } - export class HardwareToken implements Windows.System.Profile.IHardwareToken { - certificate: Windows.Storage.Streams.IBuffer; - id: Windows.Storage.Streams.IBuffer; - signature: Windows.Storage.Streams.IBuffer; - } - export interface IHardwareIdentificationStatics { - getPackageSpecificToken(nonce: Windows.Storage.Streams.IBuffer): Windows.System.Profile.HardwareToken; - } - export class HardwareIdentification { - static getPackageSpecificToken(nonce: Windows.Storage.Streams.IBuffer): Windows.System.Profile.HardwareToken; - } - } - } -} -declare module Windows { - export module System { - export module Threading { - export enum WorkItemPriority { - low, - normal, - high, - } - export enum WorkItemOptions { - none, - timeSliced, - } - export interface TimerElapsedHandler { - (timer: Windows.System.Threading.ThreadPoolTimer): void; - } - export class ThreadPoolTimer implements Windows.System.Threading.IThreadPoolTimer { - delay: number; - period: number; - cancel(): void; - static createPeriodicTimer(handler: Windows.System.Threading.TimerElapsedHandler, period: number): Windows.System.Threading.ThreadPoolTimer; - static createTimer(handler: Windows.System.Threading.TimerElapsedHandler, delay: number): Windows.System.Threading.ThreadPoolTimer; - static createPeriodicTimer(handler: Windows.System.Threading.TimerElapsedHandler, period: number, destroyed: Windows.System.Threading.TimerDestroyedHandler): Windows.System.Threading.ThreadPoolTimer; - static createTimer(handler: Windows.System.Threading.TimerElapsedHandler, delay: number, destroyed: Windows.System.Threading.TimerDestroyedHandler): Windows.System.Threading.ThreadPoolTimer; - } - export interface TimerDestroyedHandler { - (timer: Windows.System.Threading.ThreadPoolTimer): void; - } - export interface WorkItemHandler { - (operation: Windows.Foundation.IAsyncAction): void; - } - export interface IThreadPoolStatics { - runAsync(handler: Windows.System.Threading.WorkItemHandler): Windows.Foundation.IAsyncAction; - runAsync(handler: Windows.System.Threading.WorkItemHandler, priority: Windows.System.Threading.WorkItemPriority): Windows.Foundation.IAsyncAction; - runAsync(handler: Windows.System.Threading.WorkItemHandler, priority: Windows.System.Threading.WorkItemPriority, options: Windows.System.Threading.WorkItemOptions): Windows.Foundation.IAsyncAction; - } - export interface IThreadPoolTimer { - delay: number; - period: number; - cancel(): void; - } - export interface IThreadPoolTimerStatics { - createPeriodicTimer(handler: Windows.System.Threading.TimerElapsedHandler, period: number): Windows.System.Threading.ThreadPoolTimer; - createTimer(handler: Windows.System.Threading.TimerElapsedHandler, delay: number): Windows.System.Threading.ThreadPoolTimer; - createPeriodicTimer(handler: Windows.System.Threading.TimerElapsedHandler, period: number, destroyed: Windows.System.Threading.TimerDestroyedHandler): Windows.System.Threading.ThreadPoolTimer; - createTimer(handler: Windows.System.Threading.TimerElapsedHandler, delay: number, destroyed: Windows.System.Threading.TimerDestroyedHandler): Windows.System.Threading.ThreadPoolTimer; - } - export class ThreadPool { - static runAsync(handler: Windows.System.Threading.WorkItemHandler): Windows.Foundation.IAsyncAction; - static runAsync(handler: Windows.System.Threading.WorkItemHandler, priority: Windows.System.Threading.WorkItemPriority): Windows.Foundation.IAsyncAction; - static runAsync(handler: Windows.System.Threading.WorkItemHandler, priority: Windows.System.Threading.WorkItemPriority, options: Windows.System.Threading.WorkItemOptions): Windows.Foundation.IAsyncAction; - } - } - } -} -declare module Windows { - export module System { - export module Threading { - export module Core { - export interface SignalHandler { - (signalNotifier: Windows.System.Threading.Core.SignalNotifier, timedOut: boolean): void; - } - export class SignalNotifier implements Windows.System.Threading.Core.ISignalNotifier { - enable(): void; - terminate(): void; - static attachToEvent(name: string, handler: Windows.System.Threading.Core.SignalHandler): Windows.System.Threading.Core.SignalNotifier; - static attachToEvent(name: string, handler: Windows.System.Threading.Core.SignalHandler, timeout: number): Windows.System.Threading.Core.SignalNotifier; - static attachToSemaphore(name: string, handler: Windows.System.Threading.Core.SignalHandler): Windows.System.Threading.Core.SignalNotifier; - static attachToSemaphore(name: string, handler: Windows.System.Threading.Core.SignalHandler, timeout: number): Windows.System.Threading.Core.SignalNotifier; - } - export interface ISignalNotifierStatics { - attachToEvent(name: string, handler: Windows.System.Threading.Core.SignalHandler): Windows.System.Threading.Core.SignalNotifier; - attachToEvent(name: string, handler: Windows.System.Threading.Core.SignalHandler, timeout: number): Windows.System.Threading.Core.SignalNotifier; - attachToSemaphore(name: string, handler: Windows.System.Threading.Core.SignalHandler): Windows.System.Threading.Core.SignalNotifier; - attachToSemaphore(name: string, handler: Windows.System.Threading.Core.SignalHandler, timeout: number): Windows.System.Threading.Core.SignalNotifier; - } - export interface IPreallocatedWorkItemFactory { - createWorkItem(handler: Windows.System.Threading.WorkItemHandler): Windows.System.Threading.Core.PreallocatedWorkItem; - createWorkItemWithPriority(handler: Windows.System.Threading.WorkItemHandler, priority: Windows.System.Threading.WorkItemPriority): Windows.System.Threading.Core.PreallocatedWorkItem; - createWorkItemWithPriorityAndOptions(handler: Windows.System.Threading.WorkItemHandler, priority: Windows.System.Threading.WorkItemPriority, options: Windows.System.Threading.WorkItemOptions): Windows.System.Threading.Core.PreallocatedWorkItem; - } - export class PreallocatedWorkItem implements Windows.System.Threading.Core.IPreallocatedWorkItem { - constructor(handler: Windows.System.Threading.WorkItemHandler); - constructor(handler: Windows.System.Threading.WorkItemHandler, priority: Windows.System.Threading.WorkItemPriority); - constructor(handler: Windows.System.Threading.WorkItemHandler, priority: Windows.System.Threading.WorkItemPriority, options: Windows.System.Threading.WorkItemOptions); - runAsync(): Windows.Foundation.IAsyncAction; - } - export interface IPreallocatedWorkItem { - runAsync(): Windows.Foundation.IAsyncAction; - } - export interface ISignalNotifier { - enable(): void; - terminate(): void; - } - } - } - } -} -declare module Windows { - export module System { - export module UserProfile { - export enum AccountPictureKind { - smallImage, - largeImage, - video, - } - export enum SetAccountPictureResult { - success, - changeDisabled, - largeOrDynamicError, - videoFrameSizeError, - fileSizeError, - failure, - } - export interface IUserInformationStatics { - accountPictureChangeEnabled: boolean; - nameAccessAllowed: boolean; - getAccountPicture(kind: Windows.System.UserProfile.AccountPictureKind): Windows.Storage.IStorageFile; - setAccountPictureAsync(image: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncOperation; - setAccountPicturesAsync(smallImage: Windows.Storage.IStorageFile, largeImage: Windows.Storage.IStorageFile, video: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncOperation; - setAccountPictureFromStreamAsync(image: Windows.Storage.Streams.IRandomAccessStream): Windows.Foundation.IAsyncOperation; - setAccountPicturesFromStreamsAsync(smallImage: Windows.Storage.Streams.IRandomAccessStream, largeImage: Windows.Storage.Streams.IRandomAccessStream, video: Windows.Storage.Streams.IRandomAccessStream): Windows.Foundation.IAsyncOperation; - onaccountpicturechanged: any/* TODO */; - getDisplayNameAsync(): Windows.Foundation.IAsyncOperation; - getFirstNameAsync(): Windows.Foundation.IAsyncOperation; - getLastNameAsync(): Windows.Foundation.IAsyncOperation; - getPrincipalNameAsync(): Windows.Foundation.IAsyncOperation; - getSessionInitiationProtocolUriAsync(): Windows.Foundation.IAsyncOperation; - getDomainNameAsync(): Windows.Foundation.IAsyncOperation; - } - export class UserInformation { - static accountPictureChangeEnabled: boolean; - static nameAccessAllowed: boolean; - static getAccountPicture(kind: Windows.System.UserProfile.AccountPictureKind): Windows.Storage.IStorageFile; - static setAccountPictureAsync(image: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncOperation; - static setAccountPicturesAsync(smallImage: Windows.Storage.IStorageFile, largeImage: Windows.Storage.IStorageFile, video: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncOperation; - static setAccountPictureFromStreamAsync(image: Windows.Storage.Streams.IRandomAccessStream): Windows.Foundation.IAsyncOperation; - static setAccountPicturesFromStreamsAsync(smallImage: Windows.Storage.Streams.IRandomAccessStream, largeImage: Windows.Storage.Streams.IRandomAccessStream, video: Windows.Storage.Streams.IRandomAccessStream): Windows.Foundation.IAsyncOperation; - static onaccountpicturechanged: any/* TODO */; - static getDisplayNameAsync(): Windows.Foundation.IAsyncOperation; - static getFirstNameAsync(): Windows.Foundation.IAsyncOperation; - static getLastNameAsync(): Windows.Foundation.IAsyncOperation; - static getPrincipalNameAsync(): Windows.Foundation.IAsyncOperation; - static getSessionInitiationProtocolUriAsync(): Windows.Foundation.IAsyncOperation; - static getDomainNameAsync(): Windows.Foundation.IAsyncOperation; - } - export interface ILockScreenStatics { - originalImageFile: Windows.Foundation.Uri; - getImageStream(): Windows.Storage.Streams.IRandomAccessStream; - setImageFileAsync(value: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncAction; - setImageStreamAsync(value: Windows.Storage.Streams.IRandomAccessStream): Windows.Foundation.IAsyncAction; - } - export class LockScreen { - static originalImageFile: Windows.Foundation.Uri; - static getImageStream(): Windows.Storage.Streams.IRandomAccessStream; - static setImageFileAsync(value: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncAction; - static setImageStreamAsync(value: Windows.Storage.Streams.IRandomAccessStream): Windows.Foundation.IAsyncAction; - } - export interface IGlobalizationPreferencesStatics { - calendars: Windows.Foundation.Collections.IVectorView; - clocks: Windows.Foundation.Collections.IVectorView; - currencies: Windows.Foundation.Collections.IVectorView; - homeGeographicRegion: string; - languages: Windows.Foundation.Collections.IVectorView; - weekStartsOn: Windows.Globalization.DayOfWeek; - } - export class GlobalizationPreferences { - static calendars: Windows.Foundation.Collections.IVectorView; - static clocks: Windows.Foundation.Collections.IVectorView; - static currencies: Windows.Foundation.Collections.IVectorView; - static homeGeographicRegion: string; - static languages: Windows.Foundation.Collections.IVectorView; - static weekStartsOn: Windows.Globalization.DayOfWeek; - } - } - } -} -declare module Windows { - export module System { - export interface ILauncherUIOptions { - invocationPoint: Windows.Foundation.Point; - preferredPlacement: Windows.UI.Popups.Placement; - selectionRect: Windows.Foundation.Rect; - } - export class LauncherUIOptions implements Windows.System.ILauncherUIOptions { - invocationPoint: Windows.Foundation.Point; - preferredPlacement: Windows.UI.Popups.Placement; - selectionRect: Windows.Foundation.Rect; - } - export interface ILauncherOptions { - contentType: string; - 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; - displayApplicationPicker: boolean; - fallbackUri: Windows.Foundation.Uri; - preferredApplicationDisplayName: string; - preferredApplicationPackageFamilyName: string; - treatAsUntrusted: boolean; - uI: Windows.System.LauncherUIOptions; - } - export interface ILauncherStatics { - launchFileAsync(file: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncOperation; - launchFileAsync(file: Windows.Storage.IStorageFile, options: Windows.System.LauncherOptions): Windows.Foundation.IAsyncOperation; - launchUriAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperation; - launchUriAsync(uri: Windows.Foundation.Uri, options: Windows.System.LauncherOptions): Windows.Foundation.IAsyncOperation; - } - export class Launcher { - static launchFileAsync(file: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncOperation; - static launchFileAsync(file: Windows.Storage.IStorageFile, options: Windows.System.LauncherOptions): Windows.Foundation.IAsyncOperation; - static launchUriAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperation; - static launchUriAsync(uri: Windows.Foundation.Uri, options: Windows.System.LauncherOptions): Windows.Foundation.IAsyncOperation; - } - export enum ProcessorArchitecture { - x86, - arm, - x64, - neutral, - unknown, - } - export enum VirtualKeyModifiers { - none, - control, - menu, - shift, - windows, - } - export enum VirtualKey { - none, - leftButton, - rightButton, - cancel, - middleButton, - xButton1, - xButton2, - back, - tab, - clear, - enter, - shift, - control, - menu, - pause, - capitalLock, - kana, - hangul, - junja, - final, - hanja, - kanji, - escape, - convert, - nonConvert, - accept, - modeChange, - space, - pageUp, - pageDown, - end, - home, - left, - up, - right, - down, - select, - print, - execute, - snapshot, - insert, - delete_, - help, - number0, - number1, - number2, - number3, - number4, - number5, - number6, - number7, - number8, - number9, - a, - b, - c, - d, - e, - f, - g, - h, - i, - j, - k, - l, - m, - n, - o, - p, - q, - r, - s, - t, - u, - v, - w, - x, - y, - z, - leftWindows, - rightWindows, - application, - sleep, - numberPad0, - numberPad1, - numberPad2, - numberPad3, - numberPad4, - numberPad5, - numberPad6, - numberPad7, - numberPad8, - numberPad9, - multiply, - add, - separator, - subtract, - decimal, - divide, - f1, - f2, - f3, - f4, - f5, - f6, - f7, - f8, - f9, - f10, - f11, - f12, - f13, - f14, - f15, - f16, - f17, - f18, - f19, - f20, - f21, - f22, - f23, - f24, - numberKeyLock, - scroll, - leftShift, - rightShift, - leftControl, - rightControl, - leftMenu, - rightMenu, - } - } -} -declare module Windows { - export module System { - export module Display { - export interface IDisplayRequest { - requestActive(): void; - requestRelease(): void; - } - export class DisplayRequest implements Windows.System.Display.IDisplayRequest { - requestActive(): void; - requestRelease(): void; - } - } - } -} -declare module Windows { - export module System { - export module RemoteDesktop { - export interface IInteractiveSessionStatics { - isRemote: boolean; - } - export class InteractiveSession { - static isRemote: boolean; - } - } - } -} -declare module Windows { - export module UI { - export module ApplicationSettings { - export interface ISettingsCommandFactory { - create(settingsCommandId: any, label: string, handler: Windows.UI.Popups.UICommandInvokedHandler): Windows.UI.ApplicationSettings.SettingsCommand; - } - export class SettingsCommand implements Windows.UI.Popups.IUICommand { - constructor(settingsCommandId: any, label: string, handler: Windows.UI.Popups.UICommandInvokedHandler); - id: any; - invoked: Windows.UI.Popups.UICommandInvokedHandler; - label: string; - } - export interface ISettingsPaneCommandsRequest { - applicationCommands: Windows.Foundation.Collections.IVector; - } - export class SettingsPaneCommandsRequest implements Windows.UI.ApplicationSettings.ISettingsPaneCommandsRequest { - applicationCommands: Windows.Foundation.Collections.IVector; - } - export interface ISettingsPaneCommandsRequestedEventArgs { - request: Windows.UI.ApplicationSettings.SettingsPaneCommandsRequest; - } - export class SettingsPaneCommandsRequestedEventArgs implements Windows.UI.ApplicationSettings.ISettingsPaneCommandsRequestedEventArgs { - request: Windows.UI.ApplicationSettings.SettingsPaneCommandsRequest; - } - export enum SettingsEdgeLocation { - right, - left, - } - export interface ISettingsPaneStatics { - edge: Windows.UI.ApplicationSettings.SettingsEdgeLocation; - getForCurrentView(): Windows.UI.ApplicationSettings.SettingsPane; - show(): void; - } - export class SettingsPane implements Windows.UI.ApplicationSettings.ISettingsPane { - oncommandsrequested: any/* TODO */; - static edge: Windows.UI.ApplicationSettings.SettingsEdgeLocation; - static getForCurrentView(): Windows.UI.ApplicationSettings.SettingsPane; - static show(): void; - } - export interface ISettingsPane { - oncommandsrequested: any/* TODO */; - } - } - } -} -declare module Windows { - export module UI { - export module ViewManagement { - export enum ApplicationViewState { - fullScreenLandscape, - filled, - snapped, - fullScreenPortrait, - } - export interface IApplicationViewStatics { - value: Windows.UI.ViewManagement.ApplicationViewState; - tryUnsnap(): boolean; - } - export class ApplicationView { - static value: Windows.UI.ViewManagement.ApplicationViewState; - static tryUnsnap(): boolean; - } - export interface IInputPaneVisibilityEventArgs { - ensuredFocusedElementInView: boolean; - occludedRect: Windows.Foundation.Rect; - } - export class InputPaneVisibilityEventArgs implements Windows.UI.ViewManagement.IInputPaneVisibilityEventArgs { - ensuredFocusedElementInView: boolean; - occludedRect: Windows.Foundation.Rect; - } - export interface IInputPane { - occludedRect: Windows.Foundation.Rect; - onshowing: any/* TODO */; - onhiding: any/* TODO */; - } - export class InputPane implements Windows.UI.ViewManagement.IInputPane { - occludedRect: Windows.Foundation.Rect; - onshowing: any/* TODO */; - onhiding: any/* TODO */; - static getForCurrentView(): Windows.UI.ViewManagement.InputPane; - } - export interface IInputPaneStatics { - getForCurrentView(): Windows.UI.ViewManagement.InputPane; - } - export enum HandPreference { - leftHanded, - rightHanded, - } - export enum UIElementType { - activeCaption, - background, - buttonFace, - buttonText, - captionText, - grayText, - highlight, - highlightText, - hotlight, - inactiveCaption, - inactiveCaptionText, - window, - windowText, - } - export interface IAccessibilitySettings { - highContrast: boolean; - highContrastScheme: string; - onhighcontrastchanged: any/* TODO */; - } - export class AccessibilitySettings implements Windows.UI.ViewManagement.IAccessibilitySettings { - highContrast: boolean; - highContrastScheme: string; - onhighcontrastchanged: any/* TODO */; - } - export interface IUISettings { - animationsEnabled: boolean; - caretBlinkRate: number; - caretBrowsingEnabled: boolean; - caretWidth: number; - cursorSize: Windows.Foundation.Size; - doubleClickTime: number; - handPreference: Windows.UI.ViewManagement.HandPreference; - messageDuration: number; - mouseHoverTime: number; - scrollBarArrowSize: Windows.Foundation.Size; - scrollBarSize: Windows.Foundation.Size; - scrollBarThumbBoxSize: Windows.Foundation.Size; - uIElementColor(desiredElement: Windows.UI.ViewManagement.UIElementType): Windows.UI.Color; - } - export class UISettings implements Windows.UI.ViewManagement.IUISettings { - animationsEnabled: boolean; - caretBlinkRate: number; - caretBrowsingEnabled: boolean; - caretWidth: number; - cursorSize: Windows.Foundation.Size; - doubleClickTime: number; - handPreference: Windows.UI.ViewManagement.HandPreference; - messageDuration: number; - mouseHoverTime: number; - scrollBarArrowSize: Windows.Foundation.Size; - scrollBarSize: Windows.Foundation.Size; - scrollBarThumbBoxSize: Windows.Foundation.Size; - uIElementColor(desiredElement: Windows.UI.ViewManagement.UIElementType): Windows.UI.Color; - } - } - } -} -declare module Windows { - export module UI { - export module Input { - export enum EdgeGestureKind { - touch, - keyboard, - mouse, - } - export interface IEdgeGestureEventArgs { - kind: Windows.UI.Input.EdgeGestureKind; - } - export class EdgeGestureEventArgs implements Windows.UI.Input.IEdgeGestureEventArgs { - kind: Windows.UI.Input.EdgeGestureKind; - } - export interface IEdgeGestureStatics { - getForCurrentView(): Windows.UI.Input.EdgeGesture; - } - export class EdgeGesture implements Windows.UI.Input.IEdgeGesture { - onstarting: any/* TODO */; - oncompleted: any/* TODO */; - oncanceled: any/* TODO */; - static getForCurrentView(): Windows.UI.Input.EdgeGesture; - } - export interface IEdgeGesture { - onstarting: any/* TODO */; - oncompleted: any/* TODO */; - oncanceled: any/* TODO */; - } - export enum HoldingState { - started, - completed, - canceled, - } - export enum DraggingState { - started, - continuing, - completed, - } - export enum CrossSlidingState { - started, - dragging, - selecting, - selectSpeedBumping, - speedBumping, - rearranging, - completed, - } - export enum GestureSettings { - none, - tap, - doubleTap, - hold, - holdWithMouse, - rightTap, - drag, - manipulationTranslateX, - manipulationTranslateY, - manipulationTranslateRailsX, - manipulationTranslateRailsY, - manipulationRotate, - manipulationScale, - manipulationTranslateInertia, - manipulationRotateInertia, - manipulationScaleInertia, - crossSlide, - } - export interface ManipulationDelta { - translation: Windows.Foundation.Point; - scale: number; - rotation: number; - expansion: number; - } - export interface ManipulationVelocities { - linear: Windows.Foundation.Point; - angular: number; - expansion: number; - } - export interface CrossSlideThresholds { - selectionStart: number; - speedBumpStart: number; - speedBumpEnd: number; - rearrangeStart: number; - } - export interface ITappedEventArgs { - pointerDeviceType: Windows.Devices.Input.PointerDeviceType; - position: Windows.Foundation.Point; - tapCount: number; - } - export interface IRightTappedEventArgs { - pointerDeviceType: Windows.Devices.Input.PointerDeviceType; - position: Windows.Foundation.Point; - } - export interface IHoldingEventArgs { - holdingState: Windows.UI.Input.HoldingState; - pointerDeviceType: Windows.Devices.Input.PointerDeviceType; - position: Windows.Foundation.Point; - } - export interface IDraggingEventArgs { - draggingState: Windows.UI.Input.DraggingState; - pointerDeviceType: Windows.Devices.Input.PointerDeviceType; - position: Windows.Foundation.Point; - } - export interface IManipulationStartedEventArgs { - cumulative: Windows.UI.Input.ManipulationDelta; - pointerDeviceType: Windows.Devices.Input.PointerDeviceType; - position: Windows.Foundation.Point; - } - export interface IManipulationUpdatedEventArgs { - cumulative: Windows.UI.Input.ManipulationDelta; - delta: Windows.UI.Input.ManipulationDelta; - pointerDeviceType: Windows.Devices.Input.PointerDeviceType; - position: Windows.Foundation.Point; - velocities: Windows.UI.Input.ManipulationVelocities; - } - export interface IManipulationInertiaStartingEventArgs { - cumulative: Windows.UI.Input.ManipulationDelta; - delta: Windows.UI.Input.ManipulationDelta; - pointerDeviceType: Windows.Devices.Input.PointerDeviceType; - position: Windows.Foundation.Point; - velocities: Windows.UI.Input.ManipulationVelocities; - } - export interface IManipulationCompletedEventArgs { - cumulative: Windows.UI.Input.ManipulationDelta; - pointerDeviceType: Windows.Devices.Input.PointerDeviceType; - position: Windows.Foundation.Point; - velocities: Windows.UI.Input.ManipulationVelocities; - } - export interface ICrossSlidingEventArgs { - crossSlidingState: Windows.UI.Input.CrossSlidingState; - pointerDeviceType: Windows.Devices.Input.PointerDeviceType; - position: Windows.Foundation.Point; - } - export interface IMouseWheelParameters { - charTranslation: Windows.Foundation.Point; - deltaRotationAngle: number; - deltaScale: number; - pageTranslation: Windows.Foundation.Point; - } - export interface IGestureRecognizer { - autoProcessInertia: boolean; - crossSlideExact: boolean; - crossSlideHorizontally: boolean; - crossSlideThresholds: Windows.UI.Input.CrossSlideThresholds; - gestureSettings: Windows.UI.Input.GestureSettings; - inertiaExpansion: number; - inertiaExpansionDeceleration: number; - inertiaRotationAngle: number; - inertiaRotationDeceleration: number; - inertiaTranslationDeceleration: number; - inertiaTranslationDisplacement: number; - isActive: boolean; - isInertial: boolean; - manipulationExact: boolean; - mouseWheelParameters: Windows.UI.Input.MouseWheelParameters; - pivotCenter: Windows.Foundation.Point; - pivotRadius: number; - showGestureFeedback: boolean; - canBeDoubleTap(value: Windows.UI.Input.PointerPoint): boolean; - processDownEvent(value: Windows.UI.Input.PointerPoint): void; - processMoveEvents(value: Windows.Foundation.Collections.IVector): void; - processUpEvent(value: Windows.UI.Input.PointerPoint): void; - processMouseWheelEvent(value: Windows.UI.Input.PointerPoint, isShiftKeyDown: boolean, isControlKeyDown: boolean): void; - processInertia(): void; - completeGesture(): void; - ontapped: any/* TODO */; - onrighttapped: any/* TODO */; - onholding: any/* TODO */; - ondragging: any/* TODO */; - onmanipulationstarted: any/* TODO */; - onmanipulationupdated: any/* TODO */; - onmanipulationinertiastarting: any/* TODO */; - onmanipulationcompleted: any/* TODO */; - oncrosssliding: any/* TODO */; - } - export class MouseWheelParameters implements Windows.UI.Input.IMouseWheelParameters { - charTranslation: Windows.Foundation.Point; - deltaRotationAngle: number; - deltaScale: number; - pageTranslation: Windows.Foundation.Point; - } - export class GestureRecognizer implements Windows.UI.Input.IGestureRecognizer { - autoProcessInertia: boolean; - crossSlideExact: boolean; - crossSlideHorizontally: boolean; - crossSlideThresholds: Windows.UI.Input.CrossSlideThresholds; - gestureSettings: Windows.UI.Input.GestureSettings; - inertiaExpansion: number; - inertiaExpansionDeceleration: number; - inertiaRotationAngle: number; - inertiaRotationDeceleration: number; - inertiaTranslationDeceleration: number; - inertiaTranslationDisplacement: number; - isActive: boolean; - isInertial: boolean; - manipulationExact: boolean; - mouseWheelParameters: Windows.UI.Input.MouseWheelParameters; - pivotCenter: Windows.Foundation.Point; - pivotRadius: number; - showGestureFeedback: boolean; - canBeDoubleTap(value: Windows.UI.Input.PointerPoint): boolean; - processDownEvent(value: Windows.UI.Input.PointerPoint): void; - processMoveEvents(value: Windows.Foundation.Collections.IVector): void; - processUpEvent(value: Windows.UI.Input.PointerPoint): void; - processMouseWheelEvent(value: Windows.UI.Input.PointerPoint, isShiftKeyDown: boolean, isControlKeyDown: boolean): void; - processInertia(): void; - completeGesture(): void; - ontapped: any/* TODO */; - onrighttapped: any/* TODO */; - onholding: any/* TODO */; - ondragging: any/* TODO */; - onmanipulationstarted: any/* TODO */; - onmanipulationupdated: any/* TODO */; - onmanipulationinertiastarting: any/* TODO */; - onmanipulationcompleted: any/* TODO */; - oncrosssliding: any/* TODO */; - } - export class TappedEventArgs implements Windows.UI.Input.ITappedEventArgs { - pointerDeviceType: Windows.Devices.Input.PointerDeviceType; - position: Windows.Foundation.Point; - tapCount: number; - } - export class RightTappedEventArgs implements Windows.UI.Input.IRightTappedEventArgs { - pointerDeviceType: Windows.Devices.Input.PointerDeviceType; - position: Windows.Foundation.Point; - } - export class HoldingEventArgs implements Windows.UI.Input.IHoldingEventArgs { - holdingState: Windows.UI.Input.HoldingState; - pointerDeviceType: Windows.Devices.Input.PointerDeviceType; - position: Windows.Foundation.Point; - } - export class DraggingEventArgs implements Windows.UI.Input.IDraggingEventArgs { - draggingState: Windows.UI.Input.DraggingState; - pointerDeviceType: Windows.Devices.Input.PointerDeviceType; - position: Windows.Foundation.Point; - } - export class ManipulationStartedEventArgs implements Windows.UI.Input.IManipulationStartedEventArgs { - cumulative: Windows.UI.Input.ManipulationDelta; - pointerDeviceType: Windows.Devices.Input.PointerDeviceType; - position: Windows.Foundation.Point; - } - export class ManipulationUpdatedEventArgs implements Windows.UI.Input.IManipulationUpdatedEventArgs { - cumulative: Windows.UI.Input.ManipulationDelta; - delta: Windows.UI.Input.ManipulationDelta; - pointerDeviceType: Windows.Devices.Input.PointerDeviceType; - position: Windows.Foundation.Point; - velocities: Windows.UI.Input.ManipulationVelocities; - } - export class ManipulationInertiaStartingEventArgs implements Windows.UI.Input.IManipulationInertiaStartingEventArgs { - cumulative: Windows.UI.Input.ManipulationDelta; - delta: Windows.UI.Input.ManipulationDelta; - pointerDeviceType: Windows.Devices.Input.PointerDeviceType; - position: Windows.Foundation.Point; - velocities: Windows.UI.Input.ManipulationVelocities; - } - export class ManipulationCompletedEventArgs implements Windows.UI.Input.IManipulationCompletedEventArgs { - cumulative: Windows.UI.Input.ManipulationDelta; - pointerDeviceType: Windows.Devices.Input.PointerDeviceType; - position: Windows.Foundation.Point; - velocities: Windows.UI.Input.ManipulationVelocities; - } - export class CrossSlidingEventArgs implements Windows.UI.Input.ICrossSlidingEventArgs { - crossSlidingState: Windows.UI.Input.CrossSlidingState; - pointerDeviceType: Windows.Devices.Input.PointerDeviceType; - position: Windows.Foundation.Point; - } - export interface IPointerPointStatics { - getCurrentPoint(pointerId: number): Windows.UI.Input.PointerPoint; - getIntermediatePoints(pointerId: number): Windows.Foundation.Collections.IVector; - getCurrentPoint(pointerId: number, transform: Windows.UI.Input.IPointerPointTransform): Windows.UI.Input.PointerPoint; - getIntermediatePoints(pointerId: number, transform: Windows.UI.Input.IPointerPointTransform): Windows.Foundation.Collections.IVector; - } - export class PointerPoint implements Windows.UI.Input.IPointerPoint { - frameId: number; - isInContact: boolean; - pointerDevice: Windows.Devices.Input.PointerDevice; - pointerId: number; - position: Windows.Foundation.Point; - properties: Windows.UI.Input.PointerPointProperties; - rawPosition: Windows.Foundation.Point; - timestamp: number; - static getCurrentPoint(pointerId: number): Windows.UI.Input.PointerPoint; - static getIntermediatePoints(pointerId: number): Windows.Foundation.Collections.IVector; - static getCurrentPoint(pointerId: number, transform: Windows.UI.Input.IPointerPointTransform): Windows.UI.Input.PointerPoint; - static getIntermediatePoints(pointerId: number, transform: Windows.UI.Input.IPointerPointTransform): Windows.Foundation.Collections.IVector; - } - export interface IPointerPointTransform { - inverse: Windows.UI.Input.IPointerPointTransform; - tryTransform(inPoint: Windows.Foundation.Point): { outPoint: Windows.Foundation.Point; returnValue: boolean; }; - transformBounds(rect: Windows.Foundation.Rect): Windows.Foundation.Rect; - } - export interface IPointerPoint { - frameId: number; - isInContact: boolean; - pointerDevice: Windows.Devices.Input.PointerDevice; - pointerId: number; - position: Windows.Foundation.Point; - properties: Windows.UI.Input.PointerPointProperties; - rawPosition: Windows.Foundation.Point; - timestamp: number; - } - export class PointerPointProperties implements Windows.UI.Input.IPointerPointProperties { - contactRect: Windows.Foundation.Rect; - contactRectRaw: Windows.Foundation.Rect; - isBarrelButtonPressed: boolean; - isCanceled: boolean; - isEraser: boolean; - isHorizontalMouseWheel: boolean; - isInRange: boolean; - isInverted: boolean; - isLeftButtonPressed: boolean; - isMiddleButtonPressed: boolean; - isPrimary: boolean; - isRightButtonPressed: boolean; - isXButton1Pressed: boolean; - isXButton2Pressed: boolean; - mouseWheelDelta: number; - orientation: number; - pointerUpdateKind: Windows.UI.Input.PointerUpdateKind; - pressure: number; - touchConfidence: boolean; - twist: number; - xTilt: number; - yTilt: number; - hasUsage(usagePage: number, usageId: number): boolean; - getUsageValue(usagePage: number, usageId: number): number; - } - export enum PointerUpdateKind { - other, - leftButtonPressed, - leftButtonReleased, - rightButtonPressed, - rightButtonReleased, - middleButtonPressed, - middleButtonReleased, - xButton1Pressed, - xButton1Released, - xButton2Pressed, - xButton2Released, - } - export interface IPointerPointProperties { - contactRect: Windows.Foundation.Rect; - contactRectRaw: Windows.Foundation.Rect; - isBarrelButtonPressed: boolean; - isCanceled: boolean; - isEraser: boolean; - isHorizontalMouseWheel: boolean; - isInRange: boolean; - isInverted: boolean; - isLeftButtonPressed: boolean; - isMiddleButtonPressed: boolean; - isPrimary: boolean; - isRightButtonPressed: boolean; - isXButton1Pressed: boolean; - isXButton2Pressed: boolean; - mouseWheelDelta: number; - orientation: number; - pointerUpdateKind: Windows.UI.Input.PointerUpdateKind; - pressure: number; - touchConfidence: boolean; - twist: number; - xTilt: number; - yTilt: number; - hasUsage(usagePage: number, usageId: number): boolean; - getUsageValue(usagePage: number, usageId: number): number; - } - export interface IPointerVisualizationSettings { - isBarrelButtonFeedbackEnabled: boolean; - isContactFeedbackEnabled: boolean; - } - export interface IPointerVisualizationSettingsStatics { - getForCurrentView(): Windows.UI.Input.PointerVisualizationSettings; - } - export class PointerVisualizationSettings implements Windows.UI.Input.IPointerVisualizationSettings { - isBarrelButtonFeedbackEnabled: boolean; - isContactFeedbackEnabled: boolean; - static getForCurrentView(): Windows.UI.Input.PointerVisualizationSettings; - } - } - } -} -declare module Windows { - export module UI { - export module Popups { - export enum MessageDialogOptions { - none, - acceptUserInputAfterDelay, - } - export interface IMessageDialog { - cancelCommandIndex: number; - commands: Windows.Foundation.Collections.IVector; - content: string; - defaultCommandIndex: number; - options: Windows.UI.Popups.MessageDialogOptions; - title: string; - showAsync(): Windows.Foundation.IAsyncOperation; - } - export interface IMessageDialogFactory { - create(content: string): Windows.UI.Popups.MessageDialog; - createWithTitle(content: string, title: string): Windows.UI.Popups.MessageDialog; - } - export class MessageDialog implements Windows.UI.Popups.IMessageDialog { - constructor(content: string); - constructor(content: string, title: string); - cancelCommandIndex: number; - commands: Windows.Foundation.Collections.IVector; - content: string; - defaultCommandIndex: number; - options: Windows.UI.Popups.MessageDialogOptions; - title: string; - showAsync(): Windows.Foundation.IAsyncOperation; - } - export enum Placement { - default, - above, - below, - left, - right, - } - export interface UICommandInvokedHandler { - (command: Windows.UI.Popups.IUICommand): void; - } - export interface IUICommand { - id: any; - invoked: Windows.UI.Popups.UICommandInvokedHandler; - label: string; - } - export interface IUICommandFactory { - create(label: string): Windows.UI.Popups.UICommand; - createWithHandler(label: string, action: Windows.UI.Popups.UICommandInvokedHandler): Windows.UI.Popups.UICommand; - createWithHandlerAndId(label: string, action: Windows.UI.Popups.UICommandInvokedHandler, commandId: any): Windows.UI.Popups.UICommand; - } - export class UICommand implements Windows.UI.Popups.IUICommand { - constructor(label: string); - constructor(label: string, action: Windows.UI.Popups.UICommandInvokedHandler); - constructor(label: string, action: Windows.UI.Popups.UICommandInvokedHandler, commandId: any); - constructor(); - id: any; - invoked: Windows.UI.Popups.UICommandInvokedHandler; - label: string; - } - export class UICommandSeparator implements Windows.UI.Popups.IUICommand { - id: any; - invoked: Windows.UI.Popups.UICommandInvokedHandler; - label: string; - } - export interface IPopupMenu { - commands: Windows.Foundation.Collections.IVector; - showAsync(invocationPoint: Windows.Foundation.Point): Windows.Foundation.IAsyncOperation; - showForSelectionAsync(selection: Windows.Foundation.Rect): Windows.Foundation.IAsyncOperation; - showForSelectionAsync(selection: Windows.Foundation.Rect, preferredPlacement: Windows.UI.Popups.Placement): Windows.Foundation.IAsyncOperation; - } - export class PopupMenu implements Windows.UI.Popups.IPopupMenu { - commands: Windows.Foundation.Collections.IVector; - showAsync(invocationPoint: Windows.Foundation.Point): Windows.Foundation.IAsyncOperation; - showForSelectionAsync(selection: Windows.Foundation.Rect): Windows.Foundation.IAsyncOperation; - showForSelectionAsync(selection: Windows.Foundation.Rect, preferredPlacement: Windows.UI.Popups.Placement): Windows.Foundation.IAsyncOperation; - } - } - } -} -declare module Windows { - export module UI { - export module StartScreen { - export enum TileOptions { - none, - showNameOnLogo, - showNameOnWideLogo, - copyOnDeployment, - } - export enum ForegroundText { - dark, - light, - } - export interface ISecondaryTile { - arguments: string; - backgroundColor: Windows.UI.Color; - displayName: string; - foregroundText: Windows.UI.StartScreen.ForegroundText; - lockScreenBadgeLogo: Windows.Foundation.Uri; - lockScreenDisplayBadgeAndTileText: boolean; - logo: Windows.Foundation.Uri; - shortName: string; - smallLogo: Windows.Foundation.Uri; - tileId: string; - tileOptions: Windows.UI.StartScreen.TileOptions; - wideLogo: Windows.Foundation.Uri; - requestCreateAsync(): Windows.Foundation.IAsyncOperation; - requestCreateAsync(invocationPoint: Windows.Foundation.Point): Windows.Foundation.IAsyncOperation; - requestCreateForSelectionAsync(selection: Windows.Foundation.Rect): Windows.Foundation.IAsyncOperation; - requestCreateForSelectionAsync(selection: Windows.Foundation.Rect, preferredPlacement: Windows.UI.Popups.Placement): Windows.Foundation.IAsyncOperation; - requestDeleteAsync(): Windows.Foundation.IAsyncOperation; - requestDeleteAsync(invocationPoint: Windows.Foundation.Point): Windows.Foundation.IAsyncOperation; - requestDeleteForSelectionAsync(selection: Windows.Foundation.Rect): Windows.Foundation.IAsyncOperation; - requestDeleteForSelectionAsync(selection: Windows.Foundation.Rect, preferredPlacement: Windows.UI.Popups.Placement): Windows.Foundation.IAsyncOperation; - updateAsync(): Windows.Foundation.IAsyncOperation; - } - export interface ISecondaryTileFactory { - createTile(tileId: string, shortName: string, displayName: string, arguments: string, tileOptions: Windows.UI.StartScreen.TileOptions, logoReference: Windows.Foundation.Uri): Windows.UI.StartScreen.SecondaryTile; - createWideTile(tileId: string, shortName: string, displayName: string, arguments: string, tileOptions: Windows.UI.StartScreen.TileOptions, logoReference: Windows.Foundation.Uri, wideLogoReference: Windows.Foundation.Uri): Windows.UI.StartScreen.SecondaryTile; - createWithId(tileId: string): Windows.UI.StartScreen.SecondaryTile; - } - export class SecondaryTile implements Windows.UI.StartScreen.ISecondaryTile { - constructor(tileId: string, shortName: string, displayName: string, arguments: string, tileOptions: Windows.UI.StartScreen.TileOptions, logoReference: Windows.Foundation.Uri); - constructor(tileId: string, shortName: string, displayName: string, arguments: string, tileOptions: Windows.UI.StartScreen.TileOptions, logoReference: Windows.Foundation.Uri, wideLogoReference: Windows.Foundation.Uri); - constructor(tileId: string); - constructor(); - arguments: string; - backgroundColor: Windows.UI.Color; - displayName: string; - foregroundText: Windows.UI.StartScreen.ForegroundText; - lockScreenBadgeLogo: Windows.Foundation.Uri; - lockScreenDisplayBadgeAndTileText: boolean; - logo: Windows.Foundation.Uri; - shortName: string; - smallLogo: Windows.Foundation.Uri; - tileId: string; - tileOptions: Windows.UI.StartScreen.TileOptions; - wideLogo: Windows.Foundation.Uri; - requestCreateAsync(): Windows.Foundation.IAsyncOperation; - requestCreateAsync(invocationPoint: Windows.Foundation.Point): Windows.Foundation.IAsyncOperation; - requestCreateForSelectionAsync(selection: Windows.Foundation.Rect): Windows.Foundation.IAsyncOperation; - requestCreateForSelectionAsync(selection: Windows.Foundation.Rect, preferredPlacement: Windows.UI.Popups.Placement): Windows.Foundation.IAsyncOperation; - requestDeleteAsync(): Windows.Foundation.IAsyncOperation; - requestDeleteAsync(invocationPoint: Windows.Foundation.Point): Windows.Foundation.IAsyncOperation; - requestDeleteForSelectionAsync(selection: Windows.Foundation.Rect): Windows.Foundation.IAsyncOperation; - requestDeleteForSelectionAsync(selection: Windows.Foundation.Rect, preferredPlacement: Windows.UI.Popups.Placement): Windows.Foundation.IAsyncOperation; - updateAsync(): Windows.Foundation.IAsyncOperation; - static exists(tileId: string): boolean; - static findAllAsync(): Windows.Foundation.IAsyncOperation>; - static findAllAsync(applicationId: string): Windows.Foundation.IAsyncOperation>; - static findAllForPackageAsync(): Windows.Foundation.IAsyncOperation>; - } - export interface ISecondaryTileStatics { - exists(tileId: string): boolean; - findAllAsync(): Windows.Foundation.IAsyncOperation>; - findAllAsync(applicationId: string): Windows.Foundation.IAsyncOperation>; - findAllForPackageAsync(): Windows.Foundation.IAsyncOperation>; - } - } - } -} -declare module Windows { - export module UI { - export module Text { - export enum CaretType { - normal, - null_, - } - export enum FindOptions { - none, - word, - case_, - } - export enum FormatEffect { - off, - on, - toggle, - undefined, - } - export enum HorizontalCharacterAlignment { - left, - right, - center, - } - export enum LetterCase { - lower, - upper, - } - export enum LineSpacingRule { - undefined, - single, - oneAndHalf, - double, - atLeast, - exactly, - multiple, - percent, - } - export enum LinkType { - undefined, - notALink, - clientLink, - friendlyLinkName, - friendlyLinkAddress, - autoLink, - autoLinkEmail, - autoLinkPhone, - autoLinkPath, - } - export enum MarkerAlignment { - undefined, - left, - center, - right, - } - export enum MarkerStyle { - undefined, - parenthesis, - parentheses, - period, - plain, - minus, - noNumber, - } - export enum MarkerType { - undefined, - none, - bullet, - arabic, - lowercaseEnglishLetter, - uppercaseEnglishLetter, - lowercaseRoman, - uppercaseRoman, - unicodeSequence, - circledNumber, - blackCircleWingding, - whiteCircleWingding, - arabicWide, - simplifiedChinese, - traditionalChinese, - japanSimplifiedChinese, - japanKorea, - arabicDictionary, - arabicAbjad, - hebrew, - thaiAlphabetic, - thaiNumeric, - devanagariVowel, - devanagariConsonant, - devanagariNumeric, - } - export enum ParagraphAlignment { - undefined, - left, - center, - right, - justify, - } - export enum ParagraphStyle { - undefined, - none, - normal, - heading1, - heading2, - heading3, - heading4, - heading5, - heading6, - heading7, - heading8, - heading9, - } - export enum PointOptions { - none, - includeInset, - start, - clientCoordinates, - allowOffClient, - transform, - noHorizontalScroll, - noVerticalScroll, - } - export enum RangeGravity { - uIBehavior, - backward, - forward, - inward, - outward, - } - export enum SelectionOptions { - startActive, - atEndOfLine, - overtype, - active, - replace, - } - export enum SelectionType { - none, - insertionPoint, - normal, - inlineShape, - shape, - } - export enum TabAlignment { - left, - center, - right, - decimal, - bar, - } - export enum TabLeader { - spaces, - dots, - dashes, - lines, - thickLines, - equals, - } - export enum TextGetOptions { - none, - adjustCrlf, - useCrlf, - useObjectText, - allowFinalEop, - noHidden, - includeNumbering, - formatRtf, - } - export enum TextSetOptions { - none, - unicodeBidi, - unlink, - unhide, - checkTextLimit, - formatRtf, - applyRtfDocumentDefaults, - } - export enum TextRangeUnit { - character, - word, - sentence, - paragraph, - line, - story, - screen, - section, - window, - characterFormat, - paragraphFormat, - object, - hardParagraph, - cluster, - bold, - italic, - underline, - strikethrough, - protectedText, - link, - smallCaps, - allCaps, - hidden, - outline, - shadow, - imprint, - disabled, - revised, - subscript, - superscript, - fontBound, - linkProtected, - } - export enum TextScript { - undefined, - ansi, - eastEurope, - cyrillic, - greek, - turkish, - hebrew, - arabic, - baltic, - vietnamese, - default, - symbol, - thai, - shiftJis, - gB2312, - hangul, - big5, - pC437, - oem, - mac, - armenian, - syriac, - thaana, - devanagari, - bengali, - gurmukhi, - gujarati, - oriya, - tamil, - telugu, - kannada, - malayalam, - sinhala, - lao, - tibetan, - myanmar, - georgian, - jamo, - ethiopic, - cherokee, - aboriginal, - ogham, - runic, - khmer, - mongolian, - braille, - yi, - limbu, - taiLe, - newTaiLue, - sylotiNagri, - kharoshthi, - kayahli, - unicodeSymbol, - emoji, - glagolitic, - lisu, - vai, - nKo, - osmanya, - phagsPa, - gothic, - deseret, - tifinagh, - } - export enum UnderlineType { - undefined, - none, - single, - words, - double, - dotted, - dash, - dashDot, - dashDotDot, - wave, - thick, - thin, - doubleWave, - heavyWave, - longDash, - thickDash, - thickDashDot, - thickDashDotDot, - thickDotted, - thickLongDash, - } - export enum VerticalCharacterAlignment { - top, - baseline, - bottom, - } - export class TextConstants { - static autoColor: Windows.UI.Color; - static maxUnitCount: number; - static minUnitCount: number; - static undefinedColor: Windows.UI.Color; - static undefinedFloatValue: number; - static undefinedFontStretch: Windows.UI.Text.FontStretch; - static undefinedFontStyle: Windows.UI.Text.FontStyle; - static undefinedInt32Value: number; - } - export interface ITextConstantsStatics { - autoColor: Windows.UI.Color; - maxUnitCount: number; - minUnitCount: number; - undefinedColor: Windows.UI.Color; - undefinedFloatValue: number; - undefinedFontStretch: Windows.UI.Text.FontStretch; - undefinedFontStyle: Windows.UI.Text.FontStyle; - undefinedInt32Value: number; - } - export interface ITextDocument { - caretType: Windows.UI.Text.CaretType; - defaultTabStop: number; - selection: Windows.UI.Text.ITextSelection; - undoLimit: number; - canCopy(): boolean; - canPaste(): boolean; - canRedo(): boolean; - canUndo(): boolean; - applyDisplayUpdates(): number; - batchDisplayUpdates(): number; - beginUndoGroup(): void; - endUndoGroup(): void; - getDefaultCharacterFormat(): Windows.UI.Text.ITextCharacterFormat; - getDefaultParagraphFormat(): Windows.UI.Text.ITextParagraphFormat; - getRange(startPosition: number, endPosition: number): Windows.UI.Text.ITextRange; - getRangeFromPoint(point: Windows.Foundation.Point, options: Windows.UI.Text.PointOptions): Windows.UI.Text.ITextRange; - getText(options: Windows.UI.Text.TextGetOptions): string; - loadFromStream(options: Windows.UI.Text.TextSetOptions, value: Windows.Storage.Streams.IRandomAccessStream): void; - redo(): void; - saveToStream(options: Windows.UI.Text.TextGetOptions, value: Windows.Storage.Streams.IRandomAccessStream): void; - setDefaultCharacterFormat(value: Windows.UI.Text.ITextCharacterFormat): void; - setDefaultParagraphFormat(value: Windows.UI.Text.ITextParagraphFormat): void; - setText(options: Windows.UI.Text.TextSetOptions, value: string): void; - undo(): void; - } - export interface ITextRange { - character: string; - characterFormat: Windows.UI.Text.ITextCharacterFormat; - endPosition: number; - formattedText: Windows.UI.Text.ITextRange; - gravity: Windows.UI.Text.RangeGravity; - length: number; - link: string; - paragraphFormat: Windows.UI.Text.ITextParagraphFormat; - startPosition: number; - storyLength: number; - text: string; - canPaste(format: number): boolean; - changeCase(value: Windows.UI.Text.LetterCase): void; - collapse(value: boolean): void; - copy(): void; - cut(): void; - delete_(unit: Windows.UI.Text.TextRangeUnit, count: number): number; - endOf(unit: Windows.UI.Text.TextRangeUnit, extend: boolean): number; - expand(unit: Windows.UI.Text.TextRangeUnit): number; - findText(value: string, scanLength: number, options: Windows.UI.Text.FindOptions): number; - getCharacterUtf32(offset: number): number; - getClone(): Windows.UI.Text.ITextRange; - getIndex(unit: Windows.UI.Text.TextRangeUnit): number; - getPoint(horizontalAlign: Windows.UI.Text.HorizontalCharacterAlignment, verticalAlign: Windows.UI.Text.VerticalCharacterAlignment, options: Windows.UI.Text.PointOptions): Windows.Foundation.Point; - getRect(options: Windows.UI.Text.PointOptions): { rect: Windows.Foundation.Rect; hit: number; }; - getText(options: Windows.UI.Text.TextGetOptions): string; - getTextViaStream(options: Windows.UI.Text.TextGetOptions, value: Windows.Storage.Streams.IRandomAccessStream): void; - inRange(range: Windows.UI.Text.ITextRange): boolean; - insertImage(width: number, height: number, ascent: number, verticalAlign: Windows.UI.Text.VerticalCharacterAlignment, alternateText: string, value: Windows.Storage.Streams.IRandomAccessStream): void; - inStory(range: Windows.UI.Text.ITextRange): boolean; - isEqual(range: Windows.UI.Text.ITextRange): boolean; - move(unit: Windows.UI.Text.TextRangeUnit, count: number): number; - moveEnd(unit: Windows.UI.Text.TextRangeUnit, count: number): number; - moveStart(unit: Windows.UI.Text.TextRangeUnit, count: number): number; - paste(format: number): void; - scrollIntoView(value: Windows.UI.Text.PointOptions): void; - matchSelection(): void; - setIndex(unit: Windows.UI.Text.TextRangeUnit, index: number, extend: boolean): void; - setPoint(point: Windows.Foundation.Point, options: Windows.UI.Text.PointOptions, extend: boolean): void; - setRange(startPosition: number, endPosition: number): void; - setText(options: Windows.UI.Text.TextSetOptions, value: string): void; - setTextViaStream(options: Windows.UI.Text.TextSetOptions, value: Windows.Storage.Streams.IRandomAccessStream): void; - startOf(unit: Windows.UI.Text.TextRangeUnit, extend: boolean): number; - } - export interface ITextSelection extends Windows.UI.Text.ITextRange { - options: Windows.UI.Text.SelectionOptions; - type: Windows.UI.Text.SelectionType; - endKey(unit: Windows.UI.Text.TextRangeUnit, extend: boolean): number; - homeKey(unit: Windows.UI.Text.TextRangeUnit, extend: boolean): number; - moveDown(unit: Windows.UI.Text.TextRangeUnit, count: number, extend: boolean): number; - moveLeft(unit: Windows.UI.Text.TextRangeUnit, count: number, extend: boolean): number; - moveRight(unit: Windows.UI.Text.TextRangeUnit, count: number, extend: boolean): number; - moveUp(unit: Windows.UI.Text.TextRangeUnit, count: number, extend: boolean): number; - typeText(value: string): void; - } - export interface ITextCharacterFormat { - allCaps: Windows.UI.Text.FormatEffect; - backgroundColor: Windows.UI.Color; - bold: Windows.UI.Text.FormatEffect; - fontStretch: Windows.UI.Text.FontStretch; - fontStyle: Windows.UI.Text.FontStyle; - foregroundColor: Windows.UI.Color; - hidden: Windows.UI.Text.FormatEffect; - italic: Windows.UI.Text.FormatEffect; - kerning: number; - languageTag: string; - linkType: Windows.UI.Text.LinkType; - name: string; - outline: Windows.UI.Text.FormatEffect; - position: number; - protectedText: Windows.UI.Text.FormatEffect; - size: number; - smallCaps: Windows.UI.Text.FormatEffect; - spacing: number; - strikethrough: Windows.UI.Text.FormatEffect; - subscript: Windows.UI.Text.FormatEffect; - superscript: Windows.UI.Text.FormatEffect; - textScript: Windows.UI.Text.TextScript; - underline: Windows.UI.Text.UnderlineType; - weight: number; - setClone(value: Windows.UI.Text.ITextCharacterFormat): void; - getClone(): Windows.UI.Text.ITextCharacterFormat; - isEqual(format: Windows.UI.Text.ITextCharacterFormat): boolean; - } - export interface ITextParagraphFormat { - alignment: Windows.UI.Text.ParagraphAlignment; - firstLineIndent: number; - keepTogether: Windows.UI.Text.FormatEffect; - keepWithNext: Windows.UI.Text.FormatEffect; - leftIndent: number; - lineSpacing: number; - lineSpacingRule: Windows.UI.Text.LineSpacingRule; - listAlignment: Windows.UI.Text.MarkerAlignment; - listLevelIndex: number; - listStart: number; - listStyle: Windows.UI.Text.MarkerStyle; - listTab: number; - listType: Windows.UI.Text.MarkerType; - noLineNumber: Windows.UI.Text.FormatEffect; - pageBreakBefore: Windows.UI.Text.FormatEffect; - rightIndent: number; - rightToLeft: Windows.UI.Text.FormatEffect; - spaceAfter: number; - spaceBefore: number; - style: Windows.UI.Text.ParagraphStyle; - tabCount: number; - widowControl: Windows.UI.Text.FormatEffect; - addTab(position: number, align: Windows.UI.Text.TabAlignment, leader: Windows.UI.Text.TabLeader): void; - clearAllTabs(): void; - deleteTab(position: number): void; - getClone(): Windows.UI.Text.ITextParagraphFormat; - getTab(index: number): { position: number; align: Windows.UI.Text.TabAlignment; leader: Windows.UI.Text.TabLeader; }; - isEqual(format: Windows.UI.Text.ITextParagraphFormat): boolean; - setClone(format: Windows.UI.Text.ITextParagraphFormat): void; - setIndents(start: number, left: number, right: number): void; - setLineSpacing(rule: Windows.UI.Text.LineSpacingRule, spacing: number): void; - } - export enum FontStyle { - normal, - oblique, - italic, - } - export enum FontStretch { - undefined, - ultraCondensed, - extraCondensed, - condensed, - semiCondensed, - normal, - semiExpanded, - expanded, - extraExpanded, - ultraExpanded, - } - export interface FontWeight { - weight: number; - } - export interface IFontWeights { - } - export interface IFontWeightsStatics { - black: Windows.UI.Text.FontWeight; - bold: Windows.UI.Text.FontWeight; - extraBlack: Windows.UI.Text.FontWeight; - extraBold: Windows.UI.Text.FontWeight; - extraLight: Windows.UI.Text.FontWeight; - light: Windows.UI.Text.FontWeight; - medium: Windows.UI.Text.FontWeight; - normal: Windows.UI.Text.FontWeight; - semiBold: Windows.UI.Text.FontWeight; - semiLight: Windows.UI.Text.FontWeight; - thin: Windows.UI.Text.FontWeight; - } - export class FontWeights implements Windows.UI.Text.IFontWeights { - static black: Windows.UI.Text.FontWeight; - static bold: Windows.UI.Text.FontWeight; - static extraBlack: Windows.UI.Text.FontWeight; - static extraBold: Windows.UI.Text.FontWeight; - static extraLight: Windows.UI.Text.FontWeight; - static light: Windows.UI.Text.FontWeight; - static medium: Windows.UI.Text.FontWeight; - static normal: Windows.UI.Text.FontWeight; - static semiBold: Windows.UI.Text.FontWeight; - static semiLight: Windows.UI.Text.FontWeight; - static thin: Windows.UI.Text.FontWeight; - } - } - } -} -declare module Windows { - export module UI { - export module Core { - export module AnimationMetrics { - export enum PropertyAnimationType { - scale, - translation, - opacity, - } - export interface IPropertyAnimation { - control1: Windows.Foundation.Point; - control2: Windows.Foundation.Point; - delay: number; - duration: number; - type: Windows.UI.Core.AnimationMetrics.PropertyAnimationType; - } - export interface IScaleAnimation extends Windows.UI.Core.AnimationMetrics.IPropertyAnimation { - finalScaleX: number; - finalScaleY: number; - initialScaleX: number; - initialScaleY: number; - normalizedOrigin: Windows.Foundation.Point; - } - export interface IOpacityAnimation extends Windows.UI.Core.AnimationMetrics.IPropertyAnimation { - finalOpacity: number; - initialOpacity: number; - } - export enum AnimationEffect { - expand, - collapse, - reposition, - fadeIn, - fadeOut, - addToList, - deleteFromList, - addToGrid, - deleteFromGrid, - addToSearchGrid, - deleteFromSearchGrid, - addToSearchList, - deleteFromSearchList, - showEdgeUI, - showPanel, - hideEdgeUI, - hidePanel, - showPopup, - hidePopup, - pointerDown, - pointerUp, - dragSourceStart, - dragSourceEnd, - transitionContent, - reveal, - hide, - dragBetweenEnter, - dragBetweenLeave, - swipeSelect, - swipeDeselect, - swipeReveal, - enterPage, - transitionPage, - crossFade, - peek, - updateBadge, - } - export enum AnimationEffectTarget { - primary, - added, - affected, - background, - content, - deleted, - deselected, - dragSource, - hidden, - incoming, - outgoing, - outline, - remaining, - revealed, - rowIn, - rowOut, - selected, - selection, - shown, - tapped, - } - export interface IAnimationDescription { - animations: Windows.Foundation.Collections.IVectorView; - delayLimit: number; - staggerDelay: number; - staggerDelayFactor: number; - zOrder: number; - } - export interface IAnimationDescriptionFactory { - createInstance(effect: Windows.UI.Core.AnimationMetrics.AnimationEffect, target: Windows.UI.Core.AnimationMetrics.AnimationEffectTarget): Windows.UI.Core.AnimationMetrics.AnimationDescription; - } - export class AnimationDescription implements Windows.UI.Core.AnimationMetrics.IAnimationDescription { - constructor(effect: Windows.UI.Core.AnimationMetrics.AnimationEffect, target: Windows.UI.Core.AnimationMetrics.AnimationEffectTarget); - animations: Windows.Foundation.Collections.IVectorView; - delayLimit: number; - staggerDelay: number; - staggerDelayFactor: number; - zOrder: number; - } - export class PropertyAnimation implements Windows.UI.Core.AnimationMetrics.IPropertyAnimation { - control1: Windows.Foundation.Point; - control2: Windows.Foundation.Point; - delay: number; - duration: number; - type: Windows.UI.Core.AnimationMetrics.PropertyAnimationType; - } - export class ScaleAnimation implements Windows.UI.Core.AnimationMetrics.IScaleAnimation, Windows.UI.Core.AnimationMetrics.IPropertyAnimation { - finalScaleX: number; - finalScaleY: number; - initialScaleX: number; - initialScaleY: number; - normalizedOrigin: Windows.Foundation.Point; - control1: Windows.Foundation.Point; - control2: Windows.Foundation.Point; - delay: number; - duration: number; - type: Windows.UI.Core.AnimationMetrics.PropertyAnimationType; - } - export class TranslationAnimation implements Windows.UI.Core.AnimationMetrics.IPropertyAnimation { - control1: Windows.Foundation.Point; - control2: Windows.Foundation.Point; - delay: number; - duration: number; - type: Windows.UI.Core.AnimationMetrics.PropertyAnimationType; - } - export class OpacityAnimation implements Windows.UI.Core.AnimationMetrics.IOpacityAnimation, Windows.UI.Core.AnimationMetrics.IPropertyAnimation { - finalOpacity: number; - initialOpacity: number; - control1: Windows.Foundation.Point; - control2: Windows.Foundation.Point; - delay: number; - duration: number; - type: Windows.UI.Core.AnimationMetrics.PropertyAnimationType; - } - } - } - } -} -declare module Windows { - export module UI { - export module Core { - export enum CoreWindowActivationState { - codeActivated, - deactivated, - pointerActivated, - } - export enum CoreCursorType { - arrow, - cross, - custom, - hand, - help, - iBeam, - sizeAll, - sizeNortheastSouthwest, - sizeNorthSouth, - sizeNorthwestSoutheast, - sizeWestEast, - universalNo, - upArrow, - wait, - } - export enum CoreDispatcherPriority { - low, - normal, - high, - } - export enum CoreProcessEventsOption { - processOneAndAllPending, - processOneIfPresent, - processUntilQuit, - processAllIfPresent, - } - export enum CoreWindowFlowDirection { - leftToRight, - rightToLeft, - } - export enum CoreVirtualKeyStates { - none, - down, - locked, - } - export enum CoreAcceleratorKeyEventType { - character, - deadCharacter, - keyDown, - keyUp, - systemCharacter, - systemDeadCharacter, - systemKeyDown, - systemKeyUp, - unicodeCharacter, - } - export enum CoreProximityEvaluationScore { - closest, - farthest, - } - export interface CorePhysicalKeyStatus { - repeatCount: number; - scanCode: number; - isExtendedKey: boolean; - isMenuKeyDown: boolean; - wasKeyDown: boolean; - isKeyReleased: boolean; - } - export interface CoreProximityEvaluation { - score: number; - adjustedPoint: Windows.Foundation.Point; - } - export interface ICoreWindowEventArgs { - handled: boolean; - } - export interface IAutomationProviderRequestedEventArgs extends Windows.UI.Core.ICoreWindowEventArgs { - automationProvider: any; - } - export interface ICharacterReceivedEventArgs extends Windows.UI.Core.ICoreWindowEventArgs { - keyCode: number; - keyStatus: Windows.UI.Core.CorePhysicalKeyStatus; - } - export interface IInputEnabledEventArgs extends Windows.UI.Core.ICoreWindowEventArgs { - inputEnabled: boolean; - } - export interface IKeyEventArgs extends Windows.UI.Core.ICoreWindowEventArgs { - keyStatus: Windows.UI.Core.CorePhysicalKeyStatus; - virtualKey: Windows.System.VirtualKey; - } - export interface IPointerEventArgs extends Windows.UI.Core.ICoreWindowEventArgs { - currentPoint: Windows.UI.Input.PointerPoint; - keyModifiers: Windows.System.VirtualKeyModifiers; - getIntermediatePoints(): Windows.Foundation.Collections.IVector; - } - export interface ITouchHitTestingEventArgs extends Windows.UI.Core.ICoreWindowEventArgs { - boundingBox: Windows.Foundation.Rect; - point: Windows.Foundation.Point; - proximityEvaluation: Windows.UI.Core.CoreProximityEvaluation; - evaluateProximity(controlBoundingBox: Windows.Foundation.Rect): Windows.UI.Core.CoreProximityEvaluation; - evaluateProximity(controlVertices: Windows.Foundation.Point[]): Windows.UI.Core.CoreProximityEvaluation; - } - export interface IWindowActivatedEventArgs extends Windows.UI.Core.ICoreWindowEventArgs { - windowActivationState: Windows.UI.Core.CoreWindowActivationState; - } - export interface IWindowSizeChangedEventArgs extends Windows.UI.Core.ICoreWindowEventArgs { - size: Windows.Foundation.Size; - } - export interface IVisibilityChangedEventArgs extends Windows.UI.Core.ICoreWindowEventArgs { - visible: boolean; - } - export interface ICoreWindow { - automationHostProvider: any; - bounds: Windows.Foundation.Rect; - customProperties: Windows.Foundation.Collections.IPropertySet; - dispatcher: Windows.UI.Core.CoreDispatcher; - flowDirection: Windows.UI.Core.CoreWindowFlowDirection; - isInputEnabled: boolean; - pointerCursor: Windows.UI.Core.CoreCursor; - pointerPosition: Windows.Foundation.Point; - visible: boolean; - activate(): void; - close(): void; - getAsyncKeyState(virtualKey: Windows.System.VirtualKey): Windows.UI.Core.CoreVirtualKeyStates; - getKeyState(virtualKey: Windows.System.VirtualKey): Windows.UI.Core.CoreVirtualKeyStates; - releasePointerCapture(): void; - setPointerCapture(): void; - onactivated: any/* TODO */; - onautomationproviderrequested: any/* TODO */; - oncharacterreceived: any/* TODO */; - onclosed: any/* TODO */; - oninputenabled: any/* TODO */; - onkeydown: any/* TODO */; - onkeyup: any/* TODO */; - onpointercapturelost: any/* TODO */; - onpointerentered: any/* TODO */; - onpointerexited: any/* TODO */; - onpointermoved: any/* TODO */; - onpointerpressed: any/* TODO */; - onpointerreleased: any/* TODO */; - ontouchhittesting: any/* TODO */; - onpointerwheelchanged: any/* TODO */; - onsizechanged: any/* TODO */; - onvisibilitychanged: any/* TODO */; - } - export class CoreDispatcher implements Windows.UI.Core.ICoreDispatcher, Windows.UI.Core.ICoreAcceleratorKeys { - hasThreadAccess: boolean; - processEvents(options: Windows.UI.Core.CoreProcessEventsOption): void; - runAsync(priority: Windows.UI.Core.CoreDispatcherPriority, agileCallback: Windows.UI.Core.DispatchedHandler): Windows.Foundation.IAsyncAction; - runIdleAsync(agileCallback: Windows.UI.Core.IdleDispatchedHandler): Windows.Foundation.IAsyncAction; - onacceleratorkeyactivated: any/* TODO */; - } - export class CoreCursor implements Windows.UI.Core.ICoreCursor { - constructor(type: Windows.UI.Core.CoreCursorType, id: number); - id: number; - type: Windows.UI.Core.CoreCursorType; - } - export class CoreWindow implements Windows.UI.Core.ICoreWindow { - automationHostProvider: any; - bounds: Windows.Foundation.Rect; - customProperties: Windows.Foundation.Collections.IPropertySet; - dispatcher: Windows.UI.Core.CoreDispatcher; - flowDirection: Windows.UI.Core.CoreWindowFlowDirection; - isInputEnabled: boolean; - pointerCursor: Windows.UI.Core.CoreCursor; - pointerPosition: Windows.Foundation.Point; - visible: boolean; - activate(): void; - close(): void; - getAsyncKeyState(virtualKey: Windows.System.VirtualKey): Windows.UI.Core.CoreVirtualKeyStates; - getKeyState(virtualKey: Windows.System.VirtualKey): Windows.UI.Core.CoreVirtualKeyStates; - releasePointerCapture(): void; - setPointerCapture(): void; - onactivated: any/* TODO */; - onautomationproviderrequested: any/* TODO */; - oncharacterreceived: any/* TODO */; - onclosed: any/* TODO */; - oninputenabled: any/* TODO */; - onkeydown: any/* TODO */; - onkeyup: any/* TODO */; - onpointercapturelost: any/* TODO */; - onpointerentered: any/* TODO */; - onpointerexited: any/* TODO */; - onpointermoved: any/* TODO */; - onpointerpressed: any/* TODO */; - onpointerreleased: any/* TODO */; - ontouchhittesting: any/* TODO */; - onpointerwheelchanged: any/* TODO */; - onsizechanged: any/* TODO */; - onvisibilitychanged: any/* TODO */; - static getForCurrentThread(): Windows.UI.Core.CoreWindow; - } - export class WindowActivatedEventArgs implements Windows.UI.Core.IWindowActivatedEventArgs, Windows.UI.Core.ICoreWindowEventArgs { - windowActivationState: Windows.UI.Core.CoreWindowActivationState; - handled: boolean; - } - export class AutomationProviderRequestedEventArgs implements Windows.UI.Core.IAutomationProviderRequestedEventArgs, Windows.UI.Core.ICoreWindowEventArgs { - automationProvider: any; - handled: boolean; - } - export class CharacterReceivedEventArgs implements Windows.UI.Core.ICharacterReceivedEventArgs, Windows.UI.Core.ICoreWindowEventArgs { - keyCode: number; - keyStatus: Windows.UI.Core.CorePhysicalKeyStatus; - handled: boolean; - } - export class CoreWindowEventArgs implements Windows.UI.Core.ICoreWindowEventArgs { - handled: boolean; - } - export class InputEnabledEventArgs implements Windows.UI.Core.IInputEnabledEventArgs, Windows.UI.Core.ICoreWindowEventArgs { - inputEnabled: boolean; - handled: boolean; - } - export class KeyEventArgs implements Windows.UI.Core.IKeyEventArgs, Windows.UI.Core.ICoreWindowEventArgs { - keyStatus: Windows.UI.Core.CorePhysicalKeyStatus; - virtualKey: Windows.System.VirtualKey; - handled: boolean; - } - export class PointerEventArgs implements Windows.UI.Core.IPointerEventArgs, Windows.UI.Core.ICoreWindowEventArgs { - currentPoint: Windows.UI.Input.PointerPoint; - keyModifiers: Windows.System.VirtualKeyModifiers; - handled: boolean; - getIntermediatePoints(): Windows.Foundation.Collections.IVector; - } - export class TouchHitTestingEventArgs implements Windows.UI.Core.ITouchHitTestingEventArgs, Windows.UI.Core.ICoreWindowEventArgs { - boundingBox: Windows.Foundation.Rect; - point: Windows.Foundation.Point; - proximityEvaluation: Windows.UI.Core.CoreProximityEvaluation; - handled: boolean; - evaluateProximity(controlBoundingBox: Windows.Foundation.Rect): Windows.UI.Core.CoreProximityEvaluation; - evaluateProximity(controlVertices: Windows.Foundation.Point[]): Windows.UI.Core.CoreProximityEvaluation; - } - export class WindowSizeChangedEventArgs implements Windows.UI.Core.IWindowSizeChangedEventArgs, Windows.UI.Core.ICoreWindowEventArgs { - size: Windows.Foundation.Size; - handled: boolean; - } - export class VisibilityChangedEventArgs implements Windows.UI.Core.IVisibilityChangedEventArgs, Windows.UI.Core.ICoreWindowEventArgs { - visible: boolean; - handled: boolean; - } - export interface ICoreWindowStatic { - getForCurrentThread(): Windows.UI.Core.CoreWindow; - } - export interface DispatchedHandler { - (): void; - } - export interface IdleDispatchedHandler { - (e: Windows.UI.Core.IdleDispatchedHandlerArgs): void; - } - export class IdleDispatchedHandlerArgs implements Windows.UI.Core.IIdleDispatchedHandlerArgs { - isDispatcherIdle: boolean; - } - export interface IAcceleratorKeyEventArgs extends Windows.UI.Core.ICoreWindowEventArgs { - eventType: Windows.UI.Core.CoreAcceleratorKeyEventType; - keyStatus: Windows.UI.Core.CorePhysicalKeyStatus; - virtualKey: Windows.System.VirtualKey; - } - export interface ICoreAcceleratorKeys { - onacceleratorkeyactivated: any/* TODO */; - } - export class AcceleratorKeyEventArgs implements Windows.UI.Core.IAcceleratorKeyEventArgs, Windows.UI.Core.ICoreWindowEventArgs { - eventType: Windows.UI.Core.CoreAcceleratorKeyEventType; - keyStatus: Windows.UI.Core.CorePhysicalKeyStatus; - virtualKey: Windows.System.VirtualKey; - handled: boolean; - } - export interface ICoreDispatcher extends Windows.UI.Core.ICoreAcceleratorKeys { - hasThreadAccess: boolean; - processEvents(options: Windows.UI.Core.CoreProcessEventsOption): void; - runAsync(priority: Windows.UI.Core.CoreDispatcherPriority, agileCallback: Windows.UI.Core.DispatchedHandler): Windows.Foundation.IAsyncAction; - runIdleAsync(agileCallback: Windows.UI.Core.IdleDispatchedHandler): Windows.Foundation.IAsyncAction; - } - export interface IIdleDispatchedHandlerArgs { - isDispatcherIdle: boolean; - } - export class CoreAcceleratorKeys implements Windows.UI.Core.ICoreAcceleratorKeys { - onacceleratorkeyactivated: any/* TODO */; - } - export interface ICoreCursor { - id: number; - type: Windows.UI.Core.CoreCursorType; - } - export interface ICoreCursorFactory { - createCursor(type: Windows.UI.Core.CoreCursorType, id: number): Windows.UI.Core.CoreCursor; - } - export interface IInitializeWithCoreWindow { - initialize(window: Windows.UI.Core.CoreWindow): void; - } - export interface ICoreWindowResizeManager { - notifyLayoutCompleted(): void; - } - export interface ICoreWindowResizeManagerStatics { - getForCurrentView(): Windows.UI.Core.CoreWindowResizeManager; - } - export class CoreWindowResizeManager implements Windows.UI.Core.ICoreWindowResizeManager { - notifyLayoutCompleted(): void; - static getForCurrentView(): Windows.UI.Core.CoreWindowResizeManager; - } - export interface ICoreWindowPopupShowingEventArgs { - setDesiredSize(value: Windows.Foundation.Size): void; - } - export class CoreWindowPopupShowingEventArgs implements Windows.UI.Core.ICoreWindowPopupShowingEventArgs { - setDesiredSize(value: Windows.Foundation.Size): void; - } - export interface ICoreWindowDialog { - backButtonCommand: Windows.UI.Popups.UICommandInvokedHandler; - cancelCommandIndex: number; - commands: Windows.Foundation.Collections.IVector; - defaultCommandIndex: number; - isInteractionDelayed: number; - maxSize: Windows.Foundation.Size; - minSize: Windows.Foundation.Size; - title: string; - onshowing: any/* TODO */; - showAsync(): Windows.Foundation.IAsyncOperation; - } - export interface ICoreWindowDialogFactory { - createWithTitle(title: string): Windows.UI.Core.CoreWindowDialog; - } - export class CoreWindowDialog implements Windows.UI.Core.ICoreWindowDialog { - constructor(title: string); - constructor(); - backButtonCommand: Windows.UI.Popups.UICommandInvokedHandler; - cancelCommandIndex: number; - commands: Windows.Foundation.Collections.IVector; - defaultCommandIndex: number; - isInteractionDelayed: number; - maxSize: Windows.Foundation.Size; - minSize: Windows.Foundation.Size; - title: string; - onshowing: any/* TODO */; - showAsync(): Windows.Foundation.IAsyncOperation; - } - export interface ICoreWindowFlyout { - backButtonCommand: Windows.UI.Popups.UICommandInvokedHandler; - commands: Windows.Foundation.Collections.IVector; - defaultCommandIndex: number; - isInteractionDelayed: number; - maxSize: Windows.Foundation.Size; - minSize: Windows.Foundation.Size; - title: string; - onshowing: any/* TODO */; - showAsync(): Windows.Foundation.IAsyncOperation; - } - export interface ICoreWindowFlyoutFactory { - create(position: Windows.Foundation.Point): Windows.UI.Core.CoreWindowFlyout; - createWithTitle(position: Windows.Foundation.Point, title: string): Windows.UI.Core.CoreWindowFlyout; - } - export class CoreWindowFlyout implements Windows.UI.Core.ICoreWindowFlyout { - constructor(position: Windows.Foundation.Point); - constructor(position: Windows.Foundation.Point, title: string); - backButtonCommand: Windows.UI.Popups.UICommandInvokedHandler; - commands: Windows.Foundation.Collections.IVector; - defaultCommandIndex: number; - isInteractionDelayed: number; - maxSize: Windows.Foundation.Size; - minSize: Windows.Foundation.Size; - title: string; - onshowing: any/* TODO */; - showAsync(): Windows.Foundation.IAsyncOperation; - } - } - } -} -declare module Windows { - export module UI { - export module Input { - export module Inking { - export enum InkManipulationMode { - inking, - erasing, - selecting, - } - export enum InkRecognitionTarget { - all, - selected, - recent, - } - export enum PenTipShape { - circle, - rectangle, - } - export interface IInkDrawingAttributes { - color: Windows.UI.Color; - fitToCurve: boolean; - ignorePressure: boolean; - penTip: Windows.UI.Input.Inking.PenTipShape; - size: Windows.Foundation.Size; - } - export class InkDrawingAttributes implements Windows.UI.Input.Inking.IInkDrawingAttributes { - color: Windows.UI.Color; - fitToCurve: boolean; - ignorePressure: boolean; - penTip: Windows.UI.Input.Inking.PenTipShape; - size: Windows.Foundation.Size; - } - export interface IInkStrokeRenderingSegment { - bezierControlPoint1: Windows.Foundation.Point; - bezierControlPoint2: Windows.Foundation.Point; - position: Windows.Foundation.Point; - pressure: number; - tiltX: number; - tiltY: number; - twist: number; - } - export class InkStrokeRenderingSegment implements Windows.UI.Input.Inking.IInkStrokeRenderingSegment { - bezierControlPoint1: Windows.Foundation.Point; - bezierControlPoint2: Windows.Foundation.Point; - position: Windows.Foundation.Point; - pressure: number; - tiltX: number; - tiltY: number; - twist: number; - } - export interface IInkStroke { - boundingRect: Windows.Foundation.Rect; - drawingAttributes: Windows.UI.Input.Inking.InkDrawingAttributes; - recognized: boolean; - selected: boolean; - getRenderingSegments(): Windows.Foundation.Collections.IVectorView; - clone(): Windows.UI.Input.Inking.InkStroke; - } - export class InkStroke implements Windows.UI.Input.Inking.IInkStroke { - boundingRect: Windows.Foundation.Rect; - drawingAttributes: Windows.UI.Input.Inking.InkDrawingAttributes; - recognized: boolean; - selected: boolean; - getRenderingSegments(): Windows.Foundation.Collections.IVectorView; - clone(): Windows.UI.Input.Inking.InkStroke; - } - export interface IInkStrokeBuilder { - beginStroke(pointerPoint: Windows.UI.Input.PointerPoint): void; - appendToStroke(pointerPoint: Windows.UI.Input.PointerPoint): Windows.UI.Input.PointerPoint; - endStroke(pointerPoint: Windows.UI.Input.PointerPoint): Windows.UI.Input.Inking.InkStroke; - createStroke(points: Windows.Foundation.Collections.IIterable): Windows.UI.Input.Inking.InkStroke; - setDefaultDrawingAttributes(drawingAttributes: Windows.UI.Input.Inking.InkDrawingAttributes): void; - } - export class InkStrokeBuilder implements Windows.UI.Input.Inking.IInkStrokeBuilder { - beginStroke(pointerPoint: Windows.UI.Input.PointerPoint): void; - appendToStroke(pointerPoint: Windows.UI.Input.PointerPoint): Windows.UI.Input.PointerPoint; - endStroke(pointerPoint: Windows.UI.Input.PointerPoint): Windows.UI.Input.Inking.InkStroke; - createStroke(points: Windows.Foundation.Collections.IIterable): Windows.UI.Input.Inking.InkStroke; - setDefaultDrawingAttributes(drawingAttributes: Windows.UI.Input.Inking.InkDrawingAttributes): void; - } - export interface IInkRecognitionResult { - boundingRect: Windows.Foundation.Rect; - getTextCandidates(): Windows.Foundation.Collections.IVectorView; - getStrokes(): Windows.Foundation.Collections.IVectorView; - } - export class InkRecognitionResult implements Windows.UI.Input.Inking.IInkRecognitionResult { - boundingRect: Windows.Foundation.Rect; - getTextCandidates(): Windows.Foundation.Collections.IVectorView; - getStrokes(): Windows.Foundation.Collections.IVectorView; - } - export interface IInkStrokeContainer { - boundingRect: Windows.Foundation.Rect; - addStroke(stroke: Windows.UI.Input.Inking.InkStroke): void; - deleteSelected(): Windows.Foundation.Rect; - moveSelected(translation: Windows.Foundation.Point): Windows.Foundation.Rect; - selectWithPolyLine(polyline: Windows.Foundation.Collections.IIterable): Windows.Foundation.Rect; - selectWithLine(from: Windows.Foundation.Point, to: Windows.Foundation.Point): Windows.Foundation.Rect; - copySelectedToClipboard(): void; - pasteFromClipboard(position: Windows.Foundation.Point): Windows.Foundation.Rect; - canPasteFromClipboard(): boolean; - loadAsync(inputStream: Windows.Storage.Streams.IInputStream): Windows.Foundation.IAsyncActionWithProgress; - saveAsync(outputStream: Windows.Storage.Streams.IOutputStream): Windows.Foundation.IAsyncOperationWithProgress; - updateRecognitionResults(recognitionResults: Windows.Foundation.Collections.IVectorView): void; - getStrokes(): Windows.Foundation.Collections.IVectorView; - getRecognitionResults(): Windows.Foundation.Collections.IVectorView; - } - export class InkStrokeContainer implements Windows.UI.Input.Inking.IInkStrokeContainer { - boundingRect: Windows.Foundation.Rect; - addStroke(stroke: Windows.UI.Input.Inking.InkStroke): void; - deleteSelected(): Windows.Foundation.Rect; - moveSelected(translation: Windows.Foundation.Point): Windows.Foundation.Rect; - selectWithPolyLine(polyline: Windows.Foundation.Collections.IIterable): Windows.Foundation.Rect; - selectWithLine(from: Windows.Foundation.Point, to: Windows.Foundation.Point): Windows.Foundation.Rect; - copySelectedToClipboard(): void; - pasteFromClipboard(position: Windows.Foundation.Point): Windows.Foundation.Rect; - canPasteFromClipboard(): boolean; - loadAsync(inputStream: Windows.Storage.Streams.IInputStream): Windows.Foundation.IAsyncActionWithProgress; - saveAsync(outputStream: Windows.Storage.Streams.IOutputStream): Windows.Foundation.IAsyncOperationWithProgress; - updateRecognitionResults(recognitionResults: Windows.Foundation.Collections.IVectorView): void; - getStrokes(): Windows.Foundation.Collections.IVectorView; - getRecognitionResults(): Windows.Foundation.Collections.IVectorView; - } - export interface IInkRecognizer { - name: string; - } - export class InkRecognizer implements Windows.UI.Input.Inking.IInkRecognizer { - name: string; - } - export interface IInkRecognizerContainer { - setDefaultRecognizer(recognizer: Windows.UI.Input.Inking.InkRecognizer): void; - recognizeAsync(strokeCollection: Windows.UI.Input.Inking.InkStrokeContainer, recognitionTarget: Windows.UI.Input.Inking.InkRecognitionTarget): Windows.Foundation.IAsyncOperation>; - getRecognizers(): Windows.Foundation.Collections.IVectorView; - } - export class InkRecognizerContainer implements Windows.UI.Input.Inking.IInkRecognizerContainer { - setDefaultRecognizer(recognizer: Windows.UI.Input.Inking.InkRecognizer): void; - recognizeAsync(strokeCollection: Windows.UI.Input.Inking.InkStrokeContainer, recognitionTarget: Windows.UI.Input.Inking.InkRecognitionTarget): Windows.Foundation.IAsyncOperation>; - getRecognizers(): Windows.Foundation.Collections.IVectorView; - } - export interface IInkManager extends Windows.UI.Input.Inking.IInkStrokeContainer, Windows.UI.Input.Inking.IInkRecognizerContainer { - mode: Windows.UI.Input.Inking.InkManipulationMode; - processPointerDown(pointerPoint: Windows.UI.Input.PointerPoint): void; - processPointerUpdate(pointerPoint: Windows.UI.Input.PointerPoint): any; - processPointerUp(pointerPoint: Windows.UI.Input.PointerPoint): Windows.Foundation.Rect; - setDefaultDrawingAttributes(drawingAttributes: Windows.UI.Input.Inking.InkDrawingAttributes): void; - recognizeAsync(strokeCollection: Windows.UI.Input.Inking.InkStrokeContainer, recognitionTarget: Windows.UI.Input.Inking.InkRecognitionTarget): Windows.Foundation.IAsyncOperation>; - recognizeAsync(recognitionTarget: Windows.UI.Input.Inking.InkRecognitionTarget): Windows.Foundation.IAsyncOperation>; - } - export class InkManager implements Windows.UI.Input.Inking.IInkManager, Windows.UI.Input.Inking.IInkStrokeContainer, Windows.UI.Input.Inking.IInkRecognizerContainer { - mode: Windows.UI.Input.Inking.InkManipulationMode; - boundingRect: Windows.Foundation.Rect; - processPointerDown(pointerPoint: Windows.UI.Input.PointerPoint): void; - processPointerUpdate(pointerPoint: Windows.UI.Input.PointerPoint): any; - processPointerUp(pointerPoint: Windows.UI.Input.PointerPoint): Windows.Foundation.Rect; - setDefaultDrawingAttributes(drawingAttributes: Windows.UI.Input.Inking.InkDrawingAttributes): void; - recognizeAsync(recognitionTarget: Windows.UI.Input.Inking.InkRecognitionTarget): Windows.Foundation.IAsyncOperation>; - addStroke(stroke: Windows.UI.Input.Inking.InkStroke): void; - deleteSelected(): Windows.Foundation.Rect; - moveSelected(translation: Windows.Foundation.Point): Windows.Foundation.Rect; - selectWithPolyLine(polyline: Windows.Foundation.Collections.IIterable): Windows.Foundation.Rect; - selectWithLine(from: Windows.Foundation.Point, to: Windows.Foundation.Point): Windows.Foundation.Rect; - copySelectedToClipboard(): void; - pasteFromClipboard(position: Windows.Foundation.Point): Windows.Foundation.Rect; - canPasteFromClipboard(): boolean; - loadAsync(inputStream: Windows.Storage.Streams.IInputStream): Windows.Foundation.IAsyncActionWithProgress; - saveAsync(outputStream: Windows.Storage.Streams.IOutputStream): Windows.Foundation.IAsyncOperationWithProgress; - updateRecognitionResults(recognitionResults: Windows.Foundation.Collections.IVectorView): void; - getStrokes(): Windows.Foundation.Collections.IVectorView; - getRecognitionResults(): Windows.Foundation.Collections.IVectorView; - setDefaultRecognizer(recognizer: Windows.UI.Input.Inking.InkRecognizer): void; - recognizeAsync(strokeCollection: Windows.UI.Input.Inking.InkStrokeContainer, recognitionTarget: Windows.UI.Input.Inking.InkRecognitionTarget): Windows.Foundation.IAsyncOperation>; - getRecognizers(): Windows.Foundation.Collections.IVectorView; - } - } - } - } -} -declare module Windows { - export module UI { - export module WebUI { - export interface IActivatedDeferral { - complete(): void; - } - export class ActivatedDeferral implements Windows.UI.WebUI.IActivatedDeferral { - complete(): void; - } - export interface IActivatedOperation { - getDeferral(): Windows.UI.WebUI.ActivatedDeferral; - } - export class ActivatedOperation implements Windows.UI.WebUI.IActivatedOperation { - getDeferral(): Windows.UI.WebUI.ActivatedDeferral; - } - export interface IActivatedEventArgsDeferral { - activatedOperation: Windows.UI.WebUI.ActivatedOperation; - } - export class WebUILaunchActivatedEventArgs implements Windows.ApplicationModel.Activation.ILaunchActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs, Windows.UI.WebUI.IActivatedEventArgsDeferral { - arguments: string; - tileId: string; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - activatedOperation: Windows.UI.WebUI.ActivatedOperation; - } - export class WebUISearchActivatedEventArgs implements Windows.ApplicationModel.Activation.ISearchActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs, Windows.UI.WebUI.IActivatedEventArgsDeferral { - language: string; - queryText: string; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - activatedOperation: Windows.UI.WebUI.ActivatedOperation; - } - export class WebUIShareTargetActivatedEventArgs implements Windows.ApplicationModel.Activation.IShareTargetActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs, Windows.UI.WebUI.IActivatedEventArgsDeferral { - shareOperation: Windows.ApplicationModel.DataTransfer.ShareTarget.ShareOperation; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - activatedOperation: Windows.UI.WebUI.ActivatedOperation; - } - export class WebUIFileActivatedEventArgs implements Windows.ApplicationModel.Activation.IFileActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs, Windows.UI.WebUI.IActivatedEventArgsDeferral { - files: Windows.Foundation.Collections.IVectorView; - verb: string; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - activatedOperation: Windows.UI.WebUI.ActivatedOperation; - } - export class WebUIProtocolActivatedEventArgs implements Windows.ApplicationModel.Activation.IProtocolActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs, Windows.UI.WebUI.IActivatedEventArgsDeferral { - uri: Windows.Foundation.Uri; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - activatedOperation: Windows.UI.WebUI.ActivatedOperation; - } - export class WebUIFileOpenPickerActivatedEventArgs implements Windows.ApplicationModel.Activation.IFileOpenPickerActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs, Windows.UI.WebUI.IActivatedEventArgsDeferral { - fileOpenPickerUI: Windows.Storage.Pickers.Provider.FileOpenPickerUI; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - activatedOperation: Windows.UI.WebUI.ActivatedOperation; - } - export class WebUIFileSavePickerActivatedEventArgs implements Windows.ApplicationModel.Activation.IFileSavePickerActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs, Windows.UI.WebUI.IActivatedEventArgsDeferral { - fileSavePickerUI: Windows.Storage.Pickers.Provider.FileSavePickerUI; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - activatedOperation: Windows.UI.WebUI.ActivatedOperation; - } - export class WebUICachedFileUpdaterActivatedEventArgs implements Windows.ApplicationModel.Activation.ICachedFileUpdaterActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs, Windows.UI.WebUI.IActivatedEventArgsDeferral { - cachedFileUpdaterUI: Windows.Storage.Provider.CachedFileUpdaterUI; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - activatedOperation: Windows.UI.WebUI.ActivatedOperation; - } - export class WebUIContactPickerActivatedEventArgs implements Windows.ApplicationModel.Activation.IContactPickerActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs, Windows.UI.WebUI.IActivatedEventArgsDeferral { - contactPickerUI: Windows.ApplicationModel.Contacts.Provider.ContactPickerUI; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - activatedOperation: Windows.UI.WebUI.ActivatedOperation; - } - export class WebUIDeviceActivatedEventArgs implements Windows.ApplicationModel.Activation.IDeviceActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs, Windows.UI.WebUI.IActivatedEventArgsDeferral { - deviceInformationId: string; - verb: string; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - activatedOperation: Windows.UI.WebUI.ActivatedOperation; - } - export class WebUIPrintTaskSettingsActivatedEventArgs implements Windows.ApplicationModel.Activation.IPrintTaskSettingsActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs, Windows.UI.WebUI.IActivatedEventArgsDeferral { - configuration: Windows.Devices.Printers.Extensions.PrintTaskConfiguration; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - activatedOperation: Windows.UI.WebUI.ActivatedOperation; - } - export class WebUICameraSettingsActivatedEventArgs implements Windows.ApplicationModel.Activation.ICameraSettingsActivatedEventArgs, Windows.ApplicationModel.Activation.IActivatedEventArgs, Windows.UI.WebUI.IActivatedEventArgsDeferral { - videoDeviceController: any; - videoDeviceExtension: any; - kind: Windows.ApplicationModel.Activation.ActivationKind; - previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; - splashScreen: Windows.ApplicationModel.Activation.SplashScreen; - activatedOperation: Windows.UI.WebUI.ActivatedOperation; - } - export interface ActivatedEventHandler { - (sender: any, eventArgs: Windows.ApplicationModel.Activation.IActivatedEventArgs): void; - } - export interface ResumingEventHandler { - (sender: any): void; - } - export interface SuspendingEventHandler { - (sender: any, e: Windows.ApplicationModel.ISuspendingEventArgs): void; - } - export interface NavigatedEventHandler { - (sender: any, e: Windows.UI.WebUI.IWebUINavigatedEventArgs): void; - } - export interface IWebUINavigatedEventArgs { - navigatedOperation: Windows.UI.WebUI.WebUINavigatedOperation; - } - export class WebUINavigatedOperation implements Windows.UI.WebUI.IWebUINavigatedOperation { - getDeferral(): Windows.UI.WebUI.WebUINavigatedDeferral; - } - export class SuspendingDeferral implements Windows.ApplicationModel.ISuspendingDeferral { - complete(): void; - } - export class SuspendingOperation implements Windows.ApplicationModel.ISuspendingOperation { - deadline: Date; - getDeferral(): Windows.ApplicationModel.SuspendingDeferral; - } - export class SuspendingEventArgs implements Windows.ApplicationModel.ISuspendingEventArgs { - suspendingOperation: Windows.ApplicationModel.SuspendingOperation; - } - export interface IWebUIBackgroundTaskInstance { - succeeded: boolean; - } - export interface IWebUIBackgroundTaskInstanceStatics { - current: Windows.UI.WebUI.IWebUIBackgroundTaskInstance; - } - export class WebUIBackgroundTaskInstanceRuntimeClass implements Windows.UI.WebUI.IWebUIBackgroundTaskInstance, Windows.ApplicationModel.Background.IBackgroundTaskInstance { - succeeded: boolean; - instanceId: string; - progress: number; - suspendedCount: number; - task: Windows.ApplicationModel.Background.BackgroundTaskRegistration; - triggerDetails: any; - oncanceled: any/* TODO */; - getDeferral(): Windows.ApplicationModel.Background.BackgroundTaskDeferral; - } - export class WebUIBackgroundTaskInstance { - static current: Windows.UI.WebUI.IWebUIBackgroundTaskInstance; - } - export interface IWebUINavigatedDeferral { - complete(): void; - } - export class WebUINavigatedDeferral implements Windows.UI.WebUI.IWebUINavigatedDeferral { - complete(): void; - } - export interface IWebUINavigatedOperation { - getDeferral(): Windows.UI.WebUI.WebUINavigatedDeferral; - } - export class WebUINavigatedEventArgs implements Windows.UI.WebUI.IWebUINavigatedEventArgs { - navigatedOperation: Windows.UI.WebUI.WebUINavigatedOperation; - } - export interface IWebUIActivationStatics { - onactivated: any/* TODO */; - onsuspending: any/* TODO */; - onresuming: any/* TODO */; - onnavigated: any/* TODO */; - } - export class WebUIApplication { - static onactivated: any/* TODO */; - static onsuspending: any/* TODO */; - static onresuming: any/* TODO */; - static onnavigated: any/* TODO */; - } - } - } -} -declare module Windows { - export module UI { - export interface IColors { - } - export interface IColorsStatics { - aliceBlue: Windows.UI.Color; - antiqueWhite: Windows.UI.Color; - aqua: Windows.UI.Color; - aquamarine: Windows.UI.Color; - azure: Windows.UI.Color; - beige: Windows.UI.Color; - bisque: Windows.UI.Color; - black: Windows.UI.Color; - blanchedAlmond: Windows.UI.Color; - blue: Windows.UI.Color; - blueViolet: Windows.UI.Color; - brown: Windows.UI.Color; - burlyWood: Windows.UI.Color; - cadetBlue: Windows.UI.Color; - chartreuse: Windows.UI.Color; - chocolate: Windows.UI.Color; - coral: Windows.UI.Color; - cornflowerBlue: Windows.UI.Color; - cornsilk: Windows.UI.Color; - crimson: Windows.UI.Color; - cyan: Windows.UI.Color; - darkBlue: Windows.UI.Color; - darkCyan: Windows.UI.Color; - darkGoldenrod: Windows.UI.Color; - darkGray: Windows.UI.Color; - darkGreen: Windows.UI.Color; - darkKhaki: Windows.UI.Color; - darkMagenta: Windows.UI.Color; - darkOliveGreen: Windows.UI.Color; - darkOrange: Windows.UI.Color; - darkOrchid: Windows.UI.Color; - darkRed: Windows.UI.Color; - darkSalmon: Windows.UI.Color; - darkSeaGreen: Windows.UI.Color; - darkSlateBlue: Windows.UI.Color; - darkSlateGray: Windows.UI.Color; - darkTurquoise: Windows.UI.Color; - darkViolet: Windows.UI.Color; - deepPink: Windows.UI.Color; - deepSkyBlue: Windows.UI.Color; - dimGray: Windows.UI.Color; - dodgerBlue: Windows.UI.Color; - firebrick: Windows.UI.Color; - floralWhite: Windows.UI.Color; - forestGreen: Windows.UI.Color; - fuchsia: Windows.UI.Color; - gainsboro: Windows.UI.Color; - ghostWhite: Windows.UI.Color; - gold: Windows.UI.Color; - goldenrod: Windows.UI.Color; - gray: Windows.UI.Color; - green: Windows.UI.Color; - greenYellow: Windows.UI.Color; - honeydew: Windows.UI.Color; - hotPink: Windows.UI.Color; - indianRed: Windows.UI.Color; - indigo: Windows.UI.Color; - ivory: Windows.UI.Color; - khaki: Windows.UI.Color; - lavender: Windows.UI.Color; - lavenderBlush: Windows.UI.Color; - lawnGreen: Windows.UI.Color; - lemonChiffon: Windows.UI.Color; - lightBlue: Windows.UI.Color; - lightCoral: Windows.UI.Color; - lightCyan: Windows.UI.Color; - lightGoldenrodYellow: Windows.UI.Color; - lightGray: Windows.UI.Color; - lightGreen: Windows.UI.Color; - lightPink: Windows.UI.Color; - lightSalmon: Windows.UI.Color; - lightSeaGreen: Windows.UI.Color; - lightSkyBlue: Windows.UI.Color; - lightSlateGray: Windows.UI.Color; - lightSteelBlue: Windows.UI.Color; - lightYellow: Windows.UI.Color; - lime: Windows.UI.Color; - limeGreen: Windows.UI.Color; - linen: Windows.UI.Color; - magenta: Windows.UI.Color; - maroon: Windows.UI.Color; - mediumAquamarine: Windows.UI.Color; - mediumBlue: Windows.UI.Color; - mediumOrchid: Windows.UI.Color; - mediumPurple: Windows.UI.Color; - mediumSeaGreen: Windows.UI.Color; - mediumSlateBlue: Windows.UI.Color; - mediumSpringGreen: Windows.UI.Color; - mediumTurquoise: Windows.UI.Color; - mediumVioletRed: Windows.UI.Color; - midnightBlue: Windows.UI.Color; - mintCream: Windows.UI.Color; - mistyRose: Windows.UI.Color; - moccasin: Windows.UI.Color; - navajoWhite: Windows.UI.Color; - navy: Windows.UI.Color; - oldLace: Windows.UI.Color; - olive: Windows.UI.Color; - oliveDrab: Windows.UI.Color; - orange: Windows.UI.Color; - orangeRed: Windows.UI.Color; - orchid: Windows.UI.Color; - paleGoldenrod: Windows.UI.Color; - paleGreen: Windows.UI.Color; - paleTurquoise: Windows.UI.Color; - paleVioletRed: Windows.UI.Color; - papayaWhip: Windows.UI.Color; - peachPuff: Windows.UI.Color; - peru: Windows.UI.Color; - pink: Windows.UI.Color; - plum: Windows.UI.Color; - powderBlue: Windows.UI.Color; - purple: Windows.UI.Color; - red: Windows.UI.Color; - rosyBrown: Windows.UI.Color; - royalBlue: Windows.UI.Color; - saddleBrown: Windows.UI.Color; - salmon: Windows.UI.Color; - sandyBrown: Windows.UI.Color; - seaGreen: Windows.UI.Color; - seaShell: Windows.UI.Color; - sienna: Windows.UI.Color; - silver: Windows.UI.Color; - skyBlue: Windows.UI.Color; - slateBlue: Windows.UI.Color; - slateGray: Windows.UI.Color; - snow: Windows.UI.Color; - springGreen: Windows.UI.Color; - steelBlue: Windows.UI.Color; - tan: Windows.UI.Color; - teal: Windows.UI.Color; - thistle: Windows.UI.Color; - tomato: Windows.UI.Color; - transparent: Windows.UI.Color; - turquoise: Windows.UI.Color; - violet: Windows.UI.Color; - wheat: Windows.UI.Color; - white: Windows.UI.Color; - whiteSmoke: Windows.UI.Color; - yellow: Windows.UI.Color; - yellowGreen: Windows.UI.Color; - } - export class Colors implements Windows.UI.IColors { - static aliceBlue: Windows.UI.Color; - static antiqueWhite: Windows.UI.Color; - static aqua: Windows.UI.Color; - static aquamarine: Windows.UI.Color; - static azure: Windows.UI.Color; - static beige: Windows.UI.Color; - static bisque: Windows.UI.Color; - static black: Windows.UI.Color; - static blanchedAlmond: Windows.UI.Color; - static blue: Windows.UI.Color; - static blueViolet: Windows.UI.Color; - static brown: Windows.UI.Color; - static burlyWood: Windows.UI.Color; - static cadetBlue: Windows.UI.Color; - static chartreuse: Windows.UI.Color; - static chocolate: Windows.UI.Color; - static coral: Windows.UI.Color; - static cornflowerBlue: Windows.UI.Color; - static cornsilk: Windows.UI.Color; - static crimson: Windows.UI.Color; - static cyan: Windows.UI.Color; - static darkBlue: Windows.UI.Color; - static darkCyan: Windows.UI.Color; - static darkGoldenrod: Windows.UI.Color; - static darkGray: Windows.UI.Color; - static darkGreen: Windows.UI.Color; - static darkKhaki: Windows.UI.Color; - static darkMagenta: Windows.UI.Color; - static darkOliveGreen: Windows.UI.Color; - static darkOrange: Windows.UI.Color; - static darkOrchid: Windows.UI.Color; - static darkRed: Windows.UI.Color; - static darkSalmon: Windows.UI.Color; - static darkSeaGreen: Windows.UI.Color; - static darkSlateBlue: Windows.UI.Color; - static darkSlateGray: Windows.UI.Color; - static darkTurquoise: Windows.UI.Color; - static darkViolet: Windows.UI.Color; - static deepPink: Windows.UI.Color; - static deepSkyBlue: Windows.UI.Color; - static dimGray: Windows.UI.Color; - static dodgerBlue: Windows.UI.Color; - static firebrick: Windows.UI.Color; - static floralWhite: Windows.UI.Color; - static forestGreen: Windows.UI.Color; - static fuchsia: Windows.UI.Color; - static gainsboro: Windows.UI.Color; - static ghostWhite: Windows.UI.Color; - static gold: Windows.UI.Color; - static goldenrod: Windows.UI.Color; - static gray: Windows.UI.Color; - static green: Windows.UI.Color; - static greenYellow: Windows.UI.Color; - static honeydew: Windows.UI.Color; - static hotPink: Windows.UI.Color; - static indianRed: Windows.UI.Color; - static indigo: Windows.UI.Color; - static ivory: Windows.UI.Color; - static khaki: Windows.UI.Color; - static lavender: Windows.UI.Color; - static lavenderBlush: Windows.UI.Color; - static lawnGreen: Windows.UI.Color; - static lemonChiffon: Windows.UI.Color; - static lightBlue: Windows.UI.Color; - static lightCoral: Windows.UI.Color; - static lightCyan: Windows.UI.Color; - static lightGoldenrodYellow: Windows.UI.Color; - static lightGray: Windows.UI.Color; - static lightGreen: Windows.UI.Color; - static lightPink: Windows.UI.Color; - static lightSalmon: Windows.UI.Color; - static lightSeaGreen: Windows.UI.Color; - static lightSkyBlue: Windows.UI.Color; - static lightSlateGray: Windows.UI.Color; - static lightSteelBlue: Windows.UI.Color; - static lightYellow: Windows.UI.Color; - static lime: Windows.UI.Color; - static limeGreen: Windows.UI.Color; - static linen: Windows.UI.Color; - static magenta: Windows.UI.Color; - static maroon: Windows.UI.Color; - static mediumAquamarine: Windows.UI.Color; - static mediumBlue: Windows.UI.Color; - static mediumOrchid: Windows.UI.Color; - static mediumPurple: Windows.UI.Color; - static mediumSeaGreen: Windows.UI.Color; - static mediumSlateBlue: Windows.UI.Color; - static mediumSpringGreen: Windows.UI.Color; - static mediumTurquoise: Windows.UI.Color; - static mediumVioletRed: Windows.UI.Color; - static midnightBlue: Windows.UI.Color; - static mintCream: Windows.UI.Color; - static mistyRose: Windows.UI.Color; - static moccasin: Windows.UI.Color; - static navajoWhite: Windows.UI.Color; - static navy: Windows.UI.Color; - static oldLace: Windows.UI.Color; - static olive: Windows.UI.Color; - static oliveDrab: Windows.UI.Color; - static orange: Windows.UI.Color; - static orangeRed: Windows.UI.Color; - static orchid: Windows.UI.Color; - static paleGoldenrod: Windows.UI.Color; - static paleGreen: Windows.UI.Color; - static paleTurquoise: Windows.UI.Color; - static paleVioletRed: Windows.UI.Color; - static papayaWhip: Windows.UI.Color; - static peachPuff: Windows.UI.Color; - static peru: Windows.UI.Color; - static pink: Windows.UI.Color; - static plum: Windows.UI.Color; - static powderBlue: Windows.UI.Color; - static purple: Windows.UI.Color; - static red: Windows.UI.Color; - static rosyBrown: Windows.UI.Color; - static royalBlue: Windows.UI.Color; - static saddleBrown: Windows.UI.Color; - static salmon: Windows.UI.Color; - static sandyBrown: Windows.UI.Color; - static seaGreen: Windows.UI.Color; - static seaShell: Windows.UI.Color; - static sienna: Windows.UI.Color; - static silver: Windows.UI.Color; - static skyBlue: Windows.UI.Color; - static slateBlue: Windows.UI.Color; - static slateGray: Windows.UI.Color; - static snow: Windows.UI.Color; - static springGreen: Windows.UI.Color; - static steelBlue: Windows.UI.Color; - static tan: Windows.UI.Color; - static teal: Windows.UI.Color; - static thistle: Windows.UI.Color; - static tomato: Windows.UI.Color; - static transparent: Windows.UI.Color; - static turquoise: Windows.UI.Color; - static violet: Windows.UI.Color; - static wheat: Windows.UI.Color; - static white: Windows.UI.Color; - static whiteSmoke: Windows.UI.Color; - static yellow: Windows.UI.Color; - static yellowGreen: Windows.UI.Color; - } - export interface Color { - a: number; - r: number; - g: number; - b: number; - } - export interface IColorHelper { - } - export interface IColorHelperStatics { - fromArgb(a: number, r: number, g: number, b: number): Windows.UI.Color; - } - export class ColorHelper implements Windows.UI.IColorHelper { - static fromArgb(a: number, r: number, g: number, b: number): Windows.UI.Color; - } - } -} -declare module Windows { - export module UI { - export module Notifications { - export enum NotificationSetting { - enabled, - disabledForApplication, - disabledForUser, - disabledByGroupPolicy, - disabledByManifest, - } - export enum ToastDismissalReason { - userCanceled, - applicationHidden, - timedOut, - } - export enum BadgeTemplateType { - badgeGlyph, - badgeNumber, - } - export enum TileTemplateType { - tileSquareImage, - tileSquareBlock, - tileSquareText01, - tileSquareText02, - tileSquareText03, - tileSquareText04, - tileSquarePeekImageAndText01, - tileSquarePeekImageAndText02, - tileSquarePeekImageAndText03, - tileSquarePeekImageAndText04, - tileWideImage, - tileWideImageCollection, - tileWideImageAndText01, - tileWideImageAndText02, - tileWideBlockAndText01, - tileWideBlockAndText02, - tileWidePeekImageCollection01, - tileWidePeekImageCollection02, - tileWidePeekImageCollection03, - tileWidePeekImageCollection04, - tileWidePeekImageCollection05, - tileWidePeekImageCollection06, - tileWidePeekImageAndText01, - tileWidePeekImageAndText02, - tileWidePeekImage01, - tileWidePeekImage02, - tileWidePeekImage03, - tileWidePeekImage04, - tileWidePeekImage05, - tileWidePeekImage06, - tileWideSmallImageAndText01, - tileWideSmallImageAndText02, - tileWideSmallImageAndText03, - tileWideSmallImageAndText04, - tileWideSmallImageAndText05, - tileWideText01, - tileWideText02, - tileWideText03, - tileWideText04, - tileWideText05, - tileWideText06, - tileWideText07, - tileWideText08, - tileWideText09, - tileWideText10, - tileWideText11, - } - export enum ToastTemplateType { - toastImageAndText01, - toastImageAndText02, - toastImageAndText03, - toastImageAndText04, - toastText01, - toastText02, - toastText03, - toastText04, - } - export enum PeriodicUpdateRecurrence { - halfHour, - hour, - sixHours, - twelveHours, - daily, - } - export interface IToastDismissedEventArgs { - reason: Windows.UI.Notifications.ToastDismissalReason; - } - export interface IToastFailedEventArgs { - errorCode: number; - } - export interface ITileUpdateManagerStatics { - createTileUpdaterForApplication(): Windows.UI.Notifications.TileUpdater; - createTileUpdaterForApplication(applicationId: string): Windows.UI.Notifications.TileUpdater; - createTileUpdaterForSecondaryTile(tileId: string): Windows.UI.Notifications.TileUpdater; - getTemplateContent(type: Windows.UI.Notifications.TileTemplateType): Windows.Data.Xml.Dom.XmlDocument; - } - export class TileUpdater implements Windows.UI.Notifications.ITileUpdater { - setting: Windows.UI.Notifications.NotificationSetting; - update(notification: Windows.UI.Notifications.TileNotification): void; - clear(): void; - enableNotificationQueue(enable: boolean): void; - addToSchedule(scheduledTile: Windows.UI.Notifications.ScheduledTileNotification): void; - removeFromSchedule(scheduledTile: Windows.UI.Notifications.ScheduledTileNotification): void; - getScheduledTileNotifications(): Windows.Foundation.Collections.IVectorView; - startPeriodicUpdate(tileContent: Windows.Foundation.Uri, requestedInterval: Windows.UI.Notifications.PeriodicUpdateRecurrence): void; - startPeriodicUpdate(tileContent: Windows.Foundation.Uri, startTime: Date, requestedInterval: Windows.UI.Notifications.PeriodicUpdateRecurrence): void; - stopPeriodicUpdate(): void; - startPeriodicUpdateBatch(tileContents: Windows.Foundation.Collections.IIterable, requestedInterval: Windows.UI.Notifications.PeriodicUpdateRecurrence): void; - startPeriodicUpdateBatch(tileContents: Windows.Foundation.Collections.IIterable, startTime: Date, requestedInterval: Windows.UI.Notifications.PeriodicUpdateRecurrence): void; - } - export interface ITileUpdater { - setting: Windows.UI.Notifications.NotificationSetting; - update(notification: Windows.UI.Notifications.TileNotification): void; - clear(): void; - enableNotificationQueue(enable: boolean): void; - addToSchedule(scheduledTile: Windows.UI.Notifications.ScheduledTileNotification): void; - removeFromSchedule(scheduledTile: Windows.UI.Notifications.ScheduledTileNotification): void; - getScheduledTileNotifications(): Windows.Foundation.Collections.IVectorView; - startPeriodicUpdate(tileContent: Windows.Foundation.Uri, requestedInterval: Windows.UI.Notifications.PeriodicUpdateRecurrence): void; - startPeriodicUpdate(tileContent: Windows.Foundation.Uri, startTime: Date, requestedInterval: Windows.UI.Notifications.PeriodicUpdateRecurrence): void; - stopPeriodicUpdate(): void; - startPeriodicUpdateBatch(tileContents: Windows.Foundation.Collections.IIterable, requestedInterval: Windows.UI.Notifications.PeriodicUpdateRecurrence): void; - startPeriodicUpdateBatch(tileContents: Windows.Foundation.Collections.IIterable, startTime: Date, requestedInterval: Windows.UI.Notifications.PeriodicUpdateRecurrence): void; - } - export class TileNotification implements Windows.UI.Notifications.ITileNotification { - constructor(content: Windows.Data.Xml.Dom.XmlDocument); - content: Windows.Data.Xml.Dom.XmlDocument; - expirationTime: Date; - tag: string; - } - export class ScheduledTileNotification implements Windows.UI.Notifications.IScheduledTileNotification { - constructor(content: Windows.Data.Xml.Dom.XmlDocument, deliveryTime: Date); - content: Windows.Data.Xml.Dom.XmlDocument; - deliveryTime: Date; - expirationTime: Date; - id: string; - tag: string; - } - export interface IBadgeUpdateManagerStatics { - createBadgeUpdaterForApplication(): Windows.UI.Notifications.BadgeUpdater; - createBadgeUpdaterForApplication(applicationId: string): Windows.UI.Notifications.BadgeUpdater; - createBadgeUpdaterForSecondaryTile(tileId: string): Windows.UI.Notifications.BadgeUpdater; - getTemplateContent(type: Windows.UI.Notifications.BadgeTemplateType): Windows.Data.Xml.Dom.XmlDocument; - } - export class BadgeUpdater implements Windows.UI.Notifications.IBadgeUpdater { - update(notification: Windows.UI.Notifications.BadgeNotification): void; - clear(): void; - startPeriodicUpdate(badgeContent: Windows.Foundation.Uri, requestedInterval: Windows.UI.Notifications.PeriodicUpdateRecurrence): void; - startPeriodicUpdate(badgeContent: Windows.Foundation.Uri, startTime: Date, requestedInterval: Windows.UI.Notifications.PeriodicUpdateRecurrence): void; - stopPeriodicUpdate(): void; - } - export interface IBadgeUpdater { - update(notification: Windows.UI.Notifications.BadgeNotification): void; - clear(): void; - startPeriodicUpdate(badgeContent: Windows.Foundation.Uri, requestedInterval: Windows.UI.Notifications.PeriodicUpdateRecurrence): void; - startPeriodicUpdate(badgeContent: Windows.Foundation.Uri, startTime: Date, requestedInterval: Windows.UI.Notifications.PeriodicUpdateRecurrence): void; - stopPeriodicUpdate(): void; - } - export class BadgeNotification implements Windows.UI.Notifications.IBadgeNotification { - constructor(content: Windows.Data.Xml.Dom.XmlDocument); - content: Windows.Data.Xml.Dom.XmlDocument; - expirationTime: Date; - } - export interface IToastNotificationManagerStatics { - createToastNotifier(): Windows.UI.Notifications.ToastNotifier; - createToastNotifier(applicationId: string): Windows.UI.Notifications.ToastNotifier; - getTemplateContent(type: Windows.UI.Notifications.ToastTemplateType): Windows.Data.Xml.Dom.XmlDocument; - } - export class ToastNotifier implements Windows.UI.Notifications.IToastNotifier { - setting: Windows.UI.Notifications.NotificationSetting; - show(notification: Windows.UI.Notifications.ToastNotification): void; - hide(notification: Windows.UI.Notifications.ToastNotification): void; - addToSchedule(scheduledToast: Windows.UI.Notifications.ScheduledToastNotification): void; - removeFromSchedule(scheduledToast: Windows.UI.Notifications.ScheduledToastNotification): void; - getScheduledToastNotifications(): Windows.Foundation.Collections.IVectorView; - } - export interface IToastNotifier { - setting: Windows.UI.Notifications.NotificationSetting; - show(notification: Windows.UI.Notifications.ToastNotification): void; - hide(notification: Windows.UI.Notifications.ToastNotification): void; - addToSchedule(scheduledToast: Windows.UI.Notifications.ScheduledToastNotification): void; - removeFromSchedule(scheduledToast: Windows.UI.Notifications.ScheduledToastNotification): void; - getScheduledToastNotifications(): Windows.Foundation.Collections.IVectorView; - } - export class ToastNotification implements Windows.UI.Notifications.IToastNotification { - constructor(content: Windows.Data.Xml.Dom.XmlDocument); - content: Windows.Data.Xml.Dom.XmlDocument; - expirationTime: Date; - ondismissed: any/* TODO */; - onactivated: any/* TODO */; - onfailed: any/* TODO */; - } - export class ScheduledToastNotification implements Windows.UI.Notifications.IScheduledToastNotification { - constructor(content: Windows.Data.Xml.Dom.XmlDocument, deliveryTime: Date); - constructor(content: Windows.Data.Xml.Dom.XmlDocument, deliveryTime: Date, snoozeInterval: number, maximumSnoozeCount: number); - content: Windows.Data.Xml.Dom.XmlDocument; - deliveryTime: Date; - id: string; - maximumSnoozeCount: number; - snoozeInterval: number; - } - export interface ITileNotificationFactory { - createTileNotification(content: Windows.Data.Xml.Dom.XmlDocument): Windows.UI.Notifications.TileNotification; - } - export interface ITileNotification { - content: Windows.Data.Xml.Dom.XmlDocument; - expirationTime: Date; - tag: string; - } - export interface IBadgeNotificationFactory { - createBadgeNotification(content: Windows.Data.Xml.Dom.XmlDocument): Windows.UI.Notifications.BadgeNotification; - } - export interface IBadgeNotification { - content: Windows.Data.Xml.Dom.XmlDocument; - expirationTime: Date; - } - export interface IToastNotificationFactory { - createToastNotification(content: Windows.Data.Xml.Dom.XmlDocument): Windows.UI.Notifications.ToastNotification; - } - export interface IToastNotification { - content: Windows.Data.Xml.Dom.XmlDocument; - expirationTime: Date; - ondismissed: any/* TODO */; - onactivated: any/* TODO */; - onfailed: any/* TODO */; - } - export class ToastDismissedEventArgs implements Windows.UI.Notifications.IToastDismissedEventArgs { - reason: Windows.UI.Notifications.ToastDismissalReason; - } - export class ToastFailedEventArgs implements Windows.UI.Notifications.IToastFailedEventArgs { - errorCode: number; - } - export interface IScheduledToastNotificationFactory { - createScheduledToastNotification(content: Windows.Data.Xml.Dom.XmlDocument, deliveryTime: Date): Windows.UI.Notifications.ScheduledToastNotification; - createScheduledToastNotification(content: Windows.Data.Xml.Dom.XmlDocument, deliveryTime: Date, snoozeInterval: number, maximumSnoozeCount: number): Windows.UI.Notifications.ScheduledToastNotification; - } - export interface IScheduledToastNotification { - content: Windows.Data.Xml.Dom.XmlDocument; - deliveryTime: Date; - id: string; - maximumSnoozeCount: number; - snoozeInterval: number; - } - export interface IScheduledTileNotificationFactory { - createScheduledTileNotification(content: Windows.Data.Xml.Dom.XmlDocument, deliveryTime: Date): Windows.UI.Notifications.ScheduledTileNotification; - } - export interface IScheduledTileNotification { - content: Windows.Data.Xml.Dom.XmlDocument; - deliveryTime: Date; - expirationTime: Date; - id: string; - tag: string; - } - export class TileUpdateManager { - static createTileUpdaterForApplication(): Windows.UI.Notifications.TileUpdater; - static createTileUpdaterForApplication(applicationId: string): Windows.UI.Notifications.TileUpdater; - static createTileUpdaterForSecondaryTile(tileId: string): Windows.UI.Notifications.TileUpdater; - static getTemplateContent(type: Windows.UI.Notifications.TileTemplateType): Windows.Data.Xml.Dom.XmlDocument; - } - export class BadgeUpdateManager { - static createBadgeUpdaterForApplication(): Windows.UI.Notifications.BadgeUpdater; - static createBadgeUpdaterForApplication(applicationId: string): Windows.UI.Notifications.BadgeUpdater; - static createBadgeUpdaterForSecondaryTile(tileId: string): Windows.UI.Notifications.BadgeUpdater; - static getTemplateContent(type: Windows.UI.Notifications.BadgeTemplateType): Windows.Data.Xml.Dom.XmlDocument; - } - export class ToastNotificationManager { - static createToastNotifier(): Windows.UI.Notifications.ToastNotifier; - static createToastNotifier(applicationId: string): Windows.UI.Notifications.ToastNotifier; - static getTemplateContent(type: Windows.UI.Notifications.ToastTemplateType): Windows.Data.Xml.Dom.XmlDocument; - } - } - } -} -declare module Windows { - export module Web { - export enum WebErrorStatus { - unknown, - certificateCommonNameIsIncorrect, - certificateExpired, - certificateContainsErrors, - certificateRevoked, - certificateIsInvalid, - serverUnreachable, - timeout, - errorHttpInvalidServerResponse, - connectionAborted, - connectionReset, - disconnected, - httpToHttpsOnRedirection, - httpsToHttpOnRedirection, - cannotConnect, - hostNameNotResolved, - operationCanceled, - redirectFailed, - unexpectedStatusCode, - unexpectedRedirection, - unexpectedClientError, - unexpectedServerError, - multipleChoices, - movedPermanently, - found, - seeOther, - notModified, - useProxy, - temporaryRedirect, - badRequest, - unauthorized, - paymentRequired, - forbidden, - notFound, - methodNotAllowed, - notAcceptable, - proxyAuthenticationRequired, - requestTimeout, - conflict, - gone, - lengthRequired, - preconditionFailed, - requestEntityTooLarge, - requestUriTooLong, - unsupportedMediaType, - requestedRangeNotSatisfiable, - expectationFailed, - internalServerError, - notImplemented, - badGateway, - serviceUnavailable, - gatewayTimeout, - httpVersionNotSupported, - } - export interface IWebErrorStatics { - getStatus(hresult: number): Windows.Web.WebErrorStatus; - } - export class WebError { - static getStatus(hresult: number): Windows.Web.WebErrorStatus; - } - } -} -declare module Windows { - export module Web { - export module Syndication { - export interface RetrievalProgress { - bytesRetrieved: number; - totalBytesToRetrieve: number; - } - export interface TransferProgress { - bytesSent: number; - totalBytesToSend: number; - bytesRetrieved: number; - totalBytesToRetrieve: number; - } - export enum SyndicationFormat { - atom10, - rss20, - rss10, - rss092, - rss091, - atom03, - } - export enum SyndicationErrorStatus { - unknown, - missingRequiredElement, - missingRequiredAttribute, - invalidXml, - unexpectedContent, - unsupportedFormat, - } - export interface ISyndicationAttribute { - name: string; - namespace: string; - value: string; - } - export class SyndicationAttribute implements Windows.Web.Syndication.ISyndicationAttribute { - constructor(attributeName: string, attributeNamespace: string, attributeValue: string); - constructor(); - name: string; - namespace: string; - value: string; - } - export interface ISyndicationAttributeFactory { - createSyndicationAttribute(attributeName: string, attributeNamespace: string, attributeValue: string): Windows.Web.Syndication.SyndicationAttribute; - } - export interface ISyndicationNode { - attributeExtensions: Windows.Foundation.Collections.IVector; - baseUri: Windows.Foundation.Uri; - elementExtensions: Windows.Foundation.Collections.IVector; - language: string; - nodeName: string; - nodeNamespace: string; - nodeValue: string; - getXmlDocument(format: Windows.Web.Syndication.SyndicationFormat): Windows.Data.Xml.Dom.XmlDocument; - } - export class SyndicationNode implements Windows.Web.Syndication.ISyndicationNode { - constructor(nodeName: string, nodeNamespace: string, nodeValue: string); - constructor(); - attributeExtensions: Windows.Foundation.Collections.IVector; - baseUri: Windows.Foundation.Uri; - elementExtensions: Windows.Foundation.Collections.IVector; - language: string; - nodeName: string; - nodeNamespace: string; - nodeValue: string; - getXmlDocument(format: Windows.Web.Syndication.SyndicationFormat): Windows.Data.Xml.Dom.XmlDocument; - } - export interface ISyndicationNodeFactory { - createSyndicationNode(nodeName: string, nodeNamespace: string, nodeValue: string): Windows.Web.Syndication.SyndicationNode; - } - export interface ISyndicationGenerator { - text: string; - uri: Windows.Foundation.Uri; - version: string; - } - export class SyndicationGenerator implements Windows.Web.Syndication.ISyndicationGenerator, Windows.Web.Syndication.ISyndicationNode { - constructor(text: string); - constructor(); - text: string; - uri: Windows.Foundation.Uri; - version: string; - attributeExtensions: Windows.Foundation.Collections.IVector; - baseUri: Windows.Foundation.Uri; - elementExtensions: Windows.Foundation.Collections.IVector; - language: string; - nodeName: string; - nodeNamespace: string; - nodeValue: string; - getXmlDocument(format: Windows.Web.Syndication.SyndicationFormat): Windows.Data.Xml.Dom.XmlDocument; - } - export interface ISyndicationGeneratorFactory { - createSyndicationGenerator(text: string): Windows.Web.Syndication.SyndicationGenerator; - } - export interface ISyndicationText extends Windows.Web.Syndication.ISyndicationNode { - text: string; - type: string; - xml: Windows.Data.Xml.Dom.XmlDocument; - } - export class SyndicationText implements Windows.Web.Syndication.ISyndicationText, Windows.Web.Syndication.ISyndicationNode { - constructor(text: string); - constructor(text: string, type: Windows.Web.Syndication.SyndicationTextType); - constructor(); - text: string; - type: string; - xml: Windows.Data.Xml.Dom.XmlDocument; - attributeExtensions: Windows.Foundation.Collections.IVector; - baseUri: Windows.Foundation.Uri; - elementExtensions: Windows.Foundation.Collections.IVector; - language: string; - nodeName: string; - nodeNamespace: string; - nodeValue: string; - getXmlDocument(format: Windows.Web.Syndication.SyndicationFormat): Windows.Data.Xml.Dom.XmlDocument; - } - export enum SyndicationTextType { - text, - html, - xhtml, - } - export interface ISyndicationTextFactory { - createSyndicationText(text: string): Windows.Web.Syndication.SyndicationText; - createSyndicationText(text: string, type: Windows.Web.Syndication.SyndicationTextType): Windows.Web.Syndication.SyndicationText; - } - export interface ISyndicationContent extends Windows.Web.Syndication.ISyndicationText, Windows.Web.Syndication.ISyndicationNode { - sourceUri: Windows.Foundation.Uri; - } - export class SyndicationContent implements Windows.Web.Syndication.ISyndicationText, Windows.Web.Syndication.ISyndicationNode, Windows.Web.Syndication.ISyndicationContent { - constructor(text: string, type: Windows.Web.Syndication.SyndicationTextType); - constructor(sourceUri: Windows.Foundation.Uri); - constructor(); - text: string; - type: string; - xml: Windows.Data.Xml.Dom.XmlDocument; - attributeExtensions: Windows.Foundation.Collections.IVector; - baseUri: Windows.Foundation.Uri; - elementExtensions: Windows.Foundation.Collections.IVector; - language: string; - nodeName: string; - nodeNamespace: string; - nodeValue: string; - sourceUri: Windows.Foundation.Uri; - getXmlDocument(format: Windows.Web.Syndication.SyndicationFormat): Windows.Data.Xml.Dom.XmlDocument; - } - export interface ISyndicationContentFactory { - createSyndicationContent(text: string, type: Windows.Web.Syndication.SyndicationTextType): Windows.Web.Syndication.SyndicationContent; - createSyndicationContent(sourceUri: Windows.Foundation.Uri): Windows.Web.Syndication.SyndicationContent; - } - export interface ISyndicationLink extends Windows.Web.Syndication.ISyndicationNode { - length: number; - mediaType: string; - relationship: string; - resourceLanguage: string; - title: string; - uri: Windows.Foundation.Uri; - } - export class SyndicationLink implements Windows.Web.Syndication.ISyndicationLink, Windows.Web.Syndication.ISyndicationNode { - constructor(uri: Windows.Foundation.Uri); - constructor(uri: Windows.Foundation.Uri, relationship: string, title: string, mediaType: string, length: number); - constructor(); - length: number; - mediaType: string; - relationship: string; - resourceLanguage: string; - title: string; - uri: Windows.Foundation.Uri; - attributeExtensions: Windows.Foundation.Collections.IVector; - baseUri: Windows.Foundation.Uri; - elementExtensions: Windows.Foundation.Collections.IVector; - language: string; - nodeName: string; - nodeNamespace: string; - nodeValue: string; - getXmlDocument(format: Windows.Web.Syndication.SyndicationFormat): Windows.Data.Xml.Dom.XmlDocument; - } - export interface ISyndicationLinkFactory { - createSyndicationLink(uri: Windows.Foundation.Uri): Windows.Web.Syndication.SyndicationLink; - createSyndicationLink(uri: Windows.Foundation.Uri, relationship: string, title: string, mediaType: string, length: number): Windows.Web.Syndication.SyndicationLink; - } - export interface ISyndicationPerson extends Windows.Web.Syndication.ISyndicationNode { - email: string; - name: string; - uri: Windows.Foundation.Uri; - } - export class SyndicationPerson implements Windows.Web.Syndication.ISyndicationPerson, Windows.Web.Syndication.ISyndicationNode { - constructor(name: string); - constructor(name: string, email: string, uri: Windows.Foundation.Uri); - constructor(); - email: string; - name: string; - uri: Windows.Foundation.Uri; - attributeExtensions: Windows.Foundation.Collections.IVector; - baseUri: Windows.Foundation.Uri; - elementExtensions: Windows.Foundation.Collections.IVector; - language: string; - nodeName: string; - nodeNamespace: string; - nodeValue: string; - getXmlDocument(format: Windows.Web.Syndication.SyndicationFormat): Windows.Data.Xml.Dom.XmlDocument; - } - export interface ISyndicationPersonFactory { - createSyndicationPerson(name: string): Windows.Web.Syndication.SyndicationPerson; - createSyndicationPerson(name: string, email: string, uri: Windows.Foundation.Uri): Windows.Web.Syndication.SyndicationPerson; - } - export interface ISyndicationCategory extends Windows.Web.Syndication.ISyndicationNode { - label: string; - scheme: string; - term: string; - } - export class SyndicationCategory implements Windows.Web.Syndication.ISyndicationCategory, Windows.Web.Syndication.ISyndicationNode { - constructor(term: string); - constructor(term: string, scheme: string, label: string); - constructor(); - label: string; - scheme: string; - term: string; - attributeExtensions: Windows.Foundation.Collections.IVector; - baseUri: Windows.Foundation.Uri; - elementExtensions: Windows.Foundation.Collections.IVector; - language: string; - nodeName: string; - nodeNamespace: string; - nodeValue: string; - getXmlDocument(format: Windows.Web.Syndication.SyndicationFormat): Windows.Data.Xml.Dom.XmlDocument; - } - export interface ISyndicationCategoryFactory { - createSyndicationCategory(term: string): Windows.Web.Syndication.SyndicationCategory; - createSyndicationCategory(term: string, scheme: string, label: string): Windows.Web.Syndication.SyndicationCategory; - } - export interface ISyndicationItem extends Windows.Web.Syndication.ISyndicationNode { - authors: Windows.Foundation.Collections.IVector; - categories: Windows.Foundation.Collections.IVector; - commentsUri: Windows.Foundation.Uri; - content: Windows.Web.Syndication.SyndicationContent; - contributors: Windows.Foundation.Collections.IVector; - eTag: string; - editMediaUri: Windows.Foundation.Uri; - editUri: Windows.Foundation.Uri; - id: string; - itemUri: Windows.Foundation.Uri; - lastUpdatedTime: Date; - links: Windows.Foundation.Collections.IVector; - publishedDate: Date; - rights: Windows.Web.Syndication.ISyndicationText; - source: Windows.Web.Syndication.SyndicationFeed; - summary: Windows.Web.Syndication.ISyndicationText; - title: Windows.Web.Syndication.ISyndicationText; - load(item: string): void; - loadFromXml(itemDocument: Windows.Data.Xml.Dom.XmlDocument): void; - } - export class SyndicationFeed implements Windows.Web.Syndication.ISyndicationFeed, Windows.Web.Syndication.ISyndicationNode { - constructor(title: string, subtitle: string, uri: Windows.Foundation.Uri); - constructor(); - authors: Windows.Foundation.Collections.IVector; - categories: Windows.Foundation.Collections.IVector; - contributors: Windows.Foundation.Collections.IVector; - firstUri: Windows.Foundation.Uri; - generator: Windows.Web.Syndication.SyndicationGenerator; - iconUri: Windows.Foundation.Uri; - id: string; - imageUri: Windows.Foundation.Uri; - items: Windows.Foundation.Collections.IVector; - lastUpdatedTime: Date; - lastUri: Windows.Foundation.Uri; - links: Windows.Foundation.Collections.IVector; - nextUri: Windows.Foundation.Uri; - previousUri: Windows.Foundation.Uri; - rights: Windows.Web.Syndication.ISyndicationText; - sourceFormat: Windows.Web.Syndication.SyndicationFormat; - subtitle: Windows.Web.Syndication.ISyndicationText; - title: Windows.Web.Syndication.ISyndicationText; - attributeExtensions: Windows.Foundation.Collections.IVector; - baseUri: Windows.Foundation.Uri; - elementExtensions: Windows.Foundation.Collections.IVector; - language: string; - nodeName: string; - nodeNamespace: string; - nodeValue: string; - load(feed: string): void; - loadFromXml(feedDocument: Windows.Data.Xml.Dom.XmlDocument): void; - getXmlDocument(format: Windows.Web.Syndication.SyndicationFormat): Windows.Data.Xml.Dom.XmlDocument; - } - export class SyndicationItem implements Windows.Web.Syndication.ISyndicationItem, Windows.Web.Syndication.ISyndicationNode { - constructor(title: string, content: Windows.Web.Syndication.SyndicationContent, uri: Windows.Foundation.Uri); - constructor(); - authors: Windows.Foundation.Collections.IVector; - categories: Windows.Foundation.Collections.IVector; - commentsUri: Windows.Foundation.Uri; - content: Windows.Web.Syndication.SyndicationContent; - contributors: Windows.Foundation.Collections.IVector; - eTag: string; - editMediaUri: Windows.Foundation.Uri; - editUri: Windows.Foundation.Uri; - id: string; - itemUri: Windows.Foundation.Uri; - lastUpdatedTime: Date; - links: Windows.Foundation.Collections.IVector; - publishedDate: Date; - rights: Windows.Web.Syndication.ISyndicationText; - source: Windows.Web.Syndication.SyndicationFeed; - summary: Windows.Web.Syndication.ISyndicationText; - title: Windows.Web.Syndication.ISyndicationText; - attributeExtensions: Windows.Foundation.Collections.IVector; - baseUri: Windows.Foundation.Uri; - elementExtensions: Windows.Foundation.Collections.IVector; - language: string; - nodeName: string; - nodeNamespace: string; - nodeValue: string; - load(item: string): void; - loadFromXml(itemDocument: Windows.Data.Xml.Dom.XmlDocument): void; - getXmlDocument(format: Windows.Web.Syndication.SyndicationFormat): Windows.Data.Xml.Dom.XmlDocument; - } - export interface ISyndicationItemFactory { - createSyndicationItem(title: string, content: Windows.Web.Syndication.SyndicationContent, uri: Windows.Foundation.Uri): Windows.Web.Syndication.SyndicationItem; - } - export interface ISyndicationFeed extends Windows.Web.Syndication.ISyndicationNode { - authors: Windows.Foundation.Collections.IVector; - categories: Windows.Foundation.Collections.IVector; - contributors: Windows.Foundation.Collections.IVector; - firstUri: Windows.Foundation.Uri; - generator: Windows.Web.Syndication.SyndicationGenerator; - iconUri: Windows.Foundation.Uri; - id: string; - imageUri: Windows.Foundation.Uri; - items: Windows.Foundation.Collections.IVector; - lastUpdatedTime: Date; - lastUri: Windows.Foundation.Uri; - links: Windows.Foundation.Collections.IVector; - nextUri: Windows.Foundation.Uri; - previousUri: Windows.Foundation.Uri; - rights: Windows.Web.Syndication.ISyndicationText; - sourceFormat: Windows.Web.Syndication.SyndicationFormat; - subtitle: Windows.Web.Syndication.ISyndicationText; - title: Windows.Web.Syndication.ISyndicationText; - load(feed: string): void; - loadFromXml(feedDocument: Windows.Data.Xml.Dom.XmlDocument): void; - } - export interface ISyndicationFeedFactory { - createSyndicationFeed(title: string, subtitle: string, uri: Windows.Foundation.Uri): Windows.Web.Syndication.SyndicationFeed; - } - export interface ISyndicationClient { - bypassCacheOnRetrieve: boolean; - maxResponseBufferSize: number; - proxyCredential: Windows.Security.Credentials.PasswordCredential; - serverCredential: Windows.Security.Credentials.PasswordCredential; - timeout: number; - setRequestHeader(name: string, value: string): void; - retrieveFeedAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperationWithProgress; - } - export class SyndicationClient implements Windows.Web.Syndication.ISyndicationClient { - constructor(serverCredential: Windows.Security.Credentials.PasswordCredential); - constructor(); - bypassCacheOnRetrieve: boolean; - maxResponseBufferSize: number; - proxyCredential: Windows.Security.Credentials.PasswordCredential; - serverCredential: Windows.Security.Credentials.PasswordCredential; - timeout: number; - setRequestHeader(name: string, value: string): void; - retrieveFeedAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperationWithProgress; - } - export interface ISyndicationClientFactory { - createSyndicationClient(serverCredential: Windows.Security.Credentials.PasswordCredential): Windows.Web.Syndication.SyndicationClient; - } - export interface ISyndicationErrorStatics { - getStatus(hresult: number): Windows.Web.Syndication.SyndicationErrorStatus; - } - export class SyndicationError { - static getStatus(hresult: number): Windows.Web.Syndication.SyndicationErrorStatus; - } - } - } -} -declare module Windows { - export module Web { - export module AtomPub { - export interface IResourceCollection extends Windows.Web.Syndication.ISyndicationNode { - accepts: Windows.Foundation.Collections.IVectorView; - categories: Windows.Foundation.Collections.IVectorView; - title: Windows.Web.Syndication.ISyndicationText; - uri: Windows.Foundation.Uri; - } - export class ResourceCollection implements Windows.Web.AtomPub.IResourceCollection, Windows.Web.Syndication.ISyndicationNode { - accepts: Windows.Foundation.Collections.IVectorView; - categories: Windows.Foundation.Collections.IVectorView; - title: Windows.Web.Syndication.ISyndicationText; - uri: Windows.Foundation.Uri; - attributeExtensions: Windows.Foundation.Collections.IVector; - baseUri: Windows.Foundation.Uri; - elementExtensions: Windows.Foundation.Collections.IVector; - language: string; - nodeName: string; - nodeNamespace: string; - nodeValue: string; - getXmlDocument(format: Windows.Web.Syndication.SyndicationFormat): Windows.Data.Xml.Dom.XmlDocument; - } - export interface IWorkspace extends Windows.Web.Syndication.ISyndicationNode { - collections: Windows.Foundation.Collections.IVectorView; - title: Windows.Web.Syndication.ISyndicationText; - } - export class Workspace implements Windows.Web.AtomPub.IWorkspace, Windows.Web.Syndication.ISyndicationNode { - collections: Windows.Foundation.Collections.IVectorView; - title: Windows.Web.Syndication.ISyndicationText; - attributeExtensions: Windows.Foundation.Collections.IVector; - baseUri: Windows.Foundation.Uri; - elementExtensions: Windows.Foundation.Collections.IVector; - language: string; - nodeName: string; - nodeNamespace: string; - nodeValue: string; - getXmlDocument(format: Windows.Web.Syndication.SyndicationFormat): Windows.Data.Xml.Dom.XmlDocument; - } - export interface IServiceDocument extends Windows.Web.Syndication.ISyndicationNode { - workspaces: Windows.Foundation.Collections.IVectorView; - } - export class ServiceDocument implements Windows.Web.AtomPub.IServiceDocument, Windows.Web.Syndication.ISyndicationNode { - workspaces: Windows.Foundation.Collections.IVectorView; - attributeExtensions: Windows.Foundation.Collections.IVector; - baseUri: Windows.Foundation.Uri; - elementExtensions: Windows.Foundation.Collections.IVector; - language: string; - nodeName: string; - nodeNamespace: string; - nodeValue: string; - getXmlDocument(format: Windows.Web.Syndication.SyndicationFormat): Windows.Data.Xml.Dom.XmlDocument; - } - export interface IAtomPubClient extends Windows.Web.Syndication.ISyndicationClient { - retrieveServiceDocumentAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperationWithProgress; - retrieveMediaResourceAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperationWithProgress; - retrieveResourceAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperationWithProgress; - createResourceAsync(uri: Windows.Foundation.Uri, description: string, item: Windows.Web.Syndication.SyndicationItem): Windows.Foundation.IAsyncOperationWithProgress; - createMediaResourceAsync(uri: Windows.Foundation.Uri, mediaType: string, description: string, mediaStream: Windows.Storage.Streams.IInputStream): Windows.Foundation.IAsyncOperationWithProgress; - updateMediaResourceAsync(uri: Windows.Foundation.Uri, mediaType: string, mediaStream: Windows.Storage.Streams.IInputStream): Windows.Foundation.IAsyncActionWithProgress; - updateResourceAsync(uri: Windows.Foundation.Uri, item: Windows.Web.Syndication.SyndicationItem): Windows.Foundation.IAsyncActionWithProgress; - updateResourceItemAsync(item: Windows.Web.Syndication.SyndicationItem): Windows.Foundation.IAsyncActionWithProgress; - deleteResourceAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncActionWithProgress; - deleteResourceItemAsync(item: Windows.Web.Syndication.SyndicationItem): Windows.Foundation.IAsyncActionWithProgress; - cancelAsyncOperations(): void; - } - export class AtomPubClient implements Windows.Web.AtomPub.IAtomPubClient, Windows.Web.Syndication.ISyndicationClient { - constructor(serverCredential: Windows.Security.Credentials.PasswordCredential); - constructor(); - bypassCacheOnRetrieve: boolean; - maxResponseBufferSize: number; - proxyCredential: Windows.Security.Credentials.PasswordCredential; - serverCredential: Windows.Security.Credentials.PasswordCredential; - timeout: number; - retrieveServiceDocumentAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperationWithProgress; - retrieveMediaResourceAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperationWithProgress; - retrieveResourceAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperationWithProgress; - createResourceAsync(uri: Windows.Foundation.Uri, description: string, item: Windows.Web.Syndication.SyndicationItem): Windows.Foundation.IAsyncOperationWithProgress; - createMediaResourceAsync(uri: Windows.Foundation.Uri, mediaType: string, description: string, mediaStream: Windows.Storage.Streams.IInputStream): Windows.Foundation.IAsyncOperationWithProgress; - updateMediaResourceAsync(uri: Windows.Foundation.Uri, mediaType: string, mediaStream: Windows.Storage.Streams.IInputStream): Windows.Foundation.IAsyncActionWithProgress; - updateResourceAsync(uri: Windows.Foundation.Uri, item: Windows.Web.Syndication.SyndicationItem): Windows.Foundation.IAsyncActionWithProgress; - updateResourceItemAsync(item: Windows.Web.Syndication.SyndicationItem): Windows.Foundation.IAsyncActionWithProgress; - deleteResourceAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncActionWithProgress; - deleteResourceItemAsync(item: Windows.Web.Syndication.SyndicationItem): Windows.Foundation.IAsyncActionWithProgress; - cancelAsyncOperations(): void; - setRequestHeader(name: string, value: string): void; - retrieveFeedAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperationWithProgress; - } - export interface IAtomPubClientFactory { - createAtomPubClientWithCredentials(serverCredential: Windows.Security.Credentials.PasswordCredential): Windows.Web.AtomPub.AtomPubClient; - } - } - } -} -declare module Windows.Foundation { - export interface IPromise { - then(success?: (value: T) => IPromise, error?: (error: any) => IPromise, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: T) => IPromise, error?: (error: any) => U, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: T) => U, error?: (error: any) => IPromise, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - then(success?: (value: T) => U, error?: (error: any) => U, progress?: (progress: any) => void ): Windows.Foundation.IPromise; - done?(success?: (value: T) => any, error?: (error: any) => any, progress?: (progress: any) => void ): void; - } -} diff --git a/win8.1/encyclopedia/Encyclopedia/js/win.ts b/win8.1/encyclopedia/Encyclopedia/js/win.ts deleted file mode 100644 index 0eca554..0000000 --- a/win8.1/encyclopedia/Encyclopedia/js/win.ts +++ /dev/null @@ -1,4 +0,0 @@ -/// -/// - -declare var msSetImmediate: (expression: any) => void; \ No newline at end of file diff --git a/win8.1/encyclopedia/Encyclopedia/package.appxmanifest b/win8.1/encyclopedia/Encyclopedia/package.appxmanifest deleted file mode 100644 index d2e18d9..0000000 --- a/win8.1/encyclopedia/Encyclopedia/package.appxmanifest +++ /dev/null @@ -1,37 +0,0 @@ - - - - - Encyclopedia - Encyclopedia - TS - images\ep-storelogo.png - - - 6.3.0 - 6.3.0 - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file